Example #1
0
    ZVariant mid(const QList<ZVariant> &args)
    {
        if (args.count() < 3)
            return ZVariant();

        return args.first().toList().mid(args.at(1).toInt(), args.at(2).toInt());
    }
Example #2
0
void FormConversion::doConversion() {
    int currentMode = conversionStack->currentIndex();
    QList<conversionData*> dataList = *(modeList->at(currentMode))->dataList;

    bool newButtonFound = false;
    for (int c = 0; c < dataList.count(); c++) {
        QPushButton *b = (*(dataList.at(c))).button;
        if (b->isChecked()) {
            if (b == currentButton) {
                b->toggle();
            } else {
                newButton = b;
                newFactor = (*(dataList.at(c))).factor;
                newButtonFound = true;
            }
        }
    }
    if (newButtonFound) {
        if (currentButton) { // temp convert ignores these anyway
            UnitConversionInstruction::from = currentFactor;
            UnitConversionInstruction::to = newFactor;
            systemEngine->pushInstruction("UnitConversion");
        }
        currentButton = newButton;
        currentFactor = newFactor;
    } else { // current button toggled off
        currentButton = 0;
    }
}
Example #3
0
bool KNMusicModel::insertMusicRows(int row,
                                   const QList<KNMusicDetailInfo> &detailInfos)
{
    //Check the row first.
    Q_ASSERT(row>-1 && row<=m_detailInfos.size());
    //Ignore the empty list.
    if(detailInfos.isEmpty())
    {
        return true;
    }
    //Follow the documentation, we have to do this.
    beginInsertRows(QModelIndex(), row, row + detailInfos.size() -1);
    //Insert the data to the detail info list.
    for(int i=detailInfos.size()-1; i>-1; --i)
    {
        //Insert the data to the specific position.
        m_detailInfos.insert(row, detailInfos.at(i));
        //Add the duration to the total duration counter.
        m_totalDuration+=detailInfos.at(i).duration;
    }
    //As the documentation said, called this after insert rows.
    endInsertRows();
    //Because this operation change the row count, the row count changed signal
    //will be emitted.
    emit rowCountChanged();
    return true;
}
Example #4
0
static void initWritingSystems(QtFontFamily *family, ATSFontRef atsFont)
{
    ByteCount length = 0;
    if (ATSFontGetTable(atsFont, MAKE_TAG('O', 'S', '/', '2'), 0, 0, 0, &length) != noErr)
        return;
    QVarLengthArray<uchar> os2Table(length);
    if (length < 86
        || ATSFontGetTable(atsFont, MAKE_TAG('O', 'S', '/', '2'), 0, length, os2Table.data(), &length) != noErr)
        return;

    quint32 unicodeRange[4] = {
        qFromBigEndian<quint32>(os2Table.data() + 42),
        qFromBigEndian<quint32>(os2Table.data() + 46),
        qFromBigEndian<quint32>(os2Table.data() + 50),
        qFromBigEndian<quint32>(os2Table.data() + 54)
    };
    quint32 codePageRange[2] = { qFromBigEndian<quint32>(os2Table.data() + 78), qFromBigEndian<quint32>(os2Table.data() + 82) };
    QList<QFontDatabase::WritingSystem> systems = determineWritingSystemsFromTrueTypeBits(unicodeRange, codePageRange);
#if 0
    QCFString name;
    ATSFontGetName(atsFont, kATSOptionFlagsDefault, &name);
    qDebug() << systems.count() << "writing systems for" << QString(name);
qDebug() << "first char" << hex << unicodeRange[0];
    for (int i = 0; i < systems.count(); ++i)
        qDebug() << QFontDatabase::writingSystemName(systems.at(i));
#endif
    for (int i = 0; i < systems.count(); ++i)
        family->writingSystems[systems.at(i)] = QtFontFamily::Supported;
}
Example #5
0
bool ConsolePlan::addSpots(float angle, QList<Plane2DCoordinate> coordinates)
{
    QString str;
    if (m_planeSpots.contains(angle))
    {

        QList<Plane2DCoordinate> planeSpots = m_planeSpots.value(angle);
        for (int i = 0;i < coordinates.size();i++)
        {
            if (containSpot(planeSpots,coordinates.at(i)) >= 0)
            {
                str = printLastAction(AddSpot) + printLastError(ErrorSuchSpotExists);
                qCWarning(PlanGenerator()) << PlanGenerator().categoryName() << str;
                return false;
            }
        }
        for (int i = 0;i < coordinates.size();i++)
        {
            addSpot(angle,coordinates.at(i));
        }

        str = printLastAction(AddSpot) + printLastError(NoError);
        qCDebug(PlanGenerator()) << PlanGenerator().categoryName() << str;
        return true;
    }else
    {
        str = printLastAction(AddSpot) + printLastError(ErrorNoSuchPlane);
        qCWarning(PlanGenerator()) << PlanGenerator().categoryName() << str;
        emit error(ErrorNoSuchPlane);
        return false;
    }
}
Example #6
0
Server::Server(QWidget *parent) : QWidget(parent)
{

    sslServer = new SSLServer(this);
    if (!sslServer->listen()) {
        QMessageBox::critical(this, tr("Secure Fortune Server"),
                              tr("Unable to start the server: %1.")
                              .arg(sslServer->errorString()));
        close();
        return;
    }
    QString ipAddress;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    // use the first non-localhost IPv4 address
    for (int i = 0; i < ipAddressesList.size(); ++i) {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
            ipAddressesList.at(i).toIPv4Address()) {
            ipAddress = ipAddressesList.at(i).toString();
            break;
        }
    }
    // if we did not find one, use IPv4 localhost
    if (ipAddress.isEmpty())
        ipAddress = QHostAddress(QHostAddress::LocalHost).toString();


    qDebug() << (tr("The server is running on\n\nIP: %1\nport: %2\n\n"
                            "Run the Secure Fortune Client example now.")
                         .arg(ipAddress).arg(sslServer->serverPort()));


    /*fortunes << tr("You've been leading a dog's life. Stay off the furniture.")
             << tr("You can always think about tomorrow later...")
             << tr("You will be surprised by a loud noise.")
             << tr("The Hokies will not be ACC champs this year. Maybe next?")
             << tr("Notre Dame in the ACC?! Give me a break!!")
             << tr("If only Blacksburg had a Trader Joes!!")
             << tr("You will feel hungry again in another hour.")
             << tr("Thank goodness we now have a Chipoltes.")
             << tr("Your time would be better spent tweeting.")
             << tr("You cannot kill time without injuring eternity.")
             << tr("You can do anything with Qt.")
             << tr("Computers are not intelligent. They only think they are.")
             << tr("Security is important as your clasmates are always wiresharking your traffic.")
             << tr("You will survive ECE 3574.");*/
    //connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
    connect(sslServer, SIGNAL(newConnection()), this, SLOT(handleNewConnection()));

    //QHBoxLayout *buttonLayout = new QHBoxLayout;
    //buttonLayout->addStretch(1);
    //buttonLayout->addWidget(quitButton);
    //buttonLayout->addStretch(1);

    //QVBoxLayout *mainLayout = new QVBoxLayout;
    //mainLayout->addWidget(statusLabel);
    //mainLayout->addLayout(buttonLayout);
    //setLayout(mainLayout);

    //setWindowTitle(tr("Secure Fortune Server"));
}
QgsAuthCertTrustPolicyComboBox::QgsAuthCertTrustPolicyComboBox( QWidget *parent,
                                                                QgsAuthCertUtils::CertTrustPolicy policy,
                                                                QgsAuthCertUtils::CertTrustPolicy defaultpolicy )
  : QComboBox( parent )
{
  QList < QPair<QgsAuthCertUtils::CertTrustPolicy, QString> > policies;
  policies << qMakePair( QgsAuthCertUtils::DefaultTrust,
                         defaultTrustText( defaultpolicy ) )
           << qMakePair( QgsAuthCertUtils::Trusted,
                         QgsAuthCertUtils::getCertTrustName( QgsAuthCertUtils::Trusted ) )
           << qMakePair( QgsAuthCertUtils::Untrusted,
                         QgsAuthCertUtils::getCertTrustName( QgsAuthCertUtils::Untrusted ) );

  for ( int i = 0; i < policies.size(); i++ )
  {
    QgsAuthCertUtils::CertTrustPolicy polcy = policies.at( i ).first;
    QString name = policies.at( i ).second;
    addItem( name, QVariant(( int )polcy ) );
  }

  setItemData(1, QgsAuthCertUtils::greenColor(), Qt::TextColorRole);
  setItemData(2, QgsAuthCertUtils::redColor(), Qt::TextColorRole);

  // for styling closed state of combobox
//  setEditable( true );
//  lineEdit()->setReadOnly( true );

  connect( this, SIGNAL( currentIndexChanged( int ) ),
           this, SLOT( highlightCurrentIndex( int ) ) );

  setTrustPolicy( policy );
  setDefaultTrustPolicy( defaultpolicy );
}
QMap<QString,QString> databaseFile:: parseEach(QString table,QXmlStreamReader& xml)
{
    QMap<QString,QString> classDB;
    /* Let's check that we're really getting a class */
    if(xml.tokenType() != QXmlStreamReader::StartElement &&
            xml.name() == table) {
        return classDB;
    }
    xml.readNext();
    while(!(xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == table))
    {
        if(xml.tokenType() == QXmlStreamReader::StartElement)
        {
            QString name = xml.name().toString();
            QList<QString> dbGet = getDbStructure(table);
            int numElement = dbGet.count();
            for(int i=0; i<numElement; i++)
                if(name == dbGet.at(i))
                {
                    classDB[dbGet.at(i)] = xml.readElementText();
                    break;
                }
        }
        xml.readNext();
    }
    return classDB;
}
QMap<QString,QString> databaseFile:: insertItemWithKeyId(QString table, QList<QString> infoInsert) // id is key ( increase each time)
{
    QList<QString> dbGet = getDbStructure(table);
    QMap<QString,QString> item;
    int numDb			 = dbGet.count();
    int numFieldInsert	 = infoInsert.count();
    if(numFieldInsert == numDb - 1) // number insert equal ( except id)
    {
        QMap<QString,QString> maxItem = searchMax(table,"id");
        int maxId = maxItem["id"].toInt() +1;
        item["id"] = QString::number(maxId); // id must be the first order
        for(int j=1; j<numDb; j++)
            item[dbGet.at(j)] = infoInsert.at(j-1);
        // append
        if(table =="class")
            classList.append(item);
        else if(table =="class_member")
            classMemberList.append(item);
        else if(table =="course")
            courseList.append(item);
        else if(table =="course_skill")
            courseSkillList.append(item);
        else if(table =="material")
            materialList.append(item);
        else if(table =="materialuse")
            materialUseList.append(item);
        else if(table =="member")
            memberList.append(item);
        else if(table =="skill")
            skillList.append(item);
        else if(table =="skill_material")
            skillMaterialList.append(item);
    }
    return item;
}
Example #10
0
void TableView::readFromFile(QString filename)
{
    QFile file(filename);
    
    if (!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::information(this, tr("Unable to open file"), file.errorString());
        return ;
    }

    QList<QPair<QString, QString> > list = passModel->getList();
    QList<QString> description = passModel->getDescription();
    QDataStream in(&file);
    in >> description >> list;

    int i;

    if (list.isEmpty())
    {
        QMessageBox::information(this, tr("Error"), tr("Nothing exists in the file"));
        return ;
    }
    else
    {
        for (i=0; i<list.size(); i++)
        {
            QPair<QString, QString> pair = list.at(i);
            addAction(description.at(i), pair.first, pair.second);
        }
    }
}
bool QGeoRoutingManagerEngineNokia::checkEngineSupport(const QGeoRouteRequest &request,
        QGeoRouteRequest::TravelModes travelModes) const
{
    QList<QGeoRouteRequest::FeatureType> featureTypeList = request.featureTypes();
    QGeoRouteRequest::FeatureTypes featureTypeFlag = QGeoRouteRequest::NoFeature;
    QGeoRouteRequest::FeatureWeights featureWeightFlag = QGeoRouteRequest::NeutralFeatureWeight;

    for (int i = 0; i < featureTypeList.size(); ++i) {
        featureTypeFlag |= featureTypeList.at(i);
        featureWeightFlag |= request.featureWeight(featureTypeList.at(i));
    }

    if ((featureTypeFlag & supportedFeatureTypes()) != featureTypeFlag)
        return false;

    if ((featureWeightFlag & supportedFeatureWeights()) != featureWeightFlag)
        return false;


    if ((request.maneuverDetail() & supportedManeuverDetails()) != request.maneuverDetail())
        return false;

    if ((request.segmentDetail() & supportedSegmentDetails()) != request.segmentDetail())
        return false;

    if ((request.routeOptimization() & supportedRouteOptimizations()) != request.routeOptimization())
        return false;

    if ((travelModes & supportedTravelModes()) != travelModes)
        return false;

    return true;
}
Example #12
0
/*
  Calculates and stores the preferred height given the width \a w.
*/
void QBoxLayoutPrivate::calcHfw(int w)
{
    QVector<QLayoutStruct> &a = geomArray;
    int n = a.count();
    int h = 0;
    int mh = 0;

    Q_ASSERT(n == list.size());

    if (horz(dir)) {
        qGeomCalc(a, 0, n, 0, w);
        for (int i = 0; i < n; i++) {
            QBoxLayoutItem *box = list.at(i);
            h = qMax(h, box->hfw(a.at(i).size));
            mh = qMax(mh, box->mhfw(a.at(i).size));
        }
    } else {
        for (int i = 0; i < n; ++i) {
            QBoxLayoutItem *box = list.at(i);
            int spacing = a.at(i).spacing;
            h += box->hfw(w);
            mh += box->mhfw(w);
            h += spacing;
            mh += spacing;
        }
    }
    hfwWidth = w;
    hfwHeight = h;
    hfwMinHeight = mh;
}
QByteArray QDeclarativeListModelParser::compile(const QList<QDeclarativeCustomParserProperty> &customProps)
{
    QList<ListInstruction> instr;
    QByteArray data;
    listElementTypeName = QByteArray(); // unknown

    for(int ii = 0; ii < customProps.count(); ++ii) {
        const QDeclarativeCustomParserProperty &prop = customProps.at(ii);
        if(!prop.name().isEmpty()) { // isn't default property
            error(prop, QDeclarativeListModel::tr("ListModel: undefined property '%1'").arg(QString::fromUtf8(prop.name())));
            return QByteArray();
        }

        if(!compileProperty(prop, instr, data)) {
            return QByteArray();
        }
    }

    int size = sizeof(ListModelData) +
               instr.count() * sizeof(ListInstruction) +
               data.count();

    QByteArray rv;
    rv.resize(size);

    ListModelData *lmd = (ListModelData *)rv.data();
    lmd->dataOffset = sizeof(ListModelData) +
                     instr.count() * sizeof(ListInstruction);
    lmd->instrCount = instr.count();
    for (int ii = 0; ii < instr.count(); ++ii)
        lmd->instructions()[ii] = instr.at(ii);
    ::memcpy(rv.data() + lmd->dataOffset, data.constData(), data.count());

    return rv;
}
Example #14
0
//static
QString RenderedLabel::createElidedLabel(const QString& srcText, const QFont& font,const QSize& bounds)
{

    QFontMetrics fm(font);

    int maxTextWidth = bounds.width();
    //check to see if the text can be simply elided by the default Qt algo
    QString modText = fm.elidedText (srcText, Qt::ElideRight,maxTextWidth*2);
    QRect br = fm.boundingRect(QRect(0, 0, maxTextWidth, bounds.height()),
                               Qt::AlignHCenter | Qt::TextWordWrap, modText);
    if (br.width() > maxTextWidth)
    {
        //it overflowed...have to do a custom eliding and linebreaking
        QList<QString> elements;
        textLabelElementsByLineBreaks(srcText,elements);
        //add elements one by one to fill the first line. If the first element doesn't fit, then split that element into 2...
        QList<QString> firstElementParts;
        customBreakString(elements[0],maxTextWidth,bounds.height(),fm,firstElementParts);
        modText.clear();
        for (int i=0; i<firstElementParts.size(); ++i)
            modText.append(firstElementParts.at(i)).append(' ');
        for (int i=1; i<elements.size(); ++i)
            modText.append(elements.at(i)).append(' ');
        modText = fm.elidedText(modText,Qt::ElideRight,maxTextWidth*2);
    }
    return modText;
}
Example #15
0
/**
 * Called, if a menu action is toggled.
 */
