Example #1
0
void CCropDialog::DoRelight(int nDirection, 
		itk::ImageLinearConstIteratorWithIndex<ImageType> InputIt, 
		itk::ImageLinearIteratorWithIndex<ImageType> OutputIt)
{
	InputIt.SetDirection(nDirection);
	OutputIt.SetDirection(nDirection);
	 
	for(InputIt.GoToBegin(), OutputIt.GoToBegin(); !InputIt.IsAtEnd(); 
			InputIt.NextLine(), OutputIt.NextLine())
	{
		QVector<PixelType> PixelsInLine;
		while( !InputIt.IsAtEndOfLine() )
		{
			PixelsInLine << InputIt.Get();  // it.Set() doesn't exist in the Const Iterator
			++InputIt;
		}
		qSort(PixelsInLine.begin(), PixelsInLine.end());
		PixelType Median = PixelsInLine[PixelsInLine.size()/2];
		
		bool bIntensityError = false;
		
		if(Median < nERROR_THRESHOLD)
			bIntensityError = true;

		for(InputIt.GoToBeginOfLine(); !InputIt.IsAtEndOfLine(); ++InputIt, ++OutputIt)
		{
			PixelType PixelValue = InputIt.Get();
			if(bIntensityError == true)
			{
				if(PixelValue < Median*nERROR_FACTOR) // (1-0.2)
				{
					OutputIt.Set(PixelValue); // use the original value
					continue;
				}
			}
			double dAdjustPixelValue = (PixelValue/(double)Median) * nILLUMINATION;
			PixelValue = (dAdjustPixelValue > (double)nMAX_PIXEL_VALUE)
							? (PixelType)nMAX_PIXEL_VALUE : (PixelType)dAdjustPixelValue;
			OutputIt.Set(PixelValue);
		}
		QCoreApplication::processEvents();
	}	
}
QVector<FoodAmount> FoodAmount::getScaledComponents() const
{
  // See getScaledNutrients for logic description

  if (getFood() == NULL) {
    throw std::logic_error("Attempted to scale the components of an undefined food.");
  }

  QVector<FoodAmount> components = getFood()->getComponentAmounts();

  double scaleFactor = getScaleFactor();

  for (QVector<FoodAmount>::iterator i = components.begin(); i != components.end(); ++i)
  {
    (*i) *= scaleFactor;
  }

  return components;
}
QVector<PasswordEntry> GnomeKeyringPasswordBackend::getEntries(const QUrl &url)
{
    initialize();

    const QString host = PasswordManager::createHost(url);

    QVector<PasswordEntry> list;

    foreach (const PasswordEntry &entry, m_allEntries) {
        if (entry.host == host) {
            list.append(entry);
        }
    }

    // Sort to prefer last updated entries
    qSort(list.begin(), list.end());

    return list;
}
Example #4
0
void InsertDeleteChangesCommand::insertDeleteChanges()
{
    int numAddedChars = 0;
    QVector<KChangeTrackerElement *> elementVector;
    KTextDocument(m_document).changeTracker()->deletedChanges(elementVector);
    qSort(elementVector.begin(), elementVector.end(), isPositionLessThan);

    foreach (KChangeTrackerElement *element, elementVector) {
        if (element->isValid() && element->deleteChangeMarker()) {
            QTextCursor caret(element->deleteChangeMarker()->document());
            caret.setPosition(element->deleteChangeMarker()->position() + numAddedChars +  1);
            QTextCharFormat f = caret.charFormat();
            f.clearProperty(KCharacterStyle::InlineInstanceId);
            caret.setCharFormat(f);
            KChangeTracker::insertDeleteFragment(caret, element->deleteChangeMarker());
            numAddedChars += KChangeTracker::fragmentLength(element->deleteData());
        }
    }
}
Example #5
0
void NSGA_II::CrowdingDistanceAssignement(QVector<Solution*>&F) {
    double max_min;
    for (int i = 0; i < F.size(); i++) {
        F[i]->zatloczenie = 0;
    }
    for (unsigned int i_fun = 0; i_fun < problem->funkcje.size(); i_fun++) {
        Solution::tmp = 0;
        qSort(F.begin(), F.end(), lessThenSolution);
        F[0]->zatloczenie = numeric_limits<double>::max();
        F[F.size() - 1]->zatloczenie = numeric_limits<double>::max();
        max_min = F[F.size() - 1]->przystosowaniePrzeskalowane[i_fun]-F[0]->przystosowaniePrzeskalowane[i_fun];
        for (int i_sol = 1; i_sol < F.size() - 1; i_sol++) {
            if (F[i_sol]->zatloczenie != numeric_limits<double>::max()) {

                F[i_sol]->zatloczenie += (F[i_sol + 1]->przystosowaniePrzeskalowane[i_fun]-F[i_sol - 1]->przystosowaniePrzeskalowane[i_fun]) / max_min;
            }
        }
    }
}
Example #6
0
    QVector<QString> readDictionary(const QString &filename, int length, bool(*f)(int,int))
    {
        QVector<QString> dictionar;
        QFile file(filename);
        if (!file.open(QIODevice::ReadOnly)) {
            QMessageBox::information(NULL, "Information", "Couldn't open the database");
        }

        QTextStream in(&file);
        while (!in.atEnd()) {
            QString word = in.readLine();
            if (f(word.size(), length))
            {
                dictionar.push_back(word);
            }
        }
        std::sort(dictionar.begin(), dictionar.end());
        return dictionar;
    }
