Example #1
0
// based on https://gist.github.com/andref/2838534.
bool JsonRpcServer::doCall(QObject* object,
                           const QMetaMethod& meta_method,
                           QVariantList& converted_args,
                           QVariant& return_value)
{
    QList<QGenericArgument> arguments;

    for (int i = 0; i < converted_args.size(); i++) {

        // Notice that we have to take a reference to the argument, else we'd be
        // pointing to a copy that will be destroyed when this loop exits.
        QVariant& argument = converted_args[i];

        // A const_cast is needed because calling data() would detach the
        // QVariant.
        QGenericArgument generic_argument(
            QMetaType::typeName(argument.userType()),
            const_cast<void*>(argument.constData())
        );

        arguments << generic_argument;
    }

    const char* return_type_name = meta_method.typeName();
    int return_type = QMetaType::type(return_type_name);
    if (return_type != QMetaType::Void) {
        return_value = QVariant(return_type, nullptr);
    }

    QGenericReturnArgument return_argument(
        return_type_name,
        const_cast<void*>(return_value.constData())
    );

    // perform the call
    bool ok = meta_method.invoke(
        object,
        Qt::DirectConnection,
        return_argument,
        arguments.value(0),
        arguments.value(1),
        arguments.value(2),
        arguments.value(3),
        arguments.value(4),
        arguments.value(5),
        arguments.value(6),
        arguments.value(7),
        arguments.value(8),
        arguments.value(9)
    );

    if (!ok) {
        // qDebug() << "calling" << meta_method.methodSignature() << "failed.";
        return false;
    }

    logInfo(logInvoke(meta_method, converted_args, return_value));

    return true;
}
TSession TSessionCookieStore::find(const QByteArray &id, const QDateTime &)
{
    TSession session;
    if (id.isEmpty())
        return session;

    QList<QByteArray> balst = id.split('_');
    if (balst.count() == 2 && !balst.value(0).isEmpty() && !balst.value(1).isEmpty()) {
        QByteArray ba = QByteArray::fromHex(balst.value(0));
        QByteArray digest = QCryptographicHash::hash(ba + Tf::app()->appSettings().value("Session.Secret").toByteArray(),
                                                     QCryptographicHash::Sha1);
        
        if (digest != QByteArray::fromHex(balst.value(1))) {
            tSystemWarn("Recieved a tampered cookie or that of other web application.");
            //throw SecurityException("Tampered with cookie", __FILE__, __LINE__);
            return session;
        }

        QDataStream ds(&ba, QIODevice::ReadOnly);
        ds >> *static_cast<QVariantHash *>(&session);
        
        if (ds.status() != QDataStream::Ok) {
            tSystemError("Unable to load a session from the cookie store.");
            session.clear();
        }
    }
Example #3
0
void KTracks::on_acSelect_triggered()
{
   QModelIndexList selection = ui->tvTracks->selectionModel()->selectedRows();
   QAbstractItemModel *model = ui->tvTracks->model();

   if (!selection.isEmpty()) {
       QList<QGeoPositionInfo> trackList;
       trackList.clear();
       trackList = sql.selTrack(model->data(model->index(selection.at(0).row(),0)).toInt());

       ui->cpPlot->clearGraphs();
       ui->cpPlot->addGraph();

       QGeoPositionInfo tp;
       QVector<double> x;
       QVector<double> y;
       int cnt = trackList.count();
       x.resize(cnt);
       y.resize(cnt);

       //options
       int pType;
       if (ui->miAltitude->isChecked()) {
           ui->cpPlot->yAxis->setLabel("Altitude [m]");
           pType = 1; }
       if (ui->miDistance->isChecked()) {
           ui->cpPlot->yAxis->setLabel("Distance [m]");
           pType = 2; }
       if (ui->miSpeed->isChecked()) {
           ui->cpPlot->yAxis->setLabel("Speed [m/s]");
           pType = 3; }
       ui->cpPlot->xAxis->setLabel("time [hh:mm:ss]");

       for (int i=0; i<cnt; i++) {
           tp = trackList.value(i);
           x[i] = tp.timestamp().toTime_t();
           switch (pType) {
             case 1: {
               y[i] = tp.coordinate().altitude();
               break; }
             case 2: {
               y[i] = tp.coordinate().distanceTo(trackList.value(0).coordinate());
               break; }
             case 3: {
               y[i] = tp.attribute(QGeoPositionInfo::GroundSpeed);
               break; }
           } //switch
       } //for to

       ui->cpPlot->graph(0)->setData(x,y);
       // set axes ranges, so we see all data:
       ui->cpPlot->xAxis->setRange(x[0],x[cnt-1]);
       qSort(y.begin(), y.end());
       ui->cpPlot->yAxis->setRange(y.first(),y.last());
       //repaint
       ui->cpPlot->replot();

   } //selection.isempty
}
Example #4
0
void THttpRequest::parseBody(const QByteArray &body, const THttpRequestHeader &header)
{
    switch (method()) {
    case Tf::Post: {
        QString ctype = QString::fromLatin1(header.contentType().trimmed());
        if (ctype.startsWith("multipart/form-data", Qt::CaseInsensitive)) {
            // multipart/form-data
            d->multipartFormData = TMultipartFormData(body, boundary());
            d->formItems = d->multipartFormData.formItems();

        } else if (ctype.startsWith("application/json", Qt::CaseInsensitive)) {
#if QT_VERSION >= 0x050000
            d->jsonData = QJsonDocument::fromJson(body);
#else
            tSystemWarn("unsupported content-type: %s", qPrintable(ctype));
#endif
        } else {
            // 'application/x-www-form-urlencoded'
            if (!body.isEmpty()) {
                QList<QByteArray> formdata = body.split('&');
                for (QListIterator<QByteArray> i(formdata); i.hasNext(); ) {
                    QList<QByteArray> nameval = i.next().split('=');
                    if (!nameval.value(0).isEmpty()) {
                        // URL decode
                        QString key = THttpUtility::fromUrlEncoding(nameval.value(0));
                        QString val = THttpUtility::fromUrlEncoding(nameval.value(1));
                        d->formItems.insertMulti(key, val);
                        tSystemDebug("POST Hash << %s : %s", qPrintable(key), qPrintable(val));
                    }
                }
            }
        }
        /* FALL THROUGH */ }

    case Tf::Get: {
        // query parameter
        QList<QByteArray> data = d->header.path().split('?');
        QString getdata = data.value(1);
        if (!getdata.isEmpty()) {
            QStringList pairs = getdata.split('&', QString::SkipEmptyParts);
            for (QStringListIterator i(pairs); i.hasNext(); ) {
                QStringList s = i.next().split('=');
                if (!s.value(0).isEmpty()) {
                    QString key = THttpUtility::fromUrlEncoding(s.value(0).toLatin1());
                    QString val = THttpUtility::fromUrlEncoding(s.value(1).toLatin1());
                    d->queryItems.insertMulti(key, val);
                    tSystemDebug("GET Hash << %s : %s", qPrintable(key), qPrintable(val));
                }
            }
        }
        break; }

    default:
        // do nothing
        break;
    }
}
void QgsRasterTransparencyWidget::pixelSelected( const QgsPointXY &canvasPoint )
{
  QgsRasterRenderer *renderer = mRasterLayer->renderer();
  if ( !renderer )
  {
    return;
  }

  //Get the pixel values and add a new entry to the transparency table
  if ( mMapCanvas && mPixelSelectorTool )
  {
    mMapCanvas->unsetMapTool( mPixelSelectorTool );

    const QgsMapSettings &ms = mMapCanvas->mapSettings();
    QgsPointXY myPoint = ms.mapToLayerCoordinates( mRasterLayer, canvasPoint );

    QgsRectangle myExtent = ms.mapToLayerCoordinates( mRasterLayer, mMapCanvas->extent() );
    double mapUnitsPerPixel = mMapCanvas->mapUnitsPerPixel();
    int myWidth = mMapCanvas->extent().width() / mapUnitsPerPixel;
    int myHeight = mMapCanvas->extent().height() / mapUnitsPerPixel;

    QMap<int, QVariant> myPixelMap = mRasterLayer->dataProvider()->identify( myPoint, QgsRaster::IdentifyFormatValue, myExtent, myWidth, myHeight ).results();

    QList<int> bands = renderer->usesBands();

    QList<double> values;
    for ( int i = 0; i < bands.size(); ++i )
    {
      int bandNo = bands.value( i );
      if ( myPixelMap.count( bandNo ) == 1 )
      {
        if ( myPixelMap.value( bandNo ).isNull() )
        {
          return; // Don't add nodata, transparent anyway
        }
        double value = myPixelMap.value( bandNo ).toDouble();
        QgsDebugMsg( QStringLiteral( "value = %1" ).arg( value, 0, 'g', 17 ) );
        values.append( value );
      }
    }
    if ( bands.size() == 1 )
    {
      // Set 'to'
      values.insert( 1, values.value( 0 ) );
    }
    tableTransparency->insertRow( tableTransparency->rowCount() );
    for ( int i = 0; i < values.size(); i++ )
    {
      setTransparencyCell( tableTransparency->rowCount() - 1, i, values.value( i ) );
    }
    setTransparencyCell( tableTransparency->rowCount() - 1, tableTransparency->columnCount() - 1, 100 );
  }

  tableTransparency->resizeColumnsToContents();
  tableTransparency->resizeRowsToContents();
}
Example #6
0
void MockQOfono::setModems(const QStringList &modems, const QList<bool> &present, const QList<bool> &ready)
{
    m_modems.clear();
    for (int i = 0; i < modems.length(); i++) {
        QList<bool> props;
        props << present.value(i, true) << ready.value(i, true);
        m_modems[modems[i]] = props;
    }
    Q_EMIT modemsChanged();
}
Example #7
0
QVariant Main::exec(const QString &command, const QList<QVariant> &arguments)
{
    if (command == "addMenu")
    {
      if (arguments.size() == 1)
      {
          QMenu* _menu = qobject_cast<QMenu*>(arguments.first().value<QObject *>());
          if(_menu)
          {
              ui->menubar->insertMenu(ui->menu_About->menuAction(), _menu);
          }
      }
    }
    else if (command == "addWidget")
    {
      if (arguments.size() == 2)
      {
          QWidget* _widget = qobject_cast<QWidget*>(arguments.value(0).value<QObject *>());
          QString _place = arguments.value(1).toString();
          if(_widget && !_place.isEmpty())
          {
              if(_place == "center")
              {
                ui->centralStack->addWidget(_widget);
                ui->centralStack->setCurrentWidget(_widget);
              }
          }
      }
    }
    else if (command == "resize")
    {
      qApp->processEvents();
      QSize _size = arguments.value(0).toSize();
      if(_size.isValid() && !_size.isEmpty())
      {
//        setMinimumSize(0, 0);
//        setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
//        resize(_size);
//        setMinimumSize(_size);
//        setMaximumSize(_size);
        setFixedSize(_size);
      }
    }
    else if(command == "show")
    {
        show();
    }
    else
    {
      return "command not found in ningeMain";
    }

    return "done";
}
void SSTimeSeriesView::setTimesLabels(const QList<int>& times, const QList<int>& labels)
{
    Mda TL0;
    TL0.allocate(2, times.count());
    for (int i = 0; i < times.count(); i++) {
        TL0.setValue(times.value(i), 0, i);
        TL0.setValue(labels.value(i), 1, i);
    }
    DiskReadMdaOld* TL = new DiskReadMdaOld;
    (*TL) = TL0;
    this->setLabels(TL, true);
}
/*!
Function for executing a slot that does not take parameters
*/
QString ObjectService::doCallMethod(TasCommand* command, QObject* target, QString& errorString)
{
    Q_ASSERT(command->name() == "CallMethod");

    QString methodName = command->parameter("method_name");
    TasLogger::logger()->debug("name: " + methodName);
    int methodId = target->metaObject()->indexOfMethod(
                QMetaObject::normalizedSignature(methodName.toLatin1()).constData());
    if (methodId == -1){
        errorString.append(methodName + " method not found on object. ");
        TasLogger::logger()->debug("...method not found on object");
    }
    else{
        QMetaMethod metaMethod = target->metaObject()->method(methodId);
        QVariantList args = parseArguments(command);
        QList<QGenericArgument> arguments;
        for (int i = 0; i < args.size(); i++) {
            QVariant& argument = args[i];
            QGenericArgument genericArgument(
                QMetaType::typeName(argument.userType()),
                const_cast<void*>(argument.constData()));
            arguments << genericArgument;
        }

        QVariant returnValue(QMetaType::type(metaMethod.typeName()),
                             static_cast<void*>(NULL));
        QGenericReturnArgument returnArgument(
            metaMethod.typeName(),
            const_cast<void*>(returnValue.constData()));

        if (!metaMethod.invoke(
                target,
                Qt::AutoConnection, // In case the object is in another thread.
                returnArgument,
                arguments.value(0),
                arguments.value(1),
                arguments.value(2),
                arguments.value(3),
                arguments.value(4),
                arguments.value(5),
                arguments.value(6),
                arguments.value(7),
                arguments.value(8),
                arguments.value(9))) {
            errorString.append(methodName + " method invocation failed! ");
        } else {
            return returnValue.toString();
        }
    }
    return QString("");
}
Example #10
0
int main(int argc, char *argv[])
{
   QCoreApplication app(argc, argv);
   QCoreApplication::setApplicationName("Find_books");
   QCoreApplication::setApplicationVersion("1.0");

   QCommandLineParser parser;
   parser.addHelpOption();
   parser.addVersionOption();
   parser.setApplicationDescription(QCoreApplication::translate("main","Find books from Gornica.ru."));


   parser.addPositionalArgument("s_file", QCoreApplication::translate("main", "Source file from read."));
   parser.addPositionalArgument("t_delay", QCoreApplication::translate("main", "Delay time."));

   parser.process(app);

   QList<QString> args = parser.positionalArguments();

   d_time=0;


#ifdef Q_OS_WIN32
   QTextCodec::setCodecForLocale(QTextCodec::codecForName("IBM 866"));
#endif

#ifdef Q_OS_LINUX
   QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
#endif
   //QTextStream Qcout(stdout);

   downloader = new Downloader(); // Инициализируем Downloader

   if (((args.size() < 1))) {
      printf("%s\n", qPrintable(QCoreApplication::translate("main", "Error: Must specify one filename argument.")));
      parser.showHelp(1);
   }
   else
   {

      m_File.append(args.value(0));
      d_time = args.value(1,"8000").toInt();
      m_CreateLists(m_File);
   }

   qDebug()  <<m_File;

   m_ReadF();
   app.exit();
}
Example #11
0
void qtDLGDisassembler::OnF2BreakPointPlace()
{
	QList<QTableWidgetItem *> currentSelectedItems = tblDisAs->selectedItems();
	if(currentSelectedItems.count() <= 0) return;

	quint64 dwSelectedVA = currentSelectedItems.value(0)->text().toULongLong(0,16);
	if(coreDebugger->AddBreakpointToList(NULL,DR_EXECUTE,-1,dwSelectedVA,NULL,true))
		currentSelectedItems.value(0)->setForeground(QColor(qtNanomiteDisAsColor->colorBP));
	else
	{// exists
		coreDebugger->RemoveBPFromList(dwSelectedVA,NULL);
		currentSelectedItems.value(0)->setForeground(QColor("Black"));
	}	
	return;
}
Example #12
0
void Test_ormtool::cutModelInfo()
{
    Parser parser;
    QString str = "abcORMObject<Class1>abcORMObject<Class2>gfi";
    QList<QString> list = parser.cutModelInfo(str);
    QCOMPARE(list.value(0), QString("ORMObject<Class1>abc"));
    QCOMPARE(list.value(1), QString("ORMObject<Class2>gfi"));
    str = "ORMObject<Class1>abcORMObject<Class2>";
    list = parser.cutModelInfo(str);
    QCOMPARE(list.value(0), QString("ORMObject<Class1>abc"));
    QCOMPARE(list.value(1), QString("ORMObject<Class2>"));
    str = "abcgfi";
    list = parser.cutModelInfo(str);
    QCOMPARE(list.isEmpty(), true);
}
Example #13
0
void smart_plot::zoomInButtonPressed()
{
    QList<QCPAxis*> axes = activePlot()->axisRect()->axes();

    int axisIndex = 0;
    while(axisIndex < axes.size())
    {
        if ( (activePlot()->selectedAxes().size() == 0) || axisHandler.isAxisSelected( axes.value(axisIndex) ) )
        {
            axes.value(axisIndex)->scaleRange(.5,axes.value(axisIndex)->range().center());
        }
        axisIndex++;
    }
    activePlot()->replot();
}
Example #14
0
QVariant QXmppInvokable::dispatch( const QByteArray & method, const QList< QVariant > & args )
{
    buildMethodHash();

    if( !m_methodHash.contains(method))
        return QVariant();

    int idx = m_methodHash[method];
    if( paramTypes( args) != metaObject()->method(idx).parameterTypes ())
        return QVariant();

    const char *typeName = metaObject()->method(idx).typeName();
    int resultType = QMetaType::type(typeName);
    void *result = QMetaType::construct(resultType, 0);

    QGenericReturnArgument ret( typeName, result );
    QList<QGenericArgument> genericArgs;
    QList<QVariant>::ConstIterator iter = args.begin();
    while( iter != args.end())
    {
        const void *data = iter->data();
        const char *name = iter->typeName();
        genericArgs << QGenericArgument(name,data);
        ++iter;
    }

    if( QMetaObject::invokeMethod ( this, method.constData(), ret,
                                    genericArgs.value(0, QGenericArgument() ),
                                    genericArgs.value(1, QGenericArgument() ),
                                    genericArgs.value(2, QGenericArgument() ),
                                    genericArgs.value(3, QGenericArgument() ),
                                    genericArgs.value(4, QGenericArgument() ),
                                    genericArgs.value(5, QGenericArgument() ),
                                    genericArgs.value(6, QGenericArgument() ),
                                    genericArgs.value(7, QGenericArgument() ),
                                    genericArgs.value(8, QGenericArgument() ),
                                    genericArgs.value(9, QGenericArgument() )) )
    {
        QVariant returnValue( resultType, result);
        QMetaType::destroy(resultType, result);
        return returnValue;
    }
    else
    {
        qDebug("No such method '%s'", method.constData() );
        return QVariant();
    }
}
Example #15
0
void QSplitterPrivate::setSizes_helper(const QList<int> &sizes, bool clampNegativeSize)
{
    int j = 0;

    for (int i = 0; i < list.size(); ++i) {
        QSplitterLayoutStruct *s = list.at(i);

        s->collapsed = false;
        s->sizer = sizes.value(j++);
        if (clampNegativeSize && s->sizer < 0)
            s->sizer = 0;
        int smartMinSize = pick(qSmartMinSize(s->widget));

        // Make sure that we reset the collapsed state.
        if (s->sizer == 0) {
            if (collapsible(s) && smartMinSize > 0) {
                s->collapsed = true;
            } else {
                s->sizer = smartMinSize;
            }
        } else {
            if (s->sizer < smartMinSize)
                s->sizer = smartMinSize;
        }
    }
    doResize();
}
Example #16
0
void TablePageManager::preparePage(int page)
{
    // The first page is the master page, which always exists.
    if (page == 1) {
        return;
    }
    KoTextShapeData* const data = static_cast<KoTextShapeData*>(d->master->KoShape::parent()->userData());
    if (!data) {
        // not embedded in a text shape
        return;
    }
    Q_CHECK_PTR(data);
    QTextDocument* const document = data->document();
    Q_CHECK_PTR(document);
    KoTextDocumentLayout* const layout = qobject_cast<KoTextDocumentLayout*>(document->documentLayout());
    Q_CHECK_PTR(layout);
    const QList<KoShape*> textShapes = layout->shapes();
    const int masterIndex = textShapes.indexOf(d->master);
    if (masterIndex < 0)
        return;  // huh?
    KoShapeContainer* const textShape = dynamic_cast<KoShapeContainer*>(textShapes.value(masterIndex + page - 1));
    if (textShape) {
        TableShape* const shape = new TableShape(d->master->columns(), d->master->rows());
        const TableShape* predecessor = d->pages[page - 1];
        shape->setPosition(predecessor->position() + QPointF(0.0, predecessor->size().height()));
        d->pages.append(shape);
        textShape->addShape(shape);
    }
}
Example #17
0
	Comparison Context::interrogate(Meme* memeKey, Equivalence eqvEquivalence, Meme* memeValue)
	{
		// Create the comparison structure
		Comparison instComparison(Equivalence::Unknown, false);
		// Check for associations
		if (this->mAssociations.isEmpty() || !this->mAssociations.contains(memeKey)) {
			// Reset the structure
			instComparison.equivalence = Equivalence::Unknown;
			instComparison.matched     = false;
		} else if (this->mAssociations.value(memeKey).contains(QPair<Equivalence, Meme*>(eqvEquivalence, memeValue))) {
			// Reset the structure
			instComparison.equivalence = eqvEquivalence;
			instComparison.matched     = true;
		} else {
			// Localize the pair
			QList<QPair<Equivalence, Meme*>> qlRelations = this->mAssociations.value(memeKey);
			// Iterate over the pairs
			for (int intPair = 0; intPair < qlRelations.size(); ++intPair) {
				// Create our recursive comparison
				Comparison instRecursiveComparison = this->interrogate(qlRelations.value(intPair).second, qlRelations.value(intPair).first, memeValue);
				// Interrogate the pair
				if (instRecursiveComparison.getMatched()) {
					// We're done
					return instRecursiveComparison;
				}
			}
		}
		// We're done
		return instComparison;
	}
Example #18
0
	void EntryBase::SetDiscoIdentities (const QString& variant, const QList<QXmppDiscoveryIq::Identity>& ids)
	{
		Variant2Identities_ [variant] = ids;

		const QString& name = ids.value (0).name ();
		const QString& type = ids.value (0).type ();
		if (name.contains ("Kopete"))
		{
			Variant2ClientInfo_ [variant] ["client_type"] = "kopete";
			Variant2ClientInfo_ [variant] ["client_name"] = "Kopete";
			Variant2ClientInfo_ [variant] ["raw_client_name"] = "kopete";
			emit statusChanged (GetStatus (variant), variant);
		}
		else if (name.contains ("emacs", Qt::CaseInsensitive) ||
				name.contains ("jabber.el", Qt::CaseInsensitive))
		{
			Variant2ClientInfo_ [variant] ["client_type"] = "jabber.el";
			Variant2ClientInfo_ [variant] ["client_name"] = "Emacs Jabber.El";
			Variant2ClientInfo_ [variant] ["raw_client_name"] = "jabber.el";
			emit statusChanged (GetStatus (variant), variant);
		}
		else if (type == "mrim")
		{
			Variant2ClientInfo_ [variant] ["client_type"] = "mailruagent";
			Variant2ClientInfo_ [variant] ["client_name"] = "Mail.Ru Agent Gateway";
			Variant2ClientInfo_ [variant] ["raw_client_name"] = "mailruagent";
			emit statusChanged (GetStatus (variant), variant);
		}
	}
Example #19
0
void EquipCard::use(Room *room, ServerPlayer *source, const QList<ServerPlayer *> &targets) const{
    const EquipCard *equipped = NULL;
    ServerPlayer *target = targets.value(0, source);
    
    switch(location()){
    case WeaponLocation: equipped = target->getWeapon(); break;
    case ArmorLocation: equipped = target->getArmor(); break;
    case DefensiveHorseLocation: equipped = target->getDefensiveHorse(); break;
    case OffensiveHorseLocation: equipped = target->getOffensiveHorse(); break;
    }

    if(equipped)
        room->throwCard(equipped, source);
    int tmpId = -1;
    if(getId() > -1)
        tmpId = getId();
    else if(!getSubcards().empty())
       tmpId = this->getSubcards().first();
    if(this->objectName() == "gale-shell" || room->getCardOwner(tmpId)->objectName() == target->objectName()){
        LogMessage log;
        log.from = target;
        log.type = "$Install";
        log.card_str = QString::number(tmpId);
        room->sendLog(log);
        room->moveCardTo(this, target, Player::Equip, true);
    }
}
bool
CloudDBChartClient::getChartByID(qint64 id, ChartAPIv1 *chart) {

    // read from Cache first
    if (readChartCache(id, chart)) return CloudDBCommon::APIresponseOk;

    // now from GAE
    QNetworkRequest request;
    CloudDBCommon::prepareRequest(request, g_chart_url_base+QString::number(id, 10));
    g_reply = g_nam->get(request);

    // wait for reply (synchronously) and process error codes as necessary
    if (!CloudDBCommon::replyReceivedAndOk(g_reply)) return false;

    // call successfull
    QByteArray result = g_reply->readAll();
    QList<ChartAPIv1>* charts = new QList<ChartAPIv1>;
    unmarshallAPIv1(result, charts);
    if (charts->size() > 0) {
        *chart = charts->value(0);
        writeChartCache(chart);
        charts->clear();
        delete charts;
        return true;
    }
    delete charts;
    return false;
}
Example #21
0
Note* Score::upAlt(Element* element)
      {
      Element* re = 0;
      if (element->type() == Element::REST) {
            if (_is.track() <= 0)
                  return 0;
            _is.setTrack(_is.track() - 1);
            re = searchNote(static_cast<Rest*>(element)->tick(), _is.track());
            }
      else if (element->type() == Element::NOTE) {
            // find segment
            Chord* chord     = static_cast<Note*>(element)->chord();
            Segment* segment = chord->segment();

            // collect all notes for this segment in noteList:
            QList<Note*> rnl;
            int tracks = nstaves() * VOICES;
            for (int track = 0; track < tracks; ++track) {
                  Element* el = segment->element(track);
                  if (!el || el->type() != Element::CHORD)
                        continue;
                  rnl.append(static_cast<Chord*>(el)->notes());
                  qSort(rnl.begin(), rnl.end(), noteLessThan);
                  int idx = rnl.indexOf(static_cast<Note*>(element));
                  if (idx < rnl.size()-1)
                        ++idx;
                  re = rnl.value(idx);
                  }
            }
      if (re == 0)
            return 0;
      if (re->type() == Element::CHORD)
            re = ((Chord*)re)->notes().front();
      return (Note*)re;
      }
static PyObject *convertFrom_QList_1800(void *sipCppV, PyObject *)
{
   QList<int> *sipCpp = reinterpret_cast<QList<int> *>(sipCppV);

#line 632 "/Users/Kunwiji/Dropbox/Spectroscopy_paper/PyQt-mac-gpl-4.11.2/sip/QtCore/qlist.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 = SIPLong_FromLong(sipCpp->value(i))) == NULL)
        {
            Py_DECREF(l);

            return NULL;
        }

        PyList_SET_ITEM(l, i, pobj);
    }

    return l;
#line 139 "/Users/Kunwiji/Dropbox/Spectroscopy_paper/PyQt-mac-gpl-4.11.2/QtCore/sipQtCoreQList1800.cpp"
}
Example #23
0
int Ax12MovementEditor::insertPosition(const QList<float> &positions, float maxSpeed, float torque, float loadLimit, int position)
{
	ui->movementTree->blockSignals(true);
	int row = position;
	ui->movementTree->insertRow(row);

	for(int i = 0; i < ui->movementTree->columnCount() - 3; ++i)
	{
		QTableWidgetItem* item = new QTableWidgetItem(QString::number(positions.value(i, -1.)));
		ui->movementTree->setItem(row, i, item);
	}

	QTableWidgetItem* speedItem = new QTableWidgetItem(QString::number(maxSpeed));
	ui->movementTree->setItem(row, ui->movementTree->columnCount() - 3, speedItem);

	QTableWidgetItem* torqueItem = new QTableWidgetItem(QString::number(torque));
	ui->movementTree->setItem(row, ui->movementTree->columnCount() - 2, torqueItem);

	QTableWidgetItem* loadItem = new QTableWidgetItem(QString::number(loadLimit));
	ui->movementTree->setItem(row, ui->movementTree->columnCount() - 1, loadItem);

	ui->movementTree->blockSignals(false);

	return row;
}
Example #24
0
void MyBaseListWidget::chargeListImageInsequence(Sequence sq, bool sorted, int nb_image_charge){

    this->clear();
    QList<ImageInSequence> listImg = sq.listImageInSequence;

       if(sorted){
           qSort(listImg.begin(), listImg.end(), ImageInSequence::lessThan);
        }else{
            QList<ImageInSequence> randlistImg;
           while(listImg.count() > 0){
                int nb = listImg.count();
               int rand = Util::random(0,nb);

                randlistImg << listImg.value(rand);
                listImg.removeAt(rand);
            }
            listImg = randlistImg;
        }
    int i = 0;
    while(i < listImg.count() && i < nb_image_charge){
        ImageInSequence imgSeq = listImg.at(i);
        this->addImage(imgSeq.img.name,Util::getIcon(imgSeq.img.image_file, sq.name));
        ++i;
    }
}
Example #25
0
void qtDLGPEEditor::InsertImports()
{
	QList<APIData> imports = m_pEManager->getImports(m_currentFile);
	if(imports.size() <= 0) return;

	QTreeWidgetItem *topElement,
					*moduleElement;
	QString lastTopElement;
	quint64	dwOffset = NULL;

	topElement = new QTreeWidgetItem();
	topElement->setText(0,"Imports");
	treePE->addTopLevelItem(topElement);

	for(int importCount = 0; importCount < imports.size(); importCount++)
	{
		QStringList currentElement = imports.value(importCount).APIName.split("::");

		if(currentElement[0].compare(lastTopElement) != NULL)
		{	
			moduleElement = new QTreeWidgetItem(topElement);
			moduleElement->setText(0,currentElement[0]);  
			lastTopElement = currentElement[0];
			dwOffset = clsHelperClass::CalcOffsetForModule((PTCHAR)currentElement[0].toLower().toStdWString().c_str(),NULL,m_processID);
		}
		
		QTreeWidgetItem* childElement = new QTreeWidgetItem(moduleElement);
		childElement->setText(0,currentElement[1]);
		if(dwOffset == 0)
			childElement->setText(1,QString("%1").arg(0,16,16,QChar('0')));
		else
			childElement->setText(1,QString("%1").arg(clsHelperClass::RemoteGetProcAddr(currentElement[1],dwOffset,m_processID),16,16,QChar('0')));
	}
}
Example #26
0
/*!
    This slot is called when the engine require a context sensitive menu to be displayed.

    The \a menu passed as a parameter is the menu to be displayed. It is populated with the
    actions possible for its current position. The menu is empty if there is no action for the position.
*/
void QGraphicsWKView::showContextMenu(QSharedPointer<QMenu> menu)
{
    // Remove the active menu in case this function is called twice.
    if (d->activeMenu)
        d->activeMenu->hide();

    if (menu->isEmpty())
        return;

    d->activeMenu = menu;

    QWidget* view = 0;
    if (QGraphicsScene* myScene = scene()) {
        const QList<QGraphicsView*> views = myScene->views();
        for (unsigned i = 0; i < views.size(); ++i) {
            if (views.at(i) == QApplication::focusWidget()) {
                view = views.at(i);
                break;
            }
        }
        if (!view)
            view = views.value(0, 0);
    }
    if (view)
        menu->setParent(view, menu->windowFlags());
    menu->exec(view->mapToGlobal(menu->pos()));
    if (d->activeMenu == menu)
        d->activeMenu.clear();
}
Example #27
0
void NutshSqlSaver::inserer(QList<NutshMetaData> meta, const QString& listName) {
    //insertion de multiple metadonnees
    for(unsigned int i = 0;i<static_cast<unsigned int>(meta.count());i++) {

        this->inserer(meta.value(i), listName);
    }
}
	void AccountConfigDialog::resetInPort ()
	{
		const QList<int> values { 465, 993, 143 };

		const int pos = Ui_.InSecurityType_->currentIndex ();
		Ui_.InPort_->setValue (values.value (pos));
	}
