当前位置: 首页>>代码示例>>C++>>正文


C++ QVector::size方法代码示例

本文整理汇总了C++中QVector::size方法的典型用法代码示例。如果您正苦于以下问题:C++ QVector::size方法的具体用法?C++ QVector::size怎么用?C++ QVector::size使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QVector的用法示例。


在下文中一共展示了QVector::size方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: if

/*!
    \fn QDBusMetaType::typeToSignature(int type)
    \internal 

    Returns the D-Bus signature equivalent to the supplied meta type id \a type.

    More types can be registered with the qDBusRegisterMetaType() function.

    \sa QDBusUtil::isValidSingleSignature(), signatureToType(),
        QVariant::type(), QVariant::userType()
*/
const char *QDBusMetaType::typeToSignature(int type)
{
    // check if it's a static type
    switch (type)
    {
    case QMetaType::UChar:
        return DBUS_TYPE_BYTE_AS_STRING;

    case QVariant::Bool:
        return DBUS_TYPE_BOOLEAN_AS_STRING;

    case QMetaType::Short:
        return DBUS_TYPE_INT16_AS_STRING;

    case QMetaType::UShort:
        return DBUS_TYPE_UINT16_AS_STRING;

    case QVariant::Int:
        return DBUS_TYPE_INT32_AS_STRING;

    case QVariant::UInt:
        return DBUS_TYPE_UINT32_AS_STRING;

    case QVariant::LongLong:
        return DBUS_TYPE_INT64_AS_STRING;

    case QVariant::ULongLong:
        return DBUS_TYPE_UINT64_AS_STRING;

    case QVariant::Double:
        return DBUS_TYPE_DOUBLE_AS_STRING;

    case QVariant::String:
        return DBUS_TYPE_STRING_AS_STRING;

    case QVariant::StringList:
        return DBUS_TYPE_ARRAY_AS_STRING
            DBUS_TYPE_STRING_AS_STRING; // as

    case QVariant::ByteArray:
        return DBUS_TYPE_ARRAY_AS_STRING
            DBUS_TYPE_BYTE_AS_STRING; // ay
    }

    QDBusMetaTypeId::init();
    if (type == QDBusMetaTypeId::variant)
        return DBUS_TYPE_VARIANT_AS_STRING;
    else if (type == QDBusMetaTypeId::objectpath)
        return DBUS_TYPE_OBJECT_PATH_AS_STRING;
    else if (type == QDBusMetaTypeId::signature)
        return DBUS_TYPE_SIGNATURE_AS_STRING;

    // try the database
    QVector<QDBusCustomTypeInfo> *ct = customTypes();
    {
        QReadLocker locker(customTypesLock());
        if (type >= ct->size())
            return 0;           // type not registered with us

        const QDBusCustomTypeInfo &info = (*ct).at(type);

        if (!info.signature.isNull())
            return info.signature;

        if (!info.marshall)
            return 0;           // type not registered with us
    }

    // call to user code to construct the signature type
    QDBusCustomTypeInfo *info;
    {
        // createSignature will never return a null QByteArray
        // if there was an error, it'll return ""
        QByteArray signature = QDBusArgumentPrivate::createSignature(type);

        // re-acquire lock
        QWriteLocker locker(customTypesLock());
        info = &(*ct)[type];
        info->signature = signature;
    }
    return info->signature;
}
开发者ID:muromec,项目名称:qtopia-ezx,代码行数:93,代码来源:qdbusmetatype.cpp

示例2: paintGL

void GLWidget::paintGL()
{
    int width = this->width() * devicePixelRatio();
    int height = this->height() * devicePixelRatio();

    glDisable(GL_BLEND);
    glDisable(GL_DEPTH_TEST);
    glDepthMask(GL_FALSE);
    glViewport(0, 0, width, height);
    check_error();
    QColor color = QPalette().color(QPalette::Window);
    glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
    glClear(GL_COLOR_BUFFER_BIT);
    check_error();

    if (!m_texture[0]) return;

    // Bind textures.
    for (int i = 0; i < 3; ++i) {
        if (m_texture[i]) {
            glActiveTexture(GL_TEXTURE0 + i);
            glBindTexture(GL_TEXTURE_2D, m_texture[i]);
            check_error();
        }
    }

    // Init shader program.
    m_shader->bind();
    if (m_glslManager) {
        m_shader->setUniformValue(m_textureLocation[0], 0);
    } else {
        m_shader->setUniformValue(m_textureLocation[0], 0);
        m_shader->setUniformValue(m_textureLocation[1], 1);
        m_shader->setUniformValue(m_textureLocation[2], 2);
        m_shader->setUniformValue(m_colorspaceLocation, MLT.profile().colorspace());
    }
    check_error();

    // Setup an orthographic projection.
    QMatrix4x4 projection;
    projection.scale(2.0f / width, 2.0f / height);
    m_shader->setUniformValue(m_projectionLocation, projection);
    check_error();

    // Set model view.
    QMatrix4x4 modelView;
    if (m_zoom > 0.0) {
        if (offset().x() || offset().y())
            modelView.translate(-offset().x() * devicePixelRatio(),
                                 offset().y() * devicePixelRatio());
        modelView.scale(zoom(), zoom());
    }
    m_shader->setUniformValue(m_modelViewLocation, modelView);
    check_error();

    // Provide vertices of triangle strip.
    QVector<QVector2D> vertices;
    width = m_rect.width() * devicePixelRatio();
    height = m_rect.height() * devicePixelRatio();
    vertices << QVector2D(float(-width)/2.0f, float(-height)/2.0f);
    vertices << QVector2D(float(-width)/2.0f, float( height)/2.0f);
    vertices << QVector2D(float( width)/2.0f, float(-height)/2.0f);
    vertices << QVector2D(float( width)/2.0f, float( height)/2.0f);
    m_shader->enableAttributeArray(m_vertexLocation);
    check_error();
    m_shader->setAttributeArray(m_vertexLocation, vertices.constData());
    check_error();

    // Provide texture coordinates.
    QVector<QVector2D> texCoord;
    texCoord << QVector2D(0.0f, 1.0f);
    texCoord << QVector2D(0.0f, 0.0f);
    texCoord << QVector2D(1.0f, 1.0f);
    texCoord << QVector2D(1.0f, 0.0f);
    m_shader->enableAttributeArray(m_texCoordLocation);
    check_error();
    m_shader->setAttributeArray(m_texCoordLocation, texCoord.constData());
    check_error();

    // Render
    glDrawArrays(GL_TRIANGLE_STRIP, 0, vertices.size());
    check_error();

    // Cleanup
    m_shader->disableAttributeArray(m_vertexLocation);
    m_shader->disableAttributeArray(m_texCoordLocation);
    m_shader->release();
    for (int i = 0; i < 3; ++i) {
        if (m_texture[i]) {
            glActiveTexture(GL_TEXTURE0 + i);
            glBindTexture(GL_TEXTURE_2D, 0);
            check_error();
        }
    }
    glActiveTexture(GL_TEXTURE0);
    check_error();
}
开发者ID:AresDice,项目名称:shotcut,代码行数:97,代码来源:glwidget.cpp

