LongInt Algorithm::Modular_exponentiation(LongInt a,LongInt m, LongInt r)
{
    //qDebug()<<"algorithm.cpp: Modular_exponentiation"<<a<<m<<r;
    if(r==0)
    {
        //qDebug()<<"algorithm.cpp: Modular_exponentiation :( 1 )";
        return LongInt(1);
    }
    QVector<LongInt> part;
    part<<1;
    LongInt a_k(1),k(1);

    while(1)
    {
        //qDebug()<<a_k<<a<<m;
        a_k=((a_k*a)%m);
        part<<a_k;
        if(part.last()==1)
        {
            part.removeLast();
            //qDebug()<<"algorithm.cpp: Modular_exponentiation :"<<part.value( ((r % LongInt(part.length()))).toInt());
            return part.value( ((r % LongInt(part.length()))).toInt());
        }
        k+=1;
        if(k>r)
        {
            //qDebug()<<"algorithm.cpp: Modular_exponentiation :"<<part.value( ((r % LongInt(part.length()))).toInt());
            return part.value( ((r % LongInt(part.length()))).toInt());
            return a_k;
        }
    }
}
Ejemplo n.º 2
0
void QCanvas::print_poly(QVector<QPointF>& poly)
{
    for(size_t i = 0; i<poly.size(); ++i)
    {
        Add_lines(poly.value(i),poly.value((i+1)%poly.size()),Qt::blue);
    }
}
Ejemplo n.º 3
0
int find_max(const QVector<int> &X) {
	int ret=X.value(0);
	for (int i=0; i<X.count(); i++) {
		ret=qMax(ret,X.value(i));
	}
	return ret;
}
Ejemplo n.º 4
0
void PrintDialogController::addDocToTable(QVector<SimpleDocumentInfo> vectorDoc)
{
    getView()->getTable()->setRowCount(vectorDoc.size());
    for(int i =0; i<vectorDoc.size();i++)
    {
    getView()->getTable()->setItem(i,0,new QTableWidgetItem(vectorDoc.value(i).getSymbol()));
    getView()->getTable()->item(i,0)->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled|Qt::ItemIsUserCheckable);
    getView()->getTable()->item(i,0)->setCheckState(Qt::Unchecked);
    getView()->getTable()->setItem(i,1,new QTableWidgetItem(QVariant(vectorDoc.value(i).getDocumentDate()).toString()));
    getView()->getTable()->item(i,1)->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
    }

}
static PyObject *convertFrom_QVector_1900(void *sipCppV, PyObject *)
{
   QVector<uint> *sipCpp = reinterpret_cast<QVector<uint> *>(sipCppV);

#line 159 "/Users/Kunwiji/Dropbox/Spectroscopy_paper/PyQt-mac-gpl-4.11.2/sip/QtCore/qvector.sip"
    // Create the list.
    PyObject *l;

    if ((l = PyList_New(sipCpp->size())) == NULL)
        return NULL;

    // Set the list elements.
    for (int i = 0; i < sipCpp->size(); ++i)
    {
        PyObject *pobj;

        // Convert to a Python long to make sure it doesn't get interpreted as
        // a signed value.
        if ((pobj = PyLong_FromUnsignedLong(sipCpp->value(i))) == NULL)
        {
            Py_DECREF(l);

            return NULL;
        }

        PyList_SET_ITEM(l, i, pobj);
    }

    return l;
#line 122 "/Users/Kunwiji/Dropbox/Spectroscopy_paper/PyQt-mac-gpl-4.11.2/QtCore/sipQtCoreQVector1900.cpp"
}
Ejemplo n.º 6
0
static QAccessibleInterface *relatedInterface(QAccessibleInterface *iface, QAccessible::RelationFlag flag)
{
    typedef QPair<QAccessibleInterface *, QAccessible::Relation> RelationPair;
    QVector<RelationPair> rels = iface->relations(flag);

    return rels.value(0).first;
}
Ejemplo n.º 7
0
void MapScene::addTrack(const QVector<QPointF>& points,
                        const QVector<float>& metaData, QVariant idTrack)
{
    if (points.isEmpty())
        return;

    QPainterPath route;
    TrackItem* track = new TrackItem;
    track->setId(idTrack);

    // Add each CoordinateItems which constitute the track
    for (int i(0); i < points.count(); i++)
    {
        qreal sx = points[i].x() * this->_amplificationRatio;
        qreal sy = points[i].y() * -this->_amplificationRatio;

        CoordinateItem* ci = new CoordinateItem;
        ci->setPos(sx, sy);
        ci->setAcceptHoverEvents(this->_trackAcceptHoverEvents);
        track->insertCoordinate(ci, metaData.value(i));

        if (i == 0)
            route.moveTo(sx, sy);
        else
            route.lineTo(sx, sy);
    }

    this->_tracks << track;
    this->addItem(track);
    QGraphicsItem* path = this->addPath(route, QPen(Qt::white));
    path->setParentItem(track);
    this->setSceneRect(this->itemsBoundingRect());
}
static PyObject *convertFrom_QVector_1900(void *sipCppV,PyObject *)
{
   QVector<uint> *sipCpp = reinterpret_cast<QVector<uint> *>(sipCppV);

#line 115 "/home/tsheasha/GUC/Bachelors/android-python27/python-build/PyQt-x11-gpl-4.8/sip/QtCore/qvector.sip"
    // Create the list.
    PyObject *l;

    if ((l = PyList_New(sipCpp->size())) == NULL)
        return NULL;

    // Set the list elements.
    for (int i = 0; i < sipCpp->size(); ++i)
    {
        PyObject *pobj;

        // Convert to a Python long to make sure it doesn't get interpreted as
        // a signed value.
        if ((pobj = PyLong_FromUnsignedLong(sipCpp->value(i))) == NULL)
        {
            Py_DECREF(l);

            return NULL;
        }

        PyList_SET_ITEM(l, i, pobj);
    }

    return l;
#line 127 "sipQtCoreQVector1900.cpp"
}
Ejemplo n.º 9
0
void Plotter::drawCurves(QPainter& painter)
{
    noOfCurves = curveDataMap.count();
    QRect rect = this->printRect();
    double x=0,y=0;
    double width = rect.width() - 1;
    double height = rect.height() - 1;
    double yCount = maxY - minY;
    if(antiAliasing)
        painter.setRenderHints(QPainter::Antialiasing);
    painter.translate(Margin + 1,rect.bottom()-1);
    for(int i=0; i < noOfCurves ; i++)
    {
        QPolygonF polyline;
        QVector<double>* dataPtr = curveDataMap[i] ;
        for(int j = 0 ; j <= noOfPoints ; j++)
        {
            x = (width * j)/noOfPoints;
            y = (height * dataPtr->value(j))/yCount;
            polyline << QPoint(x,-y);
            //qDebug() << y;
        }
        qDebug() << x <<rect.right();
        painter.setPen(colorMap.value(i));
        painter.drawPolyline(polyline);

    }
}
Ejemplo n.º 10
0
static PyObject *convertFrom_QVector_1800(void *sipCppV, PyObject *)
{
   QVector<int> *sipCpp = reinterpret_cast<QVector<int> *>(sipCppV);

#line 105 "/home/vikky/Desktop/DVCS/stuff/scrapy/soft/PyQt-x11-gpl-4.11.4/sip/QtCore/qvector.sip"
    // Create the list.
    PyObject *l;

    if ((l = PyList_New(sipCpp->size())) == NULL)
        return NULL;

    // Set the list elements.
    for (int i = 0; i < sipCpp->size(); ++i)
    {
        PyObject *pobj;

        // Convert to a Python long to make sure it doesn't get interpreted as
        // a signed value.
        if ((pobj = SIPLong_FromLong(sipCpp->value(i))) == NULL)
        {
            Py_DECREF(l);

            return NULL;
        }

        PyList_SET_ITEM(l, i, pobj);
    }

    return l;
#line 117 "/home/vikky/Desktop/DVCS/stuff/scrapy/soft/PyQt-x11-gpl-4.11.4/QtCore/sipQtCoreQVector1800.cpp"
}
Ejemplo n.º 11
0
static PyObject *convertFrom_QVector_2400(void *sipCppV, PyObject *)
{
   QVector<qreal> *sipCpp = reinterpret_cast<QVector<qreal> *>(sipCppV);

#line 203 "/home/vikky/Desktop/DVCS/stuff/scrapy/soft/PyQt-x11-gpl-4.11.4/sip/QtCore/qvector.sip"
    // Create the list.
    PyObject *l;

    if ((l = PyList_New(sipCpp->size())) == NULL)
        return NULL;

    // Set the list elements.
    for (int i = 0; i < sipCpp->size(); ++i)
    {
        PyObject *pobj;

        if ((pobj = PyFloat_FromDouble(sipCpp->value(i))) == NULL)
        {
            Py_DECREF(l);

            return NULL;
        }

        PyList_SET_ITEM(l, i, pobj);
    }

    return l;
#line 115 "/home/vikky/Desktop/DVCS/stuff/scrapy/soft/PyQt-x11-gpl-4.11.4/QtCore/sipQtCoreQVector2400.cpp"
}
Ejemplo n.º 12
0
static PyObject *convertFrom_QVector_1900(void *sipCppV, PyObject *)
{
   QVector<GLuint> *sipCpp = reinterpret_cast<QVector<GLuint> *>(sipCppV);

#line 29 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\sip/QtGui/qpygui_qvector.sip"
    PyObject *l = PyList_New(sipCpp->size());

    if (!l)
        return 0;

    for (int i = 0; i < sipCpp->size(); ++i)
    {
        // Convert to a Python long to make sure it doesn't get interpreted as
        // a signed value.
        PyObject *pobj = PyLong_FromUnsignedLong(sipCpp->value(i));

        if (!pobj)
        {
            Py_DECREF(l);

            return 0;
        }

        PyList_SET_ITEM(l, i, pobj);
    }

    return l;
#line 169 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\QtGui/sipQtGuiQVector1900.cpp"
}
Ejemplo n.º 13
0
void QCanvas::razor_CH(QVector<QCanvas::line_t> razor, QVector<QPointF> &poly, bool time_sleep)
{
    for(size_t i = 0; i<razor.size(); ++i)
    {
        QVector<QPointF> tmp;
        for(size_t j = 0; j< poly.size(); ++j)
        {
            QPointF S = poly.value(j);
            QPointF F = poly.value((j+1) % poly.size());
            size_t flag = Intersection(S,F,razor.value(i).S,razor.value(i).F);
            while(flag)
            switch (flag) {
            case 1:
            {
                flag = 0;
                continue;
            }
            case 2:
            {
                QPointF add = LinesCross(S,F,razor.value(i).S,razor.value(i).F);
                if (add == F)
                {
                    flag = 3;
                    continue;
                }
                tmp.push_back(add);
                tmp.push_back(F);
                flag = 0;
                continue;
            }
            case 3:
            {
                tmp.push_back(F);
                flag = 0;
                continue;
            }
            case 4:
            {
                QPointF add = LinesCross(S,F,razor.value(i).S,razor.value(i).F);
                if (add == F)
                {
                    flag = 3;
                    continue;
                }
                tmp.push_back(add);
                flag = 0;
                continue;
            }
            }

        }
        poly.swap(tmp);
    }
}
Ejemplo n.º 14
0
static QAccessibleInterface *relatedInterface(QAccessibleInterface *iface, QAccessible::RelationFlag flag)
{
    typedef QPair<QAccessibleInterface *, QAccessible::Relation> RelationPair;
    QVector<RelationPair> rels = iface->relations(flag);

    for (int i = 1; i < rels.count(); ++i)
        delete rels.at(i).first;

    return rels.value(0).first;
}
int QcepDataArraySpreadsheetModel::columnCount(const QModelIndex &parent) const
{
  QcepDataArrayPtr array(m_Array);

  if (array) {
    QVector<int> dims = array->dimensions();

    return dims.value(1);
  } else {
    return 0;
  }
}
Ejemplo n.º 16
0
void AccumulateEnergy::SetEnergyData(QVector<AccumulateEnergy::EnergyData> &data)
{

    startdate_ = data.value(0).date;
    days_ = data.size();
    datas_ = data;

    float accumulateenergy = 0;
    float advancemeters = 0;
    int tmaxeventnum = 0;

    for (int i = 0;i< data.size();i++)
    {
        if (tmaxeventnum < data.value(i).eventnum)
        {
            tmaxeventnum = data.value(i).eventnum;
        }

        if (advancemeters < data.value(i).advancemeter)
        {
            advancemeters = data.value(i).advancemeter;
        }
        accumulateenergy += data.value(i).energy;
        //advancemeters+= data.value(i).advancemeter;
    }

    maxaccumulateenergy_ = accumulateenergy;
    maxadvancemeter_ = advancemeters;
    maxeventnum_ = tmaxeventnum;

}
Ejemplo n.º 17
0
QImage ImageProcessor::equalizeHistogram(QImage input) {
    QImage returnMe(input.width(),input.height(),QImage::Format_ARGB32);
    QPainter painter(&returnMe);

    QVector<float> occ = ImageProcessor::findOccurrences(input);
    QVector<float> pdf;
    float currentpdf =0;
    for(int i=0;i<occ.count();i++) {
        currentpdf += occ.value(i);
        pdf.append(currentpdf);
    }

    for(int x=0;x<input.width();x++) {
        for(int y=0;y<input.height();y++) {
            int originalVal = qRed(input.pixel(x,y));
            float pdfVal = pdf.value(originalVal);
            int newVal = (int)(pdfVal * 255);
            painter.fillRect(x,y,1,1,QColor(newVal,newVal,newVal));
        }
    }
    return returnMe;
}
Ejemplo n.º 18
0
void TerminalImageFilterChain::setImage( const Character* const image , int lines , int columns, const QVector<LineProperty>& lineProperties )
{
//qDebug("%s %d", __FILE__, __LINE__);
  if ( empty() )
    return;
//qDebug("%s %d", __FILE__, __LINE__);

  // reset all filters and hotspots
  reset();
//qDebug("%s %d", __FILE__, __LINE__);

  PlainTextDecoder decoder;
  decoder.setTrailingWhitespace( false );

//qDebug("%s %d", __FILE__, __LINE__);
  // setup new shared buffers for the filters to process on
  QString* newBuffer = new QString();
  QList<int>* newLinePositions = new QList<int>();
  setBuffer( newBuffer , newLinePositions );

  // free the old buffers
  delete _buffer;
  delete _linePositions;

  _buffer = newBuffer;
  _linePositions = newLinePositions;

  QTextStream lineStream( _buffer );
  decoder.begin( &lineStream );

  for ( int i = 0 ; i < lines ; i++ )
  {
    _linePositions->append( _buffer->length() );
    decoder.decodeLine( image + i*columns, columns, LINE_DEFAULT );

    // pretend that each line ends with a newline character.
    // this prevents a link that occurs at the end of one line
    // being treated as part of a link that occurs at the start of the next line
    //
    // the downside is that links which are spread over more than one line are not
    // highlighted.
    //
    // TODO - Use the "line wrapped" attribute associated with lines in a
    // terminal image to avoid adding this imaginary character for wrapped
    // lines
    if ( !( lineProperties.value( i, LINE_DEFAULT ) & LINE_WRAPPED ) )
      lineStream << QChar( '\n' );
  }
  decoder.end();
//    qDebug("%s %d", __FILE__, __LINE__);
}
Ejemplo n.º 19
0
QVector<float> ImageProcessor::findOccurrences(QImage input, int offset) {
    QVector<float> returnMe;
    returnMe.fill(0,256);
    float single = 1.0 / (input.width() * input.height());

    for(int x=0;x<input.width();x++) {
        for(int y=0;y<input.height();y++) {
            int pixelIndex = qRed(input.pixel(x,y)) + offset;
            pixelIndex = qMax(pixelIndex,0);
            pixelIndex = qMin(pixelIndex,255);
            float newVal = returnMe.value(pixelIndex)+single;
            returnMe.replace(pixelIndex,newVal);
        }
    }

    return returnMe;
}
Ejemplo n.º 20
0
	int LJProfile::GetFreeGroupId () const
	{
		QVector<int> baseVector (30);
		int current = 0;
		std::generate (baseVector.begin (), baseVector.end (),
				[&current] () { return ++current; });

		QVector<int> existingIds;
		for (const auto& group : ProfileData_.FriendGroups_)
			existingIds.append (group.Id_);

		std::sort (existingIds.begin (), existingIds.end ());
		QVector<int> result;
		std::set_difference (baseVector.begin (), baseVector.end (),
				existingIds.begin (), existingIds.end (),
				std::back_inserter (result));

		return result.value (0, -1);
	}
