void draw() { // Attempting to draw before we're visible and have a valid size will // produce GL errors. if (!isVisible() || _size.width() <= 0 || _size.height() <= 0) { return; } makeCurrent(); gpu::Batch batch; batch.clearColorFramebuffer(gpu::Framebuffer::BUFFER_COLORS, { 0.0f, 0.0f, 0.0f, 1.0f }); batch.clearDepthFramebuffer(1e4); batch.setViewportTransform({ 0, 0, _size.width() * devicePixelRatio(), _size.height() * devicePixelRatio() }); batch.setProjectionTransform(_projectionMatrix); float t = _time.elapsed() * 1e-3f; glm::vec3 unitscale { 1.0f }; glm::vec3 up { 0.0f, 1.0f, 0.0f }; float distance = 3.0f; glm::vec3 camera_position{ distance * sinf(t), 0.0f, distance * cosf(t) }; static const vec3 camera_focus(0); static const vec3 camera_up(0, 1, 0); glm::mat4 camera = glm::inverse(glm::lookAt(camera_position, camera_focus, up)); batch.setViewTransform(camera); batch.setPipeline(_pipeline); batch.setModelTransform(Transform()); auto geometryCache = DependencyManager::get<GeometryCache>(); // Render grid on xz plane (not the optimal way to do things, but w/e) // Note: GeometryCache::renderGrid will *not* work, as it is apparenly unaffected by batch rotations and renders xy only { static const std::string GRID_INSTANCE = "Grid"; static auto compactColor1 = toCompactColor(vec4{ 0.35f, 0.25f, 0.15f, 1.0f }); static auto compactColor2 = toCompactColor(vec4{ 0.15f, 0.25f, 0.35f, 1.0f }); static std::vector<glm::mat4> transforms; static gpu::BufferPointer colorBuffer; if (!transforms.empty()) { transforms.reserve(200); colorBuffer = std::make_shared<gpu::Buffer>(); for (int i = 0; i < 100; ++i) { { glm::mat4 transform = glm::translate(mat4(), vec3(0, -1, -50 + i)); transform = glm::scale(transform, vec3(100, 1, 1)); transforms.push_back(transform); colorBuffer->append(compactColor1); } { glm::mat4 transform = glm::mat4_cast(quat(vec3(0, PI / 2.0f, 0))); transform = glm::translate(transform, vec3(0, -1, -50 + i)); transform = glm::scale(transform, vec3(100, 1, 1)); transforms.push_back(transform); colorBuffer->append(compactColor2); } } } auto pipeline = geometryCache->getSimplePipeline(); for (auto& transform : transforms) { batch.setModelTransform(transform); batch.setupNamedCalls(GRID_INSTANCE, [=](gpu::Batch& batch, gpu::Batch::NamedBatchData& data) { batch.setViewTransform(camera); batch.setPipeline(_pipeline); geometryCache->renderWireShapeInstances(batch, GeometryCache::Line, data.count(), colorBuffer); }); } } { static const size_t ITEM_COUNT = 1000; static const float SHAPE_INTERVAL = (PI * 2.0f) / ITEM_COUNT; static const float ITEM_INTERVAL = SHAPE_INTERVAL / TYPE_COUNT; static const gpu::Element POSITION_ELEMENT{ gpu::VEC3, gpu::FLOAT, gpu::XYZ }; static const gpu::Element NORMAL_ELEMENT{ gpu::VEC3, gpu::FLOAT, gpu::XYZ }; static const gpu::Element COLOR_ELEMENT{ gpu::VEC4, gpu::NUINT8, gpu::RGBA }; static const gpu::Element TRANSFORM_ELEMENT{ gpu::MAT4, gpu::FLOAT, gpu::XYZW }; static std::vector<Transform> transforms; static std::vector<vec4> colors; static gpu::BufferPointer indirectBuffer; static gpu::BufferPointer transformBuffer; static gpu::BufferPointer colorBuffer; static gpu::BufferView colorView; static gpu::BufferView instanceXfmView; if (!transformBuffer) { transformBuffer = std::make_shared<gpu::Buffer>(); colorBuffer = std::make_shared<gpu::Buffer>(); indirectBuffer = std::make_shared<gpu::Buffer>(); static const float ITEM_RADIUS = 20; static const vec3 ITEM_TRANSLATION{ 0, 0, -ITEM_RADIUS }; for (size_t i = 0; i < TYPE_COUNT; ++i) { GeometryCache::Shape shape = SHAPE[i]; GeometryCache::ShapeData shapeData = geometryCache->_shapes[shape]; { gpu::Batch::DrawIndexedIndirectCommand indirectCommand; indirectCommand._count = (uint)shapeData._indexCount; indirectCommand._instanceCount = ITEM_COUNT; indirectCommand._baseInstance = (uint)(i * ITEM_COUNT); indirectCommand._firstIndex = (uint)shapeData._indexOffset / 2; indirectCommand._baseVertex = 0; indirectBuffer->append(indirectCommand); } //indirectCommand._count float startingInterval = ITEM_INTERVAL * i; for (size_t j = 0; j < ITEM_COUNT; ++j) { float theta = j * SHAPE_INTERVAL + startingInterval; auto transform = glm::rotate(mat4(), theta, Vectors::UP); transform = glm::rotate(transform, (randFloat() - 0.5f) * PI / 4.0f, Vectors::UNIT_X); transform = glm::translate(transform, ITEM_TRANSLATION); transform = glm::scale(transform, vec3(randFloat() / 2.0f + 0.5f)); transformBuffer->append(transform); transforms.push_back(transform); auto color = vec4{ randomColorValue(64), randomColorValue(64), randomColorValue(64), 255 }; color /= 255.0f; colors.push_back(color); colorBuffer->append(toCompactColor(color)); } } colorView = gpu::BufferView(colorBuffer, COLOR_ELEMENT); instanceXfmView = gpu::BufferView(transformBuffer, TRANSFORM_ELEMENT); } #if 1 GeometryCache::ShapeData shapeData = geometryCache->_shapes[GeometryCache::Icosahedron]; { batch.setViewTransform(camera); batch.setModelTransform(Transform()); batch.setPipeline(_pipeline); batch.setInputFormat(getInstancedSolidStreamFormat()); batch.setInputBuffer(gpu::Stream::COLOR, colorView); batch.setIndirectBuffer(indirectBuffer); shapeData.setupBatch(batch); batch.multiDrawIndexedIndirect(TYPE_COUNT, gpu::TRIANGLES); } #else batch.setViewTransform(camera); batch.setPipeline(_pipeline); for (size_t i = 0; i < TYPE_COUNT; ++i) { GeometryCache::Shape shape = SHAPE[i]; for (size_t j = 0; j < ITEM_COUNT; ++j) { int index = i * ITEM_COUNT + j; batch.setModelTransform(transforms[index]); const vec4& color = colors[index]; batch._glColor4f(color.r, color.g, color.b, 1.0); geometryCache->renderShape(batch, shape); } } #endif } // Render unlit cube + sphere static auto startUsecs = usecTimestampNow(); float seconds = getSeconds(startUsecs); seconds /= 4.0f; int shapeIndex = ((int)seconds) % TYPE_COUNT; bool wire = (seconds - floorf(seconds) > 0.5f); batch.setModelTransform(Transform()); batch._glColor4f(0.8f, 0.25f, 0.25f, 1.0f); if (wire) { geometryCache->renderWireShape(batch, SHAPE[shapeIndex]); } else { geometryCache->renderShape(batch, SHAPE[shapeIndex]); } batch.setModelTransform(Transform().setScale(2.05f)); batch._glColor4f(1, 1, 1, 1); geometryCache->renderWireCube(batch); _context->render(batch); _qGlContext.swapBuffers(this); fps.increment(); if (fps.elapsed() >= 0.5f) { qDebug() << "FPS: " << fps.rate(); fps.reset(); } }
int main( int argc, char** argv ) { KApplication app(argc, argv, "KSpell2Test"); Broker::Ptr broker = Broker::openBroker(); kdDebug()<< "Clients are " << broker->clients() << endl; kdDebug()<< "Languages are " << broker->languages() << endl; Dictionary *dict = broker->dictionary( "en_US" ); QStringList words; words << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted" << "hello" << "helo" << "enviroment" << "guvernment" << "farted"; QTime mtime; mtime.start(); for ( QStringList::Iterator itr = words.begin(); itr != words.end(); ++itr ) { if ( dict && !dict->check( *itr ) ) { //kdDebug()<<"Word " << *itr <<" is misspelled"<<endl; QStringList sug = dict->suggest( *itr ); //kdDebug()<<"Suggestions : "<<sug<<endl; } } //mtime.stop(); kdDebug()<<"Elapsed time is "<<mtime.elapsed()<<endl; delete dict; return 0; }
/** \fn PreviewGenerator::RunReal(void) * \brief This call creates a preview without starting a new thread. */ bool PreviewGenerator::RunReal(void) { QString msg; QTime tm = QTime::currentTime(); bool ok = false; bool is_local = IsLocal(); if (!is_local && !!(m_mode & kRemote)) { LOG(VB_GENERAL, LOG_ERR, LOC + QString("RunReal() file not local: '%1'") .arg(m_pathname)); } else if (!(m_mode & kLocal) && !(m_mode & kRemote)) { LOG(VB_GENERAL, LOG_ERR, LOC + QString("RunReal() Preview of '%1' failed " "because mode was invalid 0x%2") .arg(m_pathname).arg((int)m_mode,0,16)); } else if (!!(m_mode & kLocal) && LocalPreviewRun()) { ok = true; msg = QString("Generated on %1 in %2 seconds, starting at %3") .arg(gCoreContext->GetHostName()) .arg(tm.elapsed()*0.001) .arg(tm.toString(Qt::ISODate)); } else if (!!(m_mode & kRemote)) { if (is_local && (m_mode & kLocal)) { LOG(VB_GENERAL, LOG_WARNING, LOC + "Failed to save preview." "\n\t\t\tYou may need to check user and group ownership on" "\n\t\t\tyour frontend and backend for quicker previews.\n" "\n\t\t\tAttempting to regenerate preview on backend.\n"); } ok = RemotePreviewRun(); if (ok) { msg = QString("Generated remotely in %1 seconds, starting at %2") .arg(tm.elapsed()*0.001) .arg(tm.toString(Qt::ISODate)); } else { msg = "Remote preview failed"; } } else { msg = "Could not access recording"; } QMutexLocker locker(&m_previewLock); if (m_listener) { QString output_fn = m_outFileName.isEmpty() ? (m_programInfo.GetPathname()+".png") : m_outFileName; QDateTime dt; if (ok) { QFileInfo fi(output_fn); if (fi.exists()) dt = fi.lastModified(); } QString message = (ok) ? "PREVIEW_SUCCESS" : "PREVIEW_FAILED"; QStringList list; list.push_back(QString::number(m_programInfo.GetRecordingID())); list.push_back(output_fn); list.push_back(msg); list.push_back(dt.isValid()?dt.toUTC().toString(Qt::ISODate):""); list.push_back(m_token); QCoreApplication::postEvent(m_listener, new MythEvent(message, list)); } return ok; }
QTime time = QTime::fromString("1.30", "m.s"); // time is 00:01:30.000 //! [8] //! [9] QTime::isValid(21, 10, 30); // returns true QTime::isValid(22, 5, 62); // returns false //! [9] //! [10] QTime t; t.start(); some_lengthy_task(); qDebug("Time elapsed: %d ms", t.elapsed()); //! [10] //! [11] QDateTime now = QDateTime::currentDateTime(); QDateTime xmas(QDate(now.date().year(), 12, 25), QTime(0, 0)); qDebug("There are %d seconds to Christmas", now.secsTo(xmas)); //! [11] //! [12] QTime time1 = QTime::fromString("131", "HHh"); // time1 is 13:00:00 QTime time1 = QTime::fromString("1apA", "1amAM"); // time1 is 01:00:00
void MainWindow::processFile() { if (generalLock == false) { generalLock = true; } else { return; } QTime timer; if (!fileLoaded) { mainWindow.statusLabel->setText("No file loaded"); return; } else { QString pattern = mainWindow.patternTextEdit->toPlainText(); if (pattern == "") { mainWindow.statusLabel->setText("No pattern given"); } else { QString output = ""; QList<int> results; int elapsedTime; mainWindow.statusLabel->setText("Processing file contents..."); QCoreApplication::processEvents(); if (mainWindow.chooseAlgCombo->currentText() == "Brute Force") { BruteForce bf= BruteForce(); timer.start(); results = bf.find(pattern, pattern.size(), textFileContents, textFileContents.size(), mainWindow.progressBar); elapsedTime = timer.elapsed(); } else if (mainWindow.chooseAlgCombo->currentText() == "Morris-Pratt") { MorrisPratt mp = MorrisPratt(); timer.start(); results = mp.find(pattern, pattern.size(), textFileContents, textFileContents.size(), mainWindow.progressBar); elapsedTime = timer.elapsed(); } else if (mainWindow.chooseAlgCombo->currentText() == "Boyer-Moore") { BoyerMoore bm = BoyerMoore(); timer.start(); results = bm.find(pattern, pattern.size(), textFileContents, textFileContents.size(), mainWindow.progressBar); elapsedTime = timer.elapsed(); } else if (mainWindow.chooseAlgCombo->currentText() == "TwoWay") { TwoWay tw = TwoWay(); timer.start(); results = tw.find(pattern, pattern.size(), textFileContents, textFileContents.size(), mainWindow.progressBar); elapsedTime = timer.elapsed(); } else { mainWindow.statusLabel->setText("Algorithm not supported"); return; } mainWindow.statusLabel->setText("Preparing results..."); QCoreApplication::processEvents(); output = processOutput(results, elapsedTime); chartWidget->addResult(getNameShortcut(mainWindow.chooseAlgCombo->currentText()), "", pattern, elapsedTime, textFileContents.size() / 1024); chartWidget->repaint(); mainWindow.statusLabel->setText("Processing finished"); mainWindow.consoleBrowser->setText(output); } } generalLock = false; }
void Worker::armAdios() { QTime t; int count=0; while(rbAdios->isChecked()) { if (count>1) break; count++; try { armrocio->setPose(RoboCompArmrocio::hola1); } catch (Ice::Exception e ) { qDebug()<<"Error talking to Arm"<<e.what(); } t.start(); while(t.elapsed()<4000) { if(!armrocio->isMoving()) { break; } QApplication::processEvents(); usleep(1000); } if(count == 1) { try { QString s (QString::fromUtf8("<prosody range=\"x-high\"> Adiós.</prosody> <emphasis level=\"moderate\"> Cuídate mucho. Nos vemos el próximo día.</emphasis>" )); speech->say( s.toStdString(),true); // armrocio->setPose(RoboCompArmrocio::adios); } catch (Ice::Exception e) { qDebug()<<"Error talking to ArmRocio: "<<e.what(); } } try { armrocio->setPose(RoboCompArmrocio::hola2); } catch (Ice::Exception e ) { qDebug()<<"Error talking to Arm"<<e.what(); } t.restart(); while(t.elapsed()<4000) { if(!armrocio->isMoving()) { break; } QApplication::processEvents(); usleep(1000); } } try { armrocio->setPose(RoboCompArmrocio::reposo); } catch (Ice::Exception e ) { qDebug()<<"Error talking to Arm"<<e.what(); } }
int main (int, char **) { int w = 768, h = 768, iterations = 0; std::vector<glm::vec3> colors(w * h, glm::vec3{0.f, 0.f, 0.f}); Ray cam {{50, 52, 295.6}, glm::normalize(glm::vec3{0, -0.042612, -1})}; // cam pos, dir float near = 1.f; float far = 10000.f; glm::mat4 camera = glm::scale(glm::mat4(1.f), glm::vec3(float(w), float(h), 1.f)) * glm::translate(glm::mat4(1.f), glm::vec3(0.5, 0.5, 0.f)) * glm::perspective(float(54.5f * pi / 180.f), float(w) / float(h), near, far) * glm::lookAt(cam.origin, cam.origin + cam.direction, glm::vec3(0, 1, 0)) ; glm::mat4 screenToRay = glm::inverse(camera); QTime t; t.start(); #pragma omp parallel for for (int y = 0; y < h; y++) { std::cerr << "\rRendering: " << 100 * iterations / ((w-1)*(h-1)) << "%"; for (unsigned short x = 0; x < w; x++) { glm::vec3 r; float smoothies = 5.f; for(int smooths = 0; smooths < smoothies; ++smooths) { float u = random_u(); //float v = random_u(); float R = sqrt(-2*log(u)); //float R2 = sqrt(-2*log(v)); float xDecal = R * cos(2*pi*u)*.5; float yDecal = R * sin(2*pi*u)*.5; glm::vec4 p0 = screenToRay * glm::vec4{float(x)+xDecal-.5, float(h - y )+ yDecal-.5, 0.f, 1.f}; glm::vec4 p1 = screenToRay * glm::vec4{float(x)+xDecal-.5, float(h - y )+ yDecal-.5, 1.f, 1.f}; glm::vec3 pp0 = glm::vec3(p0 / p0.w); glm::vec3 pp1 = glm::vec3(p1 / p1.w); glm::vec3 d = glm::normalize(pp1 - pp0); r += radiance (Ray{pp0, d}); } r/=smoothies; colors[y * w + x] = colors[y * w + x]*0.25f + glm::clamp(r, glm::vec3(0.f, 0.f, 0.f), glm::vec3(1.f, 1.f, 1.f));// * 0.25f; ++iterations; } } { std::fstream f("C:\\Users\\etu\\Desktop\\image6.ppm", std::fstream::out); f << "P3\n" << w << " " << h << std::endl << "255" << std::endl; for (auto c : colors) f << toInt(c.x) << " " << toInt(c.y) << " " << toInt(c.z) << " "; } std::cout << std::endl << "Rendered in " << t.elapsed()/1000. << "s." << std::endl; }
QString VdpauWidget::benchMixer() { QString directoryName(dataDirectory); directoryName.append("mpghd.dat"); MPEGDecoder *d = new MPEGDecoder( vc, directoryName ); if ( !d->init() ) { delete d; return "Can't initialize MPEG decoder!"; } if ( mixerWidth!=d->width || mixerHeight!=d->height ) createMixer( d->width, d->height ); QList< VdpVideoSurface > list = d->getOrderedFrames(); VdpStatus st = vc->vdp_output_surface_create( vc->vdpDevice, VDP_RGBA_FORMAT_B8G8R8A8, d->width, d->height, &mixerSurface ); if ( st != VDP_STATUS_OK ) { delete d; return "FATAL: Can't create mixer output surface !!\n"; } int i, loop=0; VdpRect vid_source = { 0, 0, d->width, d->height }; setSkipChroma( 0 ); // weave setDeinterlace( DEINT_BOB ); QTime t; int e; t.start(); while ( t.elapsed() < MIXERLOOP ) { for ( i=1; i<NUMSURFACES-1; ++i ) { vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_FRAME, 0, 0, list.at(i), 0, 0, &vid_source, mixerSurface, &vid_source, &vid_source, 0, NULL ); } ++loop; } e = t.elapsed(); int n = (NUMSURFACES-2)*loop; benchMixerResult = QString("MIXER WEAVE (%1x%2): %3 frames/s\n").arg(d->width).arg(d->height).arg(n*1000/e); // bob loop = 0; t.start(); while ( t.elapsed() < MIXERLOOP ) { for ( i=1; i<NUMSURFACES-1; ++i ) { st = vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_BOTTOM_FIELD, 0, 0, list.at(i), 0, 0, &vid_source, mixerSurface, &vid_source, &vid_source, 0, NULL ); if ( st != VDP_STATUS_OK ) fprintf( stderr, "vdp_video_mixer_render failed: %s\n", vc->vdp_get_error_string( st ) ); st = vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_TOP_FIELD, 0, 0, list.at(i), 0, 0, &vid_source, mixerSurface, &vid_source, &vid_source, 0, NULL ); if ( st != VDP_STATUS_OK ) fprintf( stderr, "vdp_video_mixer_render failed: %s\n", vc->vdp_get_error_string( st ) ); } loop += 2; } e = t.elapsed(); n = (NUMSURFACES-2)*loop; benchMixerResult += QString("MIXER BOB (%1x%2): %3 fields/s\n").arg(d->width).arg(d->height).arg(n*1000/e); VdpVideoSurface past[2]; VdpVideoSurface future[1]; // temporal setDeinterlace( DEINT_TEMPORAL ); loop = 0; t.start(); while ( t.elapsed() < MIXERLOOP ) { for ( i=1; i<NUMSURFACES-1; ++i ) { past[1] = past[0] = list.at(i-1); future[0] = list.at(i); st = vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_BOTTOM_FIELD, 2, past, list.at(i), 1, future, &vid_source, mixerSurface, &vid_source, &vid_source, 0, NULL ); if ( st != VDP_STATUS_OK ) fprintf( stderr, "vdp_video_mixer_render failed: %s\n", vc->vdp_get_error_string( st ) ); past[0] = list.at(i); future[0] = list.at(i+1); st = vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_TOP_FIELD, 2, past, list.at(i), 1, future, &vid_source, mixerSurface, &vid_source, &vid_source, 0, NULL ); if ( st != VDP_STATUS_OK ) fprintf( stderr, "vdp_video_mixer_render failed: %s\n", vc->vdp_get_error_string( st ) ); } loop += 2; } e = t.elapsed(); n = (NUMSURFACES-2)*loop; benchMixerResult += QString("MIXER TEMPORAL (%1x%2): %3 fields/s\n").arg(d->width).arg(d->height).arg(n*1000/e); // temporal + ivtc setIvtc( 1 ); loop = 0; t.start(); while ( t.elapsed() < MIXERLOOP ) { for ( i=1; i<NUMSURFACES-1; ++i ) { past[1] = past[0] = list.at(i-1); future[0] = list.at(i); st = vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_BOTTOM_FIELD, 2, past, list.at(i), 1, future, &vid_source, mixerSurface, &vid_source, &vid_source, 0, NULL ); if ( st != VDP_STATUS_OK ) fprintf( stderr, "vdp_video_mixer_render failed: %s\n", vc->vdp_get_error_string( st ) ); past[0] = list.at(i); future[0] = list.at(i+1); st = vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_TOP_FIELD, 2, past, list.at(i), 1, future, &vid_source, mixerSurface, &vid_source, &vid_source, 0, NULL ); if ( st != VDP_STATUS_OK ) fprintf( stderr, "vdp_video_mixer_render failed: %s\n", vc->vdp_get_error_string( st ) ); } loop += 2; } e = t.elapsed(); n = (NUMSURFACES-2)*loop; benchMixerResult += QString("MIXER TEMPORAL + IVTC (%1x%2): %3 fields/s\n").arg(d->width).arg(d->height).arg(n*1000/e); setIvtc( 0 ); // temporal + skip_chroma setSkipChroma( 1 ); loop = 0; t.start(); while ( t.elapsed() < MIXERLOOP ) { for ( i=1; i<NUMSURFACES-1; ++i ) { past[1] = past[0] = list.at(i-1); future[0] = list.at(i); st = vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_BOTTOM_FIELD, 2, past, list.at(i), 1, future, &vid_source, mixerSurface, &vid_source, &vid_source, 0, NULL ); if ( st != VDP_STATUS_OK ) fprintf( stderr, "vdp_video_mixer_render failed: %s\n", vc->vdp_get_error_string( st ) ); past[0] = list.at(i); future[0] = list.at(i+1); st = vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_TOP_FIELD, 2, past, list.at(i), 1, future, &vid_source, mixerSurface, &vid_source, &vid_source, 0, NULL ); if ( st != VDP_STATUS_OK ) fprintf( stderr, "vdp_video_mixer_render failed: %s\n", vc->vdp_get_error_string( st ) ); } loop += 2; } e = t.elapsed(); n = (NUMSURFACES-2)*loop; benchMixerResult += QString("MIXER TEMPORAL + SKIP_CHROMA (%1x%2): %3 fields/s\n").arg(d->width).arg(d->height).arg(n*1000/e); setSkipChroma( 0 ); // temporal_spatial setDeinterlace( DEINT_TEMPORAL_SPATIAL ); loop = 0; t.start(); while ( t.elapsed() < MIXERLOOP ) { for ( i=1; i<NUMSURFACES-1; ++i ) { past[1] = past[0] = list.at(i-1); future[0] = list.at(i); st = vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_BOTTOM_FIELD, 2, past, list.at(i), 1, future, &vid_source, mixerSurface, &vid_source, &vid_source, 0, NULL ); if ( st != VDP_STATUS_OK ) fprintf( stderr, "vdp_video_mixer_render failed: %s\n", vc->vdp_get_error_string( st ) ); past[0] = list.at(i); future[0] = list.at(i+1); st = vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_TOP_FIELD, 2, past, list.at(i), 1, future, &vid_source, mixerSurface, &vid_source, &vid_source, 0, NULL ); if ( st != VDP_STATUS_OK ) fprintf( stderr, "vdp_video_mixer_render failed: %s\n", vc->vdp_get_error_string( st ) ); } loop += 2; } e = t.elapsed(); n = (NUMSURFACES-2)*loop; benchMixerResult += QString("MIXER TEMPORAL_SPATIAL (%1x%2): %3 fields/s\n").arg(d->width).arg(d->height).arg(n*1000/e); // temporal_spatial + ivtc setIvtc( 1 ); loop = 0; t.start(); while ( t.elapsed() < MIXERLOOP ) { for ( i=1; i<NUMSURFACES-1; ++i ) { past[1] = past[0] = list.at(i-1); future[0] = list.at(i); st = vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_BOTTOM_FIELD, 2, past, list.at(i), 1, future, &vid_source, mixerSurface, &vid_source, &vid_source, 0, NULL ); if ( st != VDP_STATUS_OK ) fprintf( stderr, "vdp_video_mixer_render failed: %s\n", vc->vdp_get_error_string( st ) ); past[0] = list.at(i); future[0] = list.at(i+1); st = vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_TOP_FIELD, 2, past, list.at(i), 1, future, &vid_source, mixerSurface, &vid_source, &vid_source, 0, NULL ); if ( st != VDP_STATUS_OK ) fprintf( stderr, "vdp_video_mixer_render failed: %s\n", vc->vdp_get_error_string( st ) ); } loop += 2; } e = t.elapsed(); n = (NUMSURFACES-2)*loop; benchMixerResult += QString("MIXER TEMPORAL_SPATIAL + IVTC (%1x%2): %3 fields/s\n").arg(d->width).arg(d->height).arg(n*1000/e); setIvtc( 0 ); // temporal_spatial + skip_chroma setSkipChroma( 1 ); loop = 0; t.start(); while ( t.elapsed() < MIXERLOOP ) { for ( i=1; i<NUMSURFACES-1; ++i ) { past[1] = past[0] = list.at(i-1); future[0] = list.at(i); st = vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_BOTTOM_FIELD, 2, past, list.at(i), 1, future, &vid_source, mixerSurface, &vid_source, &vid_source, 0, NULL ); if ( st != VDP_STATUS_OK ) fprintf( stderr, "vdp_video_mixer_render failed: %s\n", vc->vdp_get_error_string( st ) ); past[0] = list.at(i); future[0] = list.at(i+1); st = vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_TOP_FIELD, 2, past, list.at(i), 1, future, &vid_source, mixerSurface, &vid_source, &vid_source, 0, NULL ); if ( st != VDP_STATUS_OK ) fprintf( stderr, "vdp_video_mixer_render failed: %s\n", vc->vdp_get_error_string( st ) ); } loop += 2; } e = t.elapsed(); n = (NUMSURFACES-2)*loop; benchMixerResult += QString("MIXER TEMPORAL_SPATIAL + SKIP_CHROMA (%1x%2): %3 fields/s\n").arg(d->width).arg(d->height).arg(n*1000/e); setSkipChroma( 0 ); delete d; vc->vdp_output_surface_destroy( mixerSurface ); // SD directoryName.clear(); directoryName.append(dataDirectory); directoryName.append("mpgsd.dat"); d = new MPEGDecoder( vc, directoryName ); if ( !d->init() ) { delete d; return "Can't initialize MPEG decoder!"; } if ( mixerWidth!=d->width || mixerHeight!=d->height ) createMixer( d->width, d->height ); list = d->getOrderedFrames(); int sdwidth=1920, sdheight=1080; st = vc->vdp_output_surface_create( vc->vdpDevice, VDP_RGBA_FORMAT_B8G8R8A8, sdwidth, sdheight, &mixerSurface ); if ( st != VDP_STATUS_OK ) { delete d; return "FATAL: Can't create mixer output surface !!\n"; } vid_source.x1 = d->width; vid_source.y1 = d->height; VdpRect vid_dest = { 0, 0, sdwidth, sdheight }; // temporal_spatial SD setDeinterlace( DEINT_TEMPORAL_SPATIAL ); loop = 0; t.start(); while ( t.elapsed() < MIXERLOOP ) { for ( i=1; i<NUMSURFACES-1; ++i ) { past[1] = past[0] = list.at(i-1); future[0] = list.at(i); st = vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_TOP_FIELD, 2, past, list.at(i), 1, future, &vid_source, mixerSurface, &vid_dest, &vid_dest, 0, NULL ); if ( st != VDP_STATUS_OK ) fprintf( stderr, "vdp_video_mixer_render failed: %s\n", vc->vdp_get_error_string( st ) ); past[0] = list.at(i); future[0] = list.at(i+1); st = vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_BOTTOM_FIELD, 2, past, list.at(i), 1, future, &vid_source, mixerSurface, &vid_dest, &vid_dest, 0, NULL ); if ( st != VDP_STATUS_OK ) fprintf( stderr, "vdp_video_mixer_render failed: %s\n", vc->vdp_get_error_string( st ) ); } loop+=2; } e = t.elapsed(); n = (NUMSURFACES-2)*loop; benchMixerResult += QString("MIXER TEMPORAL_SPATIAL (%1x%2 video to 1920x1080 display): %3 fields/s\n").arg(d->width).arg(d->height).arg(n*1000/e); // temporal_spatial SD + hqScaling if ( vc->hqScalingSupported() ) { setHqScaling( 1 ); loop = 0; t.start(); while ( t.elapsed() < MIXERLOOP ) { for ( i=1; i<NUMSURFACES-1; ++i ) { past[1] = past[0] = list.at(i-1); future[0] = list.at(i); st = vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_TOP_FIELD, 2, past, list.at(i), 1, future, &vid_source, mixerSurface, &vid_dest, &vid_dest, 0, NULL ); if ( st != VDP_STATUS_OK ) fprintf( stderr, "vdp_video_mixer_render failed: %s\n", vc->vdp_get_error_string( st ) ); past[0] = list.at(i); future[0] = list.at(i+1); st = vc->vdp_video_mixer_render( mixer, VDP_INVALID_HANDLE, 0, VDP_VIDEO_MIXER_PICTURE_STRUCTURE_BOTTOM_FIELD, 2, past, list.at(i), 1, future, &vid_source, mixerSurface, &vid_dest, &vid_dest, 0, NULL ); if ( st != VDP_STATUS_OK ) fprintf( stderr, "vdp_video_mixer_render failed: %s\n", vc->vdp_get_error_string( st ) ); } loop+=2; } e = t.elapsed(); n = (NUMSURFACES-2)*loop; benchMixerResult += QString("MIXER TEMPORAL_SPATIAL + HQSCALING (%1x%2 video to 1920x1080 display): %3 fields/s\n").arg(d->width).arg(d->height).arg(n*1000/e); setHqScaling( 0 ); } delete d; return benchMixerResult; }
// next 2 functions are the 2 threads. // the first one (the main thread) runs the decoder // the second one runs the mixer QString VdpauWidget::benchMT() { // init a mpeg decoder QString directoryName(dataDirectory); directoryName.append("mpghd.dat"); MPEGDecoder *m = new MPEGDecoder( vc, directoryName ); if ( !m->init() ) { delete m; return "Can't initialize MPEG decoder (1)!"; } // create the rgba surface used by the mixer VdpStatus st = vc->vdp_output_surface_create( vc->vdpDevice, VDP_RGBA_FORMAT_B8G8R8A8, m->width, m->height, &mixerSurface ); if ( st != VDP_STATUS_OK ) { delete m; return "FATAL: Can't create mixer output surface !!\n"; } if ( mixerWidth!=m->width || mixerHeight!=m->height ) createMixer( m->width, m->height ); setDeinterlace( DEINT_TEMPORAL ); // init the mixer thread // m->getOrderedFrames returns a list of 22 decoded surfaces in display order and destroys the decoder ... VdpauThread vt( vc, m->getOrderedFrames(), mixer, mixerSurface, m->width, m->height ); // ... so we can create a new one here directoryName.clear(); directoryName.append(dataDirectory); directoryName.append("mpghd.dat"); MPEGDecoder *d = new MPEGDecoder( vc, directoryName ); if ( !d->init( true ) ) { delete d; delete m; vc->vdp_output_surface_destroy( mixerSurface ); return "Can't initialize MPEG decoder (2)!"; } vt.running = true; // start the mixer thread vt.start(); int loop=0; QTime t; t.start(); // this is the decoder loop while ( t.elapsed() < MIXERLOOP ) { // decode next frame (25 frames in turn) d->getNextFrame(); ++loop; } int e = t.elapsed(); vt.running = false; // wait for the mixer thread to end vt.wait(); benchMTResult = QString("MULTITHREADED MPEG DECODING (%1x%2): %3 frames/s\n").arg(d->width).arg(d->height).arg(loop*1000/e); benchMTResult += vt.result; delete d; delete m; vc->vdp_output_surface_destroy( mixerSurface ); return benchMTResult; }
bool SceneViewer::event(QEvent *e) { if (e->type() == QEvent::ShortcutOverride || e->type() == QEvent::KeyPress) { if (!((QKeyEvent *)e)->isAutoRepeat()) { TApp::instance()->getCurrentTool()->storeTool(); } } if (e->type() == QEvent::ShortcutOverride) { TTool *tool = TApp::instance()->getCurrentTool()->getTool(); if (tool && tool->isEnabled() && tool->getName() == T_Type && tool->isActive()) e->accept(); return true; } if (e->type() == QEvent::KeyRelease) { if (!((QKeyEvent *)e)->isAutoRepeat()) { QWidget *focusWidget = QApplication::focusWidget(); if (focusWidget == 0 || QString(focusWidget->metaObject()->className()) == "SceneViewer") TApp::instance()->getCurrentTool()->restoreTool(); } } // discard too frequent move events static QTime clock; if (e->type() == QEvent::MouseButtonPress) clock.start(); else if (e->type() == QEvent::MouseMove) { if (clock.elapsed() < 10) { e->accept(); return true; } clock.start(); } /* switch(e->type()) { case QEvent::Enter: qDebug() << "************************** Enter"; break; case QEvent::Leave: qDebug() << "************************** Leave"; break; case QEvent::TabletPress: qDebug() << "************************** TabletPress" << m_pressure; break; case QEvent::TabletMove: qDebug() << "************************** TabletMove"; break; case QEvent::TabletRelease: qDebug() << "************************** TabletRelease"; break; case QEvent::MouseButtonPress: qDebug() << "**************************MouseButtonPress" << m_pressure << " " << m_tabletEvent; break; case QEvent::MouseMove: qDebug() << "**************************MouseMove" << m_pressure; break; case QEvent::MouseButtonRelease: qDebug() << "**************************MouseButtonRelease"; break; case QEvent::MouseButtonDblClick: qDebug() << "============================== MouseButtonDblClick"; break; } */ return QGLWidget::event(e); }
void AdapterTimeSeriesDataSetTest::test_deserialise_timing() { try { // Create configuration node. _fixedSizePackets = "false"; _config = _configXml(_fixedSizePackets, _dataBitSize, _udpPacketsPerIteration, _samplesPerPacket, _outputChannelsPerSubband, _subbandsPerPacket, _nRawPolarisations); typedef TYPES::i16complex i16c; // Construct the adapter. AdapterTimeSeriesDataSet adapter(_config); // Construct a data blob to adapt into. TimeSeriesDataSetC32 timeSeries; unsigned nTimes = (_udpPacketsPerIteration * _samplesPerPacket); unsigned nTimeBlocks = nTimes / _outputChannelsPerSubband; unsigned nData = _subbandsPerPacket * _nRawPolarisations * _samplesPerPacket; size_t packetSize = sizeof(UDPPacket::Header) + (nData * _dataBitSize * 2) / 8; size_t chunkSize = packetSize * _udpPacketsPerIteration; // Configure the adapter setting the data blob, chunk size and service data. adapter.config(&timeSeries, chunkSize, QHash<QString, DataBlob*>()); // Create and fill UDP packets. std::vector<UDPPacket> packets(_udpPacketsPerIteration); unsigned index = 0; for (unsigned i = 0; i < _udpPacketsPerIteration; ++i) { // Fill in the header packets[i].header.version = uint8_t(0 + i); packets[i].header.sourceInfo = uint8_t(1 + i); packets[i].header.configuration = uint16_t(_dataBitSize); packets[i].header.station = uint16_t(3 + i); packets[i].header.nrBeamlets = uint8_t(4 + i); packets[i].header.nrBlocks = uint8_t(5 + i); packets[i].header.timestamp = uint32_t(6 + i); packets[i].header.blockSequenceNumber = uint32_t(7 + i); // Fill in the data for (unsigned ii = 0, t = 0; t < _samplesPerPacket; ++t) { for (unsigned c = 0; c < _subbandsPerPacket; ++c) { for (unsigned p = 0; p < _nRawPolarisations; ++p) { i16c* data = reinterpret_cast<i16c*>(packets[i].data); index = _nRawPolarisations * (t * _subbandsPerPacket + c) + p; data[index] = i16c(ii++, i); } } } } // Stick the chunk of packets into an QIODevice (buffer). { QBuffer buffer; buffer.setData(reinterpret_cast<char*>(&packets[0]), chunkSize); buffer.open(QBuffer::ReadOnly); adapter.deserialise(&buffer); } QBuffer buffer; buffer.setData(reinterpret_cast<char*>(&packets[0]), chunkSize); buffer.open(QBuffer::ReadOnly); QTime timer; timer.start(); adapter.deserialise(&buffer); int elapsed = timer.elapsed(); // std::cout << timeSeries.timeSeries(0) << cout << endl; cout << "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" << endl; cout << "[AdapterTimeSeriesDataSet]: deserialise() " << endl; cout << "- nChan = " << _outputChannelsPerSubband << endl << endl; if (_verbose) { cout << "- nBlocks = " << nTimeBlocks << endl; cout << "- nSubbands = " << _subbandsPerPacket << endl; cout << "- nPols = " << _nRawPolarisations << endl; cout << "- nTimes = " << nTimes << endl; } cout << "* Elapsed = " << elapsed << " ms." << endl; cout << "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" << endl; } catch (const QString& err) { CPPUNIT_FAIL(err.toStdString().data()); } }
void tst_QSemaphore::tryAcquireWithTimeout() { QFETCH(int, timeout); QSemaphore semaphore; QTime time; QCOMPARE(semaphore.available(), 0); semaphore.release(); QCOMPARE(semaphore.available(), 1); time.start(); QVERIFY(!semaphore.tryAcquire(2, timeout)); QVERIFY(time.elapsed() >= timeout); QCOMPARE(semaphore.available(), 1); semaphore.release(); QCOMPARE(semaphore.available(), 2); time.start(); QVERIFY(!semaphore.tryAcquire(3, timeout)); QVERIFY(time.elapsed() >= timeout); QCOMPARE(semaphore.available(), 2); semaphore.release(10); QCOMPARE(semaphore.available(), 12); time.start(); QVERIFY(!semaphore.tryAcquire(100, timeout)); QVERIFY(time.elapsed() >= timeout); QCOMPARE(semaphore.available(), 12); semaphore.release(10); QCOMPARE(semaphore.available(), 22); time.start(); QVERIFY(!semaphore.tryAcquire(100, timeout)); QVERIFY(time.elapsed() >= timeout); QCOMPARE(semaphore.available(), 22); time.start(); QVERIFY(semaphore.tryAcquire(1, timeout)); QVERIFY(time.elapsed() <= timeout); QCOMPARE(semaphore.available(), 21); time.start(); QVERIFY(semaphore.tryAcquire(1, timeout)); QVERIFY(time.elapsed() <= timeout); QCOMPARE(semaphore.available(), 20); time.start(); QVERIFY(semaphore.tryAcquire(10, timeout)); QVERIFY(time.elapsed() <= timeout); QCOMPARE(semaphore.available(), 10); time.start(); QVERIFY(semaphore.tryAcquire(10, timeout)); QVERIFY(time.elapsed() <= timeout); QCOMPARE(semaphore.available(), 0); // should not be able to acquire more time.start(); QVERIFY(!semaphore.tryAcquire(1, timeout)); QVERIFY(time.elapsed() >= timeout); QCOMPARE(semaphore.available(), 0); time.start(); QVERIFY(!semaphore.tryAcquire(1, timeout)); QVERIFY(time.elapsed() >= timeout); QCOMPARE(semaphore.available(), 0); time.start(); QVERIFY(!semaphore.tryAcquire(10, timeout)); QVERIFY(time.elapsed() >= timeout); QCOMPARE(semaphore.available(), 0); time.start(); QVERIFY(!semaphore.tryAcquire(10, timeout)); QVERIFY(time.elapsed() >= timeout); QCOMPARE(semaphore.available(), 0); }
void CSyncThread::run() { CSYNC *csync; WalkStats *wStats = new WalkStats; QTime walkTime; wStats->sourcePath = 0; wStats->errorType = 0; wStats->eval = 0; wStats->removed = 0; wStats->renamed = 0; wStats->newFiles = 0; wStats->ignores = 0; wStats->sync = 0; wStats->seenFiles = 0; wStats->conflicts = 0; wStats->error = 0; _mutex.lock(); if( csync_create(&csync, _source.toLocal8Bit().data(), _target.toLocal8Bit().data()) < 0 ) { emit csyncError( tr("CSync create failed.") ); } // FIXME: Check if we really need this stringcopy! wStats->sourcePath = qstrdup( _source.toLocal8Bit().constData() ); _mutex.unlock(); qDebug() << "## CSync Thread local only: " << _localCheckOnly; csync_set_auth_callback( csync, getauth ); csync_enable_conflictcopys(csync); MirallConfigFile cfg; QString excludeList = cfg.excludeFile(); if( !excludeList.isEmpty() ) { qDebug() << "==== added CSync exclude List: " << excludeList.toAscii(); csync_add_exclude_list( csync, excludeList.toAscii() ); } QTime t; t.start(); _mutex.lock(); if( _localCheckOnly ) { csync_set_local_only( csync, true ); } _mutex.unlock(); if( csync_init(csync) < 0 ) { CSYNC_ERROR_CODE err = csync_errno(); QString errStr; switch( err ) { case CSYNC_ERR_LOCK: errStr = tr("CSync failed to create a lock file."); break; case CSYNC_ERR_STATEDB_LOAD: errStr = tr("CSync failed to load the state db."); break; case CSYNC_ERR_MODULE: errStr = tr("CSync failed to load the ownCloud module."); break; case CSYNC_ERR_TIMESKEW: errStr = tr("The system time between the local machine and the server differs " "too much. Please use a time syncronization service (ntp) on both machines."); break; case CSYNC_ERR_FILESYSTEM: errStr = tr("CSync could not detect the filesystem type."); break; case CSYNC_ERR_TREE: errStr = tr("CSync got an error while processing internal trees."); break; default: errStr = tr("An internal error number %1 happend.").arg( (int) err ); } qDebug() << " #### ERROR String emitted: " << errStr; emit csyncError(errStr); goto cleanup; } qDebug() << "############################################################### >>"; if( csync_update(csync) < 0 ) { emit csyncError(tr("CSync Update failed.")); goto cleanup; } qDebug() << "<<###############################################################"; csync_set_userdata(csync, wStats); walkTime.start(); if( csync_walk_local_tree(csync, &checkPermissions, 0) < 0 ) { qDebug() << "Error in treewalk."; if( wStats->errorType == WALK_ERROR_DIR_PERMS ) { emit csyncError(tr("The local filesystem has directories which are write protected.\n" "That prevents ownCloud from successful syncing.\n" "Please make sure that all directories are writeable.")); } else if( wStats->errorType == WALK_ERROR_WALK ) { emit csyncError(tr("CSync encountered an error while examining the file system.\n" "Syncing is not possible.")); } else if( wStats->errorType == WALK_ERROR_INSTRUCTIONS ) { emit csyncError(tr("CSync update generated a strange instruction.\n" "Please write a bug report.")); } emit csyncError(tr("Local filesystem problems. Better disable Syncing and check.")); goto cleanup; } qDebug() << " ..... Local walk finished: " << walkTime.elapsed(); // emit the treewalk results. Do not touch the wStats after this. emit treeWalkResult(wStats); _mutex.lock(); if( _localCheckOnly ) { _mutex.unlock(); // we have to go out here as its local check only. goto cleanup; } else { _mutex.unlock(); // check if we can write all over. if( csync_reconcile(csync) < 0 ) { emit csyncError(tr("CSync reconcile failed.")); goto cleanup; } if( csync_propagate(csync) < 0 ) { emit csyncError(tr("CSync propagate failed.")); goto cleanup; } } cleanup: csync_destroy(csync); /* * Attention: do not delete the wStat memory here. it is deleted in the * slot catching the signel treeWalkResult because this thread can faster * die than the slot has read out the data. */ qDebug() << "CSync run took " << t.elapsed() << " Milliseconds"; }
void ImageViewController::imageAndGridDoneSlot( QImage image, Carta::Lib::VectorGraphics::VGList gridVG, Carta::Lib::VectorGraphics::VGList contourVG, ServiceSync::JobId /*jobId*/ ) { /// \todo we should make sure the jobId matches the last submitted job, otherwise /// we are wasting CPU rendering old job... // qDebug() << "imageAndGridDoneSlot" << jobId << "xyz"; m_renderBuffer = image; // draw the grid over top QTime t; t.restart(); QPainter painter( & m_renderBuffer ); painter.setRenderHint( QPainter::Antialiasing, true ); Carta::Lib::VectorGraphics::VGListQPainterRenderer vgRenderer; if ( ! vgRenderer.render( gridVG, painter ) ) { qWarning() << "could not render grid vector graphics"; } qDebug() << "Grid VG rendered in" << t.elapsed() / 1000.0 << "sec" << "xyz"; t.restart(); { QPen lineColor( QColor( "red" ), 1 ); lineColor.setCosmetic( true ); painter.setPen( lineColor ); // where does 0.5, 0.5 map to? QPointF p1 = m_renderService-> img2screen( { 0.5, 0.5 } ); // where does 1.5, 1.5 map to? QPointF p2 = m_renderService-> img2screen( { 1.5, 1.5 } ); QTransform tf; double m11 = p2.x() - p1.x(); double m22 = p2.y() - p1.y(); double m33 = 1; // no projection double m13 = 0; // no projection double m23 = 0; // no projection double m12 = 0; // no shearing double m21 = 0; // no shearing double m31 = p1.x() - m11 * 0.5; double m32 = p1.y() - m22 * 0.5; tf.setMatrix( m11, m12, m13, m21, m22, m23, m31, m32, m33 ); painter.setTransform( tf ); } if ( ! vgRenderer.render( contourVG, painter ) ) { qWarning() << "could not render contour vector graphics"; } qDebug() << "Contour VG rendered in" << t.elapsed() / 1000.0 << "sec" << "xyz"; // // paint contours // QPen lineColor( QColor( "red" ), 1 ); // lineColor.setCosmetic( true ); // painter.setPen( lineColor ); // // where does 0.5, 0.5 map to? // QPointF p1 = m_renderService-> img2screen( { 0.5, 0.5 } // ); // // where does 1.5, 1.5 map to? // QPointF p2 = m_renderService-> img2screen( { 1.5, 1.5 } // ); // QTransform tf; // double m11 = p2.x() - p1.x(); // double m22 = p2.y() - p1.y(); // double m33 = 1; // no projection // double m13 = 0; // no projection // double m23 = 0; // no projection // double m12 = 0; // no shearing // double m21 = 0; // no shearing // double m31 = p1.x() - m11 * 0.5; // double m32 = p1.y() - m22 * 0.5; // tf.setMatrix( m11, m12, m13, m21, m22, m23, m31, m32, m33 ); // painter.setTransform( tf ); // for ( size_t k = 0 ; k < m_contours.size() ; ++k ) { // std::vector < QPolygonF > con = m_contours[k]; // for ( size_t i = 0 ; i < con.size() ; ++i ) { // QPolygonF & poly = con[i]; // painter.drawPolyline( poly ); // } // } // schedule a repaint with the connector m_connector-> refreshView( this ); } // imageAndGridDoneSlot
void NBioBSP_IndexSearch::on_btIdentify_pressed() { NBioAPI_UINT32 nDataCount = 0; //NBioAPI Search DB Count. NBioAPI_GetDataCountFromIndexSearchDB(m_hNBioBSP, &nDataCount); ui->pgbarSearch->setRange(0, nDataCount); ui->pgbarSearch->setValue(0); m_bStopFlag = false; NBioAPI_RETURN nRet = NBioAPI_OpenDevice(m_hNBioBSP, NBioAPI_DEVICE_ID_AUTO); if (NBioAPIERROR_NONE != nRet) { QString szError; szError.sprintf("NBioAPI_OpenDevice error: %04X", nRet); ui->labelStatus->setText(szError); } else { NBioAPI_FIR_HANDLE hFIR; //NBioAPI Capture nRet = NBioAPI_Capture(m_hNBioBSP, NBioAPI_FIR_PURPOSE_IDENTIFY, &hFIR, NBioAPI_USE_DEFAULT_TIMEOUT, NULL, NULL); if (NBioAPIERROR_NONE == nRet) { NBioAPI_INPUT_FIR inputFIR; inputFIR.Form = NBioAPI_FIR_FORM_HANDLE; inputFIR.InputFIR.FIRinBSP = &hFIR; NBioAPI_INDEXSEARCH_FP_INFO infoFp; NBioAPI_INDEXSEARCH_CALLBACK_INFO_0 callbackInfo0; callbackInfo0.CallBackType = 0; callbackInfo0.CallBackFunction = MyIndexSearchCallBack; callbackInfo0.UserCallBackParam = this; //Search DB QTime t; ui->btStop->setEnabled(true); pSearchModel->removeRows(0, pSearchModel->rowCount(QModelIndex()), QModelIndex()); t.start(); nRet = NBioAPI_IdentifyDataFromIndexSearchDB(m_hNBioBSP, &inputFIR, 5, &infoFp, &callbackInfo0); int nElapsed = t.elapsed(); ui->btStop->setEnabled(false); ui->labelSearchTime->setText(QString("%1.%2 sec").arg(nElapsed / 1000).arg(nElapsed % 1000)); if (NBioAPIERROR_NONE != nRet) { if (NBioAPIERROR_INDEXSEARCH_IDENTIFY_STOP != nRet) QMessageBox::warning(this, "NBioBSP_IndexSearch", "Failed to identify fingerprint data from DB!"); } else { int nIndex = 0; pSearchModel->insertRow(nIndex, QModelIndex()); pSearchModel->setData(pSearchModel->index(nIndex, 0, QModelIndex()), infoFp.ID); pSearchModel->setData(pSearchModel->index(nIndex, 1, QModelIndex()), infoFp.FingerID); pSearchModel->setData(pSearchModel->index(nIndex, 2, QModelIndex()), infoFp.SampleNumber); pSearchModel->setData(pSearchModel->index(nIndex, 3, QModelIndex()), "-"); } } NBioAPI_FreeFIRHandle(m_hNBioBSP, hFIR); NBioAPI_CloseDevice(m_hNBioBSP, NBioAPI_DEVICE_ID_AUTO); } if (ui->pgbarSearch->maximum() == 0) ui->pgbarSearch->setRange(0, 100); }
void PathFinding::internalSearchPath(const std::string &destination_map,const uint8_t &destination_x,const uint8_t &destination_y, const std::string ¤t_map,const uint8_t &x,const uint8_t &y,const std::unordered_map<uint16_t,uint32_t> &items) { Q_UNUSED(items); QTime time; time.restart(); std::unordered_map<std::string,SimplifiedMapForPathFinding> simplifiedMapList; //transfer from object to local variable { QMutexLocker locker(&mutex); simplifiedMapList=this->simplifiedMapList; this->simplifiedMapList.clear(); } //resolv the path if(!tryCancel) { std::vector<MapPointToParse> mapPointToParseList; //init the first case { MapPointToParse tempPoint; tempPoint.map=current_map; tempPoint.x=x; tempPoint.y=y; mapPointToParseList.push_back(tempPoint); std::pair<uint8_t,uint8_t> coord(tempPoint.x,tempPoint.y); SimplifiedMapForPathFinding &tempMap=simplifiedMapList[current_map]; tempMap.pathToGo[coord].left.push_back( std::pair<CatchChallenger::Orientation,uint8_t/*step number*/>(CatchChallenger::Orientation_left,1)); tempMap.pathToGo[coord].right.push_back( std::pair<CatchChallenger::Orientation,uint8_t/*step number*/>(CatchChallenger::Orientation_right,1)); tempMap.pathToGo[coord].bottom.push_back( std::pair<CatchChallenger::Orientation,uint8_t/*step number*/>(CatchChallenger::Orientation_bottom,1)); tempMap.pathToGo[coord].top.push_back( std::pair<CatchChallenger::Orientation,uint8_t/*step number*/>(CatchChallenger::Orientation_top,1)); } std::pair<uint8_t,uint8_t> coord; while(!mapPointToParseList.empty()) { const SimplifiedMapForPathFinding &simplifiedMapForPathFinding=simplifiedMapList.at(current_map); const MapPointToParse tempPoint=mapPointToParseList.front(); mapPointToParseList.erase(mapPointToParseList.cbegin()); SimplifiedMapForPathFinding::PathToGo pathToGo; if(destination_map==current_map && tempPoint.x==destination_x && tempPoint.y==destination_y) qDebug() << "final dest"; //resolv the own point int index=0; while(index<1)/*2*/ { if(tryCancel) { tryCancel=false; return; } { //if the right case have been parsed coord=std::pair<uint8_t,uint8_t>(tempPoint.x+1,tempPoint.y); if(simplifiedMapForPathFinding.pathToGo.find(coord)!=simplifiedMapForPathFinding.pathToGo.cend()) { const SimplifiedMapForPathFinding::PathToGo &nearPathToGo=simplifiedMapForPathFinding.pathToGo.at(coord); if(pathToGo.left.empty() || pathToGo.left.size()>nearPathToGo.left.size()) { pathToGo.left=nearPathToGo.left; pathToGo.left.back().second++; } if(pathToGo.top.empty() || pathToGo.top.size()>(nearPathToGo.left.size()+1)) { pathToGo.top=nearPathToGo.left; pathToGo.top.push_back(std::pair<CatchChallenger::Orientation,uint8_t/*step number*/>(CatchChallenger::Orientation_top,1)); } if(pathToGo.bottom.empty() || pathToGo.bottom.size()>(nearPathToGo.left.size()+1)) { pathToGo.bottom=nearPathToGo.left; pathToGo.bottom.push_back(std::pair<CatchChallenger::Orientation,uint8_t/*step number*/>(CatchChallenger::Orientation_bottom,1)); } } //if the left case have been parsed coord=std::pair<uint8_t,uint8_t>(tempPoint.x-1,tempPoint.y); if(simplifiedMapForPathFinding.pathToGo.find(coord)!=simplifiedMapForPathFinding.pathToGo.cend()) { const SimplifiedMapForPathFinding::PathToGo &nearPathToGo=simplifiedMapForPathFinding.pathToGo.at(coord); if(pathToGo.right.empty() || pathToGo.right.size()>nearPathToGo.right.size()) { pathToGo.right=nearPathToGo.right; pathToGo.right.back().second++; } if(pathToGo.top.empty() || pathToGo.top.size()>(nearPathToGo.right.size()+1)) { pathToGo.top=nearPathToGo.right; pathToGo.top.push_back(std::pair<CatchChallenger::Orientation,uint8_t/*step number*/>(CatchChallenger::Orientation_top,1)); } if(pathToGo.bottom.empty() || pathToGo.bottom.size()>(nearPathToGo.right.size()+1)) { pathToGo.bottom=nearPathToGo.right; pathToGo.bottom.push_back(std::pair<CatchChallenger::Orientation,uint8_t/*step number*/>(CatchChallenger::Orientation_bottom,1)); } } //if the top case have been parsed coord=std::pair<uint8_t,uint8_t>(tempPoint.x,tempPoint.y+1); if(simplifiedMapForPathFinding.pathToGo.find(coord)!=simplifiedMapForPathFinding.pathToGo.cend()) { const SimplifiedMapForPathFinding::PathToGo &nearPathToGo=simplifiedMapForPathFinding.pathToGo.at(coord); if(pathToGo.top.empty() || pathToGo.top.size()>nearPathToGo.top.size()) { pathToGo.top=nearPathToGo.top; pathToGo.top.back().second++; } if(pathToGo.left.empty() || pathToGo.left.size()>(nearPathToGo.top.size()+1)) { pathToGo.left=nearPathToGo.top; pathToGo.left.push_back(std::pair<CatchChallenger::Orientation,uint8_t/*step number*/>(CatchChallenger::Orientation_left,1)); } if(pathToGo.right.empty() || pathToGo.right.size()>(nearPathToGo.top.size()+1)) { pathToGo.right=nearPathToGo.top; pathToGo.right.push_back(std::pair<CatchChallenger::Orientation,uint8_t/*step number*/>(CatchChallenger::Orientation_right,1)); } } //if the bottom case have been parsed coord=std::pair<uint8_t,uint8_t>(tempPoint.x,tempPoint.y-1); if(simplifiedMapForPathFinding.pathToGo.find(coord)!=simplifiedMapForPathFinding.pathToGo.cend()) { const SimplifiedMapForPathFinding::PathToGo &nearPathToGo=simplifiedMapForPathFinding.pathToGo.at(coord); if(pathToGo.bottom.empty() || pathToGo.bottom.size()>nearPathToGo.bottom.size()) { pathToGo.bottom=nearPathToGo.bottom; pathToGo.bottom.back().second++; } if(pathToGo.left.empty() || pathToGo.left.size()>(nearPathToGo.bottom.size()+1)) { pathToGo.left=nearPathToGo.bottom; pathToGo.left.push_back(std::pair<CatchChallenger::Orientation,uint8_t/*step number*/>(CatchChallenger::Orientation_left,1)); } if(pathToGo.right.empty() || pathToGo.right.size()>(nearPathToGo.bottom.size()+1)) { pathToGo.right=nearPathToGo.bottom; pathToGo.right.push_back(std::pair<CatchChallenger::Orientation,uint8_t/*step number*/>(CatchChallenger::Orientation_right,1)); } } } index++; } coord=std::pair<uint8_t,uint8_t>(tempPoint.x,tempPoint.y); if(simplifiedMapForPathFinding.pathToGo.find(coord)==simplifiedMapForPathFinding.pathToGo.cend()) { #ifdef CATCHCHALLENGER_EXTRA_CHECK extraControlOnData(pathToGo.left,CatchChallenger::Orientation_left); extraControlOnData(pathToGo.right,CatchChallenger::Orientation_right); extraControlOnData(pathToGo.top,CatchChallenger::Orientation_top); extraControlOnData(pathToGo.bottom,CatchChallenger::Orientation_bottom); #endif simplifiedMapList[current_map].pathToGo[coord]=pathToGo; } if(destination_map==current_map && tempPoint.x==destination_x && tempPoint.y==destination_y) { tryCancel=false; std::vector<std::pair<CatchChallenger::Orientation,uint8_t/*step number*/> > returnedVar; if(returnedVar.empty() || pathToGo.bottom.size()<returnedVar.size()) if(!pathToGo.bottom.empty()) returnedVar=pathToGo.bottom; if(returnedVar.empty() || pathToGo.top.size()<returnedVar.size()) if(!pathToGo.top.empty()) returnedVar=pathToGo.top; if(returnedVar.empty() || pathToGo.right.size()<returnedVar.size()) if(!pathToGo.right.empty()) returnedVar=pathToGo.right; if(returnedVar.empty() || pathToGo.left.size()<returnedVar.size()) if(!pathToGo.left.empty()) returnedVar=pathToGo.left; if(!returnedVar.empty()) { if(returnedVar.back().second<=1) { qDebug() << "Bug due for last step"; return; } else { qDebug() << "Path result into " << time.elapsed() << "ms"; returnedVar.back().second--; emit result(current_map,x,y,returnedVar); return; } } else { returnedVar.clear(); qDebug() << "Bug due to resolved path is empty"; return; } } //revers resolv //add to point to parse { //if the right case have been parsed coord=std::pair<uint8_t,uint8_t>(tempPoint.x+1,tempPoint.y); if(simplifiedMapForPathFinding.pathToGo.find(coord)==simplifiedMapForPathFinding.pathToGo.cend()) { MapPointToParse newPoint=tempPoint; newPoint.x++; if(newPoint.x<simplifiedMapForPathFinding.width) if(PathFinding::canGoOn(simplifiedMapForPathFinding,newPoint.x,newPoint.y) || (destination_map==current_map && newPoint.x==destination_x && newPoint.y==destination_y)) { std::pair<uint8_t,uint8_t> point(newPoint.x,newPoint.y); if(simplifiedMapForPathFinding.pointQueued.find(point)==simplifiedMapForPathFinding.pointQueued.cend()) { simplifiedMapList[current_map].pointQueued.insert(point); mapPointToParseList.push_back(newPoint); } } } //if the left case have been parsed coord=std::pair<uint8_t,uint8_t>(tempPoint.x-1,tempPoint.y); if(simplifiedMapForPathFinding.pathToGo.find(coord)==simplifiedMapForPathFinding.pathToGo.cend()) { MapPointToParse newPoint=tempPoint; if(newPoint.x>0) { newPoint.x--; if(PathFinding::canGoOn(simplifiedMapForPathFinding,newPoint.x,newPoint.y) || (destination_map==current_map && newPoint.x==destination_x && newPoint.y==destination_y)) { std::pair<uint8_t,uint8_t> point(newPoint.x,newPoint.y); if(simplifiedMapForPathFinding.pointQueued.find(point)==simplifiedMapForPathFinding.pointQueued.cend()) { simplifiedMapList[current_map].pointQueued.insert(point); mapPointToParseList.push_back(newPoint); } } } } //if the bottom case have been parsed coord=std::pair<uint8_t,uint8_t>(tempPoint.x,tempPoint.y+1); if(simplifiedMapForPathFinding.pathToGo.find(coord)==simplifiedMapForPathFinding.pathToGo.cend()) { MapPointToParse newPoint=tempPoint; newPoint.y++; if(newPoint.y<simplifiedMapForPathFinding.height) if(PathFinding::canGoOn(simplifiedMapForPathFinding,newPoint.x,newPoint.y) || (destination_map==current_map && newPoint.x==destination_x && newPoint.y==destination_y)) { std::pair<uint8_t,uint8_t> point(newPoint.x,newPoint.y); if(simplifiedMapForPathFinding.pointQueued.find(point)==simplifiedMapForPathFinding.pointQueued.cend()) { simplifiedMapList[current_map].pointQueued.insert(point); mapPointToParseList.push_back(newPoint); } } } //if the top case have been parsed coord=std::pair<uint8_t,uint8_t>(tempPoint.x,tempPoint.y-1); if(simplifiedMapForPathFinding.pathToGo.find(coord)==simplifiedMapForPathFinding.pathToGo.cend()) { MapPointToParse newPoint=tempPoint; if(newPoint.y>0) { newPoint.y--; if(PathFinding::canGoOn(simplifiedMapForPathFinding,newPoint.x,newPoint.y) || (destination_map==current_map && newPoint.x==destination_x && newPoint.y==destination_y)) { std::pair<uint8_t,uint8_t> point(newPoint.x,newPoint.y); if(simplifiedMapForPathFinding.pointQueued.find(point)==simplifiedMapForPathFinding.pointQueued.cend()) { simplifiedMapList[current_map].pointQueued.insert(point); mapPointToParseList.push_back(newPoint); } } } } } /*uint8_t tempX=x,TempY=y; std::string tempMap=current_map; SimplifiedMapForPathFinding::PathToGo pathToGoTemp; simplifiedMapList[current_map].pathToGo[std::pair<uint8_t,uint8_t>(x,y)]=pathToGoTemp;*/ } } //drop the local variable { for ( auto &n : simplifiedMapList ) { if(n.second.dirt!=NULL) { delete n.second.dirt; n.second.dirt=NULL; } if(n.second.ledges!=NULL) { delete n.second.ledges; n.second.ledges=NULL; } if(n.second.walkable!=NULL) { delete n.second.walkable; n.second.walkable=NULL; } if(n.second.monstersCollisionMap!=NULL) { delete n.second.monstersCollisionMap; n.second.monstersCollisionMap=NULL; } } } tryCancel=false; emit result(std::string(),0,0,std::vector<std::pair<CatchChallenger::Orientation,uint8_t> >()); qDebug() << "Path not found into " << time.elapsed() << "ms"; }
void Worker::armHola() { QTime t; int count=0; while(rbHola->isChecked()) { if (count>1) break; count++; try { armrocio->setMaxSpeed(6.f); armrocio->setPose(RoboCompArmrocio::hola1); } catch (Ice::Exception e ) { qDebug()<<"Error talking to Arm"<<e.what(); } t.start(); while(t.elapsed()<4000) { if(!armrocio->isMoving()) { break; } QApplication::processEvents(); usleep(1000); } if(count == 1) { try { QString s (QString::fromUtf8("<prosody range=\"x-high\"> ¡Hola!.</prosody> <emphasis level=\"strong\">Es un placer verte.</emphasis>" )); speech->say( s.toStdString(),true); } catch (Ice::Exception e) { qDebug()<<"Error talking to ArmRocio: "<<e.what(); } } try { armrocio->setPose(RoboCompArmrocio::hola2); } catch (Ice::Exception e ) { qDebug()<<"Error talking to Arm"<<e.what(); } t.restart(); while(t.elapsed()<4000) { if(!armrocio->isMoving()) { break; } QApplication::processEvents(); usleep(1000); } } try { armrocio->setPose(RoboCompArmrocio::reposo); armrocio->setMaxSpeed(2.5); } catch (Ice::Exception e ) { qDebug()<<"Error talking to Arm"<<e.what(); } }
void MainWindow::code() { QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::information(this,"Error","Can't open the file!"); return; } QTextStream in(&file); QStringList text; int i=0; while(!in.atEnd()) { if(i==1) text.append(in.readLine()); else in.readLine(); i++; if(i==4) i=0; } //qDebug()<<text; file.close(); HashTable *hashTable = new HashTable; unsigned int FirPrefix[1048576]; unsigned int count=0; for(i=0;i<text.length();i++) { for(int j=0;j<65;j++) { hashTable->addTable(text[i].mid(j,24)); } } /*for(i=0;i<1048576;i++) { hashTable->locate(i); if(hashTable->getFreInRead()!=0) { FirPrefix[count]=i; count++; } } unsigned int countFreInRead[9]; for(i=0;i<9;i++) countFreInRead[i]=0; for(unsigned int i=0;i<count;i++) { hashTable->locate(FirPrefix[i]); unsigned short freInRead=hashTable->getFreInRead(); //qDebug()<<freInRead<<endl; for(int j=10;j<=90;j+=10) { if(freInRead<=j&&(freInRead>j-10)) { countFreInRead[j/10-1]++; //qDebug()<<"countFreInRead["<<j/10-1<<"]="<<countFreInRead[j/10-1]; } } } for(i=0;i<9;i++) { qDebug()<<i*10<<"~"<<(i+1)*10<<" "<<countFreInRead[i]<<endl; } //研究发现,fre 值在 1~30 之间分布较集中*/ /*qDebug()<<"--------------------------"<<endl; hashTable->locate(955561); hashTable->getFirPrefix();*/ for(i=0;i<1048576;i++) { hashTable->locate(i); if(hashTable->getFreInRead()<=30&&hashTable->getFreInRead()>20) { FirPrefix[count]=i; //qDebug()<<FirPrefix[count]<<endl; count++; } } qDebug()<<"--------------------------------"; QTime t; t.start(); QStringList contigList; for(unsigned int i=0;i<count;i++) { //qDebug()<<"for"<<endl; hashTable->locate(FirPrefix[i]); //qDebug()<<FirPrefix[i]<<endl; if(hashTable->getFreInContig()==1) continue; QString contig; contig+=hashTable->getFirPrefix(); contig+=hashTable->getSecPrefix(); while(hashTable->getFreInRead()!=0&&hashTable->getFreInContig()!=1) { //qDebug()<<"while"<<endl; hashTable->setFreInContig(); contig+=hashTable->getPostfix(); //qDebug()<<contig<<endl; unsigned int next = hashTable->hash(contig.mid(contig.length()-20,10)); //qDebug()<<next<<endl; hashTable->locate(next); } contigList.append(contig); } int time = t.elapsed(); QString outputFileName(fileName); outputFileName+=".assembly"; QFile outputFile(outputFileName); if (!outputFile.open(QIODevice::WriteOnly | QIODevice::Text)) { QMessageBox::information(this,"Error","Can't create the assembly file!"); return; } QTextStream out(&outputFile); unsigned int totalLength=0; unsigned int maximalLength=0; unsigned int length[contigList.length()]; unsigned int medianLength; unsigned int N50Length; for(unsigned int i=0;i<contigList.length();i++) { out<<contigList[i]<<endl; totalLength+=contigList[i].length(); length[i]=contigList[i].length(); if(contigList[i].length()>maximalLength) maximalLength=contigList[i].length(); } unsigned int meanLength = totalLength/contigList.length(); std::sort(length,length+contigList.length()); for(unsigned int i=0;i<contigList.length();i++) //qDebug()<<length[i]<<endl; if(contigList.length()%2==0) medianLength = (length[contigList.length()/2]+length[contigList.length()/2-1])/2; else medianLength = length[contigList.length()/2]; unsigned int sum=0; //qDebug()<<length[contigList.length()-1]; for(unsigned int i=contigList.length()-1;i>=0;i--) { //qDebug()<<"for"; sum=length[i]+sum; //qDebug()<<i; if(sum>=totalLength/2) { N50Length = length[i]; break; } } rowCount++; table->setRowCount(rowCount); table->setItem(table->rowCount()-1,0,new QTableWidgetItem(QString::number(rowCount))); table->setItem(table->rowCount()-1,1,new QTableWidgetItem(QString::number(contigList.length()))); table->setItem(table->rowCount()-1,2,new QTableWidgetItem(QString::number(totalLength))); table->setItem(table->rowCount()-1,3,new QTableWidgetItem(QString::number(maximalLength))); table->setItem(table->rowCount()-1,4,new QTableWidgetItem(QString::number(N50Length))); table->setItem(table->rowCount()-1,5,new QTableWidgetItem(QString::number(meanLength))); table->setItem(table->rowCount()-1,6,new QTableWidgetItem(QString::number(medianLength))); table->setItem(table->rowCount()-1,7,new QTableWidgetItem(QString::number(time))); QString dir("ID "); dir+=QString::number(rowCount); dir+=" finished assembling "; dir+="<a href = "; dir += outputFileName; dir += ">"; dir += outputFileName; dir +="</a>"; QLabel *fileDir = new QLabel(dir); connect(fileDir,SIGNAL(linkActivated(QString)),this,SLOT(openCodeFile(QString))); mainLayout->addWidget(fileDir); QMessageBox::information(this,"Success","Assemble success!"); }
void CameraDolly::moveToPoly(vtkPolyData & polyData, vtkIdType index, IndexType indexType, bool overTime) { if (!m_renderer) { return; } double selectionPoint[3], selectionNormal[3]; if (indexType == IndexType::cells) { vtkCell * cell = polyData.GetCell(index); assert(cell); if (!cell) { qWarning() << "[CameraDolly] Cell not found in data set: " + QString::number(index); return; } auto cellPointIds = vtkSmartPointer<vtkIdTypeArray>::New(); cellPointIds->SetArray(cell->GetPointIds()->GetPointer(0), cell->GetNumberOfPoints(), true); vtkPolygon::ComputeCentroid(cellPointIds, polyData.GetPoints(), selectionPoint); vtkPolygon::ComputeNormal(cell->GetPoints(), selectionNormal); } else { polyData.GetPoint(index, selectionPoint); auto normals = polyData.GetPointData()->GetNormals(); if (!normals) { qWarning() << "[CameraDolly] No point normals found in poly data set"; return; } normals->GetTuple(index, selectionNormal); } vtkCamera & camera = *m_renderer->GetActiveCamera(); double objectCenter[3]; polyData.GetCenter(objectCenter); double startingFocalPoint[3], targetFocalPoint[3]; double startingAzimuth, targetAzimuth; double startingElevation, targetElevation; camera.GetFocalPoint(startingFocalPoint); for (size_t i = 0; i < 3; ++i) // look at center of the object { targetFocalPoint[i] = objectCenter[i]; } startingAzimuth = TerrainCamera::getAzimuth(camera); startingElevation = TerrainCamera::getVerticalElevation(camera); // compute target camera position to find azimuth and elevation for the transition double startingPosition[3]; camera.GetPosition(startingPosition); double targetPositionXY[2]; double objectToEye[3]; vtkMath::Subtract(startingPosition, objectCenter, objectToEye); double viewDistanceXY = vtkMath::Normalize2D(objectToEye); double selectionCenterXY[2] = { selectionPoint[0], selectionPoint[1] }; double norm_objectToSelectionXY[2]; norm_objectToSelectionXY[0] = selectionCenterXY[0] - objectCenter[0]; norm_objectToSelectionXY[1] = selectionCenterXY[1] - objectCenter[1]; double selectionRadiusXY = vtkMath::Normalize2D(norm_objectToSelectionXY); // make sure to move outside of the selection if (viewDistanceXY < selectionRadiusXY) { viewDistanceXY = selectionRadiusXY * 1.5; } // choose nearest viewpoint for flat surfaces const double flat_threshold = 30; double inclination = std::acos(selectionNormal[2]) * 180.0 / vtkMath::Pi(); if (inclination < flat_threshold) { targetPositionXY[0] = objectCenter[0] + viewDistanceXY * norm_objectToSelectionXY[0]; targetPositionXY[1] = objectCenter[1] + viewDistanceXY * norm_objectToSelectionXY[1]; } // or use the hill's normal else { double selectionNormalXY[2] = { selectionNormal[0], selectionNormal[1] }; double l; if ((l = std::sqrt((selectionNormalXY[0] * selectionNormalXY[0] + selectionNormalXY[1] * selectionNormalXY[1]))) != 0.0) { selectionNormalXY[0] /= l; selectionNormalXY[1] /= l; } // get a point in front of the selected cell double selectionFrontXY[2] = { selectionCenterXY[0] + selectionNormalXY[0], selectionCenterXY[1] + selectionNormalXY[1] }; double intersections[4]; // our focal point (center of view circle) is the object center // so assume a circle center of (0,0) in the calculations bool intersects = circleLineIntersection(viewDistanceXY, selectionCenterXY, selectionFrontXY, &intersections[0], &intersections[2]); // ignore for now if (!intersects) { targetPositionXY[0] = startingPosition[0]; targetPositionXY[1] = startingPosition[1]; } else { bool towardsPositive = selectionFrontXY[0] > selectionCenterXY[0] || (selectionFrontXY[0] == selectionCenterXY[0] && selectionFrontXY[1] >= selectionCenterXY[1]); int intersectionIndex; if (towardsPositive == (intersections[0] > intersections[2] || (intersections[0] == intersections[2] && intersections[1] >= intersections[3]))) { intersectionIndex = 0; } else { intersectionIndex = 2; } targetPositionXY[0] = intersections[intersectionIndex]; targetPositionXY[1] = intersections[intersectionIndex + 1]; } } auto targetCamera = vtkSmartPointer<vtkCamera>::New(); targetCamera->SetPosition(targetPositionXY[0], targetPositionXY[1], startingPosition[2]); targetCamera->SetFocalPoint(targetFocalPoint); targetCamera->SetViewUp(camera.GetViewUp()); targetAzimuth = TerrainCamera::getAzimuth(*targetCamera); targetElevation = TerrainCamera::getVerticalElevation(*targetCamera); if (overTime) { const double flyTimeSec = 0.5; const int flyDeadlineMSec = 1000; const int NumberOfFlyFrames = 15; double stepFactor = 1.0 / (NumberOfFlyFrames + 1); // transition of position, focal point, azimuth and elevation double stepFocalPoint[3], stepPosition[3], stepAzimuth, stepElevation; vtkMath::Subtract(targetFocalPoint, startingFocalPoint, stepFocalPoint); vtkMath::MultiplyScalar(stepFocalPoint, stepFactor); vtkMath::Subtract(targetCamera->GetPosition(), startingPosition, stepPosition); vtkMath::MultiplyScalar(stepPosition, stepFactor); stepAzimuth = (targetAzimuth - startingAzimuth) * stepFactor; stepElevation = (targetElevation - startingElevation) * stepFactor; double intermediateFocal[3]{ startingFocalPoint[0], startingFocalPoint[1], startingFocalPoint[2] }; double intermediatePosition[3]{ startingPosition[0], startingPosition[1], startingPosition[2] }; double intermediateAzimuth = startingAzimuth; double intermediateElevation = startingElevation; QTime startingTime = QTime::currentTime(); QTime deadline = startingTime.addMSecs(flyDeadlineMSec); long sleepMSec = long(flyTimeSec * 1000.0 * stepFactor); QTime renderTime; int i = 0; for (; i < NumberOfFlyFrames; ++i) { renderTime.start(); vtkMath::Add(intermediateFocal, stepFocalPoint, intermediateFocal); vtkMath::Add(intermediatePosition, stepPosition, intermediatePosition); intermediateAzimuth += stepAzimuth; intermediateElevation += stepElevation; camera.SetFocalPoint(intermediateFocal); camera.SetPosition(intermediatePosition); TerrainCamera::setAzimuth(camera, intermediateAzimuth); TerrainCamera::setVerticalElevation(camera, intermediateElevation); m_renderer->ResetCameraClippingRange(); m_renderer->GetRenderWindow()->InvokeEvent(vtkCommandExt::ForceRepaintEvent); if (QTime::currentTime() > deadline) { break; } QThread::msleep((unsigned long)std::max(0l, sleepMSec - renderTime.elapsed())); } } // in any case, jump to target position camera.SetFocalPoint(targetFocalPoint); camera.SetPosition(targetCamera->GetPosition()); TerrainCamera::setAzimuth(camera, targetAzimuth); TerrainCamera::setVerticalElevation(camera, targetElevation); m_renderer->ResetCameraClippingRange(); m_renderer->GetRenderWindow()->Render(); }
void MythSocketThread::run(void) { RunProlog(); LOG(VB_SOCKET, LOG_DEBUG, LOC + "readyread thread start"); QMutexLocker locker(&m_readyread_lock); m_readyread_started_wait.wakeAll(); while (m_readyread_run) { LOG(VB_SOCKET, LOG_DEBUG, LOC + "ProcessAddRemoveQueues"); ProcessAddRemoveQueues(); LOG(VB_SOCKET, LOG_DEBUG, LOC + "Construct FD_SET"); // construct FD_SET for all connected and unlocked sockets... int maxfd = -1; fd_set rfds; FD_ZERO(&rfds); QList<MythSocket*>::const_iterator it = m_readyread_list.begin(); for (; it != m_readyread_list.end(); ++it) { if (!(*it)->TryLock(false)) continue; if ((*it)->state() == MythSocket::Connected && !(*it)->m_notifyread) { FD_SET((*it)->socket(), &rfds); maxfd = std::max((*it)->socket(), maxfd); } (*it)->Unlock(false); } // There are no unlocked sockets, wait for event before we continue.. if (maxfd < 0) { LOG(VB_SOCKET, LOG_DEBUG, LOC + "Empty FD_SET, sleeping"); if (m_readyread_wait.wait(&m_readyread_lock)) LOG(VB_SOCKET, LOG_DEBUG, LOC + "Empty FD_SET, woken up"); else LOG(VB_SOCKET, LOG_DEBUG, LOC + "Empty FD_SET, timed out"); continue; } int rval = 0; if (m_readyread_pipe[0] >= 0) { // Clear out any pending pipe reads, we have already taken care of // this event above under the m_readyread_lock. char dummy[128]; if (m_readyread_pipe_flags[0] & O_NONBLOCK) { rval = ::read(m_readyread_pipe[0], dummy, 128); FD_SET(m_readyread_pipe[0], &rfds); maxfd = std::max(m_readyread_pipe[0], maxfd); } // also exit select on exceptions on same descriptors fd_set efds; memcpy(&efds, &rfds, sizeof(fd_set)); // The select waits forever for data, so if we need to process // anything else we need to write to m_readyread_pipe[1].. // We unlock the ready read lock, because we don't need it // and this will allow WakeReadyReadThread() to run.. m_readyread_lock.unlock(); LOG(VB_SOCKET, LOG_DEBUG, LOC + "Waiting on select.."); rval = select(maxfd + 1, &rfds, NULL, &efds, NULL); LOG(VB_SOCKET, LOG_DEBUG, LOC + "Got data on select"); m_readyread_lock.lock(); if (rval > 0 && FD_ISSET(m_readyread_pipe[0], &rfds)) { int ret = ::read(m_readyread_pipe[0], dummy, 128); if (ret < 0) { LOG(VB_SOCKET, LOG_ERR, LOC + "Strange.. failed to read event pipe"); } } } else { LOG(VB_SOCKET, LOG_DEBUG, LOC + "Waiting on select.. (no pipe)"); // also exit select on exceptions on same descriptors fd_set efds; memcpy(&efds, &rfds, sizeof(fd_set)); // Unfortunately, select on a pipe is not supported on all // platforms. So we fallback to a loop that instead times out // of select and checks for wakeAll event. while (!rval) { struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = kShortWait * 1000; rval = select(maxfd + 1, &rfds, NULL, &efds, &timeout); if (!rval) m_readyread_wait.wait(&m_readyread_lock, kShortWait); } LOG(VB_SOCKET, LOG_DEBUG, LOC + "Got data on select (no pipe)"); } if (rval <= 0) { if (rval == 0) { // Note: This should never occur when using pipes. When there // is no error there should be data in at least one fd.. LOG(VB_SOCKET, LOG_DEBUG, LOC + "select timeout"); } else LOG(VB_SOCKET, LOG_ERR, LOC + "select returned error" + ENO); m_readyread_wait.wait(&m_readyread_lock, kShortWait); continue; } // ReadyToBeRead allows calls back into the socket so we need // to release the lock for a little while. // since only this loop updates m_readyread_list this is safe. m_readyread_lock.unlock(); // Actually read some data! This is a form of co-operative // multitasking so the ready read handlers should be quick.. uint downref_tm = 0; if (!m_readyread_downref_list.empty()) { LOG(VB_SOCKET, LOG_DEBUG, LOC + "Deleting stale sockets"); QTime tm = QTime::currentTime(); for (it = m_readyread_downref_list.begin(); it != m_readyread_downref_list.end(); ++it) { (*it)->DownRef(); } m_readyread_downref_list.clear(); downref_tm = tm.elapsed(); } LOG(VB_SOCKET, LOG_DEBUG, LOC + "Processing ready reads"); QMap<uint,uint> timers; QTime tm = QTime::currentTime(); it = m_readyread_list.begin(); for (; it != m_readyread_list.end() && m_readyread_run; ++it) { if (!(*it)->TryLock(false)) continue; int socket = (*it)->socket(); if (socket >= 0 && (*it)->state() == MythSocket::Connected && FD_ISSET(socket, &rfds)) { QTime rrtm = QTime::currentTime(); ReadyToBeRead(*it); timers[socket] = rrtm.elapsed(); } (*it)->Unlock(false); } if (VERBOSE_LEVEL_CHECK(VB_SOCKET, LOG_DEBUG)) { QString rep = QString("Total read time: %1ms, on sockets") .arg(tm.elapsed()); QMap<uint,uint>::const_iterator it = timers.begin(); for (; it != timers.end(); ++it) rep += QString(" {%1,%2ms}").arg(it.key()).arg(*it); if (downref_tm) rep += QString(" {downref, %1ms}").arg(downref_tm); LOG(VB_SOCKET, LOG_DEBUG, LOC + rep); } m_readyread_lock.lock(); LOG(VB_SOCKET, LOG_DEBUG, LOC + "Reacquired ready read lock"); } LOG(VB_SOCKET, LOG_DEBUG, LOC + "readyread thread exit"); RunEpilog(); }
//----------------------------------------------------------------------------- void KMAcctMaildir::processNewMail(bool) { QTime t; hasNewMail = false; if ( precommand().isEmpty() ) { QFileInfo fi( location() ); if ( !fi.exists() ) { checkDone( hasNewMail, CheckOK ); BroadcastStatus::instance()->setStatusMsgTransmissionCompleted( mName, 0 ); return; } } KMFolder mailFolder(0, location(), KMFolderTypeMaildir, false /* no index */, false /* don't export sernums */); long num = 0; int rc; KMMessage* msg; bool addedOk; if (!mFolder) { checkDone( hasNewMail, CheckError ); BroadcastStatus::instance()->setStatusMsg( i18n( "Transmission failed." )); return; } BroadcastStatus::instance()->setStatusMsg( i18n("Preparing transmission from \"%1\"...", mName)); Q_ASSERT( !mMailCheckProgressItem ); mMailCheckProgressItem = KPIM::ProgressManager::createProgressItem( "MailCheck" + mName, mName, i18n("Preparing transmission from \"%1\"...", mName), false, // cannot be canceled false ); // no tls/ssl // run the precommand if (!runPrecommand(precommand())) { kDebug() << "cannot run precommand" << precommand(); checkDone( hasNewMail, CheckError ); BroadcastStatus::instance()->setStatusMsg( i18n( "Transmission failed." )); return; } rc = mailFolder.open( "acctmaildirMail" ); if (rc) { QString aStr = i18n("<qt>Cannot open folder <b>%1</b>.</qt>", mailFolder.location() ); KMessageBox::sorry(0, aStr); kDebug() << "cannot open folder" << mailFolder.location(); checkDone( hasNewMail, CheckError ); BroadcastStatus::instance()->setStatusMsg( i18n( "Transmission failed." )); return; } mFolder->open( "acctmaildirFold" ); num = mailFolder.count(); addedOk = true; t.start(); mMailCheckProgressItem->setTotalItems( num ); for (long i=0; i<num; i++) { if( kmkernel->mailCheckAborted() ) { BroadcastStatus::instance()->setStatusMsg( i18n("Transmission aborted.") ); num = i; addedOk = false; } if (!addedOk) break; QString statusMsg = i18n( "Moving message %1 of %2 from %3.", i, num, mailFolder.location() ); mMailCheckProgressItem->incCompletedItems(); mMailCheckProgressItem->updateProgress(); mMailCheckProgressItem->setStatus( statusMsg ); msg = mailFolder.take(0); if (msg) { msg->setStatus(msg->headerField("Status").toLatin1(), msg->headerField("X-Status").toLatin1()); if ( !msg->headerField( "X-KMail-EncryptionState" ).isEmpty() ) msg->setEncryptionStateChar( msg->headerField( "X-KMail-EncryptionState" ).at(0) ); if ( !msg->headerField( "X-KMail-SignatureState" ).isEmpty() ) msg->setSignatureStateChar( msg->headerField( "X-KMail-SignatureState" ).at(0)); addedOk = processNewMsg(msg); if (addedOk) hasNewMail = true; } if (t.elapsed() >= 200) { //hardwired constant qApp->processEvents(); t.start(); } } if( mMailCheckProgressItem ) { // do this only once... BroadcastStatus::instance()->setStatusMsgTransmissionCompleted( num ); mMailCheckProgressItem->setStatus( i18np( "Fetched 1 message from maildir folder %2.", "Fetched %1 messages from maildir folder %2.", num, mailFolder.location() ) ); mMailCheckProgressItem->setComplete(); mMailCheckProgressItem = 0; } if (addedOk) { BroadcastStatus::instance()->setStatusMsgTransmissionCompleted( mName, num ); } // else warning is written already mailFolder.close( "acctmaildirMail" ); mFolder->close( "acctmaildirFold" ); checkDone( hasNewMail, CheckOK ); return; }
//............................................................................ QSTimeCtr QS::onGetTime(void) { return (QSTimeCtr)l_time.elapsed(); }
bool QgsRenderChecker::runTest( QString theTestName, unsigned int theMismatchCount ) { if ( mExpectedImageFile.isEmpty() ) { qDebug( "QgsRenderChecker::runTest failed - Expected Image File not set." ); mReport = "<table>" "<tr><td>Test Result:</td><td>Expected Result:</td></tr>\n" "<tr><td>Nothing rendered</td>\n<td>Failed because Expected " "Image File not set.</td></tr></table>\n"; return false; } // // Load the expected result pixmap // QImage myExpectedImage( mExpectedImageFile ); mMatchTarget = myExpectedImage.width() * myExpectedImage.height(); // // Now render our layers onto a pixmap // mMapSettings.setBackgroundColor( qRgb( 152, 219, 249 ) ); mMapSettings.setFlag( QgsMapSettings::Antialiasing ); mMapSettings.setOutputSize( QSize( myExpectedImage.width(), myExpectedImage.height() ) ); QTime myTime; myTime.start(); QgsMapRendererSequentialJob job( mMapSettings ); job.start(); job.waitForFinished(); mElapsedTime = myTime.elapsed(); QImage myImage = job.renderedImage(); // // Save the pixmap to disk so the user can make a // visual assessment if needed // mRenderedImageFile = QDir::tempPath() + QDir::separator() + theTestName + "_result.png"; myImage.setDotsPerMeterX( myExpectedImage.dotsPerMeterX() ); myImage.setDotsPerMeterY( myExpectedImage.dotsPerMeterY() ); myImage.save( mRenderedImageFile, "PNG", 100 ); //create a world file to go with the image... QFile wldFile( QDir::tempPath() + QDir::separator() + theTestName + "_result.wld" ); if ( wldFile.open( QIODevice::WriteOnly ) ) { QgsRectangle r = mMapSettings.extent(); QTextStream stream( &wldFile ); stream << QString( "%1\r\n0 \r\n0 \r\n%2\r\n%3\r\n%4\r\n" ) .arg( qgsDoubleToString( mMapSettings.mapUnitsPerPixel() ) ) .arg( qgsDoubleToString( -mMapSettings.mapUnitsPerPixel() ) ) .arg( qgsDoubleToString( r.xMinimum() + mMapSettings.mapUnitsPerPixel() / 2.0 ) ) .arg( qgsDoubleToString( r.yMaximum() - mMapSettings.mapUnitsPerPixel() / 2.0 ) ); } return compareImages( theTestName, theMismatchCount ); }
void beamtest::readbinarywithcolor() { QTime time; time.start(); Handle_AIS_InteractiveContext ic = ui::getInstance()->getWindowContext(); QString filename = QFileDialog::getOpenFileName ( this, tr("Import File"),""); QFile file(filename); file.open(QIODevice::ReadOnly); QDataStream in(&file); // read the data serialized from the file //double pcount; //in >> pcount ; // extract "the answer is" and 42 //QProgressDialog progress("loading cloudpoint", "Abort Copy", 1,100); //QList<Graphic3d_Vertex> vertlist; QList<gp_Pnt> vertlist; //for (int i=0;i < pcount;i++) //{ double x ; double y ; double z ; double intensity; int i=0; do { i++; in >> x >> y >> z >> intensity; if (i % 100000 == 0) qDebug() << i; //Graphic3d_Vertex thevert(x,y,z); gp_Pnt thevert(x,y,z); vertlist.append(thevert); // Quantity_Color rgbval(intensity,0,0,Quantity_TOC_RGB); // colorlist.append(rgbval); //if (i > 30000000) break; } while ( in.status() ==QDataStream::Ok ); file.close(); Handle(AIS_PointCloud) mypc1 = new AIS_PointCloud(vertlist); ic->Display(mypc1); double milliseconds = time.elapsed(); double seconds = (milliseconds/1000); double minutes = seconds/60; double hours = minutes/60; QString timetxt; QTextStream linestream(&timetxt); linestream << "h" << hours << ":m " << minutes << ":s " << seconds << ".ms" << milliseconds; ui::getInstance()->Statusbar(timetxt); qDebug() << "time ellapsed:" << timetxt; }
int OpenAipPoiLoader::load( QList<Airfield>& airfieldList ) { // Set a global lock during execution to avoid calls in parallel. QMutexLocker locker( &m_mutexAf ); QTime t; t.start(); int loadCounter = 0; // number of successfully loaded files QString mapDir = MapContents::instance()->getMapRootDirectory() + "/points"; QStringList preselect; // Setup a filter for the desired file extensions. QString filter = "*_wpt.aip"; MapContents::addDir( preselect, mapDir, filter ); if( preselect.count() == 0 ) { qWarning( "OAIP: No airfield files found in the map directory!" ); return loadCounter; } // Check, which files shall be loaded. QStringList files = _settings.value( "/Points/FileList", QStringList(QString("All"))).toStringList(); if( files.isEmpty() ) { // No files shall be loaded qWarning() << "OAIP: No airfield files defined for loading by the user!"; return loadCounter; } if( files.first() != "All" ) { // Tidy up the preselection list, if not all found files shall be loaded. for( int i = preselect.size() - 1; i >= 0; i-- ) { QString file = QFileInfo(preselect.at(i)).fileName(); if( files.contains( file ) == false ) { preselect.removeAt(i); } } } while( ! preselect.isEmpty() ) { QString srcName; OpenAip openAip; QString errorInfo; srcName = preselect.first(); // Remove source file to be read from the list. preselect.removeAt(0); bool ok = openAip.readAirfields( srcName, airfieldList, errorInfo, true ); if( ok ) { loadCounter++; } } qDebug( "OAIP: %d airfield file(s) with %d items loaded in %dms", loadCounter, airfieldList.size(), t.elapsed() ); return loadCounter; }
void beamtest::readfile() { QTime time; time.start(); Handle_AIS_InteractiveContext ic = ui::getInstance()->getWindowContext(); double chunk = 30000000; double chunkcount = 3; //double maxpoints = chunkcount * chunk; double maxpoints = chunk-1; Graphic3d_Array1OfVertex* thepointcloud1 = new Graphic3d_Array1OfVertex(1,chunk); //Graphic3d_Array1OfVertex thepointcloud2(1,chunk); //Graphic3d_Array1OfVertex thepointcloud3(1,chunk); QString filename = QFileDialog::getOpenFileName ( this, tr("Import File"),"", tr( "All point cloud formats (*.ptx);;" "XYZ (*.xyz *XYZ);;" "PTX (*.ptx *.PTX)")); QFile file(filename); if (!file.open(QFile::ReadOnly)) return ; QMap<QString,gp_Pnt> pointmap; QProgressDialog progress("loading cloudpoint", "Abort Copy", 1,100); int count = 0; int filepos = 0; QTextStream stream(&file ); QString line; do { filepos++; //qDebug() << "file-linepos:" << filepos; line = stream.readLine(); QStringList linelist = line.split(tr(" ")); if (linelist.size() == 4) { double x = linelist.at(0).toDouble(); double y = linelist.at(1).toDouble(); double z = linelist.at(2).toDouble(); QString index = linelist.at(0) + linelist.at(1) + linelist.at(2) ; if(!pointmap.contains(index)) { count++; if (count % 100000 == 0){ progress.setValue((count *100/maxpoints)); } // double intensity = linelist.at(3).toDouble(); gp_Pnt p1(x,y,z); //TopoDS_Shape point =hsf::AddNewPoint(p1); //vis(point) Graphic3d_Vertex thevert(x,y,z); thepointcloud1->SetValue(count,thevert); /* if (count < chunk && count > 0) { thepointcloud1.SetValue(count,thevert); } else if (count > chunk && count <= (2*chunk)) { thepointcloud2.SetValue(count-chunk,thevert); } else if (count > (2*chunk) && count < (3 * chunk)) { thepointcloud3.SetValue(count-(chunk*2),thevert); }*/ pointmap.insert(index,p1); } } if (count > maxpoints) break; } while (!line.isNull()); //Handle(AIS_PointCloud) mypc1 = new AIS_PointCloud(*thepointcloud1); //ic->Display(mypc1); // //Handle(AIS_PointCloud) mypc2 = new AIS_PointCloud(thepointcloud2); //ic->Display(mypc2); // // //Handle(AIS_PointCloud) mypc3 = new AIS_PointCloud(thepointcloud3); //ic->Display(mypc3); //ENDPART double milliseconds = time.elapsed(); double seconds = (milliseconds/1000); double minutes = seconds/60; double hours = minutes/60; QString timetxt; QTextStream linestream(&timetxt); linestream << "h" << hours << ":m " << minutes << ":s " << seconds << ".ms" << milliseconds; ui::getInstance()->Statusbar(timetxt); qDebug() << "time ellapsed:" << timetxt; }
int main(int argc, char *argv[]) { // #ifdef QT_DEBUG // debugStreamFile.open(QFile::WriteOnly | QFile::Truncate); // #endif //FIXME qInstallMsgHandler( debugOutput ); spDebugConsole = 0; Q_INIT_RESOURCE(mudlet_alpha); QApplication app(argc, argv); app.setOrganizationName("Mudlet"); app.setApplicationName("Mudlet"); app.setApplicationVersion(APP_VERSION); QPixmap pixmap(":/Mudlet_splashscreen_main.png"); QSplashScreen splash(pixmap); QString startupMessage; if( QByteArray( APP_BUILD ).isEmpty() ) startupMessage = QString("Mudlet\n(Release version: ") % APP_VERSION % QString(")\n\n"); else startupMessage = QString("Mudlet\n(Development version: ") % APP_VERSION % APP_BUILD % QString(")\n\n"); // Following is suggested by GPL documentation startupMessage.append("Copyright " % QChar(169) % "2014 Heiko K" % QChar(246) % "hn\n\n"); startupMessage.append("Mudlet comes with\nABSOLUTELY NO WARRANTY\n\n"); startupMessage.append("This is free software, and you are welcome to\n"); startupMessage.append("redistribute it under certain conditions;\nselect the 'About' item for details.\n\nLoading profiles..."); splash.show(); splash.showMessage(startupMessage, Qt::AlignHCenter); app.processEvents(); //qt_ntfs_permission_lookup++; // turn permission checking on on NTFS file systems QTime t; t.start(); while( t.elapsed() < 1000 ) ; // Do nothing here for a second QString directory = QDir::homePath()+"/.config/mudlet"; QDir dir; if( ! dir.exists( directory ) ) { dir.mkpath( directory ); } // QFile file_doc(":/mudlet_documentation.html"); // QFile file_doc_old; // file_doc_old.setFileName( directory+"/mudlet_documentation.html" ); // if( file_doc_old.exists() ) // { //NOTE: B. von Roeder found out that the removal of old versions may *sometimes* fail on windows 7 due permission issues // if( ! file_doc_old.setPermissions( QFile::WriteOwner | QFile::ReadOwner | QFile::ReadUser | QFile::WriteUser | QFile::ReadOther | QFile::WriteOther ) ) // { // cout << "[ERROR] could not set file permissions of the old version of the manual" << endl; // gSysErrors << "[ERROR] could not set file permissions of the old version of the manual"; // } // string old_man_path = directory.toLatin1().data(); // old_man_path += "/mudlet_documentation.html"; // bool ok=file_doc_old.remove(); // if( ok ) // { // cout << "[INFO] deleted old version of the manual: " << old_man_path << endl; // } // else // { // cout << "[ERROR] could not remove old version of the manual: " << old_man_path << endl; // QString _m = "[ERROR] could not remove old version of the manual: "; // _m.append( old_man_path.c_str() ); // gSysErrors << _m; // } // } // else // { // gSysErrors << "[INFO] no old version of the manual found"; // } // if( file_doc.copy( directory+"/mudlet_documentation.html" ) ) // { // cout << "[OK] successfully copied new version of the manual" << endl; // QString _m = "[INFO] local manual: "; // _m.append( directory ); // gSysErrors << _m; // } // else // { // cout << "[ERROR] copy of new version of the manual failed" << endl; // gSysErrors << "[ERROR] copy of new version of the manual failed"; // } // QFile file_lua(":/LuaGlobal.lua"); // QFile file_lua_old( directory+"/LuaGlobal.lua" ); // if( ! file_lua_old.setPermissions( QFile::WriteOwner | QFile::ReadOwner | QFile::ReadUser | QFile::WriteUser | QFile::ReadOther | QFile::WriteOther ) ) // { // cout << "[ERROR] failed to set file permissions for the old version of LuaGlobal.lua" << endl; // gSysErrors << "[ERROR] failed to set file permissions for the old version of LuaGlobal.lua"; // } // else // { // cout << "[OK] successfully set file permissions for the old version of LuaGlobal.lua" << endl; // } // if( file_lua_old.remove() ) // { // cout << "[OK] old LuaGlobal.lua removed successfully" << endl; // gSysErrors << "[INFO] old LuaGlobal.lua removed successfully"; // } // else // { // cout << "[ERROR] failed to remove the old version of LuaGlobal.lua" << endl; // gSysErrors << "[ERROR] failed to remove the old version of LuaGlobal.lua"; // } // if( file_lua.copy( directory+"/LuaGlobal.lua" ) ) // { // cout << "[OK] new version of LuaGlobal.lua copied successfully" << endl; // gSysErrors << "[INFO] LuaGlobal.lua restored successfully"; // QFile file_lua_new(directory+"/LuaGlobal.lua"); // if( ! file_lua_new.setPermissions( QFile::WriteOwner | QFile::ReadOwner | QFile::ReadUser | QFile::WriteUser | QFile::ReadOther | QFile::WriteOther ) ) // { // cout << "[ERROR] failed to set file permissions for the new version of LuaGlobal.lua" << endl; // gSysErrors << "[ERROR] failed to set file permissions for the new version of LuaGlobal.lua"; // } // else // { // cout << "[OK] successfully set file permissions for the new version of LuaGlobal.lua" << endl; // } // } // QFile file_db(":/db.lua"); // QFile file_db_old( directory+"/db.lua" ); // if( ! file_db_old.setPermissions( QFile::WriteOwner | QFile::ReadOwner | QFile::ReadUser | QFile::WriteUser | QFile::ReadOther | QFile::WriteOther ) ) // { // cout << "[ERROR] failed to set file permissions for the old version of db.lua" << endl; // gSysErrors << "[ERROR] failed to set file permissions for the old version of db.lua"; // } // else // { // cout << "[OK] successfully set file permissions for the old version of db.lua" << endl; // } // if( file_db_old.remove() ) // { // cout << "[OK] old db.lua removed successfully" << endl; // gSysErrors << "[INFO] old db.lua removed successfully"; // } // else // { // cout << "[ERROR] failed to remove the old version of db.lua" << endl; // gSysErrors << "[ERROR] failed to remove the old version of db.lua"; // } // if( file_db.copy( directory+"/db.lua" ) ) // { // cout << "[OK] new version of db.lua copied successfully" << endl; // gSysErrors << "[INFO] db.lua restored successfully"; // QFile file_db_new(directory+"/db.lua"); // if( ! file_db_new.setPermissions( QFile::WriteOwner | QFile::ReadOwner | QFile::ReadUser | QFile::WriteUser | QFile::ReadOther | QFile::WriteOther ) ) // { // cout << "[ERROR] failed to set file permissions for the new version of db.lua" << endl; // gSysErrors << "[ERROR] failed to set file permissions for the new version of db.lua"; // } // else // { // cout << "[OK] successfully set file permissions for the new version of db.lua" << endl; // } // } startupMessage.append(" Done.\nLoading font files..."); splash.showMessage(startupMessage, Qt::AlignHCenter); app.processEvents(); t.restart(); while( t.elapsed() < 1000 ) ; // Do nothing here for a second QFile file_f1(":/fonts/ttf-bitstream-vera-1.10/COPYRIGHT.TXT"); file_f1.copy( directory+"/COPYRIGHT.TXT" ); QFile file_f2(":/fonts/ttf-bitstream-vera-1.10/RELEASENOTES.TXT"); file_f2.copy( directory+"/RELEASENOTES.TXT" ); QFile file_f3(":/fonts/ttf-bitstream-vera-1.10/VeraMoIt.ttf"); file_f3.copy( directory+"/VeraMoIt.ttf" ); QFile file_f4(":/fonts/ttf-bitstream-vera-1.10/local.conf"); file_f4.copy( directory+"/local.conf" ); QFile file_f5(":/fonts/ttf-bitstream-vera-1.10/VeraMoBd.ttf"); file_f5.copy( directory+"/VeraMoBd.ttf" ); QFile file_f6(":/fonts/ttf-bitstream-vera-1.10/VeraMoBd.ttf"); file_f6.copy( directory+"/VeraMoBd.ttf" ); QFile file_f7(":/fonts/ttf-bitstream-vera-1.10/README.TXT"); file_f7.copy( directory+"/README.TXT" ); QFile file_f8(":/fonts/ttf-bitstream-vera-1.10/VeraMoBI.ttf"); file_f8.copy( directory+"/VeraMoBI.ttf" ); QFile file_f9(":/fonts/ttf-bitstream-vera-1.10/VeraMono.ttf"); file_f9.copy( directory+"/VeraMono.ttf" ); /*QFile file_f(":/fonts/ttf-bitstream-vera-1.10/"); file_f.copy( directory+"/" ); QFile file_f(":/fonts/ttf-bitstream-vera-1.10/"); file_f.copy( directory+"/" ); QFile file_f(":/fonts/ttf-bitstream-vera-1.10/"); file_f.copy( directory+"/" ); */ startupMessage.append(" Done.\nAll data has been loaded successfully.\nStarting...\n\n\nHave fun!"); splash.showMessage(startupMessage, Qt::AlignHCenter); app.processEvents(); t.restart(); while( t.elapsed() < 1000 ) ; // Do nothing here for a second splash.finish( mudlet::self() ); // This seems to be the point at which instance of mudlet is created!!! mudlet::debugMode = false; HostManager::self(); FontManager fm; fm.addFonts(); QString home = QDir::homePath()+"/.config/mudlet"; QString homeLink = QDir::homePath()+"/mudlet-data"; QFile::link(home, homeLink); mudlet::self()->show(); app.exec(); }
void fenetre_bc::run(){ QTime timer; // on crée un objet de type timer timer.start(); // on demarre le timer liste_messages->append(""); liste_messages->append("Démarrage du mode nominal."); liste_messages->update(); while(1){ for(int i=0;i<=30;i++){ if(liste_rt[i]=="true"){ liste_messages->append(""); liste_messages->append("Envoi d'une demande si le RT a un message a envoyer"); liste_messages->update(); frame m_frame; // on instancie un objet de type frame QString frame_t=m_frame.create_frame(QString::number(i),"BC","Message a transmettre?"); // creation de la frame pour la requete par appel de la fonction create_frame liste_messages->append("Trame envoyé : "+frame_t); liste_messages->append("Attente de la Reponse du RT."); liste_messages->update(); send(frame_t); // envoi de la requete timer.restart(); while((timer.elapsed()<=attente && message_is_recieved==false)){ QCoreApplication::processEvents(); } if(message_is_recieved==true){ liste_messages->append(tr("Le RT N° %1").arg(i)+" a repondu : "+contenu_frame); liste_messages->update(); } else{ liste_messages->append(tr("Aucune reponse de la part du RT N° %1").arg(i)); liste_messages->update(); } message_is_recieved=false; if(m_frame.get_frame_message(contenu_frame)=="Message a envoyer"){ liste_messages->append("Le RT a des messages a envoyer."); liste_messages->append("Envoi d'une demande au RT d'envoyer le message."); frame m_frame; // on instancie un objet de type frame QString frame_t=m_frame.create_frame(QString::number(i),"BC","Transmit Data"); // creation de la frame pour la requete par appel de la fonction create_frame liste_messages->append("Trame envoyé : "+frame_t); liste_messages->append("Attente de la Reponse du RT."); send(frame_t); // envoi de la requete timer.restart(); while((timer.elapsed()<=attente && message_is_recieved==false)){ QCoreApplication::processEvents(); } if(message_is_recieved==true){ liste_messages->append(tr("Le RT N° %1").arg(i)+" a repondu : "+contenu_frame); if (m_frame.get_frame_destinataire(contenu_frame)!="BC"){ liste_messages->append("On envoie le message au destinataire."); liste_messages->append("Trame envoyé : "+contenu_frame); send(contenu_frame); // envoi de la requete } } else{ liste_messages->append(tr("Aucune reponse de la part du RT N° %1").arg(i)); } } message_is_recieved=false; } QCoreApplication::processEvents(); liste_messages->update(); timer.restart(); while(timer.elapsed()<=attente){ QCoreApplication::processEvents(); } } } }
bool PreviewGenerator::Run(void) { QString msg; QDateTime dtm = MythDate::current(); QTime tm = QTime::currentTime(); bool ok = false; QString command = GetAppBinDir() + "mythpreviewgen"; bool local_ok = ((IsLocal() || !!(m_mode & kForceLocal)) && (!!(m_mode & kLocal)) && QFileInfo(command).isExecutable()); if (!local_ok) { if (!!(m_mode & kRemote)) { ok = RemotePreviewRun(); if (ok) { msg = QString("Generated remotely in %1 seconds, starting at %2") .arg(tm.elapsed()*0.001) .arg(tm.toString(Qt::ISODate)); } } else { LOG(VB_GENERAL, LOG_ERR, LOC + QString("Run() cannot generate preview locally for: '%1'") .arg(m_pathname)); msg = "Failed, local preview requested for remote file."; } } else { // This is where we fork and run mythpreviewgen to actually make preview QStringList cmdargs; cmdargs << "--size" << QString("%1x%2").arg(m_outSize.width()).arg(m_outSize.height()); if (m_captureTime >= 0) { if (m_timeInSeconds) cmdargs << "--seconds"; else cmdargs << "--frame"; cmdargs << QString::number(m_captureTime); } cmdargs << "--chanid" << QString::number(m_programInfo.GetChanID()) << "--starttime" << m_programInfo.GetRecordingStartTime(MythDate::kFilename); if (!m_outFileName.isEmpty()) cmdargs << "--outfile" << m_outFileName; // Timeout in 30s MythSystemLegacy *ms = new MythSystemLegacy(command, cmdargs, kMSDontBlockInputDevs | kMSDontDisableDrawing | kMSProcessEvents | kMSAutoCleanup | kMSPropagateLogs); ms->SetNice(10); ms->SetIOPrio(7); ms->Run(30); uint ret = ms->Wait(); delete ms; if (ret != GENERIC_EXIT_OK) { LOG(VB_GENERAL, LOG_ERR, LOC + QString("Encountered problems running '%1 %2' - (%3)") .arg(command).arg(cmdargs.join(" ")).arg(ret)); } else { LOG(VB_PLAYBACK, LOG_INFO, LOC + "Preview process returned 0."); QString outname = (!m_outFileName.isEmpty()) ? m_outFileName : (m_pathname + ".png"); QString lpath = QFileInfo(outname).fileName(); if (lpath == outname) { StorageGroup sgroup; QString tmpFile = sgroup.FindFile(lpath); outname = (tmpFile.isEmpty()) ? outname : tmpFile; } QFileInfo fi(outname); ok = (fi.exists() && fi.isReadable() && fi.size()); if (ok) { LOG(VB_PLAYBACK, LOG_INFO, LOC + "Preview process ran ok."); msg = QString("Generated on %1 in %2 seconds, starting at %3") .arg(gCoreContext->GetHostName()) .arg(tm.elapsed()*0.001) .arg(tm.toString(Qt::ISODate)); } else { LOG(VB_GENERAL, LOG_ERR, LOC + "Preview process not ok." + QString("\n\t\t\tfileinfo(%1)").arg(outname) + QString(" exists: %1").arg(fi.exists()) + QString(" readable: %1").arg(fi.isReadable()) + QString(" size: %1").arg(fi.size())); LOG(VB_GENERAL, LOG_ERR, LOC + QString("Despite command '%1' returning success") .arg(command)); msg = QString("Failed to read preview image despite " "preview process returning success."); } } } QMutexLocker locker(&m_previewLock); // Backdate file to start of preview time in case a bookmark was made // while we were generating the preview. QString output_fn = m_outFileName.isEmpty() ? (m_programInfo.GetPathname()+".png") : m_outFileName; QDateTime dt; if (ok) { QFileInfo fi(output_fn); if (fi.exists()) dt = fi.lastModified(); } QString message = (ok) ? "PREVIEW_SUCCESS" : "PREVIEW_FAILED"; if (m_listener) { QStringList list; list.push_back(QString::number(m_programInfo.GetRecordingID())); list.push_back(output_fn); list.push_back(msg); list.push_back(dt.isValid()?dt.toUTC().toString(Qt::ISODate):""); list.push_back(m_token); QCoreApplication::postEvent(m_listener, new MythEvent(message, list)); } return ok; }
QString MarkovChainGUI::getAnalysisResult(QTime analysisTime) { return tr("Processed %1 words in %2 seconds.") .arg(analyzedWordTotal + analysisProgress) .arg(QLocale::system().toString(analysisTime.elapsed() / 1000.0, 'f', timeFloatAccuracy)); }