示例3: initGeometry

void GeometryEngine::initGeometry(TriangleList triangles, QVector<QVector3D> lines, QVector<QVector3D> points)
{
    isTransparent = false;

    initializeOpenGLFunctions();

    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // Generate 2 VBOs
    arrayBuf.create();
    indexBuf.create();
    arrayBufLines.create();
    arrayBufPoints.create();

    std::vector<VertexData> vertices;
    std::vector<GLuint> indices;
    std::vector<GLuint> tmp(3);

    // iterate over all triangles
    for (uint i = 0; i < triangles.size(); i++) {
        // iterate over all vertices in triangle
        for (int j = 0; j < 3; j++) {
            // create vertex with texture coords
            VertexData vertex = {
                QVector3D(triangles[i][j][0], triangles[i][j][1], triangles[i][j][2]),
                QVector2D(abs(((j+1)%2)-1), abs(((j+1)%3)-1)) // tex coords (0,0),(1,1),(0,1)
            };

            // is vertex already in indices?
            GLuint idx = indexOf(vertices, vertex);
            if (idx >= vertices.size()) {
                // no, add it to the end of the list
                //idx = vertices.size();
                vertices.push_back(vertex);
            }
            // prime the index of current vertex for insertion
            tmp[j] = idx;
        }
        // insert vertex indices of current triangle
        indices.insert(indices.end(), tmp.begin(), tmp.end());

        // render both sides of triangles, for now as a #define option
#if TWO_SIDED
        std::reverse(tmp.begin(), tmp.end());
        indices.insert(indices.end(), tmp.begin(), tmp.end());
#endif
    }

#if DEBUG
    std::cout << "Vertices:" << std::endl << vertices.size() << std::endl;
    for (auto i = vertices.begin(); i != vertices.end(); ++i)
        std::cout << "(" << (*i).position[0] <<"," << (*i).position[1] <<"," << (*i).position[2] <<")" << ' ';
    std::cout << std::endl;

    std::cout << "Indices:" << std::endl << indices.size() << std::endl;
    for (auto i = indices.begin(); i != indices.end(); ++i)
        std::cout << *i << ' ';
    std::cout << std::endl;
#endif

    arrayBuf.bind();
    arrayBuf.allocate(&vertices[0], vertices.size() * sizeof(VertexData));

    indexBuf.bind();
    indexBuf.allocate(&indices[0], indices.size() * sizeof(GLuint));

    idxLen = indices.size();

    if (!lines.empty())
    {
        arrayBufLines.bind();
        arrayBufLines.allocate(&lines[0], lines.size() * sizeof(QVector3D));
    }

    if (!points.empty())
    {
        arrayBufPoints.bind();
        arrayBufPoints.allocate(&points[0], points.size() * sizeof(QVector3D));
    }
}
开发者ID:gareins,项目名称:surface-reconstruction,代码行数:80,代码来源:geometryengine.cpp

示例4: dragCheckPending

int UIDnDHandler::dragCheckPending(ulong screenID)
{
    int rc;
#ifdef VBOX_WITH_DRAG_AND_DROP_GH

    LogFlowFunc(("enmMode=%RU32, fIsPending=%RTbool, screenID=%RU32\n", m_enmMode, m_fIsPending, screenID));

    {
        QMutexLocker AutoReadLock(&m_ReadLock);

        if (   m_enmMode != DNDMODE_UNKNOWN
            && m_enmMode != DNDMODE_GUESTTOHOST) /* Wrong mode set? */
            return VINF_SUCCESS;

        if (m_fIsPending) /* Pending operation is in progress. */
            return VINF_SUCCESS;
    }

    QMutexLocker AutoWriteLock(&m_WriteLock);
    m_fIsPending = true;
    AutoWriteLock.unlock();

    /**
     * How this works: Source is asking the target if there is any DnD
     * operation pending, when the mouse leaves the guest window. On
     * return there is some info about a running DnD operation
     * (or defaultAction is KDnDAction_Ignore if not). With
     * this information we create a Qt QDrag object with our own QMimeType
     * implementation and call exec.
     *
     * Note: This function *blocks* until the actual drag'n drop operation
     *       has been finished (successfully or not)!
     */
    CGuest guest = m_pSession->guest();

    /* Clear our current data set. */
    m_dataSource.lstFormats.clear();
    m_dataSource.vecActions.clear();

    /* Ask the guest if there is a drag and drop operation pending (on the guest). */
    QVector<QString> vecFormats;
    m_dataSource.defaultAction = m_dndSource.DragIsPending(screenID, vecFormats, m_dataSource.vecActions);

    LogRelMax3(10, ("DnD: Default action is: 0x%x\n", m_dataSource.defaultAction));
    LogRelMax3(10, ("DnD: Number of supported guest actions: %d\n", m_dataSource.vecActions.size()));
        for (int i = 0; i < m_dataSource.vecActions.size(); i++)
            LogRelMax3(10, ("DnD: \tAction %d: 0x%x\n", i, m_dataSource.vecActions.at(i)));

    LogRelMax3(10, ("DnD: Number of supported guest formats: %d\n", vecFormats.size()));
        for (int i = 0; i < vecFormats.size(); i++)
        {
            const QString &strFmtGuest = vecFormats.at(i);
            LogRelMax3(10, ("DnD: \tFormat %d: %s\n", i, strFmtGuest.toAscii().constData()));
        }

    LogFlowFunc(("defaultAction=0x%x, vecFormatsSize=%d, vecActionsSize=%d\n",
                 m_dataSource.defaultAction, vecFormats.size(), m_dataSource.vecActions.size()));

    if (   m_dataSource.defaultAction != KDnDAction_Ignore
        && vecFormats.size())
    {
        for (int i = 0; i < vecFormats.size(); i++)
        {
            const QString &strFormat = vecFormats.at(i);
            m_dataSource.lstFormats << strFormat;
        }

        rc = VINF_SUCCESS; /* There's a valid pending drag and drop operation on the guest. */
    }
    else /* No format data from the guest arrived yet. */
        rc = VERR_NO_DATA;

    AutoWriteLock.relock();
    m_fIsPending = false;
    AutoWriteLock.unlock();

#else /* !VBOX_WITH_DRAG_AND_DROP_GH */

    NOREF(screenID);

    rc = VERR_NOT_SUPPORTED;

#endif /* VBOX_WITH_DRAG_AND_DROP_GH */

    LogFlowFuncLeaveRC(rc);
    return rc;
}
开发者ID:rickysarraf,项目名称:virtualbox,代码行数:87,代码来源:UIDnDHandler.cpp

