void Core::writeOra(const QString& oraPath, const QSize& canvasSize, const QVariantList layerList) { QZipWriter zipWriter(oraPath); zipWriter.setCompressionPolicy(QZipWriter::AutoCompress); QByteArray xmlByteArray; // mimetype file xmlByteArray.append("image/openraster"); zipWriter.addFile("mimetype", xmlByteArray); // stack.xml file QXmlStreamWriter stream(&xmlByteArray); stream.setAutoFormatting(true); stream.writeStartDocument(); stream.writeStartElement("image"); stream.writeAttribute("w", QString::number(canvasSize.width())); stream.writeAttribute("h",QString::number(canvasSize.height())); stream.writeStartElement("stack"); QByteArray ba; QBuffer buffer(&ba); for (int i = 0; i < layerList.count(); i++) { QMap<QString, QVariant> map = layerList.at(i).toMap(); QString name = map.value("name").toString(); QString isVisible = map.value("isVisible").toString(); QString isLock = map.value("isLock").toString(); QString isSelected = map.value("isSelected").toString(); buffer.open(QIODevice::WriteOnly); QObject* obj = qvariant_cast<QObject*>(map.value("canvasItem")); CanvasItem* canvasItem = qobject_cast<CanvasItem*>(obj); QPixmap* pixmap = canvasItem->pixmap(); pixmap->save(&buffer, "PNG"); buffer.close(); QString src = "data/" + name + ".png"; zipWriter.addFile(src, ba); // layer stream.writeStartElement("layer"); stream.writeAttribute("name", name); stream.writeAttribute("composite-op", "svg:src-over"); stream.writeAttribute("visibility", isVisible == "true" ? "visible" : "hidden"); stream.writeAttribute("edit-locked", isLock); stream.writeAttribute("selected", isSelected); stream.writeAttribute("src", src); stream.writeAttribute("x", "0"); stream.writeAttribute("y", "0"); stream.writeAttribute("opacity", "1.0"); stream.writeEndElement(); // layer } stream.writeEndElement(); // stack stream.writeEndElement(); // image stream.writeEndDocument(); // document zipWriter.addFile("stack.xml", xmlByteArray); zipWriter.close(); }
QScriptValue REcmaSharedPointerBlock::getProperty (QScriptContext* context, QScriptEngine* engine) { //REcmaHelper::functionStart("REcmaSharedPointerBlock::getProperty", context, engine); //qDebug() << "ECMAScript WRAPPER: REcmaSharedPointerBlock::getProperty"; //QCoreApplication::processEvents(); QScriptValue result = engine->undefinedValue(); // public function: can be called from ECMA wrapper of ECMA shell: RBlock* self = getSelf("getProperty", context); //Q_ASSERT(self!=NULL); if (self==NULL) { return REcmaHelper::throwError("self is NULL", context); } if( context->argumentCount() == 1 && ( context->argument(0).isVariant() || context->argument(0).isQObject() || context->argument(0).isNull() ) /* type: RPropertyTypeId */ ){ // prepare arguments: // argument isCopyable and has default constructor and isSimpleClass RPropertyTypeId* ap0 = qscriptvalue_cast< RPropertyTypeId* >( context->argument( 0 ) ); if (ap0 == NULL) { return REcmaHelper::throwError("RBlock: Argument 0 is not of type RPropertyTypeId.", context); } RPropertyTypeId a0 = *ap0; // end of arguments // call C++ function: // return type 'QPair < QVariant , RPropertyAttributes >' QPair < QVariant , RPropertyAttributes > cppResult = self->getProperty(a0); // return type: QPair < QVariant , RPropertyAttributes > // Pair of ...: //result = REcmaHelper::pairToScriptValue(engine, cppResult); QVariantList vl; QVariant v; // first type of pair is variant: if (QString(cppResult.first.typeName())=="RLineweight::Lineweight") { v.setValue((int)cppResult.first.value<RLineweight::Lineweight>()); } else { v.setValue(cppResult.first); } vl.append(v); v.setValue(cppResult.second); vl.append(v); result = qScriptValueFromValue(engine, vl); } else if( context->argumentCount() == 2 && ( context->argument(0).isVariant() || context->argument(0).isQObject() || context->argument(0).isNull() ) /* type: RPropertyTypeId */ && ( context->argument(1).isBool() ) /* type: bool */ ){ // prepare arguments: // argument isCopyable and has default constructor and isSimpleClass RPropertyTypeId* ap0 = qscriptvalue_cast< RPropertyTypeId* >( context->argument( 0 ) ); if (ap0 == NULL) { return REcmaHelper::throwError("RBlock: Argument 0 is not of type RPropertyTypeId.", context); } RPropertyTypeId a0 = *ap0; // argument isStandardType bool a1 = (bool) context->argument( 1 ). toBool(); // end of arguments // call C++ function: // return type 'QPair < QVariant , RPropertyAttributes >' QPair < QVariant , RPropertyAttributes > cppResult = self->getProperty(a0 , a1); // return type: QPair < QVariant , RPropertyAttributes > // Pair of ...: //result = REcmaHelper::pairToScriptValue(engine, cppResult); QVariantList vl; QVariant v; // first type of pair is variant: if (QString(cppResult.first.typeName())=="RLineweight::Lineweight") { v.setValue((int)cppResult.first.value<RLineweight::Lineweight>()); } else { v.setValue(cppResult.first); } vl.append(v); v.setValue(cppResult.second); vl.append(v); result = qScriptValueFromValue(engine, vl); } else if( context->argumentCount() == 3 && ( context->argument(0).isVariant() || context->argument(0).isQObject() || context->argument(0).isNull() ) /* type: RPropertyTypeId */ && ( context->argument(1).isBool() ) /* type: bool */ && ( context->argument(2).isBool() ) /* type: bool */ ){ // prepare arguments: // argument isCopyable and has default constructor and isSimpleClass RPropertyTypeId* ap0 = qscriptvalue_cast< RPropertyTypeId* >( context->argument( 0 ) ); if (ap0 == NULL) { return REcmaHelper::throwError("RBlock: Argument 0 is not of type RPropertyTypeId.", context); } RPropertyTypeId a0 = *ap0; // argument isStandardType bool a1 = (bool) context->argument( 1 ). toBool(); // argument isStandardType bool a2 = (bool) context->argument( 2 ). toBool(); // end of arguments // call C++ function: // return type 'QPair < QVariant , RPropertyAttributes >' QPair < QVariant , RPropertyAttributes > cppResult = self->getProperty(a0 , a1 , a2); // return type: QPair < QVariant , RPropertyAttributes > // Pair of ...: //result = REcmaHelper::pairToScriptValue(engine, cppResult); QVariantList vl; QVariant v; // first type of pair is variant: if (QString(cppResult.first.typeName())=="RLineweight::Lineweight") { v.setValue((int)cppResult.first.value<RLineweight::Lineweight>()); } else { v.setValue(cppResult.first); } vl.append(v); v.setValue(cppResult.second); vl.append(v); result = qScriptValueFromValue(engine, vl); } else { return REcmaHelper::throwError("Wrong number/types of arguments for RBlock.getProperty().", context); } //REcmaHelper::functionEnd("REcmaSharedPointerBlock::getProperty", context, engine); return result; }
void writeInstance(QXmlStreamWriter &stream, const QVariantList &v) { stream.writeStartElement("instance"); writeName(stream, v[1]); QVariant vViewRef = v[2]; if (vViewRef.type() == QVariant::List) { QVariantList l = vViewRef.toList(); if (l[0].toString() == "viewRef") { writeCellRef(stream, l[2].toList()); } else { qWarning("Wrong instance cell description"); } } else { qWarning("Wrong instance description"); } if (v.size() > 3) { if (v[3].type() == QVariant::List) { QVariantList l = v[3].toList(); if (l[0].toString() == "property") { QString propertyName = l[1].toString(); QVariant vValue = l[2]; if (vValue.type() == QVariant::List) { QVariantList l2 = vValue.toList(); QString valueType = l2[0].toString(); if (valueType == "string") { QString value = stripQuotes(l2[1].toString()); stream.writeStartElement("property"); stream.writeAttribute("name", propertyName); stream.writeAttribute("value", value); stream.writeEndElement(); } else { qWarning("Unsupported value type '%s' for property", qPrintable(valueType)); } } } else { qWarning("Wrong instance cell description"); } } } stream.writeEndElement(); }
Tileset *VariantToMapConverter::toTileset(const QVariant &variant) { const QVariantMap variantMap = variant.toMap(); const int firstGid = variantMap["firstgid"].toInt(); const QString name = variantMap["name"].toString(); const int tileWidth = variantMap["tilewidth"].toInt(); const int tileHeight = variantMap["tileheight"].toInt(); const int spacing = variantMap["spacing"].toInt(); const int margin = variantMap["margin"].toInt(); const QVariantMap tileOffset = variantMap["tileoffset"].toMap(); const int tileOffsetX = tileOffset["x"].toInt(); const int tileOffsetY = tileOffset["y"].toInt(); if (tileWidth <= 0 || tileHeight <= 0 || firstGid == 0) { mError = tr("Invalid tileset parameters for tileset '%1'").arg(name); return 0; } typedef QScopedPointer<Tileset> TilesetPtr; TilesetPtr tileset(new Tileset(name, tileWidth, tileHeight, spacing, margin)); tileset->setTileOffset(QPoint(tileOffsetX, tileOffsetY)); const QString trans = variantMap["transparentcolor"].toString(); if (!trans.isEmpty() && QColor::isValidColor(trans)) tileset->setTransparentColor(QColor(trans)); QVariant imageVariant = variantMap["image"]; if (!imageVariant.isNull()) { QString imagePath = resolvePath(mMapDir, imageVariant); if (!tileset->loadFromImage(imagePath)) { mError = tr("Error loading tileset image:\n'%1'").arg(imagePath); return 0; } } tileset->setProperties(toProperties(variantMap["properties"])); // Read terrains QVariantList terrainsVariantList = variantMap["terrains"].toList(); for (int i = 0; i < terrainsVariantList.count(); ++i) { QVariantMap terrainMap = terrainsVariantList[i].toMap(); tileset->addTerrain(terrainMap["name"].toString(), terrainMap["tile"].toInt()); } // Read tile terrain and external image information const QVariantMap tilesVariantMap = variantMap["tiles"].toMap(); QVariantMap::const_iterator it = tilesVariantMap.constBegin(); for (; it != tilesVariantMap.end(); ++it) { bool ok; const int tileIndex = it.key().toInt(); if (tileIndex < 0) { mError = tr("Tileset tile index negative:\n'%1'").arg(tileIndex); } if (tileIndex >= tileset->tileCount()) { // Extend the tileset to fit the tile if (tileIndex >= tilesVariantMap.count()) { // If tiles are defined this way, there should be an entry // for each tile. // Limit the index to number of entries to prevent running out // of memory on malicious input. mError = tr("Tileset tile index too high:\n'%1'").arg(tileIndex); return 0; } for (int i = tileset->tileCount(); i <= tileIndex; i++) tileset->addTile(QPixmap()); } Tile *tile = tileset->tileAt(tileIndex); if (tile) { const QVariantMap tileVar = it.value().toMap(); QList<QVariant> terrains = tileVar["terrain"].toList(); if (terrains.count() == 4) { for (int i = 0; i < 4; ++i) { int terrainId = terrains.at(i).toInt(&ok); if (ok && terrainId >= 0 && terrainId < tileset->terrainCount()) tile->setCornerTerrain(i, terrainId); } } float terrainProbability = tileVar["probability"].toFloat(&ok); if (ok) tile->setTerrainProbability(terrainProbability); imageVariant = tileVar["image"]; if (!imageVariant.isNull()) { QString imagePath = resolvePath(mMapDir, imageVariant); tileset->setTileImage(tileIndex, QPixmap(imagePath), imagePath); } QVariantMap objectGroupVariant = tileVar["objectgroup"].toMap(); if (!objectGroupVariant.isEmpty()) tile->setObjectGroup(toObjectGroup(objectGroupVariant)); QVariantList frameList = tileVar["animation"].toList(); if (!frameList.isEmpty()) { QVector<Frame> frames(frameList.size()); for (int i = frameList.size() - 1; i >= 0; --i) { const QVariantMap frameVariantMap = frameList[i].toMap(); Frame &frame = frames[i]; frame.tileId = frameVariantMap["tileid"].toInt(); frame.duration = frameVariantMap["duration"].toInt(); } tile->setFrames(frames); } } } // Read tile properties QVariantMap propertiesVariantMap = variantMap["tileproperties"].toMap(); for (it = propertiesVariantMap.constBegin(); it != propertiesVariantMap.constEnd(); ++it) { const int tileIndex = it.key().toInt(); const QVariant propertiesVar = it.value(); if (tileIndex >= 0 && tileIndex < tileset->tileCount()) { const Properties properties = toProperties(propertiesVar); tileset->tileAt(tileIndex)->setProperties(properties); } } mGidMapper.insert(firstGid, tileset.data()); return tileset.take(); }
bool QgsAfsProvider::getFeature( const QgsFeatureId &id, QgsFeature &f, bool fetchGeometry, const QList<int>& /*fetchAttributes*/, const QgsRectangle filterRect ) { // If cached, return cached feature QMap<QgsFeatureId, QgsFeature>::const_iterator it = mCache.find( id ); if ( it != mCache.end() ) { f = it.value(); return filterRect.isNull() || f.geometry().intersects( filterRect ); } // Determine attributes to fetch /*QStringList fetchAttribNames; foreach ( int idx, fetchAttributes ) fetchAttribNames.append( mFields.at( idx ).name() ); */ // When fetching from server, fetch all attributes and geometry by default so that we can cache them QStringList fetchAttribNames; QList<int> fetchAttribIdx; for ( int idx = 0, n = mFields.size(); idx < n; ++idx ) { fetchAttribNames.append( mFields.at( idx ).name() ); fetchAttribIdx.append( idx ); } fetchGeometry = true; // Fetch 100 features at the time int startId = ( id / 100 ) * 100; int stopId = qMin( startId + 100, mObjectIds.length() ); QList<quint32> objectIds; for ( int i = startId; i < stopId; ++i ) { objectIds.append( mObjectIds[i] ); } // Query QString errorTitle, errorMessage; QVariantMap queryData = QgsArcGisRestUtils::getObjects( mDataSource.param( "url" ), objectIds, mDataSource.param( "crs" ), fetchGeometry, fetchAttribNames, QgsWkbTypes::hasM( mGeometryType ), QgsWkbTypes::hasZ( mGeometryType ), filterRect, errorTitle, errorMessage ); if ( queryData.isEmpty() ) { const_cast<QgsAfsProvider*>( this )->pushError( errorTitle + ": " + errorMessage ); QgsDebugMsg( "Query returned empty result" ); return false; } QVariantList featuresData = queryData["features"].toList(); if ( featuresData.isEmpty() ) { QgsDebugMsg( "Query returned no features" ); return false; } for ( int i = 0, n = featuresData.size(); i < n; ++i ) { QVariantMap featureData = featuresData[i].toMap(); QgsFeature feature; // Set FID feature.setFeatureId( startId + i ); // Set attributes if ( !fetchAttribIdx.isEmpty() ) { QVariantMap attributesData = featureData["attributes"].toMap(); feature.setFields( mFields ); QgsAttributes attributes( mFields.size() ); foreach ( int idx, fetchAttribIdx ) { attributes[idx] = attributesData[mFields.at( idx ).name()]; } feature.setAttributes( attributes ); } // Set geometry if ( fetchGeometry ) { QVariantMap geometryData = featureData["geometry"].toMap(); QgsAbstractGeometry* geometry = QgsArcGisRestUtils::parseEsriGeoJSON( geometryData, queryData["geometryType"].toString(), QgsWkbTypes::hasM( mGeometryType ), QgsWkbTypes::hasZ( mGeometryType ) ); // Above might return 0, which is ok since in theory empty geometries are allowed feature.setGeometry( QgsGeometry( geometry ) ); } feature.setValid( true ); mCache.insert( feature.id(), feature ); }
void ApiYandexSearch::getSuggestionsFinished(QNetworkReply *reply) { QByteArray content = reply->readAll(); if (m_suggestionsParameters.v == "4") { QJsonParseError parseError; QVariant json = QJsonDocument::fromJson(content, &parseError).toVariant(); if (Q_UNLIKELY(parseError.error)) { qWarning() << "ApiYandexSearch::getSuggestionsFinished():" << tr("Can't parse JSON data:") << content << tr(". Parser returned an error:") << parseError.errorString(); qWarning() << "Request:" << m_currentSuggestionsRequest; m_currentSuggestionsRequest.clear(); return; } QVariantList jsonList = json.toList(); if (jsonList.size() == 0) { return; } QVariantList suggestions = jsonList.at(1).toList(); QList<Consts::Shared::Suggestion> suggestionsToReturn; forc11 (QVariant var, suggestions) { Consts::Shared::Suggestion suggestion; // Query if (var.type() == QVariant::String) { suggestion.text = var.toString(); suggestion.kind = Consts::Shared::Suggestion::Kind::Query; } else if (var.type() == QVariant::List) { QVariantList list = var.toList(); QString kind = list.first().toString(); // Fact if (kind == "fact") { suggestion.text = list.at(1).toString(); suggestion.kind = Consts::Shared::Suggestion::Kind::Fact; suggestion.others.fact = list.at(2).toString(); } // Navigation else if (kind == "nav") { suggestion.text = list.at(3).toString(); suggestion.kind = Consts::Shared::Suggestion::Kind::Navigation; const QString nameOfGoToSite = QString::fromUtf8("перейти на сайт"); if (list.at(2).toString() != nameOfGoToSite) suggestion.others.linkTitle = list.at(2).toString(); } else { continue; } } else { continue; } suggestionsToReturn.append(suggestion); }
/* taken from http://delta.affinix.com/2006/08/14/invokemethodwithvariants/ thanks to Justin Karneges once again :) */ bool MaiaXmlRpcServerConnection::invokeMethodWithVariants( QObject *obj, const QByteArray &method, const QVariantList &args, QVariant *ret, Qt::ConnectionType type ) { // QMetaObject::invokeMethod() has a 10 argument maximum if( args.count() > 10 ) { return false; } QList<QByteArray> argTypes; for( int n = 0; n < args.count(); ++n ) { argTypes += args[n].typeName(); } // get return type int metatype = 0; QByteArray retTypeName = getReturnType(obj->metaObject(), method, argTypes); if( !retTypeName.isEmpty() && retTypeName != "QVariant" ) { metatype = QMetaType::type(retTypeName.data()); if( metatype == 0 ) { // lookup failed return false; } } QGenericArgument arg[10]; for( int n = 0; n < args.count(); ++n ) { arg[n] = QGenericArgument(args[n].typeName(), args[n].constData()); } QGenericReturnArgument retarg; QVariant retval; if( metatype != 0 && retTypeName != "void" ) { retval = QVariant(metatype, (const void *)0); retarg = QGenericReturnArgument(retval.typeName(), retval.data()); } else { /* QVariant */ retarg = QGenericReturnArgument("QVariant", &retval); } if( retTypeName.isEmpty() || retTypeName == "void" ) { /* void */ if( !QMetaObject::invokeMethod(obj, method.data(), type, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9]) ) { return false; } } else { if( !QMetaObject::invokeMethod(obj, method.data(), type, retarg, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9]) ) { return false; } } if( retval.isValid() && ret ) { *ret = retval; } return true; } // bool invokeMethodWithVariants( QObject *obj, const QByteArray &method, const QVariantList &args, QVariant *ret, Qt::ConnectionType type )
void CustomGroupModel::loadEvents() { const QDate today = QDate::currentDate(); const QTime midnight(0, 0, 0); const QTime startday(0, 0, 1); const QTime endday(23, 59, 59); QDateTime searchStartTime = QDateTime(today, startday); QDateTime searchEndTime = QDateTime(today, endday); // Setup the search parameters with time range as specified by filter criterion EventSearchParameters searchParameters; searchParameters.setStart(searchStartTime); searchParameters.setEnd(searchEndTime); searchParameters.setDetails(DetailLevel::Weekly); bb::pim::calendar::CalendarService* calendarService = new CalendarService(); const QList<CalendarEvent> events = calendarService->events(searchParameters); // get list of all calendars QList<CalendarFolder> allFolders = calendarService->folders(); CalendarFolder cf = allFolders.at(0); QMap<std::string, uint > accountColor; for (int i = 0; i < allFolders.size(); i++) { std::stringstream keyStream; keyStream << allFolders.at(i).accountId() << allFolders.at(i).id(); std::string key = keyStream.str(); accountColor.insert(key, allFolders.at(i).color()); // qDebug() << "############## folder:" << allFolders.at(i).name() << ", key:" << QString::fromStdString(key) << "=" << QString::fromStdString(value); // accountColor.insert(as.append(fs), allFolders.at(i).color()); } // Clear the old events information from the model clear(); // Iterate over the list of events QVariantList entries; int order = 0; foreach (const CalendarEvent &event, events) { // Copy the data into a model entry QVariantMap entry; entry["myType"] = QVariant(trUtf8("today")); entry["eventId"] = event.id(); entry["accountId"] = event.accountId(); entry["subject"] = event.subject().replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """); entry["order"] = order++; entry["startTime"] = event.startTime(); entry["endTime"] = event.endTime(); entry["timeString"] = ""; entry["account"] = event.accountId(); std::stringstream keyStream; keyStream << event.accountId() << event.folderId(); std::string key = keyStream.str(); entry["color24"] = QString::number(accountColor[key], 16); qDebug() << "FMI ######### key:" << QString::fromStdString(key) << "=" << accountColor[key]; qDebug() << "FMI ######### id:" << event.id() << " subject" << event.subject() << " startTime:" << event.startTime().toString(Qt::DefaultLocaleShortDate); entries.append(entry); }
void CWebAPI::OnRequestCompleted() { CHttpSocket* pRequest = (CHttpSocket*)sender(); ASSERT(pRequest->GetState() == CHttpSocket::eHandling); QString Path = pRequest->GetPath(); TArguments Cookies = GetArguments(pRequest->GetHeader("Cookie")); TArguments Arguments = GetArguments(pRequest->GetQuery().mid(1),'&'); switch(pRequest->GetType()) { case CHttpSocket::eDELETE: pRequest->RespondWithError(501); case CHttpSocket::eHEAD: case CHttpSocket::eOPTIONS: pRequest->SendResponse(); return; } if(Path.compare("/WebAPI/") == 0) pRequest->RespondWithError(403); else if(Path.left(14).compare("/WebAPI/Icons/") == 0) { int Size; if(Arguments["Size"] == "Small") Size = 16; else // if(Arguments["Size"] == "Large") Size = 32; QString Ext = Split2(Path.mid(14), ".").first; QString IconPath = theCore->Cfg()->GetSettingsDir() + "/Cache/Icons/" + Ext + QString::number(Size) + ".png"; if(!QFile::exists(IconPath)) { if(theLoader) QMetaObject::invokeMethod(theLoader, "CreateFileIcon", Qt::BlockingQueuedConnection, Q_ARG(QString, Ext)); else IconPath = ":/Icon" + QString::number(Size) + ".png"; } pRequest->SetCaching(HR2S(48)); pRequest->RespondWithFile(IconPath); } else if(Path.left(11).compare("/WebAPI/FS/") == 0) { StrPair CmdExt = Split2(Path.mid(11),"."); QVariantMap Result; if(CmdExt.first.compare("dir", Qt::CaseInsensitive) == 0) { QVariantList Entrys; QString DirPath = Arguments["Path"]; QDir Dir(DirPath); foreach (const QString& Name, Dir.entryList()) { if (Name.compare(".") == 0 || Name.compare("..") == 0) continue; QVariantMap Entry; QFileInfo Info(DirPath + "/" + Name); Entry["Name"] = Info.fileName(); Entry["Created"] = Info.created(); Entry["Modifyed"] = Info.lastModified(); if (Info.isDir()) Entry["Size"] = "dir"; else Entry["Size"] = Info.size(); Entrys.append(Entry); } Result["List"] = Entrys; }
int FeedsViewModel::childCount(const QVariantList &indexPath) { if (indexPath.length() == 0) { return m_resultList.size(); } return 0; }
QVariant FeedsViewModel::data(const QVariantList &indexPath) { return m_resultList.at(indexPath.at(0).toInt()); }
QString FeedsViewModel::itemType(const QVariantList &indexPath) { if (indexPath.size() == 1) { return "item"; } return ""; }
{ reqlist.push_back(prop.toStdString()); } request.properties = reqlist; request.completed = [&cbFunction](AsyncRangePropertyReply* reply) { if(!reply->success) { DebugOut(DebugOut::Error)<<"bluemoney get history call failed"<<endl; return; } if(cbFunction.isCallable()) { QVariantList list; for(auto val : reply->values) { list.append(toQVariant(val)); } QJSValue val = cbFunction.engine()->toScriptValue<QVariantList>(list); cbFunction.call(QJSValueList()<<val); } delete reply; };
void ParticleEditor::SaveConfigFile(QString filename) { FILE* sFile; sFile = fopen(filename.toLocal8Bit().data(), "wb"); if (!sFile){ addConsoleInfo("保存失败"); return; } QVariantMap document; QVariantList resList; QVariantMap particleData; //导出资源 QStringList imageList = resourceView->getImageList(); for (int i = 0; i < imageList.size(); i++){ QVariant res = imageList.at(i); resList.append(res); } //导出粒子 auto layer = dynamic_cast<C3DLayer*>(g_Layer); auto particleSystem = layer->getParticleSystem(); particleData.insert("texture", particleSystem->getTextureFileName().c_str()); particleData.insert("count", particleSystem->getParticleCount()); particleData.insert("particle_type", particleSystem->getParticleType()); particleData.insert("blendfunc_src", particleSystem->getBlendFunc().src); particleData.insert("blendfunc_dst", particleSystem->getBlendFunc().dst); auto data = particleSystem->getParticleData(); particleData.insert("velocity_min_x", data.m_Velocity_Min.x); particleData.insert("velocity_min_y", data.m_Velocity_Min.y); particleData.insert("velocity_min_z", data.m_Velocity_Min.z); particleData.insert("velocity_max_x", data.m_Velocity_Max.x); particleData.insert("velocity_max_y", data.m_Velocity_Max.y); particleData.insert("velocity_max_z", data.m_Velocity_Max.z); particleData.insert("accleration_min_x", data.m_Acceleration_Min.x); particleData.insert("accleration_min_y", data.m_Acceleration_Min.y); particleData.insert("accleration_min_z", data.m_Acceleration_Min.z); particleData.insert("accleration_max_x", data.m_Acceleration_Max.x); particleData.insert("accleration_max_y", data.m_Acceleration_Max.y); particleData.insert("accleration_max_z", data.m_Acceleration_Max.z); particleData.insert("size_min_x", data.m_Size_Min.x); particleData.insert("size_min_y", data.m_Size_Min.y); particleData.insert("size_min_z", data.m_Size_Min.z); particleData.insert("size_max_x", data.m_Size_Max.x); particleData.insert("size_max_y", data.m_Size_Max.y); particleData.insert("size_max_z", data.m_Size_Max.z); particleData.insert("size_velocity_x", data.m_Size_Velocity.x); particleData.insert("size_velocity_y", data.m_Size_Velocity.y); particleData.insert("size_velocity_z", data.m_Size_Velocity.z); particleData.insert("color_min_x", data.m_Color_Min.x); particleData.insert("color_min_y", data.m_Color_Min.y); particleData.insert("color_min_z", data.m_Color_Min.z); particleData.insert("color_max_x", data.m_Color_Max.x); particleData.insert("color_max_y", data.m_Color_Max.y); particleData.insert("color_max_z", data.m_Color_Max.z); particleData.insert("color_velocity_x", data.m_Color_Velocity.x); particleData.insert("color_velocity_y", data.m_Color_Velocity.y); particleData.insert("color_velocity_z", data.m_Color_Velocity.z); particleData.insert("life_min", data.m_Life_Min); particleData.insert("life_max", data.m_Life_Max); particleData.insert("life_velocity", data.m_Life_Velocity); particleData.insert("m_color_r", particleSystem->getColor()[0]); particleData.insert("m_color_g", particleSystem->getColor()[1]); particleData.insert("m_color_b", particleSystem->getColor()[2]); particleData.insert("m_color_a", particleSystem->getColor()[3]); document.insert("resList", resList); document.insert("particleData", particleData); QJsonDocument jsonDocument = QJsonDocument::fromVariant(document); QByteArray array = jsonDocument.toJson(QJsonDocument::Compact); unsigned int count = array.size(); const char* data__ = (const char*)array.data(); fwrite(data__, count, 1, sFile); fclose(sFile); }
/*! \fn void QSListModel::insert(int index, const QVariantList &value) Returns the index position of the first occurrence of the byte array ba in this byte array, */ void QSListModel::insert(int index, const QVariantList &value) { if (value.count() == 0) { return; } else if (value.count() == 1) { insert(index, value.at(0).toMap()); return; } if (m_roles.isEmpty()) { setRoleNames(value.at(0).toMap()); } beginInsertRows(QModelIndex(), index, index + value.count() - 1); m_storage.reserve(m_storage.count() + value.count()); QVariantList mid = m_storage.mid(index); for (int i = 0 ; i < value.size() ; i++) { if (index + i < m_storage.size()) { m_storage[index + i] = value.at(i); } else { m_storage.append(value.at(i)); } } for (int i = 0; i < mid.size(); i++) { int idx = index + value.size() + i; if (idx < m_storage.count()) { m_storage[idx] = mid.at(i); } else { m_storage.append(mid.at(i)); } } endInsertRows(); emit countChanged(); }
void CookieJar::addCookiesFromMapList(const QVariantList &cookies, const QString &url) { QVariantList::const_iterator i; for(i=cookies.cbegin(); i!=cookies.cend(); ++i) { addCookieFromMap((*i).toMap(), url); } }
void CountryByShape::postQuestion( QObject *gameObject ) { //Find a random placemark Q_ASSERT_X( d->m_countryNames, "CountryByShape::postQuestion", "CountryByShapePrivate::m_countryNames is NULL" ); QVector<GeoDataPlacemark*> countryPlacemarks = d->m_countryNames->placemarkList(); uint randomSeed = uint(QTime::currentTime().msec()); qsrand( randomSeed ); bool found = false; GeoDataPlacemark *placemark =0; GeoDataPoint *point = 0; GeoDataCoordinates coord; GeoDataLatLonAltBox box; QVariantList answerOptions; while ( !found ) { int randomIndex = qrand()%countryPlacemarks.size(); placemark = countryPlacemarks[randomIndex]; point = dynamic_cast<GeoDataPoint*>( placemark->geometry() ); coord = point->coordinates(); if ( point ) { /** * Find the country geometry and fetch corresponding * GeoDataLatLonAltBox to zoom in to that country so that * it fills the viewport. */ Q_ASSERT_X( d->m_countryBoundaries, "CountryByShape::postQuestion", "CountryByShapePrivate::m_countryBoundaries is NULL" ); QVector<GeoDataFeature*>::Iterator i = d->m_countryBoundaries->begin(); QVector<GeoDataFeature*>::Iterator const end = d->m_countryBoundaries->end(); for ( ; i != end; ++i ) { GeoDataPlacemark *country = static_cast<GeoDataPlacemark*>( *i ); GeoDataPolygon *polygon = dynamic_cast<GeoDataPolygon*>( country->geometry() ); GeoDataLinearRing *linearring = dynamic_cast<GeoDataLinearRing*>( country->geometry() ); GeoDataMultiGeometry *multigeom = dynamic_cast<GeoDataMultiGeometry*>( country->geometry() ); if ( polygon && polygon->contains( coord ) && !d->m_continentsAndOceans.contains(country->name(), Qt::CaseSensitive) ) { box = polygon->latLonAltBox(); found = true; break; } if ( linearring && linearring->contains( coord ) && !d->m_continentsAndOceans.contains(country->name(), Qt::CaseSensitive) ) { box = linearring->latLonAltBox(); found = true; break; } if ( multigeom ) { QVector<GeoDataGeometry*>::Iterator iter = multigeom->begin(); QVector<GeoDataGeometry*>::Iterator const end = multigeom->end(); for ( ; iter != end; ++iter ) { GeoDataPolygon *poly = dynamic_cast<GeoDataPolygon*>( *iter ); if ( poly && poly->contains( coord ) && !d->m_continentsAndOceans.contains(country->name(), Qt::CaseSensitive) ) { box = poly->latLonAltBox(); found = true; break; } } } if ( found ) { break; } } } } d->m_marbleWidget->setHighlightEnabled( true ); emit announceHighlight( coord.longitude(GeoDataCoordinates::Degree), coord.latitude(GeoDataCoordinates::Degree), GeoDataCoordinates::Degree ); /** * Now disable the highlight feature so that * the user click doesn't disturbe the highlight * we did to ask question. */ d->m_marbleWidget->setHighlightEnabled( false ); d->m_marbleWidget->centerOn( box, true ); answerOptions << placemark->name() << countryPlacemarks[qrand()%countryPlacemarks.size()]->name() << countryPlacemarks[qrand()%countryPlacemarks.size()]->name() << countryPlacemarks[qrand()%countryPlacemarks.size()]->name(); // Randomize options in list answerOptions for ( int i = 0; i < answerOptions.size(); ++i ) { QVariant option = answerOptions.takeAt( qrand()%answerOptions.size() ); answerOptions.append( option ); } if ( gameObject ) { QMetaObject::invokeMethod( gameObject, "countryByShapeQuestion", Q_ARG(QVariant, QVariant(answerOptions)), Q_ARG(QVariant, QVariant(placemark->name())) ); } }
void ReverseGeoLookupThread::run() { if (geo_lookup_data.isEmpty()) return; QNetworkRequest request; QNetworkAccessManager *rgl = new QNetworkAccessManager(); QEventLoop loop; QString mapquestURL("http://open.mapquestapi.com/nominatim/v1/reverse.php?format=json&accept-language=%1&lat=%2&lon=%3"); QString geonamesURL("http://api.geonames.org/findNearbyPlaceNameJSON?language=%1&lat=%2&lng=%3&radius=50&username=dirkhh"); QString geonamesOceanURL("http://api.geonames.org/oceanJSON?language=%1&lat=%2&lng=%3&radius=50&username=dirkhh"); QString divelogsURL("https://www.divelogs.de/mapsearch_divespotnames.php?lat=%1&lng=%2&radius=50"); QTimer timer; request.setRawHeader("Accept", "text/json"); request.setRawHeader("User-Agent", getUserAgent().toUtf8()); connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); Q_FOREACH (const GeoLookupInfo& info, geo_lookup_data ) { struct dive_site *ds = info.uuid ? get_dive_site_by_uuid(info.uuid) : &displayed_dive_site; // first check the findNearbyPlaces API from geonames - that should give us country, state, city request.setUrl(geonamesURL.arg(uiLanguage(NULL)).arg(info.lat.udeg / 1000000.0).arg(info.lon.udeg / 1000000.0)); QNetworkReply *reply = rgl->get(request); timer.setSingleShot(true); connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); timer.start(5000); // 5 secs. timeout loop.exec(); if(timer.isActive()) { timer.stop(); if(reply->error() > 0) { report_error("got error accessing geonames.org: %s", qPrintable(reply->errorString())); goto clear_reply; } int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (v < 200 || v >= 300) goto clear_reply; QByteArray fullReply = reply->readAll(); QJsonParseError errorObject; QJsonDocument jsonDoc = QJsonDocument::fromJson(fullReply, &errorObject); if (errorObject.error != QJsonParseError::NoError) { report_error("error parsing geonames.org response: %s", qPrintable(errorObject.errorString())); goto clear_reply; } QJsonObject obj = jsonDoc.object(); QVariant geoNamesObject = obj.value("geonames").toVariant(); QVariantList geoNames = geoNamesObject.toList(); if (geoNames.count() > 0) { QVariantMap firstData = geoNames.at(0).toMap(); int ri = 0, l3 = -1, lt = -1; if (ds->taxonomy.category == NULL) { ds->taxonomy.category = alloc_taxonomy(); } else { // clear out the data (except for the ocean data) int ocean; if ((ocean = taxonomy_index_for_category(&ds->taxonomy, TC_OCEAN)) > 0) { ds->taxonomy.category[0] = ds->taxonomy.category[ocean]; ds->taxonomy.nr = 1; } else { // ocean is -1 if there is no such entry, and we didn't copy above // if ocean is 0, so the following gets us the correct count ds->taxonomy.nr = ocean + 1; } } // get all the data - OCEAN is special, so start at COUNTRY for (int j = TC_COUNTRY; j < TC_NR_CATEGORIES; j++) { if (firstData[taxonomy_api_names[j]].isValid()) { ds->taxonomy.category[ri].category = j; ds->taxonomy.category[ri].origin = taxonomy::GEOCODED; free((void*)ds->taxonomy.category[ri].value); ds->taxonomy.category[ri].value = copy_string(qPrintable(firstData[taxonomy_api_names[j]].toString())); ri++; } } ds->taxonomy.nr = ri; l3 = taxonomy_index_for_category(&ds->taxonomy, TC_ADMIN_L3); lt = taxonomy_index_for_category(&ds->taxonomy, TC_LOCALNAME); if (l3 == -1 && lt != -1) { // basically this means we did get a local name (what we call town), but just like most places // we didn't get an adminName_3 - which in some regions is the actual city that town belongs to, // then we copy the town into the city ds->taxonomy.category[ri].value = copy_string(ds->taxonomy.category[lt].value); ds->taxonomy.category[ri].origin = taxonomy::COPIED; ds->taxonomy.category[ri].category = TC_ADMIN_L3; ds->taxonomy.nr++; } mark_divelist_changed(true); } else { report_error("geonames.org did not provide reverse lookup information"); qDebug() << "no reverse geo lookup; geonames returned\n" << fullReply; } } else { report_error("timeout accessing geonames.org"); disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit())); reply->abort(); } // next check the oceans API to figure out the body of water request.setUrl(geonamesOceanURL.arg(uiLanguage(NULL)).arg(info.lat.udeg / 1000000.0).arg(info.lon.udeg / 1000000.0)); reply = rgl->get(request); connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); timer.start(5000); // 5 secs. timeout loop.exec(); if(timer.isActive()) { timer.stop(); if(reply->error() > 0) { report_error("got error accessing oceans API of geonames.org: %s", qPrintable(reply->errorString())); goto clear_reply; } int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (v < 200 || v >= 300) goto clear_reply; QByteArray fullReply = reply->readAll(); QJsonParseError errorObject; QJsonDocument jsonDoc = QJsonDocument::fromJson(fullReply, &errorObject); if (errorObject.error != QJsonParseError::NoError) { report_error("error parsing geonames.org response: %s", qPrintable(errorObject.errorString())); goto clear_reply; } QJsonObject obj = jsonDoc.object(); QVariant oceanObject = obj.value("ocean").toVariant(); QVariantMap oceanName = oceanObject.toMap(); if (oceanName["name"].isValid()) { int idx; if (ds->taxonomy.category == NULL) ds->taxonomy.category = alloc_taxonomy(); idx = taxonomy_index_for_category(&ds->taxonomy, TC_OCEAN); if (idx == -1) idx = ds->taxonomy.nr; if (idx < TC_NR_CATEGORIES) { ds->taxonomy.category[idx].category = TC_OCEAN; ds->taxonomy.category[idx].origin = taxonomy::GEOCODED; ds->taxonomy.category[idx].value = copy_string(qPrintable(oceanName["name"].toString())); if (idx == ds->taxonomy.nr) ds->taxonomy.nr++; } mark_divelist_changed(true); } } else { report_error("timeout accessing geonames.org"); disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit())); reply->abort(); } clear_reply: reply->deleteLater(); } rgl->deleteLater(); }
void Card::on_invoked(const bb::system::InvokeRequest& request) { qDebug() << "==== Card::onInvoked() START ===="; emit load_configuration(); QVariantMap metadata = request.metadata(); QString source = request.source().installId() + " - " + request.source().groupId(); QString listId = QString::number(request.listId()); QString action = request.action(); QString target = request.target(); QString uri = request.uri().toString(); QString data = QString::fromUtf8(request.data()); qDebug() << "==== Card::onInvoked(): action: " << action << data << ", uri: " << uri; if(action == "bb.action.VIEW") { JsonDataAccess jda; QVariantMap objectMap = (jda.loadFromBuffer(data)).toMap(); QVariantMap itemMap = objectMap["attributes"].toMap(); QString messageID1 = itemMap["messageid"].toString(); QString sourceID1 = itemMap["sourceId"].toString(); QString itemsFromJSON = Utilities::get_string_from_file("data/hub_items.json"); QVariantList itemsFromJSONList = jda.loadFromBuffer(itemsFromJSON).toList(); qDebug() << "**** Card::onInvoked: itemsFromJSONList: " << itemsFromJSONList.size() << ", sourceId1: " << sourceID1 << ", messageID1: " << messageID1; for(int index = 0; index < itemsFromJSONList.size(); index++) { QVariantMap attributes = itemsFromJSONList.at(index).toMap(); QString pageName = attributes["thePage"].toString(); QString theData = attributes["theData"].toString(); QString sourceID2 = attributes["sourceId"].toString(); qDebug() << "**** Card::onInvoked: thePage" << pageName << ", theData: " << theData << ", sourceId2: " << sourceID2; if (sourceID2 == messageID1 || sourceID2 == sourceID1) { InvokeRequest request2; request2.setTarget("com.nemory.Insta10HeadlessService"); request2.setAction("bb.action.MARKREAD"); request2.setMimeType("hub/item"); request2.setUri(QUrl("pim:")); QByteArray bytes; jda.saveToBuffer(objectMap, &bytes); request2.setData(bytes); InvokeTargetReply *reply = _invoke_manager->invoke(request2); if (!reply) { qDebug() << "**** FAILED Card::onInvoked: " << reply->errorCode(); reply->deleteLater(); } QmlDocument *pageDocument = QmlDocument::create("asset:///pages/" + pageName).parent(this); _page = pageDocument->createRootObject<Page>(); _page->setProperty("is_card", true); //_page->setActionBarVisibility((getSetting("backButton", "false") == "false") ? ChromeVisibility::Hidden : ChromeVisibility::Default); _navigation_pane->push(_page); Application::instance()->setScene(_navigation_pane); emit initialize_card(); emit opened_item(attributes, theData); break; } } jda.deleteLater(); } else if(action == "bb.action.COMPOSE") { } else if(action == "bb.action.SHARE") { startHeadless(); } else { startHeadless(); } }
/*! * \brief Executes a command from telnet interface */ void TelnetSocket::execute(const QString &command) { QString arguments; Console::Command cmd = parseCommand(command, arguments); switch (cmd) { case Console::Empty: show(QString()); break; case Console::Help: show(helpMessage(arguments == QLatin1String("0"))); break; case Console::Quit: show(quitMessage(), false); disconnectFromHost(); break; case Console::Kill: show(quitMessage(), false); disconnectFromHost(); Console::execute(Console::Kill); break; case Console::Download: { QVariantList arg; arg.append(QVariant::fromValue(arguments)); arg.append(QVariant::fromValue(true)); if (Console::execute(Console::Download, arg)) show(color(tr("Link '%1' added").arg(arguments), Cyan)); else show(color(tr("Failed to add link '%1'").arg(arguments), Red)); } break; case Console::StartTask: case Console::PauseTask: case Console::StopTask: case Console::DeleteTask: { QVariantList arg; arg.append(QVariant::fromValue(arguments.toInt())); if (Console::execute(cmd, arg)) show(color(tr("Done"), Cyan)); else show(color(tr("Invalid task ID : '%1'").arg(arguments.toInt()), Red)); } break; case Console::GetProperty: { QVariantList arg; QVariant result; arg.append(QVariant::fromValue(arguments)); if (Console::execute(cmd, arg, &result)) show(color(tr("%1 : %2").arg(arguments).arg(result.toString()), Cyan)); else show(color(tr("Invalid property : '%1'").arg(arguments), Red)); } break; case Console::SetProperty: { QVariantList arg; arg.append(QVariant::fromValue(arguments.section(QLatin1Char(' '), 0, 0))); arg.append(QVariant::fromValue(arguments.section(QLatin1Char(' '), 1, 1).toInt())); if (Console::execute(cmd, arg)) show(color(tr("Done"), Cyan)); else show(color(tr("Invalid property : '%1'").arg(arguments), Red)); } break; case Console::Status: { /// \todo ugly here QStringList title; QList<QStringList> list; title.append(tr("ID")); title.append(tr("State")); title.append(tr("File")); title.append(tr("%")); title.append(tr("Size")); title.append(tr("DownloadTime")); const TaskManager::Tasks &tasks = TaskManager::getInstance()->getTasks(); for (auto iter = tasks.constBegin(); iter != tasks.constEnd(); ++iter) { QStringList item; item.append(QString::number(iter.key())); item.append(iter.value()->getStateString()); item.append(iter.value()->getName()); item.append(Utility::HumanReadable::formatPercent(iter.value()->getProgress())); item.append(Utility::HumanReadable::formatByte(iter.value()->getSize())); item.append(QString::number(iter.value()->getTransferTime())); list.append(item); } // get the max width for each column QList<int> width; foreach (const QString &columnName, title) width.append(columnName.size()); foreach (const QStringList &item, list) for (int i = 0; i < item.size(); ++i) width[i] = qMax(width[i], item[i].size()); // padding for (int i = 0; i < width.size(); ++i) width[i] += 3; QString result; // title for (int i = 0; i < title.size(); ++i) result.append(title[i].rightJustified(width[i])); result = color(result, Cyan); result.append(QLatin1Char('\n')); // items foreach (const QStringList &item, list) { for (int i = 0; i < item.size(); ++i) result.append(item[i].rightJustified(width[i])); result.append(QLatin1Char('\n')); } // global statistics result.append(tr("Download Rate : %1/s Upload Rate : %2/s") .arg(Utility::HumanReadable::formatByte(Network::TrafficManager::getInstance()->getDownloadRate())) .arg(Utility::HumanReadable::formatByte(Network::TrafficManager::getInstance()->getUploadRate()))); show(result); } break; default: show(color(tr("Invalid command '%1'\n\n").arg(command), Red) + helpMessage(true)); break; } }
int HtmlExporter::exportSelected(bool open) { int exported = 0, totalToExport = 0, currentPage = 0, totalPages = 0, exportedPage = 0; QString filename = saveHtmlFileDialog(); QString basename = QFileInfo(filename).fileName(); qDebug() << "exportSelectedHtml" << filename; if(filename.isEmpty()) return 0; const QItemSelection sel = controller->getSelection(); for(QItemSelectionRange rng : sel) totalToExport += rng.height(); totalPages = static_cast<int>(std::ceil(static_cast<float>(totalToExport) / static_cast<float>(pageSize))); if(!askOverwriteDialog(filename, totalPages)) return exported; QFile file(filename); QXmlStreamWriter stream; if(!startFile(file, basename, stream, currentPage, totalPages)) return exported; QVector<const Column *> columnList = controller->getCurrentColumns(); QVector<int> visualColumnIndex; for(QItemSelectionRange rng : sel) for(int row = rng.top(); row <= rng.bottom(); ++row) { if(exportedPage == 0) { // Create an index that maps the (probably reordered) columns of the // view to the model createVisualColumnIndex(columnList.size(), visualColumnIndex); writeHtmlTableHeader(stream, headerNames(columnList.size(), visualColumnIndex)); } exportedPage++; stream.writeStartElement("tr"); if((exported % 2) == 1) // Write alternating color class stream.writeAttribute("class", "alt"); QVariantList values = controller->getFormattedModelData(row); for(int col = 0; col < values.size(); ++col) { int physIndex = visualColumnIndex[col]; if(physIndex != -1) writeHtmlTableCellRaw(stream, columnList.at(physIndex)->getColumnName(), values.at(physIndex).toString(), exported); } stream.writeEndElement(); // tr exported++; if((exported % pageSize) == 0) { endFile(file, basename, stream, currentPage, totalPages); currentPage++; exportedPage = 0; file.setFileName(filenameForPage(filename, currentPage)); if(!startFile(file, basename, stream, currentPage, totalPages)) return exported; } } endFile(file, basename, stream, currentPage, totalPages); if(open) openDocument(filename); return exported; }
ConnSettingsValue *IAPConfPrivate::variantToValue(const QVariant &variant) { // Convert variant to ConnSettingsValue ConnSettingsValue *value = conn_settings_value_new(); if (value == 0) { qWarning("IAPConf: Unable to create new ConnSettingsValue"); return 0; } switch(variant.type()) { case QVariant::Invalid: value->type = CONN_SETTINGS_VALUE_INVALID; break; case QVariant::String: { char *valueStr = strdup(QSTRING_TO_CONST_CSTR(variant.toString())); value->type = CONN_SETTINGS_VALUE_STRING; value->value.string_val = valueStr; break; } case QVariant::Int: value->type = CONN_SETTINGS_VALUE_INT; value->value.int_val = variant.toInt(); break; case QMetaType::Float: case QVariant::Double: value->type = CONN_SETTINGS_VALUE_DOUBLE; value->value.double_val = variant.toDouble(); break; case QVariant::Bool: value->type = CONN_SETTINGS_VALUE_BOOL; value->value.bool_val = variant.toBool() ? 1 : 0; break; case QVariant::ByteArray: { QByteArray array = variant.toByteArray(); value->type = CONN_SETTINGS_VALUE_BYTE_ARRAY; value->value.byte_array.len = array.size(); value->value.byte_array.val = (unsigned char *)malloc(array.size()); memcpy(value->value.byte_array.val, array.constData(), array.size()); break; } case QVariant::List: { QVariantList list = variant.toList(); ConnSettingsValue **list_val = (ConnSettingsValue **)malloc( (list.size() + 1) * sizeof(ConnSettingsValue *)); for (int idx = 0; idx < list.size(); idx++) { list_val[idx] = variantToValue(list.at(idx)); } list_val[list.size()] = 0; value->type = CONN_SETTINGS_VALUE_LIST; value->value.list_val = list_val; break; } default: qWarning("IAPConf: Can not handle QVariant of type %d", variant.type()); conn_settings_value_destroy(value); return 0; } return value; }
Client::DataList Client::getData(const string& query) { QJsonDocument root; QString temp = QString::fromStdString(query); QByteArray bytearray = query.c_str(); QString query_string = QString::fromUtf8(bytearray.data(), bytearray.size()); qDebug() << "query_string: " << query_string; QString uri = getQueryString(query_string); qDebug() << "uri: " << uri; get(uri, root); DataList result; QVariantMap variant = root.toVariant().toMap(); // Iterate through the weather data for (const QVariant &i : variant["businesses"].toList()) { QVariantMap item = i.toMap(); QString name = removeTestInfo(item["name"].toString()); qDebug() << "name: " << name; QString business_url = item["business_url"].toString(); qDebug() << "business_url: " << business_url; QString s_photo_url = item["s_photo_url"].toString(); qDebug() << "s_photo_url: " << s_photo_url; QString photo_url = item["photo_url"].toString(); qDebug() << "photo_url: " << photo_url; QString rating_s_img_url = item["rating_s_img_url"].toString(); qDebug() << "rating_s_img_url: " << rating_s_img_url; QString address = item["address"].toString(); qDebug() << "address: " << address; QString telephone = item["telephone"].toString(); qDebug() << "telephone: " << telephone; QVariantList deals = item["deals"].toList(); QString summary; if ( deals.count() > 0 ) { QVariantMap temp = deals.first().toMap(); summary = temp["description"].toString(); } qDebug() << "summary: " << summary; // Add a result to the weather list result.emplace_back( Data { name.toStdString(), business_url.toStdString(), s_photo_url.toStdString(), photo_url.toStdString(), rating_s_img_url.toStdString(), address.toStdString(), telephone.toStdString(), summary.toStdString() }); } return result; }
void TestDeltaT::historicalTest() { // test data from http://eclipse.gsfc.nasa.gov/SEcat5/deltat.html#tab1 QVariantList data; data << -500 << 17190 << 430; data << -400 << 15530 << 390; data << -300 << 14080 << 360; data << -200 << 12790 << 330; data << -100 << 11640 << 290; data << 0 << 10580 << 260; data << 100 << 9600 << 240; data << 200 << 8640 << 210; data << 300 << 7680 << 180; data << 400 << 6700 << 160; data << 500 << 5710 << 140; data << 600 << 4740 << 120; data << 700 << 3810 << 100; data << 800 << 2960 << 80; data << 900 << 2200 << 70; data << 1000 << 1570 << 55; data << 1100 << 1090 << 40; data << 1200 << 740 << 30; data << 1300 << 490 << 20; data << 1400 << 320 << 20; data << 1500 << 200 << 20; data << 1600 << 120 << 20; data << 1700 << 9 << 5; data << 1750 << 13 << 2; data << 1800 << 14 << 1; data << 1850 << 7 << 1; data << 1900 << -3 << 1; data << 1950 << 29 << 0.1; data << 1955 << 31.1 << 0.1; data << 1960 << 33.2 << 0.1; data << 1965 << 35.7 << 0.1; data << 1970 << 40.2 << 0.1; data << 1975 << 45.5 << 0.1; data << 1980 << 50.5 << 0.1; data << 1985 << 54.3 << 0.1; data << 1990 << 56.9 << 0.1; data << 1995 << 60.8 << 0.1; data << 2000 << 63.8 << 0.1; data << 2005 << 64.7 << 0.1; while(data.count() >= 3) { int year = data.takeFirst().toInt(); int yout, mout, dout; double JD; double expectedResult = data.takeFirst().toDouble(); double acceptableError = data.takeFirst().toDouble(); StelUtils::getJDFromDate(&JD, year, 1, 1, 0, 0, 0); double result = StelUtils::getDeltaTByEspenakMeeus(JD); double actualError = std::abs(expectedResult) - std::abs(result); StelUtils::getDateFromJulianDay(JD, &yout, &mout, &dout); QVERIFY2(actualError <= acceptableError, QString("date=%2 year=%3 result=%4 error=%5 acceptable=%6") .arg(QString("%1-%2-%3 00:00:00").arg(yout).arg(mout).arg(dout)) .arg(year) .arg(result) .arg(actualError) .arg(acceptableError) .toUtf8()); } }
/*static*/ PyObject * PythonScript::VariantToPython(const QVariant & v) { int i; QVariantList::const_iterator iList; QVariantList list; #if QT_VERSION >= 0x040500 QVariantHash::const_iterator iHash; QVariantHash hash; #endif QVariantMap::const_iterator iMap; QVariantMap map; PyObject * pyList, * pyDict; if (v.isNull()) Py_RETURN_NONE; switch ((QMetaType::Type)v.type()) { case QVariant::Double: return Py_BuildValue("d", v.toDouble()); case QVariant::Bool: if (v.toBool()) Py_RETURN_TRUE; else Py_RETURN_FALSE; case QVariant::Int: return Py_BuildValue("i", v.toInt()); case QVariant::LongLong: return Py_BuildValue("L", v.toLongLong()); case QVariant::UInt: return Py_BuildValue("I", v.toUInt()); case QVariant::ULongLong: return Py_BuildValue("K", v.toULongLong()); case QVariant::Char: case QVariant::String: #ifdef Py_UNICODE_WIDE { QVector<uint> tmp = v.toString().toUcs4(); return Py_BuildValue("u#", tmp.constData(), tmp.count()); } #else return Py_BuildValue("u", v.toString().constData()); #endif case QVariant::List: case QVariant::StringList: list = v.toList(); pyList = PyList_New(list.size()); for (i = 0, iList = list.begin(); iList != list.end(); ++iList, ++i) { PyList_SetItem(pyList, i, PythonScript::VariantToPython(*iList)); } return pyList; #if QT_VERSION >= 0x040500 case QVariant::Hash: hash = v.toHash(); pyDict = PyDict_New(); for (iHash = hash.begin(); iHash != hash.end(); ++iHash) { PyDict_SetItemString(pyDict, qPrintable(iHash.key()), PythonScript::VariantToPython(iHash.value())); } return pyDict; #endif case QVariant::Map: map = v.toMap(); pyDict = PyDict_New(); for (iMap = map.begin(); iMap != map.end(); ++iMap) { PyDict_SetItemString(pyDict, qPrintable(iMap.key()), PythonScript::VariantToPython(iMap.value())); } return pyDict; case QMetaType::QObjectStar: return PythonScript::QObjectToPython(v.value<QObject*>()); #if QT_VERSION < 0x050000 case QMetaType::QWidgetStar: return PythonScript::QObjectToPython(qobject_cast<QObject*>(v.value<QWidget*>())); #endif default: PyErr_Format(PyExc_TypeError, qPrintable(tr("the type %s is currently not supported")), v.typeName()); return NULL; } Py_RETURN_NONE; }
void ChatList::updateContent() { m_model->clear(); if (m_filter & 1) { for (int i = 0; i < m_dialogs->size(); i++) { //Chat* chat = m_dialogs->value(i); m_model->insert(m_dialogs->value(i)); } } if ((m_filter & 2) && m_model->size() && m_searchText.size()) { QVariantList it = m_model->last(); while(!it.empty()) { Peer* contact = (Peer*)m_model->data(it).value<QObject*>(); if (contact->title().indexOf(m_searchText) == -1) { QVariantList toRemove = it; it = m_model->before(it); m_model->removeAt(toRemove); continue; } else it = m_model->before(it); } } /*if ((m_filter & 4) && m_model->size() && m_searchText.size()) { QVariantList it = m_model->last(); while(!it.empty()) { Chat* contact = (Chat*)m_model->data(it).value<QObject*>(); GroupDataModel* messages = (GroupDataModel*)contact->messages(); bool found = false; for (QVariantList indexPath = messages->first(); !indexPath.isEmpty(); indexPath = messages->after(indexPath)) { Message* message = (Message*)messages->data(indexPath).value<QObject*>(); if (message->text().indexOf(m_searchText) != -1) { found = true; break; } } if(!found) { QVariantList toRemove = it; it = m_model->before(it); m_model->removeAt(toRemove); Storage::instance()->searchMessage(contact, 0, contact->lastMessageDate().toTime_t(), 1, 0, m_searchText.toUtf8().data()); } else it = m_model->before(it); } }*/ emit contentUpdated(); }
int main(int argc, char **argv) { enum ExitCode { /** * We start from 2, because QApplicationArgumentParser * uses 1. */ QueryFailure = 2, StdOutFailure }; const QCoreApplication app(argc, argv); QCoreApplication::setApplicationName(QLatin1String("xmlpatterns")); QXmlNamePool namePool; PatternistApplicationParser parser(argc, argv, namePool); parser.setApplicationDescription(QLatin1String("A tool for running XQuery queries.")); parser.setApplicationVersion(QLatin1String("0.1")); QApplicationArgument param(QLatin1String("param"), QXmlPatternistCLI::tr("Binds an external variable. The value is directly available using the variable reference: $name."), qMetaTypeId<Parameter>()); param.setMaximumOccurrence(-1); parser.addArgument(param); const QApplicationArgument noformat(QLatin1String("no-format"), QXmlPatternistCLI::tr("By default output is formatted for readability. When specified, strict serialization is performed.")); parser.addArgument(noformat); const QApplicationArgument isURI(QLatin1String("is-uri"), QXmlPatternistCLI::tr("If specified, all filenames on the command line are interpreted as URIs instead of a local filenames.")); parser.addArgument(isURI); const QApplicationArgument initialTemplateName(QLatin1String("initial-template"), QXmlPatternistCLI::tr("The name of the initial template to call as a Clark Name."), QVariant::String); parser.addArgument(initialTemplateName); /* The temporary object is required to compile with g++ 3.3. */ QApplicationArgument queryURI = QApplicationArgument(QLatin1String("query/stylesheet"), QXmlPatternistCLI::tr("A local filename pointing to the query to run. If the name ends with .xsl it's assumed " "to be an XSL-T stylesheet. If it ends with .xq, it's assumed to be an XQuery query. (In " "other cases it's also assumed to be an XQuery query, but that interpretation may " "change in a future release of Qt.)"), QVariant::String); queryURI.setMinimumOccurrence(1); queryURI.setNameless(true); parser.addArgument(queryURI); QApplicationArgument focus = QApplicationArgument(QLatin1String("focus"), QXmlPatternistCLI::tr("The document to use as focus. Mandatory " "in case a stylesheet is used. This option is " "also affected by the is-uris option."), QVariant::String); focus.setMinimumOccurrence(0); focus.setNameless(true); parser.addArgument(focus); QApplicationArgument output(QLatin1String("output"), QXmlPatternistCLI::tr("A local file to which the output should be written. " "The file is overwritten, or if not exist, created. " "If absent, stdout is used."), qMetaTypeId<QIODevice *>()); parser.addArgument(output); if(!parser.parse()) return parser.exitCode(); /* Get the query URI. */ const QUrl effectiveURI(finalizeURI(parser, isURI, queryURI)); QXmlQuery::QueryLanguage lang; if(effectiveURI.toString().endsWith(QLatin1String(".xsl"))) lang = QXmlQuery::XSLT20; else lang = QXmlQuery::XQuery10; if(lang == QXmlQuery::XQuery10 && parser.has(initialTemplateName)) { parser.message(QXmlPatternistCLI::tr("An initial template name cannot be specified when running an XQuery.")); return QApplicationArgumentParser::ParseError; } QXmlQuery query(lang, namePool); query.setInitialTemplateName(qVariantValue<QXmlName>(parser.value(initialTemplateName))); /* Bind external variables. */ { const QVariantList parameters(parser.values(param)); const int len = parameters.count(); /* For tracking duplicates. */ QSet<QString> usedParameters; for(int i = 0; i < len; ++i) { const Parameter p(qVariantValue<Parameter>(parameters.at(i))); if(usedParameters.contains(p.first)) { parser.message(QXmlPatternistCLI::tr("Each parameter must be unique, %1 is specified at least twice.").arg(p.first)); return QApplicationArgumentParser::ParseError; } else { usedParameters.insert(p.first); query.bindVariable(p.first, QXmlItem(p.second)); } } } if(parser.has(focus)) { if(!query.setFocus(finalizeURI(parser, isURI, focus))) return QueryFailure; } else if(lang == QXmlQuery::XSLT20 && !parser.has(initialTemplateName)) { parser.message(QXmlPatternistCLI::tr("When a stylesheet is used, a " "document must be specified as a focus, or an " "initial template name must be specified, or both.")); return QApplicationArgumentParser::ParseError; } query.setQuery(effectiveURI); const QPatternist::AutoPtr<QIODevice> outDevice(qVariantValue<QIODevice *>(parser.value(output))); Q_ASSERT(outDevice); Q_ASSERT(outDevice->isWritable()); if(query.isValid()) { typedef QPatternist::AutoPtr<QAbstractXmlReceiver> RecPtr; RecPtr receiver; if(parser.has(noformat)) receiver = RecPtr(new QXmlSerializer(query, outDevice.data())); else receiver = RecPtr(new QXmlFormatter(query, outDevice.data())); const bool success = query.evaluateTo(receiver.data()); if(success) return parser.exitCode(); else return QueryFailure; } else return QueryFailure; }
void Client::batch_get(const net::Uri::Path &path, const net::Uri::QueryParameters ¶meters, const std::deque<std::string> &ids, QVariantList &results) { // Create a new HTTP client auto client = http::make_client(); // Start building the request configuration http::Request::Configuration configuration; configuration.uri = config_->apidomain + "/batch"; std::string boundary = "batch_boundary_fnord"; configuration.header.add("Authorization", "Bearer " + access_token()); configuration.header.add("User-Agent", config_->user_agent); configuration.header.add("Content-Type", "multipart/mixed; boundary=" + boundary); std::stringstream ss; int i = 0; for (const std::string& id : ids) { ss << "--" << boundary << "\n"; ss << "Content-Type: application/http\n"; ss << "Content-ID: <" << i << ":" << id << "@rschroll.developer.ubuntu.com>\n\n"; net::Uri::Path p(path); p.emplace_back(id); net::Uri uri = net::make_uri(config_->apiroot, p, parameters); ss << "GET " << client->uri_to_string(uri) << "\n\n"; i += 1; } ss << "--" << boundary << "--\n"; // Build a HTTP request object from our configuration auto request = client->post(configuration, ss.str(), "multipart/mixed"); try { // Synchronously make the HTTP request // We bind the cancellable callback to #progress_report auto response = request->execute( std::bind(&Client::progress_report, this, std::placeholders::_1)); std::cerr << configuration.uri << std::endl; // Check that we got a sensible HTTP status code if (response.status != http::Status::ok) { throw std::domain_error(response.body); } QString response_body(response.body.c_str()); // Is there no way to inspect the header? We assume that the first line is a boundary marker. QString boundary = response_body.section("\r\n", 0, 0); QStringList response_parts = response_body.split(boundary); // We assume the parts come back in the same order. This isn't guaranteed. We could look // at the Content-ID of each part, in which is embedded the index of the original message. // But for right now, this seems to work. for (const QString part : response_parts) { QString payload = part.section("\r\n\r\n", 2, -1); if (payload != "") { QJsonDocument root = QJsonDocument::fromJson(payload.toUtf8()); results.append(root.toVariant()); } } } catch (net::Error &) { } }
QT_BEGIN_NAMESPACE QVariant convertValue(GVariant *value) { if (!value) return QVariant(QVariant::Invalid); switch (g_variant_classify(value)) { case G_VARIANT_CLASS_BOOLEAN: return QVariant((bool)g_variant_get_boolean(value)); case G_VARIANT_CLASS_BYTE: return QVariant(QLatin1Char(g_variant_get_byte(value))); case G_VARIANT_CLASS_INT16: return QVariant((int)g_variant_get_int16(value)); case G_VARIANT_CLASS_UINT16: return QVariant((uint)g_variant_get_uint16(value)); case G_VARIANT_CLASS_INT32: return QVariant((int)g_variant_get_int32(value)); case G_VARIANT_CLASS_UINT32: return QVariant((uint)g_variant_get_uint32(value)); case G_VARIANT_CLASS_INT64: return QVariant((qlonglong)g_variant_get_int64(value)); case G_VARIANT_CLASS_UINT64: return QVariant((qulonglong)g_variant_get_uint64(value)); case G_VARIANT_CLASS_DOUBLE: return QVariant(g_variant_get_double(value)); case G_VARIANT_CLASS_STRING: return QVariant(QString::fromUtf8(g_variant_get_string(value, NULL))); case G_VARIANT_CLASS_ARRAY: if (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING_ARRAY)) { GVariantIter iter; QStringList list; const gchar *str; g_variant_iter_init(&iter, value); while (g_variant_iter_next(&iter, "&s", &str)) list.append(QString::fromUtf8(str)); return QVariant(list); } else if (g_variant_is_of_type(value, G_VARIANT_TYPE_BYTESTRING_ARRAY)) { GVariantIter iter; QVariantList list; const gchar *item; g_variant_iter_init(&iter, value); while (g_variant_iter_next(&iter, "&y", &item)) list.append(QByteArray(item)); return list; #ifndef QT_NO_DATASTREAM } else if (g_variant_is_of_type(value, G_VARIANT_TYPE_BYTESTRING)) { QByteArray a(g_variant_get_bytestring(value)); QDataStream s(&a, QIODevice::ReadOnly); s.setVersion(QDataStream::Qt_4_0); QVariant result; s >> result; return result; #else Q_ASSERT(!"QConfiguration: Cannot load custom types without QDataStream support"); #endif } default: break; } return QVariant(QVariant::Invalid); }
int DatabaseHelper::addPaper(const Paper& paper) { int bookTitleId = getBookTitleId(paper.getBookTitle()); if (bookTitleId == -1) { bookTitleId = addBookTitle(paper.getBookTitle()); } vector<int> authorsId(paper.getAuthors().size()); for (vector<int>::size_type i = 0; i < paper.getAuthors().size(); ++i) { const string& author = paper.getAuthors().at(i); int authorId = getAuthorId(author); if (authorId == -1) { authorId = addAuthor(author); } authorsId[i] = authorId; } vector<int> tagsId(paper.getTags().size()); for (vector<int>::size_type i = 0; i < paper.getTags().size(); ++i) { const string& tag = paper.getTags().at(i); int tagId = getTagId(tag); if (tagId == -1) { tagId = addTag(tag); } tagsId[i] = tagId; } QSqlQuery query; if (paper.getId() <= 0) { query.prepare("INSERT INTO pl_paper(year, book_title_id, title, path, comment) " "VALUES(:year, :book_title_id, :title, :path, :comment)"); query.bindValue(":year", paper.getYear()); query.bindValue(":book_title_id", bookTitleId); query.bindValue(":title", paper.getTitle().c_str()); query.bindValue(":path", paper.getPath().c_str()); query.bindValue(":comment", paper.getComment().c_str()); } else { query.prepare("INSERT INTO pl_paper(paper_id, year, book_title_id, title, path, comment) " "VALUES(:paper_id, :year, :book_title_id, :title, :path, :comment)"); query.bindValue(":paper_id", paper.getId()); query.bindValue(":year", paper.getYear()); query.bindValue(":book_title_id", bookTitleId); query.bindValue(":title", paper.getTitle().c_str()); query.bindValue(":path", paper.getPath().c_str()); query.bindValue(":comment", paper.getComment().c_str()); } query.exec(); int paperId = query.lastInsertId().toInt(); QVariantList paperIdList, authorIdList; for (int i = 0; i < static_cast<int>(authorsId.size()); ++i) { paperIdList.append(paperId); authorIdList.append(authorsId[i]); } query.prepare("INSERT INTO pl_paper2author(paper_id, author_id) " "VALUES(:paper_id, :author_id)"); query.bindValue(":paper_id", paperIdList); query.bindValue(":author_id", authorIdList); query.execBatch(); paperIdList.clear(); QVariantList tagIdList; for (int i = 0; i < static_cast<int>(tagsId.size()); ++i) { paperIdList.append(paperId); tagIdList.append(tagsId[i]); } query.prepare("INSERT INTO pl_paper2tag(paper_id, tag_id) " "VALUES(:paper_id, :tag_id)"); query.bindValue(":paper_id", paperIdList); query.bindValue(":tag_id", tagIdList); query.execBatch(); return paperId; }