void ConsoleProgressImpl::updateView(vector< DownloadRecordForPrint > records, uint8_t overallDownloadPercent, size_t overallEstimatedTime, size_t speed) { // print 'em all! // sort by download numbers std::sort(records.begin(), records.end(), [](const DownloadRecordForPrint& left, const DownloadRecordForPrint& right) { return left.record.number < right.record.number; }); string viewString = format2("%d%% ", overallDownloadPercent); for (const auto& it: records) { string suffix; if (it.record.phase == DownloadRecord::Phase::Postprocessed) { suffix = " | postprocessing"; } else if (it.record.size != (size_t)-1 && it.record.size != 0 /* no sense for empty files */) { suffix = format2("/%s %.0f%%", humanReadableSizeString(it.record.size), (float)it.record.downloadedSize / it.record.size * 100); } viewString += format2("[#%zu %s %s%s]", it.record.number, it.shortAlias, humanReadableSizeString(it.record.downloadedSize), suffix); } auto speedAndTimeAppendage = string("| ") + humanReadableSpeedString(speed) + string(" | ETA: ") + humanReadableDifftimeString(overallEstimatedTime); termPrint(viewString, speedAndTimeAppendage); }
void WorkerBase::p_runCommandWithInput(Logger::Subsystem subsystem, Logger::Level level, const string& command, const CommandInput& input) { auto inputPipeName = format2("input stream for '%s'", command); unique_ptr<Pipe> inputPipe(new Pipe(inputPipeName, true)); ScopedThread inputStreamThread(std::thread(writeBufferToFd, std::ref(*inputPipe), std::cref(input.buffer), std::cref(inputPipeName))); auto fdAmendedCommand = format2("bash -c '(%s) %s'", command, getRedirectionSuffix(inputPipe->getReaderFd(), input.fd)); p_invokeShellCommand(subsystem, level, fdAmendedCommand); readTheRest(*inputPipe); }
main () { printf (MSG ("\nFORMAT 4K %s %s\n", "\nРАЗМЕТКА 4K %s %s\n"), BOOTVERSION, MSG (LCOPYRIGHT, RCOPYRIGHT)); printf (MSG ("\nUsing this program you may OVERWRITE information on your hard disks.\n", "\nПри работе с этой программой Вы можете ЗАТЕРЕТЬ информацию на дисках.\n")); printf (MSG ("\nIt is strongly recommended to TURN unnecessary disks 'READ-ONLY'.\n", "\nНастоятельно рекомендуется ЗАКРЫТЬ ненужные дискм на ЗАПИСЬ.\n")); printf (MSG ("Do you want to continue", "Продолжать")); if (yes () != 1) return; unit = getunit (); nbad = 0; printf (MSG ("\nFormat unit %d", "\nФорматировать устройство %d"), unit); if (yes () != 1) return; /* инициализация переменных и массивов разметки */ init (unit); printf (MSG ("\nINITIAL FORMATTING\n", "\nПЕРВИЧНАЯ РАЗМЕТКА\n")); if (! format1 ()) return; if (nbad) { printf (MSG ("\nBAD TRACKS REMAPPING\n", "\nДЕФЕКТАЦИЯ\n")); if (! format2 ()) return; } printf (MSG ("\nFormat completed.\n", "\nФорматирование закончено.\n")); }
//#include <sys/time.h> void PlainConfigFile::write() const { kdebugf(); /* struct timeval t1,t2; gettimeofday(&t1, NULL); for(int j=0; j<100; ++j) {*/ QFile file(filename); QString line; QStringList out; QString format1("[%1]\n"); QString format2("%1=%2\n"); if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { kdebugm(KDEBUG_INFO, "file opened '%s'\n", qPrintable(file.fileName())); QTextStream stream(&file); stream.setCodec(codec_latin2); foreach(const QString &key, groups.keys()) { // kdebugm(KDEBUG_DUMP, ">> %s\n", (i.key())); out.append(format1.arg(key)); foreach(const QString &dataKey, groups[key].keys()) { QString q = groups[key][dataKey]; out.append(format2.arg(dataKey).arg(q.replace('\n', "\\n"))); // kdebugm(KDEBUG_DUMP, ">>>>> %s %s\n", qPrintable(key()), qPrintable(q)); } out.append("\n"); } stream << out.join(QString::null); file.close(); }
void __init() { setOption(CURLOPT_FAILONERROR, 1, "fail on error"); setOption(CURLOPT_NETRC, CURL_NETRC_OPTIONAL, "netrc"); setOption(CURLOPT_USERAGENT, format2("Curl (libcupt/%s)", cupt::libraryVersion), "user-agent"); curl_easy_setopt(__handle, CURLOPT_ERRORBUFFER, __error_buffer); }
string perform(const shared_ptr< const Config >& /* config */, const download::Uri& uri, const string& targetPath, const std::function< void (const vector< string >&) >& callback) { auto sourcePath = uri.getOpaque(); auto protocol = uri.getProtocol(); // preparing source string openError; File sourceFile(sourcePath, "r", openError); if (!openError.empty()) { return format2("unable to open the file '%s' for reading: %s", sourcePath, openError); } if (protocol == "copy") { return copyFile(sourcePath, sourceFile, targetPath, callback); // full copying } else if (protocol == "file") { // symlinking unlink(targetPath.c_str()); // yep, no error handling; if (symlink(sourcePath.c_str(), targetPath.c_str()) == -1) { return format2e("unable to create symbolic link '%s' -> '%s'", targetPath, sourcePath); } return string(); } else { fatal2i("a wrong scheme '%s' for the 'file' download method", protocol); return string(); // unreachable } }
void ConsoleProgressImpl::newDownload(const DownloadRecord& record, const string& longAlias) { string sizeSuffix; if (record.size != (size_t)-1) { sizeSuffix = string(" [") + humanReadableSizeString(record.size) + "]"; } termClean(); nonBlockingPrint(getNumberPrefix(record.number) + format2("starting %s%s\n", longAlias, sizeSuffix)); }
vector< const SourceVersion* > selectBySourceFse(const Cache& cache, const string& fse, QueryProcessor queryProcessor, bool throwOnError) { auto result = __select_using_function< SourceVersion >(cache, fse, queryProcessor, false, false); if (result.empty()) { string binaryFromSourceFse = format2("binary-to-source(%s)", fse); result = __select_using_function< SourceVersion >(cache, binaryFromSourceFse, queryProcessor, false, throwOnError); } return result; }
void ConsoleProgressImpl::finishedDownload(const string& uri, const string& result, size_t number, bool isOptional) { if (!result.empty()) { // some error occured, output it string toPrint = getNumberPrefix(number); toPrint += isOptional ? "not available\n" : format2("failed: %s (uri '%s')\n", result, uri); termClean(); nonBlockingPrint(toPrint); } }
string convertWildcardedExpressionToFse(const string& expression) { auto getPackageNameFse = [](const string& packageNameExpression) { return format2("package:name(%s)", globToRegexString(packageNameExpression)); }; auto delimiterPosition = expression.find_first_of("/="); if (delimiterPosition != string::npos) { string additionalFseRule; string packageGlobExpression = expression.substr(0, delimiterPosition); string remainder = expression.substr(delimiterPosition+1); if (expression[delimiterPosition] == '/') // distribution { static const sregex distributionExpressionRegex = sregex::compile("[a-z-]+"); static smatch m; if (!regex_match(remainder, m, distributionExpressionRegex)) { fatal2(__("bad distribution '%s' requested, use archive or codename"), remainder); } additionalFseRule = format2("or(release:archive(%s), release:codename(%s))", remainder, remainder); } else // exact version string { checkVersionString(remainder); additionalFseRule = format2("version(%s)", globToRegexString(remainder)); } return format2("%s & %s", getPackageNameFse(packageGlobExpression), additionalFseRule); } else { return getPackageNameFse(expression); } }
string getWaitStatusDescription(int status) { if (status == 0) { return "success"; } else if (WIFSIGNALED(status)) { return format2("terminated by signal '%s'", strsignal(WTERMSIG(status))); } else if (WIFSTOPPED(status)) { return format2("stopped by signal '%s'", strsignal(WSTOPSIG(status))); } else if (WIFEXITED(status)) { return format2("exit code '%d'", WEXITSTATUS(status)); } else { return "unknown status"; } }
bool architectureMatch(const string& architecture, const string& pattern) { static std::map< pair< string, string >, bool > cache; auto key = make_pair(architecture, pattern); auto insertResult = cache.insert(make_pair(key, false /* doesn't matter */)); auto it = insertResult.first; if (insertResult.second) { // new element it->second = !system(format2("dpkg-architecture -a%s -i%s", architecture, pattern).c_str()); } return it->second; }
//THE START OF MOD 1 CODE void project3() { output = fopen("output.txt", "w"); initArray(); //printf("It initialized the arrays\n"); load3(); //testFunction(); format2(); while(1==1) { fetch(); execute(); } }
void Population::Iterate(int times) { _history = 0; float pc; struct basicxmlnode *run = getchildxmlnode(_rootConfig, "Run"); int interval = getchildxmlnodeintvalue(run, "StatusUpdateStep"); double last = -interval; //time_t start_time; //time_t current_time; //time_t span; //time_t est; double start_time; double current_time; double span; double est; double avg; //time(&start_time); start_time = get_time(); for (int n = 0; n < times; n++) { pc = ((float)n) / times * 100; if (last + interval <= pc) { //time(¤t_time); current_time = get_time(); span = current_time - start_time; if (n > 0) avg = (double) span / n; else avg = 0; est = (double) (times * avg); avg = floor(avg * 10000) / 10000; std::cout << "(" << format2((int)pc) << "% of " << times << ") - " << "Elapsed: " << format(span) << " - " << "Estimated: " << format(est) << " - " << "Secs/loop: " << avg << "\n"; last = pc; } _iterate(); //callIterate(); } std::cout << "(100% of " << times << ")\n"; }
string copyFile(const string& sourcePath, File& sourceFile, const string& targetPath, const std::function< void (const vector< string >&) >& callback) { // preparing target string openError; File targetFile(targetPath, "a", openError); if (!openError.empty()) { return format2("unable to open the file '%s' for appending: %s", targetPath, openError); } auto totalBytes = targetFile.tell(); callback(vector< string > { "downloading", lexical_cast< string >(totalBytes), lexical_cast< string >(0)}); { // determing the size struct stat st; if (::stat(sourcePath.c_str(), &st) == -1) { fatal2e(__("%s() failed: '%s'"), "stat", sourcePath); } callback(vector< string > { "expected-size", lexical_cast< string >(st.st_size) }); } { // writing char buffer[4096]; size_t size = sizeof(buffer); while (sourceFile.getBlock(buffer, size), size) { targetFile.put(buffer, size); totalBytes += size; callback(vector< string > { "downloading", lexical_cast< string >(totalBytes), lexical_cast< string >(size)}); } } return string(); }
void WorkerBase::_run_external_command(Logger::Subsystem subsystem, const string& command, const CommandInput& commandInput, const string& errorId) { const Logger::Level level = 3; _logger->log(subsystem, level, format2("running: %s", command)); if (_config->getBool("cupt::worker::simulate")) { if (commandInput.buffer.empty()) { simulate2("running command '%s'", command); } else { simulate2("running command '%s' with the input\n-8<-\n%s\n->8-", command, commandInput.buffer); } } else { const string& id = (errorId.empty() ? command : errorId); if (commandInput.buffer.empty()) { p_invokeShellCommand(subsystem, level, command); } else try { p_runCommandWithInput(subsystem, level, command, commandInput); } catch (...) { _logger->loggedFatal2(subsystem, level, format2, "%s failed", id); } } }
string Resolver::RelationExpressionReason::toString() const { static const map< BinaryVersion::RelationTypes::Type, string > dependencyTypeTranslations = { { BinaryVersion::RelationTypes::PreDepends, __("pre-depends on") }, { BinaryVersion::RelationTypes::Depends, __("depends on") }, { BinaryVersion::RelationTypes::Recommends, __("recommends") }, { BinaryVersion::RelationTypes::Suggests, __("suggests") }, { BinaryVersion::RelationTypes::Conflicts, __("conflicts with") }, { BinaryVersion::RelationTypes::Breaks, __("breaks") }, }; auto dependencyTypeTranslationIt = dependencyTypeTranslations.find(dependencyType); if (dependencyTypeTranslationIt == dependencyTypeTranslations.end()) { warn2(__("unsupported reason dependency type '%s'"), BinaryVersion::RelationTypes::strings[dependencyType]); return string(); } else { return format2("%s %s %s '%s'", version->packageName, version->versionString, dependencyTypeTranslationIt->second, relationExpression.toString()); } }
void TestStyles::testApplyParagraphStyleWithParent() { KoParagraphStyle style1; style1.setStyleId(1002); KoParagraphStyle style2; style2.setStyleId(1003); KoParagraphStyle style3; style3.setStyleId(1004); style3.setParentStyle(&style2); style2.setParentStyle(&style1); style1.setAlignment(Qt::AlignRight); QCOMPARE(style1.alignment(), Qt::AlignRight); QCOMPARE(style2.alignment(), Qt::AlignRight); QCOMPARE(style3.alignment(), Qt::AlignRight); style2.setAlignment(Qt::AlignCenter); QCOMPARE(style1.alignment(), Qt::AlignRight); QCOMPARE(style2.alignment(), Qt::AlignCenter); QCOMPARE(style3.alignment(), Qt::AlignCenter); style3.setAlignment(Qt::AlignLeft | Qt::AlignAbsolute); QCOMPARE(style1.alignment(), Qt::AlignRight); QCOMPARE(style2.alignment(), Qt::AlignCenter); QCOMPARE(style3.alignment(), Qt::AlignLeft | Qt::AlignAbsolute); style3.setLineSpacing(23.45); style3.setLineHeightPercent(150); style3.setLineHeightAbsolute(8.0); QCOMPARE(style3.lineHeightPercent(), 0.0); QCOMPARE(style3.lineHeightAbsolute(), 8.0); QCOMPARE(style3.lineSpacing(), 23.45); QVERIFY(!style3.hasNormalLineHeight()); style3.setNormalLineHeight(); QCOMPARE(style3.lineHeightPercent(), 0.0); QCOMPARE(style3.lineHeightAbsolute(), 0.0); QCOMPARE(style3.lineSpacing(), 0.0); QVERIFY(style3.hasNormalLineHeight()); style3.setLineHeightPercent(150); style3.setLineSpacing(56.78); QCOMPARE(style3.lineHeightPercent(), 150.0); QCOMPARE(style3.lineHeightAbsolute(), 0.0); QCOMPARE(style3.lineSpacing(), 56.78); QVERIFY(!style3.hasNormalLineHeight()); QTextLength length0(QTextLength::FixedLength, 0.0); QTextLength length1(QTextLength::FixedLength, 10.0); QTextLength length2(QTextLength::FixedLength, 20.0); style1.setLeftMargin(length1); QCOMPARE(style1.leftMargin(), 10.0); QCOMPARE(style2.leftMargin(), 10.0); QCOMPARE(style3.leftMargin(), 10.0); style2.setRightMargin(length2); QCOMPARE(style1.rightMargin(), 0.0); QCOMPARE(style2.rightMargin(), 20.0); QCOMPARE(style3.rightMargin(), 20.0); // now actually apply it. QTextBlockFormat rawFormat; style1.applyStyle(rawFormat); KoParagraphStyle format(rawFormat, rawFormat.toCharFormat()); QCOMPARE(rawFormat.properties().count(), 4); QCOMPARE(format.alignment(), Qt::AlignRight); QCOMPARE(rawFormat.property(KoParagraphStyle::StyleId).toInt(), 1002); //since we have not specified any NextStyle it should be the same as the current style QCOMPARE(rawFormat.property(KoParagraphStyle::StyleId).toInt(), rawFormat.property(KoParagraphStyle::NextStyle).toInt()); QCOMPARE(format.leftMargin(), 10.0); QCOMPARE(format.rightMargin(), 0.0); style2.applyStyle(rawFormat); KoParagraphStyle format2(rawFormat, rawFormat.toCharFormat()); QCOMPARE(rawFormat.properties().count(), 5); QCOMPARE(format2.alignment(), Qt::AlignCenter); QCOMPARE(rawFormat.property(KoParagraphStyle::StyleId).toInt(), 1003); //since we have not specified any NextStyle it should be the same as the current style QCOMPARE(rawFormat.property(KoParagraphStyle::StyleId).toInt(), rawFormat.property(KoParagraphStyle::NextStyle).toInt()); QCOMPARE(format2.leftMargin(), 10.0); QCOMPARE(format2.rightMargin(), 20.0); style3.applyStyle(rawFormat); KoParagraphStyle format3(rawFormat, rawFormat.toCharFormat()); QCOMPARE(rawFormat.properties().count(), 9); QCOMPARE(rawFormat.property(KoParagraphStyle::LineSpacing).toReal(), 56.78); QCOMPARE(format3.alignment(), Qt::AlignLeft | Qt::AlignAbsolute); QCOMPARE(rawFormat.property(KoParagraphStyle::StyleId).toInt(), 1004); //since we have not specified any NextStyle it should be the same as the current style QCOMPARE(rawFormat.property(KoParagraphStyle::StyleId).toInt(), rawFormat.property(KoParagraphStyle::NextStyle).toInt()); QCOMPARE(format3.leftMargin(), 10.0); QCOMPARE(format3.rightMargin(), 20.0); }
void tst_QVideoSurfaceFormat::compare() { QVideoSurfaceFormat format1( QSize(16, 16), QVideoFrame::Format_RGB32, QAbstractVideoBuffer::GLTextureHandle); QVideoSurfaceFormat format2( QSize(16, 16), QVideoFrame::Format_RGB32, QAbstractVideoBuffer::GLTextureHandle); QVideoSurfaceFormat format3( QSize(32, 32), QVideoFrame::Format_YUV444, QAbstractVideoBuffer::GLTextureHandle); QVideoSurfaceFormat format4( QSize(16, 16), QVideoFrame::Format_RGB32, QAbstractVideoBuffer::UserHandle); QCOMPARE(format1 == format2, true); QCOMPARE(format1 != format2, false); QCOMPARE(format1 == format3, false); QCOMPARE(format1 != format3, true); QCOMPARE(format1 == format4, false); QCOMPARE(format1 != format4, true); format2.setFrameSize(1024, 768); // Not equal, frame size differs. QCOMPARE(format1 == format2, false); QCOMPARE(format1 != format2, true); format1.setFrameSize(1024, 768); // Equal. QCOMPARE(format1 == format2, true); QCOMPARE(format1 != format2, false); format1.setViewport(QRect(0, 0, 800, 600)); format2.setViewport(QRect(112, 84, 800, 600)); // Not equal, viewports differ. QCOMPARE(format1 == format2, false); QCOMPARE(format1 != format2, true); format1.setViewport(QRect(112, 84, 800, 600)); // Equal. QCOMPARE(format1 == format2, true); QCOMPARE(format1 != format2, false); format2.setScanLineDirection(QVideoSurfaceFormat::BottomToTop); // Not equal scan line direction differs. QCOMPARE(format1 == format2, false); QCOMPARE(format1 != format2, true); format1.setScanLineDirection(QVideoSurfaceFormat::BottomToTop); // Equal. QCOMPARE(format1 == format2, true); QCOMPARE(format1 != format2, false); format1.setFrameRate(7.5); // Not equal frame rate differs. QCOMPARE(format1 == format2, false); QCOMPARE(format1 != format2, true); format2.setFrameRate(qreal(7.50001)); // Equal. QCOMPARE(format1 == format2, true); QCOMPARE(format1 != format2, false); format2.setPixelAspectRatio(4, 3); // Not equal pixel aspect ratio differs. QCOMPARE(format1 == format2, false); QCOMPARE(format1 != format2, true); format1.setPixelAspectRatio(QSize(4, 3)); // Equal. QCOMPARE(format1 == format2, true); QCOMPARE(format1 != format2, false); format2.setYCbCrColorSpace(QVideoSurfaceFormat::YCbCr_xvYCC601); // Not equal yuv color space differs. QCOMPARE(format1 == format2, false); QCOMPARE(format1 != format2, true); format1.setYCbCrColorSpace(QVideoSurfaceFormat::YCbCr_xvYCC601); // Equal. QCOMPARE(format1 == format2, true); QCOMPARE(format1 != format2, false); format1.setProperty("integer", 12); // Not equal, property mismatch. QCOMPARE(format1 == format2, false); QCOMPARE(format1 != format2, true); format2.setProperty("integer", 45); // Not equal, integer differs. QCOMPARE(format1 == format2, false); QCOMPARE(format1 != format2, true); format2.setProperty("integer", 12); // Equal. QCOMPARE(format1 == format2, true); QCOMPARE(format1 != format2, false); format1.setProperty("string", QString::fromLatin1("Hello")); format2.setProperty("size", QSize(12, 54)); // Not equal, property mismatch. QCOMPARE(format1 == format2, false); QCOMPARE(format1 != format2, true); format2.setProperty("string", QString::fromLatin1("Hello")); format1.setProperty("size", QSize(12, 54)); // Equal. QCOMPARE(format1 == format2, true); QCOMPARE(format1 != format2, false); format1.setProperty("string", QVariant()); // Not equal, property mismatch. QCOMPARE(format1 == format2, false); QCOMPARE(format1 != format2, true); }
void __mydebug_wrapper(const Solution& solution, size_t id, const Args&... args) { string levelString(solution.level, ' '); debug2("%s(%u:%zd) %s", levelString, id, solution.score, format2(args...)); }
void ConsoleProgressImpl::finish(uint64_t size, size_t time) { termClean(); nonBlockingPrint(format2(__("Fetched %s in %s.\n"), humanReadableSizeString(size), humanReadableDifftimeString(time))); }
string perform(const shared_ptr< const Config >& config, const download::Uri& uri, const string& targetPath, const std::function< void (const vector< string >&) >& callback) { try { CurlWrapper curl; // bad connections can return 'receive failure' transient error // occasionally, give them several tries to finish the download auto transientErrorsLeft = config->getInteger("acquire::retries"); { // setting options curl.setOption(CURLOPT_URL, string(uri), "uri"); auto downloadLimit = getIntegerAcquireSuboptionForUri(config, uri, "dl-limit"); if (downloadLimit) { curl.setLargeOption(CURLOPT_MAX_RECV_SPEED_LARGE, downloadLimit*1024, "upper speed limit"); } auto proxy = getAcquireSuboptionForUri(config, uri, "proxy"); if (proxy == "DIRECT") { curl.setOption(CURLOPT_PROXY, "", "proxy"); } else if (!proxy.empty()) { curl.setOption(CURLOPT_PROXY, proxy, "proxy"); } if (uri.getProtocol() == "http" && config->getBool("acquire::http::allowredirect")) { curl.setOption(CURLOPT_FOLLOWLOCATION, 1, "follow-location"); } auto timeout = getIntegerAcquireSuboptionForUri(config, uri, "timeout"); if (timeout) { curl.setOption(CURLOPT_CONNECTTIMEOUT, timeout, "connect timeout"); curl.setOption(CURLOPT_LOW_SPEED_LIMIT, 1, "low speed limit"); curl.setOption(CURLOPT_LOW_SPEED_TIME, timeout, "low speed timeout"); } curl.setOption(CURLOPT_WRITEFUNCTION, (void*)&curlWriteFunction, "write function"); } string openError; File file(targetPath, "a", openError); if (!openError.empty()) { fatal2(__("unable to open the file '%s': %s"), targetPath, openError); } start: ssize_t totalBytes = file.tell(); callback(vector< string > { "downloading", lexical_cast< string >(totalBytes), lexical_cast< string >(0)}); curl.setOption(CURLOPT_RESUME_FROM, totalBytes, "resume from"); string fileWriteError; { fileWriteErrorPtr = &fileWriteError; filePtr = &file; curlPtr = &curl; callbackPtr = &callback; totalBytesPtr = &totalBytes; } auto performResult = curl.perform(); if (!fileWriteError.empty()) { return fileWriteError; } else if (performResult == CURLE_OK) { return string(); // all went ok } else if (performResult == CURLE_PARTIAL_FILE) { // partial data? no problem, we might request it return string(); } else { // something went wrong :( // transient errors handling if (performResult == CURLE_RECV_ERROR && transientErrorsLeft) { if (config->getBool("debug::downloader")) { debug2("transient error while downloading '%s'", string(uri)); } --transientErrorsLeft; goto start; } if (performResult == CURLE_RANGE_ERROR) { if (config->getBool("debug::downloader")) { debug2("range command failed, need to restart from beginning while downloading '%s'", string(uri)); } if (unlink(targetPath.c_str()) == -1) { return format2e(__("unable to remove target file for re-downloading")); } goto start; } return curl.getError(); } } catch (Exception& e) { return format2(__("download method error: %s"), e.what()); } }
std::string format(const std::string& format, const std::map<std::string, std::string>& map) { using tokeniter = std::sregex_token_iterator; bool matched = true; auto opacc = [&](std::string& acc, const tokeniter::value_type& sm) { matched = !matched; // toggle if (!matched) return std::ref(acc += sm.str()); const auto replace = map.find(std::string{sm.first + 1, sm.second - 1}); return std::ref(acc += (replace == end(map)?sm.str():replace->second)); }; static const std::regex kDirective{R"((\{[_[:alpha:]][_[:alnum:]]*\}))"}; const tokeniter first{begin(format), end(format), kDirective, {-1, 1}}; const tokeniter last{}; std::string ret; return std::accumulate(first, last, std::ref(ret), opacc); } std::string format2(const std::string& format, const std::map<std::string, std::string>& map) { using tokeniter = std::sregex_token_iterator; bool matched = true; std::string acc; auto opacc = [&](const tokeniter::value_type& sm) { matched = !matched; // toggle if (!matched) return (acc += sm.str()); const auto replace = map.find(std::string{sm.first + 1, sm.second - 1}); return (acc += (replace == end(map)?sm.str():replace->second)); }; static const std::regex kDirective{R"((\{[_[:alpha:]][_[:alnum:]]*\}))"}; const tokeniter first{begin(format), end(format), kDirective, {-1, 1}}; const tokeniter last{}; std::for_each(first, last, opacc); return acc; } std::string format3(const std::string& format, const std::map<std::string, std::string>& map) { using tokeniter = std::sregex_token_iterator; std::string acc; auto appender = [&](const std::string& sm) { acc.append(sm); }; bool matched = true; auto opacc = [&](const tokeniter::value_type& sm) { matched = !matched; // toggle if (!matched) return sm.str(); const auto replace = map.find(std::string{sm.first + 1, sm.second - 1}); return std::string{replace == end(map) ? sm.str() : replace->second}; }; static const std::regex kDirective{R"((\{[_[:alpha:]][_[:alnum:]]*\}))"}; const tokeniter first{begin(format), end(format), kDirective, {-1, 1}}; const tokeniter last{}; std::transform(first, last, boost::make_function_output_iterator(appender), opacc); return acc; } int main() { std::cout << format("a{b1}aaa {a1} {a2} {{a3} bbb", {{"a1", "@11"}, {"a2", "222"}}) << std::endl; std::cout << format2("a{b1}aaa {a1} {a2} {{a3} bbb", {{"a1", "@11"}, {"a2", "222"}}) << std::endl; std::cout << format3("a{b1}aaa {a1} {a2} {{a3} bbb", {{"a1", "@11"}, {"a2", "222"}}) << std::endl; // expected : a{b1}aaa @11 222 {{a3} bbb std::cout << format("aaa {} {{}} {a1} bbb}", {{"a1", "111"}}) << std::endl; std::cout << format2("aaa {} {{}} {a1} bbb}", {{"a1", "111"}}) << std::endl; std::cout << format3("aaa {} {{}} {a1} bbb}", {{"a1", "111"}}) << std::endl; // expected : aaa {} {{}} 111 bbb} return 0; }
void Package::__merge_version(unique_ptr< Version >&& parsedVersion) { if (!_is_architecture_appropriate(parsedVersion.get())) { return; // skip this version } // merging try { if (__is_installed(parsedVersion.get())) { // no way to know is this version the same as in repositories, // until for example #667665 is implemented parsedVersion->versionString += versionstring::idSuffixDelimiter; parsedVersion->versionString += "installed"; __parsed_versions.push_back(std::move(parsedVersion)); } else { const auto& parsedVersionString = parsedVersion->versionString; bool clashed = false; bool merged = false; for (const auto& presentVersion: __parsed_versions) { if (!versionstring::sameOriginal(presentVersion->versionString, parsedVersionString)) { continue; } if (__is_installed(presentVersion.get())) { continue; } if (presentVersion->areHashesEqual(parsedVersion.get())) { // ok, this is the same version, so adding new Version::Source info presentVersion->sources.push_back(parsedVersion->sources[0]); merged = true; break; } else { clashed = true; // err, no, this is different version :( } } if (!merged) { if (clashed) { static size_t idCounter = 0; parsedVersion->versionString += versionstring::idSuffixDelimiter; parsedVersion->versionString += format2("dhs%zu", idCounter++); } __parsed_versions.push_back(std::move(parsedVersion)); } } } catch (Exception&) { fatal2(__("error while merging the version '%s' for the package '%s'"), parsedVersion->versionString, parsedVersion->packageName); }; }
string Resolver::SynchronizationReason::toString() const { return format2(__("%s: synchronization with %s %s"), relatedPackageName, version->packageName, version->versionString); }
bool ValueFormatTest::InitFromString() { WgValueFormat format1("1000"); TEST_ASSERT( format1.decimals == 0 ); TEST_ASSERT( format1.grouping == 0 ); TEST_ASSERT( format1.prefix[0] == 0 ); TEST_ASSERT( format1.suffix[0] == 0 ); WgValueFormat format2("1;000"); TEST_ASSERT( format2.decimals == 0 ); TEST_ASSERT( format2.grouping == 3 ); TEST_ASSERT( format2.separator == ';' ); TEST_ASSERT( format2.prefix[0] == 0 ); TEST_ASSERT( format2.suffix[0] == 0 ); WgValueFormat format3("1;000:0"); TEST_ASSERT( format3.decimals == 1 ); TEST_ASSERT( format3.grouping == 3 ); TEST_ASSERT( format3.separator == ';' ); TEST_ASSERT( format3.period == ':' ); TEST_ASSERT( format3.prefix[0] == 0 ); TEST_ASSERT( format3.suffix[0] == 0 ); TEST_ASSERT( format3.bForceDecimals == true ); WgValueFormat format4("1;00:000"); TEST_ASSERT( format4.decimals == 3 ); TEST_ASSERT( format4.grouping == 2 ); TEST_ASSERT( format4.separator == ';' ); TEST_ASSERT( format4.period == ':' ); TEST_ASSERT( format4.prefix[0] == 0 ); TEST_ASSERT( format4.suffix[0] == 0 ); TEST_ASSERT( format4.bForceDecimals == true ); WgValueFormat format5("100:000"); TEST_ASSERT( format5.decimals == 3 ); TEST_ASSERT( format5.grouping == 0 ); TEST_ASSERT( format5.period == ':' ); TEST_ASSERT( format5.prefix[0] == 0 ); TEST_ASSERT( format5.suffix[0] == 0 ); TEST_ASSERT( format5.bForceDecimals == true ); std::string a = std::string("$\xc2\xa3\xe2\x82\xac") + std::string("1;000000:0000 USD"); // string is '$£€1;000000:0000 USD' WgValueFormat format6( a ); TEST_ASSERT( format6.decimals == 4 ); TEST_ASSERT( format6.grouping == 6 ); TEST_ASSERT( format6.separator == ';' ); TEST_ASSERT( format6.prefix[0] == '$' ); TEST_ASSERT( format6.prefix[1] == 0xa3 ); // pound sign TEST_ASSERT( format6.prefix[2] == 0x20ac ); // euro sign TEST_ASSERT( format6.prefix[3] == 0 ); TEST_ASSERT( format6.suffix[0] == ' ' ); TEST_ASSERT( format6.suffix[1] == 'U' ); TEST_ASSERT( format6.suffix[2] == 'S' ); TEST_ASSERT( format6.suffix[3] == 'D' ); TEST_ASSERT( format6.bForceDecimals == true ); return true; }
string ScoreManager::getScoreChangeString(const ScoreChange& scoreChange) const { return format2("%s=%zd", scoreChange.__to_string(), getScoreChangeValue(scoreChange)); }
unsigned gameMode(Screen &/*screen*/, const void * data){ GameState state; Surface blankBack(SUR_UNINIT, 1, 1, BLUE); MessageBox fpsDisplay(WHITE, Screen::getScreenRes().x / 2 - 40, 2, 1, blankBack, FONT_DEBUG, 0, false, DEBUG); SDL_ShowCursor(SDL_DISABLE); //flush event queue before accepting game controls, //specifically the mouse up event from clicking "Play Game" SDL_Event event; while(SDL_PollEvent(&event)) debug("Unhandled event: ", int(event.type)); timer_t oldTicks = SDL_GetTicks(); //data tells us which level we're in. int level = *(int*)data; //first: tutorial { Surface tutImage(IMAGE_PATH + "level" + format2(level) + ".png"); screenBuf << tutImage; screenBuf.flip(); //wait for key down or mouse down //while (true){ // SDL_PollEvent(&event); // if (event.type == SDL_MOUSEBUTTONUP || event.type == SDL_KEYUP) // break; //} while (true){ SDL_PollEvent(&event); if (event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_KEYDOWN) break; } while (true){ SDL_PollEvent(&event); if (event.type == SDL_MOUSEBUTTONUP || event.type == SDL_KEYUP) break; } } state.setLevel(level); while (state.loop){ //time stuff timer_t newTicks = SDL_GetTicks(); timer_t delta = newTicks - oldTicks; oldTicks = newTicks; if (delta > 500) continue; double deltaMod = 1.0 * delta / DELTA_MODIFIER; double fps = delta == 0 ? 0 : 1000 / delta; fpsDisplay(format3(fps), "fps | ", delta, "ms "); //force interface refresh pushMouseMove(); //update state updateState(deltaMod, state, fpsDisplay); //render render(state, fpsDisplay); } //Clean up SDL_ShowCursor(SDL_ENABLE); GameOutcome outcome = state.outcome; return outcome; //return something more meaningful }
static inline string getRedirectionSuffix(int fromFd, int toFd) { return format2("%zu<&%zu", toFd, fromFd); }