Example #7
0
void SOM::train( QMap<QString, QVariant> somParameters, QVector<FeaturePtr> features, bool skipInit_debugOnly )
{

    if( skipInit_debugOnly == false )
        initializeTraining( somParameters, features );

    do
    {
       // Shuffle the list of features to remove bias
        std::random_shuffle( features.begin(), features.end() );

        // Update the SOM with each feature from the globalFeatures list.
        // @todo: consider random sampling for the training if the number of features is high
        foreach( FeaturePtr feature, features )
            update( feature );

    } while( nextEpoch() != false );

}
Example #8
0
QString STGoThroughCommonStringPool(const char *s, int *outIndex){
    initCommonStringPool();
    QVector<CommonCStringPair>::iterator it;
    CommonCStringPair pair;
    pair.text=s;
    pair.index=0;
    it=qLowerBound(g_commonsStringsVector.begin(),
                   g_commonsStringsVector.end(),
                   pair, cStringComparer);
    if(it==g_commonsStringsVector.end() || strcmp(it->text, s)){
        if(outIndex)
            *outIndex=-1;
        return QString(s);
    }
    int index=it->index;
    if(outIndex)
        *outIndex=index;
    return g_commonStringsQList[index];
}
Example #9
0
void MeshControlPainter::_paintShape(QPainter *painter, MapperGLCanvas* canvas)
{
  Mesh* mesh = static_cast<Mesh*>(getShape().data());
  Q_ASSERT(mesh);

  // Init colors and stroke.
  painter->setPen(getRescaledShapeStroke(canvas, true));

  // Draw inner quads.
  QVector<Quad::ptr> quads = mesh->getQuads();
  for (QVector<Quad::ptr>::const_iterator it = quads.begin(); it != quads.end(); ++it)
  {
    painter->drawPolygon((*it)->toPolygon());
  }

  // Draw outer quad.
  painter->setPen(getRescaledShapeStroke(canvas));
  painter->drawPolygon(_shapeItem->mapFromScene(mesh->toPolygon()));
}
void SubItemDelegate::paint( QPainter * p,
				const QStyleOptionViewItem & option,
				const QModelIndex & index ) const  
{
	p->save();
	if (option.state & QStyle::State_Selected)
	{
		p->fillRect(option.rect, option.palette.highlight());
		p->setPen( Qt::white );
	}
	QVariant var = index.model()->data(index, Qt::DisplayRole);
	Subtitle *_subtitle = qVariantValue<Subtitle *>(var);
	QFontMetrics fm( QApplication::font() );
	p->setFont( QApplication::font() );
	int begin =  option.rect.y() + fm.lineSpacing();
	int xbeg = option.rect.x() + 3;
	if ( _subtitle->getProblem() )
	{
		p->setPen( Qt::red );
	}
	p->drawText( xbeg, begin, _subtitle->getTiming() );
	
	QVector<Subline> v = _subtitle->getSubs();
	QVector<Subline>::const_iterator it;
	for ( it = v.begin(); it != v.end(); it++ )
	{
		begin += fm.lineSpacing();
		QFont f( QApplication::font() );
		if ( it->getFmt() == Subline::Italic )
		{
			f.setItalic( true );

		}
		else if ( it->getFmt() == Subline::Bold )
		{
			f.setBold( true );
		}
		p->setFont( f );
		p->drawText( xbeg, begin, it->getLine() );
		p->setFont( QApplication::font() );
	}
	p->restore();
}
Example #11
0
    void checkRemoveEntitiesNotInSubset()
    {
        // GIVEN
        Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport();
        Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport);
        Qt3DRender::QLayerFilter *layerFilter = new Qt3DRender::QLayerFilter(clearBuffer);
        Qt3DRender::QLayer *layer = new Qt3DRender::QLayer();
        layerFilter->addLayer(layer);
        Qt3DRender::TestAspect testAspect(buildEntityFilterTestScene(viewport, layer));

        // THEN
        Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(layerFilter->id());
        QVERIFY(leafNode != nullptr);

        // WHEN
        Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer());
        renderViewBuilder.setLayerCacheNeedsToBeRebuilt(true);
        renderViewBuilder.prepareJobs();
        renderViewBuilder.buildJobHierachy();

        renderViewBuilder.renderViewJob()->run();
        renderViewBuilder.renderableEntityFilterJob()->run();
        renderViewBuilder.syncRenderViewInitializationJob()->run();
        renderViewBuilder.filterEntityByLayerJob()->run();

        QVector<Qt3DRender::Render::Entity *> renderableEntity = renderViewBuilder.renderableEntityFilterJob()->filteredEntities();
        QVector<Qt3DRender::Render::Entity *> filteredEntity = renderViewBuilder.filterEntityByLayerJob()->filteredEntities();

        // THEN
        QCOMPARE(renderableEntity.size(), 200);
        QCOMPARE(filteredEntity.size(), 100);

        std::sort(renderableEntity.begin(), renderableEntity.end());

        // WHEN
        renderableEntity = Qt3DRender::Render::RenderViewBuilder::entitiesInSubset(renderableEntity, filteredEntity);

        // THEN
        QCOMPARE(renderableEntity.size(), 100);
        for (const auto entity : renderableEntity) {
            QVERIFY(filteredEntity.contains(entity));
        }
    }
