int main(int argc, char *argv[]) { bool hasTouchScreen = QFile::exists("/sys/devices/platform/rpi_ft5406"); // Unless we have a touch screen, wait for keyboard to appear before displaying anything if (!hasTouchScreen) KeyDetection::waitForKeyboard(); int rev = readBoardRevision(); qDebug() << "Board revision is " << rev; int gpioChannel; if (rev == 2 || rev == 3) gpioChannel = 0; else gpioChannel = 2; QApplication a(argc, argv); RightButtonFilter rbf; LongPressHandler lph; GpioInput gpio(gpioChannel); bool runinstaller = false; bool gpio_trigger = false; bool keyboard_trigger = true; bool force_trigger = false; QString defaultLang = "en"; QString defaultKeyboard = "gb"; QString defaultDisplay = "0"; QString defaultPartition = "800"; // Process command-line arguments for (int i=1; i<argc; i++) { // Flag to indicate first boot if (strcmp(argv[i], "-runinstaller") == 0) runinstaller = true; // Enables use of GPIO 3 to force NOOBS to launch by pulling low else if (strcmp(argv[i], "-gpiotriggerenable") == 0) gpio_trigger = true; // Disables use of keyboard to trigger recovery GUI else if (strcmp(argv[i], "-keyboardtriggerdisable") == 0) keyboard_trigger = false; // Forces display of recovery GUI every time else if (strcmp(argv[i], "-forcetrigger") == 0) force_trigger = true; // Allow default language to be specified in commandline else if (strcmp(argv[i], "-lang") == 0) { if (argc > i+1) defaultLang = argv[i+1]; } // Allow default keyboard layout to be specified in commandline else if (strcmp(argv[i], "-kbdlayout") == 0) { if (argc > i+1) defaultKeyboard = argv[i+1]; } // Allow default display mode to be specified in commandline else if (strcmp(argv[i], "-dispmode") == 0) { if (argc > i+1) defaultDisplay = --argv[i+1]; } // Allow default boot partition to be specified in commandline else if (strcmp(argv[i], "-partition") == 0) { if (argc > i+1) defaultPartition = argv[i+1]; } } // Intercept right mouse clicks sent to the title bar a.installEventFilter(&rbf); // Treat long holds as double-clicks if (hasTouchScreen) a.installEventFilter(&lph); #ifdef Q_WS_QWS QWSServer::setCursorVisible(false); #endif QDir settingsdir; settingsdir.mkdir("/settings"); // Set wallpaper and icon, if we have resource files for that if (QFile::exists(":/icons/raspberry_icon.png")) a.setWindowIcon(QIcon(":/icons/raspberry_icon.png")); #ifdef Q_WS_QWS QWSServer::setBackground(BACKGROUND_COLOR); #endif QSplashScreen *splash = new QSplashScreen(QPixmap(":/wallpaper.png")); splash->show(); QApplication::processEvents(); // Wait for drive device to show up QString drive; bool driveReady = false; QTime t; t.start(); while (t.elapsed() < 10000) { if (drive.isEmpty()) { /* We do not know the exact drive name to wait for */ drive = findRecoveryDrive(); if (!drive.isEmpty()) { driveReady = true; break; } } else if (drive.startsWith("/dev")) { if (QFile::exists(drive)) { driveReady = true; break; } } QApplication::processEvents(QEventLoop::WaitForMoreEvents, 100); } if (!driveReady) { QMessageBox::critical(NULL, "Files not found", QString("Cannot find the drive with NOOBS files %1").arg(drive), QMessageBox::Close); return 1; } qDebug() << "NOOBS drive:" << drive; // If -runinstaller is not specified, only continue if SHIFT is pressed, GPIO is triggered, // or no OS is installed (/settings/installed_os.json does not exist) bool bailout = !runinstaller && !force_trigger && !(gpio_trigger && (gpio.value() == 0 )) && hasInstalledOS(drive); if (bailout && keyboard_trigger) { t.start(); while (t.elapsed() < 2000) { QApplication::processEvents(QEventLoop::WaitForMoreEvents, 10); if (QApplication::queryKeyboardModifiers().testFlag(Qt::ShiftModifier)) { bailout = false; qDebug() << "Shift detected"; break; } if (hasTouchScreen && QApplication::mouseButtons().testFlag(Qt::LeftButton)) { bailout = false; qDebug() << "Tap detected"; break; } } } if (bailout) { splash->hide(); showBootMenu(drive, defaultPartition, true); } #ifdef Q_WS_QWS QWSServer::setCursorVisible(true); #endif // Main window in the middle of screen MainWindow mw(drive, defaultDisplay, splash); mw.setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, mw.size(), a.desktop()->availableGeometry())); mw.show(); #ifdef ENABLE_LANGUAGE_CHOOSER // Language chooser at the bottom center LanguageDialog* ld = new LanguageDialog(defaultLang, defaultKeyboard); ld->setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignHCenter | Qt::AlignBottom, ld->size(), a.desktop()->availableGeometry())); ld->show(); #endif a.exec(); showBootMenu(drive, defaultPartition, false); return 0; }
int main(int argc,char *argv[]) { QApplication a(argc,argv,false); new MainObject(NULL,"main"); return a.exec(); }
void Foam::threePhaseInterfaceProperties::correctContactAngle ( surfaceVectorField::GeometricBoundaryField& nHatb ) const { const volScalarField::GeometricBoundaryField& alpha1 = mixture_.alpha1().boundaryField(); const volScalarField::GeometricBoundaryField& alpha2 = mixture_.alpha2().boundaryField(); const volScalarField::GeometricBoundaryField& alpha3 = mixture_.alpha3().boundaryField(); const volVectorField::GeometricBoundaryField& U = mixture_.U().boundaryField(); const fvMesh& mesh = mixture_.U().mesh(); const fvBoundaryMesh& boundary = mesh.boundary(); forAll(boundary, patchi) { if (isA<alphaContactAngleFvPatchScalarField>(alpha1[patchi])) { const alphaContactAngleFvPatchScalarField& a2cap = refCast<const alphaContactAngleFvPatchScalarField> (alpha2[patchi]); const alphaContactAngleFvPatchScalarField& a3cap = refCast<const alphaContactAngleFvPatchScalarField> (alpha3[patchi]); scalarField twoPhaseAlpha2(max(a2cap, scalar(0))); scalarField twoPhaseAlpha3(max(a3cap, scalar(0))); scalarField sumTwoPhaseAlpha ( twoPhaseAlpha2 + twoPhaseAlpha3 + SMALL ); twoPhaseAlpha2 /= sumTwoPhaseAlpha; twoPhaseAlpha3 /= sumTwoPhaseAlpha; fvsPatchVectorField& nHatp = nHatb[patchi]; scalarField theta ( convertToRad * ( twoPhaseAlpha2*(180 - a2cap.theta(U[patchi], nHatp)) + twoPhaseAlpha3*(180 - a3cap.theta(U[patchi], nHatp)) ) ); vectorField nf(boundary[patchi].nf()); // Reset nHatPatch to correspond to the contact angle scalarField a12(nHatp & nf); scalarField b1(cos(theta)); scalarField b2(nHatp.size()); forAll(b2, facei) { b2[facei] = cos(acos(a12[facei]) - theta[facei]); } scalarField det(1.0 - a12*a12); scalarField a((b1 - a12*b2)/det); scalarField b((b2 - a12*b1)/det); nHatp = a*nf + b*nHatp; nHatp /= (mag(nHatp) + deltaN_.value()); } }
int main(int argc, char *argv[]) { int ret = 0; struct sr_context *sr_ctx = NULL; const char *open_file = NULL; QApplication a(argc, argv); // Set some application metadata QApplication::setApplicationVersion(DS_VERSION_STRING); QApplication::setApplicationName("DSLogic"); QApplication::setOrganizationDomain("http://www.DreamSourceLab.com"); // Parse arguments while (1) { static const struct option long_options[] = { {"loglevel", required_argument, 0, 'l'}, {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; const int c = getopt_long(argc, argv, "l:Vh?", long_options, NULL); if (c == -1) break; switch (c) { case 'l': { const int loglevel = atoi(optarg); sr_log_loglevel_set(loglevel); #ifdef ENABLE_SIGROKDECODE srd_log_loglevel_set(loglevel); #endif break; } case 'V': // Print version info fprintf(stdout, "%s %s\n", DS_TITLE, DS_VERSION_STRING); return 0; case 'h': case '?': usage(); return 0; } } if (argc - optind > 1) { fprintf(stderr, "Only one file can be openened.\n"); return 1; } else if (argc - optind == 1) open_file = argv[argc - 1]; // Initialise libsigrok if (sr_init(&sr_ctx) != SR_OK) { qDebug() << "ERROR: libsigrok init failed."; return 1; } do { #ifdef ENABLE_SIGROKDECODE // Initialise libsigrokdecode if (srd_init(NULL) != SRD_OK) { qDebug() << "ERROR: libsigrokdecode init failed."; break; } // Load the protocol decoders srd_decoder_load_all(); #endif try { // Create the device manager, initialise the drivers pv::DeviceManager device_manager(sr_ctx); // Initialise the main window pv::MainWindow w(device_manager, open_file); //QFile qss(":/levelfour.qss"); QFile qss(":/stylesheet.qss"); qss.open(QFile::ReadOnly); a.setStyleSheet(qss.readAll()); qss.close(); w.show(); // Run the application ret = a.exec(); } catch(std::exception e) { qDebug() << e.what(); } #ifdef ENABLE_SIGROKDECODE // Destroy libsigrokdecode srd_exit(); #endif } while (0); // Destroy libsigrok if (sr_ctx) sr_exit(sr_ctx); return ret; }
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QStringList args = a.arguments(); if (args.size() < 3) { QStringList usage; usage << args.at(0) << "[train data]" << "[test data]"; qFatal("Too few arguments. Usage:\n%s\n", usage.join(" ").toStdString().c_str()); } QFile trainFile(args.at(1)); if (!trainFile.open(QIODevice::ReadOnly)) { qFatal("Failed to open train file %s.\n", trainFile.fileName().toStdString().c_str()); } QFile testFile(args.at(2)); if (!testFile.open(QIODevice::ReadOnly)) { qFatal("Failed to open test file %s.\n", testFile.fileName().toStdString().c_str()); } QElapsedTimer loadTimer; loadTimer.start(); FeatureImporter trainFeatures; FeatureImporter testFeatures; #pragma omp sections { #pragma omp section { trainFeatures.open(&trainFile); } #pragma omp section { testFeatures.open(&testFile); } } int loadMsecs = loadTimer.elapsed(); qDebug() << "loading took" << loadMsecs << "msecs"; trainFile.close(); testFile.close(); QVector<QString> hash; QVector<qint8> trainClasses; for (int i = 0; i < trainFeatures.labels().size(); i++) { qint8 index = hash.indexOf(trainFeatures.labels().at(i)); if (index == -1) { QString dbg("Appending label \"%1\" to hash at position %2. It has now value \"%3\""); hash.append(trainFeatures.labels().at(i)); index = hash.size() - 1; //qDebug() << dbg.arg(trainFeatures.labels().at(i), QString::number(index), hash.at(index)); } trainClasses.append(index); } ClassifierInterface *ci = new CpuClassifier(); QVector<QVector<int> > classes; qDebug() << "starting classification"; QList<int> k; bool ok = true; int i = 50; if (args.size() >= 4) { i = qMax(0, args.at(3).toInt(&ok)); } else { ok = false; } if (!ok) { qDebug() << "no k given, assuming k = 50"; i = 50; } qDebug() << "initial k:" << i; for (; i >= 1; i--) { k.append(i); } QElapsedTimer timer; timer.start(); classes = ci->classify(trainFeatures.features(), testFeatures.features(), trainClasses.constData(), NULL, testFeatures.featuresPerItem(), trainFeatures.itemCount(), testFeatures.itemCount(), k); delete ci; int msecs = timer.elapsed(); qDebug() << "calculations took" << msecs << "msecs"; for (int w = 0; w < classes.size(); w++) { int correct = 0; QVector<QVector<qreal> > confusionMatrix; confusionMatrix.resize(hash.size()); for (int i = 0; i < confusionMatrix.size(); i++) { confusionMatrix[i].resize(hash.size()); } for (int i = 0; i < classes.at(w).size(); i++) { /*qDebug() << i; qDebug() << classes.at(i); qDebug() << hash.at(classes.at(i)); qDebug() << testFeatures.labels().at(i);*/ confusionMatrix[hash.indexOf(testFeatures.labels().at(i))][classes.at(w).at(i)]++; /*if (hash.at(classes.at(w).at(i)) == QString("5")) { qDebug() << "is 5, should be " << testFeatures.labels().at(i); }*/ if (hash.at(classes.at(w).at(i)) == testFeatures.labels().at(i)) { correct++; } } QVector<QPair<QString, int> > sorter; for (int i = 0; i < hash.size(); i++) { sorter << qMakePair(hash.at(i), i); } qSort(sorter); QStringList l; for (int i = 0; i < hash.size(); i++) { l << sorter.at(i).first; } QVector<QVector<qreal> > tempConfusionMatrix; tempConfusionMatrix.resize(hash.size()); for (int j = 0; j < confusionMatrix.size(); j++) { for (int i = 0; i < sorter.size(); i++) { tempConfusionMatrix[j] << confusionMatrix.at(j).at(sorter.at(i).second); } } confusionMatrix = tempConfusionMatrix; for (int j = 0; j < confusionMatrix.size(); j++) { tempConfusionMatrix[j] = confusionMatrix.at(sorter.at(j).second); } confusionMatrix = tempConfusionMatrix; #ifdef PERCENTAGE_CONFUSION for (int i = 0; i < confusionMatrix.size(); i++) { qreal sum = 0; for (int j = 0; j < confusionMatrix.at(i).size(); j++) { sum += confusionMatrix.at(j).at(i); } for (int j = 0; j < confusionMatrix.at(i).size(); j++) { confusionMatrix[j][i] = confusionMatrix.at(j).at(i) / sum * 100.0; } } #endif QTextStream stream(stdout); stream << "k: " << k.at(w) << endl; stream << "\t&\t" << l.join("\t&\t") << "\\\\" << endl; for (int i = 0; i < confusionMatrix.size(); i++) { QStringList list; list << sorter.at(i).first; for (int j = 0; j < confusionMatrix.size(); j++) { list << QString::number(confusionMatrix[i][j], 'g', 4); } const QString joined(list.join("\t&\t")); stream << joined << "\\\\" << endl; } stream << "correct: " << ((float)correct / (float)classes.at(w).size()) * 100 << "%" << endl; } msecs = timer.elapsed(); qDebug() << "everything took" << msecs << "msecs"; return 0; }
int main() { Type type; type.destructor = [] (Value* self) { std::cout << "destroying " << self << "!\n"; }; boost::intrusive_ptr<Value> a(new Value); a->type = &type; }
int main() { AA aa; AA a(aa); return 0; }
/************************************************************************* Testing symmetric EVD subroutine *************************************************************************/ bool testsevd(bool silent) { bool result; ap::real_2d_array a; ap::real_2d_array al; ap::real_2d_array au; ap::real_2d_array z; int pass; int n; int i; int j; int mkind; int passcount; int maxn; double materr; double valerr; double orterr; bool wnsorted; int failc; int runs; double failr; double failthreshold; double threshold; bool waserrors; bool wfailed; failthreshold = 0.005; threshold = 1000*ap::machineepsilon; materr = 0; valerr = 0; orterr = 0; wnsorted = false; wfailed = false; failc = 0; runs = 0; maxn = 20; passcount = 10; // // Main cycle // for(n = 1; n <= maxn; n++) { // // Prepare // a.setbounds(0, n-1, 0, n-1); al.setbounds(0, n-1, 0, n-1); au.setbounds(0, n-1, 0, n-1); for(i = 0; i <= n-1; i++) { for(j = i+1; j <= n-1; j++) { // // A // a(i,j) = 2*ap::randomreal()-1; a(j,i) = a(i,j); // // A lower // al(i,j) = 2*ap::randomreal()-1; al(j,i) = a(i,j); // // A upper // au(i,j) = a(i,j); au(j,i) = 2*ap::randomreal()-1; } a(i,i) = 2*ap::randomreal()-1; al(i,i) = a(i,i); au(i,i) = a(i,i); } // // Test // testevdproblem(a, al, au, n, materr, valerr, orterr, wnsorted, failc); runs = runs+1; } // // report // failr = double(failc)/double(runs); wfailed = failr>failthreshold; waserrors = materr>threshold||valerr>threshold||orterr>threshold||wnsorted||wfailed; if( !silent ) { printf("TESTING SYMMETRIC EVD\n"); printf("EVD matrix error: %5.3le\n", double(materr)); printf("EVD values error (different variants): %5.3le\n", double(valerr)); printf("EVD orthogonality error: %5.3le\n", double(orterr)); printf("Eigen values order: "); if( !wnsorted ) { printf("OK\n"); } else { printf("FAILED\n"); } printf("Always converged: "); if( !wfailed ) { printf("YES\n"); } else { printf("NO\n"); printf("Fail ratio: %5.3lf\n", double(failr)); } printf("Threshold: %5.3le\n", double(threshold)); if( waserrors ) { printf("TEST FAILED\n"); } else { printf("TEST PASSED\n"); } printf("\n\n"); } result = !waserrors; return result; }
void SvgElementVisitor::visit(clan::DomElement &e) { if (e.get_namespace_uri() != Svg::svg_ns) return; // To do: do a more efficient search for the correct handler auto local_name = e.get_local_name(); if (local_name == "a") a(e); else if (local_name == "altGlyph") altGlyph(e); else if (local_name == "altGlyphDef") altGlyphDef(e); else if (local_name == "altGlyphItem") altGlyphItem(e); else if (local_name == "animate") animate(e); else if (local_name == "animateColor") animateColor(e); else if (local_name == "animateMotion") animateMotion(e); else if (local_name == "animateTransform") animateTransform(e); else if (local_name == "circle") circle(e); else if (local_name == "clipPath") clipPath(e); else if (local_name == "color-profile") color_profile(e); else if (local_name == "cursor") cursor(e); else if (local_name == "defs") defs(e); else if (local_name == "desc") desc(e); else if (local_name == "ellipse") ellipse(e); else if (local_name == "feBlend") feBlend(e); else if (local_name == "feColorMatrix") feColorMatrix(e); else if (local_name == "feComponentTransfer") feComponentTransfer(e); else if (local_name == "feComposite") feComposite(e); else if (local_name == "feConvolveMatrix") feConvolveMatrix(e); else if (local_name == "feDiffuseLighting") feDiffuseLighting(e); else if (local_name == "feDisplacementMap") feDisplacementMap(e); else if (local_name == "feDistantLight") feDistantLight(e); else if (local_name == "feFlood") feFlood(e); else if (local_name == "feFuncA") feFuncA(e); else if (local_name == "feFuncB") feFuncB(e); else if (local_name == "feFuncG") feFuncG(e); else if (local_name == "feFuncR") feFuncR(e); else if (local_name == "feGaussianBlur") feGaussianBlur(e); else if (local_name == "feImage") feImage(e); else if (local_name == "feMerge") feMerge(e); else if (local_name == "feMergeNode") feMergeNode(e); else if (local_name == "feMorphology") feMorphology(e); else if (local_name == "feOffset") feOffset(e); else if (local_name == "fePointLight") fePointLight(e); else if (local_name == "feSpecularLighting") feSpecularLighting(e); else if (local_name == "feSpotLight") feSpotLight(e); else if (local_name == "feTile") feTile(e); else if (local_name == "feTurbulence") feTurbulence(e); else if (local_name == "filter") filter(e); else if (local_name == "font") font(e); else if (local_name == "font-face") font_face(e); else if (local_name == "font-face-format") font_face_format(e); else if (local_name == "font-face-name") font_face_name(e); else if (local_name == "font-face-src") font_face_src(e); else if (local_name == "font-face-uri") font_face_uri(e); else if (local_name == "foreignObject") foreignObject(e); else if (local_name == "g") g(e); else if (local_name == "glyph") glyph(e); else if (local_name == "glyphRef") glyphRef(e); else if (local_name == "hkern") hkern(e); else if (local_name == "image") image(e); else if (local_name == "line") line(e); else if (local_name == "linearGradient") linearGradient(e); else if (local_name == "marker") marker(e); else if (local_name == "mask") mask(e); else if (local_name == "metadata") metadata(e); else if (local_name == "missing-glyph") missing_glyph(e); else if (local_name == "mpath") mpath(e); else if (local_name == "path") path(e); else if (local_name == "pattern") pattern(e); else if (local_name == "polygon") polygon(e); else if (local_name == "polyline") polyline(e); else if (local_name == "radialGradient") radialGradient(e); else if (local_name == "rect") rect(e); else if (local_name == "script") script(e); else if (local_name == "set") set(e); else if (local_name == "stop") stop(e); else if (local_name == "style") style(e); else if (local_name == "svg") svg(e); else if (local_name == "switch") switch_(e); else if (local_name == "symbol") symbol(e); else if (local_name == "text") text(e); else if (local_name == "textPath") textPath(e); else if (local_name == "title") title(e); else if (local_name == "tref") tref(e); else if (local_name == "tspan") tspan(e); else if (local_name == "use") use(e); else if (local_name == "view") view(e); else if (local_name == "vkern") vkern(e); }
void b2ContactSolver::SolveVelocityConstraints() { for (int32 i = 0; i < m_count; ++i) { b2ContactVelocityConstraint* vc = m_velocityConstraints + i; int32 indexA = vc->indexA; int32 indexB = vc->indexB; float32 mA = vc->invMassA; float32 iA = vc->invIA; float32 mB = vc->invMassB; float32 iB = vc->invIB; int32 pointCount = vc->pointCount; b2Vec2 vA = m_velocities[indexA].v; float32 wA = m_velocities[indexA].w; b2Vec2 vB = m_velocities[indexB].v; float32 wB = m_velocities[indexB].w; b2Vec2 normal = vc->normal; b2Vec2 tangent = b2Cross(normal, 1.0f); float32 friction = vc->friction; b2Assert(pointCount == 1 || pointCount == 2); // Solve tangent constraints first because non-penetration is more important // than friction. for (int32 j = 0; j < pointCount; ++j) { b2VelocityConstraintPoint* vcp = vc->points + j; // Relative velocity at contact b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA); // Compute tangent force float32 vt = b2Dot(dv, tangent); float32 lambda = vcp->tangentMass * (-vt); // b2Clamp the accumulated force float32 maxFriction = friction * vcp->normalImpulse; float32 newImpulse = b2Clamp(vcp->tangentImpulse + lambda, -maxFriction, maxFriction); lambda = newImpulse - vcp->tangentImpulse; vcp->tangentImpulse = newImpulse; // Apply contact impulse b2Vec2 P = lambda * tangent; vA -= mA * P; wA -= iA * b2Cross(vcp->rA, P); vB += mB * P; wB += iB * b2Cross(vcp->rB, P); } // Solve normal constraints if (vc->pointCount == 1) { b2VelocityConstraintPoint* vcp = vc->points + 0; // Relative velocity at contact b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA); // Compute normal impulse float32 vn = b2Dot(dv, normal); float32 lambda = -vcp->normalMass * (vn - vcp->velocityBias); // b2Clamp the accumulated impulse float32 newImpulse = b2Max(vcp->normalImpulse + lambda, 0.0f); lambda = newImpulse - vcp->normalImpulse; vcp->normalImpulse = newImpulse; // Apply contact impulse b2Vec2 P = lambda * normal; vA -= mA * P; wA -= iA * b2Cross(vcp->rA, P); vB += mB * P; wB += iB * b2Cross(vcp->rB, P); } else { // Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite). // Build the mini LCP for this contact patch // // vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2 // // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n ) // b = vn0 - velocityBias // // The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i // implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases // vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid // solution that satisfies the problem is chosen. // // In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires // that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i). // // Substitute: // // x = a + d // // a := old total impulse // x := new total impulse // d := incremental impulse // // For the current iteration we extend the formula for the incremental impulse // to compute the new total impulse: // // vn = A * d + b // = A * (x - a) + b // = A * x + b - A * a // = A * x + b' // b' = b - A * a; b2VelocityConstraintPoint* cp1 = vc->points + 0; b2VelocityConstraintPoint* cp2 = vc->points + 1; b2Vec2 a(cp1->normalImpulse, cp2->normalImpulse); b2Assert(a.x >= 0.0f && a.y >= 0.0f); // Relative velocity at contact b2Vec2 dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); b2Vec2 dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); // Compute normal velocity float32 vn1 = b2Dot(dv1, normal); float32 vn2 = b2Dot(dv2, normal); b2Vec2 b; b.x = vn1 - cp1->velocityBias; b.y = vn2 - cp2->velocityBias; // Compute b' b -= b2Mul(vc->K, a); const float32 k_errorTol = 1e-3f; B2_NOT_USED(k_errorTol); for (;;) { // // Case 1: vn = 0 // // 0 = A * x + b' // // Solve for x: // // x = - inv(A) * b' // b2Vec2 x = - b2Mul(vc->normalMass, b); if (x.x >= 0.0f && x.y >= 0.0f) { // Get the incremental impulse b2Vec2 d = x - a; // Apply incremental impulse b2Vec2 P1 = d.x * normal; b2Vec2 P2 = d.y * normal; vA -= mA * (P1 + P2); wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); vB += mB * (P1 + P2); wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); // Accumulate cp1->normalImpulse = x.x; cp2->normalImpulse = x.y; #if B2_DEBUG_SOLVER == 1 // Postconditions dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); // Compute normal velocity vn1 = b2Dot(dv1, normal); vn2 = b2Dot(dv2, normal); b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); #endif break; } // // Case 2: vn1 = 0 and x2 = 0 // // 0 = a11 * x1 + a12 * 0 + b1' // vn2 = a21 * x1 + a22 * 0 + b2' // x.x = - cp1->normalMass * b.x; x.y = 0.0f; vn1 = 0.0f; vn2 = vc->K.ex.y * x.x + b.y; if (x.x >= 0.0f && vn2 >= 0.0f) { // Get the incremental impulse b2Vec2 d = x - a; // Apply incremental impulse b2Vec2 P1 = d.x * normal; b2Vec2 P2 = d.y * normal; vA -= mA * (P1 + P2); wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); vB += mB * (P1 + P2); wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); // Accumulate cp1->normalImpulse = x.x; cp2->normalImpulse = x.y; #if B2_DEBUG_SOLVER == 1 // Postconditions dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); // Compute normal velocity vn1 = b2Dot(dv1, normal); b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); #endif break; } // // Case 3: vn2 = 0 and x1 = 0 // // vn1 = a11 * 0 + a12 * x2 + b1' // 0 = a21 * 0 + a22 * x2 + b2' // x.x = 0.0f; x.y = - cp2->normalMass * b.y; vn1 = vc->K.ey.x * x.y + b.x; vn2 = 0.0f; if (x.y >= 0.0f && vn1 >= 0.0f) { // Resubstitute for the incremental impulse b2Vec2 d = x - a; // Apply incremental impulse b2Vec2 P1 = d.x * normal; b2Vec2 P2 = d.y * normal; vA -= mA * (P1 + P2); wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); vB += mB * (P1 + P2); wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); // Accumulate cp1->normalImpulse = x.x; cp2->normalImpulse = x.y; #if B2_DEBUG_SOLVER == 1 // Postconditions dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); // Compute normal velocity vn2 = b2Dot(dv2, normal); b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); #endif break; } // // Case 4: x1 = 0 and x2 = 0 // // vn1 = b1 // vn2 = b2; x.x = 0.0f; x.y = 0.0f; vn1 = b.x; vn2 = b.y; if (vn1 >= 0.0f && vn2 >= 0.0f ) { // Resubstitute for the incremental impulse b2Vec2 d = x - a; // Apply incremental impulse b2Vec2 P1 = d.x * normal; b2Vec2 P2 = d.y * normal; vA -= mA * (P1 + P2); wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); vB += mB * (P1 + P2); wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); // Accumulate cp1->normalImpulse = x.x; cp2->normalImpulse = x.y; break; } // No solution, give up. This is hit sometimes, but it doesn't seem to matter. break; } } m_velocities[indexA].v = vA; m_velocities[indexA].w = wA; m_velocities[indexB].v = vB; m_velocities[indexB].w = wB; } }
int main(int argc, char *argv[]) { int res = 0; { Device::instance(); // initialize device #ifndef i386 QProcess::execute("eips -c"); pTouch = new TouchScreen(); #endif lString16 exedir = LVExtractPath(LocalToUnicode(lString8(argv[0]))); LVAppendPathDelimiter(exedir); lString16 datadir = exedir + L"data/"; lString16 exefontpath = exedir + L"fonts"; lString16Collection fontDirs; fontDirs.add(exefontpath); #ifndef i386 fontDirs.add(lString16(L"/usr/java/lib/fonts")); fontDirs.add(lString16(L"/mnt/us/fonts")); #endif CRPropRef props = LVCreatePropsContainer(); { LVStreamRef cfg = LVOpenFileStream(UnicodeToUtf8(datadir + L"cr3.ini").data(), LVOM_READ); if(!cfg.isNull()) props->loadFromStream(cfg.get()); } lString16 lang = props->getStringDef(PROP_WINDOW_LANG, ""); InitCREngineLog(props); CRLog::info("main()"); if(!InitCREngine(argv[0], fontDirs)) { printf("Cannot init CREngine - exiting\n"); return 2; } #ifndef i386 PrintString(1, 1, "crengine version: " + QString(CR_ENGINE_VERSION)); PrintString(1, 2, QString("buid date: %1 %2").arg(__DATE__).arg(__TIME__)); if (!Device::isTouch()) { QString message = "Please wait while application is loading..."; int xpos = ((Device::getWidth()/12-1)-message.length())/2; int ypos = (Device::getHeight()/20-2)/2; PrintString(xpos, ypos, message); } #endif // set row count int rc = props->getIntDef(PROP_WINDOW_ROW_COUNT, 0); if(!rc) { #ifndef i386 props->setInt(PROP_WINDOW_ROW_COUNT, Device::getModel() != Device::KDX ? 10 : 16); #else props->setInt(PROP_WINDOW_ROW_COUNT, 10); #endif LVStreamRef cfg = LVOpenFileStream(UnicodeToUtf8(datadir + L"cr3.ini").data(), LVOM_WRITE); props->saveToStream(cfg.get()); } QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); MyApplication a(argc, argv); pMyApp = &a; // set app stylesheet #ifndef i386 QString style = (Device::getModel() != Device::KDX ? "stylesheet_k3.qss" : "stylesheet_dx.qss"); if (Device::getModel() == Device::KPW) style = "stylesheet_pw.qss"; QFile qss(QDir::toNativeSeparators(cr2qt(datadir)) + style); // set up full update interval for the graphics driver QKindleFb *pscreen = static_cast<QKindleFb*>(QScreen::instance()); pscreen->setFullUpdateEvery(props->getIntDef(PROP_DISPLAY_FULL_UPDATE_INTERVAL, 1)); #else QFile qss(QDir::toNativeSeparators(cr2qt(datadir)) + "stylesheet_k3.qss"); #endif qss.open(QFile::ReadOnly); if(qss.error() == QFile::NoError) { a.setStyleSheet(qss.readAll()); qss.close(); } QString translations = cr2qt(datadir) + "i18n"; QTranslator myappTranslator; if(!lang.empty() && lang.compare(L"English")) { if(myappTranslator.load(cr2qt(lang), translations)) QApplication::installTranslator(&myappTranslator); else qDebug("Can`t load translation file %s from dir %s", UnicodeToUtf8(lang).c_str(), UnicodeToUtf8(qt2cr(translations)).c_str()); } (void) signal(SIGUSR1, sigCatcher); MainWindow mainWin; a.setMainWindow(&mainWin); mainWin.showFullScreen(); mainWin.doStartupActions(); res = a.exec(); } ShutdownCREngine(); return res; }
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); //![2] QLoggingCategory::setFilterRules(QStringLiteral("qt.driver.usb.debug=true")); //![2] //![22] // ... oldCategoryFilter = QLoggingCategory::installFilter(myCategoryFilter); //![22] //![3] qSetMessagePattern("%{category} %{message}"); //![3] //![4] // usbEntries() will only be called if QT_DRIVER_USB category is enabled qCDebug(QT_DRIVER_USB) << "devices: " << usbEntries(); //![4] { //![10] QLoggingCategory category("qt.driver.usb"); qCDebug(category) << "a debug message"; //![10] } { //![11] QLoggingCategory category("qt.driver.usb"); qCWarning(category) << "a warning message"; //![11] } { //![12] QLoggingCategory category("qt.driver.usb"); qCCritical(category) << "a critical message"; //![12] } { //![13] QLoggingCategory category("qt.driver.usb"); qCDebug(category, "a debug message logged into category %s", category.categoryName()); //![13] } { //![14] QLoggingCategory category("qt.driver.usb"); qCWarning(category, "a warning message logged into category %s", category.categoryName()); //![14] } { //![15] QLoggingCategory category("qt.driver.usb"); qCCritical(category, "a critical message logged into category %s", category.categoryName()); //![15] } return 0; }
/* Match image a to image b, returning the nearest neighbor field mapping a => b coords, stored in an RGB 24-bit image as (by<<12)|bx. */ void PatchMatch::patchmatch(cv::Mat &image, cv::Mat &b, BITMAP *ann, BITMAP &annd) { /* Initialize with random nearest neighbor field (NNF). */ cv::Mat a(image.size(), CV_64F); image.copyTo(a); int aew = a.cols - patch_w+1, aeh = a.rows - patch_w + 1; /* Effective width and height (possible upper left corners of patches). */ int bew = b.cols - patch_w+1, beh = b.rows - patch_w + 1; for (int ay = 0; ay < aeh; ay++) { for (int ax = 0; ax < aew; ax++) { int bx, by; //if((*ann)[ay][ax] == 0){ // bx = rand() % bew; // by = rand() % beh; // (*ann)[ay][ax] = XY_TO_INT(bx, by); //} //else{ // bx = INT_TO_X((*ann)[ay][ax]); // by = INT_TO_Y((*ann)[ay][ax]); //} bx = rand() % bew; by = rand() % beh; (*ann)[ay][ax] = XY_TO_INT(bx, by); annd[ay][ax] = dist(a, b, ax, ay, bx, by); } } int as; std::ofstream o_file; o_file.open("1.txt"); for (int iter = 0; iter < pm_iters; iter++) { /* In each iteration, improve the NNF, by looping in scanline or reverse-scanline order. */ int ystart = 0, yend = aeh, ychange = 1; int xstart = 0, xend = aew, xchange = 1; if (iter % 2 == 1) { xstart = xend-1; xend = -1; xchange = -1; ystart = yend-1; yend = -1; ychange = -1; } // if(iter == 2) as = 0; for (int ay = ystart; ay != yend; ay += ychange) { for (int ax = xstart; ax != xend; ax += xchange) { /* Current (best) guess. */ //if(ax == 366 && ay == 367) // as++; // int sdsd = targetMask[ay * a.cols + ax]; //if(ax == 352 && ay == 73){ // as++; //} int v = (*ann)[ay][ax]; int xbest = INT_TO_X(v), ybest = INT_TO_Y(v); int dbest = annd[ay][ax]; /* Propagation: Improve current guess by trying instead correspondences from left and above (below and right on odd iterations). */ int targetCount = 0; for(int i = 0; i < patch_w; i++){ for(int j = 0; j < patch_w; j++){ if(targetMask[(ay + i) * a.cols + ax + j] > 0) targetCount++; } } if(targetCount > patch_w){ int vp = (*ann)[ay][ax - xchange]; int xp = INT_TO_X(vp) + xchange, yp = INT_TO_Y(vp); if ((unsigned) xp < (unsigned) bew) { xbest = xp; ybest = yp; (*ann)[ay][ax] = XY_TO_INT(xbest, ybest); annd[ay][ax] = annd[ay][ax - xchange]; continue; } //else{ // vp = (*ann)[ay - ychange][ax]; // xp = INT_TO_X(vp), yp = INT_TO_Y(vp) + ychange; // if ((unsigned) yp < (unsigned) beh) { // xbest = xp; // ybest = yp; // (*ann)[ay][ax] = XY_TO_INT(xbest, ybest); // annd[ay][ax] = annd[ay - ychange][ax]; // continue; // } //} if((unsigned) (ay - ychange) < (unsigned) aeh){ int vp = (*ann)[ay - ychange][ax]; int xp = INT_TO_X(vp), yp = INT_TO_Y(vp) + ychange; if ((unsigned) yp < (unsigned) beh) { improve_guess(a, b, ax, ay, xbest, ybest, dbest, xp, yp); } } } else{ if ((unsigned) (ax - xchange) < (unsigned) aew) { int vp = (*ann)[ay][ax - xchange]; int xp = INT_TO_X(vp) + xchange, yp = INT_TO_Y(vp); if ((unsigned) xp < (unsigned) bew) { improve_guess(a, b, ax, ay, xbest, ybest, dbest, xp, yp); } } if ((unsigned) (ay - ychange) < (unsigned) aeh) { int vp = (*ann)[ay - ychange][ax]; int xp = INT_TO_X(vp), yp = INT_TO_Y(vp) + ychange; if ((unsigned) yp < (unsigned) beh) { improve_guess(a, b, ax, ay, xbest, ybest, dbest, xp, yp); } } } /* Random search: Improve current guess by searching in boxes of exponentially decreasing size around the current best guess. */ int rs_start = rs_max; if (rs_start > MAX(b.cols, b.rows)) { rs_start = MAX(b.cols, b.rows); } for (int mag = rs_start; mag >= 1; mag /= 2) { /* Sampling window */ int xmin = MAX(xbest-mag, 0), xmax = MIN(xbest+mag+1,bew); int ymin = MAX(ybest-mag, 0), ymax = MIN(ybest+mag+1,beh); int xp = xmin+rand()%(xmax-xmin); int yp = ymin+rand()%(ymax-ymin); int targetCount = 0; for(int i = 0; i < patch_w; i++){ for(int j = 0; j < patch_w; j++){ if(targetMask[(yp + i) * a.cols + xp + j] > 0){ targetCount++; break; } } if(targetCount > 0) break; } if(targetCount > 0){ mag *= 2; continue; } improve_guess(a, b, ax, ay, xbest, ybest, dbest, xp, yp); } (*ann)[ay][ax] = XY_TO_INT(xbest, ybest); annd[ay][ax] = dbest; //a.at<cv::Vec3b>(ay, ax) = b.at<cv::Vec3b>(ybest, xbest); //for (int dy = 0; dy < patch_w; dy++) { // for (int dx = 0; dx < patch_w; dx++) { // a.at<cv::Vec3b>(ay + dy, ax + dx) = b.at<cv::Vec3b>(ybest + dy, xbest + dx); // } // } if(ay != ybest || ax != xbest) as++; if(ax == 352 && ay == 73){ as++; } // for(int i = 0; i < cvImage.rows - 7 + 1; i++){ // for(int j = 0; j < cvImage.cols - 7 + 1; j++){ // int v = (*ann)[i][j]; // int x = INT_TO_X(v); // int y = INT_TO_Y(v); // anni.at<cv::Vec3b>(i, j).val[0] = (0+ x) % 256; // anni.at<cv::Vec3b>(i, j).val[1] = (0 + y) % 256; // anni.at<cv::Vec3b>(i, j).val[2] = 0; // if(annd[i][j] > 0){ // anndi.at<cv::Vec3b>(i, j).val[0] = annd[i][j] % 256; // } // else // anndi.at<cv::Vec3b>(i, j).val[0] = 0; // anndi.at<cv::Vec3b>(i, j).val[1] = 0; // anndi.at<cv::Vec3b>(i, j).val[2] = 0; // } //} //cv::imshow("r", anni); //cv::imshow("rd", anndi); } } //std::string s[] = {"0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"}; //cv::imshow(s[iter], a); o_file<<as<<std::endl; std::cout<<as<<std::endl; } o_file.close(); a.copyTo(image); }
int main( int argc_, char **argv_ ) { meerkat::mk_argument_manager a("Force-directed edge bundling calculator", "Usage: fdeb [options]"); a.add_help(); a.add_argument_entry( "nodes", MK_VALUE, "--nodes", "-n", "File containing node positions", "", MK_REQUIRED); a.add_argument_entry( "edges", MK_VALUE, "--edges", "-e", "File containing edges", "", MK_REQUIRED); a.add_argument_entry( "json", MK_VALUE, "--json", "-json", "Prints result in a JSON file [unset]", "", MK_OPTIONAL); a.add_argument_entry( "K", MK_VALUE, "--K", "-K", "Edge stiffness [0.1]", "0.1", MK_OPTIONAL); a.add_argument_entry( "S", MK_VALUE, "--S", "-S", "Initial value of S [0.4]", "0.4", MK_OPTIONAL); a.add_argument_entry( "I", MK_VALUE, "--I", "-i", "Initial number of iterations [90]", "90", MK_OPTIONAL); a.add_argument_entry( "compat", MK_VALUE, "--compat", "-c", "Compatibility threshold [0.6]", "0.6", MK_OPTIONAL); a.add_argument_entry( "cycles", MK_VALUE, "--cycles", "-C", "Max number of cycles [5]", "5", MK_OPTIONAL); a.add_argument_entry( "sigma", MK_VALUE, "--sigma", "-s", "Smoothing width [3]", "3", MK_OPTIONAL); a.add_argument_entry( "edge weight", MK_VALUE, "--edge-weight", "-ew", "Edge weight threshold for edge filtering [unset]." "Edges with a weight below the given value are dropped", "-1.0", MK_OPTIONAL); a.add_argument_entry( "edge percentage", MK_VALUE, "--edge-percentage", "-ep", "Edge percentage for edge filtering [unset]." "The given fraction of edges among the strongest ones are kept", "-1.0", MK_OPTIONAL); a.add_argument_entry( "epsilon", MK_VALUE, "--epsilon", "-E", "Lowest interaction distance [1e-4]", "0.0001", MK_OPTIONAL); a.add_argument_entry( "gravitation center x", MK_VALUE, "--gravitation-center-x", "-gcx", "Gravitation center x coordinate [0.0]. If set, gravitation is turned on", "0.0", MK_OPTIONAL); a.add_argument_entry( "gravitation center y", MK_VALUE, "--gravitation-center-y", "-gcy", "Gravitation center y coordinate [0.0]. If set, gravitation is turned on", "0.0", MK_OPTIONAL); a.add_argument_entry( "gravitation exponent", MK_VALUE, "--gravitation-exponent", "-ge", "Gravitation exponent [-2.0]. If set, gravitation is turned on", "1.0", MK_OPTIONAL); a.add_argument_entry( "visualization", MK_FLAG, "--visualize", "-v", "Enables real-time visualization [off]", "0", MK_OPTIONAL); a.add_argument_entry( "transparency", MK_VALUE, "--transparency", "-t", "Transparency of edges", "0.3", MK_OPTIONAL); a.read_arguments(argc_, argv_); a.show_settings(); // set params and read graph gGraph.set_algorithm_params( a.get_double_argument("K"), a.get_int_argument("cycles"), a.get_int_argument("I"), a.get_double_argument("compat"), a.get_double_argument("sigma")); gGraph.set_network_params( a.get_double_argument("edge weight"), a.get_double_argument("edge percentage") ); gGraph.set_physics_params( a.get_double_argument("S"), a.get_double_argument("epsilon"), meerkat::mk_vector2(a.get_double_argument("gravitation center x"), a.get_double_argument("gravitation center y")), a.get_double_argument("gravitation exponent") ); if( a.is_set("gravitation center x") || a.is_set("gravitation center y") || a.is_set("gravitation exponent") ) gGraph.enable_gravitation(); // Read graph gGraph.read(a.get_string_argument("nodes"), a.get_string_argument("edges")); // Get output name if( a.is_set("json") ) gJson = a.get_string_argument("json"); // If visualization is enabled if( a.is_set("visualization") ) { // Set graphical parameters gGraph.set_graphics_params( a.get_double_argument("transparency") ); // Get bounding box meerkat::mk_vector2 bottomLeft, topRight; gGraph.get_bounding_box(bottomLeft, topRight, 20.0); double gWidth = topRight.x() - bottomLeft.x(); double gHeight = topRight.y() - bottomLeft.y(); // Init GLUT int wWidth = DEFAULT_SIZE, wHeight = DEFAULT_SIZE; if( gWidth > gHeight ) wHeight = int(wWidth * gHeight/gWidth); else wWidth = int(wHeight * gWidth/gHeight); glutInit( &argc_, argv_ ); glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE ); glutInitWindowSize( wWidth, wHeight ); glutInitWindowPosition( 10, 100 ); glutCreateWindow( "fdeb" ); init(bottomLeft, topRight); // Increase cycle index and enter main loop glutDisplayFunc( display ); glutKeyboardFunc( keyboard ); glutTimerFunc( 10, timer, 1 ); glutMainLoop(); } // Otherwise, just perform edge bundling else { do { while( gGraph.iterate() > 0 ); gGraph.add_subvisions(); } while( gGraph.update_cycle() > 0 ); gGraph.smooth(); if( gJson != "" ) gGraph.print_json(gJson); } return 0; }
int main() { namespace stdx = std::experimental; namespace mem_usage_able = std::experimental; { int i = 0; std::experimental::Array<int> a (10); std::vector<int> v (10); std::vector<std::pair<int, int>> vp; std::pair<std::vector<int>, std::vector<int>> pv; boost::optional<int> o; boost::optional<std::vector<int>> ov; std::vector<boost::optional<int>> vo; std::unique_ptr<int> up; boost::optional<std::tuple<int>> ot; static_assert(stdx::meta::is_valid<decltype(mem_usage_able::mem_usage(i))>, ""); std::cout << mem_usage_able::mem_usage(i) << "\n"; std::cout << mem_usage_able::mem_usage(a) << "\n"; std::cout << mem_usage_able::mem_usage(v) << "\n"; std::cout << mem_usage_able::mem_usage(o) << "\n"; #if 0 // compile fails as expected decltype(mem_usage_able::mem_usage(up)) xx; #endif std::cout << mem_usage_able::mem_usage(vp) << "\n"; std::cout << mem_usage_able::mem_usage(pv) << "\n"; std::cout << mem_usage_able::mem_usage(ov) << "\n"; std::cout << mem_usage_able::mem_usage(vo) << "\n"; } int i = 0; std::experimental::Array<int> a (10); std::vector<int> v (10); std::vector<std::pair<int, int>> vp; boost::optional<int> o; boost::optional<std::vector<int>> ov; std::cout << mem_usage_able::mem_usage(i) << "\n"; std::cout << mem_usage_able::mem_usage(a) << "\n"; std::cout << mem_usage_able::mem_usage(v) << "\n"; std::cout << mem_usage_able::mem_usage(o) << "\n"; std::cout << mem_usage_able::mem_usage(vp) << "\n"; std::cout << mem_usage_able::mem_usage(ov) << "\n"; { int* t; std::cout << "int* " << mem_usage_able::mem_usage(t) << "\n"; } { trace = true; int* t=new int; std::cout << "int* " << mem_usage_able::mem_usage(t) << "\n"; trace = false; } #if __cplusplus > 201402L { std::tuple<int, int> t; std::cout <<"std::tuple<int, int> " << mem_usage_able::mem_usage(t) << "\n"; } { std::tuple<std::vector<int>, int> t; std::cout << mem_usage_able::mem_usage(t) << "\n"; } { trace = false; using T = std::pair<int, int>; static_assert(! std::is_trivial<T>::value, ""); static_assert(stdx::is_product_type<T>::value, ""); T t; std::cout << mem_usage_able::mem_usage(t) << "\n"; trace = false; } { trace = false; typedef Point2D T; T t; std::cout << "X=== " << mem_usage_able::mem_usage(t) << "\n"; trace = false; } #if 0 { // COMPILE FAIL AS EXPECTED: mem_usage for pt is been defined // However we don't want this behavior. trace = true; using T = std::pair<short, Point2D>; static_assert(! std::is_trivial<T>::value, ""); static_assert(stdx::is_product_type<T>::value, ""); T t; std::cout << "std::pair<short, std::pair<X, X>>=== " << mem_usage_able::mem_usage(t) << "\n"; trace = false; } #endif { // fixme : why this works? mem_usage for pt is been defined trace = false; using T = std::pair<short, std::pair<Point2D, X>>; //using T = std::pair<short, Point2D>; static_assert(stdx::product_type::size<std::pair<short, std::pair<X, long>>>::value == 2, ""); static_assert(! std::is_trivial<T>::value, ""); static_assert(stdx::is_product_type<T>::value, ""); T t; std::cout << "std::pair<short, std::pair<X, X>>=== " << mem_usage_able::mem_usage(t) << "\n"; trace = false; } { trace = false; using T = std::array<int, 3>; static_assert(std::is_trivial<T>::value, ""); static_assert(stdx::is_product_type<T>::value, ""); T t; std::cout << mem_usage_able::mem_usage(t) << "\n"; trace = false; } { typedef int T[3]; static_assert(std::is_trivial<T>::value, ""); static_assert(stdx::is_product_type<T>::value, ""); T t; std::cout << "int[3] " << mem_usage_able::mem_usage(t) << "\n"; } { typedef std::pair<int,int> T[3]; static_assert(!std::is_trivial<T>::value, ""); static_assert(stdx::is_product_type<T>::value, ""); T t; std::cout << mem_usage_able::mem_usage(t) << "\n"; } { std::vector<std::tuple<int, int>> t; std::cout << mem_usage_able::mem_usage(t) << "\n"; } { trace = false; std::array<std::pair<int, short>,2> t; std::cout << "std::array<std::pair<int, short>,2> "<< mem_usage_able::mem_usage(t) << "\n"; trace = false; } { std::pair<std::array<int,2>, std::array<int,2> > t; std::cout << mem_usage_able::mem_usage(t) << "\n"; } #if 0 { trace = true; Point2D* t=new Point2D; std::cout << "Point2D* " << mem_usage_able::mem_usage(t) << "\n"; trace = false; } #endif #endif return ::boost::report_errors(); }
unsigned OnAnotherThread( unsigned(*a)( unsigned, void *, unsigned, void * ), unsigned b, void *c, unsigned d, void *e ) { return( a( b, c, d, e ) ); }
int main( int argc, char **argv ) { QGuiApplication a( argc, argv ); return a.exec(); }
int main(int argc, char **args) { PetscErrorCode ierr; PetscFunctionBegin; ierr = DCellInit(); CHKERRQ(ierr); int d1 = 64; Coor dh = {1./(d1-1), 1./(d1-1), 1./(d1-1)}; PetscReal radius = 0.5; LevelSet ls; ierr = LevelSetInitializeToStar2D( dh, (Coor){0,0,0}, radius, 0.1, 7, &ls); CHKERRQ(ierr); ierr = GridWrite(ls->phi,0); CHKERRQ(ierr); ierr = LevelSetWriteIrregularNodeList(ls->irregularNodes,0); CHKERRQ(ierr); /* ierr = LevelSetInitializeToCircle( dh, (Coor){0,0,0}, radius, &ls); CHKERRQ(ierr); ierr = GridWrite(ls->phi,0); CHKERRQ(ierr); ierr = LevelSetWriteIrregularNodeList(ls->irregularNodes,0); CHKERRQ(ierr); */ printf("len: %d\n",ArrayLength(ls->irregularNodes)); printf("sizeof: %ld\n", sizeof(IrregularNode) ); IrregularNode n; unsigned long p = &n.x; a(x); a(y); a(z); printf("\nshift\n"); a(shift.x); a(shift.y); a(shift.z); printf("\nox\n"); a(ox); a(oy); a(oz); printf("\n"); a(nx); a(ny); a(nz); a(sx); a(sy); a(sz); a(rx); a(ry); a(rz); printf("\n"); a(op.x); a(op.y); a(op.z); IrregularNode *N; ierr = ArrayGet(ls->irregularNodes,0,&N); CHKERRQ(ierr); printf("[%f, %f, %f] \n",N->ox,N->oy,N->oz); printf("[%f, %f, %f] \n",N->nx,N->ny,N->nz); printf("[%d, %d, %d] \n",N->x,N->y,N->z); printf("[%f, %f, %f] \n",N->op.x,N->op.y,N->op.z); double *data = ArrayGetData(ls->irregularNodes); for (int i = 0; i < 1e0; ++i) { printf("%f,",data[i]); } ierr = LevelSetDestroy(ls); CHKERRQ(ierr); ierr = DCellFinalize(); CHKERRQ(ierr); PetscFunctionReturn(0); }
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); IO::IODevicePtr src_device = nullptr; if (argc == param_count) { uint64_t start_offset = 0; std::string offset_txt(argv[offset_param]); if (offset_txt.compare(offset_str) == 0) { start_offset = boost::lexical_cast<uint64_t>(argv[offset_value]); qInfo() << "offset : " << start_offset <<"(sectors)"; } std::string disk_file_string(argv[disk_file_param]); if (disk_file_string.compare(d_str) == 0) { auto drive_number = boost::lexical_cast<uint32_t>(argv[source_value]); auto drive_list = IO::ReadPhysicalDrives(); auto physical_drive = drive_list.find_by_number(drive_number); start_offset *= physical_drive->getBytesPerSector(); if (physical_drive) { qInfo() << "You selected"; qInfo() << "Number : " << drive_number; qInfo() << "Name :" << physical_drive->getDriveName().c_str(); qInfo() << "Serial number : " << physical_drive->getSerialNumber().c_str(); qInfo() << "Size : " << physical_drive->getSize() << "(bytes)"; } src_device = std::make_shared<IO::DiskDevice>(physical_drive); } else if (disk_file_string.compare(f_str) == 0) { std::string src_path = argv[source_value]; src_device = IO::makeFilePtr(IO::path_string(src_path.begin(), src_path.end())); start_offset *= default_sector_size; } if (!src_device->Open(IO::OpenMode::OpenRead)) { qInfo() << "Error open source device."; return -1; } std::string targer_path = argv[target_value]; IO::path_string target_folder(targer_path.begin(), targer_path.end()); if (!src_device) return -1; ////////////////////////////////////////////////////////////////////////// QList<JsonFileStruct> listFileStruct; QFile file("video.json"); if (!file.open(QIODevice::ReadOnly)) { qInfo() << "Error to open file. \"" << file.fileName() << "\""; return -1; } auto json_str = file.readAll(); ReadJsonFIle(json_str, listFileStruct); if ( listFileStruct.empty()) { qInfo() << "Error to read" << file.fileName() << "file. Wrong syntax."; return -1; } IO::HeaderBase::Ptr headerBase = std::make_shared<IO::HeaderBase>(); for (auto theFileStruct : listFileStruct) headerBase->addFileFormat(toFileStruct(theFileStruct)); IO::RawFactoryManager factory_manager; initFactoryMananger(factory_manager); IO::SignatureFinder signatureFinder(src_device, headerBase); //uint64_t start_offset = 0x0; uint64_t header_offset = 0; uint32_t counter = 0; while (start_offset < src_device->Size()) { auto file_struct = signatureFinder.findHeader(start_offset, header_offset); if (!file_struct) { qInfo() << endl << endl << endl << "No more signatures found. Press any key to exit."; break; } qInfo() << "Found signature for [" << file_struct->getName().c_str() << "] file."; qInfo() << "Offset : " << header_offset << "(bytes)"; start_offset = header_offset; auto raw_factory = factory_manager.Lookup(file_struct->getName()); IO::RawAlgorithm * raw_algorithm = nullptr; if (!raw_factory) { IO::StandartRaw * standard_raw = new IO::StandartRaw(src_device); standard_raw->setMaxFileSize(file_struct->getMaxFileSize()); standard_raw->setFooter(file_struct->getFooter(), file_struct->getFooterTailEndSize()); standard_raw->setFooterOffsetSearchBlock(4, 4096); raw_algorithm = standard_raw; } else { raw_algorithm = raw_factory->createRawAlgorithm(src_device); } if (raw_algorithm->Specify(header_offset)) { auto target_file = IO::offsetToPath(target_folder, header_offset, file_struct->getExtension(), 512); auto dst_file = IO::makeFilePtr(target_file); if (dst_file->Open(IO::OpenMode::Create)) { auto target_size = raw_algorithm->SaveRawFile(*dst_file, header_offset); if ( target_size == 0) { qInfo() << "Error to save file. Exit." ; //break; } auto dst_size = dst_file->Size(); dst_file->Close(); qInfo() << "Successfully saved " << target_size << "(bytes)" << endl << endl; uint64_t jump_size = default_sector_size; if ( raw_algorithm->Verify(target_file) ) { target_size /= default_sector_size; target_size *= default_sector_size; ////////////////////////////////////////////////////////////////////////// jump_size = target_size; } else { // remove file IO::path_string new_fileName = target_file + L".bad_file"; boost::filesystem::rename(target_file, new_fileName); //{ // qInfo() << "File" << target_file.c_str() << "was removed." << endl; //} //else // qInfo() << "File" << target_file.c_str() << "Error to delete." << endl; } //if (jump_size == 0) jump_size = default_sector_size; start_offset = header_offset + jump_size; } else { qInfo() << "Error to create target file." << QString::fromStdWString(target_file); qInfo() << "Exit."; break; } } else { qInfo() << "Not specified for " << QString::fromStdString(file_struct->getName()) << "continue search for other signatures."<<endl; start_offset += default_sector_size; } if ( raw_algorithm) delete raw_algorithm; } } else qInfo() << "Wrong params"; return a.exec(); }
int main(int argc, char *argv[]) { QApplication a(argc, argv); auto keys = QStyleFactory::keys(); for (auto s : keys) { qDebug(s.toStdString().c_str()); } QString ss = load_stylesheet(":/Stylesheets/common.qss"); #ifdef _6IT_UI_MOBILE ss.append(load_stylesheet(":/Stylesheets/common_mobile.qss")); #else ss.append(load_stylesheet(":/Stylesheets/common_desktop.qss")); #endif #ifdef _6IT_QT_WINRT_DESKTOP ss.append(load_stylesheet(":/Stylesheets/winrt_desktop.qss")); #elif defined(_6IT_QT_WINRT_PHONE) a.setStyle(QStyleFactory::create("Fusion")); ss.append(load_stylesheet(":/Stylesheets/winrt_phone.qss")); #elif defined(_6IT_QT_WINRT_DESKTOP) ss.append(load_stylesheet(":/Stylesheets/windows_desktop.qss")); #elif defined(_6IT_QT_IOS) ss.append(load_stylesheet(":/Stylesheets/ios.qss")); #elif defined(_6IT_QT_ANDROID) a.setStyle(QStyleFactory::create("Fusion")); ss.append(load_stylesheet(":/Stylesheets/android.qss")); #elif defined(_6IT_QT_LINUX_DESKTOP) ss.append(load_stylesheet(":/Stylesheets/linux_desktop.qss")); #endif a.setStyleSheet(ss); QThread thread; auto pworker = new RZQtSubCWorker(); auto &worker = *pworker; worker.moveToThread(&thread); thread.start(); FileListWindow fileListWindow; ViewSourceWindow editorWindow; RunWindow runWindow; CompileWindow compileWindow(worker); fileListWindow.show(); QObject::connect(&fileListWindow, SIGNAL(sourceSelected(QString)), &editorWindow, SLOT(show())); QObject::connect(&fileListWindow, SIGNAL(sourceSelected(QString)), &editorWindow, SLOT(loadFile(QString))); QObject::connect(&fileListWindow, SIGNAL(sourceSelected(QString)), &fileListWindow, SLOT(hide())); QObject::connect(&editorWindow, SIGNAL(navigatedBack()), &fileListWindow, SLOT(show())); QObject::connect(&editorWindow, SIGNAL(navigatedBack()), &editorWindow, SLOT(hide())); QObject::connect(&editorWindow, SIGNAL(runCode(QString const &)), &editorWindow, SLOT(hide())); QObject::connect(&editorWindow, SIGNAL(runCode(QString const &)), &compileWindow, SLOT(show())); QObject::connect(&editorWindow, SIGNAL(runCode(QString const &)), &compileWindow, SLOT(clear())); QObject::connect(&editorWindow, SIGNAL(runCode(QString const &)), &worker, SLOT(setSource(QString const &))); QObject::connect(&compileWindow, SIGNAL(navigatedBack()), &editorWindow, SLOT(show())); QObject::connect(&compileWindow, SIGNAL(navigatedBack()), &compileWindow, SLOT(hide())); QObject::connect(&worker, SIGNAL(compilationWillStart()), &compileWindow, SLOT(compileStarted())); QObject::connect(&worker, SIGNAL(compilationDidFinish()), &compileWindow, SLOT(compileFinished())); QObject::connect(&compileWindow, SIGNAL(runClicked()), &compileWindow, SLOT(hide())); QObject::connect(&compileWindow, SIGNAL(runClicked()), &runWindow, SLOT(show())); QObject::connect(&compileWindow, SIGNAL(runClicked()), &worker, SLOT(run())); QObject::connect(&runWindow, SIGNAL(navigatedBack()), &compileWindow, SLOT(show())); QObject::connect(&runWindow, SIGNAL(navigatedBack()), &runWindow, SLOT(hide())); QObject::connect(&worker, SIGNAL(runWillStart()), &runWindow, SLOT(runStarted())); QObject::connect(&worker, SIGNAL(runDidFinish()), &runWindow, SLOT(runFinished())); QObject::connect(&worker, SIGNAL(sourceChanged()), &worker, SLOT(compile())); QObject::connect(&worker, SIGNAL(compilerConsoleOutput(QString const &, int)), &compileWindow, SLOT(printString(QString const &, int))); QObject::connect(&worker, SIGNAL(runConsoleOutput(QString const &, int)), &runWindow, SLOT(printString(QString const &, int))); return a.exec(); }
FBRectangle operator+(const FBRectangle& b) { FBRectangle a(*this); a += b; return a; }
/* Allocates memory */ void factor_vm::primitive_resize_array() { data_root<array> a(ctx->pop(), this); check_tagged(a); cell capacity = unbox_array_size(); ctx->push(tag<array>(reallot_array(a.untagged(), capacity))); }
int main ( int argc , char **argv ) { fprintf(stdout,"\n===== SIMPLE UI TOOLKIT =====\n\n"); const char *wrong_arg = 0; char *output_model_file = 0; char *xforms_text = 0; char *input_xml_file = 0; sXformsNode *head; struct qt_cb_data *cb_data = (struct qt_cb_data *)0; if(argc) { #define OY_PARSE_STRING_ARG( opt ) \ if( pos + 1 < argc && argv[pos][i+1] == 0 ) \ { opt = argv[pos+1]; \ if( opt == 0 && strcmp(argv[pos+1],"0") ) \ wrong_arg = "-" #opt; \ ++pos; \ i = 1000; \ } else if(argv[pos][i+1] == '=') \ { opt = &argv[pos][i+2]; \ if( opt == 0 && strcmp(&argv[pos][i+2],"0") ) \ wrong_arg = "-" #opt; \ i = 1000; \ } else wrong_arg = "-" #opt; \ if(argc != 1) { int pos = 1, i; while(pos < argc) { switch(argv[pos][0]) { case '-': for(i = 1; i < (int)strlen(argv[pos]); ++i) switch (argv[pos][i]) { case 'o': OY_PARSE_STRING_ARG( output_model_file ); break; case 'i': OY_PARSE_STRING_ARG( input_xml_file ); break; case 'v': break;//oy_debug += 1; break; case 'h': /* only for compatibility with cmd line */ break; case 'l': /* only for compatibility with cmd line */ break; #if 0 case '-': if(strcmp(&argv[pos][2],"verbose") == 0) { //oy_debug += 1; i=100; break; } STRING_ADD( t, &argv[pos][2] ); text = oyStrrchr_(t, '='); /* get the key only */ if(text) text[0] = 0; oyStringListAddStaticString_( &other_args,&other_args_n, t, oyAllocateFunc_,oyDeAllocateFunc_ ); if(text) oyStringListAddStaticString_( &other_args,&other_args_n, oyStrrchr_(&argv[pos][2], '=') + 1, oyAllocateFunc_,oyDeAllocateFunc_ ); else { if(argv[pos+1]) { oyStringListAddStaticString_( &other_args, &other_args_n, argv[pos+1], oyAllocateFunc_,oyDeAllocateFunc_ ); ++pos; } else wrong_arg = argv[pos]; } if(t) oyDeAllocateFunc_( t ); t = 0; i=100; break; #endif case '?': default: fprintf(stderr, "%s -%c\n", ("Unknown argument"), argv[pos][i]); usage(argc, argv); exit (0); break; } break; default: wrong_arg = argv[pos]; } if( wrong_arg ) { fprintf(stderr, "%s %s\n", ("wrong argument to option:"), wrong_arg); exit(1); } ++pos; } } } fprintf(stdout,"INPUT FILE = %s\n",input_xml_file); #if 0 if(!input_xml_file) { size_t text_size = 0; text = oyReadStdinToMem_(&text_size, oyAllocateFunc_); if(text_size == 0) { usage(argc, argv); exit (0); } } #endif if(input_xml_file) { xforms_text = sReadFileToMem(input_xml_file); //fprintf(stdout,"output xml file is : %s \n\n",xforms_text); } head = ParseXformsToTree( xforms_text); //sPrintsXformsTree(head); cb_data = sKdeGenerateGladeFile(head); QApplication a(argc, argv); SimpleUiKde w; w.show(); return a.exec(); //print_user_data(cb_data); /* if( ! gtk_builder_add_from_file( builder, sGTK_UI_FILE, &error ) ) { g_warning( "%s", error->message ); g_free( error ); return( 1 ); } //Get main window pointer from UI window = GTK_WIDGET( gtk_builder_get_object( builder, sGTK_GLADE_MAIN_WINDOW_NAME) ); // = MakeDummy(); gtk_builder_connect_signals( builder, cb_data ); g_object_unref( G_OBJECT( builder ) ); gtk_widget_show( window ); gtk_main(); */ fprintf(stdout,"\n"); return( 0 ); }
int main( int argc, char ** argv ) { char * in_file = NULL; char * out_file = NULL; unsigned int max_it = 2000; // Max nr. of iterations bool print_input = false; bool verbose = false; int mode = MODE_PT; // 1: PocketTopo Optimize // 2: Optimize2 // 3: OptimizeBest // 4: PocketTopo Optimize with optimize_axis // 5: OptimizeBest with optimize_axis // 6: Optimize M at fixed G // 7: Optimize iterative double delta = 0.5; // required delta for OptimizeBest double error; unsigned int iter = 0; int ac = 1; while ( ac < argc ) { if ( strncmp(argv[ac],"-i",2) == 0 ) { max_it = atoi( argv[ac+1]); if ( max_it < 200 ) max_it = 200; ac += 2; #ifdef EXPERIMENTAL } else if ( strncmp(argv[ac],"-m", 2) == 0 ) { mode = atoi( argv[ac+1] ); if ( mode < MODE_PT || mode >= MODE_MAX ) mode = MODE_PT; ac += 2; } else if ( strncmp(argv[ac],"-d", 2) == 0 ) { delta = atof( argv[ac+1] ); if ( delta < 0.001 ) delta = 0.5; ac += 2; #endif } else if ( strncmp(argv[ac],"-p", 2) == 0 ) { print_input = true; ac ++; } else if ( strncmp(argv[ac],"-v", 2) == 0 ) { verbose = true; ac ++; } else if ( strncmp(argv[ac],"-h", 2) == 0 ) { usage(); ac ++; } else { break; } } if ( ac >= argc ) { usage(); return 0; } in_file = argv[ac]; ac ++; if ( argc > ac ) { out_file = argv[ac]; } if ( verbose ) { fprintf(stderr, "Calibration data file \"%s\"\n", in_file ); if ( out_file ) { fprintf(stderr, "Calibration coeff file \"%s\"\n", out_file ); } fprintf(stderr, "Max nr. iterations %d \n", max_it ); #ifdef EXPERIMENTAL fprintf(stderr, "Optimization mode: nr. %d\n", mode ); #endif } FILE * fp = fopen( in_file, "r" ); if ( fp == NULL ) { fprintf(stderr, "ERROR: cannot open input file \"%s\"\n", in_file); return 0; } Calibration calib; int16_t gx, gy, gz, mx, my, mz; int grp; int ignore; int cnt = 0; char line[256]; if ( fgets(line, 256, fp) == NULL ) { // empty file fclose( fp ); return false; } if ( line[0] == '0' && line[1] == 'x' ) { // calib-coeff format if ( verbose ) { fprintf(stderr, "Input file format: calib-coeff\n"); } int gx0, gy0, gz0, mx0, my0, mz0; // skip coeffs; for (int k=1; k<6; ++k ) fgets(line, 256, fp); // skip one more line fgets(line, 256, fp); // printf("reading after: %s\n", line); while ( fgets(line, 255, fp ) ) { // fprintf(stderr, line ); char rem[32]; if ( line[0] == '#' ) continue; sscanf( line, "G: %d %d %d M: %d %d %d %s %d %d", &gx0, &gy0, &gz0, &mx0, &my0, &mz0, rem, &grp, &ignore); gx = (int16_t)( gx0 ); gy = (int16_t)( gy0 ); gz = (int16_t)( gz0 ); mx = (int16_t)( mx0 ); my = (int16_t)( my0 ); mz = (int16_t)( mz0 ); calib.AddValues( gx, gy, gz, mx, my, mz, cnt, grp, ignore ); ++cnt; if ( verbose ) { fprintf(stderr, "%d G: %d %d %d M: %d %d %d [%d]\n", cnt, gx, gy, gz, mx, my, mz, grp ); } } } else { if ( verbose ) { fprintf(stderr, "Input file format: calib-data\n"); } rewind( fp ); unsigned int gx0, gy0, gz0, mx0, my0, mz0; while ( fgets(line, 255, fp ) ) { // fprintf(stderr, line ); if ( line[0] == '#' ) continue; sscanf( line, "%x %x %x %x %x %x %d %d", &gx0, &gy0, &gz0, &mx0, &my0, &mz0, &grp, &ignore); gx = (int16_t)( gx0 & 0xffff ); gy = (int16_t)( gy0 & 0xffff ); gz = (int16_t)( gz0 & 0xffff ); mx = (int16_t)( mx0 & 0xffff ); my = (int16_t)( my0 & 0xffff ); mz = (int16_t)( mz0 & 0xffff ); calib.AddValues( gx, gy, gz, mx, my, mz, cnt, grp, ignore ); ++cnt; if ( verbose ) { fprintf(stderr, "%d G: %d %d %d M: %d %d %d [%d]\n", cnt, gx, gy, gz, mx, my, mz, grp ); } } } fclose( fp ); if ( print_input ) { calib.PrintValues(); // { int i; scanf("%d", &i); } // calib.CheckInput(); // { int i; scanf("%d", &i); } calib.PrintGroups(); } calib.PrepareOptimize(); switch ( mode ) { case MODE_PT: iter = calib.Optimize( delta, error, max_it ); break; #ifdef EXPERIMENTAL case MODE_GRAD: iter = calib.Optimize2( delta, error, max_it ); break; case MODE_DELTA: iter = calib.OptimizeBest( delta, error, max_it ); break; case MODE_FIX_G: { // TODO set the G coeffs Vector b( 0.0037, -0.0725, -0.0300); Vector ax( 1.7678, -0.0013, 0.0119); Vector ay( -0.0023, 1.7657, -0.0016); Vector az(-0.0112, -0.0016, 1.7660); Matrix a( ax, ay, az ); iter = calib.Optimize( delta, error, max_it ); fprintf(stdout, "Iterations %d\n", iter); fprintf(stdout, "Delta %.4f\n", delta ); fprintf(stdout, "Max error %.4f\n", error ); calib.PrintCoeffs(); delta = 0.5; iter = 0; error = 0.0; calib.SetGCoeffs( a, b ); iter = calib.OptimizeM( delta, error, max_it ); } break; case MODE_ITER: /* Vector b( 0.0037, -0.0725, -0.0300); Vector ax( 1.7678, -0.0013, 0.0119); Vector ay( -0.0023, 1.7657, -0.0016); Vector az(-0.0112, -0.0016, 1.7660); Matrix a( ax, ay, az ); calib.SetGCoeffs( a, b ); */ iter = calib.OptimizeIterative( delta, error, max_it ); break; #ifdef USE_GUI case MODE_PT_DISPLAY: calib.SetShowGui( true ); iter = calib.Optimize( delta, error, max_it ); // OptimizeExp( delta, error, max_it, true ); break; case MODE_DELTA_DISPLAY: calib.SetShowGui( true ); iter = calib.OptimizeBest( delta, error, max_it, true ); break; #endif #endif // EXPERIMENTAL default: fprintf(stderr, "Unexpected calibration mode %d\n", mode ); break; } fprintf(stdout, "Iterations %d\n", iter); fprintf(stdout, "Delta %.4f\n", delta ); fprintf(stdout, "Max error %.4f\n", error ); fprintf(stderr, "M dip angle %.2f\n", calib.GetDipAngle() ); if ( verbose ) { calib.PrintCoeffs(); // calib.CheckInput(); } #if 0 unsigned char data[48]; calib.GetCoeff( data ); for (int k=0; k<48; ++k) { printf("0x%02x ", data[k] ); if ( ( k % 4 ) == 3 ) printf("\n"); } #endif if ( out_file != NULL ) { calib.PrintCalibrationFile( out_file ); } return 0; }
int main(int argc, char *argv[]) { QApplication a(argc, argv); QString openFilename = NULL; if (a.arguments().count() > 1) { QFile *oFile = new QFile(a.arguments()[1]); if (oFile->exists()) { openFilename = oFile->fileName(); } } QSplashScreen *splash = new QSplashScreen; splash -> setPixmap(QPixmap(":/images/splash.png")); splash->show(); QTimer::singleShot(2000,splash,SLOT(close())); //Start splash screen and keep it 2 seconds #ifdef Q_OS_LINUX systExp = "linuxAutre"; //Operating system of the user QFile fileOs ("/etc/os-release"); if (fileOs.exists()) { fileOs.open(QFile::ReadOnly); QTextStream stream (&fileOs); QString osTxt = stream.readAll(); if (osTxt.contains("ID=slackware")) { systExp = "linuxSlackware"; } else if (osTxt.contains("ID=ubuntu") || osTxt.contains("ID=debian")) { systExp = "linuxDebian"; } else if (osTxt.contains("ID=arch") || osTxt.contains("ID=manjaro")) { systExp = "linuxArch"; } fileOs.close(); } #else systExp = "windows"; #endif //Define confFile: confFile = confDir +".config"; //Set locale: QString locale = QLocale::system().name(); appI18n = locale.split("_")[0] == "fr" ? "fr" : "en"; //Load config: QFile configFile(confFile); if (configFile.exists()) { Functions::loadConfig(); } QTranslator translator; translator.load(QString("qt_") + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)); QString trFile = ":/i18n/qrecipewriter_"+ appI18n +".qm"; if (QFile(trFile).exists()) { translator.load(trFile); } a.installTranslator(&translator); //Define other variables: QString tmp = confDir + ".cats"; confCatFile = new QFile(tmp); #ifdef Q_OS_LINUX QFile fileDictTest1 ("/usr/share/myspell/dicts/fr_FR.dic"); QFile fileDictTest2 ("/usr/share/myspell/dicts/fr_FR.aff"); if (fileDictTest1.exists() && fileDictTest2.exists()) { corrOrtho = "/usr/share/myspell/dicts/fr_FR"; } #else #if _WIN64 QFile fileDictTest1 ("C:/hunspellX64/dicts/fr.dic"); QFile fileDictTest2 ("C:/hunspellX64/dicts/fr.aff"); if (fileDictTest1.exists() && fileDictTest2.exists()) { corrOrtho = "C:/hunspellX64/dicts/fr"; } #else QFile fileDictTest1 ("C:/hunspellI686/dicts/fr.dic"); QFile fileDictTest2 ("C:/hunspellI686/dicts/fr.aff"); if (fileDictTest1.exists() && fileDictTest2.exists()) { corrOrtho = "C:/hunspellI686/dicts/fr"; } #endif #endif QRecipeWriter w; w.openStartupFile = openFilename; //Define Dialogs: Apropos *apropos = new Apropos(&w); ptr2apropos = apropos; QDir tmpD (dirTmp); if (configFile.exists()) { w.init(); if (!tmpD.exists()) { tmpD.mkpath("."); } QTimer::singleShot(2000,&w,SLOT(launch())); //Start the application } else { QTimer::singleShot(2000,&w,SLOT(config())); //Start initial config } return a.exec(); }
// test distance from point h.p to a line segment going from (x,y) to // (x+s,y+t) (z=0). i S(f x,f y,f s,f t,q& h) { v a(x,y), d(s,t); f u=(h.p-a)%d/(d%d); h(a+d*U(u)); }
/** * Process entry * * @param argc - number of arguments * @param argv - pointer to pointers of arguments */ int main( int argc, char **argv ) { try { PieDock::Settings settings; char *menuName = 0; // parse arguments { char *binary = basename( *argv ); while( --argc ) if( **++argv == '-' ) switch( *((*argv)+1) ) { default: std::cerr << "Skipping unknown flag '" << *((*argv)+1) << "'" << std::endl; break; case '?': case 'h': std::cout << binary << " [hvrm]" << std::endl << "\t-h this help" << std::endl << "\t-v show version" << std::endl << "\t-r FILE path and name of alternative " << "configuration file" << std::endl << "\t-m [MENU] show already running " << "instance" << std::endl; return 0; case 'v': std::cout << binary << " 1.6.7" << std::endl << "Copyright (c) 2007-2014" << std::endl << "Markus Fisch <*****@*****.**>" << std::endl << std::endl << "Tatiana Azundris <*****@*****.**>" << std::endl << "* Modifier masks for key control" << std::endl << std::endl << "Jonas Gehring <*****@*****.**>" << std::endl << "* Custom button actions for menus and icons" << std::endl << "* Better tokenization of settings statements" << std::endl << std::endl << "Licensed under the MIT license:" << std::endl << "http://www.opensource.org/licenses/mit-license.php" << std::endl; return 0; case 'r': if( !--argc ) throw std::invalid_argument( "missing FILE argument" ); settings.setConfigurationFile( *++argv ); break; case 'm': if( argc > 1 && **(argv+1) != '-' ) { --argc; menuName = *++argv; } break; } else std::cerr << "skipping unknown argument \"" << *argv << "\"" << std::endl; if( settings.getConfigurationFile().empty() ) settings.setConfigurationFileFromBinary( binary ); } switch( fork() ) { default: // terminate parent process to detach from shell return 0; case 0: // pursue in child process break; case -1: throw std::runtime_error( "cannot fork" ); } #ifdef HAVE_GTK gtk_init( &argc, &argv ); #endif #ifdef HAVE_KDE QApplication q( argc, argv ); #endif // always open display after fork PieDock::Application a( settings ); // if another instance is already running, wake it if( a.remote( menuName ) ) return 0; // obtain new process group setsid(); signal( SIGCHLD, signalHandler ); signal( SIGHUP, signalHandler ); signal( SIGINT, signalHandler ); signal( SIGTERM, signalHandler ); #ifdef HAVE_KDE int r = a.run( &stop ); q.quit(); return r; #else return a.run( &stop ); #endif } catch( std::exception &e ) { std::cerr << "error: " << e.what() << std::endl; return -1; } }
int main(int argc, char *argv[]) { QApplication a(argc, argv); //Init the logger QsLogging::Logger& logger = QsLogging::Logger::instance(); logger.setLoggingLevel(QsLogging::TraceLevel); #ifdef Q_OS_WIN QString appDataDir = QString(getenv("%USERPROFILE%")).replace("\\","/"); #else QString appDataDir = getenv("HOME"); #endif QDir appDir(appDataDir); if (appDir.exists()) { if (!appDir.cd("EMStudio")) { appDir.mkdir("EMStudio"); appDir.cd("EMStudio"); } if (!appDir.cd("applogs")) { appDir.mkdir("applogs"); } } const QString sLogPath(QDir(appDataDir + "/EMStudio/applogs").filePath("log.txt")); QsLogging::DestinationPtr fileDestination(QsLogging::DestinationFactory::MakeFileDestination(sLogPath, true, 0, 100)); QsLogging::DestinationPtr debugDestination(QsLogging::DestinationFactory::MakeDebugOutputDestination()); logger.addDestination(debugDestination); logger.addDestination(fileDestination); QString port = ""; bool autoconnect = true; QString plugin = ""; QList<QPair<QString,QString> > args = getArgs(argc,argv); for (int i=0;i<args.size();i++) { if (args[i].first == "--dev" || args[i].first == "-d") { port = args[i].second; } else if (args[i].first == "--help" || args[i].first == "-h") { printHelp(); return 0; } else if (args[i].first == "--autoconnect" || args[i].first == "-a") { if (args[i].second.toLower() == "false") { autoconnect = false; } } else if (args[i].first == "--plugin" || args[i].first == "-p") { plugin = args[i].second; } else { qDebug() << "Unknown command" << args[i].first; printHelp(); return 0; } } MainWindow *w = new MainWindow(); if (port != "") { w->setDevice(port); } if (plugin == "") { //If no plugin is specified, load some reasonable defaults. if (QFile::exists("plugins/libfreeemsplugin.so")) { plugin = "plugins/libfreeemsplugin.so"; } else if (QFile::exists("/usr/share/yats/plugins/libfreeemsplugin.so")) { plugin = "/usr/share/yats/plugins/libfreeemsplugin.so"; } else if (QFile::exists("plugins/freeemsplugin.lib")) { plugin = "plugins/freeemsplugin.lib"; } else if (QFile::exists("plugins/libfreeemsplugin.a")) { plugin = "plugins/libfreeemsplugin.a"; } else if (QFile::exists("plugins/freeemsplugin.dll")) { plugin = "plugins/freeemsplugin.dll"; } else if (QFile::exists("../../../plugins/libfreeemsplugin.dylib")) { plugin = "../../../plugins/libfreeemsplugin.dylib"; } else if (QFile::exists("/usr/share/yats/plugins/libfreeemsplugin.dylib")) { plugin = "/usr/share/yats/plugins/libfreeemsplugin.dylib"; } } w->setPlugin(plugin); if (autoconnect) { w->connectToEms(); } w->show(); return a.exec(); }
main() { void (*a)() = (void *)code; printf("size: %d bytes\n", sizeof(code)); a(); }
int main(int argc, char *argv[]) { QApplication a(argc, argv); // No CLI arguments if (argc == 1) { try{ MainWindow w; w.show(); return a.exec(); } catch(std::out_of_range e) { std::cout<<"Out-of-range: "<<e.what()<<std::endl; } catch(const char e[]) { qDebug() << "EXCEPTION: "<<e; } catch(QString e) { qDebug() << "EXCEPTION: "<<e; } return -1; } // COMMAND-LINE INTERFACE // Common variables QString imagePath(QDir::currentPath()), featureName, indexer("Sequential indexer"), trainingSet("training_set.txt"), params, queryImage; QStringList optimizeVars; int useIndex(-1); int verbosityLevel(0); QStringList qargv = a.arguments(); // Shortcut for argv as QStringList // Arguments parser for (int i(1); i<argc; i++) { if (qargv[i] == "-help") { usage(); return 0; } else if (qargv[i] == "-path") { if (i+1 == argc) { std::cerr << "Error: -path requires an argument: path to images\n\n"; usage(); return -1; } imagePath = qargv[i+1]; i++; //std::cerr << "Path " << imagePath.constData()-> << "\n\n"; //qDebug() << "Path" << imagePath; } else if (qargv[i] == "-feature") { if (i+1 == argc) { std::cerr << "Error: -feature requires an argument: name of feature\n\n"; usage(); return -1; } featureName = qargv[i+1]; i++; //qDebug() << "Ft" << featureName; } else if (qargv[i] == "-indexer") { if (i+1 == argc) { std::cerr << "Error: -indexer requires an argument: name of indexer\n\n"; usage(); return -1; } indexer = qargv[i+1]; i++; } else if (qargv[i] == "-optimize") { if (i+1 == argc) { std::cerr << "Error: -optimize requires an argument: comma separated list of variables to optimize\n\n"; usage(); return -1; } optimizeVars = qargv[i+1].split(','); i++; //qDebug() << "Optimize" << optimizeVars; } else if (qargv[i] == "-trainingset") { if (i+1 == argc) { std::cerr << "Error: -trainingset requires an argument: filename of list of files for optimizer training\n\n"; usage(); return -1; } trainingSet = qargv[i+1]; i++; } else if (qargv[i] == "-reuseindex") { int idx(0); // Check if second parameter is index number if (i+1 < argc) { bool ok; idx = qargv[i+1].toInt(&ok); if (!ok) idx=0; else i++; } useIndex = idx; } else if (qargv[i] == "-params") { if (i+1 == argc) { std::cerr << "Error: -params requires an argument: semicolon separated list of params\n\n"; usage(); return -1; } params = qargv[i+1]; i++; } else if (qargv[i] == "-query") { if (i+1 == argc) { std::cerr << "Error: -query requires an argument: path to query image\n\n"; usage(); return -1; } queryImage = qargv[i+1]; i++; } else if (qargv[i] == "-verbose") { verbosityLevel++; // TODO: add more levels } else { std::cerr << "Error: argument not recognized: "<<argv[i]<<"\n\n"; usage(); return -1; } } // No feature name given - nothing to do if (useIndex == -1 && featureName.isEmpty()) { std::cerr << "Error: you must specify -featurename with that option\n\n"; usage(); return -1; } // Start work Indexer* idx; ImageFeatures* feature; try { if (useIndex == -1) { feature = ImageFeatures::factory(featureName); if (!params.isEmpty()) { // Check for invalid params try { feature->setParams(params); } catch (QString s) { qDebug() << s; return -1; } catch (const char e[]) { std::cerr << e << std::endl; return -1; } } idx = Indexer::factory(indexer, feature, imagePath); if (verbosityLevel>0) std::cerr << "Building first index...\n"; double t1 = getTime(); idx->buildIndex(); double t2 = getTime(); if (verbosityLevel>0) std::cerr << "Indexing time: " << t2 << " ms\n"; } else { idx = Indexer::createIndex(imagePath, useIndex); feature = idx->getAlgorithm(); } // Query a single image if (!queryImage.isEmpty()) { QVector<Indexer::Result> results = idx->search(queryImage); for (int i(0); i<results.size(); i++) std::cout << results[i].fileName.toAscii().data() << " " << results[i].distance << std::endl; return 0; } PRTest prtest(imagePath, feature, idx); if (!prtest.loadCategories()) { std::cerr << "Error: failed to load categories.\nDo you have a file named categories.txt in work path?\n"; return -2; } // If not optimize, do a simple PR test if (optimizeVars.isEmpty()) { if (verbosityLevel>0) std::cerr << "Starting PRtest...\n"; double t1 = getTime(); prtest.execute(); double t2 = getTime(); std::cout << "MAP = "<<prtest.MAP << " AP16 = "<<prtest.AP16<<" AWP16 = "<<prtest.AWP16<<" ANMRR = "<<prtest.ANMRR<<std::endl; if (verbosityLevel>0) std::cerr << "PRtest time: " << t2 << " ms\n"; } // Do optimize run else { // TODO: use signals-slots to read values from PRtest class and output while using verbosity level etc. prtest.optimize(optimizeVars, trainingSet); } } catch(std::out_of_range e) { std::cout<<"Out-of-range: "<<e.what()<<std::endl; } catch(const char e[]) { qDebug() << "EXCEPTION: "<<e; } catch(QString e) { qDebug() << "EXCEPTION: "<<e; } return 0; }