void KFLogTreeWidget::slotMenuActionTriggered( QAction* action )
{
  int columnIdx = action->data().toInt();

  if( columnIdx == -1 )
    {
      // All columns should be switched on.
      QList<QAction *> actions = menuActionGroup->actions ();

      for( int i = 0; i < actions.size(); i++ )
        {
          columnIdx = actions.at(i)->data().toInt();

          if( columnIdx == -1 )
            {
              continue;
            }

          setColumnHidden( columnIdx, false );
          actions.at(i)->setChecked( true );
        }

      slotResizeColumns2Content();
      return;
    }

  // Only one column has to handle.
  setColumnHidden( columnIdx, ( action->isChecked() == false ) );
  slotResizeColumns2Content();
}
Example #16
0
QMap<QString,QString> databaseFile::searchMax(QString table, QString field)
{
    QList<QString> dbGet = getDbStructure(table);
    QList< QMap<QString,QString> > listInfo = getDbBrowse(table);

    // find if that field is exist in table
    bool isExist = isItemExist(dbGet,field );
    int maxValue = 0;
    int indexMax = 0;
    // exist --> find the max
    if(isExist == true)
    {
        int numRow = listInfo.count();
        // check if number
        QMap<QString,QString> tempInfo = listInfo.at(0);
        QString tempValue = tempInfo[field];
        if(isNumber(tempValue) == true)
        {
            for(int j=0; j<numRow; j++)
            {
                QMap<QString,QString> itemInfo = listInfo.at(j);
                QString itemValue = itemInfo[field];
                int itemValueInt  = itemValue.toInt();
                if(itemValueInt > maxValue)
                {
                    maxValue = itemValueInt;
                    indexMax = j;
                }
            }
        }
    }
    return listInfo.at(indexMax);
}
Example #17
0
QList<GLC_Point2d> glc::normalyzePolygon(const QList<GLC_Point2d>& polygon)
{
    QList<GLC_Point2d> subject;
    const int count= polygon.count();
    Q_ASSERT(count > 2);

    GLC_Point2d minPoint= polygon.first();
    GLC_Point2d maxPoint= minPoint;
    for (int i= 1; i < count; ++i)
    {
        GLC_Point2d point= polygon.at(i);
        minPoint.setX(qMin(point.x(), minPoint.x()));
        minPoint.setY(qMin(point.y(), minPoint.y()));

        maxPoint.setX(qMax(point.x(), maxPoint.x()));
        maxPoint.setY(qMax(point.y(), maxPoint.y()));
    }
    const GLC_Vector2d range= maxPoint - minPoint;
    Q_ASSERT(range.x() != 0.0);
    Q_ASSERT(range.y() != 0.0);

    for (int i= 0; i < count; ++i)
    {
        const GLC_Point2d point= polygon.at(i);
        const GLC_Point2d temp= (point - minPoint);

        const GLC_Point2d result(temp.x() / range.x(), temp.y() / range.y());
        subject.append(result);
    }

    return subject;
}
QString TCPNetworkServer::startServer(const QString &sAddress, int port)
{
	QHostAddress address = QHostAddress::Any;
	if(sAddress != "")
		address.setAddress(sAddress);
	if (!this->listen(address,port)) 
	{
		return QString("Unable to start the server: %1.").arg(this->errorString());
	}
	QString ipAddress;
	QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
	// use the first non-localhost IPv4 address
	for (int i = 0; i < ipAddressesList.size(); ++i) {
		if (ipAddressesList.at(i) != QHostAddress::LocalHost &&	ipAddressesList.at(i).toIPv4Address()) 
		{
				ipAddress = ipAddressesList.at(i).toString();
				break;
		}
	}
	// if we did not find one, use IPv4 localhost
	if (ipAddress.isEmpty())
		ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
	connect(this, SIGNAL(newConnection()), this, SLOT(newIncomingConnectionFromClient()));
	QString usedAddress = sAddress;
	if(usedAddress == "")
		usedAddress = QString("%1").arg(ipAddress);
	QString sInfo = QString("%1:%2").arg(usedAddress).arg(this->serverPort());
	return sInfo;
}
Example #19
0
void BookmarkWidget::deleteItemPermanently(const QString xmlPath, QTreeWidgetItem* item)
{
    if(!item) {
        QList<QTreeWidgetItem*> list = bTreeWidget->selectedItems();
        if(list.isEmpty()) return;
        item = list.at(0);
        if(!item) return;
    }
    // DT: don't move this!
    QString uuid = item->text(UUID_COLUMN);

    QDomDocument doc;
    QDomElement elt = findElementbyUUID(doc, uuid, BOOKMARK, xmlPath);

    QList<QTreeWidgetItem *> items = bTreeWidget->findItems(uuid, Qt::MatchExactly, UUID_COLUMN);
    item = items.at(0);
    delete item;

    if(elt.isNull()) return;

    QDomNode parent = elt.parentNode();
    parent.removeChild(elt);
    saveDOMToFile(doc, xmlPath);
    //refreshBookmarkList();
}
void detailManagingDialog::on_pushButton_done_clicked()
{
    QString detailDesignation;
    QString detailName;

    QList<QTableWidgetItem*> items = ui->tableWidget_aom_detailsTable->selectedItems();
    if(items.isEmpty())
    {
        m_signalNewDetail();
        this->reject();
    }

    if(items.at(0))
    {
        detailDesignation = items.at(0)->text();
        if(detailDesignation.isEmpty())
        {
            m_signalNewDetail();
            this->reject();
        }
    }

    if(items.at(1))
    {
        detailName = items.at(0)->text();
        if(detailName.isEmpty())
        {
            m_signalNewDetail();
            this->reject();
        }
    }

    m_signalNewDetail(true, detailDesignation, detailName);
    this->accept();
}
void PluginChoooserWidget::loadImpl()
{
	clear();
	Config group = Config().group("plugins/list");
	QStandardItem *parent_item = m_model->invisibleRootItem();

    QList<QWeakPointer<Plugin> > plugins = pluginsList();
	QStringList helper;
    for (int i = 0; i < plugins.size(); i++) {
        const PluginInfo &info = plugins.at(i).data()->info();
        QLatin1String class_name(plugins.at(i).data()->metaObject()->className());
        if (!m_plugin_items.contains(info.name())) {
			QIcon icon = info.icon();
			if (icon.isNull() || !icon.availableSizes().count())
				icon = Icon("applications-system");
			QString name = info.name();
			int index = qLowerBound(helper, name) - helper.constBegin();
			helper.insert(index, name);
			ServiceItem *item = new ServiceItem(icon, name);
			item->setToolTip(html(info));
			item->setCheckable(true);
			item->setData(true,ServiceItem::ExclusiveRole);
			item->setData(info.description().toString(), DescriptionRole);
			item->setCheckState((group.value(class_name, true) ? Qt::Checked : Qt::Unchecked));
			parent_item->insertRow(index, item);
			m_plugin_items.insert(class_name, item);
            m_plugins.insert(class_name, plugins.at(i).data());
		}
	}
}
Example #22
0
void NetGUI::loadNetKit()
{
    QString configFile = BaseDir + "/lab.conf";
    QFile labFile(configFile);
    if(!labFile.exists())
    {
        //notify user
        return;
    }
    nodes.clear();
    ui->NodeList->clear();
    if(baseConfig == NULL)
    {
        delete baseConfig;
    }
    baseConfig = new BaseConfig(BaseDir, configFile);

    QList<QString> nodeList = baseConfig->getNodeList();
    for(int i = 0; i < nodeList.size(); i++)
    {
        Node node(BaseDir, nodeList.at(i));
        nodes.append(node);
        ui->NodeList->addItem(nodeList.at(i));
    }
    ui->StartButton->setEnabled(true);
    ui->EditButton->setEnabled(true);
    ui->AddButton->setEnabled(true);
    ui->RemoveButton->setEnabled(true);
}
Example #23
0
/**
 * @brief Tests the sorting method for SearchResultElements.
 */