Example #12
0
QPair<T, T> confint(const QVector<T> &vecin) {
	long double avg = 0.0;
	long double stddev = 0.0;
	QVector<T> vec = vecin;
	qSort(vec.begin(), vec.end());
	for (int i=0;i<vec.count() / 20;++i) {
		vec.pop_front();
		vec.pop_back();
	}

	foreach(T v, vec)
		avg += v;
	avg /= vec.count();

	foreach(T v, vec)
		stddev += (v-avg)*(v-avg);
	stddev = sqrtl(stddev / vec.count());
	return QPair<T,T>(static_cast<T>(avg), static_cast<T>(1.96 * stddev));
}
void RealTimeMultiSampleArray::setVector(QVector<double> v)
{
    if(v.size() != int(m_uiNumChannels))
        qDebug() << "Error Occured in RealTimeMultiSampleArray::setVector: Vector size does not matche the number of channels! ";

    for(QVector<double>::iterator it = v.begin(); it != v.end(); ++it)
    {
        if(*it < m_dMinValue) *it = m_dMinValue;
        else if(*it > m_dMaxValue) *it = m_dMaxValue;
    }

    m_vecValue = v;
    m_matSamples.push_back(m_vecValue);
    if(m_matSamples.size() >= m_ucMultiArraySize && notifyEnabled)
    {
        notify();
        m_matSamples.clear();
    }
}
Example #14
0
	void SeparateTabBar::UpdateComputedWidths () const
	{
		const auto cnt = count ();
		ComputedWidths_.resize (cnt);

		const auto maxTabWidth = width () / 4;

		struct TabInfo
		{
			int Idx_;
			int WidthHint_;
		};
		QVector<TabInfo> infos;
		for (int i = 0; i < cnt - 1; ++i)
			infos.push_back ({ i, std::min (QTabBar::tabSizeHint (i).width (), maxTabWidth) });
		std::sort (infos.begin (), infos.end (),
				[] (const TabInfo& l, const TabInfo& r) { return l.WidthHint_ < r.WidthHint_; });

		const auto hspace = std::max (style ()->pixelMetric (QStyle::PM_TabBarTabHSpace), 10);
		const auto btnWidth = AddTabButton_ ? AddTabButton_->sizeHint ().width () + hspace : 30;

		auto remainder = width () - btnWidth;

		while (!infos.isEmpty ())
		{
			auto currentMax = remainder / infos.size ();
			if (infos.front ().WidthHint_ > currentMax)
				break;

			const auto& info = infos.front ();
			remainder -= info.WidthHint_;
			ComputedWidths_ [info.Idx_] = info.WidthHint_;
			infos.pop_front ();
		}

		if (infos.isEmpty ())
			return;

		const auto uniform = remainder / infos.size ();
		for (const auto& info : infos)
			ComputedWidths_ [info.Idx_] = uniform;
	}