示例5: on_buttonBox_accepted

// TODO: Build own exporter class
void objectExporter::on_buttonBox_accepted()
{
    QString fileName = QFileDialog::getSaveFileName(gloParent, "Save 3ds Object", ".", "3D Object (*.3ds)", 0, 0);

    QList<trackHandler*> trackList = gloParent->getTrackList();
    trackHandler* curTrack = trackList[ui->trackBox->currentIndex()];

    trackMesh* mesh = curTrack->mMesh;

    QVector<float> *vertices = new QVector<float>();
    QVector<unsigned int> *indices = new QVector<unsigned int>();
    QVector<unsigned int> *borders = new QVector<unsigned int>();

    Lib3dsFile *file = lib3ds_file_new();
    file->frames = 360;

    {
        Lib3dsMaterial* mat = lib3ds_material_new("coaster");
        lib3ds_file_insert_material(file, mat, -1);
        mat->diffuse[0] = curTrack->trackColors[0].red()/255.f;
        mat->diffuse[1] = curTrack->trackColors[0].green()/255.f;
        mat->diffuse[2] = curTrack->trackColors[0].blue()/255.f;
    }

    {
        for(int section = 0; section < curTrack->trackData->lSections.size(); ++section) {
            vertices->clear();
            indices->clear();
            borders->clear();
            mesh->build3ds(section, vertices, indices, borders);

            float* fvertices = new float[vertices->size()];
            for(int i = 0; i < vertices->size()/3; ++i) {
                fvertices[3*i+0] = vertices->at(3*i+0);
                fvertices[3*i+1] = -vertices->at(3*i+2);
                fvertices[3*i+2] = vertices->at(3*i+1);

                //exportScreen->doFastExport();
            }
            for(int subIndex = 0; subIndex < borders->size()-2; subIndex+= 2) {
                int fromVIndex = borders->at(subIndex)/3;
                int toVIndex = borders->at(subIndex+2)/3;
                int fromIIndex = borders->at(subIndex+1)/3;
                int toIIndex = borders->at(subIndex+3)/3;

                int i, j;
                QString name = QString::number(section).append(QString("_").append(QString::number(subIndex/2)));
                Lib3dsMesh *mesh = lib3ds_mesh_new(name.toLocal8Bit().data());
                Lib3dsMeshInstanceNode *inst;
                lib3ds_file_insert_mesh(file, mesh, -1);

                lib3ds_mesh_resize_vertices(mesh, toVIndex-fromVIndex, 1, 0);
                for (i = 0; i < toVIndex-fromVIndex; ++i) {
                    lib3ds_vector_copy(mesh->vertices[i], &fvertices[(i+fromVIndex)*3]);
                    mesh->texcos[i][0] = 0.f;
                    mesh->texcos[i][1] = 0.f;
                }

                lib3ds_mesh_resize_faces(mesh, toIIndex-fromIIndex);
                for (i = 0; i < toIIndex-fromIIndex; ++i) {
                    for (j = 0; j < 3; ++j) {
                        mesh->faces[i].index[j] = indices->at(3*(i+fromIIndex)+j)-fromVIndex;
                        mesh->faces[i].material = 0;
                    }
                }
                inst = lib3ds_node_new_mesh_instance(mesh, name.toLocal8Bit().data(), NULL, NULL, NULL);
                lib3ds_file_append_node(file, (Lib3dsNode*)inst, NULL);
            }
            delete[] fvertices;
        }
    }

    {
        Lib3dsCamera *camera;
        Lib3dsCameraNode *n;
        Lib3dsTargetNode *t;
        int i;

        camera = lib3ds_camera_new("camera01");
        lib3ds_file_insert_camera(file, camera, -1);
        lib3ds_vector_make(camera->position, 0.0, -100, 0.0);
        lib3ds_vector_make(camera->target, 0.0, 0.0, 0.0);

        n = lib3ds_node_new_camera(camera);
        t = lib3ds_node_new_camera_target(camera);
        lib3ds_file_append_node(file, (Lib3dsNode*)n, NULL);
        lib3ds_file_append_node(file, (Lib3dsNode*)t, NULL);

        lib3ds_track_resize(&n->pos_track, 37);
        for (i = 0; i <= 36; i++) {
            n->pos_track.keys[i].frame = 10 * i;
            lib3ds_vector_make(n->pos_track.keys[i].value,
                (float)(100.0 * cos(2 * F_PI * i / 36.0)),
                (float)(100.0 * sin(2 * F_PI * i / 36.0)),
                50.0
            );
        }
    }

//.........这里部分代码省略.........
开发者ID:esanderson,项目名称:openFVD,代码行数:101,代码来源:objectexporter.cpp

示例6: draw

void QSvgText::draw(QPainter *p, QSvgExtraStates &states)
{
    applyStyle(p, states);
    qreal oldOpacity = p->opacity();
    p->setOpacity(oldOpacity * states.fillOpacity);

    // Force the font to have a size of 100 pixels to avoid truncation problems
    // when the font is very small.
    qreal scale = 100.0 / p->font().pointSizeF();
    Qt::Alignment alignment = states.textAnchor;

    QTransform oldTransform = p->worldTransform();
    p->scale(1 / scale, 1 / scale);

    qreal y = 0;
    bool initial = true;
    qreal px = m_coord.x() * scale;
    qreal py = m_coord.y() * scale;
    QSizeF scaledSize = m_size * scale;

    if (m_type == TEXTAREA) {
        if (alignment == Qt::AlignHCenter)
            px += scaledSize.width() / 2;
        else if (alignment == Qt::AlignRight)
            px += scaledSize.width();
    }

    QRectF bounds;
    if (m_size.height() != 0)
        bounds = QRectF(0, py, 1, scaledSize.height()); // x and width are not used.

    bool appendSpace = false;
    QVector<QString> paragraphs;
    QStack<QTextCharFormat> formats;
    QVector<QList<QTextLayout::FormatRange> > formatRanges;
    paragraphs.push_back(QString());
    formatRanges.push_back(QList<QTextLayout::FormatRange>());

    for (int i = 0; i < m_tspans.size(); ++i) {
        if (m_tspans[i] == LINEBREAK) {
            if (m_type == TEXTAREA) {
                if (paragraphs.back().isEmpty()) {
                    QFont font = p->font();
                    font.setPixelSize(font.pointSizeF() * scale);

                    QTextLayout::FormatRange range;
                    range.start = 0;
                    range.length = 1;
                    range.format.setFont(font);
                    formatRanges.back().append(range);

                    paragraphs.back().append(QLatin1Char(' '));;
                }
                appendSpace = false;
                paragraphs.push_back(QString());
                formatRanges.push_back(QList<QTextLayout::FormatRange>());
            }
        } else {
            WhitespaceMode mode = m_tspans[i]->whitespaceMode();
            m_tspans[i]->applyStyle(p, states);

            QFont font = p->font();
            font.setPixelSize(font.pointSizeF() * scale);

            QString newText(m_tspans[i]->text());
            newText.replace(QLatin1Char('\t'), QLatin1Char(' '));
            newText.replace(QLatin1Char('\n'), QLatin1Char(' '));

            bool prependSpace = !appendSpace && !m_tspans[i]->isTspan() && (mode == Default) && !paragraphs.back().isEmpty() && newText.startsWith(QLatin1Char(' '));
            if (appendSpace || prependSpace)
                paragraphs.back().append(QLatin1Char(' '));

            bool appendSpaceNext = (!m_tspans[i]->isTspan() && (mode == Default) && newText.endsWith(QLatin1Char(' ')));

            if (mode == Default) {
                newText = newText.simplified();
                if (newText.isEmpty())
                    appendSpaceNext = false;
            }

            QTextLayout::FormatRange range;
            range.start = paragraphs.back().length();
            range.length = newText.length();
            range.format.setFont(font);
            range.format.setTextOutline(p->pen());
            range.format.setForeground(p->brush());

            if (appendSpace) {
                Q_ASSERT(!formatRanges.back().isEmpty());
                ++formatRanges.back().back().length;
            } else if (prependSpace) {
                --range.start;
                ++range.length;
            }
            formatRanges.back().append(range);

            appendSpace = appendSpaceNext;
            paragraphs.back() += newText;

            m_tspans[i]->revertStyle(p, states);
//.........这里部分代码省略.........
开发者ID:MarianMMX,项目名称:MarianMMX,代码行数:101,代码来源:qsvggraphics.cpp

示例7: plotOther

int BarPlot::plotOther()
{
	string dataType = Node->getFirst();

	// Get the types
	// Note the type is not always going to be the within the children of the node (depending on what node is passed)
	// It will be possible to pass in a different node (say a publication type node) when implemented
	vector<node*> types;
	if (Node->getParent() == NULL){
		vector<node*>* temptypes = Node->getChildren();
		for (int i = 0; i < temptypes->size(); i++){
			if (temptypes->at(i)->getSecond() > 0)
				types.push_back(temptypes->at(i));
		}
	}
	else{ types.push_back(Node);}

	// Grab Data and prepare x axis with (professor Name) labels:
	QVector<QString> labels;
	// Search for the prof names
	for (int i = 0; i < types.size(); i++){
		for (int j = 0; j < types.at(i)->getChildren()->size(); j++){
			QString name = QString::fromStdString(types.at(i)->getChildren()->at(j)->getFirst());
			if (!(labels.contains(name)))
				labels.push_back(name);
		}
	}

	// stacked bar chart can get cluttered, ensure no more than 30 different types
	// determine which types to push into an "Others" group
	vector<int> othersNdx;
	if (types.size() > COUNT_MAX){
		vector<double> typeSumCounts;
		for (int i = 0; i < types.size(); i++){
			if (Node->getFourth() > 0.0)
				typeSumCounts.push_back(types.at(i)->getFourth());
			else
				typeSumCounts.push_back(types.at(i)->getSecond());
		}
		while (types.size() - othersNdx.size() > COUNT_MAX){
			othersNdx.push_back(min_element(typeSumCounts.begin(), typeSumCounts.end()) - typeSumCounts.begin());
			typeSumCounts.at(min_element(typeSumCounts.begin(), typeSumCounts.end()) - typeSumCounts.begin()) = std::numeric_limits<double>::infinity();
		}
	}

	QVector<double> ticks;
	for (int i = 1; i <= labels.size(); i++)
		ticks.push_back(i);

	vector<QCPBars*> bars;
	QVector<double> othersCount(labels.size());
	double *othersData = othersCount.data();
	// create a new plottable area for each type, group everything within the "Others" group together
	for (int i = 0; i < types.size(); i++)
	{
		QVector<double> count(labels.size());
		double *data = count.data();
		// Note: not all types have same number of children (profs)
		// this would affect the labels (prof names)
		for (int j = 0; j < types.at(i)->getChildren()->size(); j++){
			int pos = labels.indexOf(QString::fromStdString(types.at(i)->getChildren()->at(j)->getFirst()));
			if (Node->getFourth() > 0.0)
				data[pos] = types.at(i)->getChildren()->at(j)->getFourth();
			else
				data[pos] = types.at(i)->getChildren()->at(j)->getSecond();
		}


		QCPBars *temp = new QCPBars(this->xAxis, this->yAxis);

		if (std::find(othersNdx.begin(), othersNdx.end(), i) != othersNdx.end()){
			for (int j = 0; j < labels.size(); j++)
				othersData[j] += count[j];
		}
		else{
			temp->setName(QString::fromStdString(types.at(i)->getFirst()));
			temp->setData(ticks, count);
			bars.push_back(temp);
			this->addPlottable(temp);
		}
	}
	// Graph "Others" only if there's something in it
	if (std::find(othersCount.begin(), othersCount.end(), (!0)) != othersCount.end()){
		QCPBars *temp = new QCPBars(this->xAxis, this->yAxis);
		temp->setName("Others");
		temp->setData(ticks, othersCount);
		bars.push_back(temp);
		this->addPlottable(temp);
	}
	// stack bars ontop of each other:
	// loop through each of the QCPBar objects in the list bars
	if (bars.size() > 1){
		for (int i = 0; i < (bars.size() - 1); i++)
			bars[i + 1]->moveAbove(bars[i]);
	}
	// set the colors
	QPen pen;
	pen.setWidthF(1.2);
	int C_HUE = 0;
	for (int i = 0; i < bars.size(); i++)
//.........这里部分代码省略.........
开发者ID:bpoulse,项目名称:teampear,代码行数:101,代码来源:barplot.cpp

示例8: mousePressEvent

void SCgModeBus::mousePressEvent (QGraphicsSceneMouseEvent * mouseEvent , bool afterSceneEvent)
{
    if(afterSceneEvent)
    {
        if(mDecoratedMode)
            mDecoratedMode->mousePressEvent(mouseEvent, afterSceneEvent);
        return;
    }

    mouseEvent->accept();
    QPointF mousePos = mouseEvent->scenePos();

    if (mPathItem && mouseEvent->button() == Qt::LeftButton)
        mPathItem->pushPoint(mousePos);

    // right button
    if (mouseEvent->button() == Qt::RightButton)
    {
        if (mPathItem)
        {
            mPathItem->popPoint();
            // if there is no points
            if (mPathItem->points().empty())
                delete mPathItem;
            return;
        }
    }

    if (mouseEvent->button() == Qt::LeftButton)
    {
        if (!mPathItem)
        {
            SCgVisualObject *obj = scene()->scgVisualObjectAt(mousePos);
            mNode = (obj != 0 && obj->type() == SCgVisualObject::SCgNodeType) ? static_cast<SCgVisualNode*>(obj) : 0;
            if(mNode)
            {
                mPathItem = new SCgPathItem(scene());
                mPathItem->pushPoint(mNode->scenePos());

                QPen pen;

                pen.setColor(Qt::blue);
                pen.setWidthF(5.f);
                pen.setCapStyle(Qt::RoundCap);
                pen.setStyle(Qt::DashDotLine);

                mPathItem->setPen(pen);
                return;
            }

        }else
        {
            QVector<QPointF> points = mPathItem->points();
            // The last point in points is mousePos, so we should get previous
            QVector2D vec(points.at(points.size() - 2) - mousePos);

            Q_ASSERT(mNode && mNode->baseObject() && mNode->baseObject()->type() == SCgObject::Node);
            if (points.size() > 2 && vec.length() < 5.f)
            {
                points.pop_back();

//                SCgVisualContour* contour = 0;
                // get parent contour
//                QGraphicsItem* parent = mNode->parentItem();

//                if (parent && parent->type() == SCgVisualContour::Type)
//                    contour = static_cast<SCgVisualContour*>(parent);

                scene()->pushCommand(new SCgCommandCreateBus(scene(), static_cast<SCgNode*>(mNode->baseObject()),
                                                                   points, 0));
                delete mPathItem;

                return;
            }
        }
    }

    if(mDecoratedMode)
    {
        mDecoratedMode->mousePressEvent(mouseEvent, afterSceneEvent);
        mPassMouseReleaseEvent = true;
    }
}
开发者ID:mcdir,项目名称:sui,代码行数:83,代码来源:scgmodebus.cpp

示例9: openForReWrite

// not threadsafe
bool DataFile::openForReWrite(const DataFile & other, const QString & filename, const QVector<unsigned> & chanNumSubset)
{
	if (!other.isOpenForRead()) {
		Error() << "INTERNAL ERROR: First parameter to DataFile::openForReWrite() needs to be another DataFile that is opened for reading.";
		return false;
	}
	if (isOpen()) closeAndFinalize();
	
	QString outputFile (filename);
	if (!QFileInfo(outputFile).isAbsolute())
        outputFile = mainApp()->outputDirectory() + "/" + outputFile; 
    
    Debug() << "outdir: " << mainApp()->outputDirectory() << " outfile: " << outputFile;
    
	dataFile.close();  metaFile.close();
    dataFile.setFileName(outputFile);
    metaFile.setFileName(metaFileForFileName(outputFile));
	
    if (!dataFile.open(QIODevice::WriteOnly|QIODevice::Truncate) ||
        !metaFile.open(QIODevice::WriteOnly|QIODevice::Truncate)) {
        Error() << "Failed to open either one or both of the data and meta files for " << outputFile;
        return false;
    }
	
//    badData = other.badData;
    badData.clear();
	mode = Output;
	const int nOnChans = chanNumSubset.size();
	params = other.params;
	params["outputFile"] = outputFile;
    params.remove("badData"); // rebuild this as we write!
	scanCt = 0;
	nChans = nOnChans;
	sha.Reset();
	sRate = other.sRate;
	range = other.range;
    writeRateAvg = 0.;
    nWritesAvg = 0;
    nWritesAvgMax = /*unsigned(sRate/10.)*/10;
    if (!nWritesAvgMax) nWritesAvgMax = 1;
	// compute save channel subset fudge
	const QVector<unsigned> ocid = other.channelIDs();
	chanIds.clear();
	customRanges.clear();
	chanDisplayNames.clear();
	QString crStr(""), cdnStr("");
	foreach (unsigned i, chanNumSubset) {
		if (i < unsigned(ocid.size())) {
			chanIds.push_back(ocid[i]);
			if (i < (unsigned)other.customRanges.size()) customRanges.push_back(other.customRanges[i]);
			else customRanges.push_back(range);
			if (i < (unsigned)other.chanDisplayNames.size()) chanDisplayNames.push_back(other.chanDisplayNames[i]);
			else chanDisplayNames.push_back(QString("Ch ") + QString::number(i));
			crStr.append(QString("%3%1:%2").arg(customRanges.back().min,0,'f',9).arg(customRanges.back().max,0,'f',9).arg(crStr.length() ? "," : ""));
			if (cdnStr.length()) cdnStr.append(",");
			cdnStr.append(QString(chanDisplayNames.back()).replace(",",""));
		} else 
			Error() << "INTERNAL ERROR: The chanNumSubset passet to DataFile::openForRead must be a subset of channel numbers (indices, not IDs) to use in the rewrite.";
	}
	params["saveChannelSubset"] = ConfigureDialogController::generateAIChanString(chanIds);
	params["nChans"] = nChans;
	if (params.contains("chanDisplayNames")) params["chanDisplayNames"] = cdnStr;
	if (params.contains("customRanges")) params["customRanges"] = crStr;
	pd_chanId = other.pd_chanId;
	
	return true;
}
开发者ID:cculianu,项目名称:SpikeGL,代码行数:68,代码来源:DataFile.cpp

示例10: CalculateIslands

 /**
  *  Determines whether or not islands exist and calculates what they are if
  *  present
  */
 void ControlGraph::CalculateIslands()
 {
   // assume subgraphs exist! (check assumption at the very end of the method)
   
   // A search list has a value for every cube, which defaults to false.
   // A breadth-first search is used to test connectivity and works by setting
   // each cubes cooresponding search list value to true as it is visited.
   // At the end of the first round the true entries make up the first
   // subgragh.  As they are added to the first subgraph they are removed from
   // the search list.  The remaining false entries must have the breadth-first
   // search done on them to determine the next subgraph(s).  This process
   // continues until all entries in the search list are true (until all cubes
   // have been visited)
   QMap< int, bool > searchList;
   for (int i = 0; i < graph->size(); i++)
     searchList.insert(i, false);
 
   // For each subgraph keep a list of the cubes in the subgraph.  This is 
   // represented by a 2d vector where the inner vectors are cubes within a
   // subgraph and the outer vector is a list of subgraphs
   islands = new QVector< QVector< int > >();
   
   // keeps track of which itteration of the breadth-first search we are on and
   // thus also which subgraph we are currently populating
   int subgraphIndex = -1;
   
   while (searchList.size())
   {
     // create a new subgraph
     subgraphIndex++;
     islands->push_back(QVector< int >());
     
     // The queue used for breadth-first searching
     QQueue< int > q;
     
     // visit the first cube
     searchList.begin().value() = true;
     q.enqueue(searchList.begin().key());
     
     // visit all cubes possible using the breadth-first approach
     while (q.size())
     {
       int curVertex(q.dequeue());
       QVector< int > adjacentVertices = graph->find(curVertex).value().first
           .GetAdjacentCubes();
  
       for (int i = 0; i < adjacentVertices.size(); i++)
       {
         const int & curNeighbor = adjacentVertices[i];
         
         ASSERT(searchList.find(curNeighbor) != searchList.end());
         
         if (!searchList.find(curNeighbor).value())
         {
           searchList.find(curNeighbor).value() = true;
           q.enqueue(curNeighbor);
         }
       }
     } // end of breadth-first search
     
     // add all true entries to the current subgraph
     QMap< int, bool >::iterator i = searchList.begin();
     while (i != searchList.end())
     {
       if (i.value())
       {
         (*islands)[subgraphIndex].push_back(i.key());
       }
       i++;
     }
     
     // remove all the true entries from the search list
     for (int i = 0; i < (*islands)[subgraphIndex].size(); i++)
     {
       searchList.remove((*islands)[subgraphIndex][i]);
     }
   }
   
   // if there was only ever one subgraph created then the initial assumption
   // was wrong!  There are no islands at all - this is a connected graph!
   if (subgraphIndex == 0)
   {
     islands->clear();
   }
 }
开发者ID:assutech,项目名称:isis3,代码行数:89,代码来源:ControlGraph.cpp

示例11: execute

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void WritePoleFigure::execute()
{
  setErrorCondition(0);
  dataCheck();
  if(getErrorCondition() < 0) { return; }

  DataContainer::Pointer m = getDataContainerArray()->getDataContainer(m_CellPhasesArrayPath.getDataContainerName());

  size_t dims[3] = { 0, 0, 0 };
  m->getGeometryAs<ImageGeom>()->getDimensions(dims);

  // Make sure any directory path is also available as the user may have just typed
  // in a path without actually creating the full path
  QDir path(getOutputPath());

  if (!path.mkpath(".") )
  {
    QString ss = QObject::tr("Error creating parent path '%1'").arg(path.absolutePath());
    setErrorCondition(-1);
    notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
    return;
  }

  bool missingGoodVoxels = true;

  if (NULL != m_GoodVoxels)
  {
    missingGoodVoxels = false;
  }

  // Find how many phases we have by getting the number of Crystal Structures
  size_t numPoints = m->getGeometryAs<ImageGeom>()->getNumberOfElements();
  size_t numPhases = m_CrystalStructuresPtr.lock()->getNumberOfTuples();

  // Loop over all the voxels gathering the Eulers for a specific phase into an array
  for (size_t phase = 1; phase < numPhases; ++phase)
  {
    size_t count = 0;
    // First find out how many voxels we are going to have. This is probably faster to loop twice than to
    // keep allocating memory everytime we find one.
    for (size_t i = 0; i < numPoints; ++i)
    {
      if (m_CellPhases[i] == phase)
      {
        if (missingGoodVoxels == true || m_GoodVoxels[i] == true)
        {
          count++;
        }
      }
    }
    QVector<size_t> eulerCompDim(1, 3);
    FloatArrayType::Pointer subEulers = FloatArrayType::CreateArray(count, eulerCompDim, "Eulers_Per_Phase");
    subEulers->initializeWithValue(std::numeric_limits<float>::signaling_NaN());
    float* eu = subEulers->getPointer(0);

    // Now loop through the eulers again and this time add them to the subEulers Array
    count = 0;
    for (size_t i = 0; i < numPoints; ++i)
    {
      if (m_CellPhases[i] == phase)
      {
        if (missingGoodVoxels == true || m_GoodVoxels[i] == true)
        {
          eu[count * 3] = m_CellEulerAngles[i * 3];
          eu[count * 3 + 1] = m_CellEulerAngles[i * 3 + 1];
          eu[count * 3 + 2] = m_CellEulerAngles[i * 3 + 2];
          count++;
        }
      }
    }
    if (subEulers->getNumberOfTuples() == 0) { continue; } // Skip because we have no Pole Figure data

    QVector<UInt8ArrayType::Pointer> figures;

    PoleFigureConfiguration_t config;
    config.eulers = subEulers.get();
    config.imageDim = getImageSize();
    config.lambertDim = getLambertSize();
    config.numColors = getNumColors();

    QString label("Phase_");
    label.append(QString::number(phase));

    QString ss = QObject::tr("Generating Pole Figures for Phase %1").arg(phase);
    notifyStatusMessage(getMessagePrefix(), getHumanLabel(), ss);

    switch(m_CrystalStructures[phase])
    {
      case Ebsd::CrystalStructure::Cubic_High:
        figures = makePoleFigures<CubicOps>(config);
        break;
      case Ebsd::CrystalStructure::Cubic_Low:
        figures = makePoleFigures<CubicLowOps>(config);
        break;
      case Ebsd::CrystalStructure::Hexagonal_High:
        figures = makePoleFigures<HexagonalOps>(config);
        break;
//.........这里部分代码省略.........
开发者ID:BlueQuartzSoftware,项目名称:DREAM3D,代码行数:101,代码来源:WritePoleFigure.cpp

示例12: updateStatus

bool
PowerTapDevice::download( const QDir &tmpdir,
                         QList<DeviceDownloadFile> &files,
                         QString &err)
{
    if (!dev->open(err)) {
        err = tr("ERROR: open failed: ") + err;
        return false;
    }
    // make several attempts at reading the version
    int attempts = 3;
    int veridx = -1;
    int version_len;
    char vbuf[256];
    QByteArray version;

    do {
	if (!doWrite(dev, 0x56, false, err)) // 'V'
	    return false;

    emit updateStatus( tr("Reading version...") );
    if(m_Cancelled) {
        err = tr("download cancelled");
	    return false;
	}

	version_len = readUntilNewline(dev, vbuf, sizeof(vbuf), err);
	if (version_len < 0) {
	    err = tr("Error reading version: ") + err;
	    return false;
	}
	if (PT_DEBUG) {
	    printf("read version \"%s\"\n",
		   cEscape(vbuf, version_len).toAscii().constData());
	}
	version = QByteArray(vbuf, version_len);

	// We expect the version string to be something like
	// "VER 02.21 PRO...", so if we see two V's, it's probably
	// because there's a hardware echo going on.
	veridx = version.indexOf("VER");

    } while ((--attempts > 0) && (veridx < 0));

    if (veridx < 0) {
	err = QString(tr("Unrecognized version \"%1\""))
	    .arg(cEscape(vbuf, version_len));
	return false;
    }
    bool hwecho = version.indexOf('V') < veridx;
    if (PT_DEBUG) printf("hwecho=%s\n", hwecho ? "true" : "false");

    emit updateStatus( tr("Reading header...") );
    if(m_Cancelled) {
        err = tr("download cancelled");
        return false;
    }

    if (!doWrite(dev, 0x44, hwecho, err)) // 'D'
        return false;
    unsigned char header[6];
    int header_len = dev->read(header, sizeof(header), err);
    if (header_len != 6) {
        if (header_len < 0)
            err = tr("ERROR: reading header: ") + err;
        else
            err = tr("ERROR: timeout reading header");
        return false;
    }
    if (PT_DEBUG) {
        printf("read header \"%s\"\n",
               cEscape((char*) header,
                       sizeof(header)).toAscii().constData());
    }
    QVector<unsigned char> records;
    for (size_t i = 0; i < sizeof(header); ++i)
        records.append(header[i]);

    emit updateStatus( tr("Reading ride data...") );
    if(m_Cancelled) {
        err = tr("download cancelled");
        return false;
    }
    double recIntSecs = 0.0;

    fflush(stdout);
    while (true) {
        if (PT_DEBUG) printf("reading block\n");
        unsigned char buf[256 * 6 + 1];
        int n = dev->read(buf, 2, err);
        if (n < 2) {
            if (n < 0)
                err = tr("ERROR: reading first two: ") + err;
            else
                err = tr("ERROR: timeout reading first two");
            return false;
        }
        if (PT_DEBUG) {
            printf("read 2 bytes: \"%s\"\n",
                   cEscape((char*) buf, 2).toAscii().constData());
//.........这里部分代码省略.........
开发者ID:ClaFio,项目名称:GoldenCheetah,代码行数:101,代码来源:PowerTapDevice.cpp

示例13: fin

int
main(int argc, char *argv[])
{

    //QMultiHash<QString, StringPair> hashTable;
    QHash<QString, QSet<QString> > predictTable;
    QHash<StringPair, ulong> countTable;
    QVector<QString> tagsV;
    QHash<ulong, QVector<StringPair> > hashTb;
    tagsV.clear();
    QFile fin(argv[1]);
    QTextStream out(stdout);
    QTextStream err(stderr);

    if (argc != 3) {
        out << "Usage: genhashtable dictfile.txt hashtablefile.txt" << endl;
        return 0;
    }

    if (!fin.open(QIODevice::ReadOnly | QIODevice::Text)) {
        err << "ERROR: input file not found" << endl;
        return 1;
    }

    QTextStream sfin(&fin);
    sfin.setCodec("UTF-8");
    out.setCodec("UTF-8");
    QString line = sfin.readLine();
    QStringList lineParts;

    bool isfirst = false;

    QString form, normalForm, tags;
    while (!line.isNull()) {
        lineParts = line.split(QRegExp("[\t ]"), QString::SkipEmptyParts);
        if (isfirst) {
            if (!(lineParts.size() < 2 || lineParts[1].startsWith("VERB,") || lineParts[1].startsWith("PRTF,")
                    || lineParts[1].startsWith("PRTS,") || lineParts[1].startsWith("GRND,"))) {
                normalForm = lineParts[0];
            }
            isfirst = false;
        }

        if (lineParts.size() > 2 && lineParts[1].startsWith("INFN,")) {
            normalForm = lineParts[0];
        }

        if (lineParts.size() < 1) {
            line = sfin.readLine();
            continue;
        }

        if (lineParts.size() == 1) {
            isfirst = true;
            line = sfin.readLine();
            continue;
        }
        form = lineParts[0]; 
        QChar yo = QString::fromUtf8("Ё")[0];
        QChar ye = QString::fromUtf8("Е")[0];
        form.replace(yo, ye, Qt::CaseInsensitive);
        tags = lineParts[1];
        
        if (lineParts.size() == 3) {
            tags += ("," + lineParts[2]);
        }

        if (tagsV.indexOf(tags) == -1) {
            tagsV.append(tags);
        }
        hashTb[tagsV.indexOf(tags)].append(StringPair(normalForm, form));

        //hashTable.insert(form, StringPair(normalForm, tags));
        predictTable[form.right(3)].insert(tags);
        ++countTable[StringPair(form.right(3), tags)];

        line = sfin.readLine();
    }
    fin.close();

    //out << "Table size: " << hashTable.size() << endl;
    QString result("");
    for (int i = 0; i < tagsV.size(); ++i) {
        result += ("& " + tagsV[i] + " ");
        for (int j = 0; j < hashTb[i].size(); ++j) {
            result += (hashTb[i][j].first + " " + hashTb[i][j].second + " ");
        }
    }
    
    result += "\n----------";
    for (QHash<QString, QSet<QString> >::const_iterator itr = predictTable.begin(); itr != predictTable.end(); ++itr) {
        for (QSet<QString>::const_iterator jtr = itr.value().begin(); jtr != itr.value().end(); ++jtr) {
            result += (" " + itr.key() + " " + *jtr);
        }
    }
    result += "\n----------";
    for (QHash<StringPair, ulong>::const_iterator itr = countTable.begin(); itr != countTable.end(); ++itr) {
        result += (" " + itr.key().first + " " + itr.key().second + " " + QString::number(itr.value()));
    }
    result += "\n----------";
//.........这里部分代码省略.........
开发者ID:al-pacino,项目名称:RussianDependencyParser,代码行数:101,代码来源:genhashtable.cpp

示例14: calculateBpm

double BeatUtils::calculateBpm(const QVector<double>& beats, int SampleRate,
                               int min_bpm, int max_bpm) {
    /*
     * Let's compute the average local
     * BPM for N subsequent beats.
     * The average BPMs are
     * added to a list from which the statistical
     * median is computed
     *
     * N=12 seems to work great; We coincide with Traktor's
     * BPM value in many case but not worse than +-0.2 BPM
     */
    /*
     * Just to demonstrate how you would count the beats manually
     *
     *    Beat numbers:   1  2  3  4   5  6  7  8    9
     *    Beat positions: ?  ?  ?  ?  |?  ?  ?  ?  | ?
     *
     * Usually one measures the time of N beats. One stops the timer just before
     * the (N+1)th beat begins.  The BPM is then computed by 60*N/<time needed
     * to count N beats (in seconds)>
     *
     * Although beat tracking through QM is promising, the local average BPM of
     * 4 beats varies frequently by +-2 BPM.  Somtimes there N subsequent beats
     * in the grid that are computed wrongly by QM.
     *
     * Their local BPMs can be considered as outliers which would influence the
     * BPM computation negatively. To exclude outliers, we select the median BPM
     * over a window of N subsequent beats.

     * To do this, we take the average local BPM for every N subsequent
     * beats. We then sort the averages and take the middle to find the median
     * BPM.
     */

    if (beats.size() < 2) {
        return 0;
    }

    // If we don't have enough beats for our regular approach, just divide the #
    // of beats by the duration in minutes.
    if (beats.size() <= N) {
        return 60.0 * (beats.size()-1) * SampleRate / (beats.last() - beats.first());
    }

    QMap<double, int> frequency_table;
    QList<double> average_bpm_list = computeWindowedBpmsAndFrequencyHistogram(
        beats, N, 1, SampleRate, &frequency_table);

    // Get the median BPM.
    qSort(average_bpm_list);
    const double median = computeSampleMedian(average_bpm_list);

    /*
     * Okay, let's consider the median an estimation of the BPM To not soley
     * rely on the median, we build the average weighted value of all bpm values
     * being at most +-1 BPM from the median away.  Please note, this has
     * improved the BPM: While relying on median only we may have a deviation of
     * about +-0.2 BPM, taking into account BPM values around the median leads
     * to deviation of +- 0.05 Please also note that this value refers to
     * electronic music, but to be honest, the BPM detection of Traktor and Co
     * work best with electronic music, too. But BPM detection for
     * non-electronic music isn't too bad.
     */

    //qDebug() << "BPM range between " << min_bpm << " and " << max_bpm;

    // a subset of the 'frequency_table', where the bpm values are +-1 away from
    // the median average BPM.
    QMap<double, int> filtered_bpm_frequency_table;
    const double filterWeightedAverageBpm = computeFilteredWeightedAverage(
        frequency_table, median, kBpmFilterTolerance, &filtered_bpm_frequency_table);

    if (sDebug) {
        qDebug() << "Statistical median BPM: " << median;
        qDebug() << "Weighted Avg of BPM values +- 1BPM from the media"
                 << filterWeightedAverageBpm;
    }

    /*
     * Although we have a minimal deviation of about +- 0.05 BPM units compared
     * to Traktor, this deviation may cause the beat grid to look unaligned,
     * especially at the end of a track.  Let's try to get the BPM 'perfect' :-)
     *
     * Idea: Iterate over the original beat set where some detected beats may be
     * wrong. The beat is considered 'correct' if the beat position is within
     * epsilon of a beat grid obtained by the global BPM.
     *
     * If the beat turns out correct, we can compute the error in BPM units.
     * E.g., we can check the original beat position after 60 seconds. Ideally,
     * the approached beat is just a couple of samples away, i.e., not worse
     * than 0.05 BPM units.  The distance between these two samples can be used
     * for BPM error correction.
     */

     double perfect_bpm = 0;
     double firstCorrectBeatSample = beats.first();
     bool foundFirstCorrectBeat = false;

     int counter = 0;
//.........这里部分代码省略.........
开发者ID:Alppasa,项目名称:mixxx,代码行数:101,代码来源:beatutils.cpp

示例15: newEntry

QVector<QString> HMMTagger::tag(QVector<QString> const &sentence) const
{
	QVector<QVector<TagMatrixEntry> > tagMatrix(sentence.size(), QVector<TagMatrixEntry>());

	// We can't estimate the trigram probabilities for the first two tags,
	// so add them to the tag matrix as-is. Normally, these are start markers
	// anyway. XXX - maybe we should at the very least look them up in the
	// lexicon?
	size_t startTag = d_model->tagNumbers().find(sentence[0]).value();
	tagMatrix[0].push_back(TagMatrixEntry(startTag));
	tagMatrix[1].push_back(TagMatrixEntry(startTag));
	tagMatrix[1][0].probs[&tagMatrix[0][0]] = 0.0;
	tagMatrix[1][0].bps[&tagMatrix[0][0]] = 0;

	double beam = 0.0;

	// Loop through the tokens.
	for (int i = 2; i < sentence.size(); ++i)
	{
		double columnHighestProb = -numeric_limits<double>::infinity();
		WordHandler::ProbSet tagProbs = d_wordHandler->tags(sentence[i]);

		// Loop over all possible tags for the current word.
		for (WordHandler::ProbSet::const_iterator tagProbsIter = tagProbs.begin();
			tagProbsIter != tagProbs.end(); ++tagProbsIter)
		{
			TagMatrixEntry newEntry(tagProbsIter->first);

			// Loop over all possible trigrams.
			for (QVector<TagMatrixEntry>::const_iterator t2Iter =
				tagMatrix[i - 1].begin(); t2Iter != tagMatrix[i - 1].end();
				++t2Iter)
			{
				double highestProb = -numeric_limits<double>::infinity();
				TagMatrixEntry const *highestProbBp = 0;

				for (QHash<TagMatrixEntry const *, double>::const_iterator t1Iter =
					t2Iter->probs.begin(); t1Iter != t2Iter->probs.end(); ++t1Iter)
				{
					if (t1Iter.value() < beam)
						continue;

					TriGram curTriGram(t1Iter.key()->tag, t2Iter->tag, tagProbsIter->first);
					double triGramProb = d_smoothing->triGramProb(curTriGram);

					// The probability of the current state is P(w|t) * p(t3|t1,t2) *
					// p(prev_state).
					double prob = triGramProb + tagProbsIter->second + t1Iter.value();

					// Store the path the maximizes the probability.
					if (prob > highestProb)
					{
						highestProb = prob;
						//highestProbBp = t2Iter->bps.find(t1Iter->first)->second;
						highestProbBp = t1Iter.key();
					}
				}

				newEntry.probs[&(*t2Iter)] = highestProb;
				newEntry.bps[&(*t2Iter)] = highestProbBp;

				if (highestProb > columnHighestProb)
					columnHighestProb = highestProb;
			}


			tagMatrix[i].push_back(newEntry);
		}

		beam = columnHighestProb - d_beamFactor;
	}

	// Find the most probable final state.
	double highestProb = -numeric_limits<double>::infinity();
	TagMatrixEntry const *tail = 0;
	TagMatrixEntry const *beforeTail = 0;

	QVector<TagMatrixEntry> &lastColumn = tagMatrix[sentence.size() - 1];

	for (QVector<TagMatrixEntry>::const_iterator iter = lastColumn.begin();
			iter != lastColumn.end(); ++iter)
		for (QHash<TagMatrixEntry const *, double>::const_iterator probIter =
			iter->probs.begin(); probIter != iter->probs.end(); ++probIter)
		{
			if (probIter.value() > highestProb)
			{
				highestProb = probIter.value();
				tail = &(*iter);
				beforeTail = probIter.key();
			}
		}

	// Extract the most probable tag sequence.
	QVector<QString> tagSequence;
	for (int i = tagMatrix.size() - 1; i >= 0; --i)
	{
		QString tagString = d_model->numberTags().find(tail->tag).value();
		tagSequence.push_back(tagString);

		if (beforeTail)
//.........这里部分代码省略.........
开发者ID:luoq,项目名称:citar,代码行数:101,代码来源:HMMTagger.cpp


注:本文中的QVector::size方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。