void SearchResultTester::testSort()
{
    QList<SearchResultElement> list;
    SearchResult s(list);
    SearchResultElement element1;
    element1.setScore(4);
    SearchResultElement element2;
    element2.setScore(1);
    SearchResultElement element3;
    element3.setScore(7);
    SearchResultElement element4;
    element4.setScore(3);
    SearchResultElement element5;
    element5.setScore(2);
    s.addResultElement(element1);
    s.addResultElement(element2);
    s.addResultElement(element3);
    s.addResultElement(element4);
    s.addResultElement(element5);

    QList<SearchResultElement> sortedList = s.sortByScore();

    QCOMPARE(sortedList.at(0).getScore(), element2.getScore());
    QCOMPARE(sortedList.at(1).getScore(), element5.getScore());
    QCOMPARE(sortedList.at(2).getScore(), element4.getScore());
    QCOMPARE(sortedList.at(3).getScore(), element1.getScore());
    QCOMPARE(sortedList.at(4).getScore(), element3.getScore());

}
Example #24
0
void tstCatMngr::testGetAllCategories()
{
  printStartMsg("tstCatMngr::testGetAllCategories");
  
  TournamentDB* db = getScenario01(true);
  CatMngr cmngr(db);
  
  // run on empty table
  QList<Category> result = cmngr.getAllCategories();
  CPPUNIT_ASSERT(result.length() == 0);
  
  // actually create a valid category
  CPPUNIT_ASSERT(cmngr.createNewCategory("c1") == OK);
  CPPUNIT_ASSERT(cmngr.createNewCategory("c2") == OK);
  
  // run on filled table
  result = cmngr.getAllCategories();
  CPPUNIT_ASSERT(result.length() == 2);
  Category c = result.at(0);
  CPPUNIT_ASSERT(c.getId() == 1);
  CPPUNIT_ASSERT(c.getName() == "c1");
  c = result.at(1);
  CPPUNIT_ASSERT(c.getId() == 2);
  CPPUNIT_ASSERT(c.getName() == "c2");
  
  delete db;
  printEndMsg();
}
void LocalClientHandler::addExistingMonster(QList<PlayerMonster> tradeMonster)
{
    int index=0;
    while(index<tradeMonster.size())
    {
        switch(GlobalServerData::serverSettings.database.type)
        {
            default:
            case ServerSettings::Database::DatabaseType_Mysql:
                emit dbQuery(QString("UPDATE monster SET player=%2 WHERE id=%1;")
                             .arg(tradeMonster.at(index).id)
                             .arg(player_informations->id)
                             );
            break;
            case ServerSettings::Database::DatabaseType_SQLite:
                emit dbQuery(QString("UPDATE monster SET player=%2 WHERE id=%1;")
                             .arg(tradeMonster.at(index).id)
                             .arg(player_informations->id)
                             );
            break;
        }
        index++;
    }
    player_informations->public_and_private_informations.playerMonster << tradeMonster;
}
Example #26
0
void PluginList::readLockedOrderFrom(const QString &fileName)
{
    m_LockedOrder.clear();

    QFile file(fileName);
    if (!file.exists()) {
        // no locked load order, that's ok
        return;
    }

    file.open(QIODevice::ReadOnly);
    while (!file.atEnd()) {
        QByteArray line = file.readLine();
        if ((line.size() > 0) && (line.at(0) != '#')) {
            QList<QByteArray> fields = line.split('|');
            if (fields.count() == 2) {
                m_LockedOrder[QString::fromUtf8(fields.at(0))] = fields.at(1).trimmed().toInt();
            } else {
                reportError(tr("The file containing locked plugin indices is broken"));
                break;
            }
        }
    }
    file.close();
}
Example #27
0
ServerDialog::ServerDialog(MainWidget *field) : ui(new Ui::ServerDialog), field(field)
{
    ui->setupUi(this);

    QString ipAddress;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();

    server = new Server(field);
    for (int i = 0; i < ipAddressesList.size(); ++i)
    {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
                ipAddressesList.at(i).toIPv4Address())
        {
            ipAddress = ipAddressesList.at(i).toString();
            break;
        }
    }

    if (ipAddress.isEmpty())
        ipAddress = QHostAddress(QHostAddress::LocalHost).toString();

    if (!server->listen(QHostAddress(ipAddress), 5555))
    {
        QMessageBox::critical(this, this->windowTitle(),
                              QString("Невозможно запустить сервер: %1.").arg(server->errorString()));
        close();
        return;
    }

    ui->adress->setText(ipAddress);
    ui->port->setText(QString::number(server->serverPort()));
    this->setFixedSize(size());

}
Example #28
0
bool FileEngine::saveMenu(Menu *menu, bool replace)
{
    Q_D(const FileEngine);

    bool ret = false;
    d->settings->beginGroup(QStringLiteral("Menus"));

    if (replace || !d->settings->childGroups().contains(menu->id())) {
        d->settings->beginGroup(menu->id());

        d->settings->setValue(QStringLiteral("Name"), menu->name());
        d->settings->setValue(QStringLiteral("AutoAddPages"), menu->autoAddPages());
        d->settings->setValue(QStringLiteral("Locations"), menu->locations());

        QList<QVariantHash> urls = menu->entries();
        d->settings->beginWriteArray(QStringLiteral("urls"), urls.size());
        for (int i = 0; i < urls.size(); ++i) {
            d->settings->setArrayIndex(i);
            // TODO save all values
            d->settings->setValue(QStringLiteral("text"), urls.at(i).value(QStringLiteral("text")));
            d->settings->setValue(QStringLiteral("url"), urls.at(i).value(QStringLiteral("url")));
        }
        d->settings->endArray();

        d->settings->endGroup();
        ret = true;
    }

    d->settings->endGroup(); // Menus

    // Force reloading of settings
    loadSettings();

    return ret && d->settings->isWritable();
}
Example #29
0
bool Doc::addFixture(Fixture* fixture, quint32 id)
{
    Q_ASSERT(fixture != NULL);

    // No ID given, this method can assign one
    if (id == Fixture::invalidId())
        id = createFixtureId();

    if (m_fixtures.contains(id) == true || id == Fixture::invalidId())
    {
        qWarning() << Q_FUNC_INFO << "a fixture with ID" << id << "already exists!";
        return false;
    }
    else
    {
        fixture->setID(id);
        m_fixtures.insert(id, fixture);

        /* Patch fixture change signals thru Doc */
        connect(fixture, SIGNAL(changed(quint32)),
                this, SLOT(slotFixtureChanged(quint32)));

        /* Keep track of fixture addresses */
        for (uint i = fixture->universeAddress();
             i < fixture->universeAddress() + fixture->channels(); i++)
        {
            m_addresses[i] = id;
        }

        // Add the fixture channels capabilities to the universe they belong
        QList<Universe *> universes = inputOutputMap()->claimUniverses();
        int uni = fixture->universe();

        // TODO !!! if a universe for this fixture doesn't exist, add it !!!
        QList<int> forcedHTP = fixture->forcedHTPChannels();
        QList<int> forcedLTP = fixture->forcedLTPChannels();

        for (quint32 i = 0 ; i < fixture->channels(); i++)
        {
            const QLCChannel* channel(fixture->channel(i));
            if (forcedHTP.contains(i))
                universes.at(uni)->setChannelCapability(fixture->address() + i,
                                                        channel->group(), Universe::HTP);
            else if (forcedLTP.contains(i))
                universes.at(uni)->setChannelCapability(fixture->address() + i,
                                                        channel->group(), Universe::LTP);
            else
                universes.at(uni)->setChannelCapability(fixture->address() + i,
                                                        channel->group());
            ChannelModifier *mod = fixture->channelModifier(i);
            universes.at(uni)->setChannelModifier(fixture->address() + i, mod);
        }
        inputOutputMap()->releaseUniverses(true);

        emit fixtureAdded(id);
        setModified();

        return true;
    }
}
void WidgetMenuBarMapEditor::updateRight(QAction *action)
{
    WidgetMenuBarMapEditor *bar = getBarRight();

    int index = bar->actions().indexOf(action);
    QList<int> list;
    list << static_cast<int>(MapEditorModesKind::DrawPencil) << static_cast<int>
        (MapEditorModesKind::DrawPin) << static_cast<int>(
        MapEditorModesKind::LayerNone)<< static_cast<int>(
        MapEditorModesKind::LayerOn);

    // Deselect previous selected action
    for (int i = 0; i < list.size() / 2; i++) {
        int l = list.at(i * 2);
        int r = list.at(i * 2 + 1);
        if (index >= l && index <= r) {
            for (int i = l; i <= r; i++)
                bar->actions().at(i)->setProperty("selection", false);
        }
    }

    // Select the pressed action
    action->setProperty("selection", true);

    // Repaint
    this->repaint();
}