Example #15
0
void MainWindow::exportImage() {

    QVector<CPoint> centroids = nGas.getCentroids();
    QVector<KPoint> points = nGas.getPoints();

    QImage image(imageSize,QImage::Format_RGB32);

    QProgressDialog progress(this);
    progress.setWindowTitle("Self-organizing maps");
    progress.setLabelText("Generating file...");
    progress.setModal(true);
    progress.show();

    int k = 0;

    for(int i=0;i<image.width();i++) {
        progress.setValue(((double)i / (double)image.width()) * 100);
        if(progress.wasCanceled())
            return;

        for(int j=0;j<image.height();j++) {
            for(int d=0;d<centroids.size();d++)
                centroids[d].setDistance(Centroids::countDistance(centroids[d],points[k]));
            qSort(centroids.begin(),centroids.end(),SortByDistance());
            image.setPixel(i,j,qRgb(centroids[0].paramAt(0),centroids[1].paramAt(1),centroids[2].paramAt(2)));
            k++;
        }
    }

    progress.setValue(100);

    QGraphicsScene* scene = new QGraphicsScene(this);
    ui->graphicsView_2->setScene(scene);
    scene->addPixmap(QPixmap::fromImage(image.scaled(ui->graphicsView->width()*0.95,ui->graphicsView->height()*0.95)));
    ui->graphicsView_2->show();

    QImageWriter writer;
    writer.setFileName(QFileDialog::getSaveFileName(this,tr("Open image"),"C:\\Users\\GiBSoN\\Desktop",tr("Image files (*.jpg *.png)")));
    writer.setFormat("jpg");
    writer.setCompression(10);
    writer.write(image);
}
Example #16
0
void placeHyphens(const QString& word, QString& hyphenWord)
{
    QString alphabet = "[абвгдеёжзийклмнопрстуфхцчшщъыьэюя]";
    QString vowel = "[аеёиоуыэюя]";
    QString consonant = "[бвгджзйклмнпрстфхцчшщ]";
    QString special = "[ьъй]";
    QString replacementSymbols = "\1";

    // Правила для расстановки мягких переносов.
    typedef QRegularExpression RX;
    QString replaceOn = "\\1" + replacementSymbols + "\\2";
    QVector<QRegularExpression> rules;
    
    rules.push_back(RX("(" + special + ")" + "(" + alphabet + alphabet + ")", RX::CaseInsensitiveOption));
    rules.push_back(RX("(" + vowel + ")" + "(" + vowel + alphabet + ")", RX::CaseInsensitiveOption));
    rules.push_back(RX("(" + vowel + consonant + ")" + "(" + consonant + vowel + ")", RX::CaseInsensitiveOption));
    rules.push_back(RX("(" + consonant + vowel + ")" + "(" + consonant + vowel + ")", RX::CaseInsensitiveOption));
    rules.push_back(RX("(" + vowel + consonant + ")" + "(" + consonant + consonant + vowel + ")", RX::CaseInsensitiveOption));
    rules.push_back(RX("(" + vowel + consonant + consonant + ")" + "(" + consonant + consonant + vowel + ")", RX::CaseInsensitiveOption));
    

    // Вспомогательная функция для замены символов в строке str по правилу rx,
    // на replacement. Стандартный подход str.replace(rx, replacement) сделает
    // не полную замену ("об-лачный" вместо "об-лач-ный").
    auto replaceAll = [](QString& str, const QRegularExpression& rx, const QString& replacement)
    {
        QString temp;
        do
        {
            temp = str;
            str.replace(rx, replacement);
        } while (temp != str);
    };

    // Расставить мягкие переносы.
    hyphenWord = word;
	QVector<QRegularExpression>::Iterator i = rules.begin();
    for (; i != rules.end(); ++i)
    {
        replaceAll(hyphenWord, *i, replaceOn);
    }
}
void ArtNetSubnetSender::sendUniverseUnicast(int universe, const QVector<uint8_t>& data, const QVector<QHostAddress>& addresses) {
    Q_ASSERT_X(universe <= 15, "ArtNetSubnetSender::sendUniverse", "Universe number too large");
    Q_ASSERT_X(universe >= 0, "ArtNetSubnetSender::sendUniverse", "Universe number too small");
    Q_ASSERT_X(data.size() == 512, "ArtNetSubnetSender::sendUniverse", "data has not length 512");

    QVector<uint8_t>& universePacket = m_preparedPackets[universe];

    // fill raw DMX data in prepared packet:
    std::copy(data.begin(), data.end(), universePacket.begin() + 18);
    // set sequence number:
    universePacket[12] = m_sequenceNumber;
    m_sequenceNumber = (m_sequenceNumber + 1) % 256;

    // send prepared packet with filled in data via UDP socket:
    const char* packet = reinterpret_cast<const char*>(universePacket.constData());

    for (const QHostAddress& address: addresses) {
        m_udpSocket.writeDatagram(packet, 18+512, address, ARTNET_PORT);
    }
}
void QRasterWindowSurface::beginPaint(const QRegion &rgn)
{
#if (defined(Q_WS_X11) && !defined(QT_NO_XRENDER)) || (defined(Q_WS_WIN) && !defined(Q_WS_WINCE))
    if (!qt_widget_private(window())->isOpaque && window()->testAttribute(Qt::WA_TranslucentBackground)) {
#if defined(Q_WS_WIN) && !defined(Q_WS_WINCE)
        if (d_ptr->image->image.format() != QImage::Format_ARGB32_Premultiplied)
            prepareBuffer(QImage::Format_ARGB32_Premultiplied, window());
#endif
        QPainter p(&d_ptr->image->image);
        p.setCompositionMode(QPainter::CompositionMode_Source);
        const QVector<QRect> rects = rgn.rects();
        const QColor blank = Qt::transparent;
        for (QVector<QRect>::const_iterator it = rects.begin(); it != rects.end(); ++it) {
            p.fillRect(*it, blank);
        }
    }
#else
    Q_UNUSED(rgn);
#endif
}
Example #19
0
/**
 * Returns a list of rectangles that cover all the used area of this layer.
 * The list is sorted by the top-left of each rectangle.
 *
 * This function is used to determine the chunks to write when saving a tile
 * layer.
 */
