int CreateFunction::writeToDB(const QByteArray &pdata, const QString pkgname, QString &errMsg) { if (DEBUG) qDebug("CreateFunction::writeToDb(%s, %s, &errMsg)", pdata.data(), qPrintable(pkgname)); QSqlQuery oidq; QMap<QString,int> oldoids; if (! pkgname.isEmpty()) { oidq.prepare("SELECT pg_proc.oid, oidvectortypes(proargtypes) " "FROM pg_proc, pg_namespace " "WHERE ((pg_namespace.oid=pronamespace)" " AND (proname=:name)" " AND (nspname=:schema));"); oidq.bindValue(":name", _name); oidq.bindValue(":schema", pkgname); oidq.exec(); while (oidq.next()) { oldoids.insert(oidq.value(1).toString(), oidq.value(0).toInt()); } if (oidq.lastError().type() != QSqlError::NoError) { errMsg = _sqlerrtxt.arg(_filename) .arg(oidq.lastError().databaseText()) .arg(oidq.lastError().driverText()); return -1; } if (DEBUG) { QMap<QString, int>::const_iterator i = oldoids.constBegin(); while (i != oldoids.constEnd()) { qDebug("CreateFunction::writeToDB() %s(%s) -> %d", qPrintable(_name), qPrintable(i.key()), i.value()); i++; } } } int returnVal = Script::writeToDB(pdata, pkgname, errMsg); if (returnVal < 0) return returnVal; if (! pkgname.isEmpty()) { QSqlQuery select; int pkgheadid = -1; select.prepare("SELECT pkghead_id FROM pkghead WHERE (pkghead_name=:name);"); select.bindValue(":name", pkgname); select.exec(); if (select.first()) pkgheadid = select.value(0).toInt(); else if (select.lastError().type() != QSqlError::NoError) { errMsg = _sqlerrtxt.arg(_filename) .arg(select.lastError().databaseText()) .arg(select.lastError().driverText()); return -4; } oidq.exec(); // reuse the query int count = 0; while (oidq.next()) { if (DEBUG) qDebug("CreateFunction::writeToDB() oid = %d, argtypes = %s", oidq.value(0).toInt(), qPrintable(oidq.value(1).toString())); int tmp = upsertPkgItem(pkgheadid, oldoids, oidq.value(1).toString(), oidq.value(0).toInt(), errMsg); if (tmp < 0) return tmp; count++; } if (oidq.lastError().type() != QSqlError::NoError) { errMsg = _sqlerrtxt.arg(_filename) .arg(oidq.lastError().databaseText()) .arg(oidq.lastError().driverText()); return -5; } if (count == 0) { errMsg = TR("Could not find function %1 in the database for package %2. " "The script %3 does not match the contents.xml description.") .arg(_name).arg(pkgname).arg(_filename); return -6; } } return 0; }
bool SASLAuthFeature::xmppStanzaIn(IXmppStream *AXmppStream, Stanza &AStanza, int AOrder) { if (AXmppStream==FXmppStream && AOrder==XSHO_XMPP_FEATURE) { if (AStanza.kind() == "challenge") { QByteArray challengeData = QByteArray::fromBase64(AStanza.element().text().toLatin1()); LOG_STRM_DEBUG(FXmppStream->streamJid(),QString("SASL auth challenge received: %1").arg(QString::fromUtf8(challengeData))); QMap<QByteArray, QByteArray> responseMap; QMap<QByteArray, QByteArray> challengeMap = parseChallenge(challengeData); if (challengeMap.value("qop") == "auth") { QByteArray randBytes(32,' '); for (int i=0; i<randBytes.size(); i++) randBytes[i] = (char) (256.0 * qrand() / (RAND_MAX + 1.0)); responseMap["cnonce"] = randBytes.toHex(); if (challengeMap.contains("realm")) responseMap["realm"] = challengeMap.value("realm"); else responseMap["realm"] = FXmppStream->streamJid().pDomain().toUtf8(); responseMap["username"] = FXmppStream->streamJid().pNode().toUtf8(); responseMap["nonce"] = challengeMap.value("nonce"); responseMap["nc"] = "00000001"; responseMap["qop"] = "auth"; responseMap["digest-uri"] = QString("xmpp/%1").arg(FXmppStream->streamJid().pDomain()).toUtf8(); responseMap["charset"] = "utf-8"; responseMap["response"] = getResponseValue(responseMap,FXmppStream->password()); } QByteArray responseData = serializeResponse(responseMap); Stanza response("response",NS_FEATURE_SASL); response.element().appendChild(response.createTextNode(responseData.toBase64())); FXmppStream->sendStanza(response); LOG_STRM_DEBUG(FXmppStream->streamJid(),QString("SASL auth response sent: %1").arg(QString::fromUtf8(responseData))); } else { FXmppStream->removeXmppStanzaHandler(XSHO_XMPP_FEATURE,this); if (AStanza.kind() == "success") { LOG_STRM_INFO(FXmppStream->streamJid(),"Authorization successes"); deleteLater(); emit finished(true); } else if (AStanza.kind() == "failure") { XmppSaslError err(AStanza.element()); LOG_STRM_WARNING(FXmppStream->streamJid(),QString("Authorization failed: %1").arg(err.condition())); emit error(err); } else { XmppError err(IERR_SASL_AUTH_INVALID_RESPONSE); LOG_STRM_WARNING(FXmppStream->streamJid(),QString("Authorization error: Invalid stanza kind=%1").arg(AStanza.kind())); emit error(err); } } return true; } return false; }
bool HsMenuClientPrivate::add(const QVariantMap &entryPreference) { bool result = false; QMap<QString, QVariant> pref = entryPreference; CaIconDescription iconDesc; if(pref.contains(hsItemId)) { QSharedPointer<CaEntry> update_entry = CaService::instance()->getEntry(pref.take(hsItemId).toInt()); if(pref.contains(hsItemLocName)) { update_entry->setText(pref.take(hsItemLocName).toString(),true); } else { update_entry->setText(pref.take(hsItemName).toString()); } if(pref.contains(hsItemLocDescription)) { update_entry->setDescription(pref.take(hsItemLocDescription).toString(), true); } else { update_entry->setDescription(pref.take(hsItemDescription).toString()); } iconDesc.setFilename(pref.take(hsIconFileName).toString()); iconDesc.setSkinId(pref.take(hsIconName).toString()); iconDesc.setApplicationId(pref.take(hsIconApplicationId).toString()); update_entry->setIconDescription(iconDesc); QMapIterator<QString, QVariant> k(pref); while (k.hasNext()) { k.next(); update_entry->setAttribute(k.key(),k.value().toString()); } result = CaService::instance()->updateEntry(*update_entry); } else if ((pref.contains(hsItemName) || pref.contains(hsItemLocName)) && pref.contains(hsitemLaunchUri) && pref.contains(hsitemPublisherId)) { CaEntry add_entry(ItemEntryRole); add_entry.setEntryTypeName(Hs::templatedApplicationTypeName); // mandatory values if(pref.contains(hsItemLocName)) { add_entry.setText(pref.take(hsItemLocName).toString(),true); } else { add_entry.setText(pref.take(hsItemName).toString()); } iconDesc.setFilename(pref.take(hsIconFileName).toString()); iconDesc.setSkinId(pref.take(hsIconName).toString()); iconDesc.setApplicationId(pref.take(hsIconApplicationId).toString()); add_entry.setIconDescription(iconDesc); if(pref.contains(hsItemLocDescription)) { add_entry.setDescription(pref.take(hsItemLocDescription).toString(), true); } else { add_entry.setDescription(pref.take(hsItemDescription).toString()); } QMapIterator<QString, QVariant> k(pref); while (k.hasNext()) { k.next(); add_entry.setAttribute(k.key(),k.value().toString()); } add_entry.setFlags(add_entry.flags() & ~RemovableEntryFlag); QSharedPointer<CaEntry> entry = CaService::instance()->createEntry(add_entry); if (!entry.isNull()) { result = true; } } else { return false; } return result; }
bool XMLParser::loadFile(QSharedPointer<AXRBuffer> file) { if (!d->controller) { throw AXRError("XMLParser", "The controller was not set on the XML parser"); } axr_log(LoggerChannelOverview, "XMLParser: loading file " + file->sourceUrl().toString()); if (!file->isValid()) { axr_log(LoggerChannelOverview, "XMLParser: failed to load file " + file->sourceUrl().toString()); return false; } try { // Parse the XML file... QXmlStreamReader xml(file->getBuffer()); while (!xml.atEnd() && !xml.hasError()) { xml.readNext(); if (xml.isStartElement()) { AXRString name = xml.name().toString(); axr_log(LoggerChannelXMLParser, "XMLParser: found opening tag with name " + name); d->controller->enterElement(name); Q_FOREACH (const QXmlStreamAttribute &attr, xml.attributes()) { d->controller->addAttribute(attr.name().toString(), attr.value().toString()); } } else if (xml.isEndElement()) { axr_log(LoggerChannelXMLParser, "XMLParser: found closing tag with name " + xml.name().toString()); d->controller->exitElement(); } else if (xml.isCharacters()) { axr_log(LoggerChannelXMLParser, AXRString("XMLParser: reading character data: \"%1\"").arg(xml.text().toString())); d->controller->appendContentText(xml.text().toString()); } else if (xml.isProcessingInstruction()) { AXRString instructionName = xml.processingInstructionTarget().toString(); axr_log(LoggerChannelXMLParser, "XMLParser: found XML instruction with name " + instructionName); // Probable HSS stylesheet encountered, try to load it into the controller if (instructionName == "xml-stylesheet") { QMap<AXRString, AXRString> instructionAttributes; // A little trickery to easily parse the key-value pairs from the instruction... // We basically embed the processing instruction value, which looks like a set of XML // attributes, within a fake XML tag to create a document that we can parse, allowing // the XML parser to handle the syntax instead of doing it manually QXmlStreamReader instructionParser(AXRString("<node %1 />").arg(xml.processingInstructionData().toString())); while (!instructionParser.atEnd() && !instructionParser.hasError()) { instructionParser.readNext(); if (instructionParser.isStartElement()) { // Read all the attributes from our fake tag, which are the xml-stylesheet parameters Q_FOREACH (const QXmlStreamAttribute &attr, instructionParser.attributes()) { instructionAttributes.insert(attr.name().toString(), attr.value().toString()); } } }
// This method will cause the class to rebuild its text representation. // based on the parent classifier object. // For any situation in which this is called, we are either building the code // document up, or replacing/regenerating the existing auto-generated parts. As // such, we will want to insert everything we resonablely will want // during creation. We can set various parts of the document (esp. the // comments) to appear or not, as needed. void DClassifierCodeDocument::updateContent() { // Gather info on the various fields and parent objects of this class... UMLClassifier * c = getParentClassifier(); Q_ASSERT(c != 0); CodeGenerationPolicy * commonPolicy = UMLApp::app()->commonPolicy(); CodeGenPolicyExt * pe = UMLApp::app()->policyExt(); DCodeGenerationPolicy * policy = dynamic_cast<DCodeGenerationPolicy*>(pe); // first, set the global flag on whether or not to show classfield info // This depends on whether or not we have attribute/association classes const CodeClassFieldList * cfList = getCodeClassFieldList(); CodeClassFieldList::const_iterator it = cfList->begin(); CodeClassFieldList::const_iterator end = cfList->end(); for (; it != end; ++it) { CodeClassField * field = *it; if (field->parentIsAttribute()) field->setWriteOutMethods(policy->getAutoGenerateAttribAccessors()); else field->setWriteOutMethods(policy->getAutoGenerateAssocAccessors()); } // attribute-based ClassFields // we do it this way to have the static fields sorted out from regular ones CodeClassFieldList staticAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true); CodeClassFieldList attribClassFields = getSpecificClassFields (CodeClassField::Attribute, false); // association-based ClassFields // don't care if they are static or not..all are lumped together CodeClassFieldList plainAssocClassFields = getSpecificClassFields (CodeClassField::PlainAssociation); CodeClassFieldList aggregationClassFields = getSpecificClassFields (CodeClassField::Aggregation); CodeClassFieldList compositionClassFields = getSpecificClassFields (CodeClassField::Composition); bool isInterface = parentIsInterface(); bool hasOperationMethods = false; UMLOperationList list = c->getOpList(); hasOperationMethods = ! list.isEmpty(); QString endLine = commonPolicy->getNewLineEndingChars(); // a shortcut..so we don't have to call this all the time // // START GENERATING CODE/TEXT BLOCKS and COMMENTS FOR THE DOCUMENT // // // PACKAGE CODE BLOCK // QString pkgs = getPackage(); pkgs.replace(QRegExp(QLatin1String("::")), QLatin1String(".")); QString packageText = getPackage().isEmpty() ? QString() : QString(QLatin1String("package ")+pkgs+QLatin1Char(';')+endLine); CodeBlockWithComments * pblock = addOrUpdateTaggedCodeBlockWithComments(QLatin1String("packages"), packageText, QString(), 0, false); if (packageText.isEmpty() && pblock->contentType() == CodeBlock::AutoGenerated) pblock->setWriteOutText(false); else pblock->setWriteOutText(true); // IMPORT CODEBLOCK // // Q: Why all utils? Aren't just List and Vector the only classes we are using? // A: doesn't matter at all; it is more readable to just include '*' and d compilers // don't slow down or anything. (TZ) QString importStatement; if (hasObjectVectorClassFields()) importStatement.append(QLatin1String("import d.util.*;")); //only import classes in a different package from this class UMLPackageList imports; QMap<UMLPackage*, QString> packageMap; // so we don't repeat packages CodeGenerator::findObjectsRelated(c, imports); for (UMLPackageListIt importsIt(imports); importsIt.hasNext();) { UMLPackage *con = importsIt.next(); // NO (default) datatypes in the import statement.. use defined // ones whould be possible, but no idea how to do that...at least for now. // Dynamic casting is slow..not an optimal way to do this. if (!packageMap.contains(con) && !con->isUMLDatatype()) { packageMap.insert(con, con->package()); // now, we DON'T need to import classes that are already in our own package // (that is, IF a package is specified). Otherwise, we should have a declaration. if (con->package() != c->package() || (c->package().isEmpty() && con->package().isEmpty())) { importStatement.append(endLine+QLatin1String("import ")); if (!con->package().isEmpty()) importStatement.append(con->package()+QLatin1Char('.')); importStatement.append(CodeGenerator::cleanName(con->name())+QLatin1Char(';')); } } } // now, add/update the imports codeblock CodeBlockWithComments * iblock = addOrUpdateTaggedCodeBlockWithComments(QLatin1String("imports"), importStatement, QString(), 0, false); if (importStatement.isEmpty() && iblock->contentType() == CodeBlock::AutoGenerated) iblock->setWriteOutText(false); else iblock->setWriteOutText(true); // CLASS DECLARATION BLOCK // // get the declaration block. If it is not already present, add it too DClassDeclarationBlock * myClassDeclCodeBlock = getClassDecl(); addTextBlock(myClassDeclCodeBlock); // note: wont add if already present // NOW create document in sections.. // now we want to populate the body of our class // our layout is the following general groupings of code blocks: // start d classifier document // header comment // package code block // import code block // class declaration // section: // - class field declaration section comment // - class field declarations (0+ codeblocks) // section: // - methods section comment // sub-section: constructor ops // - constructor method section comment // - constructor methods (0+ codeblocks) // sub-section: accessors // - accessor method section comment // - static accessor methods (0+ codeblocks) // - non-static accessor methods (0+ codeblocks) // sub-section: non-constructor ops // - operation method section comment // - operations (0+ codeblocks) // end class declaration // end d classifier document // Q: Why use the more complicated scheme of arranging code blocks within codeblocks? // A: This will allow us later to preserve the format of our document so that if // codeblocks are added, they may be easily added in the correct place, rather than at // the end of the document, or by using a difficult algorithm to find the location of // the last appropriate code block sibling (which may not exist.. for example user adds // a constructor operation, but there currently are no constructor code blocks // within the document). // // * CLASS FIELD declaration section // // get/create the field declaration code block HierarchicalCodeBlock * fieldDeclBlock = myClassDeclCodeBlock->getHierarchicalCodeBlock(QLatin1String("fieldsDecl"), QLatin1String("Fields"), 1); // Update the comment: we only set comment to appear under the following conditions CodeComment * fcomment = fieldDeclBlock->getComment(); if (isInterface || (!forceDoc() && !hasClassFields())) fcomment->setWriteOutText(false); else fcomment->setWriteOutText(true); // now actually declare the fields within the appropriate HCodeBlock declareClassFields(staticAttribClassFields, fieldDeclBlock); declareClassFields(attribClassFields, fieldDeclBlock); declareClassFields(plainAssocClassFields, fieldDeclBlock); declareClassFields(aggregationClassFields, fieldDeclBlock); declareClassFields(compositionClassFields, fieldDeclBlock); // // METHODS section // // get/create the method codeblock HierarchicalCodeBlock * methodsBlock = myClassDeclCodeBlock->getHierarchicalCodeBlock(QLatin1String("methodsBlock"), QLatin1String("Methods"), 1); // Update the section comment CodeComment * methodsComment = methodsBlock->getComment(); // set conditions for showing this comment if (!forceDoc() && !hasClassFields() && !hasOperationMethods) methodsComment->setWriteOutText(false); else methodsComment->setWriteOutText(true); // METHODS sub-section : constructor methods // // get/create the constructor codeblock HierarchicalCodeBlock * constBlock = methodsBlock->getHierarchicalCodeBlock(QLatin1String("constructorMethods"), QLatin1String("Constructors"), 1); constructorBlock = constBlock; // record this codeblock for later, when operations are updated // special condiions for showing comment: only when autogenerateding empty constructors // Although, we *should* check for other constructor methods too CodeComment * constComment = constBlock->getComment(); CodeGenerationPolicy *pol = UMLApp::app()->commonPolicy(); if (!forceDoc() && (isInterface || !pol->getAutoGenerateConstructors())) constComment->setWriteOutText(false); else constComment->setWriteOutText(true); // add/get the empty constructor QString DClassName = getDClassName(c->name()); QString emptyConstStatement = QLatin1String("public ")+DClassName+QLatin1String(" () { }"); CodeBlockWithComments * emptyConstBlock = constBlock->addOrUpdateTaggedCodeBlockWithComments(QLatin1String("emptyconstructor"), emptyConstStatement, QLatin1String("Empty Constructor"), 1, false); // Now, as an additional condition we only show the empty constructor block // IF it was desired to be shown if (parentIsClass() && pol->getAutoGenerateConstructors()) emptyConstBlock->setWriteOutText(true); else emptyConstBlock->setWriteOutText(false); // METHODS subsection : ACCESSOR METHODS // // get/create the accessor codeblock HierarchicalCodeBlock * accessorBlock = methodsBlock->getHierarchicalCodeBlock(QLatin1String("accessorMethods"), QLatin1String("Accessor Methods"), 1); // set conditions for showing section comment CodeComment * accessComment = accessorBlock->getComment(); if (!forceDoc() && !hasClassFields()) accessComment->setWriteOutText(false); else accessComment->setWriteOutText(true); // now, 2 sub-sub sections in accessor block // add/update accessor methods for attributes HierarchicalCodeBlock * staticAccessors = accessorBlock->getHierarchicalCodeBlock(QLatin1String("staticAccessorMethods"), QString(), 1); staticAccessors->getComment()->setWriteOutText(false); // never write block comment staticAccessors->addCodeClassFieldMethods(staticAttribClassFields); staticAccessors->addCodeClassFieldMethods(attribClassFields); // add/update accessor methods for associations HierarchicalCodeBlock * regularAccessors = accessorBlock->getHierarchicalCodeBlock(QLatin1String("regularAccessorMethods"), QString(), 1); regularAccessors->getComment()->setWriteOutText(false); // never write block comment regularAccessors->addCodeClassFieldMethods(plainAssocClassFields); regularAccessors->addCodeClassFieldMethods(aggregationClassFields); regularAccessors->addCodeClassFieldMethods(compositionClassFields); // METHODS subsection : Operation methods (which arent constructors) // // get/create the operations codeblock operationsBlock = methodsBlock->getHierarchicalCodeBlock(QLatin1String("operationMethods"), QLatin1String("Operations"), 1); // set conditions for showing section comment CodeComment * ocomment = operationsBlock->getComment(); if (!forceDoc() && !hasOperationMethods) ocomment->setWriteOutText(false); else ocomment->setWriteOutText(true); }
QList<QPair<QLabel*, QWidget*> > QgsVectorLayerSaveAsDialog::createControls( const QMap<QString, QgsVectorFileWriter::Option*>& options ) { QList<QPair<QLabel*, QWidget*> > controls; QMap<QString, QgsVectorFileWriter::Option*>::ConstIterator it; for ( it = options.constBegin(); it != options.constEnd(); ++it ) { QgsVectorFileWriter::Option* option = it.value(); QLabel* label = new QLabel( it.key() ); QWidget* control; switch ( option->type ) { case QgsVectorFileWriter::Int: { QgsVectorFileWriter::IntOption* opt = dynamic_cast<QgsVectorFileWriter::IntOption*>( option ); QSpinBox* sb = new QSpinBox(); sb->setObjectName( it.key() ); sb->setValue( opt->defaultValue ); control = sb; break; } case QgsVectorFileWriter::Set: { QgsVectorFileWriter::SetOption* opt = dynamic_cast<QgsVectorFileWriter::SetOption*>( option ); QComboBox* cb = new QComboBox(); cb->setObjectName( it.key() ); Q_FOREACH( const QString& val, opt->values ) { cb->addItem( val, val ); } if ( opt->allowNone ) cb->addItem( tr( "<Default>" ), QVariant( QVariant::String ) ); int idx = cb->findText( opt->defaultValue ); if ( idx == -1 ) idx = cb->findData( QVariant( QVariant::String ) ); cb->setCurrentIndex( idx ); control = cb; break; } case QgsVectorFileWriter::String: { QgsVectorFileWriter::StringOption* opt = dynamic_cast<QgsVectorFileWriter::StringOption*>( option ); QLineEdit* le = new QLineEdit( opt->defaultValue ); le->setObjectName( it.key() ); control = le; break; } case QgsVectorFileWriter::Hidden: control = 0; break; } if ( control ) { // Pack the tooltip in some html element, so it gets linebreaks. label->setToolTip( QString( "<p>%1</p>" ).arg( option->docString ) ); control->setToolTip( QString( "<p>%1</p>" ).arg( option->docString ) ); controls << QPair<QLabel*, QWidget*>( label, control ); } } return controls; }
void GetSystemDetails::GetOperationInfo_sys(QMap<QString, QMap<QString, QStringList> > &OutData) { if(mdllPath.compare("") ==0) { QMessageBox::warning(NULL,"exit",mdllPath); return; } qDebug() << "Load Operation is start" << mdllPath; sysDllLibrary = new QLibrary(mdllPath); if ( sysDllLibrary->load() ){ typedef BOOL (*GetFunction)(INFOLIST**); GetFunction GetOperationDetails = (GetFunction) sysDllLibrary->resolve("GetOperationDetails"); typedef void (*FreeFunction)(INFOLIST*); FreeFunction FreeOperListBuff = (FreeFunction) sysDllLibrary->resolve("FreeOperListBuff"); QString namePara; namePara = "Operating System"; INFOLIST* rListData = NULL; GetOperationDetails(&rListData); qDebug() << "Get result Data!" << rListData->m_Count; ////Get return result Data mDetails.clear(); QString ItemName; QString ItemValue; cDetailsMap.clear(); for (int i=0; i<rListData->m_Count; i++){ ItemName.clear(); ItemValue.clear(); qDebug() << "Data: " << QString::fromWCharArray(rListData->lpItem[i].m_Name) << "-->" << QString::fromWCharArray(rListData->lpItem[i].m_Value); ItemName = QString::fromWCharArray(rListData->lpItem[i].m_Name); ItemValue = QString::fromWCharArray(rListData->lpItem[i].m_Value); mDetails.push_back(ItemName); mDetails.push_back(ItemValue); } cDetailsMap.insert("OpertionInfo", mDetails); OutData.insert(namePara, cDetailsMap); //ÊÍ·ÅÄÚ´æ FreeOperListBuff(rListData); sysDllLibrary->unload(); }else { qDebug() << "Load " << mdllPath << " is failed"; mDetails.clear(); mDetails.push_back("Load the ComputerDetails.dll is failed"); cDetailsMap.clear(); cDetailsMap.insert("Failed", mDetails); OutData.insert("Load Error", cDetailsMap); cDetailsMap.clear(); } }
QFont QgsMapToolLabel::labelFontCurrentFeature() { QFont font; QgsVectorLayer* vlayer = currentLayer(); bool labelSettingsOk; QgsPalLayerSettings& layerSettings = currentLabelSettings( &labelSettingsOk ); if ( labelSettingsOk && vlayer ) { font = layerSettings.textFont; QgsFeature f; if ( vlayer->featureAtId( mCurrentLabelPos.featureId, f, false, true ) ) { const QgsAttributeMap& attributes = f.attributeMap(); QMap< QgsPalLayerSettings::DataDefinedProperties, int > ddProperties = layerSettings.dataDefinedProperties; //size QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator sizeIt = ddProperties.find( QgsPalLayerSettings::Size ); if ( sizeIt != ddProperties.constEnd() ) { if ( layerSettings.fontSizeInMapUnits ) { font.setPixelSize( layerSettings.sizeToPixel( attributes[*sizeIt].toDouble(), QgsRenderContext() ) ); } else { font.setPointSizeF( attributes[*sizeIt].toDouble() ); } } //family QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator familyIt = ddProperties.find( QgsPalLayerSettings::Family ); if ( familyIt != ddProperties.constEnd() ) { font.setFamily( attributes[*sizeIt].toString() ); } //underline QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator underlineIt = ddProperties.find( QgsPalLayerSettings::Underline ); if ( familyIt != ddProperties.constEnd() ) { font.setUnderline( attributes[*underlineIt].toBool() ); } //strikeout QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator strikeoutIt = ddProperties.find( QgsPalLayerSettings::Strikeout ); if ( strikeoutIt != ddProperties.constEnd() ) { font.setStrikeOut( attributes[*strikeoutIt].toBool() ); } //bold QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator boldIt = ddProperties.find( QgsPalLayerSettings::Bold ); if ( boldIt != ddProperties.constEnd() ) { font.setBold( attributes[*boldIt].toBool() ); } //italic QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator italicIt = ddProperties.find( QgsPalLayerSettings::Italic ); if ( italicIt != ddProperties.constEnd() ) { font.setItalic( attributes[*italicIt].toBool() ); } } } return font; }
LuaSkillCard *LuaSkillCard::Parse(const QString &str) { QRegExp rx("#(\\w+):(.*):(.*)"); QRegExp e_rx("#(\\w*)\\[(\\w+):(.+)\\]:(.*):(.*)"); static QMap<QString, Card::Suit> suit_map; if (suit_map.isEmpty()) { suit_map.insert("spade", Card::Spade); suit_map.insert("club", Card::Club); suit_map.insert("heart", Card::Heart); suit_map.insert("diamond", Card::Diamond); suit_map.insert("no_suit_red", Card::NoSuitRed); suit_map.insert("no_suit_black", Card::NoSuitBlack); suit_map.insert("no_suit", Card::NoSuit); } QStringList texts; QString name, suit, number; QString subcard_str; QString user_string; if (rx.exactMatch(str)) { texts = rx.capturedTexts(); name = texts.at(1); subcard_str = texts.at(2); user_string = texts.at(3); } else if (e_rx.exactMatch(str)) { texts = e_rx.capturedTexts(); name = texts.at(1); suit = texts.at(2); number = texts.at(3); subcard_str = texts.at(4); user_string = texts.at(5); } else return NULL; const LuaSkillCard *c = LuaSkillCards.value(name, NULL); if (c == NULL) return NULL; LuaSkillCard *new_card = c->clone(); if (subcard_str != ".") new_card->addSubcards(StringList2IntList(subcard_str.split("+"))); if (!suit.isEmpty()) new_card->setSuit(suit_map.value(suit, Card::NoSuit)); if (!number.isEmpty()) { int num = 0; if (number == "A") num = 1; else if (number == "J") num = 11; else if (number == "Q") num = 12; else if (number == "K") num = 13; else num = number.toInt(); new_card->setNumber(num); } new_card->setUserString(user_string); QString skillName = LuaSkillCardsSkillName.value(name, QString()); if (skillName.isEmpty()) skillName = name.toLower().remove("card"); new_card->setSkillName(skillName); return new_card; }
int main(int argc, char *argv[]) { QMap<QString,ParamPair> paramList; QString username = ""; QString filename; QString printerName; bool haveUsername = FALSE; bool haveDatabaseURL = FALSE; bool loggedIn = FALSE; bool print = FALSE; bool printPreview = FALSE; bool close = FALSE; int numCopies = 1; // BVI::Sednacom // new options bool pdfOutput = FALSE; QString pdfFileName; // BVI::Sednacom QString databaseURL = ""; QString loadFromDB = ""; QApplication app(argc, argv); app.addLibraryPath("."); OpenRPT::languages.addTranslationToDefault(":/common.qm"); OpenRPT::languages.addTranslationToDefault(":/wrtembed.qm"); OpenRPT::languages.addTranslationToDefault(":/renderer.qm"); OpenRPT::languages.addTranslationToDefault(":/renderapp.qm"); OpenRPT::languages.installSelected(); if (app.argc() > 1) { haveUsername = FALSE; bool havePasswd = FALSE; QString passwd = ""; QStringList arguments; QString firstArgument = QString( app.argv()[ 1 ] ); if( firstArgument.startsWith("-fromStdin=", Qt::CaseInsensitive) ){ QFile file; file.open(stdin, QIODevice::ReadOnly); QTextStream in(&file); in.setCodec( firstArgument.right( firstArgument.length() - 11 ).toAscii() ); QString arg; while( arg.compare("-launch") !=0 ){ arg = in.readLine(); arguments << arg; } file.close(); } else{ for (int intCounter = 1; intCounter < app.argc(); intCounter++){ arguments << QString (app.argv()[intCounter]); } } for ( QStringList::Iterator it = arguments.begin(); it != arguments.end(); ++it ) { QString argument( *it ); if (argument.startsWith("-databaseURL=", Qt::CaseInsensitive)) { haveDatabaseURL = TRUE; databaseURL = argument.right(argument.length() - 13); } else if (argument.startsWith("-username="******"-passwd=", Qt::CaseInsensitive)) { havePasswd = TRUE; passwd = argument.right(argument.length() - 8); } else if (argument.toLower() == "-noauth") { haveUsername = TRUE; havePasswd = TRUE; } else if (argument.startsWith("-numCopies=", Qt::CaseInsensitive)){ numCopies = argument.right( argument.length() - 11).toInt(); } else if (argument.toLower() == "-print") print = true; else if (argument.toLower() == "-printpreview") printPreview = true; else if (argument.toLower() == "-close") close = true; else if (argument.startsWith("-printerName=", Qt::CaseInsensitive)) printerName = argument.right(argument.length() - 13); else if (argument.startsWith("-param=", Qt::CaseInsensitive)) { QString str = argument.right(argument.length() - 7); bool active = true; QString name; QString type; QString value; QVariant var; int sep = str.indexOf('='); if(sep == -1) name = str; else { name = str.left(sep); value = str.right(str.length() - (sep + 1)); } str = name; sep = str.indexOf(':'); if(sep != -1) { name = str.left(sep); type = str.right(str.length() - (sep + 1)); } if(name.startsWith("-")) { name = name.right(name.length() - 1); active = false; } else if(name.startsWith("+")) name = name.right(name.length() - 1); if(!value.isEmpty()) var = XVariant::decode(type, value); paramList[name] = ParamPair(active, var); } // BVI::Sednacom // manage new arguments for CLI else if (argument.startsWith("-pdf", Qt::CaseInsensitive)) { pdfOutput = true ; } else if (argument.startsWith("-outpdf=", Qt::CaseInsensitive)) { pdfFileName = argument.right(argument.length() - 8 ) ; } // BVI::Sednacom else if (argument.startsWith("-loadfromdb=", Qt::CaseInsensitive)) loadFromDB = argument.right(argument.length() - 12); else if (argument.toLower() == "-e") XSqlQuery::setNameErrorValue("Missing"); else if(!argument.startsWith("-")) filename = argument; } if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) ) { QSqlDatabase db; QString protocol; QString hostName; QString dbName; QString port; db = databaseFromURL( databaseURL ); if (!db.isValid()) { QMessageBox::critical(0, QObject::tr("Can not load database driver"), QObject::tr("Unable to load the database driver. Please contact your systems administrator.")); QApplication::exit(-1); } db.setUserName(username); db.setPassword(passwd); if (!db.open()) { QMessageBox::critical(0, QObject::tr("Unable to connect to database"), QObject::tr("Unable to connect to the database with the given information.")); QApplication::exit(-1); } else loggedIn = TRUE; } } if(!loggedIn) { ParameterList params; params.append("name", RenderWindow::name()); params.append("copyright", OpenRPT::copyright); params.append("version", OpenRPT::version); params.append("build", OpenRPT::build); if (haveUsername) params.append("username", username); if (haveDatabaseURL) params.append("databaseURL", databaseURL); login newdlg(0, "", TRUE); newdlg.set(params, 0); if (newdlg.exec() == QDialog::Rejected) return -1; } // The following is code that works specifically with the xTuple ERP database // This should be expanded to be usefull when not connecting to an xTuple ERP // database as well. Command line option maybe? XSqlQuery langq("SELECT * " "FROM usr, locale LEFT OUTER JOIN" " lang ON (locale_lang_id=lang_id) LEFT OUTER JOIN" " country ON (locale_country_id=country_id) " "WHERE ( (usr_username=CURRENT_USER)" " AND (usr_locale_id=locale_id) );" ); if (langq.first()) { QStringList paths; paths << "dict"; paths << ""; paths << "../dict"; paths << app.applicationDirPath() + "/dict"; paths << app.applicationDirPath(); paths << app.applicationDirPath() + "/../dict"; #if defined Q_WS_MACX paths << app.applicationDirPath() + "/../../../dict"; paths << app.applicationDirPath() + "/../../.."; #endif QStringList files; if (!langq.value("locale_lang_file").toString().isEmpty()) files << langq.value("locale_lang_file").toString(); QString langext; if (!langq.value("lang_abbr2").toString().isEmpty() && !langq.value("country_abbr").toString().isEmpty()) { langext = langq.value("lang_abbr2").toString() + "_" + langq.value("country_abbr").toString().toLower(); } else if (!langq.value("lang_abbr2").toString().isEmpty()) { langext = langq.value("lang_abbr2").toString(); } if(!langext.isEmpty()) { files << "reports." + langext; XSqlQuery pkglist("SELECT pkghead_name FROM pkghead WHERE packageIsEnabled(pkghead_name);"); while(pkglist.next()) { files << pkglist.value("pkghead_name").toString() + "." + langext; } } if (files.size() > 0) { QTranslator *translator = new QTranslator(&app); for (QStringList::Iterator fit = files.begin(); fit != files.end(); ++fit) { for(QStringList::Iterator pit = paths.begin(); pit != paths.end(); ++pit) { qDebug("looking for %s in %s", (*fit).toAscii().data(), (*pit).toAscii().data()); if (translator->load(*fit, *pit)) { app.installTranslator(translator); qDebug("installed %s/%s", (*pit).toAscii().data(), (*fit).toAscii().data()); translator = new QTranslator(&app); break; } } } } } // END language loading code RenderWindow mainwin; mainwin._printerName = printerName; if(!filename.isEmpty()) mainwin.fileOpen(filename); if(!loadFromDB.isEmpty()) mainwin.fileLoad(loadFromDB); QMap<QString,ParamPair>::Iterator it; for ( it = paramList.begin(); it != paramList.end(); ++it ) { mainwin.updateParam(it.key(), it.value().second, it.value().first); } // BVI::Sednacom // do not display window for PDF output if (!pdfOutput) mainwin.show(); // BVI::Sednacom if(print) mainwin.filePrint( numCopies ); if(printPreview) mainwin.filePreview( numCopies ); // BVI::Sednacom // generate the PDF if (pdfOutput) mainwin.filePrintToPDF(pdfFileName); // BVI::Sednacom if(close) { mainwin.fileExit(); return 0; } return app.exec(); }
int QgsRasterCalculator::processCalculation( QProgressDialog* p ) { //prepare search string / tree QString errorString; QgsRasterCalcNode* calcNode = QgsRasterCalcNode::parseRasterCalcString( mFormulaString, errorString ); if ( !calcNode ) { //error return static_cast<int>( ParserError ); } QMap< QString, QgsRasterBlock* > inputBlocks; QVector<QgsRasterCalculatorEntry>::const_iterator it = mRasterEntries.constBegin(); for ( ; it != mRasterEntries.constEnd(); ++it ) { if ( !it->raster ) // no raster layer in entry { delete calcNode; qDeleteAll( inputBlocks ); return static_cast< int >( InputLayerError ); } QgsRasterBlock* block = nullptr; // if crs transform needed if ( it->raster->crs() != mOutputCrs ) { QgsRasterProjector proj; proj.setCrs( it->raster->crs(), mOutputCrs ); proj.setInput( it->raster->dataProvider() ); proj.setPrecision( QgsRasterProjector::Exact ); block = proj.block( it->bandNumber, mOutputRectangle, mNumOutputColumns, mNumOutputRows ); } else { block = it->raster->dataProvider()->block( it->bandNumber, mOutputRectangle, mNumOutputColumns, mNumOutputRows ); } if ( block->isEmpty() ) { delete block; delete calcNode; qDeleteAll( inputBlocks ); return static_cast<int>( MemoryError ); } inputBlocks.insert( it->ref, block ); } //open output dataset for writing GDALDriverH outputDriver = openOutputDriver(); if ( !outputDriver ) { return static_cast< int >( CreateOutputError ); } GDALDatasetH outputDataset = openOutputFile( outputDriver ); GDALSetProjection( outputDataset, mOutputCrs.toWkt().toLocal8Bit().data() ); GDALRasterBandH outputRasterBand = GDALGetRasterBand( outputDataset, 1 ); float outputNodataValue = -FLT_MAX; GDALSetRasterNoDataValue( outputRasterBand, outputNodataValue ); if ( p ) { p->setMaximum( mNumOutputRows ); } QgsRasterMatrix resultMatrix; resultMatrix.setNodataValue( outputNodataValue ); //read / write line by line for ( int i = 0; i < mNumOutputRows; ++i ) { if ( p ) { p->setValue( i ); } if ( p && p->wasCanceled() ) { break; } if ( calcNode->calculate( inputBlocks, resultMatrix, i ) ) { bool resultIsNumber = resultMatrix.isNumber(); float* calcData = new float[mNumOutputColumns]; for ( int j = 0; j < mNumOutputColumns; ++j ) { calcData[j] = ( float )( resultIsNumber ? resultMatrix.number() : resultMatrix.data()[j] ); } //write scanline to the dataset if ( GDALRasterIO( outputRasterBand, GF_Write, 0, i, mNumOutputColumns, 1, calcData, mNumOutputColumns, 1, GDT_Float32, 0, 0 ) != CE_None ) { QgsDebugMsg( "RasterIO error!" ); } delete[] calcData; } } if ( p ) { p->setValue( mNumOutputRows ); } //close datasets and release memory delete calcNode; qDeleteAll( inputBlocks ); inputBlocks.clear(); if ( p && p->wasCanceled() ) { //delete the dataset without closing (because it is faster) GDALDeleteDataset( outputDriver, mOutputFile.toUtf8().constData() ); return static_cast< int >( Canceled ); } GDALClose( outputDataset ); return static_cast< int >( Success ); }
void LibraryTreeWidget::onCustomContextMenuRequested(const QPoint& pos) { QMenu menu(this); bool file = false; bool folder = false; bool project = false; int size = selectedItems().size(); for (int i = 0; i < selectedItems().size(); ++i) { if (selectedItems()[i]->parent() == NULL) { project = true; } else { QString fileName = selectedItems()[i]->data(0, Qt::UserRole).toMap()["filename"].toString(); if (fileName.isEmpty() == true) folder = true; else file = true; } } if (size == 1 && (folder || project)) { menu.addAction(addNewFileAction_); menu.addAction(importToLibraryAction_); menu.addAction(newFolderAction_); } if (size > 0 && !project) menu.addAction(removeAction_); if (size == 1 && folder) menu.addAction(renameAction_); if (size == 1 && (folder || project)) menu.addAction(sortAction_); if (size == 1 && file) { menu.addAction(insertIntoDocumentAction_); QMap<QString, QVariant> data = selectedItems()[0]->data(0, Qt::UserRole).toMap(); QString fileName = data["filename"].toString(); QFileInfo fileInfo(fileName); QString ext = fileInfo.suffix().toLower(); if (ext == "lua") { menu.addAction(codeDependenciesAction_); bool excludeFromExecution = data.contains("excludeFromExecution") && data["excludeFromExecution"].toBool(); excludeFromExecutionAction_->setChecked(excludeFromExecution); menu.addAction(excludeFromExecutionAction_); } if (ext == "png" || ext == "jpg" || ext == "jpeg") { bool downsizing = data.contains("downsizing") && data["downsizing"].toBool(); automaticDownsizingAction_->setChecked(downsizing); menu.addAction(automaticDownsizingAction_); } } if (size == 1 && project) menu.addAction(projectPropertiesAction_); if (!menu.isEmpty()) menu.exec(QCursor::pos()); }
QDomDocument LibraryTreeWidget::toXml() const { QDomDocument doc; QDomElement root = doc.createElement("project"); QDomElement properties = doc.createElement("properties"); // graphics options properties.setAttribute("scaleMode", properties_.scaleMode); properties.setAttribute("logicalWidth", properties_.logicalWidth); properties.setAttribute("logicalHeight", properties_.logicalHeight); QDomElement imageScales = doc.createElement("imageScales"); for (size_t i = 0; i < properties_.imageScales.size(); ++i) { QDomElement scale = doc.createElement("scale"); scale.setAttribute("suffix", properties_.imageScales[i].first); scale.setAttribute("scale", properties_.imageScales[i].second); imageScales.appendChild(scale); } properties.appendChild(imageScales); properties.setAttribute("orientation", properties_.orientation); properties.setAttribute("fps", properties_.fps); // iOS options properties.setAttribute("retinaDisplay", properties_.retinaDisplay); properties.setAttribute("autorotation", properties_.autorotation); // input options properties.setAttribute("mouseToTouch", properties_.mouseToTouch ? 1 : 0); properties.setAttribute("touchToMouse", properties_.touchToMouse ? 1 : 0); properties.setAttribute("mouseTouchOrder", properties_.mouseTouchOrder); // export options properties.setAttribute("architecture", properties_.architecture); properties.setAttribute("assetsOnly", properties_.assetsOnly ? 1 : 0); properties.setAttribute("iosDevice", properties_.iosDevice); properties.setAttribute("packageName", properties_.packageName); properties.setAttribute("encryptCode", properties_.encryptCode); properties.setAttribute("encryptAssets", properties_.encryptAssets); root.appendChild(properties); doc.appendChild(root); QTreeWidgetItem* rootitem = invisibleRootItem(); if (rootitem->childCount()) rootitem = rootitem->child(0); std::stack<std::pair<QTreeWidgetItem*, QDomElement> > stack; stack.push(std::make_pair(rootitem, root)); while (stack.empty() == false) { QTreeWidgetItem* item = stack.top().first; QDomElement element = stack.top().second; stack.pop(); for (int i = 0; i < item->childCount(); ++i) { QTreeWidgetItem* childItem = item->child(i); QMap<QString, QVariant> data = childItem->data(0, Qt::UserRole).toMap(); QString fileName = data["filename"].toString(); QDomElement childElement = doc.createElement(fileName.isEmpty() ? "folder" : "file"); if (fileName.isEmpty() == false) { childElement.setAttribute("source", fileName); if (data.contains("downsizing") && data["downsizing"].toBool()) childElement.setAttribute("downsizing", 1); if (data.contains("excludeFromExecution") && data["excludeFromExecution"].toBool()) childElement.setAttribute("excludeFromExecution", 1); } else childElement.setAttribute("name", childItem->text(0)); element.appendChild(childElement); stack.push(std::make_pair(childItem, childElement)); } } std::vector<std::pair<QString, QString> > dependencies = dependencyGraph_.dependencies(); for (std::size_t i = 0; i < dependencies.size(); ++i) { QDomElement childElement = doc.createElement("dependency"); childElement.setAttribute("from", dependencies[i].first); childElement.setAttribute("to", dependencies[i].second); root.appendChild(childElement); } return doc; }
void QgsMapToolReshape::cadCanvasReleaseEvent( QgsMapMouseEvent * e ) { //check if we operate on a vector layer //todo: move this to a function in parent class to avoid duplication QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( mCanvas->currentLayer() ); if ( !vlayer ) { notifyNotVectorLayer(); return; } if ( !vlayer->isEditable() ) { notifyNotEditableLayer(); return; } //add point to list and to rubber band if ( e->button() == Qt::LeftButton ) { int error = addVertex( e->mapPoint(), e->mapPointMatch() ); if ( error == 1 ) { //current layer is not a vector layer return; } else if ( error == 2 ) { //problem with coordinate transformation emit messageEmitted( tr( "Cannot transform the point to the layers coordinate system" ), QgsMessageBar::WARNING ); return; } startCapturing(); } else if ( e->button() == Qt::RightButton ) { deleteTempRubberBand(); //find out bounding box of mCaptureList if ( size() < 1 ) { stopCapturing(); return; } QgsPoint firstPoint = points().at( 0 ); QgsRectangle bbox( firstPoint.x(), firstPoint.y(), firstPoint.x(), firstPoint.y() ); for ( int i = 1; i < size(); ++i ) { bbox.combineExtentWith( points().at( i ).x(), points().at( i ).y() ); } //query all the features that intersect bounding box of capture line QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setFilterRect( bbox ).setSubsetOfAttributes( QgsAttributeList() ) ); QgsFeature f; int reshapeReturn; bool reshapeDone = false; vlayer->beginEditCommand( tr( "Reshape" ) ); while ( fit.nextFeature( f ) ) { //query geometry //call geometry->reshape(mCaptureList) //register changed geometry in vector layer QgsGeometry geom = f.geometry(); if ( !geom.isEmpty() ) { reshapeReturn = geom.reshapeGeometry( points() ); if ( reshapeReturn == 0 ) { //avoid intersections on polygon layers if ( vlayer->geometryType() == QgsWkbTypes::PolygonGeometry ) { //ignore all current layer features as they should be reshaped too QMap<QgsVectorLayer*, QSet<QgsFeatureId> > ignoreFeatures; ignoreFeatures.insert( vlayer, vlayer->allFeatureIds() ); if ( geom.avoidIntersections( ignoreFeatures ) != 0 ) { emit messageEmitted( tr( "An error was reported during intersection removal" ), QgsMessageBar::CRITICAL ); vlayer->destroyEditCommand(); stopCapturing(); return; } if ( geom.isGeosEmpty() ) //intersection removal might have removed the whole geometry { emit messageEmitted( tr( "The feature cannot be reshaped because the resulting geometry is empty" ), QgsMessageBar::CRITICAL ); vlayer->destroyEditCommand(); stopCapturing(); return; } } vlayer->changeGeometry( f.id(), geom ); reshapeDone = true; } } } if ( reshapeDone ) { vlayer->endEditCommand(); } else { vlayer->destroyEditCommand(); } stopCapturing(); } }
int Pager::insert(int index, const QPixmap & image) { index = clampIndex(index, true); d->images.insert(index, image); d->updateScrollBar(); d->labels.insert(index, QString()); // Deal with null images FIXME // Modify current index if necessary if (index <= d->currentIndex && d->images.size() > 0) { d->currentIndex += 1; d->guiIndex += 1.0; } // Modify index modifiers QMap< int, double > updatedModifiers; QMutableMapIterator< int, double > iter(d->indexPreModifiers); iter.toBack(); while (iter.hasPrevious()) { iter.previous(); int targetIndex = iter.key(); if (targetIndex >= index) { double modifier = iter.value(); iter.remove(); updatedModifiers[targetIndex + 1] = modifier; } else { break; } } d->indexPreModifiers.unite(updatedModifiers); updatedModifiers.clear(); iter = d->indexPostModifiers; iter.toBack(); while (iter.hasPrevious()) { iter.previous(); int targetIndex = iter.key(); if (targetIndex >= index) { double modifier = iter.value(); iter.remove(); updatedModifiers[targetIndex + 1] = modifier; } else { break; } } d->indexPostModifiers.unite(updatedModifiers); // Modify transition times QMap< int, QTime > updatedTimes; QMutableMapIterator< int, QTime > t_iter(d->transitionTimes); t_iter.toBack(); while (t_iter.hasPrevious()) { t_iter.previous(); int targetIndex = t_iter.key(); if (targetIndex >= index) { QTime time = t_iter.value(); t_iter.remove(); updatedTimes[targetIndex + 1] = time; } else { break; } } d->transitionTimes.unite(updatedTimes); // Modify Search Hits QMap< int, int > updatedSearchHits; QMutableMapIterator< int, int > iter2(d->searchHits); iter2.toBack(); while (iter2.hasPrevious()) { iter2.previous(); int targetIndex = iter2.key(); if (targetIndex >= index) { int hits = iter2.value(); iter2.remove(); updatedSearchHits[targetIndex + 1] = hits; } else { break; } } d->searchHits.unite(updatedSearchHits); // Modify Annotations QMap< int, int > updatedHasAnnotation; iter2 = d->hasAnnotation; iter2.toBack(); while (iter2.hasPrevious()) { iter2.previous(); int targetIndex = iter2.key(); if (targetIndex >= index) { int hits = iter2.value(); iter2.remove(); updatedHasAnnotation[targetIndex + 1] = hits; } else { break; } } d->hasAnnotation.unite(updatedHasAnnotation); // Mask newly insert page d->indexPreModifiers[index] = -1.0; // Set up transition d->transitionTimes[index]; d->timer.start(); update(); return index; }
QMap<int, QString> SCRIBUS_API getGSExePaths(const QString& regKey) { QMap<int, QString> gsVersions; #if defined _WIN32 // Try to locate GhostScript thanks to the registry DWORD size; HKEY hKey1, hKey2; DWORD regType = REG_SZ; WCHAR regVersion[MAX_PATH]; WCHAR regPath[MAX_PATH]; WCHAR gsPath[MAX_PATH]; QString gsVersion, gsName; if( RegOpenKeyW(HKEY_LOCAL_MACHINE, (LPCWSTR) regKey.utf16(), &hKey1) == ERROR_SUCCESS ) { size = sizeof(regVersion)/sizeof(WCHAR) - 1; DWORD keyIndex = 0; while ( RegEnumKeyExW(hKey1, keyIndex, regVersion, &size, NULL, NULL, NULL, NULL) == ERROR_SUCCESS ) { int gsNumericVer, gsMajor, gsMinor; wcscpy(regPath, (const wchar_t*) regKey.utf16()); wcscat(regPath, L"\\"); wcscat(regPath, regVersion); if (RegOpenKeyW(HKEY_LOCAL_MACHINE, regPath, &hKey2) == ERROR_SUCCESS) { size = sizeof(gsPath) - 1; if (RegQueryValueExW(hKey2, L"GS_DLL", 0, ®Type, (LPBYTE) gsPath, &size) == ERROR_SUCCESS) { // We now have GhostScript dll path, but we want gswin32c.exe // Normally gswin32c.exe and gsdll.dll are in the same directory if ( getNumericGSVersion(QString::fromUtf16((const ushort*) regVersion), gsMajor, gsMinor) ) { gsNumericVer = gsMajor * 1000 + gsMinor; gsName = QString::fromUtf16((const ushort*) gsPath); size = gsName.lastIndexOf("\\"); if (size > 0) { gsName = gsName.left(size + 1); gsName += "gswin32c.exe"; gsName.replace("\\", "/"); gsVersions.insert(gsNumericVer, gsName); } } } RegCloseKey(hKey2); } keyIndex++; } RegCloseKey(hKey1); } #else int gsNumericVer, gsMajor, gsMinor; PrefsManager* prefsManager=PrefsManager::instance(); if (getNumericGSVersion(gsMajor, gsMinor)) { gsNumericVer = gsMajor * 1000 + gsMinor; gsVersions.insert(gsNumericVer, prefsManager->ghostscriptExecutable()); } #endif return gsVersions; }
bool Pager::remove(int index) { if (validIndex(index)) { d->images.removeAt(index); d->updateScrollBar(); d->labels.removeAt(index); d->searchHits.remove(index); d->hasAnnotation.remove(index); double oldPreModifier = d->indexPreModifiers.value(index, 0.0); double oldPostModifier = d->indexPostModifiers.value(index, 0.0); // Modify index modifiers QMap< int, double > updatedModifiers; QMutableMapIterator< int, double > iter(d->indexPreModifiers); iter.toBack(); while (iter.hasPrevious()) { iter.previous(); int targetIndex = iter.key(); if (targetIndex > index) { double modifier = iter.value(); iter.remove(); updatedModifiers[targetIndex - 1] = modifier; } else { if (targetIndex == index) { iter.remove(); } break; } } if (index != d->currentIndex - 1) updatedModifiers.insert(index, updatedModifiers.value(index, 0.0) + 1.0); d->indexPreModifiers.unite(updatedModifiers); updatedModifiers.clear(); iter = d->indexPostModifiers; iter.toBack(); while (iter.hasPrevious()) { iter.previous(); int targetIndex = iter.key(); if (targetIndex > index) { double modifier = iter.value(); iter.remove(); updatedModifiers[targetIndex - 1] = modifier; } else { if (targetIndex == index) { iter.remove(); } break; } } if (index == d->currentIndex - 1 && index > 0) updatedModifiers.insert(index - 1, updatedModifiers.value(index - 1, 0.0) + 1.0); d->indexPostModifiers.unite(updatedModifiers); // Modify Search Hits QMap< int, int > updatedSearchHits; QMutableMapIterator< int, int > iter2(d->searchHits); iter2.toBack(); while (iter2.hasPrevious()) { iter2.previous(); int targetIndex = iter2.key(); if (targetIndex > index) { int hits = iter2.value(); iter2.remove(); updatedSearchHits[targetIndex - 1] = hits; } else { if (targetIndex == index) { iter2.remove(); } break; } } d->searchHits.unite(updatedSearchHits); // Modify Annotations QMap< int, int > updatedHasAnnotation; iter2 = d->hasAnnotation; iter2.toBack(); while (iter2.hasPrevious()) { iter2.previous(); int targetIndex = iter2.key(); if (targetIndex > index) { int annotations = iter2.value(); iter2.remove(); updatedHasAnnotation[targetIndex - 1] = annotations; } else { if (targetIndex == index) { iter2.remove(); } break; } } d->hasAnnotation.unite(updatedHasAnnotation); if (!nearAsDamnIt(oldPreModifier, 0)) { d->indexPreModifiers.insert(index, d->indexPreModifiers.value(index, 0.0) + oldPreModifier); } if (!nearAsDamnIt(oldPostModifier, 0)) { if (index > 0) { d->indexPostModifiers.insert(index - 1, d->indexPostModifiers.value(index - 1, 0.0) + oldPostModifier); } else { d->indexPreModifiers.insert(index, d->indexPostModifiers.value(index, 0.0) + oldPostModifier); } } if (index < d->currentIndex || d->currentIndex == count()) // FIXME { if (d->currentIndex == count()) { previous(); } else { d->currentIndex -= 1; d->guiIndex -= 1.0; } } d->timer.start(); update(); return true; } return false; }
// This method will cause the class to rebuild its text representation. // based on the parent classifier object. // For any situation in which this is called, we are either building the code // document up, or replacing/regenerating the existing auto-generated parts. As // such, we will want to insert everything we resonablely will want // during creation. We can set various parts of the document (esp. the // comments) to appear or not, as needed. void CPPHeaderCodeDocument::updateContent( ) { // Gather info on the various fields and parent objects of this class... UMLClassifier * c = getParentClassifier(); CodeGenPolicyExt *pe = UMLApp::app()->policyExt(); CPPCodeGenerationPolicy * policy = dynamic_cast<CPPCodeGenerationPolicy*>(pe); // first, set the global flag on whether or not to show classfield info const CodeClassFieldList * cfList = getCodeClassFieldList(); CodeClassFieldList::const_iterator it = cfList->begin(); CodeClassFieldList::const_iterator end = cfList->end(); for( ; it != end; ++it ) (*it)->setWriteOutMethods(policy->getAutoGenerateAccessors()); // attribute-based ClassFields // we do it this way to have the static fields sorted out from regular ones CodeClassFieldList staticPublicAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true, Uml::Visibility::Public ); CodeClassFieldList publicAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, false, Uml::Visibility::Public ); CodeClassFieldList staticProtectedAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true, Uml::Visibility::Protected ); CodeClassFieldList protectedAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, false, Uml::Visibility::Protected ); CodeClassFieldList staticPrivateAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true, Uml::Visibility::Private ); CodeClassFieldList privateAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, false, Uml::Visibility::Private); // association-based ClassFields // don't care if they are static or not..all are lumped together CodeClassFieldList publicPlainAssocClassFields = getSpecificClassFields ( CodeClassField::PlainAssociation , Uml::Visibility::Public); CodeClassFieldList publicAggregationClassFields = getSpecificClassFields ( CodeClassField::Aggregation, Uml::Visibility::Public); CodeClassFieldList publicCompositionClassFields = getSpecificClassFields ( CodeClassField::Composition, Uml::Visibility::Public ); CodeClassFieldList protPlainAssocClassFields = getSpecificClassFields ( CodeClassField::PlainAssociation , Uml::Visibility::Protected); CodeClassFieldList protAggregationClassFields = getSpecificClassFields ( CodeClassField::Aggregation, Uml::Visibility::Protected); CodeClassFieldList protCompositionClassFields = getSpecificClassFields ( CodeClassField::Composition, Uml::Visibility::Protected); CodeClassFieldList privPlainAssocClassFields = getSpecificClassFields ( CodeClassField::PlainAssociation , Uml::Visibility::Private); CodeClassFieldList privAggregationClassFields = getSpecificClassFields ( CodeClassField::Aggregation, Uml::Visibility::Private); CodeClassFieldList privCompositionClassFields = getSpecificClassFields ( CodeClassField::Composition, Uml::Visibility::Private); bool hasOperationMethods = false; Q_ASSERT(c != NULL); if (c) { UMLOperationList list = c->getOpList(); hasOperationMethods = ! list.isEmpty(); } bool hasNamespace = false; bool isEnumeration = false; bool isInterface = parentIsInterface(); bool hasclassFields = hasClassFields(); bool forcedoc = UMLApp::app()->commonPolicy()->getCodeVerboseDocumentComments(); QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars(); UMLClassifierList superclasses = c->findSuperClassConcepts(); // START GENERATING CODE/TEXT BLOCKS and COMMENTS FOR THE DOCUMENT // // Write the hash define stuff to prevent multiple parsing/inclusion of header QString cppClassName = CodeGenerator::cleanName(c->name()); QString hashDefine = CodeGenerator::cleanName(c->name().toUpper().simplified()); QString defText = "#ifndef "+hashDefine + "_H"+ endLine + "#define "+ hashDefine + "_H"; addOrUpdateTaggedCodeBlockWithComments("hashDefBlock", defText, "", 0, false); // INCLUDE CODEBLOCK // // Q: Why all utils? Isnt just List and Vector the only classes we are using? // A: doesn't matter at all; its more readable to just include '*' and cpp compilers // don't slow down or anything. (TZ) QString includeStatement = ""; bool stringGlobal = policy->stringIncludeIsGlobal(); QString sStartBrak = stringGlobal ? "<" : "\""; QString sEndBrak = stringGlobal ? ">" : "\""; includeStatement.append("#include "+sStartBrak+policy->getStringClassNameInclude()+sEndBrak+endLine); if ( hasObjectVectorClassFields() ) { bool vecGlobal = policy->vectorIncludeIsGlobal(); QString vStartBrak = vecGlobal ? "<" : "\""; QString vEndBrak = vecGlobal ? ">" : "\""; QString value ="#include "+vStartBrak+policy->getVectorClassNameInclude()+vEndBrak; includeStatement.append(value+endLine); } //only include classes in a different package from this class UMLPackageList includes; QMap<UMLPackage *,QString> packageMap; // so we don't repeat packages CodeGenerator::findObjectsRelated(c,includes); foreach(UMLPackage* con, includes ) { if (con->baseType() != Uml::ot_Datatype && !packageMap.contains(con)) { packageMap.insert(con,con->package()); if(con != getParentClassifier()) includeStatement.append("#include \""+CodeGenerator::cleanName(con->name().toLower())+".h\""+endLine); } } // now, add/update the includes codeblock CodeBlockWithComments * inclBlock = addOrUpdateTaggedCodeBlockWithComments("includes", includeStatement, QString(), 0, false); if(includeStatement.isEmpty() && inclBlock->getContentType() == CodeBlock::AutoGenerated) inclBlock->setWriteOutText(false); else inclBlock->setWriteOutText(true); // Using QString usingStatement; foreach(UMLClassifier* classifier, superclasses ) { if(classifier->package()!=c->package() && !classifier->package().isEmpty()) { usingStatement.append("using "+CodeGenerator::cleanName(c->package())+"::"+cleanName(c->name())+';'+endLine); } } CodeBlockWithComments * usingBlock = addOrUpdateTaggedCodeBlockWithComments("using", usingStatement, "", 0, false); if(usingStatement.isEmpty() && usingBlock->getContentType() == CodeBlock::AutoGenerated) usingBlock->setWriteOutText(false); else usingBlock->setWriteOutText(true); // namespace // This needs special treatment. We cant use "nowriteouttext" for this, as // that will prevent the class declaration from being written. Instead, we // check if "hasNamspace" is true or not, and then indent the remaining code // appropriately as well as set the start/end text of this namespace block. if (c->umlPackage() && policy->getPackageIsNamespace()) hasNamespace = true; else hasNamespace = false; // set start/end text of namespace block m_namespaceBlock = getHierarchicalCodeBlock("namespace", "Namespace", 0); if(hasNamespace) { UMLPackageList pkgList = c->packages(); QString pkgs; UMLPackage *pkg; foreach (pkg, pkgList ) { pkgs += "namespace " + CodeGenerator::cleanName(pkg->name()) + " { "; } m_namespaceBlock->setStartText(pkgs); QString closingBraces; foreach (pkg, pkgList ) { closingBraces += "} "; } m_namespaceBlock->setEndText(closingBraces); m_namespaceBlock->getComment()->setWriteOutText(true); } else {
int NativeAbstractTextControlObject::setFont(TiObject* obj) { QMap<QString, QString> font; int error = NativeControlObject::getMapObject(obj, font); if (error != NATIVE_ERROR_OK) { return error; } QMap<QString, QString>::const_iterator it = font.begin(); for (; it != font.end(); ++it) { if (it.key().compare(FONT_FAMILY) == 0) { textControl_->textStyle()->setFontFamily(it.value()); } else if (it.key().compare(FONT_SIZE) == 0) { bool bSucceeded; float size = it.value().toFloat(&bSucceeded); if (bSucceeded) { textControl_->textStyle()->setFontSize(bb::cascades::FontSize::PointValue); textControl_->textStyle()->setFontSizeValue(size); } else { N_DEBUG(Native::Msg::Failed_to_convert_font_size_to_float_with_value << ": " << it.value()); } } else if (it.key().compare(FONT_STYLE) == 0) { if (it.value().compare(FONT_STYLE_NORMAL) == 0) { textControl_->textStyle()->setFontStyle(bb::cascades::FontStyle::Normal); } else if (it.value().compare(FONT_STYLE_ITALIC) == 0) { textControl_->textStyle()->setFontStyle(bb::cascades::FontStyle::Italic); } else { N_DEBUG(Native::Msg::Unknown_value_received << ": " << it.value()); } } else if (it.key().compare(FONT_WEIGHT) == 0) { if (it.value().compare(FONT_WEIGHT_NORMAL) == 0) { textControl_->textStyle()->setFontWeight(bb::cascades::FontWeight::Normal); } else if (it.value().compare(FONT_WEIGHT_BOLD) == 0) { textControl_->textStyle()->setFontWeight(bb::cascades::FontWeight::Bold); } else { N_DEBUG(Native::Msg::Unknown_value_received << ": " << it.value()); } } else { N_DEBUG(Native::Msg::Unknown_key_value_received << ": " << it.key() << ":" << it.value()); } } return NATIVE_ERROR_OK; }
int main(int argc, char *argv[]) { QCoreApplication application(argc, argv); const QStringList &args(application.arguments()); const bool quickMode(args.contains(QStringLiteral("-q")) || args.contains(QStringLiteral("--quick"))); QMap<QString, QString> parameters; parameters.insert(QString::fromLatin1("mergePresenceChanges"), QString::fromLatin1("false")); QContactManager manager(QString::fromLatin1("org.nemomobile.contacts.sqlite"), parameters); QContactFetchRequest request; request.setManager(&manager); // Perform an initial request to ensure the database has been created before we start timing request.start(); request.waitForFinished(); qint64 elapsedTimeTotal = 0; QElapsedTimer asyncTotalTimer; asyncTotalTimer.start(); // Fetch all, no optimization hints for (int i = 0; i < 3; ++i) { QElapsedTimer timer; timer.start(); request.start(); request.waitForFinished(); qint64 elapsed = timer.elapsed(); qDebug() << i << ": Fetch completed in" << elapsed << "ms"; elapsedTimeTotal += elapsed; } // Skip relationships QContactFetchHint hint; hint.setOptimizationHints(QContactFetchHint::NoRelationships); request.setFetchHint(hint); for (int i = 0; i < 3; ++i) { QElapsedTimer timer; timer.start(); request.start(); request.waitForFinished(); qint64 elapsed = timer.elapsed(); qDebug() << i << ": No-relationships fetch completed in" << elapsed << "ms"; elapsedTimeTotal += elapsed; } // Reduce data access hint.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactName::Type << QContactAddress::Type); request.setFetchHint(hint); for (int i = 0; i < 3; ++i) { QElapsedTimer timer; timer.start(); request.start(); request.waitForFinished(); qint64 elapsed = timer.elapsed(); qDebug() << i << ": Reduced data fetch completed in" << elapsed << "ms"; elapsedTimeTotal += elapsed; } // Reduce number of results hint.setMaxCountHint(request.contacts().count() / 8); request.setFetchHint(hint); for (int i = 0; i < 3; ++i) { QElapsedTimer timer; timer.start(); request.start(); request.waitForFinished(); qint64 elapsed = timer.elapsed(); qDebug() << i << ": Max count fetch completed in" << elapsed << "ms"; elapsedTimeTotal += elapsed; } qint64 asyncTotalElapsed = asyncTotalTimer.elapsed(); // Time some synchronous operations. First, generate the test data. qsrand((int)asyncTotalElapsed); QList<int> nbrContacts; if (quickMode) { nbrContacts << 200; } else { nbrContacts << 10 << 100 << 500 << 1000 << 2000; } QList<QList<QContact> > testData; qDebug() << "\n\nGenerating test data for timings..."; for (int i = 0; i < nbrContacts.size(); ++i) { int howMany = nbrContacts.at(i); QList<QContact> newTestData; newTestData.reserve(howMany); for (int j = 0; j < howMany; ++j) { // Use testing sync target, so 'local' won't be modified into 'was_local' via aggregation newTestData.append(generateContact(QString::fromLatin1("testing"))); } testData.append(newTestData); } // Perform the timings - these all create new contacts and assume an "empty" initial database QElapsedTimer syncTimer; for (int i = 0; i < testData.size(); ++i) { QList<QContact> td = testData.at(i); qint64 ste = 0; qDebug() << "Performing tests for" << td.size() << "contacts:"; syncTimer.start(); manager.saveContacts(&td); ste = syncTimer.elapsed(); qDebug() << " saving took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; QContactDetailFilter testingFilter; testingFilter.setDetailType(QContactSyncTarget::Type, QContactSyncTarget::FieldSyncTarget); testingFilter.setValue(QString::fromLatin1("testing")); QContactFetchHint fh; syncTimer.start(); QList<QContact> readContacts = manager.contacts(testingFilter, QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); if (readContacts.size() != td.size()) { qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << td.size(); } qDebug() << " reading all (" << readContacts.size() << "), all details, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; fh.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactDisplayLabel::Type << QContactName::Type << QContactAvatar::Type << QContactPhoneNumber::Type << QContactEmailAddress::Type); syncTimer.start(); readContacts = manager.contacts(testingFilter, QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); if (readContacts.size() != td.size()) { qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << td.size(); } qDebug() << " reading all, common details, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; fh.setOptimizationHints(QContactFetchHint::NoRelationships); fh.setDetailTypesHint(QList<QContactDetail::DetailType>()); syncTimer.start(); readContacts = manager.contacts(testingFilter, QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); if (readContacts.size() != td.size()) { qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << td.size(); } qDebug() << " reading all, no relationships, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; fh.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactDisplayLabel::Type << QContactName::Type << QContactAvatar::Type); syncTimer.start(); readContacts = manager.contacts(testingFilter, QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); if (readContacts.size() != td.size()) { qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << td.size(); } qDebug() << " reading all, display details + no rels, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; // Read the contacts, selected by ID QList<QContactId> idsToRetrieve; for (int j = 0; j < td.size(); ++j) { idsToRetrieve.append(retrievalId(td.at(j))); } syncTimer.start(); readContacts = manager.contacts(idsToRetrieve, fh, 0); ste = syncTimer.elapsed(); if (readContacts.size() != td.size()) { qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << td.size(); } qDebug() << " reading all by IDs, display details + no rels, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; // Read the same set using ID filtering QContactIdFilter idFilter; idFilter.setIds(idsToRetrieve); syncTimer.start(); readContacts = manager.contacts(idFilter, QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); if (readContacts.size() != td.size()) { qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << td.size(); } qDebug() << " reading all by ID filter, display details + no rels, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; // Read the same set, but filter everything out using syncTarget QContactDetailFilter aggregateFilter; aggregateFilter.setDetailType(QContactSyncTarget::Type, QContactSyncTarget::FieldSyncTarget); aggregateFilter.setValue(QString::fromLatin1("aggregate")); syncTimer.start(); readContacts = manager.contacts(idFilter & aggregateFilter, QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); if (readContacts.size() != 0) { qWarning() << "Invalid retrieval count:" << readContacts.size() << "expecting:" << 0; } qDebug() << " reading all by ID filter & aggregate, display details + no rels, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; QContactDetailFilter firstNameStartsA; firstNameStartsA.setDetailType(QContactName::Type, QContactName::FieldFirstName); firstNameStartsA.setValue("A"); firstNameStartsA.setMatchFlags(QContactDetailFilter::MatchStartsWith); fh.setDetailTypesHint(QList<QContactDetail::DetailType>()); syncTimer.start(); readContacts = manager.contacts(firstNameStartsA, QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); qDebug() << " reading filtered (" << readContacts.size() << "), no relationships, took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; QList<QContactId> idsToRemove; for (int j = 0; j < td.size(); ++j) { idsToRemove.append(retrievalId(td.at(j))); } syncTimer.start(); manager.removeContacts(idsToRemove); ste = syncTimer.elapsed(); qDebug() << " removing test data took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; } // these tests are slightly different to those above. They operate on much smaller // batches, but occur after the database has already been prefilled with some data. QList<int> smallerNbrContacts; if (quickMode) { smallerNbrContacts << 20; } else { smallerNbrContacts << 1 << 2 << 5 << 10 << 20 << 50; } QList<QList<QContact> > smallerTestData; qDebug() << "\n\nGenerating smaller test data for prefilled timings..."; for (int i = 0; i < smallerNbrContacts.size(); ++i) { int howMany = smallerNbrContacts.at(i); QList<QContact> newTestData; newTestData.reserve(howMany); for (int j = 0; j < howMany; ++j) { newTestData.append(generateContact()); } smallerTestData.append(newTestData); } // prefill the database QList<QContact> prefillData; for (int i = 0; i < testData.size() && testData.at(i).size() < 1001; ++i) { prefillData = testData.at(i); } qDebug() << "Prefilling database with" << prefillData.size() << "contacts... this will take a while..."; manager.saveContacts(&prefillData); qDebug() << "Now performing timings (shouldn't get aggregated)..."; for (int i = 0; i < smallerTestData.size(); ++i) { QList<QContact> td = smallerTestData.at(i); qint64 ste = 0; qDebug() << "Performing tests for" << td.size() << "contacts:"; syncTimer.start(); manager.saveContacts(&td); ste = syncTimer.elapsed(); qDebug() << " saving took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; QContactFetchHint fh; syncTimer.start(); QList<QContact> readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); qDebug() << " reading all (" << readContacts.size() << "), all details, took" << ste << "milliseconds"; elapsedTimeTotal += ste; fh.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactDisplayLabel::Type << QContactName::Type << QContactAvatar::Type << QContactPhoneNumber::Type << QContactEmailAddress::Type); syncTimer.start(); readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); qDebug() << " reading all, common details, took" << ste << "milliseconds"; elapsedTimeTotal += ste; fh.setOptimizationHints(QContactFetchHint::NoRelationships); fh.setDetailTypesHint(QList<QContactDetail::DetailType>()); syncTimer.start(); readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); qDebug() << " reading all, no relationships, took" << ste << "milliseconds"; elapsedTimeTotal += ste; fh.setDetailTypesHint(QList<QContactDetail::DetailType>() << QContactDisplayLabel::Type << QContactName::Type << QContactAvatar::Type); syncTimer.start(); readContacts = manager.contacts(QContactFilter(), QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); qDebug() << " reading all, display details + no rels, took" << ste << "milliseconds"; elapsedTimeTotal += ste; QContactDetailFilter firstNameStartsA; firstNameStartsA.setDetailType(QContactName::Type, QContactName::FieldFirstName); firstNameStartsA.setValue("A"); firstNameStartsA.setMatchFlags(QContactDetailFilter::MatchStartsWith); fh.setDetailTypesHint(QList<QContactDetail::DetailType>()); syncTimer.start(); readContacts = manager.contacts(firstNameStartsA, QList<QContactSortOrder>(), fh); ste = syncTimer.elapsed(); qDebug() << " reading filtered (" << readContacts.size() << "), no relationships, took" << ste << "milliseconds"; elapsedTimeTotal += ste; QList<QContactId> idsToRemove; for (int j = 0; j < td.size(); ++j) { idsToRemove.append(retrievalId(td.at(j))); } syncTimer.start(); manager.removeContacts(idsToRemove); ste = syncTimer.elapsed(); qDebug() << " removing test data took" << ste << "milliseconds (" << ((1.0 * ste) / (1.0 * td.size())) << "msec per contact )"; elapsedTimeTotal += ste; } // The next test is about saving contacts which should get aggregated into others. // Aggregation is an expensive operation, so we expect these save operations to take longer. qDebug() << "\n\nPerforming aggregation tests"; QList<QContact> contactsToAggregate; for (int i = 0; i < 100; ++i) { QContact existingContact = prefillData.at(prefillData.size() - 1 - i); QContact contactToAggregate; QContactSyncTarget newSyncTarget; newSyncTarget.setSyncTarget(QString(QLatin1String("fetchtimes-aggregation"))); QContactName aggName = existingContact.detail<QContactName>(); // ensures it'll get aggregated QContactOnlineAccount newOnlineAcct; // new data, which should get promoted up etc. newOnlineAcct.setAccountUri(QString(QLatin1String("test-aggregation-%1@fetchtimes")).arg(i)); contactToAggregate.saveDetail(&newSyncTarget); contactToAggregate.saveDetail(&aggName); contactToAggregate.saveDetail(&newOnlineAcct); contactsToAggregate.append(contactToAggregate); } syncTimer.start(); manager.saveContacts(&contactsToAggregate); qint64 aggregationElapsed = syncTimer.elapsed(); int totalAggregatesInDatabase = manager.contactIds().count(); qDebug() << "Average time for aggregation of" << contactsToAggregate.size() << "contacts (with" << totalAggregatesInDatabase << "existing in database):" << aggregationElapsed << "milliseconds (" << ((1.0 * aggregationElapsed) / (1.0 * contactsToAggregate.size())) << " msec per aggregated contact )"; elapsedTimeTotal += aggregationElapsed; // Now perform the test again, this time with more aggregates, to test nonlinearity. contactsToAggregate.clear(); const int high = prefillData.size() / 2, low = high / 2; for (int i = low; i < high; ++i) { QContact existingContact = prefillData.at(prefillData.size() - 1 - i); QContact contactToAggregate; QContactSyncTarget newSyncTarget; newSyncTarget.setSyncTarget(QString(QLatin1String("fetchtimes-aggregation"))); QContactName aggName = existingContact.detail<QContactName>(); // ensures it'll get aggregated QContactOnlineAccount newOnlineAcct; // new data, which should get promoted up etc. newOnlineAcct.setAccountUri(QString(QLatin1String("test-aggregation-%1@fetchtimes")).arg(i)); contactToAggregate.saveDetail(&newSyncTarget); contactToAggregate.saveDetail(&aggName); contactToAggregate.saveDetail(&newOnlineAcct); contactsToAggregate.append(contactToAggregate); } syncTimer.start(); manager.saveContacts(&contactsToAggregate); aggregationElapsed = syncTimer.elapsed(); totalAggregatesInDatabase = manager.contactIds().count(); qDebug() << "Average time for aggregation of" << contactsToAggregate.size() << "contacts (with" << totalAggregatesInDatabase << "existing in database):" << aggregationElapsed << "milliseconds (" << ((1.0 * aggregationElapsed) / (1.0 * contactsToAggregate.size())) << " msec per aggregated contact )"; elapsedTimeTotal += aggregationElapsed; // The next test is about updating existing contacts, amongst a large set. // We're especially interested in presence updates, as these are common. qDebug() << "\n\nPerforming presence update tests:"; // in the first presence update test, we update a small number of contacts. QStringList presenceAvatars = generateAvatarsList(); QList<QContact> contactsToUpdate; for (int i = 0; i < 10; ++i) { contactsToUpdate.append(prefillData.at(prefillData.size() - 1 - i)); } // modify the presence, nickname and avatar of the test data for (int j = 0; j < contactsToUpdate.size(); ++j) { QString genstr = QString::number(j); QContact curr = contactsToUpdate[j]; QContactPresence cp = curr.detail<QContactPresence>(); QContactNickname nn = curr.detail<QContactNickname>(); QContactAvatar av = curr.detail<QContactAvatar>(); cp.setNickname(genstr); cp.setCustomMessage(genstr); cp.setTimestamp(QDateTime::currentDateTime()); cp.setPresenceState(static_cast<QContactPresence::PresenceState>(qrand() % 4)); nn.setNickname(nn.nickname() + genstr); av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size())); curr.saveDetail(&cp); curr.saveDetail(&nn); curr.saveDetail(&av); contactsToUpdate.replace(j, curr); } // perform a batch save. syncTimer.start(); manager.saveContacts(&contactsToUpdate); qint64 presenceElapsed = syncTimer.elapsed(); totalAggregatesInDatabase = manager.contactIds().count(); qDebug() << " update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, all overlap):" << presenceElapsed << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )"; elapsedTimeTotal += presenceElapsed; // in the second presence update test, we update ALL of the contacts // This simulates having a large number of contacts from a single source (eg, a social network) // where (due to changed connectivity status) presence updates for the entire set become available. contactsToUpdate.clear(); QDateTime timestamp = QDateTime::currentDateTime(); for (int j = 0; j < prefillData.size(); ++j) { QContact curr = prefillData.at(j); QString genstr = QString::number(j) + "2"; QContactPresence cp = curr.detail<QContactPresence>(); QContactNickname nn = curr.detail<QContactNickname>(); QContactAvatar av = curr.detail<QContactAvatar>(); cp.setNickname(genstr); cp.setCustomMessage(genstr); cp.setTimestamp(timestamp); cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1)); nn.setNickname(nn.nickname() + genstr); av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size())); curr.saveDetail(&cp); curr.saveDetail(&nn); curr.saveDetail(&av); contactsToUpdate.append(curr); } // perform a batch save. syncTimer.start(); manager.saveContacts(&contactsToUpdate); presenceElapsed = syncTimer.elapsed(); totalAggregatesInDatabase = manager.contactIds().count(); qDebug() << " update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, all overlap):" << presenceElapsed << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )"; elapsedTimeTotal += presenceElapsed; // the third presence update test is identical to the previous, but with 2000 prefilled contacts in database. qDebug() << " Adding more prefill data, please wait..."; QList<QContact> morePrefillData; for (int i = 0; i < contactsToUpdate.size(); ++i) { morePrefillData.append(generateContact(QString::fromLatin1("testing"))); } manager.saveContacts(&morePrefillData); // now do the updates and save. contactsToUpdate.clear(); timestamp = QDateTime::currentDateTime(); for (int j = 0; j < prefillData.size(); ++j) { QContact curr = prefillData.at(j); QString genstr = QString::number(j) + "3"; QContactPresence cp = curr.detail<QContactPresence>(); QContactNickname nn = curr.detail<QContactNickname>(); QContactAvatar av = curr.detail<QContactAvatar>(); cp.setNickname(genstr); cp.setCustomMessage(genstr); cp.setTimestamp(timestamp); cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1)); nn.setNickname(nn.nickname() + genstr); av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size())); curr.saveDetail(&cp); curr.saveDetail(&nn); curr.saveDetail(&av); contactsToUpdate.append(curr); } for (int j = 0; j < morePrefillData.size(); ++j) { QContact curr = morePrefillData.at(j); QString genstr = QString::number(j) + "3"; QContactPresence cp = curr.detail<QContactPresence>(); QContactNickname nn = curr.detail<QContactNickname>(); QContactAvatar av = curr.detail<QContactAvatar>(); cp.setNickname(genstr); cp.setCustomMessage(genstr); cp.setTimestamp(timestamp); cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1)); nn.setNickname(nn.nickname() + genstr); av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size())); curr.saveDetail(&cp); curr.saveDetail(&nn); curr.saveDetail(&av); contactsToUpdate.append(curr); } // perform a batch save. syncTimer.start(); manager.saveContacts(&contactsToUpdate); presenceElapsed = syncTimer.elapsed(); totalAggregatesInDatabase = manager.contactIds().count(); qDebug() << " update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, all overlap):" << presenceElapsed << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )"; elapsedTimeTotal += presenceElapsed; // clean up the "more prefill data" qDebug() << " cleaning up extra prefill data, please wait..."; QList<QContactId> morePrefillIds; for (int j = 0; j < morePrefillData.size(); ++j) { morePrefillIds.append(retrievalId(morePrefillData.at(j))); } manager.removeContacts(morePrefillIds); // the fourth presence update test checks update time for non-overlapping sets of data. qDebug() << " generating non-overlapping / aggregated prefill data, please wait..."; morePrefillData.clear(); for (int i = 0; i < prefillData.size(); ++i) { morePrefillData.append(generateContact("test-presence-4", false)); // false = don't aggregate. } manager.saveContacts(&morePrefillData); // now do the update contactsToUpdate.clear(); timestamp = QDateTime::currentDateTime(); for (int j = 0; j < morePrefillData.size(); ++j) { QContact curr = morePrefillData.at(j); QString genstr = QString::number(j) + "4"; QContactPresence cp = curr.detail<QContactPresence>(); QContactNickname nn = curr.detail<QContactNickname>(); QContactAvatar av = curr.detail<QContactAvatar>(); cp.setNickname(genstr); cp.setCustomMessage(genstr); cp.setTimestamp(timestamp); cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1)); nn.setNickname(nn.nickname() + genstr); av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size())); curr.saveDetail(&cp); curr.saveDetail(&nn); curr.saveDetail(&av); contactsToUpdate.append(curr); } // perform a batch save. syncTimer.start(); manager.saveContacts(&contactsToUpdate); presenceElapsed = syncTimer.elapsed(); totalAggregatesInDatabase = manager.contactIds().count(); qDebug() << " update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, no overlap):" << presenceElapsed << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )"; elapsedTimeTotal += presenceElapsed; // clean up the "more prefill data" qDebug() << " cleaning up extra prefill data, please wait..."; morePrefillIds.clear(); for (int j = 0; j < morePrefillData.size(); ++j) { morePrefillIds.append(morePrefillData.at(j).id()); } manager.removeContacts(morePrefillIds); // the fifth presence update test is similar to the above except that half of // the extra contacts have a (high) chance of being aggregated into an existing contact. // So, database should have 2000 constituents, 1000 from "local", 1000 from "test-presence-5" // with 1500 aggregates (about 500 of test-presence-5 contacts will share an aggregate with // a local contact). TODO: check what happens if multiple aggregates for local contacts // could possibly match a given test-presence-5 contact (which is possible, since the backend // never aggregates two contacts from the same sync source...) qDebug() << " generating partially-overlapping / aggregated prefill data, please wait..."; morePrefillData.clear(); for (int i = 0; i < prefillData.size(); ++i) { if (i < (prefillData.size() / 2)) { morePrefillData.append(generateContact("test-presence-5", false)); // false = don't aggregate. } else { morePrefillData.append(generateContact("test-presence-5", true)); // true = possibly aggregate. } } manager.saveContacts(&morePrefillData); // now do the update contactsToUpdate.clear(); timestamp = QDateTime::currentDateTime(); for (int j = 0; j < morePrefillData.size(); ++j) { QContact curr = morePrefillData.at(j); QString genstr = QString::number(j) + "5"; QContactPresence cp = curr.detail<QContactPresence>(); QContactNickname nn = curr.detail<QContactNickname>(); QContactAvatar av = curr.detail<QContactAvatar>(); cp.setNickname(genstr); cp.setCustomMessage(genstr); cp.setTimestamp(timestamp); cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1)); nn.setNickname(nn.nickname() + genstr); av.setImageUrl(genstr + presenceAvatars.at(qrand() % presenceAvatars.size())); curr.saveDetail(&cp); curr.saveDetail(&nn); curr.saveDetail(&av); contactsToUpdate.append(curr); } // perform a batch save. syncTimer.start(); manager.saveContacts(&contactsToUpdate); presenceElapsed = syncTimer.elapsed(); totalAggregatesInDatabase = manager.contactIds().count(); qDebug() << " update ( batch of" << contactsToUpdate.size() << ") presence+nick+avatar (with" << totalAggregatesInDatabase << "existing in database, partial overlap):" << presenceElapsed << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )"; elapsedTimeTotal += presenceElapsed; // the sixth presence update test is identical to the fifth test, except that we ONLY // update the presence status (not nickname or avatar). morePrefillData = contactsToUpdate; contactsToUpdate.clear(); for (int j = 0; j < morePrefillData.size(); ++j) { QContact curr = morePrefillData.at(j); QContactPresence cp = curr.detail<QContactPresence>(); cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1)); curr.saveDetail(&cp); contactsToUpdate.append(curr); } // perform a batch save. syncTimer.start(); manager.saveContacts(&contactsToUpdate); presenceElapsed = syncTimer.elapsed(); totalAggregatesInDatabase = manager.contactIds().count(); qDebug() << " update ( batch of" << contactsToUpdate.size() << ") presence only (with" << totalAggregatesInDatabase << "existing in database, partial overlap):" << presenceElapsed << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )"; elapsedTimeTotal += presenceElapsed; // the seventh presence update test is identical to the 6th test, except that // we also pass a "detail type mask" to the update. This allows the backend // to perform optimisation based upon which details are modified. morePrefillData = contactsToUpdate; contactsToUpdate.clear(); for (int j = 0; j < morePrefillData.size(); ++j) { QContact curr = morePrefillData.at(j); QContactPresence cp = curr.detail<QContactPresence>(); cp.setPresenceState(static_cast<QContactPresence::PresenceState>((qrand() % 4) + 1)); curr.saveDetail(&cp); contactsToUpdate.append(curr); } // perform a batch save. QList<QContactDetail::DetailType> typeMask; typeMask << QContactDetail::TypePresence; syncTimer.start(); manager.saveContacts(&contactsToUpdate, typeMask); presenceElapsed = syncTimer.elapsed(); totalAggregatesInDatabase = manager.contactIds().count(); qDebug() << " update ( batch of" << contactsToUpdate.size() << ") masked presence only (with" << totalAggregatesInDatabase << "existing in database, partial overlap):" << presenceElapsed << "milliseconds (" << ((1.0 * presenceElapsed) / (1.0 * contactsToUpdate.size())) << " msec per updated contact )"; elapsedTimeTotal += presenceElapsed; // clean up the "more prefill data" qDebug() << " cleaning up extra prefill data, please wait..."; morePrefillIds.clear(); for (int j = 0; j < morePrefillData.size(); ++j) { morePrefillIds.append(morePrefillData.at(j).id()); } manager.removeContacts(morePrefillIds); qDebug() << "\n\nCumulative elapsed time:" << elapsedTimeTotal << "milliseconds"; return 0; }
void GetSystemDetails::GetNetworkInfo(QMap<QString, QMap<QString, QStringList> > &OutData) { try { QStringList netDetails; qDebug() << "Load Get Network Interface" <<mdllPath ; QMap<QString, QStringList> netDetailsMap; netDllLibrary = new QLibrary(mdllPath); if ( netDllLibrary->load() ){ qDebug() << "Load " << mdllPath << " is succ"; typedef bool (*GetFunction)(NICLIST **); GetFunction NetworkInterfaces = (GetFunction) netDllLibrary->resolve("NetworkInterfaces"); typedef void (*FreeFunction)(NICLIST*); FreeFunction FreeNicListBuff = (FreeFunction) netDllLibrary->resolve("FreeNicListBuff"); if(!NetworkInterfaces) { qDebug() << "find NetworkInterfaces error!"; return; } NICLIST *niclist = NULL; bool ret = NetworkInterfaces(&niclist); netDetailsMap.clear(); int nType; QString strId; //QString strType; QString strGuid; QList<QNetworkAddressEntry> ipInfoList; //niclist = NULL; if ( niclist != NULL ){ for (DWORD i=0;i<niclist->dwCount;++i) { nType = int(niclist->lpNics[i].m_dwNicType); if ( nType==1 || nType==2 ){ netDetails.clear(); strId = QString::number(int(niclist->lpNics[i].m_dwId), 10); netDetails.push_back("Id"); netDetails.push_back(strId); strGuid = QString::fromWCharArray(niclist->lpNics[i].m_chDevGuid); //Add other Info otherDetails = QNetworkInterface::interfaceFromName(strGuid); netDetails.push_back("Name"); netDetails.push_back(otherDetails.humanReadableName()); netDetails.push_back("HardwareAddress"); netDetails.push_back(otherDetails.hardwareAddress()); ipInfoList = otherDetails.addressEntries(); foreach(QNetworkAddressEntry ipInfo, ipInfoList){ netDetails.push_back("IP Address"); netDetails.push_back(ipInfo.ip().toString()); netDetails.push_back("Netmask"); netDetails.push_back(ipInfo.netmask().toString()); netDetails.push_back("Broadcast"); netDetails.push_back(ipInfo.broadcast().toString()); } netDetails.push_back("Description"); netDetails.push_back(QString::fromWCharArray(niclist->lpNics[i].m_chDevDesc)); netDetailsMap.insert(strId, netDetails); } } OutData.insert("Network Interface", netDetailsMap); netDetailsMap.clear(); FreeNicListBuff(niclist); }
void MyMoveServer::recognizeWithNN() { qDebug("MyMoveServer::recognizeWithNN: finger vectors 1 %d 2 %d 3 %d", m_gesture[0].length(),m_gesture[1].length(),m_gesture[2].length()); // Check if the user has been doing a two-finger gesture but // has accidentally touched the screen with a third finger if (m_fingerAmount == 3 && m_gesture[2].length() < 5) { m_fingerAmount = 2; } // Also check the same for 3-finger gesture if (m_fingerAmount == 4 && m_gesture[3].length() < 5) { m_fingerAmount = 3; } if (m_gesture[0].length() + m_gesture[1].length() <= MIN_GESTURE_LENGTH) { qDebug("Gesture vector is too short"); m_state = OBSERVING; return; } formFeatureVector(); struct fann* network = NULL; QMap<int, Gesture>* gestureList = NULL; switch(m_fingerAmount) { case 2: network = m_gestureNN2; gestureList = &m_gesturesDouble; break; case 3: network = m_gestureNN3; gestureList = &m_gesturesTriple; break; default: qDebug("Amount of fingers not supported, returning"); m_state = OBSERVING; return; break; } qDebug("Using neural network %d", m_fingerAmount); fann_type* results = NULL; results = fann_run(network, m_featureVector); int outputs = fann_get_num_output(network); int matchingIdx = -1; int matches = 0; bool falseRecognitions = false; for (int i = 0; i < outputs; i++) { if (results[i] >= GESTURE_RECOGNITION_THRESHOLD) { matches++; matchingIdx = i; } else if (results[i] >= FALSE_RECOGNITION_THRESHOLD) { falseRecognitions = true; } qDebug("Gesture %d, result: %.2f", i, results[i]); } QString command = ""; if (matches == 1 && !falseRecognitions) { qDebug("Found a single match: %d", matchingIdx); if (matchingIdx < gestureList->size()) { qDebug() << "Command to execute: " << (*gestureList)[matchingIdx].command; command = (*gestureList)[matchingIdx].command; } } m_state = OBSERVING; if (command.length() > 0) { command = command + " &"; system(command.toLatin1()); } qDebug("MyMoveServer::recognizeWithNN out"); }
void DisplayWidget::setupFragmentShader() { QMap<QString, bool> textureCacheUsed; if (shaderProgram) { shaderProgram->release(); } delete(shaderProgram); shaderProgram = new QGLShaderProgram(this); // Vertex shader bool s = false; s = shaderProgram->addShaderFromSourceCode(QGLShader::Vertex,fragmentSource.vertexSource.join("\n")); if (fragmentSource.vertexSource.count() == 0) { WARNING("No vertex shader found!"); s = false; } if (!s) WARNING("Could not create vertex shader: " + shaderProgram->log()); if (!s) { delete(shaderProgram); shaderProgram = 0; return; } if (!shaderProgram->log().isEmpty()) INFO("Vertex shader compiled with warnings: " + shaderProgram->log()); // Fragment shader s = shaderProgram->addShaderFromSourceCode(QGLShader::Fragment, fragmentSource.getText()); if (!s) WARNING("Could not create fragment shader: " + shaderProgram->log()); if (!s) { delete(shaderProgram); shaderProgram = 0; return; } if (!shaderProgram->log().isEmpty()) INFO("Fragment shader compiled with warnings: " + shaderProgram->log()); s = shaderProgram->link(); if (!s) WARNING("Could not link shaders: " + shaderProgram->log()); if (!s) { delete(shaderProgram); shaderProgram = 0; return; } if (!shaderProgram->log().isEmpty()) INFO("Fragment shader compiled with warnings: " + shaderProgram->log()); s = shaderProgram->bind(); if (!s) WARNING("Could not bind shaders: " + shaderProgram->log()); if (!s) { delete(shaderProgram); shaderProgram = 0; return; } // Setup textures. int u = 0; // Bind first texture to backbuffer int l = shaderProgram->uniformLocation("backbuffer"); if (l != -1) { if (bufferType != None) { glActiveTexture(GL_TEXTURE0+u); // non-standard (>OpenGL 1.3) gl extension GLuint i = backBuffer->texture(); glBindTexture(GL_TEXTURE_2D,i); if (fragmentSource.textureParams.contains("backbuffer")) { setGlTexParameter(fragmentSource.textureParams["backbuffer"]); } shaderProgram->setUniformValue(l, (GLuint)u); //INFO(QString("Binding back buffer (ID: %1) to active texture %2").arg(backBuffer->texture()).arg(u)); //INFO(QString("Setting uniform backbuffer to active texture %2").arg(u)); u++; } else { WARNING("Trying to use a backbuffer, but no bufferType set."); WARNING("Use the buffer define, e.g.: '#buffer RGBA8' "); } } for (QMap<QString, QString>::iterator it = fragmentSource.textures.begin(); it!=fragmentSource.textures.end(); it++) { QString textureName = it.key(); QString texturePath = it.value(); QImage im(texturePath); if (im.isNull() && !texturePath.endsWith(".hdr", Qt::CaseInsensitive)) { WARNING("Failed to load texture: " + QFileInfo(texturePath).absoluteFilePath()); } else { int l = shaderProgram->uniformLocation(textureName); if (l != -1) { if (im.isNull()) { GLuint texture = 0; // set current texture glActiveTexture(GL_TEXTURE0+u); // non-standard (>OpenGL 1.3) gl extension // allocate a texture id if (TextureCache.contains(texturePath)) { textureCacheUsed[texturePath] = true; int textureID = TextureCache[texturePath]; glBindTexture(GL_TEXTURE_2D, textureID ); INFO(QString("Found texture in cache: %1 (id: %2)").arg(texturePath).arg(textureID)); } else { glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &texture ); INFO(QString("Allocated texture ID: %1").arg(texture)); glBindTexture(GL_TEXTURE_2D, texture ); //glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // TODO: If I don't keep this line, HDR images don't work. // It must be a symptom of some kind of error in the OpenGL setup. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); if (fragmentSource.textureParams.contains(textureName)) { setGlTexParameter(fragmentSource.textureParams[textureName]); } HDRLoaderResult result; HDRLoader::load(texturePath.toAscii().data(), result); INFO(QString("Hdrloader found HDR image: %1 x %2").arg(result.width).arg(result.height)); glTexImage2D(GL_TEXTURE_2D, 0, 0x8815 , result.width, result.height, 0, GL_RGB, GL_FLOAT, result.cols); //INFO(QString("Binding %0 (ID: %1) to active texture %2").arg(textureName+":"+texturePath).arg(texture).arg(u)); TextureCache[texturePath] = texture; textureCacheUsed[texturePath] = true; } shaderProgram->setUniformValue(l, (GLuint)u); //INFO(QString("Setting uniform %0 to active texture %2").arg(textureName).arg(u)); } else { glActiveTexture(GL_TEXTURE0+u); // non-standard (>OpenGL 1.3) gl extension GLuint textureID; if (TextureCache.contains(texturePath)) { textureCacheUsed[texturePath] = true; textureID = TextureCache[texturePath]; INFO(QString("Found texture in cache: %1").arg(texturePath)); } else { textureID = bindTexture(texturePath, GL_TEXTURE_2D, GL_RGBA); TextureCache[texturePath] = textureID; textureCacheUsed[texturePath] = true; } glBindTexture(GL_TEXTURE_2D,textureID); //INFO(QString("Binding %0 (ID: %1) to active texture %2").arg(textureName+":"+texturePath).arg(textureID).arg(u)); shaderProgram->setUniformValue(l, (GLuint)u); //INFO(QString("Setting uniform %0 to active texture %2").arg(textureName).arg(u)); if (fragmentSource.textureParams.contains(textureName)) { setGlTexParameter(fragmentSource.textureParams[textureName]); } } } else { WARNING("Could not locate sampler2D uniform: " + textureName); } u++; } } nextActiveTexture = u; setupBufferShader(); // Check for unused textures QMapIterator<QString, int> i(TextureCache); while (i.hasNext()) { i.next(); if (!textureCacheUsed.contains(i.key())) { INFO("Removing texture from cache: " +i.key()); GLuint id = i.value(); glDeleteTextures(1, &id); TextureCache.remove(i.key()); } else { //INFO("Used texture: " +i.key()); } } }
/** \param fechaInicial \param fechaFinal \param cuentaInicial \param cuentaFinal \param nivel \param jerarquico **/ void BalanceView::presentarSyS ( QString fechaInicial, QString fechaFinal, QString cuentaInicial, QString cuentaFinal, int nivel, int, bool jerarquico ) { BL_FUNC_DEBUG BlFixed tsaldoant ( "0.00" ), tdebe ( "0.00" ), thaber ( "0.00" ), tsaldo ( "0.00" ); BlDbRecordSet *ramas = NULL; BlDbRecordSet *hojas = NULL; try { /// Primero, averiguaremos la cantidad de ramas iniciales que nacen de la raíz /// (tantas como número de cuentas de nivel 2) y las vamos creando. mainCompany() ->begin(); QString query = "SELECT *, nivel(codigo) AS nivel FROM cuenta ORDER BY codigo"; ramas = mainCompany() ->loadQuery ( query ); /// Creamos el arbol y lo inicializamos con todas las cuentas. BcPlanContableArbol *arbol; arbol = new BcPlanContableArbol; while ( !ramas->eof() ) { if ( ramas->value( "nivel" ).toInt() == 2 ) { /// Cuenta raíz. /// Se crea una rama en el árbol (de las primeritas que salen /// de una raíz). arbol->nuevaRama ( ramas ); } // end if ramas->nextRecord(); } // end while arbol->inicializa ( ramas ); delete ramas; /// Sacamos la subcadena para centros de coste y canales. BcCanalSeleccionarView *scanal = mainCompany() ->getselcanales(); BcCentroCosteSeleccionarView *scoste = mainCompany() ->getselccostes(); QString ccostes = scoste->cadcoste(); if ( ccostes != "" ) { ccostes = " AND apunte.idc_coste IN (" + ccostes + ") "; ; } // end if QString ccanales = scanal->cadCanal(); if (scanal->sinCanal()) { if ( ccanales != "" ) { ccanales = " AND (apunte.idcanal ISNULL OR apunte.idcanal IN (" + ccanales + ")) "; } else { ccanales = " AND apunte.idcanal ISNULL "; } // end if } else { if ( ccanales != "" ) { ccanales = " AND (apunte.idcanal <> NULL OR apunte.idcanal IN (" + ccanales + ")) "; } else { ccanales = " AND apunte.idcanal <> NULL "; } // end if } // end if QString wherecostesycanales = ccostes + ccanales; /// Ahora, usaremos el árbol para poner los datos a cada hoja (cuenta) /// según los períodos que necesitemos acotar. /// Para ello, vamos a recopilar todos los apuntes introducidos agrupados por cuenta /// para poder averiguar el estado contable de cada cuenta. query = "SELECT cuenta.idcuenta, numapuntes, cuenta.codigo, saldoant, debe, haber, ( COALESCE(saldop,0) + COALESCE(saldoant,0)) AS saldo, debeej, haberej, saldoej FROM "; query += "(SELECT idcuenta, codigo FROM cuenta) AS cuenta "; query += " LEFT JOIN (SELECT idcuenta, COALESCE(sum(debe),0) AS debeej, COALESCE(sum(haber),0) AS haberej, (COALESCE(sum(debe),0) - COALESCE(sum(haber),0)) AS saldoej FROM apunte WHERE EXTRACT(year FROM fecha) = '" + fechaFinal.right ( 4 ) + "' " + wherecostesycanales + " GROUP BY idcuenta) AS ejercicio ON ejercicio.idcuenta = cuenta.idcuenta"; query += " LEFT OUTER JOIN (SELECT idcuenta, count(idcuenta) AS numapuntes, COALESCE(sum(debe),0) AS debe, COALESCE(sum(haber),0) AS haber, (COALESCE(sum(debe),0) - COALESCE(sum(haber),0)) AS saldop FROM apunte WHERE fecha >= '" + fechaInicial + "' AND fecha <= '" + fechaFinal + "' " + wherecostesycanales + " GROUP BY idcuenta) AS periodo ON periodo.idcuenta = cuenta.idcuenta "; query += " LEFT OUTER JOIN (SELECT idcuenta, (COALESCE(sum(debe),0) - COALESCE(sum(haber),0)) AS saldoant FROM apunte WHERE fecha < '" + fechaInicial + "' " + wherecostesycanales + " GROUP BY idcuenta) AS anterior ON cuenta.idcuenta = anterior.idcuenta ORDER BY codigo"; /// Poblamos el árbol de hojas (cuentas). hojas = mainCompany() ->loadQuery ( query ); while ( !hojas->eof() ) { /// Para cada cuenta con apuntes introducidos hay que actualizar hojas del árbol. arbol->actualizaHojas ( hojas ); hojas->nextRecord(); } // end while delete hojas; /// Establecemos la hoja activa arbol->inicia(); /// Por fin, presentamos los valores. /// Aunque antes, prepararemos el Widget con la cabecera a mostrar. QStringList headers, datos; headers << _ ( "Codigo" ) << _ ( "Denominacion" ) << _ ( "Saldo anterior" ) << _ ( "Debe" ) << _ ( "Haber" ) << _ ( "Saldo" ) << _ ( "Debe " ) + fechaFinal.right ( 4 ) << _ ( "Haber " ) + fechaFinal.right ( 4 ) << _ ( "Saldo " ) + fechaFinal.right ( 4 ); mui_list->setHeaderLabels ( headers ); mui_list->clear(); /// Ponemos las columnas mui_list->setColumnWidth ( CUENTA, 250 ); mui_list->setColumnWidth ( DENOMINACION, 150 ); mui_list->setColumnWidth ( SALDO_ANT, 100 ); mui_list->setColumnWidth ( DEBE, 100 ); mui_list->setColumnWidth ( HABER, 100 ); mui_list->setColumnWidth ( SALDO, 100 ); mui_list->setColumnWidth ( DEBEEJ, 100 ); mui_list->setColumnWidth ( HABEREJ, 100 ); mui_list->setColumnWidth ( SALDOEJ, 100 ); /// Cada hoja del árbol usara uno de estos Widgets para mostrarse. QTreeWidgetItem *it; int nivelActual; /// Mantenemos una tabla con índices de niveles del árbol. QMap <int, QTreeWidgetItem *> ptrList; /// Y el iterador para controlar donde accedemos, así como un índice /// adicional. QMap <int, QTreeWidgetItem *>::const_iterator ptrIt, i; ptrList.clear(); while ( arbol->deshoja ( nivel, jerarquico ) ) { QString lcuenta = arbol->hojaActual ( "codigo" ); QString ldenominacion = arbol->hojaActual ( "descripcion" ); QString lsaldoant = arbol->hojaActual ( "saldoant" ); QString ldebe = arbol->hojaActual ( "debe" ); QString lhaber = arbol->hojaActual ( "haber" ); QString lsaldo = arbol->hojaActual ( "saldo" ); QString ldebeej = arbol->hojaActual ( "debeej" ); QString lhaberej = arbol->hojaActual ( "haberej" ); QString lsaldoej = arbol->hojaActual ( "saldoej" ); if ( lcuenta >= cuentaInicial and lcuenta <= cuentaFinal ) { /// Acumulamos los totales para al final poder escribirlos. /// Solo si son del nivel seleccionado o son hojas finales ya que en un jerarquico no se puede acumular /// TODO: No funciona bien en todos los niveles. Principalmente si el arbol no es normalizado if (lcuenta.length() == nivel) { tsaldoant = tsaldoant + BlFixed ( lsaldoant ); tsaldo = tsaldo + BlFixed ( lsaldo ); tdebe = tdebe + BlFixed ( ldebe ); thaber = thaber + BlFixed ( lhaber ); } // end if /// Las variables de las filas en formato español. lsaldoant = QString::number ( lsaldoant.toDouble(), 'f', 2 ); ldebe = QString::number ( ldebe.toDouble(), 'f', 2 ); lhaber = QString::number ( lhaber.toDouble(), 'f', 2 ); lsaldo = QString::number ( lsaldo.toDouble(), 'f', 2 ); ldebeej = QString::number ( ldebeej.toDouble(), 'f', 2 ); lhaberej = QString::number ( lhaberej.toDouble(), 'f', 2 ); lsaldoej = QString::number ( lsaldoej.toDouble(), 'f', 2 ); /// Ahora, vamos a pintar en el Widget cada línea. /// Formamos la línea. datos << lcuenta << ldenominacion << lsaldoant << ldebe << lhaber << lsaldo << ldebeej << lhaberej << lsaldoej; /// Si se van mostrar también las cuentas superiores, habrá que /// jerarquizar el árbol. Sino, se pinta cada línea al mismo nivel. if ( jerarquico ) { /// jerarquizando... nivelActual = lcuenta.length(); if ( nivelActual == 2 ) { /// La hoja cuelga de la raíz principal. it = new QTreeWidgetItem ( mui_list, datos ); } else { while ( ptrIt.key() >= nivelActual ) /// Ascendemos por el árbol para colgar la hoja en el /// lugar correcto. ptrIt--; it = new QTreeWidgetItem ( ptrIt.value(), datos ); } // end if /// Insertamos el widget (hoja actual) en la tabla controlada y obtenemos /// su puntero iterador. ptrIt = ptrList.insert ( nivelActual, it ); mui_list->setItemExpanded ( it, true ); /// Borramos el resto de niveles que cuelgan, para no seguir colgando por /// esa rama. i = ptrIt + 1; while ( i != ptrList.constEnd() ) { /// Borra todas las entradas con la misma clave. ptrList.remove ( i.key() ); ++i; } // end while } else { /// sin jerarquizar... it = new QTreeWidgetItem ( mui_list, datos ); } // end if datos.clear(); /// Formateamos un poquito la información mostrada. int tamanyo = 10; if ( ldenominacion.length() > 40 ) { tamanyo -= 1; } else if ( ldenominacion.length() > 50 ) { tamanyo -= 2; } // end if it->setFont ( DENOMINACION, QFont ( "Serif", tamanyo, -1, false ) ); for ( int col = 0; col < it->columnCount(); col++ ) { if ( col == DEBE || col == HABER || col == SALDO || col == DEBEEJ || col == HABEREJ || col == SALDOEJ ) { it->setFont ( col, QFont ( "SansSerif", 9, QFont::DemiBold, false ) ); } else { it->setFont ( col, QFont ( "SansSerif", 9, QFont::Normal, false ) ); } // end if it->setTextAlignment ( col, Qt::AlignRight ); if ( lcuenta.size() == 2 ) { it->setTextColor ( col, Qt::darkGray ); it->setFont ( col, QFont ( "SansSerif", 10, QFont::Bold, false ) ); } else if ( lcuenta.size() < 5 ) { it->setTextColor ( col, Qt::blue ); } else { if ( it->text ( col ).left ( 1 ) == "-" ) { it->setTextColor ( col, Qt::darkRed ); } else { it->setTextColor ( col, Qt::black ); } // end if } // end if } // end for } // end if } // end while mui_list->resizeColumnToContents ( 1 ); /// Hacemos la actualización de los saldos totales en formato /// español y los ponemos en su Widget. QString totsaldoant = tsaldoant.toQString(); QString totdebe = tdebe.toQString(); QString tothaber = thaber.toQString(); QString totsaldo = tsaldo.toQString(); mui_totalSaldoAnterior->setText ( totsaldoant ); mui_totalDebe->setText ( totdebe ); mui_totalHaber->setText ( tothaber ); mui_totalSaldo->setText ( totsaldo ); /// Eliminamos el árbol de la memória y cerramos la conexión /// con la BD. delete arbol; mainCompany() ->commit(); } catch ( ... ) { blMsgInfo ( _("Error en los calculos.") ); mainCompany() ->rollback(); /// Libermos posible memoria utilizada if ( ramas ) delete ramas; if ( hojas ) delete hojas; } // end try }
void ANNClassifier::trainClassifier( SuspectLibraryPtr suspectLibrary, QMap<QString,QVariant> trainingParameters ) { bool ok = true; /// @todo add a fetch required parameters method to query which parameters are required for training /// @todo Move the input and output width parameters down into the base class // Fetch the input width for this classifier SOMError::requireCondition( trainingParameters.contains( "inputWidth" ), "Missing required input width parameter" ); inputWidth = trainingParameters[ "inputWidth" ].toInt( &ok ); SOMError::requireCondition( ok, "Failed to convert input width parameter" ); SOMError::requireCondition( inputWidth > 0, "Invalid input size" ); // Fetch the output width for this classifier SOMError::requireCondition( trainingParameters.contains( "outputWidth" ), "Missing required output width parameter" ); outputWidth = trainingParameters[ "outputWidth" ].toInt( &ok ); SOMError::requireCondition( ok, "Failed to convert output width parameter" ); SOMError::requireCondition( outputWidth > 0, "Invalid output size" ); // Fetch the iterations parameter for this classifier int iterations = 0; if( trainingParameters.contains( "iterations" ) ) { iterations = trainingParameters[ "iterations" ].toInt( &ok ); SOMError::requireCondition( ok, "Failed to convert iterations parameter" ); SOMError::requireCondition( iterations > 0, "Invalid iterations value" ); } // Fetch the iterations parameter for this classifier double epsilon = 0.0; if( trainingParameters.contains( "epsilon" ) ) { epsilon = trainingParameters[ "epsilon" ].toDouble( &ok ); SOMError::requireCondition( ok, "Failed to convert epsilon parameter" ); SOMError::requireCondition( epsilon > 0.0, "Invalid epsilon value" ); } QVector< SuspectPtr > suspects = suspectLibrary->suspects(); /* Make an input matrix for training the back-end MLPANN. * This is a matrix composed of vectors the length of the SOM's area ( width x height ) */ cv::Mat_<double> input( suspects.size(), inputWidth, 0.0 ); /* Make an output matrix for trainig the back-end MLPANN. * This is a matrix composed of vectors the length of the number of classification categories. */ cv::Mat_<double> output( suspects.size(), outputWidth, 0.0 ); for( int i=0; i<suspects.size(); i++ ) { SuspectPtr suspect = suspects[i]; HistogramPtr histogram = suspect->histogram(); // Set the input for the training input matrix row to the histogram of the suspect for( int j=0; j<inputWidth; j++ ) input( i, j ) = histogram->bin( j ); // Set the output value for the real category of the suspect to 1. All other values will already be 0 output( i, suspect->realCategory() ) = 1.0; } cv::TermCriteria terminationCriteria; terminationCriteria.type = 0; if( iterations != 0 ) terminationCriteria.type += cv::TermCriteria::MAX_ITER; if( epsilon != 0.0 ) terminationCriteria.type += cv::TermCriteria::EPS; cv::ANN_MLP_TrainParams trainingParams( terminationCriteria, CvANN_MLP_TrainParams::RPROP, iterations, epsilon ); int normFlag = 0; int tmp[4]; // The input layer has one node for each element in the input histograms tmp[0] = inputWidth; // The first hidden layer is half the size of the input layer tmp[1] = inputWidth / 2; // The second input layer is one quarter the size of the input layer tmp[2] = inputWidth / 4; // The output layer has one node for each category tmp[3] = outputWidth; CvMat ls = cvMat( 4, 1, CV_32S, tmp ); // If there is already an MPLANN attached to this HSOM, delete it to start over if( _ann != NULL ) delete _ann; // Create a new MLPANN for the HSOM _ann = new CvANN_MLP( &ls, CvANN_MLP::SIGMOID_SYM ); _ann->train( input, output, cv::Mat(), cv::Mat(), trainingParams, normFlag ); }
/** \fn AutoExpire::CalcParams() * Calculates how much space needs to be cleared, and how often. */ void AutoExpire::CalcParams() { VERBOSE(VB_FILE, LOC + "CalcParams()"); vector<FileSystemInfo> fsInfos; if (mainServer) mainServer->GetFilesystemInfos(fsInfos); if (fsInfos.empty()) { QString msg = "ERROR: Filesystem Info cache is empty, unable to " "calculate necessary parameters."; VERBOSE(VB_IMPORTANT, LOC + msg); gCoreContext->LogEntry("mythbackend", LP_WARNING, "Autoexpire CalcParams", msg); return; } size_t maxKBperMin = 0; size_t extraKB = gCoreContext->GetNumSetting("AutoExpireExtraSpace", 0) << 20; QMap<int, uint64_t> fsMap; QMap<int, vector<int> > fsEncoderMap; // we use this copying on purpose. The used_encoders map ensures // that every encoder writes only to one fs. // Copying the data minimizes the time the lock is held instance_lock.lock(); QMap<int, int>::const_iterator ueit = used_encoders.begin(); while (ueit != used_encoders.end()) { fsEncoderMap[*ueit].push_back(ueit.key()); ++ueit; } instance_lock.unlock(); vector<FileSystemInfo>::iterator fsit; for (fsit = fsInfos.begin(); fsit != fsInfos.end(); ++fsit) { if (fsMap.contains(fsit->fsID)) continue; fsMap[fsit->fsID] = 0; size_t thisKBperMin = 0; // append unknown recordings to all fsIDs vector<int>::iterator unknownfs_it = fsEncoderMap[-1].begin(); for (; unknownfs_it != fsEncoderMap[-1].end(); ++unknownfs_it) fsEncoderMap[fsit->fsID].push_back(*unknownfs_it); if (fsEncoderMap.contains(fsit->fsID)) { VERBOSE(VB_FILE, QString( "fsID #%1: Total: %2 GB Used: %3 GB Free: %4 GB") .arg(fsit->fsID) .arg(fsit->totalSpaceKB / 1024.0 / 1024.0, 7, 'f', 1) .arg(fsit->usedSpaceKB / 1024.0 / 1024.0, 7, 'f', 1) .arg(fsit->freeSpaceKB / 1024.0 / 1024.0, 7, 'f', 1)); vector<int>::iterator encit = fsEncoderMap[fsit->fsID].begin(); for (; encit != fsEncoderMap[fsit->fsID].end(); ++encit) { EncoderLink *enc = *(encoderList->find(*encit)); if (!enc->IsConnected() || !enc->IsBusy()) { // remove the encoder since it can't write to any file system VERBOSE(VB_FILE, LOC + QString("Cardid %1: is not recoding, removing it " "from used list.").arg(*encit)); instance_lock.lock(); used_encoders.remove(*encit); instance_lock.unlock(); continue; } long long maxBitrate = enc->GetMaxBitrate(); if (maxBitrate<=0) maxBitrate = 19500000LL; thisKBperMin += (((size_t)maxBitrate)*((size_t)15))>>11; VERBOSE(VB_FILE, QString(" Cardid %1: max bitrate " "%2 Kb/sec, fsID %3 max is now %4 KB/min") .arg(enc->GetCardID()) .arg(enc->GetMaxBitrate() >> 10) .arg(fsit->fsID) .arg(thisKBperMin)); } } fsMap[fsit->fsID] = thisKBperMin; if (thisKBperMin > maxKBperMin) { VERBOSE(VB_FILE, QString(" Max of %1 KB/min for fsID %2 is higher " "than the existing Max of %3 so we'll use this Max instead") .arg(thisKBperMin).arg(fsit->fsID).arg(maxKBperMin)); maxKBperMin = thisKBperMin; } }
bool CSVToolWindow::importStart() { QString mapname = atlasWindow()->map(); CSVAtlas *atlas = _atlasWindow->getAtlas(); if (mapname.isEmpty()) { QStringList mList = atlas->mapList(); if(mList.isEmpty()) { _msghandler->message(QtWarningMsg, tr("No Maps Loaded"), tr("<p>There are no maps loaded to select from. " "Either load an atlas that contains maps or " "create a new one before continuing.")); return false; } mList.sort(); bool valid; mapname = QInputDialog::getItem(this, tr("Select Map"), tr("Select Map:"), mList, 0, FALSE, &valid); if (!valid) return false; } CSVMap map = atlas->map(mapname); map.simplify(); QList<CSVMapField> fields = map.fields(); if (map.name() != mapname || fields.isEmpty()) { _msghandler->message(QtWarningMsg, tr("Invalid Map"), tr("<p>The selected map does not appear to be valid.")); return false; } CSVMap::Action action = map.action(); if (action != CSVMap::Insert) { _msghandler->message(QtWarningMsg, tr("Action not implemented"), tr("<p>The action %1 for this map is not supported.") .arg(CSVMap::actionToName(action))); return false; } if (!_data || _data->rows() < 1) { _msghandler->message(QtWarningMsg, tr("No data"), tr("<p>There are no data to process. " "Load a CSV file before continuing.")); return false; } int total = _data->rows(); int current = 0, error = 0, ignored = 0; if (! _log) _log = new LogWindow(this); if(usetransaction) QSqlQuery begin("BEGIN;"); QString errMsg; if(!map.sqlPre().trimmed().isEmpty()) { if(usetransaction) QSqlQuery savepoint("SAVEPOINT presql;"); QSqlQuery pre; if(!pre.exec(map.sqlPre())) { errMsg = QString("ERROR Running Pre SQL query: %1").arg(pre.lastError().text()); _log->_log->append("\n\n----------------------\n"); _log->_log->append(errMsg); _log->show(); _log->raise(); if(map.sqlPreContinueOnError()) { _log->_log->append(tr("\n\nContinuing with rest of import\n\n")); if(usetransaction) QSqlQuery sprollback("ROLLBACK TO SAVEPOINT presql;"); if(usetransaction) QSqlQuery savepoint("RELEASE SAVEPOINT presql;"); } else { if(usetransaction) QSqlQuery rollback("ROLLBACK;"); _msghandler->message(QtWarningMsg, tr("Error"), tr("<p>There was an error running the Pre SQL " "query. Please see the log for more details. " "Aborting transaction.")); return false; } } } QString progresstext(tr("Importing %1: %2 rows out of %3")); int expected = total; QProgressDialog *progress = new QProgressDialog(progresstext .arg(map.name()).arg(0).arg(expected), tr("Cancel"), 0, expected, this); progress->setWindowModality(Qt::WindowModal); bool userCanceled = false; QString query; QString front; QString back; QString value; QString label; QVariant var; QStringList errorList; for(current = 0; current < total; ++current) { if(usetransaction) QSqlQuery savepoint("SAVEPOINT csvinsert;"); if(action == CSVMap::Insert) { query = QString("INSERT INTO %1 ").arg(map.table()); front = "("; back = " VALUES("; QList<CSVMapField> fields = map.fields(); QMap<QString,QVariant> values; for (int i = 0; i < fields.size(); i++) { switch(fields.at(i).action()) { case CSVMapField::Action_UseColumn: { value = _data->value(current, fields.at(i).column()-1); if(value.isNull()) { switch (fields.at(i).ifNullAction()) { case CSVMapField::UseDefault: continue; case CSVMapField::UseEmptyString: { var = QVariant(QString("")); break; } case CSVMapField::UseAlternateValue: { var = QVariant(fields.at(i).valueAlt()); break; } case CSVMapField::UseAlternateColumn: { value = _data->value(current, fields.at(i).columnAlt()-1); if(value.isNull()) { switch (fields.at(i).ifNullActionAlt()) { case CSVMapField::UseDefault: continue; case CSVMapField::UseEmptyString: { var = QVariant(QString("")); break; } case CSVMapField::UseAlternateValue: { var = QVariant(fields.at(i).valueAlt()); break; } default: // Nothing var = QVariant(QString::null); } } else var = QVariant(value); break; } default: // Nothing var = QVariant(QString::null); } } else var = QVariant(value); break; } case CSVMapField::Action_UseEmptyString: { var = QVariant(QString("")); break; } case CSVMapField::Action_UseAlternateValue: { var = QVariant(fields.at(i).valueAlt()); break; } case CSVMapField::Action_UseNull: { var = QVariant(QString::null); break; } default: continue; } label = ":" + fields.at(i).name(); if(!values.empty()) { front += ", "; back += ", "; } values.insert(label, var); front += fields.at(i).name(); back += label; } if(values.empty()) { ignored++; errMsg = QString("IGNORED Record %1: There are no columns to insert").arg(current+1); errorList.append(errMsg); continue; } front += ") "; back += ")"; query += front + back; QSqlQuery qry; qry.prepare(query); QMap<QString,QVariant>::iterator vit; for(vit = values.begin(); vit != values.end(); ++vit) qry.bindValue(vit.key(), vit.value()); if(!qry.exec()) { if(usetransaction) QSqlQuery sprollback("ROLLBACK TO SAVEPOINT csvinsert;"); error++; errMsg = QString("ERROR Record %1: %2").arg(current+1).arg(qry.lastError().text()); errorList.append(errMsg); } } if (progress->wasCanceled()) { userCanceled = true; break; } if(! (current % 1000)) { progress->setLabelText(progresstext.arg(map.name()).arg(current).arg(expected)); progress->setValue(current); } } progress->setValue(total); if (error || ignored || userCanceled) { _log->_log->append(tr("Map: %1\n" "Table: %2\n" "Method: %3\n\n" "Total Records: %4\n" "# Processed: %5\n" "# Ignored: %6\n" "# Errors: %7\n\n") .arg(map.name()).arg(map.table()) .arg(CSVMap::actionToName(map.action())) .arg(total).arg(current).arg(ignored).arg(error)); _log->_log->append(errMsg); _log->_log->append(errorList.join("\n")); _log->show(); _log->raise(); if (_msghandler && // log messages there's a non-interactive message handler qobject_cast<XAbstractMessageHandler*>(_msghandler) && ! qobject_cast<InteractiveMessageHandler*>(_msghandler)) _msghandler->message(error ? QtCriticalMsg : QtWarningMsg, tr("Import Processing Status"), _log->_log->toPlainText()); } if (! userCanceled && ! map.sqlPost().trimmed().isEmpty()) { QSqlQuery post; if(!post.exec(map.sqlPost())) { errMsg = QString("ERROR Running Post SQL query: %1").arg(post.lastError().text()); _log->_log->append("\n\n----------------------\n"); _log->_log->append(errMsg); _log->show(); _log->raise(); if(usetransaction) QSqlQuery rollback("ROLLBACK;"); _msghandler->message(QtCriticalMsg, tr("Error"), tr("<p>There was an error running the post sql " "query and changes were rolled back. " "Please see the log for more details.")); return false; } } if (userCanceled) { if(usetransaction) QSqlQuery rollback("ROLLBACK;"); _log->_log->append(tr("\n\nImport canceled by user. Changes were rolled back.")); return false; } if(usetransaction) QSqlQuery commit("COMMIT"); if (! error) { _msghandler->message(QtDebugMsg, tr("Import Complete"), tr("The import of %1 completed successfully.") .arg(_currentDir)); return true; } return false; }
bool WizNoteManager::updateLocalTemplates(const QByteArray& newJsonData, QNetworkAccessManager& manager) { rapidjson::Document d; d.Parse(newJsonData.constData()); if (d.HasParseError()) return false; QString localFile = Utils::WizPathResolve::wizTemplateJsonFilePath(); bool needUpdateJs = true; QMap<int, TemplateData> localTmplMap; QFile file(localFile); if (file.open(QFile::ReadOnly)) { QTextStream stream(&file); QString jsonData = stream.readAll(); rapidjson::Document localD; localD.Parse(jsonData.toUtf8().constData()); if (!localD.HasParseError()) { if (localD.HasMember("template_js_version") && d.HasMember("template_js_version")) { needUpdateJs = (localD.FindMember("template_js_version")->value.GetString() != d.FindMember("template_js_version")->value.GetString()); } } getTemplatesFromJsonData(jsonData.toUtf8(), localTmplMap); } // if (needUpdateJs) { QString link; if (d.HasMember("template_js_link")) { link = d.FindMember("template_js_link")->value.GetString(); } if (!link.isEmpty()) { qDebug() << "get templates js file from url : " << link; QString file = Utils::WizPathResolve::wizTemplateJsFilePath(); QNetworkReply* reply = manager.get(QNetworkRequest(link)); // WizAutoTimeOutEventLoop loop(reply); loop.exec(); // if (loop.error() != QNetworkReply::NoError || loop.result().isEmpty()) return false; QByteArray ba = loop.result(); std::ofstream jsFile(file.toUtf8().constData(), std::ios::out | std::ios::trunc); jsFile << ba.constData(); } } // QMap<int, TemplateData> serverTmplMap; getTemplatesFromJsonData(newJsonData, serverTmplMap); //下载服务器上有更新的模板 for (auto it = serverTmplMap.begin(); it != serverTmplMap.end(); ++it) { auto iter = localTmplMap.find(it.key()); if (iter == localTmplMap.end()) continue; if (iter.value().strVersion != it.value().strVersion || !QFile::exists(it.value().strFileName)) { QString strUrl = WizCommonApiEntry::asServerUrl() + "/a/templates/download/" + QString::number(it.value().id); QFileInfo info(it.value().strFileName); WizFileDownloader* downloader = new WizFileDownloader(strUrl, info.fileName(), info.absolutePath() + "/", false); downloader->startDownload(); } } //删除服务器上不存在的模板 for (auto it = localTmplMap.begin(); it != localTmplMap.end(); ++it) { auto iter = serverTmplMap.find(it.key()); if (iter == localTmplMap.end()) { WizDeleteFile(it.value().strFileName); } } return true; }
QString mapLanguage(const QString &v) { static QMap<QString, QString> map; static bool initialized = false; if (!initialized) { map["us"] = "English"; map["us:intl"] = "English"; map["us:alt-intl"] = "English"; map["us:dvorak"] = "English"; map["us:rus"] = "Russian"; map["ara"] = "Arabic"; map["ara:azerty"] = "Arabic"; map["ara:azerty_digits"] = "Arabic"; map["ara:digits"] = "Arabic"; map["ara:qwerty"] = "Arabic"; map["ara:qwerty_digits"] = "Arabic"; map["al"] = "Albanian"; map["am"] = "Armenian"; map["am:phonetic"] = "Armenian"; map["az"] = "Azerbaijani"; map["az:cyrillic"] = "Azerbaijani"; map["by"] = "Belarusian"; map["by:winkeys"] = "Belarusian"; map["be"] = "Dutch"; map["be:iso-alternate"] = "Dutch"; map["be:nodeadkeys"] = "Dutch"; map["be:sundeadkeys"] = "Dutch"; map["bd"] = "Bengali"; map["bd:probhat"] = "Bengali"; map["in"] = "Hindi"; map["in:ben"] = "Bengali"; map["in:ben_probhat"] = "Bengali"; map["in:guj"] = "Gujarati"; map["in:guru"] = "Punjabi"; map["in:kan"] = "Kannada"; map["in:mal"] = "Malayalam"; map["in:ori"] = "Oriya"; map["in:tam_unicode"] = "Tamil"; map["in:tam_TAB"] = "Tamil"; map["in:tam_TSCII"] = "Tamil"; map["in:tam"] = "Tamil"; map["in:tel"] = "Telugu"; map["in:urd"] = "Urdu"; map["ba"] = "Bosnian"; map["br"] = "Portuguese"; map["br:nodeadkeys"] = "Portuguese"; map["bg"] = "Bulgarian"; map["bg:phonetic"] = "Bulgarian"; map["mm"] = "Burmese"; map["ca"] = "English"; map["ca:fr-dvorak"] = "French"; map["ca:fr-legacy"] = "French"; map["ca:multi"] = "English"; map["ca:multi-2gr"] = "English"; map["ca:ike"] = "Inuktitut"; map["hr"] = "Croatian"; map["hr:us"] = "Croatian"; map["cz"] = "Czech"; map["cz:bksl"] = "Czech"; map["cz:qwerty"] = "Czech"; map["cz:qwerty_bksl"] = "Czech"; map["dk"] = "Danish"; map["dk:nodeadkeys"] = "Danish"; map["nl"] = "Dutch"; map["bt"] = "Bhutani"; map["ee"] = "Estonian"; map["ee:nodeadkeys"] = "Estonian"; map["ir"] = "Persian"; map["fo"] = "Faroese"; map["fo:nodeadkeys"] = "Faroese"; map["fi"] = "Finnish"; map["fi:nodeadkeys"] = "Finnish"; map["fi:smi"] = "Finnish"; map["fr"] = "French"; map["fr:nodeadkeys"] = "French"; map["fr:sundeadkeys"] = "French"; map["fr:latin9"] = "French"; map["fr:latin9_nodeadkeys"] = "French"; map["fr:latin9_sundeadkeys"] = "French"; map["fr:dvorak"] = "French"; map["ge"] = "Georgian"; map["ge:ru"] = "Russian"; map["de"] = "German"; map["de:deadacute"] = "German"; map["de:deadgraveacute"] = "German"; map["de:nodeadkeys"] = "German"; map["de:ro"] = "Romanian"; map["de:ro_nodeadkeys"] = "Romanian"; map["de:dvorak"] = "German"; map["gr"] = "Greek"; map["gr:extended"] = "Greek"; map["gr:nodeadkeys"] = "Greek"; map["gr:polytonic"] = "Greek"; map["hu"] = "Hungarian"; map["hu:standard"] = "Hungarian"; map["hu:nodeadkeys"] = "Hungarian"; map["hu:qwerty"] = "Hungarian"; map["hu:101_qwertz_comma_dead"] = "Hungarian"; map["hu:101_qwertz_comma_nodead"] = "Hungarian"; map["hu:101_qwertz_dot_dead"] = "Hungarian"; map["hu:101_qwertz_dot_nodead"] = "Hungarian"; map["hu:101_qwerty_comma_dead"] = "Hungarian"; map["hu:101_qwerty_comma_nodead"] = "Hungarian"; map["hu:101_qwerty_dot_dead"] = "Hungarian"; map["hu:101_qwerty_dot_nodead"] = "Hungarian"; map["hu:102_qwertz_comma_dead"] = "Hungarian"; map["hu:102_qwertz_comma_nodead"] = "Hungarian"; map["hu:102_qwertz_dot_dead"] = "Hungarian"; map["hu:102_qwertz_dot_nodead"] = "Hungarian"; map["hu:102_qwerty_comma_dead"] = "Hungarian"; map["hu:102_qwerty_comma_nodead"] = "Hungarian"; map["hu:102_qwerty_dot_dead"] = "Hungarian"; map["hu:102_qwerty_dot_nodead"] = "Hungarian"; map["is"] = "Icelandic"; map["is:Sundeadkeys"] = "Icelandic"; map["is:nodeadkeys"] = "Icelandic"; map["il"] = "Hebrew"; map["il:lyx"] = "Hebrew"; map["il:si1452"] = "Hebrew"; map["il:phonetic"] = "Hebrew"; map["it"] = "Italian"; map["it:nodeadkeys"] = "Italian"; map["jp"] = "Japanese"; map["kg"] = "Kirghiz"; map["la"] = "Laothian"; map["latam"] = "Spanish"; map["latam:nodeadkeys"] = "Spanish"; map["latam:sundeadkeys"] = "Spanish"; map["lt"] = "Lithuanian"; map["lt:std"] = "Lithuanian"; map["lt:us"] = "Lithuanian"; map["lv"] = "Latvian"; map["lv:apostrophe"] = "Latvian"; map["lv:tilde"] = "Latvian"; map["lv:fkey"] = "Latvian"; map["mao"] = "Maori"; map["mkd"] = "Macedonian"; map["mkd:nodeadkeys"] = "Macedonian"; map["mt"] = "Maltese"; map["mt:us"] = "Maltese"; map["mn"] = "Mongolian"; map["no"] = "Norwegian"; map["no:nodeadkeys"] = "Norwegian"; map["no:dvorak"] = "Norwegian"; map["no:smi"] = "Norwegian"; map["no:smi_nodeadkeys"] = "Norwegian"; map["pl"] = "Polish"; map["pl:qwertz"] = "Polish"; map["pl:dvorak"] = "Polish"; map["pl:dvorak_quotes"] = "Polish"; map["pl:dvorak_altquotes"] = "Polish"; map["pt"] = "Portuguese"; map["pt:nodeadkeys"] = "Portuguese"; map["pt:sundeadkeys"] = "Portuguese"; map["ro"] = "Romanian"; map["ro:us"] = "English"; map["ro:de"] = "German"; map["ru"] = "Russian"; map["ru:phonetic"] = "Russian"; map["ru:typewriter"] = "Russian"; map["ru:winkeys"] = "Russian"; map["srp"] = "Serbian"; map["srp:yz"] = "Serbian"; map["srp:latin"] = "Serbian"; map["srp:latinunicode"] = "Serbian"; map["srp:latinyz"] = "Serbian"; map["srp:latinunicodeyz"] = "Serbian"; map["srp:alternatequotes"] = "Serbian"; map["srp:latinalternatequotes"] = "Serbian"; map["si"] = "Slovenian"; map["sk"] = "Slovak"; map["sk:bksl"] = "Slovak"; map["sk:qwerty"] = "Slovak"; map["sk:qwerty_bksl"] = "Slovak"; map["es"] = "Spanish"; map["es:nodeadkeys"] = "Spanish"; map["es:sundeadkeys"] = "Spanish"; map["es:dvorak"] = "Spanish"; map["se"] = "Swedish"; map["se:nodeadkeys"] = "Swedish"; map["se:dvorak"] = "Swedish"; map["se:rus"] = "Russian"; map["se:rus_nodeadkeys"] = "Russian"; map["se:smi"] = "Swedish"; map["ch"] = "German"; map["ch:de_nodeadkeys"] = "German"; map["ch:de_sundeadkeys"] = "German"; map["ch:fr"] = "French"; map["ch:fr_nodeadkeys"] = "French"; map["ch:fr_sundeadkeys"] = "French"; map["sy"] = "Arabic"; map["sy:syc"] = "Arabic"; map["sy:syc_phonetic"] = "Arabic"; map["tj"] = "Tajik"; map["lk"] = "Sinhala"; map["lk:tam_unicode"] = "Tamil"; map["lk:tam_TAB"] = "Tamil"; map["lk:tam_TSCII"] = "Tamil"; map["lk:sin_phonetic"] = "Sinhala"; map["th"] = "Thai"; map["th:tis"] = "Thai"; map["th:pat"] = "Thai"; map["tr"] = "Turkish"; map["tr:f"] = "Turkish"; map["tr:alt"] = "Turkish"; map["ua"] = "Ukrainian"; map["ua:phonetic"] = "Ukrainian"; map["ua:typewriter"] = "Ukrainian"; map["ua:winkeys"] = "Ukrainian"; map["ua:rstu"] = "Ukrainian"; map["ua:rstu_ru"] = "Ukrainian"; map["gb"] = "English"; map["gb:intl"] = "English"; map["gb:dvorak"] = "English"; map["uz"] = "Uzbek"; map["vn"] = "Vietnamese"; map["nec_vndr/jp"] = "Japanese"; map["ie"] = "Irish"; map["ie:CloGaelach"] = "Gaelic"; map["ie:UnicodeExpert"] = "Irish"; map["ie:ogam"] = "Gaelic"; map["ie:ogam_is434"] = "Gaelic"; map["pk"] = "Urdu"; initialized = true; } return map.value(v, v); }
// the value of pkgitem_name differs from the version in createdbobj.cpp int CreateFunction::upsertPkgItem(const int pkgheadid, const QMap<QString, int> oldoids, const QString argtypes, const int itemid, QString &errMsg) { if (DEBUG) qDebug("CreateFunction::upsertPkgItem(%d, QMap, %s, %d, &errMsg)", pkgheadid, qPrintable(argtypes), itemid); if (pkgheadid < 0) return 0; int pkgitemid = -1; QSqlQuery select; select.prepare("SELECT pkgitem_id " "FROM pkgitem " "WHERE ((pkgitem_pkghead_id=:headid)" " AND (pkgitem_type=:type)" " AND (pkgitem_item_id=:id));"); select.bindValue(":headid", pkgheadid); select.bindValue(":type", _pkgitemtype); select.bindValue(":id", oldoids.value(argtypes)); select.exec(); if (select.first()) pkgitemid = select.value(0).toInt(); if (select.lastError().type() != QSqlError::NoError) { errMsg = _sqlerrtxt.arg(_filename) .arg(select.lastError().databaseText()) .arg(select.lastError().driverText()); return -20; } QSqlQuery upsert; if (pkgitemid >= 0) upsert.prepare("UPDATE pkgitem SET pkgitem_descrip=:descrip," " pkgitem_item_id=:itemid " "WHERE (pkgitem_id=:id);"); else { upsert.exec("SELECT NEXTVAL('pkgitem_pkgitem_id_seq');"); if (upsert.first()) pkgitemid = upsert.value(0).toInt(); else if (upsert.lastError().type() != QSqlError::NoError) { QSqlError err = upsert.lastError(); errMsg = _sqlerrtxt.arg(_name).arg(err.driverText()).arg(err.databaseText()); return -21; } upsert.prepare("INSERT INTO pkgitem (" " pkgitem_id, pkgitem_pkghead_id, pkgitem_type," " pkgitem_item_id, pkgitem_name, pkgitem_descrip" ") VALUES (" " :id, :headid, :type," " :itemid, :name, :descrip);"); } upsert.bindValue(":id", pkgitemid); upsert.bindValue(":headid", pkgheadid); upsert.bindValue(":type", _pkgitemtype); upsert.bindValue(":itemid", itemid); upsert.bindValue(":name", _name + "(" + argtypes + ")"); upsert.bindValue(":descrip", _comment); if (!upsert.exec()) { QSqlError err = upsert.lastError(); errMsg = _sqlerrtxt.arg(_name).arg(err.driverText()).arg(err.databaseText()); return -22; } return pkgitemid; }