Ejemplo n.º 21
0
int KexiComboBoxTableEdit::widthForValue(const QVariant &val, const QFontMetrics &fm)
{
    KexiDB::TableViewData *relData = column() ? column()->relatedData() : 0;
    if (lookupFieldSchema() || relData) {
        // in 'lookupFieldSchema' or  or 'related table data' model
        // we're assuming val is already the text, not the index
//! @todo ok?
        return qMax(KEXITV_MINIMUM_COLUMN_WIDTH, fm.width(val.toString()));
    }
    //use 'enum hints' model
    QVector<QString> hints = field()->enumHints();
    bool ok;
    int idx = val.toInt(&ok);
    if (!ok || idx < 0 || idx > int(hints.size() - 1))
        return KEXITV_MINIMUM_COLUMN_WIDTH;
    QString txt = hints.value(idx);
    if (txt.isEmpty())
        return KEXITV_MINIMUM_COLUMN_WIDTH;
    return fm.width(txt);
}
Ejemplo n.º 22
0
bool isValid(const QVector<bool>  &result)
{
    bool temp;
    int zeros = 0;
    int units = 0;

    for(int i = 0; i < result.size(); ++i) {
        temp = result.value(i);

        if(temp) {
            ++units;
        } else {
            ++zeros;
        }
    }

    if((zeros + 1 == units) || (zeros == units + 1)) {
        return true;
    } else {
        return false;
    }
}
Ejemplo n.º 23
0
Pattern * Pattern::adjacentPatternByOffset(int offset) const
{
	QVector<TrackContentObject *> tcos = m_instrumentTrack->getTCOs();
	int tcoNum = m_instrumentTrack->getTCONum(this);
	return dynamic_cast<Pattern*>(tcos.value(tcoNum + offset, NULL));
}
Ejemplo n.º 24
0
/**
 * @param theBandNumber the number of the band for which you want a color table
 * @param theList a pointer the object that will hold the color table
 * @return true of a color table was able to be read, false otherwise
 */