QVector<QRect> TileLayer::sortedChunksToWrite() const
{
    QVector<QRect> chunksToWrite;
    chunksToWrite.reserve(mChunks.size());

    QHashIterator<QPoint, Chunk> it(mChunks);
    while (it.hasNext()) {
        it.next();
        if (!it.value().isEmpty()) {
            const QPoint p = it.key();
            chunksToWrite.append(QRect(p.x() * CHUNK_SIZE,
                                       p.y() * CHUNK_SIZE,
                                       CHUNK_SIZE, CHUNK_SIZE));
        }
    }

    std::sort(chunksToWrite.begin(), chunksToWrite.end(), compareRectPos);

    return chunksToWrite;
}
Example #20
0
void RemoveDeleteChangesCommand::removeDeleteChanges()
{
    int numDeletedChars = 0;
    QVector<KChangeTrackerElement *> elementVector;
    KTextDocument(m_document).changeTracker()->getDeletedChanges(elementVector);
    qSort(elementVector.begin(), elementVector.end(), isPositionLessThan);

    foreach(KChangeTrackerElement *element, elementVector) {
        if (element->isValid() && element->getDeleteChangeMarker()) {
            QTextCursor caret(element->getDeleteChangeMarker()->document());
            QTextCharFormat f;
            int deletePosition = element->getDeleteChangeMarker()->position() + 1 - numDeletedChars;
            caret.setPosition(deletePosition);
            int deletedLength = KChangeTracker::fragmentLength(element->getDeleteData());
            caret.setPosition(deletePosition + deletedLength, QTextCursor::KeepAnchor);
            caret.removeSelectedText();
            numDeletedChars += KChangeTracker::fragmentLength(element->getDeleteData());
        }
    }
}
Example #21
0
QVector<UpdateInfo> UpdatesInfo::updatesInfo( int type,  int compatLevel ) const
{
    QVector<UpdateInfo> list;
    if ( compatLevel == -1 ) {
        if ( type == AllUpdate ) {
            return d->updateInfoList;
        }
        std::remove_copy_if( d->updateInfoList.begin(), d->updateInfoList.end(), std::back_inserter( list ), std::not1( TypeIs( type ) ) );
                }
                else {
        // first remove all wrong types
        std::remove_copy_if( d->updateInfoList.begin(), d->updateInfoList.end(), std::back_inserter( list ), std::not1( TypeIs( type ) ) );

        // the remove all wrong compat levels
        list.erase( 
            std::remove_if( list.begin(), list.end(), CompatLevelIsNot( compatLevel ) ), 
            list.end() );
    }
    return list;
}
Example #22
0
void Faceshift::updateFakeCoefficients(float leftBlink, float rightBlink, float browUp,
        float jawOpen, float mouth2, float mouth3, float mouth4, QVector<float>& coefficients) const {
    const int MMMM_BLENDSHAPE = 34;
    const int FUNNEL_BLENDSHAPE = 40;
    const int SMILE_LEFT_BLENDSHAPE = 28;
    const int SMILE_RIGHT_BLENDSHAPE = 29;
    const int MAX_FAKE_BLENDSHAPE = 40;  //  Largest modified blendshape from above and below

    coefficients.resize(max((int)coefficients.size(), MAX_FAKE_BLENDSHAPE + 1));
    qFill(coefficients.begin(), coefficients.end(), 0.0f);
    coefficients[_leftBlinkIndex] = leftBlink;
    coefficients[_rightBlinkIndex] = rightBlink;
    coefficients[_browUpCenterIndex] = browUp;
    coefficients[_browUpLeftIndex] = browUp;
    coefficients[_browUpRightIndex] = browUp;
    coefficients[_jawOpenIndex] = jawOpen;
    coefficients[SMILE_LEFT_BLENDSHAPE] = coefficients[SMILE_RIGHT_BLENDSHAPE] = mouth4;
    coefficients[MMMM_BLENDSHAPE] = mouth2;
    coefficients[FUNNEL_BLENDSHAPE] = mouth3;
}
QVector<int> QFilterData::_filterOrignalData(const QVector<int> &vectPressure) const
{
	QVector<int> vectRet;
	int yv[nPOLES] ={};
	QVector<int>::const_iterator iter = vectPressure.begin();
	for (;iter != vectPressure.end(); ++iter)
	{
		int nSum = 0.0f;
		for(int i = 1; i <nPOLES; ++i)
		{
			nSum += yv[nPOLES - i - 1];
			yv[nPOLES - i] = yv[nPOLES - i - 1];
		}
		yv[0] = *iter;
		nSum += yv[0];
		vectRet.append(nSum/12);
	}

	return vectRet;
}
Example #24
0
void QX11WindowSurface::beginPaint(const QRegion &rgn)
{
#ifndef QT_NO_XRENDER
    Q_ASSERT(!d_ptr->device.isNull());

    if (d_ptr->translucentBackground) {
        if (d_ptr->device.depth() != 32)
            static_cast<QX11PixmapData *>(d_ptr->device.data_ptr().data())->convertToARGB32();
        ::Picture src = X11->getSolidFill(d_ptr->device.x11Info().screen(), Qt::transparent);
        ::Picture dst = d_ptr->device.x11PictureHandle();
        const QVector<QRect> rects = rgn.rects();
        const int w = d_ptr->device.width();
        const int h = d_ptr->device.height();
        for (QVector<QRect>::const_iterator it = rects.begin(); it != rects.end(); ++it)
            XRenderComposite(X11->display, PictOpSrc, src, 0, dst,
                             0, 0, w, h, it->x(), it->y(),
                             it->width(), it->height());
    }
#endif
}
Example #25
0
double BeatUtils::calculateOffset(
    const QVector<double> beats1, const double bpm1,
    const QVector<double> beats2, const int SampleRate) {
    /*
     * Here we compare to beats vector and try to determine the best offset
     * based on the occurences, i.e. by assuming that the almost correct beats
     * are more than the "false" ones.
     */
    const double beatlength1 = (60.0 * SampleRate / bpm1);
    const double beatLength1Epsilon = beatlength1 * 0.02;

    int bestFreq = 1;
    double bestOffset = beats1.at(0) - beats2.at(0);

    // Sweep offset from [-beatlength1/2, beatlength1/2]
    double offset = floor(-beatlength1 / 2);
    while (offset < (beatlength1 / 2)) {
        int freq = 0;
        for (int i = 0; i < beats2.size(); i += 4) {
            double beats2_beat = beats2.at(i);
            QVector<double>::const_iterator it = qUpperBound(
                beats1.begin(), beats1.end(), beats2_beat);
            if (fabs(*it - beats2_beat - offset) <= beatLength1Epsilon) {
                freq++;
            }
        }
        if (freq > bestFreq) {
            bestFreq = freq;
            bestOffset = offset;
        }
        offset++;
    }

    if (sDebug) {
        qDebug() << "Best offset " << bestOffset << "guarantees that"
                << bestFreq << "over" << beats1.size()/4
                << "beats almost coincides.";
    }

    return floor(bestOffset + beatLength1Epsilon);
}
void SCsCodeErrorAnalyzer::showError(const QVector<SCsParserException> &exceptions) const
{

    if (mErrorTable == NULL)
        return;

	mErrorTable->clear();

	QVector<SCsParserException>::const_iterator it;
	for (it = exceptions.begin(); it != exceptions.end(); ++it)
	{
        QString description = getErrorDescription(*it);
        mErrorTable->addError(description, it->line(), it->positionInLine());
	}

	if (!exceptions.isEmpty())
		mErrorTable->show();
	else
		mErrorTable->hide();

}
Example #27
0
void Model::transform(QMatrix4x4 matrix)
{
    m_transform = matrix;
    if (m_vertices.empty())
        return;


    QVector<QVector3D> v;
#pragma omp parallel for
    v = m_vertices;
    auto it = v.end(), end = v.begin();
    while ( it != end ) {
//        qDebug() << "X: " << ((QVector3D*)it)->x();
        *it = matrix * *it;
        --it;
    }

    m_verticesNew = v;

    recomputeAll();
}
Example #28
0
SubstitutionCipher::SubstitutionCipher()
{
    QString original("abcdefghijklmnopqrstuvwxyz");
	
    QVector<int> mapList;
	
	for(int i = 0; i < original.length(); i++)
	{
		mapList.append(i);
	}
	
    // Assumes srand called at program init
    std::random_shuffle(mapList.begin(), mapList.end());
	
	for(int i = 0; i < original.length(); i++)
	{
        mapping.append(
                    QPair<QChar,QChar>(original[i], original[mapList[i]])
                    );
    }
}
Example #29
0
void Editor::slot_ObjectList_ItemChanged( QListWidgetItem* item )
{
	static QVector<char*> AllocatedStrs;
	const uint MAX_STR_LENGTH = 64;

	CGameObject* obj = CGame::GetObjByIndex(Instance->ui.widgetListObj->currentRow());

	for(auto itr = AllocatedStrs.begin(); itr != AllocatedStrs.end(); itr++)
	{
		if(*itr == obj->name)
		{
			strcpy((char*)obj->name, item->text().toAscii().data());
			return;
		}
	}

	char* str  = new char[MAX_STR_LENGTH];
	strcpy(str, item->text().toAscii().data());
	AllocatedStrs.push_back(str);
	obj->name = str;
}
Example #30
0
void MainWindow::update_audio_list(QVector<QString> item_values)
{
    common::log(QString("update_audio_list"));
    common::log(item_values.size());
    QVector<QString>::iterator it = item_values.begin();
    for (int i = 0; i < item_values.size(); ++i, ++it)
    {
        (*it).replace("\"", "");
        (*it).replace("/", "");
        (*it).replace("|", "");
        (*it).replace("<", "");
        (*it).replace(">", "");
        (*it).replace(":", "");
        (*it).replace("?", "");
        (*it).replace("*", "");
        (*it).replace("\\", "");
        QListWidgetItem* item = new QListWidgetItem(*it, music_list);
        item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
        item->setCheckState(Qt::Unchecked);
    }
}