Example #29
0
void Ax12MovementEditor::refreshMovementTableIds()
{
	QList<int> ids = _manager.getGroupIds(_currentGroup);

	ui->movementTree->clear();
    ui->movementTree->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
	ui->movementTree->setColumnCount(ids.count() + 3);
	for(int i = 0; i < ids.count(); ++i)
	{
		delete ui->movementTree->itemDelegateForColumn(i);
		ui->movementTree->setItemDelegateForColumn(i, new DoubleSpinBoxDelegate(-1, 300, this));
	}

	delete ui->movementTree->itemDelegateForColumn(ui->movementTree->columnCount() - 1);
	ui->movementTree->setItemDelegateForColumn(ui->movementTree->columnCount() - 2, new DoubleSpinBoxDelegate(0, 100, this));

	delete ui->movementTree->itemDelegateForColumn(ui->movementTree->columnCount() - 2);
	ui->movementTree->setItemDelegateForColumn(ui->movementTree->columnCount() - 1, new DoubleSpinBoxDelegate(0, 100, this));

	delete ui->movementTree->itemDelegateForColumn(ui->movementTree->columnCount() - 3);
	ui->movementTree->setItemDelegateForColumn(ui->movementTree->columnCount() - 2, new DoubleSpinBoxDelegate(0, 114, this));



	QStringList headers;
	for(int i = 0; i < ids.count(); ++i)
		headers << QString::number(ids.value(i));
	headers << "Max Speed" << "Torque" << "Load Limit";
	ui->movementTree->setHorizontalHeaderLabels(headers);

	if (ui->movementsTapWidget->getCurrentIndex() > 0)
		ui->movementTree->setRowCount(1);
}
Example #30
0
void QFDlgCSVParameters::reloadCSV()
{
    checkValues(false);
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    tabmodel->setReadonly(false);
    tabmodel->clear();
    bool ex=false;
    if ((ex=QFile::exists(filename))) {
        tabmodel->readCSV(filename, get_column_separator(), get_decimal_separator(), get_header_start(), get_comment_start());
    }
    ui->tableView->setVisible(ex);
    ui->lstColumns->setModel(NULL);
    QList<int> oldidx;
    for (int i=0; i<colCmb.size(); i++) {
        oldidx<<colCmb[i]->currentIndex();
        colCmb[i]->setModel(NULL);
    }
    colslistCheckable.setEditable(true);
    colslistCheckable.clear();
    colslist.setEditable(true);
    colslist.clear();
    for (int i=0; i<tabmodel->columnCount(); i++) {
        colslistCheckable.addItem(tabmodel->columnTitle(i), true);
        colslist.addItem(tabmodel->columnTitle(i));
    }
    colslist.setEditable(false);
    colslistCheckable.setEditable(false);
    for (int i=0; i<colCmb.size(); i++) {
        colCmb[i]->setModel(&colslist);
        colCmb[i]->setCurrentIndex(oldidx.value(i, i));
    }
    ui->lstColumns->setModel(&colslistCheckable);
    tabmodel->setReadonly(true);
    QApplication::restoreOverrideCursor();
}