RenderOptionsDialog::RenderOptionsDialog() : QDialog(0, Qt::CustomizeWindowHint | Qt::WindowTitleHint) { setWindowOpacity(0.75); setWindowTitle(tr("Options (double click to flip)")); QGridLayout *layout = new QGridLayout; setLayout(layout); layout->setColumnStretch(1, 1); int row = 0; QCheckBox *check = new QCheckBox(tr("Dynamic cube map")); check->setCheckState(Qt::Unchecked); // Dynamic cube maps are only enabled when multi-texturing and render to texture are available. check->setEnabled(glActiveTexture && glGenFramebuffersEXT); connect(check, SIGNAL(stateChanged(int)), this, SIGNAL(dynamicCubemapToggled(int))); layout->addWidget(check, 0, 0, 1, 2); ++row; QPalette palette; // Load all .par files // .par files have a simple syntax for specifying user adjustable uniform variables. QSet<QByteArray> uniforms; QList<QString> filter = QStringList("*.par"); QList<QFileInfo> files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable); foreach (QFileInfo fileInfo, files) { QFile file(fileInfo.absoluteFilePath()); if (file.open(QIODevice::ReadOnly)) { while (!file.atEnd()) { QList<QByteArray> tokens = file.readLine().simplified().split(' '); QList<QByteArray>::const_iterator it = tokens.begin(); if (it == tokens.end()) continue; QByteArray type = *it; if (++it == tokens.end()) continue; QByteArray name = *it; bool singleElement = (tokens.size() == 3); // type, name and one value char counter[10] = "000000000"; int counterPos = 8; // position of last digit while (++it != tokens.end()) { m_parameterNames << name; if (!singleElement) { m_parameterNames.back() += "["; m_parameterNames.back() += counter + counterPos; m_parameterNames.back() += "]"; int j = 8; // position of last digit ++counter[j]; while (j > 0 && counter[j] > '9') { counter[j] = '0'; ++counter[--j]; } if (j < counterPos) counterPos = j; } if (type == "color") { layout->addWidget(new QLabel(m_parameterNames.back())); bool ok; ColorEdit *colorEdit = new ColorEdit(it->toUInt(&ok, 16), m_parameterNames.size() - 1); m_parameterEdits << colorEdit; layout->addWidget(colorEdit); connect(colorEdit, SIGNAL(colorChanged(QRgb,int)), this, SLOT(setColorParameter(QRgb,int))); ++row; } else if (type == "float") { layout->addWidget(new QLabel(m_parameterNames.back())); bool ok; FloatEdit *floatEdit = new FloatEdit(it->toFloat(&ok), m_parameterNames.size() - 1); m_parameterEdits << floatEdit; layout->addWidget(floatEdit); connect(floatEdit, SIGNAL(valueChanged(float,int)), this, SLOT(setFloatParameter(float,int))); ++row; } }
void LibraryFile::readFile() { if (m_exists) { bool ok = true; QFile file(localFile()); if (file.open(QIODevice::ReadOnly)) { QDataStream stream(&file); char header[11]; stream.readRawData(header, 11); if (strncmp(header, "KXStitchLib", 11) == 0) { qint16 version; qint32 count; qint32 key; // version 1 of library format qint32 modifier; // version 1 of library format qint16 baseline; // version 1 of library format quint16 checksum; // version 1 of library format ok = true; QByteArray data; LibraryPattern *libraryPattern; QProgressDialog progress(0); progress.setLabelText(i18n("Loading Library %1", file.fileName())); stream >> version; switch (version) { case 1: progress.setRange(file.pos(), file.size()); progress.setValue(0); progress.show(); while (!file.atEnd() && ok) { stream >> key; stream >> modifier; stream >> baseline; stream >> checksum; // no longer used stream >> data; Qt::KeyboardModifiers replacedModifiers; if (modifier & 0x0100) { replacedModifiers |= Qt::ShiftModifier; } if (modifier & 0x0200) { replacedModifiers |= Qt::ControlModifier; } if (modifier & 0x0400) { replacedModifiers |= Qt::AltModifier; } if (modifier & 0x0800) { replacedModifiers |= Qt::MetaModifier; } if (checksum == qChecksum(data.data(), data.size())) { m_libraryPatterns.append(new LibraryPattern(data, key, replacedModifiers, baseline)); } else { KMessageBox::error(nullptr, i18n("Failed to read a pattern from the library %1.\n%2", localFile(), file.errorString()), i18n("Failed to read library.")); ok = false; } progress.setValue(file.pos()); } break; case 100: stream >> count; progress.setRange(0, count); progress.setValue(0); progress.show(); while (count--) { libraryPattern = new LibraryPattern; stream >> *libraryPattern; m_libraryPatterns.append(libraryPattern); progress.setValue(progress.value() + 1); } break; default: // not supported // throw exception break; } } file.close(); m_read = true; } else {
qint64 RCCFileInfo::writeDataBlob(RCCResourceLibrary &lib, qint64 offset, QString *errorMessage) { const bool text = (lib.m_format == RCCResourceLibrary::C_Code || lib.m_format == RCCResourceLibrary::Go_Code); //capture the offset m_dataOffset = offset; //find the data to be written QFile file(m_fileInfo.absoluteFilePath()); if (!file.open(QFile::ReadOnly)) { *errorMessage = msgOpenReadFailed(m_fileInfo.absoluteFilePath(), file.errorString()); return 0; } QByteArray data = file.readAll(); #ifndef QT_NO_COMPRESS // Check if compression is useful for this file if (m_compressLevel != 0 && data.size() != 0) { QByteArray compressed = qCompress(reinterpret_cast<uchar *>(data.data()), data.size(), m_compressLevel); int compressRatio = int(100.0 * (data.size() - compressed.size()) / data.size()); if (compressRatio >= m_compressThreshold) { data = compressed; m_flags |= Compressed; } } #endif // QT_NO_COMPRESS // some info if (text) { lib.writeString(" // "); lib.writeByteArray(m_fileInfo.absoluteFilePath().toLocal8Bit()); lib.writeString("\n "); } // write the length lib.writeNumber4(data.size()); if (text) lib.writeString("\n "); offset += 4; // write the payload const char *p = data.constData(); if (text) { for (int i = data.size(), j = 0; --i >= 0; --j) { lib.writeHex(*p++); if (j == 0) { lib.writeString("\n "); j = 16; } } } else { for (int i = data.size(); --i >= 0; ) lib.writeChar(*p++); } offset += data.size(); // done if (text) lib.writeString("\n "); return offset; }
bool Sokoban::loadMap(std::string filename){ int D = 0; // make pointer to file std::cout << "Loading file... "; std::ifstream file(filename); if(!file.is_open()){ std::cout << "Couldn't open the file" << std::endl; return false; } std::cout << "Done." << std::endl; // read file letter by letter char c; // load file dimensions and diamonds char entry = 0; int value = 0; std::cout << "Loading map settings... "; do{ file.get(c); if(c >= '0' && c <= '9'){ value = value * 10 + (c - '0'); } else{ switch (entry) { case 0: map_size_.x_ = value; break; case 1: map_size_.y_ = value; break; case 2: D = value; break; default: break; } entry++; value = 0; } }while (!(c == '\0' || c == '\n')); std::cout << "Done." << std::endl; std::cout << "w: " << (int)map_size_.x_ << ", h: " << (int)map_size_.y_ << ", D: " << D << std::endl; std::cout << "Loading Map..."; // init vectors diamonds_.clear(); goals_.clear(); map_.resize(map_size_.y_); for(int i = 0; i < map_size_.y_; i++){ (map_[i]).resize(map_size_.x_); } // load map // X || ' ' = wall, J = diamond, G = goal, . = free space, M = robot, * = J + G int x = 0; int y = 0; do{ file.get(c); if(c == 'X' || c == ' '){ map_[y][x] = MAP_WALL; } else if(c == 'J'){ map_[y][x] = MAP_FREE; diamonds_.emplace_back(pos_t(x,y)); } else if(c == 'G'){ map_[y][x] = MAP_GOAL; goals_.emplace_back(pos_t(x,y)); } else if(c == '*'){ map_[y][x] = MAP_GOAL; goals_.emplace_back(pos_t(x,y)); diamonds_.emplace_back(pos_t(x,y)); } else if(c == 'M'){ map_[y][x] = MAP_FREE; robot_.x_ = x; robot_.y_ = y; } else if(c == '.'){ map_[y][x] = MAP_FREE; } else { y++; x = -1; } x++; }while (!file.eof()); std::cout << "Done." << std::endl; // close stream file.close(); // return true return true; }
/*------------------------------------------------------------------------------------------------------------------ -- FUNCTION: OpenFile -- -- DATE: November 29, 2013 -- -- REVISIONS: none -- -- DESIGNER: Jordan Marling -- -- PROGRAMMER: Jordan Marling -- -- RETURNS: an fstream object for the file -- -- NOTES: -- Used for opening a file using a location path ----------------------------------------------------------------------------------------------------------------------*/ std::fstream OpenFile(std::string FileLocation) { std::fstream file(FileLocation); return file; }
csRef<iString> csGetPluginMetadata (const char* fullPath, csRef<iDocument>& metadata) { // @@@ There's a small inefficiency here. This function, when given a // filename of <blah>.dll or <blah>.csplugin, first checks <blah>.dll for // embedded metadata and then for the existence of a <blah>.csplugin file. // However, the csScanPluginDir() function already emits a <blah>.csplugin // file name when such a file was found, <blah>.dll otherwise. This // information can probably be reused. CS_ALLOC_STACK_ARRAY (char, dllPath, strlen (fullPath) + 5); strcpy (dllPath, fullPath); char* dot = strrchr (dllPath, '.'); bool isCsPlugin = (dot && (strcasecmp (dot, ".csplugin") == 0)); if (!dot || isCsPlugin || strcasecmp (dot, ".dll") != 0) { if (isCsPlugin) strcpy (dot, ".dll"); else strcat (dllPath, ".dll"); } csRef<iString> result; metadata = 0; #if defined(CS_EMBED_PLUGIN_META) result = InternalGetPluginMetadata (dllPath, metadata); #endif // Check whether a .csplugin file exists as well // @@@ This makes the assumption that such might only exists if this function // was called with a <blah>.csplugin filename. if (isCsPlugin) { csPhysicalFile file (fullPath, "rb"); if (file.GetStatus() == VFS_STATUS_OK) { if (metadata.IsValid()) { csString errstr; errstr.Format ("'%s' contains embedded metadata, " "but external '%s' exists as well. Ignoring the latter.", dllPath, fullPath); result.AttachNew (new scfString (errstr)); } else { csRef<iDocumentSystem> docsys = csPtr<iDocumentSystem>(new csTinyDocumentSystem ()); csRef<iDocument> doc = docsys->CreateDocument(); char const* errmsg = doc->Parse (&file, true); if (errmsg == 0) // Parse successful. metadata = doc; else // Parse failed. { csString errstr; errstr.Format ("Error parsing metadata from '%s': %s", fullPath, errmsg); result.AttachNew (new scfString (errstr)); } } } } return result; }
bool QPEvents::handleEvent(const EventAction& ev) { if (ev.type == EventAction::Internal) { if (ev.action == "email") { QString receiver = ev.arguments[0]; TeamMember member; if (receiver == "teamleader") member = Project::ref()->teamLeader(); else if (receiver.startsWith("subprojectleader-")) { QString s = receiver.remove("subprojectleader-"); member = Project::ref()->subprojectLeader(s); SubProject subProject; QValueList<SubProject> *subprojects = Project::ref()->subprojects(); for (uint i = 0 ; i < subprojects->count(); i++) { if ((*subprojects)[i].name == s) { subProject = (*subprojects)[i]; break; } } if (!subProject.location.isEmpty() && !ev.arguments[2].startsWith(subProject.location)) { kdDebug(24000) << ev.arguments[2] << " is not part of the " << subProject.name << "subproject \"" << subProject.location << "\". " << endl; return true; } } else if (receiver.startsWith("taskleader-")) member = Project::ref()->taskLeader(receiver.remove("taskleader-")); QString body; for (uint i = 2; i < ev.arguments.count(); i++) body += ev.arguments[i] + "\n"; kapp->invokeMailer(member.name + "<" + member.email + ">", "", "", ev.arguments[1], body, "", QStringList(), ""); return true; } if (ev.action == "log") { QString logFile = ev.arguments[0]; KURL url = KURL::fromPathOrURL(logFile); if (url.isValid() && !url.isLocalFile()) { KMessageBox::sorry(0L, i18n("Logging to remote files is not supported.")); return false; } if (!logFile.startsWith("/")) { url = Project::ref()->projectBaseURL(); url.addPath(logFile); if (!url.isLocalFile()) { KMessageBox::sorry(0L, i18n("Logging to files inside a remote project is not supported.")); return false; } } QFile file(url.path()); bool result; if (ev.arguments[2] == "create_new") result = file.open(IO_WriteOnly); else result = file.open(IO_WriteOnly | IO_Append); if (result) { QTextStream stream(&file); stream.setEncoding(QTextStream::UnicodeUTF8); //Note: the log text should not be translated. QString s = QDateTime::currentDateTime().toString(Qt::ISODate) + ": "; s.append( "Event : " + m_eventName + " : "); s.append( "Action: " + ev.action + " : "); if (ev.arguments[1] == "full") { s.append( "Arguments: "); for (uint i = 1; i < ev.arguments.count(); i++) s.append(ev.arguments[i] + " | "); } s[s.length() - 1] = '\n'; stream << s; file.close(); } if (!result) { KMessageBox::sorry(0L, i18n("<qt>Logging failed. Check that you have write access to <i>%1</i>.").arg(url.path())); return false; } } else KMessageBox::sorry(0L, i18n("<qt>Unsupported internal event action : <b>%1</b>.</qt>").arg(ev.action)); } else if (ev.type == EventAction::External) { //KMessageBox::sorry(0L, i18n("External event actions are not yet supported.")); if (ev.action == "script" || ev.action =="action") { QString name = ev.arguments[0]; KAction *action = quantaApp->actionCollection()->action(name); TagAction *tagAction = dynamic_cast<TagAction*>(action); if (tagAction) { bool blocking = (ev.arguments[1] == "yes"); EventAction event = ev; event.arguments.remove(event.arguments.at(1)); tagAction->addArguments(event.arguments); tagAction->execute(blocking); } else if (action) { action->activate(); } else KMessageBox::sorry(0L, i18n("<qt>The <b>%1</b> script action was not found on your system.</qt>").arg(name), i18n("Action Execution Error")); } else KMessageBox::sorry(0L, i18n("Unsupported external event action.")); } else KMessageBox::sorry(0L, i18n("Unknown event type.")); return false; }
void MainWindow::openFile() { // If the current model has been modified, warn the user before opening the new file QMessageBox::StandardButton proceed = QMessageBox::Ok; if (modelLoaded) if (model->wasModified()) proceed = QMessageBox::question(this, tr("Network Editor for SUMO"), tr("Model has been modified and not saved. Continue opening a new file?"), QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel); if (proceed == QMessageBox::Ok) { // Get file name from File Dialog QString filePath = QFileDialog::getOpenFileName(this, tr("Open SUMO Network file"), xmlPath, tr("XML Network files (*.net.xml)")); QCoreApplication::processEvents(); // Open file if (!filePath.isEmpty()) { QFile file(filePath); if (file.open(QIODevice::ReadOnly)) { // Start counting opening time QTime t; t.start(); // Create the model, parsing XML data first statusBar()->showMessage(tr("Loading XML file...")); Model *newModel = new Model(&file, this); // If the file has valid XML data, continue loading the model if (newModel->xmlDataParsed()) { // Delete the old model and connect the new one if (modelLoaded) delete model; connect(newModel, SIGNAL(statusUpdate(QString)), statusBar(), SLOT(showMessage(QString))); // Create the item selection model so that it is passed onto the // individual graphic elements as they are created treeSelections = new QItemSelectionModel(newModel); newModel->setSelectionModel(treeSelections); // Interpret XML tree and create the traffic network elements newModel->loadModel(); // Connect model with tree view tView->setModel(newModel); tView->setSelectionModel(treeSelections); tView->resizeColumnToContents(0); tView->resizeColumnToContents(1); // Connect model with network view nView->setScene(newModel->netScene); nView->setSelectionModel(treeSelections); nView->zoomExtents(); nView->setRenderHint(QPainter::Antialiasing, true); // Connect model with controls and properties view controls->reset(); controls->model = newModel; pView->model = newModel; eView->model = newModel; controlWidget->show(); propsWidget->show(); editWidget->show(); // Replace old model by new model model = newModel; modelLoaded = true; xmlPath = filePath; // Update window title QFileInfo fileInfo(file.fileName()); QString filename(fileInfo.fileName()); setWindowTitle(filename + tr(" - Network Editor for SUMO")); // Connect signals and slots between all views connect(tView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(showItem(QModelIndex))); connect(nView, SIGNAL(updateStatusBar(QString)), statusBar(), SLOT(showMessage(QString))); connect(treeSelections, SIGNAL(selectionChanged(QItemSelection, QItemSelection)), model, SLOT(selectionChanged(QItemSelection, QItemSelection))); connect(treeSelections, SIGNAL(selectionChanged(QItemSelection, QItemSelection)), pView, SLOT(selectionChanged(QItemSelection, QItemSelection))); connect(treeSelections, SIGNAL(selectionChanged(QItemSelection, QItemSelection)), eView, SLOT(selectionChanged(QItemSelection, QItemSelection))); connect(treeSelections, SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(scrollTo(QItemSelection, QItemSelection))); connect(model, SIGNAL(attrUpdate(QItemSelection, QItemSelection)), pView, SLOT(selectionChanged(QItemSelection, QItemSelection))); connect(model, SIGNAL(attrUpdate(QItemSelection, QItemSelection)), eView, SLOT(selectionChanged(QItemSelection, QItemSelection))); statusBar()->showMessage(tr("Ready. Model loaded in %1ms.").arg(t.elapsed())); } else { // The XML data in the file was not valid, so do not load the model delete newModel; QMessageBox::warning(this, tr("Network Editor for SUMO"), tr("Error parsing XML data.")); } // Close file file.close(); } } } }
Sprited::Sprited(const char *spriteName, Camera *camera = 0) : Movable(camera), spriteName(spriteName) { std::string path = "./res/sprites/"; path += spriteName; path += ".json"; std::ifstream file(path.c_str()); Json::Value root; Json::Reader reader; if (!reader.parse(file, root)) { std::cerr << "JSON parsing error: " << reader.getFormattedErrorMessages() << std::endl; } this->width = root["width"].asInt(); this->height = root["height"].asInt(); Json::Value jAnimations = root["animations"]; for (Json::ValueIterator animationsIterator = jAnimations.begin(); animationsIterator != jAnimations.end(); animationsIterator++) { Json::Value jAnimation = *animationsIterator; Animation *animation = new Animation(spriteName, animationsIterator.key().asCString(), jAnimation["fps"].asInt()); this->hold(animation, TRACE); Json::Value jFrames = jAnimation["frames"]; for (Json::ValueIterator framesIterator = jFrames.begin(); framesIterator != jFrames.end(); framesIterator++) { Json::Value jFrame = *framesIterator; sf::Vector2i frame; frame.x = jFrame[0].asInt(); frame.y = jFrame[1].asInt(); animation->frames.push_back(frame); } animations[animationsIterator.key().asString()] = animation; if (!this->currentAnimation) { // this->setAnimation(animationsIterator.key().asCString()); this->currentAnimation = animation; // std::cerr << "Current animation: " << animationsIterator.key().asCString() << std::endl; } } std::string texturePath = "./res/textures/"; texturePath += root["texture"].asString(); this->texture.loadFromFile(texturePath.c_str()); this->texture.setSmooth(true); this->sprite = sf::Sprite(this->texture); this->sprite.setTextureRect(sf::IntRect(0, 0, this->width, this->height)); this->rOrigin = sf::Vector2f(root["origin"]["x"].asInt(), root["origin"]["y"].asInt()); this->sprite.setOrigin(this->rOrigin); this->oHitbox.left = root["hitbox"][0].asFloat(); this->oHitbox.top = root["hitbox"][1].asFloat(); this->oHitbox.width = root["hitbox"][2].asFloat() - this->oHitbox.left; this->oHitbox.height = root["hitbox"][3].asFloat() - this->oHitbox.top; this->oLightbox.left = root["lightbox"][0].asFloat(); this->oLightbox.top = root["lightbox"][1].asFloat(); this->oLightbox.width = root["lightbox"][2].asFloat() - this->oLightbox.left; this->oLightbox.height = root["lightbox"][3].asFloat() - this->oLightbox.top; // std::cout << this->oHitbox.left << "/" << this->oHitbox.top << "/" << this->oHitbox.width << "/" << this->oHitbox.height; }
void OpenBalances::slotImport() { QString start = ""; QString filter = "Import Files (*.xml)"; QString filePath = QFileDialog::getOpenFileName(start, filter, this); if (filePath.isEmpty()) return; QFile file(filePath); if (!file.open(IO_ReadOnly)) { QString message = tr("Can't open import file: %1").arg(filePath); QMessageBox::critical(this, tr("Error"), message); return; } QApplication::setOverrideCursor(waitCursor); qApp->processEvents(); QDomDocument doc; QString errorMsg; int errorLine, errorCol; if (!doc.setContent(&file, &errorMsg, &errorLine, &errorCol)) { QApplication::restoreOverrideCursor(); qApp->beep(); QString message = tr("Error processing the import file on line\n" "%1, column %2:\n\n%3").arg(errorLine) .arg(errorCol).arg(errorMsg); QMessageBox::critical(this, tr("Error"), message); return; } if (doc.doctype().name() != "BALANCES") { QApplication::restoreOverrideCursor(); qApp->beep(); QString message = tr("The import file is not the right type of\n" "XML file for Quasar to use."); QMessageBox::critical(this, tr("Error"), message); return; } file.close(); _errors = 0; _customers->clear(); _vendors->clear(); _items->clear(); _accounts->clear(); QDomElement root = doc.documentElement(); unsigned int i; for (i = 0; i < root.childNodes().count(); ++i) { QDomNode node = root.childNodes().item(i); if (node.isNull()) continue; QDomElement e = node.toElement(); if (e.isNull()) continue; QString tag = e.tagName(); QString text = e.text(); QDomNodeList nodes = e.childNodes(); if (tag == "account") { QDomNodeList nodes = e.childNodes(); importAccount(nodes); } else if (tag == "customer") { QDomNodeList nodes = e.childNodes(); importCustomer(nodes); } else if (tag == "vendor") { QDomNodeList nodes = e.childNodes(); importVendor(nodes); } else if (tag == "item") { QDomNodeList nodes = e.childNodes(); importItem(nodes); } else { warning("Unknown tag: " + tag); } } _customers->appendRow(new VectorRow(_customers->columns())); _vendors->appendRow(new VectorRow(_vendors->columns())); _items->appendRow(new VectorRow(_items->columns())); _accounts->appendRow(new VectorRow(_accounts->columns())); recalculate(); QApplication::restoreOverrideCursor(); qApp->beep(); if (_errors == 0) { QString message = tr("Import completed successfully"); QMessageBox::information(this, tr("Status"), message); } else { QString message; if (_errors == 1) message = tr("Import completed with %1 error").arg(_errors); else message = tr("Import completed with %1 errors").arg(_errors); QMessageBox::critical(this, tr("Status"), message); } }
void Writer::writeToFile(const std::string& path, const Value& value) { File file(path, "wt"); FileAppender appender(file); write(appender, value, 0); }
void file_server::main(std::string file_name) { std::string path; if(!check_in_document_root(file_name,path)) { show404(); return; } int s=file_mode(path); if((s & S_IFDIR)) { std::string path2; int mode_2=0; bool have_index = check_in_document_root(file_name+"/" + index_file_ ,path2); if(have_index) { mode_2 = file_mode(path2); have_index = (mode_2 & S_IFREG) != 0; } if( !file_name.empty() && file_name[file_name.size()-1]!='/' // not ending with "/" as should && (have_index || list_directories_) ) { response().set_redirect_header(file_name + "/"); response().out()<<std::flush; return; } if(have_index) { path = path2; s=mode_2; } else { if(list_directories_) list_dir(file_name,path); else show404(); return; } } if(!(s & S_IFREG)) { show404(); return; } std::string ext; size_t pos = path.rfind('.'); if(pos != std::string::npos) ext=path.substr(pos); mime_type::const_iterator p=mime_.find(ext); if(p!=mime_.end()) response().content_type(p->second); else response().content_type("application/octet-stream"); if(!allow_deflate_) { response().io_mode(http::response::nogzip); } booster::nowide::ifstream file(path.c_str(),std::ios_base::binary); if(!file) { show404(); return; } response().out()<<file.rdbuf(); // write stream to stream }
// static void LLPreviewGesture::onLoadComplete(LLVFS *vfs, const LLUUID& asset_uuid, LLAssetType::EType type, void* user_data, S32 status, LLExtStat ext_status) { LLUUID* item_idp = (LLUUID*)user_data; LLPreview* preview = LLPreview::find(*item_idp); if (preview) { LLPreviewGesture* self = (LLPreviewGesture*)preview; if (0 == status) { LLVFile file(vfs, asset_uuid, type, LLVFile::READ); S32 size = file.getSize(); char* buffer = new char[size+1]; file.read((U8*)buffer, size); /*Flawfinder: ignore*/ buffer[size] = '\0'; LLMultiGesture* gesture = new LLMultiGesture(); LLDataPackerAsciiBuffer dp(buffer, size+1); BOOL ok = gesture->deserialize(dp); if (ok) { // Everything has been successful. Load up the UI. self->loadUIFromGesture(gesture); self->mStepList->selectFirstItem(); self->mDirty = FALSE; self->refresh(); } else { llwarns << "Unable to load gesture" << llendl; } delete gesture; gesture = NULL; delete [] buffer; buffer = NULL; self->mAssetStatus = PREVIEW_ASSET_LOADED; } else { LLViewerStats::getInstance()->incStat( LLViewerStats::ST_DOWNLOAD_FAILED ); if( LL_ERR_ASSET_REQUEST_NOT_IN_DATABASE == status || LL_ERR_FILE_EMPTY == status) { LLDelayedGestureError::gestureMissing( *item_idp ); } else { LLDelayedGestureError::gestureFailedToLoad( *item_idp ); } llwarns << "Problem loading gesture: " << status << llendl; self->mAssetStatus = PREVIEW_ASSET_ERROR; } } delete item_idp; item_idp = NULL; }
void LLPreviewGesture::saveIfNeeded() { if (!gAssetStorage) { llwarns << "Can't save gesture, no asset storage system." << llendl; return; } if (!mDirty) { return; } // Copy the UI into a gesture LLMultiGesture* gesture = createGesture(); // Serialize the gesture S32 max_size = gesture->getMaxSerialSize(); char* buffer = new char[max_size]; LLDataPackerAsciiBuffer dp(buffer, max_size); BOOL ok = gesture->serialize(dp); // <edit> //if (dp.getCurrentSize() > 1000) if(0) // </edit> { LLNotificationsUtil::add("GestureSaveFailedTooManySteps"); delete gesture; gesture = NULL; } else if (!ok) { LLNotificationsUtil::add("GestureSaveFailedTryAgain"); delete gesture; gesture = NULL; } else { // Every save gets a new UUID. Yup. LLTransactionID tid; LLAssetID asset_id; tid.generate(); asset_id = tid.makeAssetID(gAgent.getSecureSessionID()); LLVFile file(gVFS, asset_id, LLAssetType::AT_GESTURE, LLVFile::APPEND); S32 size = dp.getCurrentSize(); file.setMaxSize(size); file.write((U8*)buffer, size); BOOL delayedUpload = FALSE; // Upload that asset to the database LLViewerInventoryItem* item = (LLViewerInventoryItem*) getItem(); if (item) { std::string agent_url = gAgent.getRegion()->getCapability("UpdateGestureAgentInventory"); std::string task_url = gAgent.getRegion()->getCapability("UpdateGestureTaskInventory"); if (mObjectUUID.isNull() && !agent_url.empty()) { //need to disable the preview floater so item //isn't re-saved before new asset arrives //fake out refresh. item->setComplete(FALSE); refresh(); item->setComplete(TRUE); // Saving into agent inventory LLSD body; body["item_id"] = mItemUUID; LLHTTPClient::post(agent_url, body, new LLUpdateAgentInventoryResponder(body, asset_id, LLAssetType::AT_GESTURE)); delayedUpload = TRUE; } else if (!mObjectUUID.isNull() && !task_url.empty()) { // Saving into task inventory LLSD body; body["task_id"] = mObjectUUID; body["item_id"] = mItemUUID; LLHTTPClient::post(task_url, body, new LLUpdateTaskInventoryResponder(body, asset_id, LLAssetType::AT_GESTURE)); } else if (gAssetStorage) { LLLineEditor* descEditor = getChild<LLLineEditor>("desc"); LLSaveInfo* info = new LLSaveInfo(mItemUUID, mObjectUUID, descEditor->getText(), tid); gAssetStorage->storeAssetData(tid, LLAssetType::AT_GESTURE, onSaveComplete, info, FALSE); } } // If this gesture is active, then we need to update the in-memory // active map with the new pointer. if (!delayedUpload && LLGestureMgr::instance().isGestureActive(mItemUUID)) { // gesture manager now owns the pointer LLGestureMgr::instance().replaceGesture(mItemUUID, gesture, asset_id); // replaceGesture may deactivate other gestures so let the // inventory know. gInventory.notifyObservers(); } else { // we're done with this gesture delete gesture; gesture = NULL; } mDirty = FALSE; // refresh will be called when callback // if triggered when delayedUpload if(!delayedUpload) { refresh(); } } delete [] buffer; buffer = NULL; }
void CQFittingResult::slotSave(void) { C_INT32 Answer = QMessageBox::No; QString fileName; while (Answer == QMessageBox::No) { fileName = CopasiFileDialog::getSaveFileName(this, "Save File Dialog", QString::null, "TEXT Files (*.txt);;All Files (*.*);;", "Save to"); if (fileName.isEmpty()) return; if (!fileName.endsWith(".txt") && !fileName.endsWith(".")) fileName += ".txt"; fileName = fileName.remove(QRegExp("\\.$")); Answer = checkSelection(fileName); if (Answer == QMessageBox::Cancel) return; } std::ofstream file(utf8ToLocale(TO_UTF8(fileName)).c_str()); if (file.fail()) return; unsigned C_INT32 i, imax; // The global result and statistics file << "Objective Value\tRoot Mean Square\tStandard Deviation" << std::endl; file << mpProblem->getSolutionValue() << "\t"; file << mpProblem->getRMS() << "\t"; file << mpProblem->getStdDeviation() << std::endl; file << "Function Evaluations\tCPU Time [s]\tEvaluations/second [1/s]" << std::endl; const unsigned C_INT32 & FunctionEvaluations = mpProblem->getFunctionEvaluations(); const C_FLOAT64 & ExecutionTime = mpProblem->getExecutionTime(); file << FunctionEvaluations << "\t"; file << ExecutionTime << "\t"; file << FunctionEvaluations / ExecutionTime << std::endl; // Set up the parameters table file << std::endl << "Parameters:" << std::endl; file << "Parameter\tValue\tStd. Deviation\tCoeff. of Variation [%]\tGradient" << std::endl; // Loop over the optimization items const std::vector< COptItem * > & Items = mpProblem->getOptItemList(); const CVector< C_FLOAT64 > & Solutions = mpProblem->getSolutionVariables(); const CVector< C_FLOAT64 > & StdDeviations = mpProblem->getVariableStdDeviations(); const CVector< C_FLOAT64 > & Gradients = mpProblem->getVariableGradients(); imax = Items.size(); if (mpProblem->getFunctionEvaluations() == 0) imax = 0; assert(CCopasiRootContainer::getDatamodelList()->size() > 0); CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0]; assert(pDataModel != NULL); for (i = 0; i != imax; i++) { const CCopasiObject *pObject = pDataModel->getObject(Items[i]->getObjectCN()); if (pObject) { std::string Experiments = static_cast<CFitItem *>(Items[i])->getExperiments(); if (Experiments != "") Experiments = "; {" + Experiments + "}"; file << pObject->getObjectDisplayName() << Experiments << "\t"; } else file << "Not Found\t"; const C_FLOAT64 & Solution = Solutions[i]; file << Solution << "\t"; const C_FLOAT64 & StdDeviation = StdDeviations[i]; file << StdDeviation << "\t"; file << fabs(100.0 * StdDeviation / Solution) << "\t"; file << Gradients[i] << std::endl; } // Set up the experiments table file << std::endl << "Experiments:" << std::endl; file << "Experiment\tObjective Value\tRoot Mean Square\tError Mean\tError Mean Std. Deviation" << std::endl; // Loop over the experiments const CExperimentSet & Experiments = mpProblem->getExperiementSet(); imax = Experiments.getExperimentCount(); if (mpProblem->getFunctionEvaluations() == 0) imax = 0; for (i = 0; i != imax; i++) { const CExperiment & Experiment = * Experiments.getExperiment(i); file << Experiment.getObjectName() << "\t"; file << Experiment.getObjectiveValue() << "\t"; file << Experiment.getRMS() << "\t"; file << Experiment.getErrorMean() << "\t"; file << Experiment.getErrorMeanSD() << std::endl; } // Set up the fitted values table file << std::endl << "Fitted Values:" << std::endl; file << "Fitted Value\tObjective Value\tRoot Mean Square\tError Mean\tError Mean Std. Deviation" << std::endl; // Loop over the fitted values objects imax = Experiments.getDependentObjects().size(); if (mpProblem->getFunctionEvaluations() == 0) imax = 0; for (i = 0; i != imax; i++) { const CCopasiObject * pObject = Experiments.getDependentObjects()[i]; if (pObject) file << pObject->getObjectDisplayName() << "\t"; else file << "Not Found\t"; file << Experiments.getDependentObjectiveValues()[i] << "\t"; file << Experiments.getDependentRMS()[i] << "\t"; file << Experiments.getDependentErrorMean()[i] << "\t"; file << Experiments.getDependentErrorMeanSD()[i] << std::endl; } file << std::endl; // Save the parameter correlations file << mpProblem->getCorrelations() << std::endl; // Save the Fisher information file << mpProblem->getFisherInformation() << std::endl; }
void ScanQSS() { std::string file_name = oz::path + "save/" + oz::name + ".qss"; std::string buffer; std::ifstream file( file_name.c_str()); uint32_t line_count = 0; uint32_t screen_count = 0; uint32_t group_count = 0; uint32_t mode = 0; rectangle group; std::string current_group; uint32_t temp_convert; do { std::getline (file, buffer); switch(mode) { case QSS_INTRO: mode = QSS_SCREENCOUNT; break; case QSS_SCREENCOUNT: screen_count = atoi(buffer.c_str()); mode = QSS_SCREEN; break; case QSS_SCREEN: if ( line_count == 0) { line_count++; } else if ( line_count == 1) { line_count++; } else { screen_count--; line_count = 0; if (!screen_count) mode = QSS_GROUPCOUNT; } break; case QSS_GROUPCOUNT: group_count = atoi(buffer.c_str()); mode = QSS_GROUP; break; case QSS_GROUP: if ( line_count == 0) { current_group = buffer; line_count++; } else if ( line_count == 1) { group.x = atoi(buffer.c_str()) / 128; line_count++; } else if ( line_count == 2) { group.y = atoi(buffer.c_str()) / 96; line_count++; } else if ( line_count == 3) { group.w = atoi(buffer.c_str()) / 128; if (group.w < group.x) { temp_convert = group.x; group.x = group.w; group.w = temp_convert - group.x; } else { group.w = (atoi(buffer.c_str())/128) - group.x; } line_count++; } else if ( line_count == 4) { group.h = atoi(buffer.c_str())/96; if (group.h < group.y) { temp_convert = group.y; group.y = group.h; group.h = temp_convert - group.y; } else { group.h = (atoi(buffer.c_str())/96) - group.y; } line_count++; } else if ( line_count == 5) { line_count++; } else { oz::maps.push_back(group); group_count--; line_count = 0; if (!group_count) mode = QSS_SETTING; } break; case QSS_SETTING: if (line_count == 0) oz::startx = atoi(buffer.c_str()); else if (line_count == 1) oz::starty = atoi(buffer.c_str()); else if (line_count == 2) oz::title = buffer; else if (line_count == 3) { } else if (line_count == 4) oz::useaudio = atoi(buffer.c_str()); line_count++; break; } } while (! file.eof()); std::cout << "oz::scanGroups: " << oz::maps.size() << std::endl; }
//----------------------------------------------------------------------------- // browses the server nodes, and their database nodes // saves everything to fr_databases.conf file // returns: false if file cannot be opened for writing, true otherwise // bool Root::save() { // create directory if it doesn't exist yet. QString fileFullPath = QFileInfo(getFileName()).absoluteFilePath(); { QDir _file = fileFullPath; if (!_file.exists()) _file.mkdir(_file.path()); } QFile file(fileFullPath); if (!file.open(QFile::WriteOnly | QFile::Text)) { return false; } QXmlStreamWriter xmlWriter(&file); xmlWriter.setAutoFormatting(true); xmlWriter.writeStartDocument(); // #if !wxUSE_UNICODE // doc.SetFileEncoding(getHtmlCharset()); // #endif xmlWriter.writeStartElement(QString::fromLatin1("root")); { // QDomNode rn = new QDomNode(wxXML_ELEMENT_NODE, QString::fromLatin1("root")); // doc.SetRoot(rn); // rsAddChildNode(rn, QString::fromLatin1("nextId"), // QString::Format(QString::fromLatin1("%d"), Database::getUIDGeneratorValue())); rsAddChildNode(xmlWriter, QString::fromLatin1("nextId"), QString::fromLatin1("%1").arg(Database::getUIDGeneratorValue())); for (ServerPtrs::iterator its = serversM.begin(); its != serversM.end(); ++its) { // do not save the dummy server node for databases that were opened // either via command line switch or via drag and drop if ((*its) == unregLocalDatabasesM) continue; // QDomNode xmlWriter = new QDomNode(wxXML_ELEMENT_NODE, QString::fromLatin1("server")); // rn.AddChild(xmlWriter); xmlWriter.writeStartElement(QString::fromLatin1("server")); { rsAddChildNode(xmlWriter, QString::fromLatin1("name"), (*its)->getName_()); rsAddChildNode(xmlWriter, QString::fromLatin1("host"), (*its)->getHostname()); rsAddChildNode(xmlWriter, QString::fromLatin1("port"), (*its)->getPort()); DatabasePtrs databases((*its)->getDatabases()); for (DatabasePtrs::iterator itdb = databases.begin(); itdb != databases.end(); ++itdb) { (*itdb)->resetCredentials(); // clean up eventual extra credentials // QDomNode xmlWriter = new QDomNode(wxXML_ELEMENT_NODE, QString::fromLatin1("database")); // xmlWriter.AddChild(xmlWriter); xmlWriter.writeStartElement(QString::fromLatin1("database")); { rsAddChildNode(xmlWriter, QString::fromLatin1("id"), (*itdb)->getId()); rsAddChildNode(xmlWriter, QString::fromLatin1("name"), (*itdb)->getName_()); rsAddChildNode(xmlWriter, QString::fromLatin1("path"), (*itdb)->getPath()); rsAddChildNode(xmlWriter, QString::fromLatin1("charset"), (*itdb)->getConnectionCharset()); rsAddChildNode(xmlWriter, QString::fromLatin1("username"), (*itdb)->getUsername()); rsAddChildNode(xmlWriter, QString::fromLatin1("password"), (*itdb)->getRawPassword()); rsAddChildNode(xmlWriter, QString::fromLatin1("role"), (*itdb)->getRole()); rsAddChildNode(xmlWriter, QString::fromLatin1("authentication"), (*itdb)->getAuthenticationMode().getConfigValue()); } xmlWriter.writeEndElement(); } } xmlWriter.writeEndElement(); } } xmlWriter.writeEndElement(); xmlWriter.writeEndDocument(); file.close(); if (file.error()) { return false; } // return doc.Save(getFileName()); return true; }
// --------------------------------------------------------------------- // Loads the symbol for the subcircuit from the schematic file and // returns the number of painting elements. int Subcircuit::loadSymbol(const QString& DocName) { QFile file(DocName); if(!file.open(QIODevice::ReadOnly)) return -1; QString Line; // ***************************************************************** // To strongly speed up the file read operation the whole file is // read into the memory in one piece. QTextStream ReadWhole(&file); QString FileString = ReadWhole.read(); file.close(); QTextStream stream(&FileString, QIODevice::ReadOnly); // read header ************************** do { if(stream.atEnd()) return -2; Line = stream.readLine(); Line = Line.trimmed(); } while(Line.isEmpty()); if(Line.left(16) != "<Qucs Schematic ") // wrong file type ? return -3; Line = Line.mid(16, Line.length()-17); if(!checkVersion(Line)) // wrong version number ? return -4; // read content ************************* while(!stream.atEnd()) { Line = stream.readLine(); if(Line == "<Symbol>") break; } x1 = y1 = INT_MAX; x2 = y2 = INT_MIN; int z=0, Result; while(!stream.atEnd()) { Line = stream.readLine(); if(Line == "</Symbol>") { x1 -= 4; // enlarge component boundings a little x2 += 4; y1 -= 4; y2 += 4; return z; // return number of ports } Line = Line.trimmed(); if(Line.at(0) != '<') return -5; if(Line.at(Line.length()-1) != '>') return -6; Line = Line.mid(1, Line.length()-2); // cut off start and end character Result = analyseLine(Line, 1); if(Result < 0) return -7; // line format error z += Result; } return -8; // field not closed }
QVector<QList<QString> > iTunes::getAlbums() { QDomDocument doc("Lib"); QFile file(filePath); if(!file.open(QIODevice::ReadOnly)) throw QString("Erreur lors de l'ouverture du fichier."); if(!doc.setContent(&file)) throw QString("Erreur lors de l'initialisation du XML."); file.close(); // Root element QDomElement docElem = doc.documentElement(); // <plist> -> <dict> QDomNode n = docElem.firstChild().firstChildElement("dict"); // Get the children nodes of the first dict QDomNodeList list = n.childNodes(); int count = list.count(); // Init the albums storage QVector<QList<QString> > albums(0); int albumIterator(0); // For each child for(int nodeIterator = 0; nodeIterator <= count; nodeIterator++) { QDomElement node = list.at(nodeIterator).toElement(); // If it is a <dict> if(node.tagName().startsWith("dict")) { node = node.firstChildElement(); // We go through its children while(!node.isNull()) { // Get the key tag if(node.tagName() == "key") { // For each tag we want to store for(int keyIterator = 0; keyIterator < keys.count(); keyIterator++) { // We check if the current tag is one of them if(node.text() == keys.at(keyIterator) && node.tagName() == "key") { // The value is stored in the next element node = node.nextSiblingElement(); if(!node.isNull()) { albums.resize(albumIterator+1); QString value = node.text(); if(albums[albumIterator].indexOf(value) == -1) albums[albumIterator].insert(keys.indexOf(keys.at(keyIterator)), value); } } } } node = node.nextSiblingElement(); } albumIterator = albumIterator+1; } QCoreApplication::processEvents(); } if(albums.isEmpty()) throw QString("Aucun album retourné."); return albums; }
void BikerHttpRequestProcessor::processRequest() { std::cerr << "processing request..." << std::endl; QRegExp numberRegExp("(\\d+(?:.\\d+)?)"); //Es wird nur GET unterstützt, der Rest nicht. Bei was anderem: Grantig sein und 405 antworten. if (_requestType != "GET") { this->send405(); return; } if (_requestPath.contains("..")) { //".." im Pfad ist ein falscher Request. Damit könnte man ins Dateisystem gelangen. std::cerr << "\"..\" in request: not allowed." << std::endl; this->send400(); } std::cerr << "request file: " << _requestPath << std::endl; if (_requestPath.startsWith("/files/")) { if (! ProgramOptions::getInstance()->webserver_no_serve_files) { //"/files/" entfernen! QString _myRequestPath = _requestPath.remove(0, 7); QDir mainDir((ProgramOptions::getInstance()->webserver_public_html_folder).c_str()); if ((ProgramOptions::getInstance()->webserver_public_html_folder == "") || !mainDir.exists()) { this->send404(); return; } QFile file(QString(ProgramOptions::getInstance()->webserver_public_html_folder.c_str()) + "/" + _myRequestPath); QDir dir(QString(ProgramOptions::getInstance()->webserver_public_html_folder.c_str()) + "/" + _myRequestPath); //Wenn die Datei existiert, und alle sie lesen dürfen (nicht nur // Benutzer oder Gruppe): Datei senden. Sonst: 404 Not found. if ((!dir.exists()) && file.exists() && (file.permissions() & QFile::ReadOther)) { std::cerr << "serving file: \"" << file.fileName() << "\"" << std::endl; this->sendFile(file); } else { if (dir.exists()) std::cerr << "file is a directory: \"" << file.fileName() << "\". Not serving." << std::endl; else if (!file.exists()) std::cerr << "file not found: \"" << file.fileName() << "\". Not serving." << std::endl; else if (file.permissions() & QFile::ReadOther) std::cerr << "file does not have read permissions for everybody: \"" << file.fileName() << "\". Not serving." << std::endl; //In jedem Fall: 404 senden. this->send404(); } return; } else { //Dateien ausliefern durch Einstellungen verboten: Nicht ausliefern. std::cerr << "webserver configured not to serve files." << std::endl; this->send404(); return; } } else { /** * @todo RegExp nur einmal erzeugen und dann wiederverwenden! */ QRegExp cloudmadeApiKeyRegExp("^/([\\da-fA-F]{1,64})/(?:api|API)/0.(\\d)"); //QRegExp cloudmadeApiPointListRegExp("^/(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16})),(?:\\[(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16}))(?:,(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16}))){0,20}\\],)?(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16}))"); QRegExp cloudmadeApiPointListRegExp("^/(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16})),(?:\\[(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16}))(?:,(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16})){0,200}\\],)?(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16}))"); QRegExp cloudmadeApiPointListExtractor("(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16}))"); QRegExp cloudmadeApiRouteTypeRegExp("^/([a-zA-Z0-9]{1,64})(?:/([a-zA-Z0-9]{1,64}))?.(gpx|GPX|js|JS)$"); QString apiKey=""; int apiVersion=0; QVector<GPSPosition> routePointList; QString routeType=""; QString routeModifier=""; QString routeDataType=""; int position=0; if ((position=cloudmadeApiKeyRegExp.indexIn(_requestPath)) != -1) { apiKey = cloudmadeApiKeyRegExp.cap(1).toLower(); apiVersion = cloudmadeApiKeyRegExp.cap(2).toInt(); //API-Key gefunden. Falls uns der interessiert, hier was damit machen! if (ProgramOptions::getInstance()->webserver_apikey != "") { if (ProgramOptions::getInstance()->webserver_apikey != apiKey.toStdString()) { std::cerr << "api key \"" << apiKey << "\" is not valid." << std::endl; this->send403(); return; } } if (apiVersion != 3) { std::cerr << "requested api version 0." << apiVersion << ", which is not supported." << std::endl; this->send405(); return; } position += cloudmadeApiKeyRegExp.cap(0).length(); } else { this->send400(); return; } position+=cloudmadeApiPointListRegExp.indexIn(_requestPath.mid(position)); if (cloudmadeApiPointListRegExp.cap(0).length() != 0) { //Punktliste gefunden. Auswerten! //Neue RegExp zum Punkte herausholen... cloudmadeApiPointListExtractor.indexIn(cloudmadeApiPointListRegExp.cap(0)); QString strLat, strLon; routePointList.clear(); for (int pos=0; pos>=0; pos=cloudmadeApiPointListExtractor.indexIn(cloudmadeApiPointListRegExp.cap(0), cloudmadeApiPointListExtractor.cap(0).length()+pos)) { strLat = cloudmadeApiPointListExtractor.cap(1); strLon = cloudmadeApiPointListExtractor.cap(2); GPSPosition point(strLat.toDouble(), strLon.toDouble()); routePointList << point; } position += cloudmadeApiPointListRegExp.cap(0).length(); } else { this->send400(); return; } position+=cloudmadeApiRouteTypeRegExp.indexIn(_requestPath.mid(position)); if (cloudmadeApiRouteTypeRegExp.cap(0).length() != 0) { routeType = cloudmadeApiRouteTypeRegExp.cap(1).toLower(); routeModifier = cloudmadeApiRouteTypeRegExp.cap(2).toLower(); routeDataType = cloudmadeApiRouteTypeRegExp.cap(3).toLower(); //Routentyp gefunden. Auswerten! } else { this->send400(); return; } //this->send102(); boost::shared_ptr<RoutingMetric> metric; boost::shared_ptr<Router> router; boost::shared_ptr<DatabaseConnection> dbA; boost::shared_ptr<DatabaseConnection> dbB; boost::shared_ptr<AltitudeProvider> altitudeProvider; #ifdef ZZIP_FOUND altitudeProvider.reset(new SRTMProvider()); #else altitudeProvider.reset(new ZeroAltitudeProvider()); #endif if ((routeType == "bicycle") || (routeType == "bike")) { //altitudeProvider.reset(new ZeroAltitudeProvider()); //Routingmetrik festlegen anhand der Benutzerwahl if ((routeModifier == "euclidean")) { metric.reset(new EuclideanRoutingMetric(altitudeProvider)); } else if ((routeModifier == "simpleheight") || (routeModifier == "shortest")) { float detourPerHeightMeter = 100.0f; if (numberRegExp.indexIn(_parameterMap["detourperheightmeter"]) != -1) { detourPerHeightMeter = numberRegExp.cap(1).toFloat(); } metric.reset(new SimpleHeightRoutingMetric(altitudeProvider, detourPerHeightMeter)); } else if (routeModifier == "advancedheight") { float punishment = 1.0f; float detourPerHeightMeter = 200.0f; if (numberRegExp.indexIn(_parameterMap["punishment"]) != -1) { punishment = numberRegExp.cap(1).toFloat(); } if (numberRegExp.indexIn(_parameterMap["detourperheightmeter"]) != -1) { detourPerHeightMeter = numberRegExp.cap(1).toFloat(); } metric.reset(new AdvancedHeightRoutingMetric(altitudeProvider, detourPerHeightMeter, punishment)); } else if (routeModifier == "simplepower") { double weight = 90.0; double efficiency = 3 * weight; if (numberRegExp.indexIn(_parameterMap["weight"]) != -1) weight = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["efficiency"]) != -1) efficiency = numberRegExp.cap(1).toDouble(); metric.reset(new SimplePowerRoutingMetric(altitudeProvider, weight, efficiency)); } else if ((routeModifier == "power") || (routeModifier == "") || (routeModifier == "fastest")) { double weight = 90.0; //double maxPower = 140.0; double maxPower = 150.0; double minSpeed = 2.5; double pushBikeSpeed = 0.5; double haltungskorrekturfaktor = 0.4; double maxSpeed = -1.0; double noCyclewayPunishmentFactor = 5; if (numberRegExp.indexIn(_parameterMap["weight"]) != -1) weight = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["maxpower"]) != -1) maxPower = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["minspeed"]) != -1) minSpeed = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["maxspeed"]) != -1) maxSpeed = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["pushbikespeed"]) != -1) pushBikeSpeed = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["nocyclewaypunishmentfactor"]) != -1) noCyclewayPunishmentFactor = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["haltungskorrekturfaktor"]) != -1) haltungskorrekturfaktor = numberRegExp.cap(1).toDouble(); metric.reset(new PowerRoutingMetric(altitudeProvider, weight, maxPower, minSpeed, pushBikeSpeed, haltungskorrekturfaktor, noCyclewayPunishmentFactor ,maxSpeed)); } else if ((routeModifier == "biketourpower") || (routeModifier == "biketour")) { double weight = 90.0; //double maxPower = 140.0; double maxPower = 100.0; double minSpeed = 2.5; double pushBikeSpeed = 0.5; double haltungskorrekturfaktor = 0.4; double maxSpeed = -1.0; double noCyclewayPunishmentFactor = 7; if (numberRegExp.indexIn(_parameterMap["weight"]) != -1) weight = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["maxpower"]) != -1) maxPower = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["minspeed"]) != -1) minSpeed = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["maxspeed"]) != -1) maxSpeed = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["pushbikespeed"]) != -1) pushBikeSpeed = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["nocyclewaypunishmentfactor"]) != -1) noCyclewayPunishmentFactor = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["haltungskorrekturfaktor"]) != -1) haltungskorrekturfaktor = numberRegExp.cap(1).toDouble(); metric.reset(new BikeTourPowerRoutingMetric(altitudeProvider, weight, maxPower, minSpeed, pushBikeSpeed, haltungskorrekturfaktor, noCyclewayPunishmentFactor ,maxSpeed)); } else { std::cerr << "routeModifier \"" << routeModifier << "\" not supported." << std::endl; this->send405(); return; } } else if (routeType == "car") { //TODO this->send405(); return; } else if (routeType == "foot") { if ((routeModifier == "euclidean") || (routeModifier == "") || (routeModifier == "shortest") || (routeModifier == "fastest")) { metric.reset(new EuclideanRoutingMetric(altitudeProvider)); } } else { std::cerr << "requested routeType=" << routeType << ", which is not supported." << std::endl; this->send405(); return; } #ifdef SPATIALITE_FOUND if (ProgramOptions::getInstance()->dbBackend == "spatialite") { dbA.reset(new SpatialiteDatabaseConnection()); dbB.reset(new SpatialiteDatabaseConnection()); } else #endif if (ProgramOptions::getInstance()->dbBackend == "sqlite") { dbA.reset(new SQLiteDatabaseConnection()); dbB.reset(new SQLiteDatabaseConnection()); } //Datenbank ist die globale DB... dbA->open(ProgramOptions::getInstance()->dbFilename.c_str()); dbB->open(ProgramOptions::getInstance()->dbFilename.c_str()); //TODO: Testen, ob das mit dem Cache überhaupt was bringt... dbA = boost::shared_ptr<DatabaseConnection>(new DatabaseRAMCache(dbA, ProgramOptions::getInstance()->dbCacheSize)); dbB = boost::shared_ptr<DatabaseConnection>(new DatabaseRAMCache(dbB, ProgramOptions::getInstance()->dbCacheSize)); //Routingalgorithmus heraussuchen, je nach Angabe. Standard: Mehrthread-A* oder Mehrthread-Dijkstra - je nach Metrik. if (_parameterMap["algorithm"] == "multithreadeddijkstra") router.reset(new MultithreadedDijkstraRouter(dbA, dbB, metric)); else if (_parameterMap["algorithm"] == "dijkstra") router.reset(new DijkstraRouter(dbA, metric)); else if (_parameterMap["algorithm"] == "astar") router.reset(new AStarRouter(dbA, metric)); else if (_parameterMap["algorithm"] == "multithreadedastar") router.reset(new MultithreadedAStarRouter(dbA, dbB, metric)); else { if (metric->getMeasurementUnit() == DISTANCE) router.reset(new MultithreadedAStarRouter(dbA, dbB, metric)); else router.reset(new MultithreadedDijkstraRouter(dbA, dbB, metric)); } //Route berechnen GPSRoute route = router->calculateShortestRoute(routePointList); //Keine Route gefunden? 404 senden. if (route.isEmpty()) { std::cerr << "no route found." << std::endl; this->send404(); return; } else { std::cerr << "found route." << std::endl << " length: " << route.calcLength()/1000.0 << "km" << std::endl << " duration: " << route.getDuration()/60.0 << "min" << std::endl << " has " << route.getSize() << " points." << std::endl; } //Antwort entsprechend des Routentypen senden. if (routeDataType == "gpx") this->sendFile(route.exportGPXString(altitudeProvider)); else if (routeDataType == "js") this->sendFile(route.exportJSONString()); else std::cerr << "route datatype \"" << routeDataType << "\" not supported." << std::endl; return; } }
//-------------------------------------------------------------- void ofApp::setup(){ ofSetLogLevel(OF_LOG_NOTICE); ofSetWindowTitle("Easync Media - QR Slate"); ofLogNotice("Easync Media - QR Slate")<<"Starting application"; #ifdef APP_NO_WINDOW ofLogNotice("Easync Media - QR Slate")<<"No window mode"; #endif #ifdef TRY_HARDER ofLogNotice("Easync Media - QR Slate")<<"Try harder is ON"; #endif #ifdef USE_VLC ofLogNotice("Easync Media - QR Slate")<<"Using VLC library"; #endif font.loadFont("font.ttf",12); outputDir = ""; if(args->contains("-o")){ outputDir = args->getString("-o"); } vector< string > files; for(int i=1;i<args->getCount();i++){ string arg=args->getString(i); if(arg != "-o" && arg != outputDir) files.push_back(arg); } if(files.size()){ for(int i=1;i<files.size();i++){ string path=files[i]; ofFile file(path); if(file.exists()){ if(file.getExtension()=="json"){ ofLogNotice("Easync Media - QR Slate")<<"Parsing file: "<<path; parseJson(file.getAbsolutePath()); } else{ ofLogWarning("Easync Media - QR Slate")<<"File is not json: "<<path; } } else{ ofLogWarning("Easync Media - QR Slate")<<"File does not exist: "<<path; } } } else{ ofLogWarning("Easync Media - QR Slate")<<"No command line arguments received"; } if(!videos.size()){ ofLogWarning("Easync Media - QR Slate")<<"No videos added. Adding default video test.mp4 from data folder"; EasyncVideo test("test.mp4",outputDir); videos.push_back(test); } current=0; videos[current].start(); #ifdef TRY_HARDER for(int i=0; i<PROCESS_IMAGES; i++) process[i].allocate(videos[current].getWidth(), videos[current].getHeight()); #endif fps=nfps=ofGetFrameRate(); if(!videos.size()) std::exit(0); }
OldSoundThemeProvider::OldSoundThemeProvider(const QString &name, const QString &path, QString variant) { m_themeName = name; const Notification::Type xmlEventTypes[] = { Notification::UserOnline, Notification::UserOffline, Notification::UserChangedStatus, Notification::UserHasBirthday, Notification::AppStartup, Notification::IncomingMessage, Notification::ChatIncomingMessage, Notification::OutgoingMessage, Notification::ChatOutgoingMessage, Notification::System, Notification::UserTyping, Notification::BlockedMessage, }; const char* const xmlEventNames[] = { "c_online", "c_offline", "c_changed_status", "c_birth", "start", "m_get", "m_chat_get", "m_send", "m_chat_send", "sys_event", "c_typing", "c_blocked_message", "sys_custom" }; QDir dir(path); if (variant.isEmpty()) variant = dir.entryList(QStringList("*.xml"), QDir::Files).value(0); else variant += ".xml"; QFile file(dir.filePath(variant)); if (file.open(QIODevice::ReadOnly)) { QDomDocument doc; doc.setContent(&file); if (doc.doctype().name() != QLatin1String("qutimsounds")) return; QDomElement rootElement = doc.documentElement(); QDomNodeList soundsNodeList = rootElement.elementsByTagName("sounds"); if (soundsNodeList.count() != 1) return; QDomElement soundsElement = soundsNodeList.at(0).toElement(); soundsNodeList = soundsElement.elementsByTagName("sound"); QDomElement soundElement; QString eventName, soundFileName; for (int i = 0; i < soundsNodeList.count(); i++) { soundElement = soundsNodeList.at(i).toElement(); eventName = soundElement.attribute("event"); if (eventName.isEmpty() || !soundElement.elementsByTagName("file").count()) continue; soundFileName = dir.filePath(soundElement.elementsByTagName("file").at(0).toElement().text()); if (!QFile::exists(soundFileName)) continue; for (int i = 0, size = sizeof(xmlEventNames) / sizeof(const char*); i < size; i++) { if (eventName == QLatin1String(xmlEventNames[i])) { m_map.insert(xmlEventTypes[i], soundFileName); break; } } } m_filePath = file.fileName(); } }
void PecoApp::CreateScript(BMessage *msg) { entry_ref directory; const char *name; msg->FindRef("directory", &directory); msg->FindString("name", &name); BPath path(&directory); path.Append(name); BFile file(path.Path(), B_READ_WRITE | B_CREATE_FILE | B_ERASE_FILE); // Initiate fWindow->Lock(); fStatusBar->SetMaxValue(fList->CountItems()); BTextControl* pfadView = (BTextControl *)fWindow->FindView("pfadView"); BString Pfad(pfadView->Text()); fWindow->Unlock(); FileListItem *ListItem; BString AlterName, NeuerName; BString output = "#!/bin/sh\n" "\n" "# This script was created with PecoRename by Werner Freytag.\n" "# Visit http://www.pecora.de/pecorename for details!\n\n" "alert \"This script will rename files.\n\n" "Do you really want to continue?\" \"Yes\" \"No\"\n\n" "if [ $? -ne 0 ]\n" "then\n" " exit 0\n" "fi\n\n"; for (int32 i = 0; (ListItem = (FileListItem *)fListView->ItemAt(i)) != NULL; i++ ) { fWindow->Lock(); fStatusBar->Update(1); fWindow->Unlock(); if (ListItem->fNewName.String() != "" ) { AlterName = Pfad; AlterName.Append("/").Append(ListItem->fName); AlterName.Replace("\"", "\\\"", AlterName.Length()); NeuerName = Pfad; NeuerName.Append("/").Append(ListItem->fNewName); NeuerName.Replace("\"", "\\\"", NeuerName.Length()); output << "mv \"" << AlterName.String() << "\" \"" << NeuerName.String() << "\"\n"; } } file.Write(output.String(), output.Length()); mode_t perms; file.GetPermissions(&perms); file.SetPermissions(perms | S_IXUSR | S_IXGRP | S_IXOTH ); BNode node(file); BNodeInfo node_info(&node); node_info.SetType("text/plain"); fWindow->Lock(); fStatusBar->Reset(STATUS_STATUS); fWindow->Unlock(); }
void upscale(const Opm::parameter::ParameterGroup& param) { // Control structure. std::vector<double> saturations; Opm::SparseTable<double> all_pdrops; bool from_file = param.has("sat_pdrop_filename"); if (from_file) { std::string filename = param.get<std::string>("sat_pdrop_filename"); std::ifstream file(filename.c_str()); if (!file) { OPM_THROW(std::runtime_error, "Could not open file " << filename); } readControl(file, saturations, all_pdrops); } else { // Get a linear range of saturations. int num_sats = param.getDefault("num_sats", 4); double min_sat = param.getDefault("min_sat", 0.2); double max_sat = param.getDefault("max_sat", 0.8); saturations.resize(num_sats); for (int i = 0; i < num_sats; ++i) { double factor = num_sats == 1 ? 0 : double(i)/double(num_sats - 1); saturations[i] = (1.0 - factor)*min_sat + factor*max_sat; } // Get a logarithmic range of pressure drops. int num_pdrops = param.getDefault("num_pdrops", 5); double log_min_pdrop = std::log(param.getDefault("min_pdrop", 1e2)); double log_max_pdrop = std::log(param.getDefault("max_pdrop", 1e6)); std::vector<double> pdrops; pdrops.resize(num_pdrops); for (int i = 0; i < num_pdrops; ++i) { double factor = num_pdrops == 1 ? 0 : double(i)/double(num_pdrops - 1); pdrops[i] = std::exp((1.0 - factor)*log_min_pdrop + factor*log_max_pdrop); } // Assign the same pressure drops to all saturations. for (int i = 0; i < num_sats; ++i) { all_pdrops.appendRow(pdrops.begin(), pdrops.end()); } } int flow_direction = param.getDefault("flow_direction", 0); // Print the saturations and pressure drops. // writeControl(std::cout, saturations, all_pdrops); // Initialize upscaler. typedef SteadyStateUpscaler<Traits> Upscaler; typedef typename Upscaler::permtensor_t permtensor_t; Upscaler upscaler; upscaler.init(param); // First, compute an upscaled permeability. permtensor_t upscaled_K = upscaler.upscaleSinglePhase(); permtensor_t upscaled_K_copy = upscaled_K; upscaled_K_copy *= (1.0/(Opm::prefix::milli*Opm::unit::darcy)); std::cout.precision(15); std::cout << "Upscaled K in millidarcy:\n" << upscaled_K_copy << std::endl; std::cout << "Upscaled porosity: " << upscaler.upscalePorosity() << std::endl; // Create output streams for upscaled relative permeabilities std::string kr_filename = param.getDefault<std::string>("kr_filename", "upscaled_relperm"); std::string krw_filename = kr_filename + "_water"; std::string kro_filename = kr_filename + "_oil"; std::ofstream krw_out(krw_filename.c_str()); std::ofstream kro_out(kro_filename.c_str()); krw_out << "# Result from steady state upscaling" << std::endl; krw_out << "# Pressuredrop Sw Krxx Kryy Krzz" << std::endl; kro_out << "# Result from steady state upscaling" << std::endl; kro_out << "# Pressuredrop Sw Krxx Kryy Krzz" << std::endl; krw_out.precision(15); krw_out.setf(std::ios::scientific | std::ios::showpoint); kro_out.precision(15); kro_out.setf(std::ios::scientific | std::ios::showpoint); //#endif // Then, compute some upscaled relative permeabilities. int num_cells = upscaler.grid().size(0); int num_sats = saturations.size(); for (int i = 0; i < num_sats; ++i) { // Starting every computation with a trio of uniform profiles. std::vector<double> init_sat(num_cells, saturations[i]); const Opm::SparseTable<double>::row_type pdrops = all_pdrops[i]; int num_pdrops = pdrops.size(); for (int j = 0; j < num_pdrops; ++j) { double pdrop = pdrops[j]; std::pair<permtensor_t, permtensor_t> lambda = upscaler.upscaleSteadyState(flow_direction, init_sat, saturations[i], pdrop, upscaled_K); double usat = upscaler.lastSaturationUpscaled(); std::cout << "\n\nTensor of upscaled relperms for initial saturation " << saturations[i] << ", real steady-state saturation " << usat << " and pressure drop " << pdrop << ":\n\n[water]\n" << lambda.first << "\n[oil]\n" << lambda.second << std::endl; // Changing initial saturations for next pressure drop to equal the steady state of the last init_sat = upscaler.lastSaturationState(); writeRelPerm(krw_out, lambda.first , usat, pdrop); writeRelPerm(kro_out, lambda.second, usat, pdrop); } } }
//load the obj file and build classes void filereader(const char * filename){ selectedFace = -1 ; numfaces = 1; vertixes.resize(0); faxes.resize(0); int nVertices=0; int nFaces=0; float x, y, z; int vi; HalfEdge *myhalfedge; char characters; ifstream file(filename, ios::in); if(!file){ std::cerr << "File could not be found." << std::endl; exit(1); } // count faces and vertices while(file >> characters){ if('f' == characters) ++nFaces; if('v' == characters) ++nVertices; else std::cout << "Invalid" << std::endl; file.ignore(50,'\n'); } file.clear(); file.seekg(0); //file position @ the beginning numfaces = nFaces; for(int i = 1 ; i <= nVertices; ++i){ file >> characters; file >> x >> y >> z; file.ignore(50,'\n'); Vec3f v(x/4, y/4, z/4); //vertex Vertex myvertex; myvertex.coord = v; vertixes.push_back(myvertex); // save vertices } file.setf(ios::skipws); // skip the white space for(int i = 0; i < nFaces ; ++i){ Face myface; std::vector<int> v; // vector of vertex indices in this face std::vector<int>::const_iterator vit; file >> characters; while(file >> vi) v.push_back(vi); int j = 0; //vertex Vertex *myver; myver = new Vertex[v.size()]; myface.ver = myver; faxes.push_back(myface); faxes[i].numedges = v.size(); myhalfedge = new HalfEdge[v.size()]; for(vit = v.begin(); vit != v.end(); ++j, ++vit){ faxes[i].ver[j] = vertixes[*vit - 1]; faxes[i].ver[j].id = *vit; } faxes[i].listEdge = &myhalfedge[0]; j = 0; for(vit = v.begin() ; j < v.size(); ++j, vit++){ myhalfedge[j].head = &faxes[i].ver[(j+1)%v.size()]; myhalfedge[j].thisface = &faxes[i]; myhalfedge[j].next = &myhalfedge[(j+1)%v.size()]; if(v.end() != (vit+1)){ Pair pair(*vit, *(vit+1)); edgemap.insert(EdgeMap::value_type(pair, &myhalfedge[j])); }else{ Pair pair(*vit, *v.begin()); edgemap.insert(EdgeMap::value_type(pair, &myhalfedge[j])); } } file.clear(); //delete [] he; } edgemapwork(); }
void KPrWebPresentation::createSlidesHTML( KProgress *progressBar ) { QTextCodec *codec = KGlobal::charsets()->codecForName( m_encoding ); const QString brtag ( "<br" + QString(isXML()?" /":"") + ">" ); for ( unsigned int i = 0; i < slideInfos.count(); i++ ) { unsigned int pgNum = i + 1; // pgquiles # elpauer . org - I think this is a bug, seems to be an overflow if we have max_unsigned_int slides KTempFile tmp; QString dest= QString( "%1/html/slide_%2.html" ).arg( path ).arg( pgNum ); QString next= QString( "slide_%2.html" ).arg( pgNum<slideInfos.count() ? pgNum+1 : (m_bLoopSlides ? 1 : pgNum ) ); // Ugly, but it works QFile file( tmp.name() ); file.open( IO_WriteOnly ); QTextStream streamOut( &file ); streamOut.setCodec( codec ); writeStartOfHeader( streamOut, codec, slideInfos[ i ].slideTitle, next ); // ### TODO: transform documentinfo.xml into many <META> elements (at least the author!) if ( i > 0 ) { streamOut << "<link rel=\"first\" href=\"slide_1.html\"" << ( isXML() ?" /":"") << ">\n"; streamOut << "<link rel=\"prev\" href=\"slide_" << pgNum - 1 << ".html\"" << ( isXML() ?" /":"") << ">\n"; } if ( i < slideInfos.count() - 1 ) { streamOut << "<link rel=\"next\" href=\"slide_" << pgNum + 1 << ".html\"" << ( isXML() ?" /":"") << ">\n"; streamOut << "<link rel=\"last\" href=\"slide_" << slideInfos.count() << ".html\"" << ( isXML() ?" /":"") << ">\n"; } streamOut << "<link rel=\"contents\" href=\"../index.html\"" << ( isXML() ?" /":"") << ">\n"; streamOut << "</head>\n"; streamOut << "<body bgcolor=\"" << backColor.name() << "\" text=\"" << textColor.name() << "\">\n"; if (m_bWriteHeader) { streamOut << " <center>\n"; if ( i > 0 ) streamOut << " <a href=\"slide_1.html\">"; streamOut << "<img src=\"../pics/first.png\" border=\"0\" alt=\"" << i18n( "First" ) << "\" title=\"" << i18n( "First" ) << "\"" << ( isXML() ?" /":"") << ">"; if ( i > 0 ) streamOut << "</a>"; streamOut << "\n"; if ( i > 0 ) streamOut << " <a href=\"slide_" << pgNum - 1 << ".html\">"; streamOut << "<img src=\"../pics/prev.png\" border=\"0\" alt=\"" << i18n( "Previous" ) << "\" title=\"" << i18n( "Previous" ) << "\"" << ( isXML() ?" /":"") << ">"; if ( i > 0 ) streamOut << "</a>"; streamOut << "\n"; if ( (m_bLoopSlides) || (i < slideInfos.count() - 1 ) ) streamOut << " <a href=\"" << next << "\">"; streamOut << "<img src=\"../pics/next.png\" border=\"0\" alt=\"" << i18n( "Next" ) << "\" title=\"" << i18n( "Next" ) << "\"" << ( isXML() ?" /":"") << ">"; if ( (m_bLoopSlides) || (i < slideInfos.count() - 1 ) ) streamOut << "</a>"; streamOut << "\n"; if ( i < slideInfos.count() - 1 ) streamOut << " <a href=\"slide_" << slideInfos.count() << ".html\">"; streamOut << "<img src=\"../pics/last.png\" border=\"0\" alt=\"" << i18n( "Last" ) << "\" title=\"" << i18n( "Last" ) << "\"" << ( isXML() ?" /":"") << ">"; if ( i < slideInfos.count() - 1 ) streamOut << "</a>"; streamOut << "\n" << " \n"; streamOut << " <a href=\"../index.html\">"; streamOut << "<img src=\"../pics/home.png\" border=\"0\" alt=\"" << i18n( "Home" ) << "\" title=\"" << i18n( "Home" ) << "\"" << ( isXML() ?" /":"") << ">"; streamOut << "</a>\n"; streamOut << " </center>" << brtag << "<hr noshade=\"noshade\"" << ( isXML() ?" /":"") << ">\n"; // ### TODO: is noshade W3C? streamOut << " <center>\n <font color=\"" << escapeHtmlText( codec, titleColor.name() ) << "\">\n"; streamOut << " <b>" << escapeHtmlText( codec, title ) << "</b> - <i>" << escapeHtmlText( codec, slideInfos[ i ].slideTitle ) << "</i>\n"; streamOut << " </font>\n </center>\n"; streamOut << "<hr noshade=\"noshade\"" << ( isXML() ?" /":"") << ">" << brtag << "\n"; } streamOut << " <center>\n "; if ( (m_bLoopSlides) || (i < slideInfos.count() - 1) ) streamOut << "<a href=\"" << next << "\">"; streamOut << "<img src=\"../pics/slide_" << pgNum << ".png\" border=\"0\" alt=\"" << i18n( "Slide %1" ).arg( pgNum ) << "\"" << ( isXML() ?" /":"") << ">"; if ( i < slideInfos.count() - 1 ) streamOut << "</a>"; streamOut << "\n"; streamOut << " </center>\n"; if (m_bWriteFooter) { streamOut << brtag << "<hr noshade=\"noshade\"" << ( isXML() ?" /":"") << ">\n"; QPtrList<KPrPage> _tmpList( doc->getPageList() ); QString note ( escapeHtmlText( codec, _tmpList.at(i)->noteText() ) ); if ( !note.isEmpty() ) { streamOut << " <b>" << escapeHtmlText( codec, i18n( "Note" ) ) << "</b>\n"; streamOut << " <blockquote>\n"; streamOut << note.replace( "\n", brtag ); streamOut << " </blockquote><hr noshade=\"noshade\"" << ( isXML() ?" /":"") << ">\n"; } streamOut << " <center>\n"; QString htmlAuthor; if (email.isEmpty()) htmlAuthor=escapeHtmlText( codec, author ); else htmlAuthor=QString("<a href=\"mailto:%1\">%2</a>").arg( escapeHtmlText( codec, email )).arg( escapeHtmlText( codec, author )); streamOut << EscapeEncodingOnly ( codec, i18n( "Created on %1 by <i>%2</i> with <a href=\"http://www.koffice.org/kpresenter\">KPresenter</a>" ) .arg( KGlobal::locale()->formatDate ( QDate::currentDate() ) ).arg( htmlAuthor ) ); streamOut << " </center><hr noshade=\"noshade\"" << ( isXML() ?" /":"") << ">\n"; } streamOut << "</body>\n</html>\n"; file.close(); KIO::NetAccess::file_move( tmp.name(), dest, -1, true /*overwrite*/); int p = progressBar->progress(); progressBar->setProgress( ++p ); kapp->processEvents(); } }
boost::filesystem::path LinuxPath::getInstallPath() const { boost::filesystem::path installPath; boost::filesystem::path homePath = getUserHome(); if (!homePath.empty()) { boost::filesystem::path wineDefaultRegistry(homePath); wineDefaultRegistry /= ".wine/system.reg"; if (boost::filesystem::is_regular_file(wineDefaultRegistry)) { boost::filesystem::ifstream file(wineDefaultRegistry); bool isRegEntry = false; std::string line; std::string mwpath; while (std::getline(file, line)) { if (line[0] == '[') // we found an entry { if (isRegEntry) { break; } isRegEntry = (line.find("Softworks\\\\Morrowind]") != std::string::npos); } else if (isRegEntry) { if (line[0] == '"') // empty line means new registry key { std::string key = line.substr(1, line.find('"', 1) - 1); if (strcasecmp(key.c_str(), "Installed Path") == 0) { std::string::size_type valuePos = line.find('=') + 2; mwpath = line.substr(valuePos, line.rfind('"') - valuePos); std::string::size_type pos = mwpath.find("\\"); while (pos != std::string::npos) { mwpath.replace(pos, 2, "/"); pos = mwpath.find("\\", pos + 1); } break; } } } } if (!mwpath.empty()) { // Change drive letter to lowercase, so we could use // ~/.wine/dosdevices symlinks mwpath[0] = Misc::StringUtils::toLower(mwpath[0]); installPath /= homePath; installPath /= ".wine/dosdevices/"; installPath /= mwpath; if (!boost::filesystem::is_directory(installPath)) { installPath.clear(); } } } } return installPath; }
//////////////////////////////////////////////////////////// /// Check if file exists //////////////////////////////////////////////////////////// bool fexists(std::string filename) { std::ifstream file(filename.c_str()); return file.is_open(); }
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice, const QString &fname, QString currentPath, bool ignoreErrors) { Q_ASSERT(m_errorDevice); const QChar slash = QLatin1Char('/'); if (!currentPath.isEmpty() && !currentPath.endsWith(slash)) currentPath += slash; QDomDocument document; { QString errorMsg; int errorLine = 0; int errorColumn = 0; if (!document.setContent(inputDevice, &errorMsg, &errorLine, &errorColumn)) { if (ignoreErrors) return true; const QString msg = QString::fromUtf8("RCC Parse Error: '%1' Line: %2 Column: %3 [%4]\n").arg(fname).arg(errorLine).arg(errorColumn).arg(errorMsg); m_errorDevice->write(msg.toUtf8()); return false; } } QDomElement domRoot = document.firstChildElement(m_strings.TAG_RCC).toElement(); if (!domRoot.isNull() && domRoot.tagName() == m_strings.TAG_RCC) { for (QDomNode node = domRoot.firstChild(); !node.isNull(); node = node.nextSibling()) { if (!node.isElement()) continue; QDomElement child = node.toElement(); if (!child.isNull() && child.tagName() == m_strings.TAG_RESOURCE) { QLocale::Language language = QLocale::c().language(); QLocale::Country country = QLocale::c().country(); if (child.hasAttribute(m_strings.ATTRIBUTE_LANG)) { QString attribute = child.attribute(m_strings.ATTRIBUTE_LANG); QLocale lang = QLocale(attribute); language = lang.language(); if (2 == attribute.length()) { // Language only country = QLocale::AnyCountry; } else { country = lang.country(); } } QString prefix; if (child.hasAttribute(m_strings.ATTRIBUTE_PREFIX)) prefix = child.attribute(m_strings.ATTRIBUTE_PREFIX); if (!prefix.startsWith(slash)) prefix.prepend(slash); if (!prefix.endsWith(slash)) prefix += slash; for (QDomNode res = child.firstChild(); !res.isNull(); res = res.nextSibling()) { if (res.isElement() && res.toElement().tagName() == m_strings.TAG_FILE) { QString fileName(res.firstChild().toText().data()); if (fileName.isEmpty()) { const QString msg = QString::fromUtf8("RCC: Warning: Null node in XML of '%1'\n").arg(fname); m_errorDevice->write(msg.toUtf8()); } QString alias; if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_ALIAS)) alias = res.toElement().attribute(m_strings.ATTRIBUTE_ALIAS); else alias = fileName; int compressLevel = m_compressLevel; if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_COMPRESS)) compressLevel = res.toElement().attribute(m_strings.ATTRIBUTE_COMPRESS).toInt(); int compressThreshold = m_compressThreshold; if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_THRESHOLD)) compressThreshold = res.toElement().attribute(m_strings.ATTRIBUTE_THRESHOLD).toInt(); // Special case for -no-compress. Overrides all other settings. if (m_compressLevel == -2) compressLevel = 0; alias = QDir::cleanPath(alias); while (alias.startsWith(QLatin1String("../"))) alias.remove(0, 3); alias = QDir::cleanPath(m_resourceRoot) + prefix + alias; QString absFileName = fileName; if (QDir::isRelativePath(absFileName)) absFileName.prepend(currentPath); QFileInfo file(absFileName); if (!file.exists()) { m_failedResources.push_back(absFileName); const QString msg = QString::fromUtf8("RCC: Error in '%1': Cannot find file '%2'\n").arg(fname).arg(fileName); m_errorDevice->write(msg.toUtf8()); if (ignoreErrors) continue; else return false; } else if (file.isFile()) { const bool arc = addFile(alias, RCCFileInfo(alias.section(slash, -1), file, language, country, RCCFileInfo::NoFlags, compressLevel, compressThreshold) ); if (!arc) m_failedResources.push_back(absFileName); } else { QDir dir; if (file.isDir()) { dir.setPath(file.filePath()); } else { dir.setPath(file.path()); dir.setNameFilters(QStringList(file.fileName())); if (alias.endsWith(file.fileName())) alias = alias.left(alias.length()-file.fileName().length()); } if (!alias.endsWith(slash)) alias += slash; QDirIterator it(dir, QDirIterator::FollowSymlinks|QDirIterator::Subdirectories); while (it.hasNext()) { it.next(); QFileInfo child(it.fileInfo()); if (child.fileName() != QLatin1String(".") && child.fileName() != QLatin1String("..")) { const bool arc = addFile(alias + child.fileName(), RCCFileInfo(child.fileName(), child, language, country, RCCFileInfo::NoFlags, compressLevel, compressThreshold) ); if (!arc) m_failedResources.push_back(child.fileName()); } } } } } } } } if (m_root == 0) { const QString msg = QString::fromUtf8("RCC: Warning: No resources in '%1'.\n").arg(fname); m_errorDevice->write(msg.toUtf8()); if (!ignoreErrors && m_format == Binary) { // create dummy entry, otherwise loading qith QResource will crash m_root = new RCCFileInfo(QString(), QFileInfo(), QLocale::C, QLocale::AnyCountry, RCCFileInfo::Directory); } } return true; }
void LogViewWindow::createLog(LogFile * pLog, int iId, QString * pszFile) { if(!pLog) return; QRegExp rx; QString szLog, szLogDir, szBuffer, szLine, szTmp; QString szDate = pLog->date().toString("yyyy.MM.dd"); // The fresh new log g_pApp->getLocalKvircDirectory(szLogDir,KviApplication::Tmp); KviFileUtils::adjustFilePath(szLogDir); szLogDir += KVI_PATH_SEPARATOR_CHAR; szLog += szLogDir; szLog += QString("%1_%2.%3_%4").arg(pLog->typeString(),pLog->name(),pLog->network(),szDate); // Open file for reading QFile file(pLog->fileName()); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; // Set up a 16bit Unicode string QTextStream input(&file); input.setCodec("UTF-8"); switch(iId) { case LogFile::PlainText: { szLog += ".txt"; // Scan the file while(!input.atEnd()) { szTmp = input.readLine(); szLine = KviControlCodes::stripControlBytes(szTmp); // Remove icons' code rx.setPattern("^\\d{1,3}\\s"); szLine.replace(rx,""); // Remove link from a user speaking // e.g.: <!ncHelLViS69> --> <HelLViS69> rx.setPattern("\\s<!nc"); szLine.replace(rx," <"); // Remove link from a nick in a mask // e.g.: !nFoo [~bar@!hfoo.bar] --> Foo [~bar@!hfoo.bar] rx.setPattern("\\s!n"); szLine.replace(rx," "); // Remove link from a host in a mask // e.g.: Foo [~bar@!hfoo.bar] --> Foo [[email protected]] rx.setPattern("@!h"); szLine.replace(rx,"@"); // Remove link from a channel // e.g.: !c#KVIrc --> #KVIrc rx.setPattern("!c#"); szLine.replace(rx,"#"); szBuffer += szLine; szBuffer += "\n"; } break; } case LogFile::HTML: { szLog += ".html"; szTmp = QString("KVIrc %1 %2").arg(KVI_VERSION).arg(KVI_RELEASE_NAME); QString szNick = ""; bool bFirstLine = true; QString szTitle; switch(pLog->type()) { case LogFile::Channel: szTitle = __tr2qs_ctx("Channel %1 on %2","log").arg(pLog->name(),pLog->network()); break; case LogFile::Console: szTitle = __tr2qs_ctx("Console on %1","log").arg(pLog->network()); break; case LogFile::Query: szTitle = __tr2qs_ctx("Query with %1 on %2","log").arg(pLog->name(),pLog->network()); break; case LogFile::DccChat: szTitle = __tr2qs_ctx("DCC Chat with %1","log").arg(pLog->name()); break; case LogFile::Other: szTitle = __tr2qs_ctx("Something on %1","log").arg(pLog->network()); break; } // Prepare HTML document szBuffer += "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n"; szBuffer += "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\n"; szBuffer += "<head>\n"; szBuffer += "\t<meta http-equiv=\"content-type\" content=\"application/xhtml+xml; charset=utf-8\" />\n"; szBuffer += "\t<meta name=\"author\" content=\"" + szTmp + "\" />\n"; szBuffer += "\t<title>" + szTitle + "</title>\n"; szBuffer += "</head>\n<body>\n"; szBuffer += "<h2>" + szTitle + "</h2>\n<h3>Date: " + szDate + "</h3>\n"; // Scan the file while(!input.atEnd()) { szTmp = input.readLine(); // Find who has talked QString szTmpNick = szTmp.section(" ",2,2); if((szTmpNick.left(1) != "<") && (szTmpNick.right(1) != ">")) szTmpNick = ""; // locate msgtype QString szNum = szTmp.section(' ',0,0); bool bOk; int iMsgType = szNum.toInt(&bOk); // only human text for now... if(iMsgType != 24 && iMsgType != 25 && iMsgType != 26) continue; // remove msgtype tag szTmp = szTmp.remove(0,szNum.length()+1); szTmp = KviHtmlGenerator::convertToHtml(szTmp,true); // insert msgtype icon at start of the current text line KviMessageTypeSettings msg(KVI_OPTION_MSGTYPE(iMsgType)); QString szIcon = g_pIconManager->getSmallIconResourceName((KviIconManager::SmallIcon)msg.pixId()); szTmp.prepend("<img src=\"" + szIcon + "\" alt=\"\" /> "); /* * Check if the nick who has talked is the same of the above line. * If so, we have to put the line as it is, otherwise we have to * open a new paragraph */ if(szTmpNick != szNick) { /* * People is not the same, close the paragraph opened * before and open a new one */ if(!bFirstLine) szBuffer += "</p>\n"; szTmp.prepend("<p>"); szNick = szTmpNick; } else { // Break the line szTmp.prepend("<br />\n"); } szBuffer += szTmp; bFirstLine = false; } // Close the last paragraph szBuffer += "</p>\n"; // regexp to search all embedded icons rx.setPattern("<img src=\"smallicons:([^\"]+)"); int iIndex = szBuffer.indexOf(rx); QStringList szImagesList; // search for icons while (iIndex >= 0) { int iLength = rx.matchedLength(); QString szCap = rx.cap(1); // if the icon isn't in the images list then add if(szImagesList.indexOf(szCap) == -1) szImagesList.append(szCap); iIndex = szBuffer.indexOf(rx, iIndex + iLength); } // get current theme path QString szCurrentThemePath; g_pApp->getLocalKvircDirectory(szCurrentThemePath,KviApplication::Themes,KVI_OPTION_STRING(KviOption_stringIconThemeSubdir)); szCurrentThemePath += KVI_PATH_SEPARATOR_CHAR; // current coresmall path szCurrentThemePath += "coresmall"; szCurrentThemePath += KVI_PATH_SEPARATOR_CHAR; // check if coresmall exists in current theme if(!KviFileUtils::directoryExists(szCurrentThemePath)) { // get global coresmall path g_pApp->getGlobalKvircDirectory(szCurrentThemePath,KviApplication::Pics,"coresmall"); KviQString::ensureLastCharIs(szCurrentThemePath,QChar(KVI_PATH_SEPARATOR_CHAR)); } // copy all icons to the log destination folder for(int i=0; i < szImagesList.count(); i++) { QString szSourceFile = szCurrentThemePath + szImagesList.at(i); QString szDestFile = szLogDir + szImagesList.at(i); KviFileUtils::copyFile(szSourceFile,szDestFile); } // remove internal tags rx.setPattern("<qt>|</qt>|smallicons:"); szBuffer.replace(rx,""); szBuffer.replace(">!nc",">"); szBuffer.replace("@!nc","@"); szBuffer.replace("%!nc","%"); // Close the document szBuffer += "</body>\n</html>\n"; break; } } if(QFile::exists(szLog)) { if(QMessageBox::question(this,__tr2qs_ctx("Export Log - KVIrc","log"),__tr2qs_ctx("File '%1' already exists. Do you want to overwrite it?","log").arg(szLog),QMessageBox::Yes,QMessageBox::No) == QMessageBox::No) return; } QFile log(szLog); if(!log.open(QIODevice::WriteOnly | QIODevice::Text)) return; if(pszFile) { *pszFile = ""; QFileInfo info(log); *pszFile = info.filePath(); } // Ensure we're writing in UTF-8 QTextStream output(&log); output.setCodec("UTF-8"); output << szBuffer; // Close file descriptors file.close(); log.close(); }