QList<QgsColorRampShader::ColorRampItem> QgsGdalProviderBase::colorTable( GDALDatasetH gdalDataset, int theBandNumber )const
{
  QgsDebugMsg( "entered." );
  QList<QgsColorRampShader::ColorRampItem> ct;

  //Invalid band number, segfault prevention
  if ( 0 >= theBandNumber )
  {
    QgsDebugMsg( "Invalid parameter" );
    return ct;
  }

  GDALRasterBandH myGdalBand = GDALGetRasterBand( gdalDataset, theBandNumber );
  GDALColorTableH myGdalColorTable = GDALGetRasterColorTable( myGdalBand );

  if ( myGdalColorTable )
  {
    QgsDebugMsg( "Color table found" );

    // load category labels
    char ** categoryNames = GDALGetRasterCategoryNames( myGdalBand );
    QVector<QString> labels;
    if ( categoryNames )
    {
      int i = 0;
      while ( categoryNames[i] )
      {
        labels.append( QString( categoryNames[i] ) );
        i++;
      }
    }

    int myEntryCount = GDALGetColorEntryCount( myGdalColorTable );
    GDALColorInterp myColorInterpretation =  GDALGetRasterColorInterpretation( myGdalBand );
    QgsDebugMsg( "Color Interpretation: " + QString::number(( int )myColorInterpretation ) );
    GDALPaletteInterp myPaletteInterpretation  = GDALGetPaletteInterpretation( myGdalColorTable );
    QgsDebugMsg( "Palette Interpretation: " + QString::number(( int )myPaletteInterpretation ) );

    const GDALColorEntry* myColorEntry = 0;
    for ( int myIterator = 0; myIterator < myEntryCount; myIterator++ )
    {
      myColorEntry = GDALGetColorEntry( myGdalColorTable, myIterator );

      if ( !myColorEntry )
      {
        continue;
      }
      else
      {
        QString label = labels.value( myIterator );
        if ( label.isEmpty() )
        {
          label = QString::number( myIterator );
        }
        //Branch on the color interpretation type
        if ( myColorInterpretation == GCI_GrayIndex )
        {
          QgsColorRampShader::ColorRampItem myColorRampItem;
          myColorRampItem.value = ( double )myIterator;
          myColorRampItem.label = label;
          myColorRampItem.color = QColor::fromRgb( myColorEntry->c1, myColorEntry->c1, myColorEntry->c1, myColorEntry->c4 );
          ct.append( myColorRampItem );
        }
        else if ( myColorInterpretation == GCI_PaletteIndex )
        {
          QgsColorRampShader::ColorRampItem myColorRampItem;
          myColorRampItem.value = ( double )myIterator;
          myColorRampItem.label = label;
          //Branch on palette interpretation
          if ( myPaletteInterpretation  == GPI_RGB )
          {
            myColorRampItem.color = QColor::fromRgb( myColorEntry->c1, myColorEntry->c2, myColorEntry->c3, myColorEntry->c4 );
          }
          else if ( myPaletteInterpretation  == GPI_CMYK )
          {
            myColorRampItem.color = QColor::fromCmyk( myColorEntry->c1, myColorEntry->c2, myColorEntry->c3, myColorEntry->c4 );
          }
          else if ( myPaletteInterpretation  == GPI_HLS )
          {
            myColorRampItem.color = QColor::fromHsv( myColorEntry->c1, myColorEntry->c3, myColorEntry->c2, myColorEntry->c4 );
          }
          else
          {
            myColorRampItem.color = QColor::fromRgb( myColorEntry->c1, myColorEntry->c1, myColorEntry->c1, myColorEntry->c4 );
          }
          ct.append( myColorRampItem );
        }
        else
        {
          QgsDebugMsg( "Color interpretation type not supported yet" );
          return ct;
        }
      }
    }
  }
  else
  {
    QgsDebugMsg( "No color table found for band " + QString::number( theBandNumber ) );
    return ct;
  }

  QgsDebugMsg( "Color table loaded successfully" );
  return ct;
}
Ejemplo n.º 25
0
void ExtEdit::createAppList()
{	
#ifdef Q_WS_X11
	QByteArray globalMimeTypesList = _globalAppListPath_c + "mimeinfo.cache";
	QByteArray localMimeTypesPath = qgetenv("XDG_DATA_HOME");
	
	if (localMimeTypesPath.isEmpty() == true)
	{
		localMimeTypesPath = qgetenv("HOME") + "/.local/share";
	}
	localMimeTypesPath += "/applications/";
	QByteArray localMimeTypesList = localMimeTypesPath + "mimeinfo.cache";
	
	QVector<QByteArray> pathList;
	pathList << _globalAppListPath_c << localMimeTypesPath;
	
	QVector<QByteArray> fileList;
	fileList << globalMimeTypesList << localMimeTypesList;
	
	QFile file;
	
	for (int f = 0; f < fileList.count(); ++f)
	{		
		file.setFileName(fileList.value(f));
		if (file.open(QIODevice::ReadOnly) == true)
		{
			QString inLine;
			QString mimetype;
			QStringList desktopFiles;
			
			QTextStream in(&file);
			while(in.atEnd() == false)
			{
				inLine = in.readLine();
				if (inLine.split("=").count() > 1)
				{
					mimetype = inLine.split("=").at(0);
					if (mimetype == "image/png")
					{
						desktopFiles = inLine.split("=").at(1).split(";");
						if (desktopFiles.count() != 0)
						{
							for (int i = 0; i < desktopFiles.count(); ++i)
							{
								if (desktopFiles.at(i).isEmpty() == false)
								{
									_appList.append(readDesktopFile(desktopFiles.at(i), pathList.at(f)));
								}
							}
						}
					}
				}
			}
		}
		file.close();
	}
#endif
#ifdef Q_WS_WIN
	// TODO make read windows registry for get apps for image editing
	
	// WARNING this in dirty hack - hardcoded mspaint app
	ExtApp_t app;
	app.exec = "mspaint";
	app.name = "Paint";
	
	_appList.append(app);
#endif
}
Ejemplo n.º 26
0
void SongTest::testSearch1()
{
    Echonest::Song::SearchParams params;
    params.append( Echonest::Song::SearchParamData( Echonest::Song::Artist, QLatin1String("Modest Mouse") ) );
    params.append( Echonest::Song::SearchParamData( Echonest::Song::Title, QLatin1String("Float On") ) );
    params.append( Echonest::Song::SearchParamData( Echonest::Song::Results, 2 ) );

    QNetworkReply* reply = Echonest::Song::search( params, Echonest::SongInformation( Echonest::SongInformation::ArtistHotttnesss  | Echonest::SongInformation::ArtistLocation | Echonest::SongInformation::ArtistFamiliarity ) );
    qDebug() << "Test search:" << reply->url().toString();
    QEventLoop loop;
    loop.connect( reply, SIGNAL(finished()), SLOT(quit()) );
    loop.exec();

    QVector< Echonest::Song > songs = Echonest::Song::parseSearch( reply );
    qDebug() << songs << songs.size();
    QVERIFY( !songs.isEmpty() );
    for(int i = 0; i < songs.size(); i++) {
        Echonest::Song song = songs.value(i);
        QLatin1String title = QLatin1String( "float on" );
        QCOMPARE( song.title().toLower(), title );
        QCOMPARE( song.artistName().toLower(), QLatin1String( "modest mouse" ) );
        QVERIFY( !song.artistLocation().location.isEmpty() );
        QCOMPARE( song.hotttnesss(), -1. );
        qDebug() << song.hotttnesss() << song.artistHotttnesss() << song.artistFamiliarity() << song.artistLocation();

        // now fetch some more info and make sure everything is still sane
        QNetworkReply* moreInfo = song.fetchInformation( Echonest::SongInformation( Echonest::SongInformation::Hotttnesss ) );
        QEventLoop loop;
        loop.connect( moreInfo, SIGNAL(finished()), SLOT(quit()) );
        loop.exec();
        song.parseInformation( moreInfo );

        QCOMPARE( song.title().toLower(), title );
        QCOMPARE( song.artistName().toLower(), QLatin1String( "modest mouse" ) );
        QVERIFY( !song.artistLocation().location.isEmpty() );
        // make sure we got the new info
        QVERIFY( song.hotttnesss() != -1 );

    }

    params.clear();
    params.append( Echonest::Song::SearchParamData( Echonest::Song::Artist, QLatin1String("The Tallest Man On Earth") ) );
    params.append( Echonest::Song::SearchParamData( Echonest::Song::Title, QLatin1String("The King of Spain") ) );
    params.append( Echonest::Song::SearchParamData( Echonest::Song::Results, 3 ) );

    Echonest::SongInformation info( Echonest::SongInformation( Echonest::SongInformation::AudioSummaryInformation | Echonest::SongInformation::Tracks | Echonest::SongInformation::Hotttnesss ) );
    info.setIdSpaces( QStringList() << QLatin1String( "musicbrainz" ) << QLatin1String( "playme" ) );
    reply = Echonest::Song::search( params, info);
    qDebug() << "QUERY:" << reply->url().toString();
    loop.connect( reply, SIGNAL(finished()), SLOT(quit()) );
    loop.exec();

    songs = Echonest::Song::parseSearch( reply );
    qDebug() << songs << songs.size();
    foreach( const Echonest::Song& song, songs ) {
//         qDebug() << "SONG  TRACKS:" << song.tracks();
        foreach( const Echonest::Track& track, song.tracks() ) {
//             qDebug() << track.catalog() << track.foreignId();
            QVERIFY( !track.catalog().isEmpty() );
            QVERIFY( !track.foreignId().isEmpty() );
        }
    }
Ejemplo n.º 27
0
bool ShortNavigation::createObstaclesTables()
{
    //    OGRLayer* layer;
    status = true;
    if ( !status==false ) {
        qDebug()<<"bool ShortNavigation::createObstaclesTables()";

        /// POINT_OFFSET is the area around the obstacle,
        /// so is it's value is 5, it will draw 10 m^2

        //float POINT_OFFSET = settingsManager->getPOffset();
        float POINT_OFFSET = 5; //test values, above comment from old code
        //float NOT_ALLOWED_DEPTH = settingsManager->getMinDepth();
        float NOT_ALLOWED_DEPTH = 2; //test values, above comment from old code

        /// signsound with depth from 0 to this value are
        /// taken in consideration for the obstacles layer

        //float SIGNSOUND_THRESHOLD = settingsManager->getSignsound();
        float SIGNSOUND_THRESHOLD = 1; //test values, above comment from old code



        // ##################################################
        // list of polygon layers considered obstacles
        QList<QString> polygon_layers;
        polygon_layers.append("generarea_r");
        // list of point layers to be considered as obstacles
        QList<QString> point_layers;
        point_layers.append("rock_p");
        point_layers.append("wreck_p");
        point_layers.append("navaid_p");
        point_layers.append("signsound_p");
        // line layers to be considered as obstacles
        QList<QString> line_layers;
        line_layers.append("depthcont_l");
        //####################################################

        for (int i = 0 ; i < this->chartObjects.size(); i++) {
            //        qDebug() << "chartObjects size" << chartObjects.size();

            if(this->chartObjects.at(i)->getTableName() == "generarea_r") {
                for (int j = 0 ; j < this->chartObjects.at(i)->getCoordinateGeometry().size();j++) {
                    this->polyObstacles.append(this->chartObjects.at(i)->getCoordinateGeometry().at(j));
                }
            }
            if(this->chartObjects.at(i)->getTableName() == "depthcont_l") {
                for (int j = 0 ; j < this->chartObjects.at(i)->getCoordinateGeometry().size();j++) { //TODO: parse line from polygon
                    //this->lineObstacles.append(this->chartObjects.at(i)->getCoordinateGeometry().at(j)); //Not used in Shortnavigation -> can be removed!
                }
            }
            if(this->chartObjects.at(i)->getTableName() == "rock_p") {
                for (int j = 0 ; j < this->chartObjects.at(i)->getCoordinateGeometry().size();j++) { //need to check how vectors are written from DB. is getfeaturecount = polygonvector.size ?
                    for(int k = 0; k < this->chartObjects.at(i)->getCoordinateGeometry().at(j).size();k++) {
                        this->pointObstacles.append(this->chartObjects.at(i)->getCoordinateGeometry().at(j).at(k));
                    }
                }
            }
            if(this->chartObjects.at(i)->getTableName() == "wreck_p") {
                for (int j = 0 ; j < this->chartObjects.at(i)->getCoordinateGeometry().size();j++) {
                    for(int k = 0; k < this->chartObjects.at(i)->getCoordinateGeometry().at(j).size();k++) {
                        this->pointObstacles.append(this->chartObjects.at(i)->getCoordinateGeometry().at(j).at(k));
                    }
                }
            }
            if(this->chartObjects.at(i)->getTableName() == "navaid_p") {
                for (int j = 0 ; j < this->chartObjects.at(i)->getCoordinateGeometry().size();j++) {
                    for(int k = 0; k < this->chartObjects.at(i)->getCoordinateGeometry().at(j).size();k++) {
                        this->pointObstacles.append(this->chartObjects.at(i)->getCoordinateGeometry().at(j).at(k));

                    }
                }
            }
            if(this->chartObjects.at(i)->getTableName() == "signsound_p") {

                QVector<QPolygonF> qpoint;
                QList<QPointF> listqpoint;
                OGRLayer* layer;
                OGRFeatureDefn *poFDefn;
                OGRFeature *poFeature;

                qpoint = this->chartObjects.at(i)->getCoordinateGeometry();
                for(int n = 0; n < qpoint.size(); n++){
                    listqpoint = qpoint.value(n).toList();
                }

                layer = this->chartObjects.at(i)->getFeatureData();
                layer->ResetReading();

                QString /*sql("SELECT * FROM *"); //FIX THIS! //*/ sql("SELECT * FROM ( SELECT DISTINCT Intersects( wkb_geometry, ");
                for(int m= 0; m < layer->GetFeatureCount();m++ ) {
                    poFDefn = layer->GetLayerDefn();
                    poFeature = layer->GetNextFeature();
                    for(int j = 0; j < poFDefn->GetFieldCount(); j++ ){
                        OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn( j );
                        QString str = poFieldDefn->GetNameRef();
                        if(str.contains("depth") == true) {
                            if (poFeature->GetFieldAsDouble(j) < SIGNSOUND_THRESHOLD) { //parse out depths above signsound threshold since they are not obstacles
                                pointObstacles.append(listqpoint.at(m));
                            }
                        }
                    }
                }


                //            // CREATE NEW TABLES
                sql = "CREATE TABLE obstacles_r (ogc_fid serial);";
                sql.append( "CREATE TABLE obstacles_l (ogc_fid serial);" );
                sql.append( "SELECT AddGeometryColumn ('obstacles_r','wkb_geometry',-1,'POLYGON',2);" );
                sql.append( "SELECT AddGeometryColumn ('obstacles_l','wkb_geometry',-1,'LINESTRING',2);" );
                sql.append( "ALTER TABLE obstacles_r ADD COLUMN source_table char(11);" );
                sql.append( "ALTER TABLE obstacles_l ADD COLUMN source_table char(11);" );
                res = PQexec(conn, sql.toAscii() );
                PQclear(res);

                // INSERT POLYGON LAYERS
                sql.clear();
                // DIRECT VERSION, WITHOUT ADDING THE OFFSET

                for ( int i = 0; i < polygon_layers.size(); i++ ) {
                    sql.append( "INSERT INTO obstacles_r( wkb_geometry, source_table) SELECT wkb_geometry, '");
                    sql.append( polygon_layers[i] );
                    sql.append( "' AS source_table FROM " );
                    sql.append( polygon_layers[i] );
                    sql.append( ";" );
                    if (debug) qDebug() << QString("UwShort: Adding obstacles of %1").arg( polygon_layers[i]);
                }
                // WARNING: very long string:
                res = PQexec(conn, sql.toAscii() );
                PQclear(res);

                qDebug() << "for in 1";            // INSERT POINT LAYERS WITH OFFSET
                for ( int i = 0; i < point_layers.size(); i++ ) {
                    bool signsound = ( point_layers[i] == "signsound_p" );
                    sql = "SELECT X(wkb_geometry),Y(wkb_geometry)";
                    if ( signsound)
                        sql.append( ",depth");
                    sql.append( " FROM ");
                    sql.append( point_layers[i] );
                    if ( signsound)
                        sql.append( QString(" WHERE depth < %1 ").arg( QString::number( SIGNSOUND_THRESHOLD)));
                    sql.append( ";");
                    res = PQexec(conn, sql.toAscii() );
                    if (debug) qDebug() << QString("UwShort: Adding obstacles of %1 (%2/%3): %4 obstacles").arg( point_layers[i], QString::number(i+1), QString::number(point_layers.size()), QString::number(PQntuples(res)));
                    sql.clear();

                    for ( int j = 0; j < PQntuples(res); j++ ) {
                        QPointF point( QString( PQgetvalue( res, j, 0)).toDouble(), QString( PQgetvalue( res, j, 1)).toDouble()); //forms a qpoint double precision
                        sql.append( "INSERT INTO obstacles_r ( wkb_geometry, source_table) VALUES ( ");
                        if ( point_layers[i] == "rock_p")
                            sql.append( ShortNavigation::buildWKTPolygon( point, POINT_OFFSET * POINT_OFFSET_FACTOR_ROCK ));
                        else if ( point_layers[i] == "wreck_p" )
                            sql.append( ShortNavigation::buildWKTPolygon( point, POINT_OFFSET * POINT_OFFSET_FACTOR_ROCK ));
                        else if ( signsound)
                            // for signsound POINT_OFFSET = POINT_OFFSET / ( depth of signsound / factor )
                            // the bigger the signsound is, the bigger the point offset gets
                            sql.append( ShortNavigation::buildWKTPolygon( point, POINT_OFFSET / ( QString( PQgetvalue( res, j, 2)).toDouble() / POINT_OFFSET_FACTOR_SIGNSOUND ) ));
                        else
                            sql.append( ShortNavigation::buildWKTPolygon( point, POINT_OFFSET));
                        sql.append( ", '");
                        sql.append( point_layers[i]);
                        sql.append( "'); ");

                    }
                    PQclear(res);

                    res = PQexec( conn, sql.toAscii());
                    PQclear(res);


                    //INSERT LINE LAYERS
                    sql.clear();
                    for ( int i = 0; i < line_layers.size(); i++ ) {
                        sql.append( "INSERT INTO obstacles_l( wkb_geometry, source_table) SELECT wkb_geometry, '");
                        sql.append( line_layers[i]);
                        sql.append( "' AS source_table FROM " );
                        sql.append( line_layers[i] );
                        if ( line_layers[i] == "depthcont_l" ) {
                            sql.append( " WHERE valdco<=" );
                            sql.append( QString::number( NOT_ALLOWED_DEPTH));
                        }
                        sql.append( ";");
                        if (debug) {
                            // WARNING: very long string:
                            qDebug() << QString("UwShort: Adding obstacles of ").append( line_layers[i]);
                        }
                        res = PQexec(conn, sql.toAscii() );
                        PQclear(res);
                    }


                    //  for loop for testing
                    //                for (int s=0; s<pointObstacles.size();s++){
                    //                    qDebug() << " index: " << s << "point x" << pointObstacles.at(s).x() << "y" << pointObstacles.at(s).y();
                    //                }

                    // tables are done
                    this->obstaclesTablesCreated = true;
                    qDebug("createObstaclesTables() returns = true");
                    return true;
                }

            }

        }
    }else {
        // tables are not done
        this->obstaclesTablesCreated = false;
        return false;

    }

}
Ejemplo n.º 28
0
void PhotoMosaic::run(QVector<QString> vec)
{

    QString subImageDir = vec.value(6);
    QString mainImagePath = vec.value(5);

    int mainWidth = vec.value(0).toInt();
    int mainHeight = vec.value(1).toInt();

    int subWidth = m_subImageWidth;
    int subHeight = m_subImageHeight;
    int numOfSubImages = vec.value(4).toInt();


    mainImagePath = resizeImage(mainImagePath,mainWidth,mainHeight);

    QDir directory(subImageDir);



    int precision = vec.value(7).toInt();

    FindAvgColorsInDirectory *avgDir = new FindAvgColorsInDirectory(directory, subWidth, subHeight, "jpeg",precision);
    FindAvgColorsInMain *avgMain = new FindAvgColorsInMain(mainImagePath,subWidth,subHeight,numOfSubImages,precision);

    //QFuture carries the result of a running thread.
    QFuture<void> avgDirThread =  QtConcurrent::run(avgDir,&FindAvgColorsInDirectory::calculateAllAverages);
    QFuture<void> avgMainThread = QtConcurrent::run(avgMain,&FindAvgColorsInMain::calculateAllAverages);


    qDebug() << "waiting to finish threads";
    //wait until both threads finished.
    avgMainThread.waitForFinished();
    avgDirThread.waitForFinished();


    RGB *dirStruct = avgDir->getAverageRGBArr();
    RGB *mainStruct = avgMain->getAverageRGBArr();


    //This is how it could be computed without using extra threads.
    //    FindAvgColorsInDirectory *avgDir = new FindAvgColorsInDirectory(directory, subWidth, subHeight, "jpeg",precision);
    //    avgDir->calculateAllAverages();
    //    RGB *dirStruct = avgDir->getAverageRGBArr();

    //    FindAvgColorsInMain *avgMain = new FindAvgColorsInMain(mainImagePath,subWidth,subHeight,numOfSubImages,precision);
    //    avgMain->calculateAllAverages();
    //    RGB *mainStruct = avgMain->getAverageRGBArr();


    QStringList *listRepeat = colorDifference(dirStruct, avgDir->getArraySize(), mainStruct, avgMain->getArraySize(),(precision * precision));


    QImage base;
    base.load(mainImagePath);
    QImage* img2 = new QImage(mainWidth,mainHeight, base.format());



    constructImage(listRepeat,img2, subImageDir);
    QString saveName = QString("%1(%2)%3")
            .arg("Photo Mosaic RGB ")
            .arg(QString::number(precision))
            .arg(".jpg");

    qDebug() << saveName;
    img2->save(saveName);

    //free unused memmory.
    delete listRepeat;
    delete img2;
    delete avgMain;
    delete avgDir;
}
Ejemplo n.º 29
0
void MVTemplatesView2PanelPrivate::setup_electrode_boxes(double W, double H)
{
    m_electrode_boxes.clear();

    int top_section_height = q->font().pixelSize();

    double W1 = W;
    double H1 = H - top_section_height - m_bottom_section_height;

    QList<QVector<double> > coords = m_electrode_geometry.coordinates;
    if (coords.isEmpty()) {
        int M = m_template.N1();
        int num_rows = qMax(1, (int)sqrt(M));
        int num_cols = ceil(M * 1.0 / num_rows);
        for (int m = 0; m < M; m++) {
            QVector<double> tmp;
            tmp << (m % num_cols) + 0.5 * ((m / num_cols) % 2) << m / num_cols;
            coords << tmp;
        }
    }
    if (coords.isEmpty())
        return;

    int D = coords[0].count();
    QVector<double> mins(D), maxs(D);
    for (int d = 0; d < D; d++) {
        mins[d] = maxs[d] = coords.value(0).value(d);
    }
    for (int m = 0; m < coords.count(); m++) {
        for (int d = 0; d < D; d++) {
            mins[d] = qMin(mins[d], coords[m][d]);
            maxs[d] = qMax(maxs[d], coords[m][d]);
        }
    }

    double spacing = estimate_spacing(coords);
    spacing = spacing * 0.75;

    //double W0 = maxs.value(0) - mins.value(0);
    //double H0 = maxs.value(1) - mins.value(1);
    double W0 = maxs.value(1) - mins.value(1);
    double H0 = maxs.value(0) - mins.value(0);

    double W0_padded = W0 + spacing * 4 / 3;
    double H0_padded = H0 + spacing * 4 / 3;

    double hscale_factor = 1;
    double vscale_factor = 1;

    if (W0_padded * H1 > W1 * H0_padded) {
        //limited by width
        if (W0_padded) {
            hscale_factor = W1 / W0_padded;
            vscale_factor = W1 / W0_padded;
        }
    }
    else {
        if (H0_padded)
            vscale_factor = H1 / H0_padded;
        if (W0_padded)
            hscale_factor = W1 / W0_padded;
    }

    double offset_x = (W1 - W0 * hscale_factor) / 2;
    double offset_y = top_section_height + (H1 - H0 * vscale_factor) / 2;
    for (int m = 0; m < coords.count(); m++) {
        QVector<double> c = coords[m];
        //double x0 = offset_x + (c.value(0) - mins.value(0)) * hscale_factor;
        //double y0 = offset_y + (c.value(1) - mins.value(1)) * vscale_factor;
        double x0 = offset_x + (c.value(1) - mins.value(1)) * hscale_factor;
        double y0 = offset_y + (c.value(0) - mins.value(0)) * vscale_factor;
        double radx = spacing * hscale_factor / 2;
        double rady = spacing * vscale_factor / 3.5;
        m_electrode_boxes << QRectF(x0 - radx, y0 - rady, radx * 2, rady * 2);
    }
}
Ejemplo n.º 30
0
void ArgumentsEditor::setupCall()
{
    m_model->clear();

    QStringList headers;
    headers.append(tr("Argument"));
    headers.append(tr("Value"));
    m_model->setColumnCount(2);
    m_model->setHorizontalHeaderLabels(headers);
    m_ui.argsTabWidget->removeTab(
        m_ui.argsTabWidget->indexOf(m_ui.shaderTab));

    if (!m_call)
        return;

    m_ui.callLabel->setText(m_call->name());
    QStandardItem *rootItem = m_model->invisibleRootItem();
    for (int i = 0; i < m_call->argNames().count(); ++i) {
        QString argName = m_call->argNames()[i];
        QVariant val = m_call->arguments()[i];
        QStandardItem *nameItem = new QStandardItem(argName);
        nameItem->setFlags(nameItem->flags() ^ Qt::ItemIsEditable);
        QList<QStandardItem*> topRow;
        topRow.append(nameItem);

        if (val.canConvert<ApiArray>()) {
            ApiArray array = val.value<ApiArray>();
            QVector<QVariant> vals = array.values();

            QVariant firstVal = vals.value(0);
            if (firstVal.userType() == QVariant::String) {
                m_ui.argsTabWidget->addTab(
                    m_ui.shaderTab, argName);
                setupShaderEditor(vals);
                delete nameItem;
                continue;
            } else if (isVariantEditable(firstVal)) {
                for (int i = 0; i < vals.count(); ++i) {
                    QList<QStandardItem*> row;

                    QStandardItem *idx = new QStandardItem();
                    idx->setFlags(idx->flags() ^ Qt::ItemIsEditable);
                    idx->setText(tr("%1)").arg(i));

                    QStandardItem *col = new QStandardItem();
                    col->setFlags(col->flags() | Qt::ItemIsEditable);
                    col->setData(vals[i], Qt::EditRole);
                    row.append(idx);
                    row.append(col);
                    nameItem->appendRow(row);
                }
            } else {
                qDebug()<<"\tUnsupported array = "<<firstVal;
                delete nameItem;
                continue;
            }
        } else  if (val.canConvert<ApiPointer>()) {
            ApiPointer ptr = val.value<ApiPointer>();
            QStandardItem *item = new QStandardItem();
            item->setFlags(item->flags() ^ Qt::ItemIsEditable);
            item->setText(ptr.toString());
            QIcon icon(":/resources/emblem-locked.png");
            item->setIcon(icon);
            item->setToolTip(tr("Argument is read-only"));
            topRow.append(item);
        } else if (val.canConvert<ApiEnum>()) {
            ApiEnum en = val.value<ApiEnum>();
            QStandardItem *item = new QStandardItem();
            item->setFlags(item->flags() ^ Qt::ItemIsEditable);
            item->setText(en.toString());
            QIcon icon(":/resources/emblem-locked.png");
            item->setIcon(icon);
            item->setToolTip(tr("Argument is read-only"));
            topRow.append(item);
        } else if (val.canConvert<ApiBitmask>()) {
            ApiBitmask mask = val.value<ApiBitmask>();
            QStandardItem *item = new QStandardItem();
            item->setFlags(item->flags() ^ Qt::ItemIsEditable);
            item->setText(mask.toString());
            QIcon icon(":/resources/emblem-locked.png");
            item->setIcon(icon);
            item->setToolTip(tr("Argument is read-only"));
            topRow.append(item);
        } else if (val.canConvert<ApiStruct>()) {
            ApiStruct str = val.value<ApiStruct>();
            QStandardItem *item = new QStandardItem();
            item->setFlags(item->flags() ^ Qt::ItemIsEditable);
            item->setText(str.toString());
            QIcon icon(":/resources/emblem-locked.png");
            item->setIcon(icon);
            item->setToolTip(tr("Argument is read-only"));
            topRow.append(item);
        } else if (val.userType() == QVariant::ByteArray) {
            QByteArray ba = val.value<QByteArray>();
            QStandardItem *item = new QStandardItem();
            item->setFlags(item->flags() ^ Qt::ItemIsEditable);
            item->setText(
                tr("<binary data, size = %1 bytes>").arg(ba.size()));
            QIcon icon(":/resources/emblem-locked.png");
            item->setIcon(icon);
            item->setToolTip(tr("Argument is read-only"));
            topRow.append(item);
        } else {
            QStandardItem *item
                = new QStandardItem();

            if (isVariantEditable(val)) {
                item->setFlags(item->flags() | Qt::ItemIsEditable);
            } else {
                QIcon icon(":/resources/emblem-locked.png");
                item->setIcon(icon);
                item->setFlags(item->flags() ^ Qt::ItemIsEditable);
                item->setToolTip(tr("Argument is read-only"));
            }
            item->setData(val, Qt::EditRole);
            topRow.append(item);
        }
        rootItem->appendRow(topRow);
    }
}