text
stringlengths
54
60.6k
<commit_before>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "HttpConnection.hxx" #include "GotoConfig.hxx" #include "TranslationHandler.hxx" #include "Instance.hxx" #include "Config.hxx" #include "http_server/http_server.hxx" #include "http_server/Request.hxx" #include "translation/Handler.hxx" #include "translation/Response.hxx" #include "pool/pool.hxx" #include "RedirectHttps.hxx" #include "istream/UnusedHoldPtr.hxx" #include "util/LeakDetector.hxx" /* * TranslateHandler * */ struct LbHttpRequest final : private Cancellable, private LeakDetector { struct pool &pool; LbHttpConnection &connection; LbTranslationHandler &handler; HttpServerRequest &request; /** * This object temporarily holds the request body */ UnusedHoldIstreamPtr request_body; CancellablePointer &caller_cancel_ptr; CancellablePointer translate_cancel_ptr; LbHttpRequest(LbHttpConnection &_connection, LbTranslationHandler &_handler, HttpServerRequest &_request, CancellablePointer &_cancel_ptr) :pool(_request.pool), connection(_connection), handler(_handler), request(_request), request_body(request.pool, std::move(request.body)), caller_cancel_ptr(_cancel_ptr) { caller_cancel_ptr = *this; } void Destroy() { DeleteFromPool(pool, this); } private: /* virtual methods from class Cancellable */ void Cancel() noexcept override { CancellablePointer cancel_ptr(std::move(translate_cancel_ptr)); Destroy(); cancel_ptr.Cancel(); } }; static void lb_http_translate_response(TranslateResponse &response, void *ctx) { auto &r = *(LbHttpRequest *)ctx; auto &c = r.connection; auto &request = r.request; if (response.site != nullptr) c.per_request.site_name = p_strdup(request.pool, response.site); if (response.https_only != 0 && !c.IsEncrypted()) { r.Destroy(); const char *host = c.per_request.host; if (host == nullptr) { http_server_send_message(&request, HTTP_STATUS_BAD_REQUEST, "No Host header"); return; } http_server_send_redirect(&request, HTTP_STATUS_MOVED_PERMANENTLY, MakeHttpsRedirect(request.pool, host, response.https_only, request.uri), "This page requires \"https\""); } else if (response.status != http_status_t(0) || response.redirect != nullptr || response.message != nullptr) { r.Destroy(); auto status = response.status; if (status == http_status_t(0)) status = HTTP_STATUS_SEE_OTHER; const char *body = response.message; if (body == nullptr) body = http_status_to_string(status); http_server_simple_response(request, status, response.redirect, body); } else if (response.pool != nullptr) { auto *destination = r.handler.FindDestination(response.pool); if (destination == nullptr) { r.Destroy(); c.LogSendError(request, std::make_exception_ptr(std::runtime_error("No such pool"))); return; } if (response.canonical_host != nullptr) c.per_request.canonical_host = response.canonical_host; request.body = std::move(r.request_body); auto &caller_cancel_ptr = r.caller_cancel_ptr; r.Destroy(); c.HandleHttpRequest(*destination, request, caller_cancel_ptr); } else { r.Destroy(); c.LogSendError(request, std::make_exception_ptr(std::runtime_error("Invalid translation server response"))); } } static void lb_http_translate_error(std::exception_ptr ep, void *ctx) { auto &r = *(LbHttpRequest *)ctx; auto &request = r.request; auto &connection = r.connection; r.Destroy(); connection.LogSendError(request, ep); } static constexpr TranslateHandler lb_http_translate_handler = { .response = lb_http_translate_response, .error = lb_http_translate_error, }; /* * constructor * */ void LbHttpConnection::AskTranslationServer(LbTranslationHandler &handler, HttpServerRequest &request, CancellablePointer &cancel_ptr) { auto *r = NewFromPool<LbHttpRequest>(request.pool, *this, handler, request, cancel_ptr); handler.Pick(request.pool, request, listener.tag.empty() ? nullptr : listener.tag.c_str(), lb_http_translate_handler, r, r->translate_cancel_ptr); } <commit_msg>lb/TranslationHttpRequestHandler: include cleanup<commit_after>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "HttpConnection.hxx" #include "GotoConfig.hxx" #include "TranslationHandler.hxx" #include "Config.hxx" #include "http_server/http_server.hxx" #include "http_server/Request.hxx" #include "translation/Handler.hxx" #include "translation/Response.hxx" #include "pool/pool.hxx" #include "RedirectHttps.hxx" #include "istream/UnusedHoldPtr.hxx" #include "util/Cancellable.hxx" #include "util/LeakDetector.hxx" /* * TranslateHandler * */ struct LbHttpRequest final : private Cancellable, private LeakDetector { struct pool &pool; LbHttpConnection &connection; LbTranslationHandler &handler; HttpServerRequest &request; /** * This object temporarily holds the request body */ UnusedHoldIstreamPtr request_body; CancellablePointer &caller_cancel_ptr; CancellablePointer translate_cancel_ptr; LbHttpRequest(LbHttpConnection &_connection, LbTranslationHandler &_handler, HttpServerRequest &_request, CancellablePointer &_cancel_ptr) :pool(_request.pool), connection(_connection), handler(_handler), request(_request), request_body(request.pool, std::move(request.body)), caller_cancel_ptr(_cancel_ptr) { caller_cancel_ptr = *this; } void Destroy() { DeleteFromPool(pool, this); } private: /* virtual methods from class Cancellable */ void Cancel() noexcept override { CancellablePointer cancel_ptr(std::move(translate_cancel_ptr)); Destroy(); cancel_ptr.Cancel(); } }; static void lb_http_translate_response(TranslateResponse &response, void *ctx) { auto &r = *(LbHttpRequest *)ctx; auto &c = r.connection; auto &request = r.request; if (response.site != nullptr) c.per_request.site_name = p_strdup(request.pool, response.site); if (response.https_only != 0 && !c.IsEncrypted()) { r.Destroy(); const char *host = c.per_request.host; if (host == nullptr) { http_server_send_message(&request, HTTP_STATUS_BAD_REQUEST, "No Host header"); return; } http_server_send_redirect(&request, HTTP_STATUS_MOVED_PERMANENTLY, MakeHttpsRedirect(request.pool, host, response.https_only, request.uri), "This page requires \"https\""); } else if (response.status != http_status_t(0) || response.redirect != nullptr || response.message != nullptr) { r.Destroy(); auto status = response.status; if (status == http_status_t(0)) status = HTTP_STATUS_SEE_OTHER; const char *body = response.message; if (body == nullptr) body = http_status_to_string(status); http_server_simple_response(request, status, response.redirect, body); } else if (response.pool != nullptr) { auto *destination = r.handler.FindDestination(response.pool); if (destination == nullptr) { r.Destroy(); c.LogSendError(request, std::make_exception_ptr(std::runtime_error("No such pool"))); return; } if (response.canonical_host != nullptr) c.per_request.canonical_host = response.canonical_host; request.body = std::move(r.request_body); auto &caller_cancel_ptr = r.caller_cancel_ptr; r.Destroy(); c.HandleHttpRequest(*destination, request, caller_cancel_ptr); } else { r.Destroy(); c.LogSendError(request, std::make_exception_ptr(std::runtime_error("Invalid translation server response"))); } } static void lb_http_translate_error(std::exception_ptr ep, void *ctx) { auto &r = *(LbHttpRequest *)ctx; auto &request = r.request; auto &connection = r.connection; r.Destroy(); connection.LogSendError(request, ep); } static constexpr TranslateHandler lb_http_translate_handler = { .response = lb_http_translate_response, .error = lb_http_translate_error, }; /* * constructor * */ void LbHttpConnection::AskTranslationServer(LbTranslationHandler &handler, HttpServerRequest &request, CancellablePointer &cancel_ptr) { auto *r = NewFromPool<LbHttpRequest>(request.pool, *this, handler, request, cancel_ptr); handler.Pick(request.pool, request, listener.tag.empty() ? nullptr : listener.tag.c_str(), lb_http_translate_handler, r, r->translate_cancel_ptr); } <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <set> #include <vector> #include "paddle/math/Vector.h" #include "Evaluator.h" namespace paddle { /** * Chunk evaluator is used to evaluate segment labelling accuracy for a * sequence. It calculates the chunk detection F1 score. * * A chunk is correctly detected if its beginning, end and type are correct. * Other chunk type is ignored. * For each label in the label sequence, we have * * @code * tagType = label % numTagType * chunkType = label / numTagType * otherChunkType = numChunkTypes * @endcode * * The total number of different labels is numTagType*numChunkTypes+1 * We support 4 labelling scheme * The tag type for each of the scheme is shown as follows: * * @code * Scheme Begin Inside End Single * plain 0 - - - * IOB 0 1 - - * IOE - 0 1 - * IOBES 0 1 2 3 * @endcode * * 'plain' means the whole chunk must contain exactly the same chunk label. */ class ChunkEvaluator : public Evaluator { int otherChunkType_; int numChunkTypes_; // number of chunk types besides other chunk type int numTagTypes_; int tagBegin_; int tagInside_; int tagEnd_; int tagSingle_; int64_t numLabelSegments_; int64_t numOutputSegments_; int64_t numCorrect_; struct Segment { int begin; int end; int type; bool operator==(const Segment& y) const { return begin == y.begin && end == y.end && type == y.type; } }; std::vector<Segment> labelSegments_; std::vector<Segment> outputSegments_; std::set<int> excludedChunkTypes_; public: virtual void init(const EvaluatorConfig& config) { Evaluator::init(config); if (config.chunk_scheme() == "IOB") { numTagTypes_ = 2; tagBegin_ = 0; tagInside_ = 1; tagEnd_ = -1; tagSingle_ = -1; } else if (config.chunk_scheme() == "IOE") { numTagTypes_ = 2; tagBegin_ = -1; tagInside_ = 0; tagEnd_ = 1; tagSingle_ = -1; } else if (config.chunk_scheme() == "IOBES") { numTagTypes_ = 4; tagBegin_ = 0; tagInside_ = 1; tagEnd_ = 2; tagSingle_ = 3; } else if (config.chunk_scheme() == "plain") { numTagTypes_ = 1; tagBegin_ = -1; tagInside_ = -1; tagEnd_ = -1; tagSingle_ = -1; } else { LOG(FATAL) << "Unknown chunk scheme: " << config.chunk_scheme(); } CHECK(config.has_num_chunk_types()) << "Missing num_chunk_types in config"; otherChunkType_ = numChunkTypes_ = config.num_chunk_types(); // the chunks of types in excludedChunkTypes_ will not be counted auto& tmp = config.excluded_chunk_types(); excludedChunkTypes_.insert(tmp.begin(), tmp.end()); } virtual void start() { Evaluator::start(); numLabelSegments_ = 0; numOutputSegments_ = 0; numCorrect_ = 0; } virtual void printStats(std::ostream& os) const { double precision = (double)numCorrect_ / numOutputSegments_; double recall = (double)numCorrect_ / numLabelSegments_; double f1 = !numCorrect_ ? 0 : 2 * precision * recall / (precision + recall); os << config_.name() << "=" << f1 << " true_chunks=" << numLabelSegments_ << " result_chunks=" << numOutputSegments_ << " correct_chunks=" << numCorrect_; } virtual void distributeEval(ParameterClient2* client) { int64_t buf[3] = {numLabelSegments_, numOutputSegments_, numCorrect_}; client->reduce(buf, buf, 3, FLAGS_trainer_id, 0); numLabelSegments_ = buf[0]; numOutputSegments_ = buf[1]; numCorrect_ = buf[2]; } virtual real evalImp(std::vector<Argument>& arguments) { CHECK_EQ(arguments.size(), (size_t)2); IVectorPtr& output = arguments[0].ids; IVectorPtr& label = arguments[1].ids; CHECK(!output->useGpu() && !label->useGpu()) << "Not supported"; auto sequenceStartPositions = arguments[1].sequenceStartPositions->getVector(false); CHECK_EQ(output->getSize(), label->getSize()); CHECK(sequenceStartPositions); size_t numSequences = sequenceStartPositions->getSize() - 1; const int* starts = sequenceStartPositions->getData(); for (size_t i = 0; i < numSequences; ++i) { eval1(output->getData() + starts[i], label->getData() + starts[i], starts[i + 1] - starts[i]); } return 0; } void eval1(int* output, int* label, int length) { getSegments(output, length, outputSegments_); getSegments(label, length, labelSegments_); size_t i = 0, j = 0; while (i < outputSegments_.size() && j < labelSegments_.size()) { if (outputSegments_[i] == labelSegments_[j] && excludedChunkTypes_.count(outputSegments_[i].type) != 1) { ++numCorrect_; } if (outputSegments_[i].end < labelSegments_[j].end) { ++i; } else if (outputSegments_[i].end > labelSegments_[j].end) { ++j; } else { ++i; ++j; } } for (auto& segment : labelSegments_) { if (excludedChunkTypes_.count(segment.type) != 1) ++numLabelSegments_; } for (auto& segment : outputSegments_) { if (excludedChunkTypes_.count(segment.type) != 1) ++numOutputSegments_; } } void getSegments(int* label, int length, std::vector<Segment>& segments) { segments.clear(); segments.reserve(length); int chunkStart = 0; bool inChunk = false; int tag = -1; int type = otherChunkType_; for (int i = 0; i < length; ++i) { int prevTag = tag; int prevType = type; CHECK_LE(label[i], numChunkTypes_ * numTagTypes_); tag = label[i] % numTagTypes_; type = label[i] / numTagTypes_; if (inChunk && isChunkEnd(prevTag, prevType, tag, type)) { Segment segment{ chunkStart, // begin i - 1, // end prevType, }; segments.push_back(segment); inChunk = false; } if (isChunkBegin(prevTag, prevType, tag, type)) { chunkStart = i; inChunk = true; } } if (inChunk) { Segment segment{ chunkStart, // begin length - 1, // end type, }; segments.push_back(segment); } } // whether (prevTag, prevType) is the end of a chunk bool isChunkEnd(int prevTag, int prevType, int tag, int type) { if (prevType == otherChunkType_) return false; if (type == otherChunkType_) return true; if (type != prevType) return true; if (prevTag == tagBegin_) return tag == tagBegin_ || tag == tagSingle_; if (prevTag == tagInside_) return tag == tagBegin_ || tag == tagSingle_; if (prevTag == tagEnd_) return true; if (prevTag == tagSingle_) return true; return false; } // whether (tag, type) is the beginning of a chunk bool isChunkBegin(int prevTag, int prevType, int tag, int type) { if (prevType == otherChunkType_) return type != otherChunkType_; if (type == otherChunkType_) return false; if (type != prevType) return true; if (tag == tagBegin_) return true; if (tag == tagInside_) return prevTag == tagEnd_ || prevTag == tagSingle_; if (tag == tagEnd_) return prevTag == tagEnd_ || prevTag == tagSingle_; if (tag == tagSingle_) return true; return false; } }; REGISTER_EVALUATOR(chunk, ChunkEvaluator); } // namespace paddle <commit_msg>overload several virtual functions to make ChunkEvaluator output multiple metrics<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <set> #include <vector> #include "paddle/math/Vector.h" #include "paddle/utils/StringUtil.h" #include "Evaluator.h" namespace paddle { /** * Chunk evaluator is used to evaluate segment labelling accuracy for a * sequence. It calculates the chunk detection F1 score. * * A chunk is correctly detected if its beginning, end and type are correct. * Other chunk type is ignored. * For each label in the label sequence, we have * * @code * tagType = label % numTagType * chunkType = label / numTagType * otherChunkType = numChunkTypes * @endcode * * The total number of different labels is numTagType*numChunkTypes+1 * We support 4 labelling scheme * The tag type for each of the scheme is shown as follows: * * @code * Scheme Begin Inside End Single * plain 0 - - - * IOB 0 1 - - * IOE - 0 1 - * IOBES 0 1 2 3 * @endcode * * 'plain' means the whole chunk must contain exactly the same chunk label. */ class ChunkEvaluator : public Evaluator { int otherChunkType_; int numChunkTypes_; // number of chunk types besides other chunk type int numTagTypes_; int tagBegin_; int tagInside_; int tagEnd_; int tagSingle_; int64_t numLabelSegments_; int64_t numOutputSegments_; int64_t numCorrect_; struct Segment { int begin; int end; int type; bool operator==(const Segment& y) const { return begin == y.begin && end == y.end && type == y.type; } }; std::vector<Segment> labelSegments_; std::vector<Segment> outputSegments_; std::set<int> excludedChunkTypes_; public: virtual void init(const EvaluatorConfig& config) { Evaluator::init(config); if (config.chunk_scheme() == "IOB") { numTagTypes_ = 2; tagBegin_ = 0; tagInside_ = 1; tagEnd_ = -1; tagSingle_ = -1; } else if (config.chunk_scheme() == "IOE") { numTagTypes_ = 2; tagBegin_ = -1; tagInside_ = 0; tagEnd_ = 1; tagSingle_ = -1; } else if (config.chunk_scheme() == "IOBES") { numTagTypes_ = 4; tagBegin_ = 0; tagInside_ = 1; tagEnd_ = 2; tagSingle_ = 3; } else if (config.chunk_scheme() == "plain") { numTagTypes_ = 1; tagBegin_ = -1; tagInside_ = -1; tagEnd_ = -1; tagSingle_ = -1; } else { LOG(FATAL) << "Unknown chunk scheme: " << config.chunk_scheme(); } CHECK(config.has_num_chunk_types()) << "Missing num_chunk_types in config"; otherChunkType_ = numChunkTypes_ = config.num_chunk_types(); // the chunks of types in excludedChunkTypes_ will not be counted auto& tmp = config.excluded_chunk_types(); excludedChunkTypes_.insert(tmp.begin(), tmp.end()); } virtual void start() { Evaluator::start(); numLabelSegments_ = 0; numOutputSegments_ = 0; numCorrect_ = 0; } virtual void printStats(std::ostream& os) const { storeLocalValues(); os << config_.name() << "=" << values_["F1-score"] << " true_chunks=" << numLabelSegments_ << " result_chunks=" << numOutputSegments_ << " correct_chunks=" << numCorrect_; } virtual void distributeEval(ParameterClient2* client) { int64_t buf[3] = {numLabelSegments_, numOutputSegments_, numCorrect_}; client->reduce(buf, buf, 3, FLAGS_trainer_id, 0); numLabelSegments_ = buf[0]; numOutputSegments_ = buf[1]; numCorrect_ = buf[2]; } virtual real evalImp(std::vector<Argument>& arguments) { CHECK_EQ(arguments.size(), (size_t)2); IVectorPtr& output = arguments[0].ids; IVectorPtr& label = arguments[1].ids; CHECK(!output->useGpu() && !label->useGpu()) << "Not supported"; auto sequenceStartPositions = arguments[1].sequenceStartPositions->getVector(false); CHECK_EQ(output->getSize(), label->getSize()); CHECK(sequenceStartPositions); size_t numSequences = sequenceStartPositions->getSize() - 1; const int* starts = sequenceStartPositions->getData(); for (size_t i = 0; i < numSequences; ++i) { eval1(output->getData() + starts[i], label->getData() + starts[i], starts[i + 1] - starts[i]); } return 0; } void eval1(int* output, int* label, int length) { getSegments(output, length, outputSegments_); getSegments(label, length, labelSegments_); size_t i = 0, j = 0; while (i < outputSegments_.size() && j < labelSegments_.size()) { if (outputSegments_[i] == labelSegments_[j] && excludedChunkTypes_.count(outputSegments_[i].type) != 1) { ++numCorrect_; } if (outputSegments_[i].end < labelSegments_[j].end) { ++i; } else if (outputSegments_[i].end > labelSegments_[j].end) { ++j; } else { ++i; ++j; } } for (auto& segment : labelSegments_) { if (excludedChunkTypes_.count(segment.type) != 1) ++numLabelSegments_; } for (auto& segment : outputSegments_) { if (excludedChunkTypes_.count(segment.type) != 1) ++numOutputSegments_; } } void getSegments(int* label, int length, std::vector<Segment>& segments) { segments.clear(); segments.reserve(length); int chunkStart = 0; bool inChunk = false; int tag = -1; int type = otherChunkType_; for (int i = 0; i < length; ++i) { int prevTag = tag; int prevType = type; CHECK_LE(label[i], numChunkTypes_ * numTagTypes_); tag = label[i] % numTagTypes_; type = label[i] / numTagTypes_; if (inChunk && isChunkEnd(prevTag, prevType, tag, type)) { Segment segment{ chunkStart, // begin i - 1, // end prevType, }; segments.push_back(segment); inChunk = false; } if (isChunkBegin(prevTag, prevType, tag, type)) { chunkStart = i; inChunk = true; } } if (inChunk) { Segment segment{ chunkStart, // begin length - 1, // end type, }; segments.push_back(segment); } } // whether (prevTag, prevType) is the end of a chunk bool isChunkEnd(int prevTag, int prevType, int tag, int type) { if (prevType == otherChunkType_) return false; if (type == otherChunkType_) return true; if (type != prevType) return true; if (prevTag == tagBegin_) return tag == tagBegin_ || tag == tagSingle_; if (prevTag == tagInside_) return tag == tagBegin_ || tag == tagSingle_; if (prevTag == tagEnd_) return true; if (prevTag == tagSingle_) return true; return false; } // whether (tag, type) is the beginning of a chunk bool isChunkBegin(int prevTag, int prevType, int tag, int type) { if (prevType == otherChunkType_) return type != otherChunkType_; if (type == otherChunkType_) return false; if (type != prevType) return true; if (tag == tagBegin_) return true; if (tag == tagInside_) return prevTag == tagEnd_ || prevTag == tagSingle_; if (tag == tagEnd_) return prevTag == tagEnd_ || prevTag == tagSingle_; if (tag == tagSingle_) return true; return false; } public: // three metrics: precision, recall and F1-score void getNames(std::vector<std::string>* names) { this->storeLocalValues(); names->reserve(this->values_.size()); for (auto it = this->values_.begin(); it != this->values_.end(); ++it) { names->push_back(this->config_.name() + "." + it->first); } } // get value by field name real getValue(const std::string& name, Error* err) const { this->storeLocalValues(); std::vector<std::string> buffers; paddle::str::split(name, '.', &buffers); auto it = this->values_.find(buffers[buffers.size() - 1]); if (it == this->values_.end()) { // not found *err = Error("No such key %s", name.c_str()); return 0.0f; } return it->second; } // get type of evaluator std::string getType(const std::string& name, Error* err) const { this->getValue(name, err); if (!err->isOK()) { return std::string(); } return "chunk"; } private: void storeLocalValues() const { CHECK_GT(numOutputSegments_, 0); CHECK_GT(numLabelSegments_, 0); double precision = (double)numCorrect_ / numOutputSegments_; double recall = (double)numCorrect_ / numLabelSegments_; values_["precision"] = precision; values_["recall"] = recall; values_["F1-score"] = !numCorrect_ ? 0 : 2 * precision * recall / (precision + recall); } mutable std::unordered_map<std::string, real> values_; }; REGISTER_EVALUATOR(chunk, ChunkEvaluator); } // namespace paddle <|endoftext|>
<commit_before>#include "tags/tag-database-sqlite.h" #include <QtSql/QSqlDriver> #include <QtSql/QSqlError> #include <QtSql/QSqlField> #include <QtSql/QSqlQuery> #include <QtSql/QSqlRecord> #include <QVariant> #include <utility> #include "logger.h" #include "tags/tag.h" TagDatabaseSqlite::TagDatabaseSqlite(const QString &typeFile, QString tagFile) : TagDatabase(typeFile), m_tagFile(std::move(tagFile)), m_count(-1) {} TagDatabaseSqlite::~TagDatabaseSqlite() { if (m_database.isOpen()) { m_database.close(); } } bool TagDatabaseSqlite::open() { // Don't re-open databases if (m_database.isOpen()) { return true; } // Load and connect to the database m_database = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), "Tag database - " + m_tagFile); m_database.setDatabaseName(m_tagFile); if (!m_database.open()) { log(QStringLiteral("Could not open tag database '%1': %2").arg(m_tagFile, m_database.lastError().text()), Logger::Error); return false; } // Create schema if necessary QSqlQuery createQuery(m_database); createQuery.prepare(QStringLiteral("CREATE TABLE IF NOT EXISTS tags (id INT, tag VARCHAR(255), ttype INT);")); if (!createQuery.exec()) { log(QStringLiteral("Could not create tag database schema: %1").arg(createQuery.lastError().text()), Logger::Error); return false; } return TagDatabase::open(); } bool TagDatabaseSqlite::close() { m_database.close(); return TagDatabase::close(); } bool TagDatabaseSqlite::load() { return TagDatabase::load(); } bool TagDatabaseSqlite::save() { return TagDatabase::save(); } void TagDatabaseSqlite::setTags(const QList<Tag> &tags, bool createTagTypes) { QSqlQuery clearQuery(m_database); clearQuery.prepare(QStringLiteral("DELETE FROM tags")); if (!clearQuery.exec()) { log(QStringLiteral("SQL error when clearing tags: %1").arg(clearQuery.lastError().text()), Logger::Error); return; } if (!m_database.transaction()) { return; } QSqlQuery addQuery(m_database); addQuery.prepare(QStringLiteral("INSERT INTO tags (id, tag, ttype) VALUES (:id, :tag, :ttype)")); for (const Tag &tag : tags) { addQuery.bindValue(":id", tag.id()); addQuery.bindValue(":tag", tag.text()); addQuery.bindValue(":ttype", m_tagTypeDatabase.get(tag.type(), createTagTypes)); if (!addQuery.exec()) { log(QStringLiteral("SQL error when adding tag: %1").arg(addQuery.lastError().text()), Logger::Error); return; } } if (!m_database.commit()) { return; } m_count = -1; } QMap<QString, TagType> TagDatabaseSqlite::getTagTypes(const QStringList &tags) const { QMap<QString, TagType> ret; // Escape values QStringList formatted; QSqlDriver *driver = m_database.driver(); for (const QString &tag : tags) { if (m_cache.contains(tag)) { ret.insert(tag, m_cache[tag]); } else { QSqlField f; f.setType(QVariant::String); f.setValue(tag); formatted.append(driver->formatValue(f)); } } // If all values have already been loaded from the memory cache if (formatted.isEmpty()) { return ret; } // Execute query const QString sql = "SELECT tag, ttype FROM tags WHERE tag IN (" + formatted.join(",") + ")"; QSqlQuery query(m_database); query.setForwardOnly(true); if (!query.exec(sql)) { log(QStringLiteral("SQL error when getting tags: %1").arg(query.lastError().text()), Logger::Error); return ret; } const int idTag = query.record().indexOf("tag"); const int idTtype = query.record().indexOf("ttype"); while (query.next()) { const QString tag = query.value(idTag).toString(); const int typeId = query.value(idTtype).toInt(); if (!m_tagTypeDatabase.contains(typeId)) { continue; } const TagType type = m_tagTypeDatabase.get(typeId); ret.insert(tag, type); m_cache.insert(tag, type); } return ret; } QMap<QString, int> TagDatabaseSqlite::getTagIds(const QStringList &tags) const { QMap<QString, int> ret; // Escape values QStringList formatted; QSqlDriver *driver = m_database.driver(); for (const QString &tag : tags) { if (m_cacheIds.contains(tag)) { ret.insert(tag, m_cacheIds[tag]); } else { QSqlField f; f.setType(QVariant::String); f.setValue(tag); formatted.append(driver->formatValue(f)); } } // If all values have already been loaded from the memory cache if (formatted.isEmpty()) { return ret; } // Execute query const QString sql = "SELECT tag, id FROM tags WHERE tag IN (" + formatted.join(",") + ")"; QSqlQuery query(m_database); query.setForwardOnly(true); if (!query.exec(sql)) { log(QStringLiteral("SQL error when getting tags: %1").arg(query.lastError().text()), Logger::Error); return ret; } const int idTag = query.record().indexOf("tag"); const int idId = query.record().indexOf("id"); while (query.next()) { const QString tag = query.value(idTag).toString(); const int id = query.value(idId).toInt(); ret.insert(tag, id); m_cacheIds.insert(tag, id); } return ret; } int TagDatabaseSqlite::count() const { if (m_count != -1) { return m_count; } QSqlQuery query(m_database); const QString sql = QStringLiteral("SELECT COUNT(*) FROM tags"); if (!query.exec(sql) || !query.next()) { log(QStringLiteral("SQL error when getting tag count: %1").arg(query.lastError().text()), Logger::Error); return -1; } m_count = query.value(0).toInt(); return m_count; } <commit_msg>Create tag database parent directory if necessary<commit_after>#include "tags/tag-database-sqlite.h" #include <QDir> #include <QFileInfo> #include <QtSql/QSqlDriver> #include <QtSql/QSqlError> #include <QtSql/QSqlField> #include <QtSql/QSqlQuery> #include <QtSql/QSqlRecord> #include <QVariant> #include <utility> #include "logger.h" #include "tags/tag.h" TagDatabaseSqlite::TagDatabaseSqlite(const QString &typeFile, QString tagFile) : TagDatabase(typeFile), m_tagFile(std::move(tagFile)), m_count(-1) {} TagDatabaseSqlite::~TagDatabaseSqlite() { if (m_database.isOpen()) { m_database.close(); } } bool TagDatabaseSqlite::open() { // Don't re-open databases if (m_database.isOpen()) { return true; } // Create the parent directory if it doesn't exist const QString parentDir = QFileInfo(m_tagFile).absolutePath(); if (!QDir().exists(parentDir)) { if (!QDir().mkpath(parentDir)) { log(QStringLiteral("Error creating tag database parent directory"), Logger::Error); return false; } } // Load and connect to the database m_database = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), "Tag database - " + m_tagFile); m_database.setDatabaseName(m_tagFile); if (!m_database.open()) { log(QStringLiteral("Could not open tag database '%1': %2").arg(m_tagFile, m_database.lastError().text()), Logger::Error); return false; } // Create schema if necessary QSqlQuery createQuery(m_database); createQuery.prepare(QStringLiteral("CREATE TABLE IF NOT EXISTS tags (id INT, tag VARCHAR(255), ttype INT);")); if (!createQuery.exec()) { log(QStringLiteral("Could not create tag database schema: %1").arg(createQuery.lastError().text()), Logger::Error); return false; } return TagDatabase::open(); } bool TagDatabaseSqlite::close() { m_database.close(); return TagDatabase::close(); } bool TagDatabaseSqlite::load() { return TagDatabase::load(); } bool TagDatabaseSqlite::save() { return TagDatabase::save(); } void TagDatabaseSqlite::setTags(const QList<Tag> &tags, bool createTagTypes) { QSqlQuery clearQuery(m_database); clearQuery.prepare(QStringLiteral("DELETE FROM tags")); if (!clearQuery.exec()) { log(QStringLiteral("SQL error when clearing tags: %1").arg(clearQuery.lastError().text()), Logger::Error); return; } if (!m_database.transaction()) { return; } QSqlQuery addQuery(m_database); addQuery.prepare(QStringLiteral("INSERT INTO tags (id, tag, ttype) VALUES (:id, :tag, :ttype)")); for (const Tag &tag : tags) { addQuery.bindValue(":id", tag.id()); addQuery.bindValue(":tag", tag.text()); addQuery.bindValue(":ttype", m_tagTypeDatabase.get(tag.type(), createTagTypes)); if (!addQuery.exec()) { log(QStringLiteral("SQL error when adding tag: %1").arg(addQuery.lastError().text()), Logger::Error); return; } } if (!m_database.commit()) { return; } m_count = -1; } QMap<QString, TagType> TagDatabaseSqlite::getTagTypes(const QStringList &tags) const { QMap<QString, TagType> ret; // Escape values QStringList formatted; QSqlDriver *driver = m_database.driver(); for (const QString &tag : tags) { if (m_cache.contains(tag)) { ret.insert(tag, m_cache[tag]); } else { QSqlField f; f.setType(QVariant::String); f.setValue(tag); formatted.append(driver->formatValue(f)); } } // If all values have already been loaded from the memory cache if (formatted.isEmpty()) { return ret; } // Execute query const QString sql = "SELECT tag, ttype FROM tags WHERE tag IN (" + formatted.join(",") + ")"; QSqlQuery query(m_database); query.setForwardOnly(true); if (!query.exec(sql)) { log(QStringLiteral("SQL error when getting tags: %1").arg(query.lastError().text()), Logger::Error); return ret; } const int idTag = query.record().indexOf("tag"); const int idTtype = query.record().indexOf("ttype"); while (query.next()) { const QString tag = query.value(idTag).toString(); const int typeId = query.value(idTtype).toInt(); if (!m_tagTypeDatabase.contains(typeId)) { continue; } const TagType type = m_tagTypeDatabase.get(typeId); ret.insert(tag, type); m_cache.insert(tag, type); } return ret; } QMap<QString, int> TagDatabaseSqlite::getTagIds(const QStringList &tags) const { QMap<QString, int> ret; // Escape values QStringList formatted; QSqlDriver *driver = m_database.driver(); for (const QString &tag : tags) { if (m_cacheIds.contains(tag)) { ret.insert(tag, m_cacheIds[tag]); } else { QSqlField f; f.setType(QVariant::String); f.setValue(tag); formatted.append(driver->formatValue(f)); } } // If all values have already been loaded from the memory cache if (formatted.isEmpty()) { return ret; } // Execute query const QString sql = "SELECT tag, id FROM tags WHERE tag IN (" + formatted.join(",") + ")"; QSqlQuery query(m_database); query.setForwardOnly(true); if (!query.exec(sql)) { log(QStringLiteral("SQL error when getting tags: %1").arg(query.lastError().text()), Logger::Error); return ret; } const int idTag = query.record().indexOf("tag"); const int idId = query.record().indexOf("id"); while (query.next()) { const QString tag = query.value(idTag).toString(); const int id = query.value(idId).toInt(); ret.insert(tag, id); m_cacheIds.insert(tag, id); } return ret; } int TagDatabaseSqlite::count() const { if (m_count != -1) { return m_count; } QSqlQuery query(m_database); const QString sql = QStringLiteral("SELECT COUNT(*) FROM tags"); if (!query.exec(sql) || !query.next()) { log(QStringLiteral("SQL error when getting tag count: %1").arg(query.lastError().text()), Logger::Error); return -1; } m_count = query.value(0).toInt(); return m_count; } <|endoftext|>
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/tests/codegen_test_base.h" #include <stdlib.h> #include <utility> #include "tensorflow/compiler/xla/ptr_util.h" #include "tensorflow/compiler/xla/service/backend.h" #include "tensorflow/compiler/xla/service/compiler.h" #include "tensorflow/compiler/xla/service/hlo_module_config.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/subprocess.h" #include "tensorflow/core/platform/test.h" namespace xla { void CodegenTestBase::CompileAndVerifyIr(std::unique_ptr<HloModule> hlo_module, const string& pattern) { std::unique_ptr<Executable> executable = CompileToExecutable(std::move(hlo_module)); string ir_module_string = GetIrFromExecutable(*executable); RunFileCheck(ir_module_string, pattern); } std::unique_ptr<Executable> CodegenTestBase::CompileToExecutable( std::unique_ptr<HloModule> hlo_module) { auto module_config = MakeUnique<HloModuleConfig>( hlo_module->entry_computation()->ComputeProgramShape()); module_config->set_fast_math_disabled(fast_math_disabled_); return backend_->compiler() ->Compile(std::move(hlo_module), std::move(module_config), test_hlo_dumper_, backend_->default_stream_executor()) .ConsumeValueOrDie(); } void CodegenTestBase::RunFileCheck(const string& input, const string& pattern) { // Write input to a temporary file. char tempdir_template[] = "/tmp/ir_testXXXXXX"; char* tempdir_name = mkdtemp(tempdir_template); CHECK_NOTNULL(tempdir_name); string pattern_path = tensorflow::io::JoinPath(tempdir_name, "xla_hlo_test_ir_pattern"); TF_CHECK_OK(tensorflow::WriteStringToFile(tensorflow::Env::Default(), pattern_path, pattern)); // Invoke FileCheck to check whether input matches `pattern`. tensorflow::SubProcess file_check_process; const char* test_srcdir = getenv("TEST_SRCDIR"); if (test_srcdir == nullptr) { test_srcdir = "."; } string file_check_path = tensorflow::io::JoinPath( test_srcdir, "external/llvm/FileCheck"); file_check_process.SetProgram(file_check_path, {file_check_path, pattern_path}); file_check_process.SetChannelAction(tensorflow::CHAN_STDIN, tensorflow::ACTION_PIPE); file_check_process.SetChannelAction(tensorflow::CHAN_STDERR, tensorflow::ACTION_PIPE); CHECK(file_check_process.Start()); string standard_error; int exit_status = file_check_process.Communicate( /*stdin_input=*/&input, /*stdout_output=*/nullptr, /*stderr_output=*/&standard_error); // FileCheck returns 0 when the inputs match. If matching failed, we output // the error message generated by FileCheck. SCOPED_TRACE(tensorflow::strings::StrCat("Input to FileCheck:\n", input)); EXPECT_EQ(0, exit_status) << standard_error; } } // namespace xla <commit_msg>[XLA] Get correct path to FileCheck when TEST_SRCDIR is not passed. Change: 146715468<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/tests/codegen_test_base.h" #include <stdlib.h> #include <utility> #include "tensorflow/compiler/xla/ptr_util.h" #include "tensorflow/compiler/xla/service/backend.h" #include "tensorflow/compiler/xla/service/compiler.h" #include "tensorflow/compiler/xla/service/hlo_module_config.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/subprocess.h" #include "tensorflow/core/platform/test.h" namespace xla { void CodegenTestBase::CompileAndVerifyIr(std::unique_ptr<HloModule> hlo_module, const string& pattern) { std::unique_ptr<Executable> executable = CompileToExecutable(std::move(hlo_module)); string ir_module_string = GetIrFromExecutable(*executable); RunFileCheck(ir_module_string, pattern); } std::unique_ptr<Executable> CodegenTestBase::CompileToExecutable( std::unique_ptr<HloModule> hlo_module) { auto module_config = MakeUnique<HloModuleConfig>( hlo_module->entry_computation()->ComputeProgramShape()); module_config->set_fast_math_disabled(fast_math_disabled_); return backend_->compiler() ->Compile(std::move(hlo_module), std::move(module_config), test_hlo_dumper_, backend_->default_stream_executor()) .ConsumeValueOrDie(); } void CodegenTestBase::RunFileCheck(const string& input, const string& pattern) { using tensorflow::io::JoinPath; // Write input to a temporary file. char tempdir_template[] = "/tmp/ir_testXXXXXX"; char* tempdir_name = mkdtemp(tempdir_template); CHECK_NOTNULL(tempdir_name); string pattern_path = JoinPath(tempdir_name, "xla_hlo_test_ir_pattern"); TF_CHECK_OK(tensorflow::WriteStringToFile(tensorflow::Env::Default(), pattern_path, pattern)); // Invoke FileCheck to check whether input matches `pattern`. const char* file_check_path_suffix = "external/llvm/FileCheck"; string file_check_path; if (const char* test_srcdir = getenv("TEST_SRCDIR")) { file_check_path = JoinPath(test_srcdir, file_check_path_suffix); } else { file_check_path = file_check_path_suffix; } tensorflow::SubProcess file_check_process; file_check_process.SetProgram(file_check_path, {file_check_path, pattern_path}); file_check_process.SetChannelAction(tensorflow::CHAN_STDIN, tensorflow::ACTION_PIPE); file_check_process.SetChannelAction(tensorflow::CHAN_STDERR, tensorflow::ACTION_PIPE); CHECK(file_check_process.Start()); string standard_error; int exit_status = file_check_process.Communicate( /*stdin_input=*/&input, /*stdout_output=*/nullptr, /*stderr_output=*/&standard_error); // FileCheck returns 0 when the inputs match. If matching failed, we output // the error message generated by FileCheck. SCOPED_TRACE(tensorflow::strings::StrCat("Input to FileCheck:\n", input)); EXPECT_EQ(0, exit_status) << standard_error; } } // namespace xla <|endoftext|>
<commit_before>#include <cstdio> #include <QCoreApplication> #include <QUrl> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QNetworkCookieJar> #include <QNetworkCookie> #include <QTextStream> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QNetworkRequest req(QUrl("https://www.secure.pixiv.net/login.php?return_to=%2F")); // http://www.pixiv.net/ req.setHeader(QNetworkRequest::UserAgentHeader, "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36"); QNetworkAccessManager man; // QNetworkCookieJar *cookies = new QNetworkCookieJar(); /*Cookie:p_ab_id=7; login_ever=yes; hide_premium_tutorial_modal=1434740779; device_token=ef878b5484ef1a415161e577a9cfb6bd; module_orders_mypage=%5B%7B%22name%22%3A%22everyone_new_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22spotlight%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22featured_tags%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22contests%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22following_new_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22mypixiv_new_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22booth_follow_items%22%2C%22visible%22%3Atrue%7D%5D; PHPSESSID=0cb6a9cf98aba409e6d4ea6a01daa6b4 */ // cookies->insertCookie(QNetworkCookie("id", "227f9c4f9e0300a1||t=1414033339|et=730|cs=002213fd48d69442b24638839a")); // cookies->insertCookie(QNetworkCookie("login_ever", "yes")); // cookies->insertCookie(QNetworkCookie("module_orders_mypage ", "%5B%7B%22name%22%3A%22everyone_new_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22spotlight%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22featured_tags%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22contests%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22following_new_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22mypixiv_new_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22booth_follow_items%22%2C%22visible%22%3Atrue%7D%5D")); // cookies->insertCookie(QNetworkCookie("module_orders_mypage", "yes")); // cookies->insertCookie(QNetworkCookie("p_ab_id", "7")); // cookies->insertCookie(QNetworkCookie("PHPSESSID", "8405122_ae21044e54c09ae54e93cfc41dca9fb0")); // man.setCookieJar(cookies); QNetworkReply *reply = man.get(req); QObject::connect(reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), [&reply](QNetworkReply::NetworkError err) { QTextStream qerr(stderr); qerr << "Error: " << err << "\n"; }); QObject::connect(reply, &QNetworkReply::finished, [&reply]() { QTextStream qerr(stderr); QList<QNetworkReply::RawHeaderPair> headers(reply->rawHeaderPairs()); for (int i = 0; i < headers.size(); ++i) { qerr << "HEADER: " << headers[i].first << " CONTENT: " << headers[i].second << "\n"; } QByteArray response = reply->readAll(); qerr << "====BEGIN====\n"; qerr << QString::fromUtf8(response); qerr << "\n=====END====="; QString stringResp = QString::fromUtf8(response); FILE* f = std::fopen("pixiv.html", "w+"); std::fwrite(response.constData(), 1, response.size(), f); std::fclose(f); QRegExp regex("<a href=\".*\" class=\"user _ui-tooltip\" data-tooltip=\"\\(.*)\\\"><img src=\".*\" alt=\".*\" width=\".*\"></a>"); int pos = 0; while ((pos = regex.indexIn(stringResp, pos)) != -1) { qerr << "Watching: " << regex.cap(0) << "\n"; pos += regex.matchedLength(); } }); return a.exec(); } <commit_msg>test QtNetworkAccessManager<commit_after>#include <cstdio> #include <QCoreApplication> #include <QNetworkConfiguration> #include <QUrl> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QNetworkCookieJar> #include <QNetworkCookie> #include <QTextStream> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QNetworkRequest req; req.setUrl(QUrl("https://www.secure.pixiv.net/login.php?return_to=%2F")); // http://www.pixiv.net/ req.setHeader(QNetworkRequest::UserAgentHeader, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36"); req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); QNetworkAccessManager man; QNetworkCookieJar *cookies = new QNetworkCookieJar(); /* * Cookie:p_ab_id=7; login_ever=yes; hide_premium_tutorial_modal=1434740779; device_token=ef878b5484ef1a415161e577a9cfb6bd; module_orders_mypage=%5B%7B%22name%22%3A%22everyone_new_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22spotlight%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22featured_tags%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22contests%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22following_new_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22mypixiv_new_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22booth_follow_items%22%2C%22visible%22%3Atrue%7D%5D; PHPSESSID=0cb6a9cf98aba409e6d4ea6a01daa6b4 */ cookies->insertCookie(QNetworkCookie("p_ab_id", "7")); cookies->insertCookie(QNetworkCookie("login_ever", "yes")); cookies->insertCookie(QNetworkCookie("device_token", "ef878b5484ef1a415161e577a9cfb6bd")); cookies->insertCookie(QNetworkCookie("module_orders_mypage", "%5B%7B%22name%22%3A%22everyone_new_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22spotlight%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22featured_tags%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22contests%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22following_new_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22mypixiv_new_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22booth_follow_items%22%2C%22visible%22%3Atrue%7D%5D")); cookies->insertCookie(QNetworkCookie("PHPSESSID", "314f73945470380f25f72ee1469cb3cb")); man.setCookieJar(cookies); // cookies->setCookiesFromUrl(cookies->allCookies(), QUrl("https://www.secure.pixiv.net/login.php?return_to=%2F")); // login_data = {"mode":"login", // "return_to":"/", // "pixiv_id":"[email protected]", // "pass":"xjy168921", // "skip":"1" // } QByteArray *data = new QByteArray(); data->append("mode=login&return_to=http%3A%2F%2Fwww.pixiv.net%2F&pixiv_id=beta168921%40gmail.com&pass=Xjy%401995&skip=1"); QNetworkReply *reply = man.post(req,*data); // QTextStream qerr(stderr); // req.setUrl(QUrl("http://www.pixiv.net")); // reply = man.get(req); // reply = man.get(req.setUrl((QUrl("http://www.pixiv.net")))); // QNetworkReply *reply = man.get(req); QObject::connect(reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), [&reply](QNetworkReply::NetworkError err) { QTextStream qerr(stderr); qerr << "Error: " << err << "\n"; }); QObject::connect(reply, &QNetworkReply::finished, [&reply]() { QTextStream qerr(stderr); QList<QNetworkReply::RawHeaderPair> headers(reply->rawHeaderPairs()); for (int i = 0; i < headers.size(); ++i) { qerr << "HEADER: " << headers[i].first << " CONTENT: " << headers[i].second << "\n"; } QByteArray response = reply->readAll(); qerr << "====BEGIN====\n"; qerr << QString::fromUtf8(response); qerr << "\n=====END=====\n"; // qerr << reply->manager()->configuration().isValid(); // qerr << reply->manager()->configuration().name(); // qerr << reply->manager()->cookieJar()->allCookies(); QList<QNetworkCookie> list = reply->manager()->cookieJar()->cookiesForUrl(QUrl("http://www.pixiv.net")); for(int i = 0; i<list.size(); i++) { qerr << list.at(i).name() << "\t" << list.at(i).value() << "\n"; } QString stringResp = QString::fromUtf8(response); FILE* f = std::fopen("pixiv.html", "w+"); std::fwrite(response.constData(), 1, response.size(), f); std::fclose(f); // QRegExp regex("<a href=\".*\" class=\"user _ui-tooltip\" data-tooltip=\"\\(.*)\\\"><img src=\".*\" alt=\".*\" width=\".*\"></a>"); // int pos = 0; // while ((pos = regex.indexIn(stringResp, pos)) != -1) { // qerr << "Watching: " << regex.cap(0) << "\n"; // pos += regex.matchedLength(); // } }); return a.exec(); } <|endoftext|>
<commit_before>// Copyright (c) 2007, 2008 libmv authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include <cstdio> #include "libmv/correspondence/matches.h" #include "libmv/correspondence/feature.h" #include "libmv/logging/logging.h" #include "testing/testing.h" using libmv::Matches; using libmv::Feature; namespace { // A derived feature with a tag, so that it is possible to check that the right // features are produced by the iterators. struct MyPoint : public Feature { virtual ~MyPoint() {} MyPoint(int the_tag) : tag(the_tag) {} int tag; }; struct SiblingTestFeature : public Feature { virtual ~SiblingTestFeature() {} }; TEST(Matches, FilteringIterators) { Matches matches; int expected_its[] = { 1, 1, 11, 1, 2, 12, 2, 8, 14, 3, 9, 15, 0 }; int max_i = 0; for (; expected_its[max_i]; max_i += 3) { matches.Insert(expected_its[max_i + 0], expected_its[max_i + 1], new MyPoint(expected_its[max_i + 2])); LOG(INFO) << "Inserting " << expected_its[max_i + 0] << ", " << expected_its[max_i + 1] << ", " << expected_its[max_i + 2]; } // Add other types of features to filter out. matches.Insert(0, 0, new SiblingTestFeature); matches.Insert(4, 4, new SiblingTestFeature); matches.Insert(2, 4, new SiblingTestFeature); matches.Insert(9, 5, new SiblingTestFeature); matches.Insert(9, 10, new SiblingTestFeature); // Over images, then features in each image. int i = 0; for (Matches::ImageIterator it = matches.ImageBegin(); it != matches.ImageEnd(); ++it) { for (Matches::ImageFeatureIterator<MyPoint> tt = it.begin<MyPoint>(); tt != it.end<MyPoint>(); ++tt) { LOG(INFO) << "tt.image() " << tt.image() << " tt.track() " << tt.track() << " tt.feature()->tag() " << tt.feature()->tag; ASSERT_LT(i, max_i); EXPECT_EQ(expected_its[i+0], tt.image()); EXPECT_EQ(expected_its[i+1], tt.track()); EXPECT_EQ(expected_its[i+2], tt.feature()->tag); i += 3; } } EXPECT_EQ(12, i); // Over tracks, then features in each track. Because of specially selected // bipartite graph edges, the ordering is the same as above. i = 0; for (Matches::TrackIterator it = matches.TrackBegin(); it != matches.TrackEnd(); ++it) { for (Matches::TrackFeatureIterator<MyPoint> tt = it.begin<MyPoint>(); tt != it.end<MyPoint>(); ++tt) { LOG(INFO) << "tt.image() " << tt.image() << " tt.track() " << tt.track() << " tt.feature()->tag() " << tt.feature()->tag; ASSERT_LT(i, max_i); EXPECT_EQ(expected_its[i+0], tt.image()); EXPECT_EQ(expected_its[i+1], tt.track()); EXPECT_EQ(expected_its[i+2], tt.feature()->tag); i += 3; } } EXPECT_EQ(12, i); DeleteMatchFeatures(&matches); } TEST(Matches, IteratingOverTracksInCertainImages) { // It's often necessary to iterate over either all the tracks that are // visible in a given set of images. We do this with an iterator, shown // below, which takes a set of images and then iterates over the tracks which // appear in all images. int features[] = { // Image ID, track ID, feature tag. 1, 1, 11, // Track 1 is in all 3 images. 2, 1, 12, 3, 1, 13, 1, 2, 14, // This track, 2, should be ignored. 2, 2, 15, 1, 3, 16, // Track 3 is in all 3 images. 2, 3, 17, 3, 3, 18, 6, 3, 19, // This feature should not be scanned. 6, 4, 20, // This track should not be scanned. 0 }; Matches matches; int max_i = 0; for (; features[max_i]; max_i += 3) { matches.Insert(features[max_i + 0], features[max_i + 1], new MyPoint(features[max_i + 2])); LOG(INFO) << "> " << features[max_i + 0] << ", " << features[max_i + 1] << ", " << features[max_i + 2]; } EXPECT_EQ(max_i, 30); // Insert some distractor tracks matches.Insert(1, 50, new SiblingTestFeature); matches.Insert(2, 50, new SiblingTestFeature); matches.Insert(3, 50, new SiblingTestFeature); matches.Insert(1, 51, new SiblingTestFeature); matches.Insert(2, 51, new SiblingTestFeature); matches.Insert(3, 51, new SiblingTestFeature); std::set<Matches::Image> images; images.insert(1); images.insert(2); images.insert(3); int expected_features[] = { // Image ID, track ID, feature tag. 1, 1, 11, // Track 1 is in all 3 images. 2, 1, 12, 3, 1, 13, 1, 3, 16, // Track 3 is in all 3 images. 2, 3, 17, 3, 3, 18, 0 }; int i = 0; int num_tracks = 0; // Finally accumulate the tracks. for (Matches::TracksInImagesIterator<MyPoint> it = matches.TracksInImagesBegin<MyPoint>(images); it != matches.TracksInImagesEnd<MyPoint>(images); ++it) { for (Matches::TracksInImagesFeatureIterator<MyPoint> tt = it.begin(); tt != it.end(); ++tt) { // Stack feature x,y,whatever into matrix. EXPECT_EQ(expected_features[i + 0], tt.image()); EXPECT_EQ(expected_features[i + 1], tt.track()); EXPECT_EQ(expected_features[i + 2], tt.feature()->tag); i += 3; } LOG(INFO) << "Track: " << *it; ++num_tracks; } EXPECT_EQ(18, i); EXPECT_EQ(2, num_tracks); } } // namespace <commit_msg>Fix comments.<commit_after>// Copyright (c) 2007, 2008 libmv authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include <cstdio> #include "libmv/correspondence/matches.h" #include "libmv/correspondence/feature.h" #include "libmv/logging/logging.h" #include "testing/testing.h" using libmv::Matches; using libmv::Feature; namespace { // A derived feature with a tag, so that it is possible to check that the right // features are produced by the iterators. struct MyPoint : public Feature { virtual ~MyPoint() {} MyPoint(int the_tag) : tag(the_tag) {} int tag; }; struct SiblingTestFeature : public Feature { virtual ~SiblingTestFeature() {} }; TEST(Matches, FilteringIterators) { Matches matches; int expected_its[] = { 1, 1, 11, 1, 2, 12, 2, 8, 14, 3, 9, 15, 0 }; int max_i = 0; for (; expected_its[max_i]; max_i += 3) { matches.Insert(expected_its[max_i + 0], expected_its[max_i + 1], new MyPoint(expected_its[max_i + 2])); LOG(INFO) << "Inserting " << expected_its[max_i + 0] << ", " << expected_its[max_i + 1] << ", " << expected_its[max_i + 2]; } // Add other types of features to filter out. matches.Insert(0, 0, new SiblingTestFeature); matches.Insert(4, 4, new SiblingTestFeature); matches.Insert(2, 4, new SiblingTestFeature); matches.Insert(9, 5, new SiblingTestFeature); matches.Insert(9, 10, new SiblingTestFeature); // Over images, then features in each image. int i = 0; for (Matches::ImageIterator it = matches.ImageBegin(); it != matches.ImageEnd(); ++it) { for (Matches::ImageFeatureIterator<MyPoint> tt = it.begin<MyPoint>(); tt != it.end<MyPoint>(); ++tt) { LOG(INFO) << "tt.image() " << tt.image() << " tt.track() " << tt.track() << " tt.feature()->tag() " << tt.feature()->tag; ASSERT_LT(i, max_i); EXPECT_EQ(expected_its[i+0], tt.image()); EXPECT_EQ(expected_its[i+1], tt.track()); EXPECT_EQ(expected_its[i+2], tt.feature()->tag); i += 3; } } EXPECT_EQ(12, i); // Over tracks, then features in each track. Because of specially selected // bipartite graph edges, the ordering is the same as above. i = 0; for (Matches::TrackIterator it = matches.TrackBegin(); it != matches.TrackEnd(); ++it) { for (Matches::TrackFeatureIterator<MyPoint> tt = it.begin<MyPoint>(); tt != it.end<MyPoint>(); ++tt) { LOG(INFO) << "tt.image() " << tt.image() << " tt.track() " << tt.track() << " tt.feature()->tag() " << tt.feature()->tag; ASSERT_LT(i, max_i); EXPECT_EQ(expected_its[i+0], tt.image()); EXPECT_EQ(expected_its[i+1], tt.track()); EXPECT_EQ(expected_its[i+2], tt.feature()->tag); i += 3; } } EXPECT_EQ(12, i); DeleteMatchFeatures(&matches); } TEST(Matches, IteratingOverTracksInCertainImages) { // It's often necessary to iterate over either all the tracks that are // visible in a given set of images. We do this with an iterator, shown // below, which takes a set of images and then iterates over the tracks which // appear in all images. int features[] = { // Image ID, track ID, feature tag. 1, 1, 11, // Track 1 is in all 3 images. 2, 1, 12, 3, 1, 13, 1, 2, 14, // This track, 2, should be ignored. 2, 2, 15, 1, 3, 16, // Track 3 is in all 3 images. 2, 3, 17, 3, 3, 18, 6, 3, 19, // This feature should not be scanned. 6, 4, 20, // This track should not be scanned. 0 }; Matches matches; int max_i = 0; for (; features[max_i]; max_i += 3) { matches.Insert(features[max_i + 0], features[max_i + 1], new MyPoint(features[max_i + 2])); LOG(INFO) << "> " << features[max_i + 0] << ", " << features[max_i + 1] << ", " << features[max_i + 2]; } EXPECT_EQ(max_i, 30); // Insert some distractor tracks matches.Insert(1, 50, new SiblingTestFeature); matches.Insert(2, 50, new SiblingTestFeature); matches.Insert(3, 50, new SiblingTestFeature); matches.Insert(1, 51, new SiblingTestFeature); matches.Insert(2, 51, new SiblingTestFeature); matches.Insert(3, 51, new SiblingTestFeature); std::set<Matches::Image> images; images.insert(1); images.insert(2); images.insert(3); int expected_features[] = { // Image ID, track ID, feature tag. 1, 1, 11, // Track 1 is in all 3 images. 2, 1, 12, 3, 1, 13, 1, 3, 16, // Track 3 is in all 3 images. 2, 3, 17, 3, 3, 18, 0 }; int i = 0; int num_tracks = 0; // For each track... for (Matches::TracksInImagesIterator<MyPoint> it = matches.TracksInImagesBegin<MyPoint>(images); it != matches.TracksInImagesEnd<MyPoint>(images); ++it) { // For each feature... for (Matches::TracksInImagesFeatureIterator<MyPoint> tt = it.begin(); tt != it.end(); ++tt) { EXPECT_EQ(expected_features[i + 0], tt.image()); EXPECT_EQ(expected_features[i + 1], tt.track()); EXPECT_EQ(expected_features[i + 2], tt.feature()->tag); i += 3; } LOG(INFO) << "Track: " << *it; ++num_tracks; } EXPECT_EQ(18, i); EXPECT_EQ(2, num_tracks); } } // namespace <|endoftext|>
<commit_before>/* * caosVM_debug.cpp * openc2e * * Created by Alyssa Milburn on Sun Oct 24 2004. * Copyright (c) 2004 Alyssa Milburn. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "caosVM.h" #include "openc2e.h" #include "Agent.h" #include "World.h" #include <iostream> #include "cmddata.h" #include <cctype> #include "dialect.h" #include <algorithm> #include "caosScript.h" // #include "malloc.h" <- unportable horror! #include <sstream> #include <boost/format.hpp> using std::cerr; using std::cout; /** DBG: OUTS (command) val (string) %status maybe %pragma variants all Outputs a string to the debug log. */ void caosVM::c_DBG_OUTS() { VM_PARAM_STRING(val) cout << val << std::endl; } /** DBGM (command) val (bareword) %status maybe %pragma variants c1 c2 %pragma implementation caosVM::c_DBG_OUTS */ /** DBG: OUTV (command) val (decimal) %status maybe %pragma variants all Outputs a decimal value to the debug log. */ void caosVM::c_DBG_OUTV() { VM_VERIFY_SIZE(1) VM_PARAM_VALUE(val) if (val.hasFloat()) { cout << boost::format("%0.06f") % val.getFloat(); } else if (val.hasInt()) { cout << val.getInt(); } else if (val.hasVector()) { const Vector<float> &v = val.getVector(); cout << boost::format("(%0.6f, %0.6f)") % v.x % v.y; } else throw badParamException(); cout << std::endl; } /** DBGV (command) val (integer) %status maybe %pragma variants c1 c2 %pragma implementation caosVM::c_DBG_OUTV */ /** DBUG (command) val (integer) %status maybe %pragma variants c1 c2 */ void caosVM::c_DBUG() { inst = true; c_DBG_OUTV(); } /** UNID (integer) %status maybe %pragma variants c3 cv sm Returns the unique ID of the target agent. This is currently no good for persisting. XXX: when serialization support works, this might well become good for persisting :) */ void caosVM::v_UNID() { VM_VERIFY_SIZE(0) valid_agent(targ); result.setInt(targ->getUNID()); } /** UNID (agent) %status maybe %pragma variants c2 %pragma implementation caosVM::v_UNID_c2 Returns the unique ID of the target agent. This is currently no good for persisting. */ void caosVM::v_UNID_c2() { VM_VERIFY_SIZE(0) valid_agent(targ); result.setAgent(targ); } /** AGNT (agent) id (integer) %status maybe Returns the agent with the given UNID, or NULL if agent has been deleted. */ void caosVM::v_AGNT() { VM_VERIFY_SIZE(1) VM_PARAM_INTEGER(id) result.setAgent(world.lookupUNID(id)); } /** DBG: MALLOC (command) %status stub Dumps some random memory stats to stderr. */ void caosVM::c_DBG_MALLOC() { VM_VERIFY_SIZE(0) // more unportable horror! /* struct mallinfo mi = mallinfo(); #define MPRINT(name) \ fprintf(stderr, "%10s = %d\n", #name, mi. name) MPRINT(arena); MPRINT(ordblks); MPRINT(smblks); MPRINT(hblks); MPRINT(hblkhd); MPRINT(usmblks); MPRINT(fsmblks); MPRINT(uordblks); MPRINT(fordblks); MPRINT(keepcost); malloc_stats(); */ /*std::cerr << "caosSlab free=" << caosVarSlab.free_elements() << " used=" << caosVarSlab.used_elements() << " total=" << caosVarSlab.total_elements() << std::endl;*/ } /** DBG: DUMP (command) %status ok %pragma variants all Dumps the current script's bytecode to stderr. */ void caosVM::c_DBG_DUMP() { std::cerr << vm->currentscript->dump(); } /** DBG: TRACE (command) level (integer) %status ok %pragma variants all Sets opcode trace level. Zero disables. */ void caosVM::c_DBG_TRACE() { VM_PARAM_INTEGER(en) std::cerr << "trace: " << en << std::endl; vm->trace = en; if (vm->trace < 0) vm->trace = 0; } /** MANN (command) cmd (string) %status stub Looks up documentation on the given command and spits it on the current output stream. */ void caosVM::c_MANN() { VM_PARAM_STRING(cmd) caos_assert(outputstream); std::transform(cmd.begin(), cmd.end(), cmd.begin(), toupper); const cmdinfo *i = currentscript->dialect->cmdbase(); bool found = false; while (i->lookup_key) { // TODO: this doesn't work for FACE at the moment due to hack elsewhere if (cmd == i->fullname) { found = true; std::string d = i->docs; // TODO: docs should always include name/parameters/etc, so should never be empty if (d.size()) *outputstream << std::string(i->docs) << std::endl; else *outputstream << "no documentation for " << cmd << std::endl << std::endl; } i++; } if (!found) { *outputstream << "didn't find " << cmd << std::endl; return; } } /** DBG: DISA (command) family (integer) genus (integer) species (integer) event (integer) %pragma variants all %status ok Dumps the "bytecode" of the indicated script to the current output channel. Note that this isn't really bytecode yet (though that's a possible future improvement). If the script is not found no output will be generated. */ void caosVM::c_DBG_DISA() { VM_PARAM_INTEGER(event) VM_PARAM_INTEGER(species) VM_PARAM_INTEGER(genus) VM_PARAM_INTEGER(family) caos_assert(outputstream); shared_ptr<script> s = world.scriptorium.getScript(family, genus, species, event); if (s) { if (s->fmly != family || s->gnus != genus || s->spcs != species) { *outputstream << "warning: search resulted in script from " << s->fmly << ", " << s->gnus << ", " << s->spcs << " script" << std::endl; } *outputstream << s->dump(); } else *outputstream << "no such script" << std::endl; } /** DBG: ASRT (command) condition (condition) %pragma parser new AssertParser() %pragma variants all %status maybe Blows up unless the given condition is true. */ void caosVM::c_DBG_ASRT() { throw caosException("DBG: ASRT condition failed"); } /** DBG: IDNT (string) agent (agent) %status ok %pragma variants all (openc2e-only) Return a nicely-formatted string identifying the classifier of the agent, using the catalogue to find the name if possible. */ void caosVM::v_DBG_IDNT() { VM_PARAM_AGENT(a) if (!a) result.setString("(null)"); else result.setString(a->identify()); } /** DBG: PROF (command) %status stub Dumps the current agent profiling information to the output stream, in CSV format. */ void caosVM::c_DBG_PROF() { // TODO } /** DBG: CPRO (command) %status stub Clears the current agent profiling information. */ void caosVM::c_DBG_CPRO() { // TODO } /** DBG: STOK (string) bareword (bareword) %status ok %pragma variants all Returns the bare token in 'bareword' as a string. */ void caosVM::v_DBG_STOK() { VM_PARAM_STRING(bareword) result.setString(bareword); } /** DBG: TSLC (command) timeslice (integer) %status ok %pragma variants all %cost 0 Sets the currently executing script's remaining timeslice value. This command affects only the current timeslice; future slices use the normal amount for the dialect in question. */ void caosVM::c_DBG_TSLC() { VM_PARAM_INTEGER(tslc); timeslice = tslc; } /** DBG: TSLC (integer) %status ok %pragma variants all Returns the number of ticks left in the current script's remaining timeslice. */ void caosVM::v_DBG_TSLC() { result.setInt(timeslice); } /** DBG: SIZO (string) %status ok %pragma variants all Returns a human-readable profile of the sizes and allocation counts of various internal data structures */ void caosVM::v_DBG_SIZO() { std::ostringstream oss; #define SIZEOF_OUT(t) do { oss << "sizeof(" #t ") = " << sizeof(t) << std::endl; } while(0) SIZEOF_OUT(caosVM); SIZEOF_OUT(caosVar); SIZEOF_OUT(Agent); #undef SIZEOF_OUT #ifdef PROFILE_ALLOCATION_COUNT AllocationCounter::walk(oss); #else oss << "This build of openc2e does not have allocation profiling enabled." << std::endl; #endif oss << "Free caosVMs: " << world.vmpool_size() << std::endl; result.setString(oss.str()); } /* vim: set noet: */ <commit_msg>Add some additional types to DBG: SIZO output, tweak message a bit<commit_after>/* * caosVM_debug.cpp * openc2e * * Created by Alyssa Milburn on Sun Oct 24 2004. * Copyright (c) 2004 Alyssa Milburn. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "caosVM.h" #include "openc2e.h" #include "Agent.h" #include "World.h" #include <iostream> #include "cmddata.h" #include <cctype> #include "dialect.h" #include <algorithm> #include "caosScript.h" // #include "malloc.h" <- unportable horror! #include <sstream> #include <boost/format.hpp> using std::cerr; using std::cout; /** DBG: OUTS (command) val (string) %status maybe %pragma variants all Outputs a string to the debug log. */ void caosVM::c_DBG_OUTS() { VM_PARAM_STRING(val) cout << val << std::endl; } /** DBGM (command) val (bareword) %status maybe %pragma variants c1 c2 %pragma implementation caosVM::c_DBG_OUTS */ /** DBG: OUTV (command) val (decimal) %status maybe %pragma variants all Outputs a decimal value to the debug log. */ void caosVM::c_DBG_OUTV() { VM_VERIFY_SIZE(1) VM_PARAM_VALUE(val) if (val.hasFloat()) { cout << boost::format("%0.06f") % val.getFloat(); } else if (val.hasInt()) { cout << val.getInt(); } else if (val.hasVector()) { const Vector<float> &v = val.getVector(); cout << boost::format("(%0.6f, %0.6f)") % v.x % v.y; } else throw badParamException(); cout << std::endl; } /** DBGV (command) val (integer) %status maybe %pragma variants c1 c2 %pragma implementation caosVM::c_DBG_OUTV */ /** DBUG (command) val (integer) %status maybe %pragma variants c1 c2 */ void caosVM::c_DBUG() { inst = true; c_DBG_OUTV(); } /** UNID (integer) %status maybe %pragma variants c3 cv sm Returns the unique ID of the target agent. This is currently no good for persisting. XXX: when serialization support works, this might well become good for persisting :) */ void caosVM::v_UNID() { VM_VERIFY_SIZE(0) valid_agent(targ); result.setInt(targ->getUNID()); } /** UNID (agent) %status maybe %pragma variants c2 %pragma implementation caosVM::v_UNID_c2 Returns the unique ID of the target agent. This is currently no good for persisting. */ void caosVM::v_UNID_c2() { VM_VERIFY_SIZE(0) valid_agent(targ); result.setAgent(targ); } /** AGNT (agent) id (integer) %status maybe Returns the agent with the given UNID, or NULL if agent has been deleted. */ void caosVM::v_AGNT() { VM_VERIFY_SIZE(1) VM_PARAM_INTEGER(id) result.setAgent(world.lookupUNID(id)); } /** DBG: MALLOC (command) %status stub Dumps some random memory stats to stderr. */ void caosVM::c_DBG_MALLOC() { VM_VERIFY_SIZE(0) // more unportable horror! /* struct mallinfo mi = mallinfo(); #define MPRINT(name) \ fprintf(stderr, "%10s = %d\n", #name, mi. name) MPRINT(arena); MPRINT(ordblks); MPRINT(smblks); MPRINT(hblks); MPRINT(hblkhd); MPRINT(usmblks); MPRINT(fsmblks); MPRINT(uordblks); MPRINT(fordblks); MPRINT(keepcost); malloc_stats(); */ /*std::cerr << "caosSlab free=" << caosVarSlab.free_elements() << " used=" << caosVarSlab.used_elements() << " total=" << caosVarSlab.total_elements() << std::endl;*/ } /** DBG: DUMP (command) %status ok %pragma variants all Dumps the current script's bytecode to stderr. */ void caosVM::c_DBG_DUMP() { std::cerr << vm->currentscript->dump(); } /** DBG: TRACE (command) level (integer) %status ok %pragma variants all Sets opcode trace level. Zero disables. */ void caosVM::c_DBG_TRACE() { VM_PARAM_INTEGER(en) std::cerr << "trace: " << en << std::endl; vm->trace = en; if (vm->trace < 0) vm->trace = 0; } /** MANN (command) cmd (string) %status stub Looks up documentation on the given command and spits it on the current output stream. */ void caosVM::c_MANN() { VM_PARAM_STRING(cmd) caos_assert(outputstream); std::transform(cmd.begin(), cmd.end(), cmd.begin(), toupper); const cmdinfo *i = currentscript->dialect->cmdbase(); bool found = false; while (i->lookup_key) { // TODO: this doesn't work for FACE at the moment due to hack elsewhere if (cmd == i->fullname) { found = true; std::string d = i->docs; // TODO: docs should always include name/parameters/etc, so should never be empty if (d.size()) *outputstream << std::string(i->docs) << std::endl; else *outputstream << "no documentation for " << cmd << std::endl << std::endl; } i++; } if (!found) { *outputstream << "didn't find " << cmd << std::endl; return; } } /** DBG: DISA (command) family (integer) genus (integer) species (integer) event (integer) %pragma variants all %status ok Dumps the "bytecode" of the indicated script to the current output channel. Note that this isn't really bytecode yet (though that's a possible future improvement). If the script is not found no output will be generated. */ void caosVM::c_DBG_DISA() { VM_PARAM_INTEGER(event) VM_PARAM_INTEGER(species) VM_PARAM_INTEGER(genus) VM_PARAM_INTEGER(family) caos_assert(outputstream); shared_ptr<script> s = world.scriptorium.getScript(family, genus, species, event); if (s) { if (s->fmly != family || s->gnus != genus || s->spcs != species) { *outputstream << "warning: search resulted in script from " << s->fmly << ", " << s->gnus << ", " << s->spcs << " script" << std::endl; } *outputstream << s->dump(); } else *outputstream << "no such script" << std::endl; } /** DBG: ASRT (command) condition (condition) %pragma parser new AssertParser() %pragma variants all %status maybe Blows up unless the given condition is true. */ void caosVM::c_DBG_ASRT() { throw caosException("DBG: ASRT condition failed"); } /** DBG: IDNT (string) agent (agent) %status ok %pragma variants all (openc2e-only) Return a nicely-formatted string identifying the classifier of the agent, using the catalogue to find the name if possible. */ void caosVM::v_DBG_IDNT() { VM_PARAM_AGENT(a) if (!a) result.setString("(null)"); else result.setString(a->identify()); } /** DBG: PROF (command) %status stub Dumps the current agent profiling information to the output stream, in CSV format. */ void caosVM::c_DBG_PROF() { // TODO } /** DBG: CPRO (command) %status stub Clears the current agent profiling information. */ void caosVM::c_DBG_CPRO() { // TODO } /** DBG: STOK (string) bareword (bareword) %status ok %pragma variants all Returns the bare token in 'bareword' as a string. */ void caosVM::v_DBG_STOK() { VM_PARAM_STRING(bareword) result.setString(bareword); } /** DBG: TSLC (command) timeslice (integer) %status ok %pragma variants all %cost 0 Sets the currently executing script's remaining timeslice value. This command affects only the current timeslice; future slices use the normal amount for the dialect in question. */ void caosVM::c_DBG_TSLC() { VM_PARAM_INTEGER(tslc); timeslice = tslc; } /** DBG: TSLC (integer) %status ok %pragma variants all Returns the number of ticks left in the current script's remaining timeslice. */ void caosVM::v_DBG_TSLC() { result.setInt(timeslice); } /** DBG: SIZO (string) %status ok %pragma variants all Returns a human-readable profile of the sizes and allocation counts of various internal data structures */ void caosVM::v_DBG_SIZO() { std::ostringstream oss; #define SIZEOF_OUT(t) do { oss << "sizeof(" #t ") = " << sizeof(t) << std::endl; } while(0) SIZEOF_OUT(caosVM); SIZEOF_OUT(caosVar); SIZEOF_OUT(Agent); SIZEOF_OUT(std::string); SIZEOF_OUT(AgentRef); SIZEOF_OUT(Vector<float>); #ifdef PROFILE_ALLOCATION_COUNT AllocationCounter::walk(oss); #else oss << "This build of openc2e does not have allocation profiling enabled." << std::endl; #endif oss << "caosVMs in pool: " << world.vmpool_size() << std::endl; #undef SIZEOF_OUT result.setString(oss.str()); } /* vim: set noet: */ <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Jon Binney */ #include <ros/ros.h> #include <moveit_msgs/SaveMap.h> #include <moveit_msgs/LoadMap.h> #include <moveit/occupancy_map_monitor/occupancy_map.h> #include <moveit/occupancy_map_monitor/occupancy_map_monitor.h> #include <moveit/occupancy_map_monitor/point_cloud_occupancy_map_updater.h> #include <octomap_msgs/conversions.h> namespace occupancy_map_monitor { OccupancyMapMonitor::OccupancyMapMonitor(const Options &opt, const boost::shared_ptr<tf::Transformer> &tf) : nh_("~") { initialize(opt, tf); } OccupancyMapMonitor::OccupancyMapMonitor(const boost::shared_ptr<tf::Transformer> &tf) : nh_("~") { Options opt; // empty set of options; this will lead to having everything read from the param server initialize(opt, tf); } void OccupancyMapMonitor::initialize(const Options &input_opt, const boost::shared_ptr<tf::Transformer> &tf) { tree_update_thread_running_ = false; opt_ = input_opt; // we need to be able to update options /* load params from param server */ if (opt_.map_resolution <= 0.0) if (!nh_.getParam("octomap_resolution", opt_.map_resolution)) { opt_.map_resolution = 0.1; ROS_WARN("Resolution not specified for Octomap."); } ROS_DEBUG("Using resolution = %lf m for building octomap", opt_.map_resolution); if (opt_.map_frame.empty()) if (!nh_.getParam("octomap_frame", opt_.map_frame)) ROS_WARN("No target frame specified for Octomap. No transforms will be applied to received data."); tree_.reset(new OccMapTree(opt_.map_resolution)); tree_const_ = tree_; XmlRpc::XmlRpcValue sensor_list; if (nh_.getParam("sensors", sensor_list)) { if(!sensor_list.getType() == XmlRpc::XmlRpcValue::TypeArray) { ROS_ERROR("List of sensors must be an array!"); return; } for (int32_t i = 0; i < sensor_list.size(); ++i) { if(!sensor_list[i].getType() == XmlRpc::XmlRpcValue::TypeStruct) { ROS_ERROR("Params for sensor %d not a struct, ignoring sensor", i); continue; } if(!sensor_list[i].hasMember ("sensor_type")) { ROS_ERROR("No sensor type for sensor %d, ignoring sensor", i); continue; } std::string sensor_type = std::string (sensor_list[i]["sensor_type"]); boost::shared_ptr<OccupancyMapUpdater> up; if(sensor_type == "point_cloud_sensor") { up.reset(new PointCloudOccupancyMapUpdater(tf, opt_.map_frame)); } else { ROS_ERROR("Sensor %d has unknown type %s, ignoring sensor", i, sensor_type.c_str()); continue; } /* pass the params struct directly in to the updater */ if(!up->setParams(sensor_list[i])) { ROS_ERROR("Failed to load sensor %d of type %s", i, sensor_type.c_str()); continue; } up->setNotifyFunction(boost::bind(&OccupancyMapMonitor::updateReady, this, _1)); map_updaters_.push_back(up); } } octree_binary_pub_ = root_nh_.advertise<octomap_msgs::Octomap>("octomap_binary", 1); /* advertise a service for loading octomaps from disk */ save_map_srv_ = nh_.advertiseService("save_map", &OccupancyMapMonitor::saveMapCallback, this); load_map_srv_ = nh_.advertiseService("load_map", &OccupancyMapMonitor::loadMapCallback, this); } bool OccupancyMapMonitor::saveMapCallback(moveit_msgs::SaveMap::Request& request, moveit_msgs::SaveMap::Response& response) { ROS_INFO("Writing map to %s", request.filename.c_str()); this->lockOcTreeRead(); response.success = tree_->write(request.filename); this->unlockOcTreeRead(); return true; } bool OccupancyMapMonitor::loadMapCallback(moveit_msgs::LoadMap::Request& request, moveit_msgs::LoadMap::Response& response) { ROS_INFO("Reading map from %s", request.filename.c_str()); this->lockOcTreeWrite(); /* load the octree from disk */ octomap::AbstractOcTree* tree = octomap::AbstractOcTree::read(request.filename); if(tree == NULL) { ROS_ERROR("Failed to load map from file"); response.success = false; return true; } /* cast the abstract octree to the right type and update our shared pointer */ tree_.reset(dynamic_cast<OccMapTree*>(tree)); response.success = true; this->unlockOcTreeWrite(); return true; } void OccupancyMapMonitor::treeUpdateThread() { std::set<OccupancyMapUpdater*> ready; while (tree_update_thread_running_) { { boost::mutex::scoped_lock update_lock(update_mut_); if (update_cond_.timed_wait(update_lock, boost::posix_time::milliseconds(100))) updates_available_.swap(ready); } if (tree_update_thread_running_ && !ready.empty()) { ROS_DEBUG("Calling updaters"); { boost::unique_lock<boost::shared_mutex> ulock(tree_mutex_); for (std::set<OccupancyMapUpdater*>::iterator it = ready.begin() ; it != ready.end() ; ++it) (*it)->process(tree_); } if (update_callback_) update_callback_(); ready.clear(); publish_octomap_binary(); } } } void OccupancyMapMonitor::updateReady(OccupancyMapUpdater *updater) { { boost::mutex::scoped_lock update_lock(update_mut_); updates_available_.insert(updater); } update_cond_.notify_all(); } void OccupancyMapMonitor::lockOcTreeRead() { tree_mutex_.lock_shared(); } void OccupancyMapMonitor::unlockOcTreeRead() { tree_mutex_.unlock_shared(); } void OccupancyMapMonitor::lockOcTreeWrite() { tree_mutex_.lock(); } void OccupancyMapMonitor::unlockOcTreeWrite() { tree_mutex_.unlock(); } void OccupancyMapMonitor::publish_octomap_binary() { octomap_msgs::Octomap map; map.header.frame_id = opt_.map_frame; map.header.stamp = ros::Time::now(); if (octomap_msgs::binaryMapToMsgData(*tree_, map.data)) { octree_binary_pub_.publish(map); } else { ROS_ERROR("Could not generate OctoMap message"); } } void OccupancyMapMonitor::startMonitor() { if (!tree_update_thread_running_) { /* initialize all of the occupancy map updaters */ std::vector<boost::shared_ptr<OccupancyMapUpdater> >::iterator it; for (it = map_updaters_.begin(); it != map_updaters_.end(); it++) (*it)->initialize(); /* start a dedicated thread for updating the occupancy map */ tree_update_thread_running_ = true; tree_update_thread_.reset(new boost::thread(&OccupancyMapMonitor::treeUpdateThread, this)); } } void OccupancyMapMonitor::stopMonitor() { if (tree_update_thread_running_) { tree_update_thread_running_ = false; tree_update_thread_->join(); tree_update_thread_.reset(); } } OccupancyMapMonitor::~OccupancyMapMonitor() { stopMonitor(); } } <commit_msg>release lock when loading octomap from file fails<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Jon Binney */ #include <ros/ros.h> #include <moveit_msgs/SaveMap.h> #include <moveit_msgs/LoadMap.h> #include <moveit/occupancy_map_monitor/occupancy_map.h> #include <moveit/occupancy_map_monitor/occupancy_map_monitor.h> #include <moveit/occupancy_map_monitor/point_cloud_occupancy_map_updater.h> #include <octomap_msgs/conversions.h> namespace occupancy_map_monitor { OccupancyMapMonitor::OccupancyMapMonitor(const Options &opt, const boost::shared_ptr<tf::Transformer> &tf) : nh_("~") { initialize(opt, tf); } OccupancyMapMonitor::OccupancyMapMonitor(const boost::shared_ptr<tf::Transformer> &tf) : nh_("~") { Options opt; // empty set of options; this will lead to having everything read from the param server initialize(opt, tf); } void OccupancyMapMonitor::initialize(const Options &input_opt, const boost::shared_ptr<tf::Transformer> &tf) { tree_update_thread_running_ = false; opt_ = input_opt; // we need to be able to update options /* load params from param server */ if (opt_.map_resolution <= 0.0) if (!nh_.getParam("octomap_resolution", opt_.map_resolution)) { opt_.map_resolution = 0.1; ROS_WARN("Resolution not specified for Octomap."); } ROS_DEBUG("Using resolution = %lf m for building octomap", opt_.map_resolution); if (opt_.map_frame.empty()) if (!nh_.getParam("octomap_frame", opt_.map_frame)) ROS_WARN("No target frame specified for Octomap. No transforms will be applied to received data."); tree_.reset(new OccMapTree(opt_.map_resolution)); tree_const_ = tree_; XmlRpc::XmlRpcValue sensor_list; if (nh_.getParam("sensors", sensor_list)) { if(!sensor_list.getType() == XmlRpc::XmlRpcValue::TypeArray) { ROS_ERROR("List of sensors must be an array!"); return; } for (int32_t i = 0; i < sensor_list.size(); ++i) { if(!sensor_list[i].getType() == XmlRpc::XmlRpcValue::TypeStruct) { ROS_ERROR("Params for sensor %d not a struct, ignoring sensor", i); continue; } if(!sensor_list[i].hasMember ("sensor_type")) { ROS_ERROR("No sensor type for sensor %d, ignoring sensor", i); continue; } std::string sensor_type = std::string (sensor_list[i]["sensor_type"]); boost::shared_ptr<OccupancyMapUpdater> up; if(sensor_type == "point_cloud_sensor") { up.reset(new PointCloudOccupancyMapUpdater(tf, opt_.map_frame)); } else { ROS_ERROR("Sensor %d has unknown type %s, ignoring sensor", i, sensor_type.c_str()); continue; } /* pass the params struct directly in to the updater */ if(!up->setParams(sensor_list[i])) { ROS_ERROR("Failed to load sensor %d of type %s", i, sensor_type.c_str()); continue; } up->setNotifyFunction(boost::bind(&OccupancyMapMonitor::updateReady, this, _1)); map_updaters_.push_back(up); } } octree_binary_pub_ = root_nh_.advertise<octomap_msgs::Octomap>("octomap_binary", 1); /* advertise a service for loading octomaps from disk */ save_map_srv_ = nh_.advertiseService("save_map", &OccupancyMapMonitor::saveMapCallback, this); load_map_srv_ = nh_.advertiseService("load_map", &OccupancyMapMonitor::loadMapCallback, this); } bool OccupancyMapMonitor::saveMapCallback(moveit_msgs::SaveMap::Request& request, moveit_msgs::SaveMap::Response& response) { ROS_INFO("Writing map to %s", request.filename.c_str()); this->lockOcTreeRead(); response.success = tree_->write(request.filename); this->unlockOcTreeRead(); return true; } bool OccupancyMapMonitor::loadMapCallback(moveit_msgs::LoadMap::Request& request, moveit_msgs::LoadMap::Response& response) { ROS_INFO("Reading map from %s", request.filename.c_str()); this->lockOcTreeWrite(); /* load the octree from disk */ octomap::AbstractOcTree* tree = octomap::AbstractOcTree::read(request.filename); if(tree == NULL) { this->unlockOcTreeWrite(); ROS_ERROR("Failed to load map from file"); response.success = false; return true; } /* cast the abstract octree to the right type and update our shared pointer */ tree_.reset(dynamic_cast<OccMapTree*>(tree)); response.success = true; this->unlockOcTreeWrite(); return true; } void OccupancyMapMonitor::treeUpdateThread() { std::set<OccupancyMapUpdater*> ready; while (tree_update_thread_running_) { { boost::mutex::scoped_lock update_lock(update_mut_); if (update_cond_.timed_wait(update_lock, boost::posix_time::milliseconds(100))) updates_available_.swap(ready); } if (tree_update_thread_running_ && !ready.empty()) { ROS_DEBUG("Calling updaters"); { boost::unique_lock<boost::shared_mutex> ulock(tree_mutex_); for (std::set<OccupancyMapUpdater*>::iterator it = ready.begin() ; it != ready.end() ; ++it) (*it)->process(tree_); } if (update_callback_) update_callback_(); ready.clear(); publish_octomap_binary(); } } } void OccupancyMapMonitor::updateReady(OccupancyMapUpdater *updater) { { boost::mutex::scoped_lock update_lock(update_mut_); updates_available_.insert(updater); } update_cond_.notify_all(); } void OccupancyMapMonitor::lockOcTreeRead() { tree_mutex_.lock_shared(); } void OccupancyMapMonitor::unlockOcTreeRead() { tree_mutex_.unlock_shared(); } void OccupancyMapMonitor::lockOcTreeWrite() { tree_mutex_.lock(); } void OccupancyMapMonitor::unlockOcTreeWrite() { tree_mutex_.unlock(); } void OccupancyMapMonitor::publish_octomap_binary() { octomap_msgs::Octomap map; map.header.frame_id = opt_.map_frame; map.header.stamp = ros::Time::now(); if (octomap_msgs::binaryMapToMsgData(*tree_, map.data)) { octree_binary_pub_.publish(map); } else { ROS_ERROR("Could not generate OctoMap message"); } } void OccupancyMapMonitor::startMonitor() { if (!tree_update_thread_running_) { /* initialize all of the occupancy map updaters */ std::vector<boost::shared_ptr<OccupancyMapUpdater> >::iterator it; for (it = map_updaters_.begin(); it != map_updaters_.end(); it++) (*it)->initialize(); /* start a dedicated thread for updating the occupancy map */ tree_update_thread_running_ = true; tree_update_thread_.reset(new boost::thread(&OccupancyMapMonitor::treeUpdateThread, this)); } } void OccupancyMapMonitor::stopMonitor() { if (tree_update_thread_running_) { tree_update_thread_running_ = false; tree_update_thread_->join(); tree_update_thread_.reset(); } } OccupancyMapMonitor::~OccupancyMapMonitor() { stopMonitor(); } } <|endoftext|>
<commit_before>// $Id: ruleEvaluator.C,v 1.5 2000/05/25 11:02:01 oliver Exp $ #include <BALL/MOLMEC/COMMON/ruleEvaluator.h> #include <BALL/FORMAT/INIFile.h> #include <BALL/KERNEL/PTE.h> //#define DEBUG_RULEEVALUATOR using namespace std; namespace BALL { RuleEvaluator::RuleEvaluator() : prefix_(), rule_map_(), valid_(false) { } RuleEvaluator::RuleEvaluator(INIFile& file, const String& prefix) : prefix_(), rule_map_(), valid_(false) { valid_ = initialize(file, prefix); } RuleEvaluator::RuleEvaluator(const RuleEvaluator& evaluator) : prefix_(evaluator.prefix_), rule_map_(evaluator.rule_map_), valid_(evaluator.valid_) { } RuleEvaluator::~RuleEvaluator() { destroy(); } void RuleEvaluator::destroy() { clear(); } void RuleEvaluator::clear() { valid_ = false; prefix_ = ""; rule_map_.clear(); } const String& RuleEvaluator::getPrefix() const { return prefix_; } void RuleEvaluator::setPrefix(const String& prefix) { prefix_ = prefix; } bool RuleEvaluator::initialize (INIFile& file, const String& prefix) { // destroy the old rules rule_map_.clear(); valid_ = false; // store the new prefix prefix_ = prefix; // check whether the INI file is valid if (!file.isValid()) { // we didn't get a valid prefix file: abort return false; } // check for the sections and create the corresponding // Expressions for (Position i = 0; i < Element::NUMBER_OF_ELEMENTS; i++) { extractSection_(file, PTE[i].getSymbol()); } // the last rule is a general rule extractSection_(file, "*"); if (rule_map_.size() == 0) { Log.error() << "RuleEvaluator::initialize: no matching sections found for prefix " << prefix_ << endl; } // we create a map - done. valid_ = true; return true; } void RuleEvaluator::extractSection_(INIFile& file, const String& symbol) { // assemble the section name String section_name(prefix_ + ":" + symbol); // abort if the INI file does not contain the requested section if (!file.hasSection(section_name)) { return; } // create a new entry for symbol if (!rule_map_.has(symbol)) { rule_map_.insert(symbol, list<pair<Expression, String> >()); } // iterate over all lines of the respective section Position i = file.getSectionFirstLine(section_name); for (; i < file.getSectionLastLine(section_name); i++) { String line(*file.getLine(i)); if (line.has('=')) { if (line[0] == '=') { Log.error() << "RuleEvaluator:: invalid rule in line " << i << ": " << line << endl; continue; } String value = line.before("="); String expression_string; if (line.after("=").isValid()) { expression_string = line.after("="); } expression_string.trim(); value.trim(); // push the expression into the list rule_map_[symbol].push_back(pair<Expression, String>(Expression(expression_string), value)); } } } String RuleEvaluator::operator () (const Atom& atom) const { // check whether we got a rule for this element String symbol = atom.getElement().getSymbol(); RuleList::const_iterator it; // the return value String result = ""; if (rule_map_.has(symbol)) { // iterate over all rules in the list until the first rule // matches for (it = rule_map_[symbol].begin(); it != rule_map_[symbol].end(); ++it) { // check whether the expression matches for this atom if (it->first(atom)) { #ifdef DEBUG_RULEEVALUATOR Log.info() << "atom "<< atom.getFullName() << " matches rule " << it->first.getExpression() << endl; #endif // retrieve the return value result = it->second; break; } } } // if no rule was applicable, check the default rule "*" if ((result == "") && (rule_map_.has("*"))) { // iterate over all rules in the list until the first rule // matches for (it = rule_map_["*"].begin(); it != rule_map_["*"].end(); ++it) { // check whether the expression matches for this atom if (it->first(atom)) { // retrieve the return value result = it->second; // and exit the loop break; } } } // return the value return result; } const RuleEvaluator& RuleEvaluator::operator = (const RuleEvaluator& evaluator) { set(evaluator); return *this; } void RuleEvaluator::set(const RuleEvaluator& evaluator) { valid_ = evaluator.valid_; prefix_ = evaluator.prefix_; rule_map_ = evaluator.rule_map_; } bool RuleEvaluator::isValid() const { return valid_; } void RuleEvaluator::dump(std::ostream& s, Size indent_depth) const { // BAUSTELLE } } <commit_msg>fixed: comment lines were not ignored<commit_after>// $Id: ruleEvaluator.C,v 1.6 2000/05/26 09:28:26 oliver Exp $ #include <BALL/MOLMEC/COMMON/ruleEvaluator.h> #include <BALL/FORMAT/INIFile.h> #include <BALL/KERNEL/PTE.h> //#define DEBUG_RULEEVALUATOR using namespace std; namespace BALL { RuleEvaluator::RuleEvaluator() : prefix_(), rule_map_(), valid_(false) { } RuleEvaluator::RuleEvaluator(INIFile& file, const String& prefix) : prefix_(), rule_map_(), valid_(false) { valid_ = initialize(file, prefix); } RuleEvaluator::RuleEvaluator(const RuleEvaluator& evaluator) : prefix_(evaluator.prefix_), rule_map_(evaluator.rule_map_), valid_(evaluator.valid_) { } RuleEvaluator::~RuleEvaluator() { destroy(); } void RuleEvaluator::destroy() { clear(); } void RuleEvaluator::clear() { valid_ = false; prefix_ = ""; rule_map_.clear(); } const String& RuleEvaluator::getPrefix() const { return prefix_; } void RuleEvaluator::setPrefix(const String& prefix) { prefix_ = prefix; } bool RuleEvaluator::initialize (INIFile& file, const String& prefix) { // destroy the old rules rule_map_.clear(); valid_ = false; // store the new prefix prefix_ = prefix; // check whether the INI file is valid if (!file.isValid()) { // we didn't get a valid prefix file: abort return false; } // check for the sections and create the corresponding // Expressions for (Position i = 0; i < Element::NUMBER_OF_ELEMENTS; i++) { extractSection_(file, PTE[i].getSymbol()); } // the last rule is a general rule extractSection_(file, "*"); if (rule_map_.size() == 0) { Log.error() << "RuleEvaluator::initialize: no matching sections found for prefix " << prefix_ << endl; } // we create a map - done. valid_ = true; return true; } void RuleEvaluator::extractSection_(INIFile& file, const String& symbol) { // assemble the section name String section_name(prefix_ + ":" + symbol); // abort if the INI file does not contain the requested section if (!file.hasSection(section_name)) { return; } // create a new entry for symbol if (!rule_map_.has(symbol)) { rule_map_.insert(symbol, list<pair<Expression, String> >()); } // iterate over all lines of the respective section Position i = file.getSectionFirstLine(section_name); for (; i < file.getSectionLastLine(section_name); i++) { String line(*file.getLine(i)); // empty lines or comment lines (starting with ';' or '#') are ignored if (line.has('=') && (line[0] != ';') && (line[0] != '#')) { if (line[0] == '=') { Log.error() << "RuleEvaluator:: invalid rule in line " << i << ": " << line << endl; continue; } String value = line.before("="); String expression_string; if (line.after("=").isValid()) { expression_string = line.after("="); } expression_string.trim(); value.trim(); // push the expression into the list rule_map_[symbol].push_back(pair<Expression, String>(Expression(expression_string), value)); } } } String RuleEvaluator::operator () (const Atom& atom) const { // check whether we got a rule for this element String symbol = atom.getElement().getSymbol(); RuleList::const_iterator it; // the return value String result = ""; if (rule_map_.has(symbol)) { // iterate over all rules in the list until the first rule // matches for (it = rule_map_[symbol].begin(); it != rule_map_[symbol].end(); ++it) { // check whether the expression matches for this atom if (it->first(atom)) { #ifdef DEBUG_RULEEVALUATOR Log.info() << "atom "<< atom.getFullName() << " matches rule " << it->first.getExpression() << endl; #endif // retrieve the return value result = it->second; break; } } } // if no rule was applicable, check the default rule "*" if ((result == "") && (rule_map_.has("*"))) { // iterate over all rules in the list until the first rule // matches for (it = rule_map_["*"].begin(); it != rule_map_["*"].end(); ++it) { // check whether the expression matches for this atom if (it->first(atom)) { // retrieve the return value result = it->second; // and exit the loop break; } } } // return the value return result; } const RuleEvaluator& RuleEvaluator::operator = (const RuleEvaluator& evaluator) { set(evaluator); return *this; } void RuleEvaluator::set(const RuleEvaluator& evaluator) { valid_ = evaluator.valid_; prefix_ = evaluator.prefix_; rule_map_ = evaluator.rule_map_; } bool RuleEvaluator::isValid() const { return valid_; } void RuleEvaluator::dump(std::ostream& s, Size indent_depth) const { // BAUSTELLE } } <|endoftext|>
<commit_before>/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include "cluceneindexwriter.h" #include "tcharutils.h" #include <CLucene.h> #include <CLucene/store/Lock.h> #include "cluceneindexreader.h" #include "cluceneindexmanager.h" #include <CLucene/util/stringreader.h> #include <sstream> #include <assert.h> #ifdef STRIGI_USE_CLUCENE_COMPRESSEDFIELDS #include "jsgzipcompressstream.h" #endif #include <iostream> using lucene::document::Document; using lucene::document::Field; using lucene::index::IndexWriter; using lucene::index::Term; using lucene::index::TermDocs; using lucene::search::IndexSearcher; using lucene::search::Hits; using lucene::util::BitSet; using lucene::util::Reader; using namespace std; using namespace Strigi; struct CLuceneDocData { lucene::document::Document doc; std::string content; }; CLuceneIndexWriter::CLuceneIndexWriter(CLuceneIndexManager* m): manager(m), doccount(0) { string contentID(FieldRegister::contentFieldName.c_str()); wstring cID(utf8toucs2(contentID)); addMapping(_T(""),cID.c_str()); } CLuceneIndexWriter::~CLuceneIndexWriter() { } const wchar_t* CLuceneIndexWriter::systemlocation() { const static wstring s(utf8toucs2(FieldRegister::pathFieldName)); return s.c_str(); } void CLuceneIndexWriter::addText(const AnalysisResult* idx, const char* text, int32_t length) { CLuceneDocData* doc = static_cast<CLuceneDocData*>(idx->writerData()); doc->content.append(text, length); } #ifdef _UCS2 typedef map<wstring, wstring> CLuceneIndexWriterFieldMapType; #else typedef map<string, string> CLuceneIndexWriterFieldMapType; #endif CLuceneIndexWriterFieldMapType CLuceneIndexWriterFieldMap; void CLuceneIndexWriter::addMapping(const TCHAR* from, const TCHAR* to){ CLuceneIndexWriterFieldMap[from] = to; } const TCHAR* CLuceneIndexWriter::mapId(const TCHAR* id) { if (id == 0) id = _T(""); CLuceneIndexWriterFieldMapType::iterator itr = CLuceneIndexWriterFieldMap.find(id); if (itr == CLuceneIndexWriterFieldMap.end()) { return id; } else { return itr->second.c_str(); } } void CLuceneIndexWriter::addValue(const AnalysisResult* idx, AnalyzerConfiguration::FieldType type, const TCHAR* name, const TCHAR* value) { CLuceneDocData* doc = static_cast<CLuceneDocData*>(idx->writerData()); Field* field = new Field(name, value, (type & AnalyzerConfiguration::Stored) == AnalyzerConfiguration::Stored, (type & AnalyzerConfiguration::Indexed) == AnalyzerConfiguration::Indexed, (type & AnalyzerConfiguration::Tokenized) == AnalyzerConfiguration::Tokenized); doc->doc.add(*field); } void CLuceneIndexWriter::addValue(const AnalysisResult* idx, AnalyzerConfiguration::FieldType type, const TCHAR* fn, const std::string& value) { #if defined(_UCS2) addValue(idx, type, CLuceneIndexWriter::mapId(fn), utf8toucs2(value).c_str()); #else addValue(idx, type, CLuceneIndexWriter::mapId(fn), value.c_str()); #endif } void CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx, const Strigi::RegisteredField* field, const std::string& value) { AnalyzerConfiguration::FieldType type = idx->config().indexType(field); if (type == AnalyzerConfiguration::None) return; #if defined(_UCS2) addValue(idx, type, utf8toucs2(field->key()).c_str(), value); #else addValue(idx, type, field->key(), value); #endif } void CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx, const Strigi::RegisteredField* field, uint32_t value) { ostringstream o; o << value; addValue(idx, field, o.str()); } void CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx, const Strigi::RegisteredField* field, int32_t value) { ostringstream o; o << value; addValue(idx, field, o.str()); } void CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx, const Strigi::RegisteredField* field, const unsigned char* data, uint32_t size) { addValue(idx, field, string((const char*)data, (string::size_type)size)); } void CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx, const Strigi::RegisteredField* field, double value) { ostringstream o; o << value; addValue(idx, field, o.str()); } void CLuceneIndexWriter::startAnalysis(const AnalysisResult* idx) { doccount++; CLuceneDocData*doc = new CLuceneDocData(); idx->setWriterData(doc); } /* Close all left open indexwriters for this path. */ void CLuceneIndexWriter::finishAnalysis(const AnalysisResult* idx) { CLuceneDocData* doc = static_cast<CLuceneDocData*>(idx->writerData()); wstring c(utf8toucs2(doc->content)); jstreams::StringReader<char>* sr = NULL; //we use this for compressed streams if (doc->content.length() > 0) { const TCHAR* mappedFn = mapId(_T("")); #if defined(_UCS2) #ifndef STRIGI_USE_CLUCENE_COMPRESSEDFIELDS doc->doc.add(*Field::Text(mappedFn, c.c_str(), false)); #else // lets store the content as utf8. remember, the stream is required // until the document is added, so a static construction of stringreader // is not good enough sr = new jstreams::StringReader<char>(doc->content.c_str(), doc->content.length(), false); // add the stored field with the zipstream doc->doc.add(*new Field(mappedFn, new jstreams::GZipCompressInputStream(sr), Field::STORE_YES)); // add the tokenized/indexed field doc->doc.add(*new Field::Text(mappedFn, c.c_str(), Field::STORE_NO | Field::INDEX_TOKENIZED)); #endif #else //_UCS2 doc->doc.add(*Field::Text(mappedFn, doc->content.c_str()) ); #endif } lucene::index::IndexWriter* writer = manager->refWriter(); if (writer) { try { writer->addDocument(&doc->doc); } catch (CLuceneError& err) { fprintf(stderr, "%s: %s\n", idx->path().c_str(), err.what()); } } manager->derefWriter(); delete doc; if ( sr ) delete sr; manager->setIndexMTime(); } void CLuceneIndexWriter::deleteEntries(const std::vector<std::string>& entries) { manager->closeWriter(); if (!manager->luceneReader()->checkReader()) { fprintf(stderr,"cannot delete entry: lucene reader cannot be opened\n"); return; } lucene::index::IndexReader* reader = manager->luceneReader()->reader; for (uint i=0; i<entries.size(); ++i) { deleteEntry(entries[i], reader); } reader->commit(); manager->setIndexMTime(); } void CLuceneIndexWriter::deleteEntry(const string& entry, lucene::index::IndexReader* reader) { wstring tstr(utf8toucs2(entry)); int32_t prefixLen = tstr.length(); const TCHAR* prefixText = tstr.c_str(); int32_t maxdoc = reader->maxDoc(); for (int32_t i = 0; i < maxdoc; ++i) { if (!reader->isDeleted(i)) { Document* d = reader->document(i); const TCHAR* t = d->get(systemlocation()); if (t && _tcsncmp(t, prefixText, prefixLen) == 0) { try { reader->deleteDocument(i); } catch (...) { fprintf(stderr, "could not delete document"); } } _CLDELETE(d); } } } void CLuceneIndexWriter::deleteAllEntries() { manager->deleteIndex(); } void CLuceneIndexWriter::commit() { manager->closeWriter(); } //this function is in 0.9.17, which we do not have yet... bool isLuceneFile(const char* filename){ if ( !filename ) return false; size_t len = strlen(filename); if ( len < 6 ) //need at least x.frx return false; const char* ext = filename + len; while ( *ext != '.' && ext != filename ) ext--; if ( strcmp(ext, ".cfs") == 0 ) return true; else if ( strcmp(ext, ".fnm") == 0 ) return true; else if ( strcmp(ext, ".fdx") == 0 ) return true; else if ( strcmp(ext, ".fdt") == 0 ) return true; else if ( strcmp(ext, ".tii") == 0 ) return true; else if ( strcmp(ext, ".tis") == 0 ) return true; else if ( strcmp(ext, ".frq") == 0 ) return true; else if ( strcmp(ext, ".prx") == 0 ) return true; else if ( strcmp(ext, ".del") == 0 ) return true; else if ( strcmp(ext, ".tvx") == 0 ) return true; else if ( strcmp(ext, ".tvd") == 0 ) return true; else if ( strcmp(ext, ".tvf") == 0 ) return true; else if ( strcmp(ext, ".tvp") == 0 ) return true; else if ( strcmp(filename, "segments") == 0 ) return true; else if ( strcmp(filename, "segments.new") == 0 ) return true; else if ( strcmp(filename, "deletable") == 0 ) return true; else if ( strncmp(ext,".f",2)==0 ){ const char* n = ext+2; if ( *n && _istdigit(*n) ) return true; } return false; } void CLuceneIndexWriter::cleanUp() { // remove all unused lucene file elements... // unused elements are the result of unexpected shutdowns... // this can add up to a lot of after a while. lucene::index::IndexReader* reader = manager->luceneReader()->reader; if (!reader) { return; } lucene::store::Directory* directory = reader->getDirectory(); // Instantiate SegmentInfos lucene::store::LuceneLock* lock = directory->makeLock("commit.lock"); #ifdef LUCENE_COMMIT_LOCK_TIMEOUT // version <0.9.16 bool locked = lock->obtain(LUCENE_COMMIT_LOCK_TIMEOUT); #else bool locked = lock->obtain(lucene::index::IndexWriter::COMMIT_LOCK_TIMEOUT); #endif if (!locked) { return; } lucene::index::SegmentInfos infos; try { //Have SegmentInfos read the segments file in directory infos.read(directory); } catch(...) { lock->release(); return; //todo: this may suggest an error... } lock->release(); int i; set<string> segments; for (i = 0; i < infos.size(); i++) { lucene::index::SegmentInfo* info = infos.info(i); segments.insert(info->name); } char** files = directory->list(); char tmp[CL_MAX_PATH]; for (i = 0; files[i] != NULL; ++i) { char* file = files[i]; int fileLength = strlen(file); if ( fileLength < 6 ) { continue; } if (strncmp(file,"segments", 8) == 0 || strncmp(file, "deletable", 9) == 0) { continue; } if (!isLuceneFile(file)) { continue; } strcpy(tmp, file); tmp[fileLength-4] = '\0'; if (segments.find(tmp) != segments.end()) { continue; } directory->deleteFile(file, false); } for (i = 0; files[i] != NULL; i++) { _CLDELETE_CaARRAY(files[i]); } _CLDELETE_ARRAY(files); } void CLuceneIndexWriter::initWriterData(const FieldRegister& f) { map<string, RegisteredField*>::const_iterator i; map<string, RegisteredField*>::const_iterator end = f.fields().end(); for (i = f.fields().begin(); i != end; ++i) { i->second->setWriterData(0); } } void CLuceneIndexWriter::releaseWriterData(const FieldRegister& f) { map<string, RegisteredField*>::const_iterator i; map<string, RegisteredField*>::const_iterator end = f.fields().end(); for (i = f.fields().begin(); i != end; ++i) { delete static_cast<int*>(i->second->writerData()); } } <commit_msg>make error message more clear and use iostreams instead of fprintf.<commit_after>/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include "cluceneindexwriter.h" #include "tcharutils.h" #include <CLucene.h> #include <CLucene/store/Lock.h> #include "cluceneindexreader.h" #include "cluceneindexmanager.h" #include <CLucene/util/stringreader.h> #include <sstream> #include <assert.h> #ifdef STRIGI_USE_CLUCENE_COMPRESSEDFIELDS #include "jsgzipcompressstream.h" #endif #include <iostream> using lucene::document::Document; using lucene::document::Field; using lucene::index::IndexWriter; using lucene::index::Term; using lucene::index::TermDocs; using lucene::search::IndexSearcher; using lucene::search::Hits; using lucene::util::BitSet; using lucene::util::Reader; using namespace std; using namespace Strigi; struct CLuceneDocData { lucene::document::Document doc; std::string content; }; CLuceneIndexWriter::CLuceneIndexWriter(CLuceneIndexManager* m): manager(m), doccount(0) { string contentID(FieldRegister::contentFieldName.c_str()); wstring cID(utf8toucs2(contentID)); addMapping(_T(""),cID.c_str()); } CLuceneIndexWriter::~CLuceneIndexWriter() { } const wchar_t* CLuceneIndexWriter::systemlocation() { const static wstring s(utf8toucs2(FieldRegister::pathFieldName)); return s.c_str(); } void CLuceneIndexWriter::addText(const AnalysisResult* idx, const char* text, int32_t length) { CLuceneDocData* doc = static_cast<CLuceneDocData*>(idx->writerData()); doc->content.append(text, length); } #ifdef _UCS2 typedef map<wstring, wstring> CLuceneIndexWriterFieldMapType; #else typedef map<string, string> CLuceneIndexWriterFieldMapType; #endif CLuceneIndexWriterFieldMapType CLuceneIndexWriterFieldMap; void CLuceneIndexWriter::addMapping(const TCHAR* from, const TCHAR* to){ CLuceneIndexWriterFieldMap[from] = to; } const TCHAR* CLuceneIndexWriter::mapId(const TCHAR* id) { if (id == 0) id = _T(""); CLuceneIndexWriterFieldMapType::iterator itr = CLuceneIndexWriterFieldMap.find(id); if (itr == CLuceneIndexWriterFieldMap.end()) { return id; } else { return itr->second.c_str(); } } void CLuceneIndexWriter::addValue(const AnalysisResult* idx, AnalyzerConfiguration::FieldType type, const TCHAR* name, const TCHAR* value) { CLuceneDocData* doc = static_cast<CLuceneDocData*>(idx->writerData()); Field* field = new Field(name, value, (type & AnalyzerConfiguration::Stored) == AnalyzerConfiguration::Stored, (type & AnalyzerConfiguration::Indexed) == AnalyzerConfiguration::Indexed, (type & AnalyzerConfiguration::Tokenized) == AnalyzerConfiguration::Tokenized); doc->doc.add(*field); } void CLuceneIndexWriter::addValue(const AnalysisResult* idx, AnalyzerConfiguration::FieldType type, const TCHAR* fn, const std::string& value) { #if defined(_UCS2) addValue(idx, type, CLuceneIndexWriter::mapId(fn), utf8toucs2(value).c_str()); #else addValue(idx, type, CLuceneIndexWriter::mapId(fn), value.c_str()); #endif } void CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx, const Strigi::RegisteredField* field, const std::string& value) { AnalyzerConfiguration::FieldType type = idx->config().indexType(field); if (type == AnalyzerConfiguration::None) return; #if defined(_UCS2) addValue(idx, type, utf8toucs2(field->key()).c_str(), value); #else addValue(idx, type, field->key(), value); #endif } void CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx, const Strigi::RegisteredField* field, uint32_t value) { ostringstream o; o << value; addValue(idx, field, o.str()); } void CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx, const Strigi::RegisteredField* field, int32_t value) { ostringstream o; o << value; addValue(idx, field, o.str()); } void CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx, const Strigi::RegisteredField* field, const unsigned char* data, uint32_t size) { addValue(idx, field, string((const char*)data, (string::size_type)size)); } void CLuceneIndexWriter::addValue(const Strigi::AnalysisResult* idx, const Strigi::RegisteredField* field, double value) { ostringstream o; o << value; addValue(idx, field, o.str()); } void CLuceneIndexWriter::startAnalysis(const AnalysisResult* idx) { doccount++; CLuceneDocData*doc = new CLuceneDocData(); idx->setWriterData(doc); } /* Close all left open indexwriters for this path. */ void CLuceneIndexWriter::finishAnalysis(const AnalysisResult* idx) { CLuceneDocData* doc = static_cast<CLuceneDocData*>(idx->writerData()); wstring c(utf8toucs2(doc->content)); jstreams::StringReader<char>* sr = NULL; //we use this for compressed streams if (doc->content.length() > 0) { const TCHAR* mappedFn = mapId(_T("")); #if defined(_UCS2) #ifndef STRIGI_USE_CLUCENE_COMPRESSEDFIELDS doc->doc.add(*Field::Text(mappedFn, c.c_str(), false)); #else // lets store the content as utf8. remember, the stream is required // until the document is added, so a static construction of stringreader // is not good enough sr = new jstreams::StringReader<char>(doc->content.c_str(), doc->content.length(), false); // add the stored field with the zipstream doc->doc.add(*new Field(mappedFn, new jstreams::GZipCompressInputStream(sr), Field::STORE_YES)); // add the tokenized/indexed field doc->doc.add(*new Field::Text(mappedFn, c.c_str(), Field::STORE_NO | Field::INDEX_TOKENIZED)); #endif #else //_UCS2 doc->doc.add(*Field::Text(mappedFn, doc->content.c_str()) ); #endif } lucene::index::IndexWriter* writer = manager->refWriter(); if (writer) { try { writer->addDocument(&doc->doc); } catch (CLuceneError& err) { fprintf(stderr, "%s: %s\n", idx->path().c_str(), err.what()); } } manager->derefWriter(); delete doc; if ( sr ) delete sr; manager->setIndexMTime(); } void CLuceneIndexWriter::deleteEntries(const std::vector<std::string>& entries) { manager->closeWriter(); if (!manager->luceneReader()->checkReader()) { fprintf(stderr,"cannot delete entry: lucene reader cannot be opened\n"); return; } lucene::index::IndexReader* reader = manager->luceneReader()->reader; for (uint i=0; i<entries.size(); ++i) { deleteEntry(entries[i], reader); } reader->commit(); manager->setIndexMTime(); } void CLuceneIndexWriter::deleteEntry(const string& entry, lucene::index::IndexReader* reader) { wstring tstr(utf8toucs2(entry)); int32_t prefixLen = tstr.length(); const TCHAR* prefixText = tstr.c_str(); int32_t maxdoc = reader->maxDoc(); for (int32_t i = 0; i < maxdoc; ++i) { if (!reader->isDeleted(i)) { Document* d = reader->document(i); const TCHAR* t = d->get(systemlocation()); if (t && _tcsncmp(t, prefixText, prefixLen) == 0) { try { reader->deleteDocument(i); } catch (...) { cerr << "Could not delete document '" << entry << "' from the index." << endl; } } _CLDELETE(d); } } } void CLuceneIndexWriter::deleteAllEntries() { manager->deleteIndex(); } void CLuceneIndexWriter::commit() { manager->closeWriter(); } //this function is in 0.9.17, which we do not have yet... bool isLuceneFile(const char* filename){ if ( !filename ) return false; size_t len = strlen(filename); if ( len < 6 ) //need at least x.frx return false; const char* ext = filename + len; while ( *ext != '.' && ext != filename ) ext--; if ( strcmp(ext, ".cfs") == 0 ) return true; else if ( strcmp(ext, ".fnm") == 0 ) return true; else if ( strcmp(ext, ".fdx") == 0 ) return true; else if ( strcmp(ext, ".fdt") == 0 ) return true; else if ( strcmp(ext, ".tii") == 0 ) return true; else if ( strcmp(ext, ".tis") == 0 ) return true; else if ( strcmp(ext, ".frq") == 0 ) return true; else if ( strcmp(ext, ".prx") == 0 ) return true; else if ( strcmp(ext, ".del") == 0 ) return true; else if ( strcmp(ext, ".tvx") == 0 ) return true; else if ( strcmp(ext, ".tvd") == 0 ) return true; else if ( strcmp(ext, ".tvf") == 0 ) return true; else if ( strcmp(ext, ".tvp") == 0 ) return true; else if ( strcmp(filename, "segments") == 0 ) return true; else if ( strcmp(filename, "segments.new") == 0 ) return true; else if ( strcmp(filename, "deletable") == 0 ) return true; else if ( strncmp(ext,".f",2)==0 ){ const char* n = ext+2; if ( *n && _istdigit(*n) ) return true; } return false; } void CLuceneIndexWriter::cleanUp() { // remove all unused lucene file elements... // unused elements are the result of unexpected shutdowns... // this can add up to a lot of after a while. lucene::index::IndexReader* reader = manager->luceneReader()->reader; if (!reader) { return; } lucene::store::Directory* directory = reader->getDirectory(); // Instantiate SegmentInfos lucene::store::LuceneLock* lock = directory->makeLock("commit.lock"); #ifdef LUCENE_COMMIT_LOCK_TIMEOUT // version <0.9.16 bool locked = lock->obtain(LUCENE_COMMIT_LOCK_TIMEOUT); #else bool locked = lock->obtain(lucene::index::IndexWriter::COMMIT_LOCK_TIMEOUT); #endif if (!locked) { return; } lucene::index::SegmentInfos infos; try { //Have SegmentInfos read the segments file in directory infos.read(directory); } catch(...) { lock->release(); return; //todo: this may suggest an error... } lock->release(); int i; set<string> segments; for (i = 0; i < infos.size(); i++) { lucene::index::SegmentInfo* info = infos.info(i); segments.insert(info->name); } char** files = directory->list(); char tmp[CL_MAX_PATH]; for (i = 0; files[i] != NULL; ++i) { char* file = files[i]; int fileLength = strlen(file); if ( fileLength < 6 ) { continue; } if (strncmp(file,"segments", 8) == 0 || strncmp(file, "deletable", 9) == 0) { continue; } if (!isLuceneFile(file)) { continue; } strcpy(tmp, file); tmp[fileLength-4] = '\0'; if (segments.find(tmp) != segments.end()) { continue; } directory->deleteFile(file, false); } for (i = 0; files[i] != NULL; i++) { _CLDELETE_CaARRAY(files[i]); } _CLDELETE_ARRAY(files); } void CLuceneIndexWriter::initWriterData(const FieldRegister& f) { map<string, RegisteredField*>::const_iterator i; map<string, RegisteredField*>::const_iterator end = f.fields().end(); for (i = f.fields().begin(); i != end; ++i) { i->second->setWriterData(0); } } void CLuceneIndexWriter::releaseWriterData(const FieldRegister& f) { map<string, RegisteredField*>::const_iterator i; map<string, RegisteredField*>::const_iterator end = f.fields().end(); for (i = f.fields().begin(); i != end; ++i) { delete static_cast<int*>(i->second->writerData()); } } <|endoftext|>
<commit_before>#ifndef STAN_MATH_FWD_FUN_ACCUMULATOR_HPP #define STAN_MATH_FWD_FUN_ACCUMULATOR_HPP #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/fwd/core.hpp> #include <stan/math/fwd/meta.hpp> #include <stan/math/fwd/fun/sum.hpp> #include <stan/math/prim/fun/accumulator.hpp> #include <vector> #include <type_traits> namespace stan { namespace math { /** * Class to accumulate values and eventually return their sum. If * no values are ever added, the return value is 0. * * This class is useful for speeding up autodiff of long sums * because it uses the <code>sum()</code> operation (either from * <code>stan::math</code> or one defined by argument-dependent lookup. * * @tparam T Type of scalar added */ template <typename T> class accumulator<T, require_fvar_t<T>> { private: std::vector<T> buf_; public: /** * Add the specified arithmetic type value to the buffer after * static casting it to the class type <code>T</code>. * * <p>See the std library doc for <code>std::is_arithmetic</code> * for information on what counts as an arithmetic type. * * @tparam S Type of argument * @param x Value to add */ template <typename S, typename = require_stan_scalar_t<S>> inline void add(S x) { buf_.push_back(x); } /** * Add each entry in the specified matrix, vector, or row vector * of values to the buffer. * * @tparam S type of the matrix * @param m Matrix of values to add */ template <typename S, require_matrix_t<S>* = nullptr> inline void add(const S& m) { buf_.push_back(stan::math::sum(m)); } /** * Recursively add each entry in the specified standard vector * to the buffer. This will allow vectors of primitives, * autodiff variables to be added; if the vector entries * are collections, their elements are recursively added. * * @tparam S Type of value to recursively add. * @param xs Vector of entries to add */ template <typename S> inline void add(const std::vector<S>& xs) { for (size_t i = 0; i < xs.size(); ++i) { this->add(xs[i]); } } /** * Return the sum of the accumulated values. * * @return Sum of accumulated values. */ inline T sum() const { return stan::math::sum(buf_); } }; } // namespace math } // namespace stan #endif <commit_msg>remove fvar specialization<commit_after>#ifndef STAN_MATH_FWD_FUN_ACCUMULATOR_HPP #define STAN_MATH_FWD_FUN_ACCUMULATOR_HPP #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/fwd/core.hpp> #include <stan/math/fwd/meta.hpp> #include <stan/math/fwd/fun/sum.hpp> #include <stan/math/prim/fun/accumulator.hpp> #include <vector> #include <type_traits> #endif <|endoftext|>
<commit_before>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/inference/api/paddle_pass_builder.h" #ifdef PADDLE_WITH_CUDA #include <cudnn.h> #endif #include <glog/logging.h> namespace paddle { void PaddlePassBuilder::AppendPass(const std::string &pass_type) { passes_.push_back(pass_type); } void PaddlePassBuilder::TurnOnDebug() { std::vector<std::string> passes; auto it = std::begin(passes_); while (it != std::end(passes_)) { if (*it != "graph_viz_pass") { it = passes_.insert(it + 1, "graph_viz_pass"); } else { ++it; } } } std::string PaddlePassBuilder::DebugString() { std::stringstream ss; ss << "Passes to apply:\n"; for (auto &pass : passes_) { ss << " - " << pass << '\n'; } return ss.str(); } void PaddlePassBuilder::DeletePass(const std::string &pass_type) { auto it = std::begin(passes_); while (it != std::end(passes_)) { if (*it == pass_type) { it = passes_.erase(it); } else { ++it; } } } void PaddlePassBuilder::InsertPass(size_t idx, const std::string &pass_type) { passes_.insert(std::begin(passes_) + idx, pass_type); } void PaddlePassBuilder::DeletePass(size_t idx) { passes_.erase(std::begin(passes_) + idx); } void PaddlePassBuilder::AppendAnalysisPass(const std::string &pass) { analysis_passes_.push_back(pass); } void PaddlePassBuilder::ClearPasses() { passes_.clear(); } const std::vector<std::string> kTRTSubgraphPasses({ "conv_affine_channel_fuse_pass", // "conv_eltwiseadd_affine_channel_fuse_pass", // "shuffle_channel_detect_pass", // "quant_conv2d_dequant_fuse_pass", // "delete_quant_dequant_op_pass", // // "fc_fuse_pass", // "simplify_with_basic_ops_pass", // "embedding_eltwise_layernorm_fuse_pass", // "multihead_matmul_fuse_pass_v2", // "skip_layernorm_fuse_pass", // "conv_bn_fuse_pass", // "fc_fuse_pass", // "tensorrt_subgraph_pass", // "conv_bn_fuse_pass", // #if CUDNN_VERSION >= 7100 // To run conv_fusion, the version of cudnn must be // guaranteed at least v7 "conv_elementwise_add_act_fuse_pass", // "conv_elementwise_add2_act_fuse_pass", // "conv_elementwise_add_fuse_pass", // #endif // "transpose_flatten_concat_fuse_pass", }); const std::vector<std::string> kLiteSubgraphPasses({ #ifdef PADDLE_WITH_LITE "lite_subgraph_pass", #endif }); GpuPassStrategy::GpuPassStrategy() : PassStrategy({}) { passes_.assign({ // "identity_scale_op_clean_pass", // "is_test_pass", // "simplify_with_basic_ops_pass", // "conv_affine_channel_fuse_pass", // "conv_eltwiseadd_affine_channel_fuse_pass", // "conv_bn_fuse_pass", // "conv_eltwiseadd_bn_fuse_pass", // "embedding_eltwise_layernorm_fuse_pass", // "multihead_matmul_fuse_pass_v2", // "fc_fuse_pass", // "fc_elementwise_layernorm_fuse_pass", // #if CUDNN_VERSION >= 7100 // To run conv_fusion, the version of cudnn must be // guaranteed at least v7 "conv_elementwise_add_act_fuse_pass", // "conv_elementwise_add2_act_fuse_pass", // "conv_elementwise_add_fuse_pass", // #endif // "transpose_flatten_concat_fuse_pass", // // following pass should be located in the last, since it will // work on all fused ops. "runtime_context_cache_pass" }); use_gpu_ = true; } void GpuPassStrategy::EnableCUDNN() { if (!use_cudnn_) { passes_.insert(passes_.begin(), "cudnn_placement_pass"); } use_cudnn_ = true; } void GpuPassStrategy::EnableMKLDNN() { LOG(ERROR) << "GPU not support MKLDNN yet"; } void GpuPassStrategy::EnableMkldnnQuantizer() { LOG(ERROR) << "GPU not support MKL-DNN quantization"; } CpuPassStrategy::CpuPassStrategy() : PassStrategy({}) { // NOTE the large fusions should be located in the front, so that they will // not be damaged by smaller ones. passes_.assign({"simplify_with_basic_ops_pass", // "attention_lstm_fuse_pass", // "seqconv_eltadd_relu_fuse_pass", // // "seqpool_concat_fuse_pass", // "seqpool_cvm_concat_fuse_pass", // // "embedding_fc_lstm_fuse_pass", // "fc_lstm_fuse_pass", // "mul_lstm_fuse_pass", // "fc_gru_fuse_pass", // "mul_gru_fuse_pass", // "seq_concat_fc_fuse_pass", // "fc_fuse_pass", // "repeated_fc_relu_fuse_pass", // "squared_mat_sub_fuse_pass", // "conv_bn_fuse_pass", // "conv_eltwiseadd_bn_fuse_pass", // "conv_transpose_bn_fuse_pass", // "conv_transpose_eltwiseadd_bn_fuse_pass", // "is_test_pass", // // following pass should be located in the last, since // it will work on all fused ops. "runtime_context_cache_pass"}); use_gpu_ = false; } void CpuPassStrategy::EnableCUDNN() { LOG(ERROR) << "CPU not support cuDNN"; } void CpuPassStrategy::EnableMKLDNN() { // TODO(Superjomn) Consider the way to mix CPU with GPU. #ifdef PADDLE_WITH_MKLDNN if (!use_mkldnn_) { passes_.insert(passes_.begin(), "mkldnn_placement_pass"); for (auto &pass : std::vector<std::string>({ "depthwise_conv_mkldnn_pass", // "conv_bn_fuse_pass", // Execute BN passes again to "conv_eltwiseadd_bn_fuse_pass", // preserve correct pass order "conv_transpose_bn_fuse_pass", // "conv_transpose_eltwiseadd_bn_fuse_pass", // "conv_bias_mkldnn_fuse_pass", // "conv_transpose_bias_mkldnn_fuse_pass", "conv3d_bias_mkldnn_fuse_pass", // "conv_elementwise_add_mkldnn_fuse_pass", "conv_concat_relu_mkldnn_fuse_pass", "conv_relu_mkldnn_fuse_pass", // "conv_leaky_relu_mkldnn_fuse_pass", // "conv_relu6_mkldnn_fuse_pass", // "conv_swish_mkldnn_fuse_pass", // "scale_matmul_fuse_pass", // "reshape_transpose_matmul_mkldnn_fuse_pass", // "matmul_transpose_reshape_fuse_pass", // // Disabled due to topology-dependent speed-up // "fc_mkldnn_pass", "mkldnn_inplace_pass", // This pass should be activated after // fuses })) { passes_.push_back(pass); } } use_mkldnn_ = true; #else use_mkldnn_ = false; #endif } void CpuPassStrategy::EnableMkldnnQuantizer() { #ifdef PADDLE_WITH_MKLDNN if (!use_mkldnn_quantizer_) { passes_.push_back("cpu_quantize_placement_pass"); } use_mkldnn_quantizer_ = true; #else use_mkldnn_quantizer_ = false; #endif } } // namespace paddle <commit_msg>[oneDNN] disabling oneDNN inplace pass (#24406)<commit_after>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/inference/api/paddle_pass_builder.h" #ifdef PADDLE_WITH_CUDA #include <cudnn.h> #endif #include <glog/logging.h> namespace paddle { void PaddlePassBuilder::AppendPass(const std::string &pass_type) { passes_.push_back(pass_type); } void PaddlePassBuilder::TurnOnDebug() { std::vector<std::string> passes; auto it = std::begin(passes_); while (it != std::end(passes_)) { if (*it != "graph_viz_pass") { it = passes_.insert(it + 1, "graph_viz_pass"); } else { ++it; } } } std::string PaddlePassBuilder::DebugString() { std::stringstream ss; ss << "Passes to apply:\n"; for (auto &pass : passes_) { ss << " - " << pass << '\n'; } return ss.str(); } void PaddlePassBuilder::DeletePass(const std::string &pass_type) { auto it = std::begin(passes_); while (it != std::end(passes_)) { if (*it == pass_type) { it = passes_.erase(it); } else { ++it; } } } void PaddlePassBuilder::InsertPass(size_t idx, const std::string &pass_type) { passes_.insert(std::begin(passes_) + idx, pass_type); } void PaddlePassBuilder::DeletePass(size_t idx) { passes_.erase(std::begin(passes_) + idx); } void PaddlePassBuilder::AppendAnalysisPass(const std::string &pass) { analysis_passes_.push_back(pass); } void PaddlePassBuilder::ClearPasses() { passes_.clear(); } const std::vector<std::string> kTRTSubgraphPasses({ "conv_affine_channel_fuse_pass", // "conv_eltwiseadd_affine_channel_fuse_pass", // "shuffle_channel_detect_pass", // "quant_conv2d_dequant_fuse_pass", // "delete_quant_dequant_op_pass", // // "fc_fuse_pass", // "simplify_with_basic_ops_pass", // "embedding_eltwise_layernorm_fuse_pass", // "multihead_matmul_fuse_pass_v2", // "skip_layernorm_fuse_pass", // "conv_bn_fuse_pass", // "fc_fuse_pass", // "tensorrt_subgraph_pass", // "conv_bn_fuse_pass", // #if CUDNN_VERSION >= 7100 // To run conv_fusion, the version of cudnn must be // guaranteed at least v7 "conv_elementwise_add_act_fuse_pass", // "conv_elementwise_add2_act_fuse_pass", // "conv_elementwise_add_fuse_pass", // #endif // "transpose_flatten_concat_fuse_pass", }); const std::vector<std::string> kLiteSubgraphPasses({ #ifdef PADDLE_WITH_LITE "lite_subgraph_pass", #endif }); GpuPassStrategy::GpuPassStrategy() : PassStrategy({}) { passes_.assign({ // "identity_scale_op_clean_pass", // "is_test_pass", // "simplify_with_basic_ops_pass", // "conv_affine_channel_fuse_pass", // "conv_eltwiseadd_affine_channel_fuse_pass", // "conv_bn_fuse_pass", // "conv_eltwiseadd_bn_fuse_pass", // "embedding_eltwise_layernorm_fuse_pass", // "multihead_matmul_fuse_pass_v2", // "fc_fuse_pass", // "fc_elementwise_layernorm_fuse_pass", // #if CUDNN_VERSION >= 7100 // To run conv_fusion, the version of cudnn must be // guaranteed at least v7 "conv_elementwise_add_act_fuse_pass", // "conv_elementwise_add2_act_fuse_pass", // "conv_elementwise_add_fuse_pass", // #endif // "transpose_flatten_concat_fuse_pass", // // following pass should be located in the last, since it will // work on all fused ops. "runtime_context_cache_pass" }); use_gpu_ = true; } void GpuPassStrategy::EnableCUDNN() { if (!use_cudnn_) { passes_.insert(passes_.begin(), "cudnn_placement_pass"); } use_cudnn_ = true; } void GpuPassStrategy::EnableMKLDNN() { LOG(ERROR) << "GPU not support MKLDNN yet"; } void GpuPassStrategy::EnableMkldnnQuantizer() { LOG(ERROR) << "GPU not support MKL-DNN quantization"; } CpuPassStrategy::CpuPassStrategy() : PassStrategy({}) { // NOTE the large fusions should be located in the front, so that they will // not be damaged by smaller ones. passes_.assign({"simplify_with_basic_ops_pass", // "attention_lstm_fuse_pass", // "seqconv_eltadd_relu_fuse_pass", // // "seqpool_concat_fuse_pass", // "seqpool_cvm_concat_fuse_pass", // // "embedding_fc_lstm_fuse_pass", // "fc_lstm_fuse_pass", // "mul_lstm_fuse_pass", // "fc_gru_fuse_pass", // "mul_gru_fuse_pass", // "seq_concat_fc_fuse_pass", // "fc_fuse_pass", // "repeated_fc_relu_fuse_pass", // "squared_mat_sub_fuse_pass", // "conv_bn_fuse_pass", // "conv_eltwiseadd_bn_fuse_pass", // "conv_transpose_bn_fuse_pass", // "conv_transpose_eltwiseadd_bn_fuse_pass", // "is_test_pass", // // following pass should be located in the last, since // it will work on all fused ops. "runtime_context_cache_pass"}); use_gpu_ = false; } void CpuPassStrategy::EnableCUDNN() { LOG(ERROR) << "CPU not support cuDNN"; } void CpuPassStrategy::EnableMKLDNN() { // TODO(Superjomn) Consider the way to mix CPU with GPU. #ifdef PADDLE_WITH_MKLDNN if (!use_mkldnn_) { passes_.insert(passes_.begin(), "mkldnn_placement_pass"); for (auto &pass : std::vector<std::string>({ "depthwise_conv_mkldnn_pass", // "conv_bn_fuse_pass", // Execute BN passes again to "conv_eltwiseadd_bn_fuse_pass", // preserve correct pass order "conv_transpose_bn_fuse_pass", // "conv_transpose_eltwiseadd_bn_fuse_pass", // "conv_bias_mkldnn_fuse_pass", // "conv_transpose_bias_mkldnn_fuse_pass", "conv3d_bias_mkldnn_fuse_pass", // "conv_elementwise_add_mkldnn_fuse_pass", "conv_concat_relu_mkldnn_fuse_pass", "conv_relu_mkldnn_fuse_pass", // "conv_leaky_relu_mkldnn_fuse_pass", // "conv_relu6_mkldnn_fuse_pass", // "conv_swish_mkldnn_fuse_pass", // "scale_matmul_fuse_pass", // "reshape_transpose_matmul_mkldnn_fuse_pass", // "matmul_transpose_reshape_fuse_pass", // // Disabled due to topology-dependent speed-up // "fc_mkldnn_pass", // "mkldnn_inplace_pass", // This pass should be activated after // fuses })) { passes_.push_back(pass); } } use_mkldnn_ = true; #else use_mkldnn_ = false; #endif } void CpuPassStrategy::EnableMkldnnQuantizer() { #ifdef PADDLE_WITH_MKLDNN if (!use_mkldnn_quantizer_) { passes_.push_back("cpu_quantize_placement_pass"); } use_mkldnn_quantizer_ = true; #else use_mkldnn_quantizer_ = false; #endif } } // namespace paddle <|endoftext|>
<commit_before>#pragma once #include <cstdint> #include <functional> #include <optional> #include <unordered_map> #include "utils/Concepts.hpp" namespace utils::containers { template <NumericIntegral TValue> class DisjointSet { public: using ValueType = TValue; [[nodiscard]] int64_t size() const noexcept { return static_cast<int64_t>(m_parents.size()); } bool add(const ValueType value) { if (m_parents.contains(value)) { return false; } m_parents.emplace(value, value); return true; } std::optional<ValueType> find(const ValueType value) { if (auto it = m_parents.find(value); it != m_parents.end()) { return this->findParent(it)->first; } return std::nullopt; } bool merge(const ValueType lhs, const ValueType rhs) { auto lhsIts = m_parents.find(lhs); if (lhsIts == m_parents.end()) { return false; } auto rhsIts = m_parents.find(rhs); if (rhsIts == m_parents.end()) { return false; } auto lhsParent = this->findParent(lhsIts); auto rhsParent = this->findParent(rhsIts); if (&lhsParent == &rhsParent) { return false; } if (lhsParent->first < rhsParent->first) { rhsParent->second = lhsParent->first; } else { lhsParent->second = rhsParent->first; } return true; } private: using NodeIterator = typename std::unordered_map<ValueType, ValueType>::iterator; [[nodiscard]] NodeIterator findParent(NodeIterator it) { std::vector<NodeIterator> visitedNodesIts; while (it->first != it->second) { visitedNodesIts.push_back(it); it = m_parents.find(it->second); } for (auto &visitedNodeIt: visitedNodesIts) { visitedNodeIt->second = it->second; } return it; } std::unordered_map<ValueType, ValueType> m_parents; }; } // namespace utils::containers <commit_msg>Fix early exit logic in DisjointSet::merge<commit_after>#pragma once #include <cstdint> #include <functional> #include <optional> #include <unordered_map> #include "utils/Concepts.hpp" namespace utils::containers { template <NumericIntegral TValue> class DisjointSet { public: using ValueType = TValue; [[nodiscard]] int64_t size() const noexcept { return static_cast<int64_t>(m_parents.size()); } bool add(const ValueType value) { if (m_parents.contains(value)) { return false; } m_parents.emplace(value, value); return true; } std::optional<ValueType> find(const ValueType value) { if (auto it = m_parents.find(value); it != m_parents.end()) { return this->findParent(it)->first; } return std::nullopt; } bool merge(const ValueType lhs, const ValueType rhs) { auto lhsIts = m_parents.find(lhs); if (lhsIts == m_parents.end()) { return false; } auto rhsIts = m_parents.find(rhs); if (rhsIts == m_parents.end()) { return false; } if (lhsIts->second == rhsIts->second) { return false; } auto lhsParent = this->findParent(lhsIts); auto rhsParent = this->findParent(rhsIts); if (lhsParent == rhsParent) { return false; } if (lhsParent->first < rhsParent->first) { rhsParent->second = lhsParent->first; } else { lhsParent->second = rhsParent->first; } return true; } private: using NodeIterator = typename std::unordered_map<ValueType, ValueType>::iterator; [[nodiscard]] NodeIterator findParent(NodeIterator it) { std::vector<NodeIterator> visitedNodesIts; while (it->first != it->second) { visitedNodesIts.push_back(it); it = m_parents.find(it->second); } for (auto &visitedNodeIt: visitedNodesIts) { visitedNodeIt->second = it->second; } return it; } std::unordered_map<ValueType, ValueType> m_parents; }; } // namespace utils::containers <|endoftext|>
<commit_before>// Copyright © 2016-2017, Prosoft Engineering, Inc. (A.K.A "Prosoft") // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Prosoft nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL PROSOFT ENGINEERING, INC. BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef PS_CORE_FILESYSTEM_ITERATOR_HPP #define PS_CORE_FILESYSTEM_ITERATOR_HPP #include <iterator> #include <memory> #include <type_traits> namespace prosoft { namespace filesystem { inline namespace v1 { class file_status; class directory_entry { // C++ states that a name within a scope must have a unique meaning. // Therefore path() conflicts with the use of the 'path' type from our namespace and is ambigous. // GCC warns about this, clang does not. using path_type = prosoft::filesystem::path; path_type m_path; public: directory_entry() noexcept(std::is_nothrow_constructible<path_type>::value) : m_path() {} ~directory_entry() = default; PS_DEFAULT_COPY(directory_entry); PS_DEFAULT_MOVE(directory_entry); explicit directory_entry(const path_type& p) : m_path(p) {} // Extensions // explicit directory_entry(path_type&& p) noexcept(std::is_nothrow_move_constructible<path_type>::value) : m_path(std::move(p)) {} void assign(path_type&& p) { m_path = std::move(p); } // Extensions // void assign(const path_type& p) { m_path = p; } void replace_filename(const path_type& p) { m_path.replace_filename(p); } operator const path_type&() const noexcept { return this->path(); } const path_type& path() const noexcept { return m_path; } file_status status() const; file_status status(error_code&) const noexcept; file_status symlink_status() const; file_status symlink_status(error_code&) const noexcept; }; enum class directory_options : unsigned { none, follow_directory_symlink, skip_permission_denied, // Extensions skip_subdirectory_descendants = 1U<<20, skip_hidden_descendants = 1U<<21, skip_package_descendants = 1U<<22, // macOS follow_mountpoints = 1U<<23, include_postorder_directories = 1U<<24, // By default, we mimic the behavior of NSDirectoryEnumerator and skip "._" files. // However, unlike NSDE, we only skip "._" files that have a sibling of the same name. Orphan "._" files are always returned. // If for some reason you want paired "._" files too, set this. Normally it should not be set as the system automatically handles pairs. include_apple_double_files = 1U<<25, // macOS // Internal state reserved_state_skip_descendants = 1U<<30, reserved_state_postorder = 1U<<31, reserved_state_mask = 0xf0000000, }; PS_ENUM_BITMASK_OPS(directory_options); constexpr directory_options make_public(directory_options opts) { return opts & ~directory_options::reserved_state_mask; } using iterator_depth_type = int; namespace ifilesystem { class iterator_state { path m_root; directory_entry m_current; directory_options m_opts; protected: virtual path next(error_code&) = 0; void set(directory_options opts) noexcept { m_opts |= opts & directory_options::reserved_state_mask; } void clear(directory_options opts) noexcept { m_opts &= ~(opts & directory_options::reserved_state_mask); } public: iterator_state() = default; iterator_state(const path& p, directory_options opts, error_code&) : m_root(p) , m_current() , m_opts(opts) {} virtual ~iterator_state() = default; const path& root() const noexcept { return m_root; } const directory_entry& current() const noexcept { return m_current; } directory_options options() const noexcept { return m_opts; } void increment(error_code& ec) { m_current = directory_entry{next(ec)}; } virtual bool equal_to(const iterator_state*) const; virtual void pop() {} virtual iterator_depth_type depth() const noexcept { return 0; } virtual void skip_descendants() {} virtual bool at_end() const { return m_current.path().empty(); } }; using iterator_state_ptr = std::shared_ptr<ifilesystem::iterator_state>; struct iterator_traits { static constexpr directory_options required = directory_options::skip_subdirectory_descendants; static constexpr directory_options not_supported = directory_options::none; static constexpr directory_options defaults = required; }; struct recursive_iterator_traits { static constexpr directory_options required = directory_options::none; static constexpr directory_options not_supported = directory_options::skip_subdirectory_descendants; static constexpr directory_options defaults = required; }; template <class Traits> struct is_recursive { static constexpr bool value = is_set(Traits::not_supported & directory_options::skip_subdirectory_descendants); }; static_assert(!is_recursive<iterator_traits>::value, "WTF?"); static_assert(is_recursive<recursive_iterator_traits>::value, "WTF?"); iterator_state_ptr make_iterator_state(const path&, directory_options, error_code&, iterator_traits); inline iterator_state_ptr make_iterator_state(const path& p, directory_options opts, error_code& ec, recursive_iterator_traits) { return make_iterator_state(p, opts, ec, iterator_traits{}); } const error_code& permission_denied_error(iterator_traits); inline const error_code& permission_denied_error(recursive_iterator_traits) { return permission_denied_error(iterator_traits{}); } template <class Traits> constexpr directory_options make_options(directory_options opts) { return (make_public(opts) | Traits::required) & ~Traits::not_supported; } } // ifilesystem template <class Traits> class basic_iterator { ifilesystem::iterator_state_ptr m_i; const path& root_or_empty() const { static const path empty; return m_i ? m_i->root() : empty; } void clear_if_denied(error_code& ec) const; template <typename Recurse> struct resurse_only : public std::enable_if<ifilesystem::is_recursive<Traits>::value, Recurse> {}; template <typename Recurse> using recurse_only_t = typename resurse_only<Recurse>::type; public: using value_type = directory_entry; using difference_type = ptrdiff_t; using pointer = const value_type*; using reference = const value_type&; using iterator_category = std::input_iterator_tag; basic_iterator() noexcept(std::is_nothrow_constructible<decltype(m_i)>::value) = default; explicit basic_iterator(const path&); basic_iterator(const path& p, directory_options options); basic_iterator(const path& p, directory_options options, error_code& ec); basic_iterator(const path& p, error_code& ec); basic_iterator(const basic_iterator&) = default; basic_iterator(basic_iterator&&) noexcept(std::is_nothrow_move_constructible<decltype(m_i)>::value) = default; ~basic_iterator() = default; directory_options options() const; const directory_entry& operator*() const; const directory_entry* operator->() const; basic_iterator& operator=(const basic_iterator&) = default; basic_iterator& operator=(basic_iterator&&) noexcept(std::is_nothrow_move_constructible<decltype(m_i)>::value) = default; basic_iterator& operator++(); basic_iterator& increment(error_code&); bool operator==(const basic_iterator&) const; // Recursive only template <typename Recurse = void> iterator_depth_type depth(recurse_only_t<Recurse>* = 0) const noexcept { return m_i ? m_i->depth() : iterator_depth_type{}; } template <typename Recurse = void> bool recursion_pending(recurse_only_t<Recurse>* = 0) const noexcept { return m_i ? !is_set(m_i->options() & directory_options::reserved_state_skip_descendants) : false; } template <typename Recurse = void> void pop(recurse_only_t<Recurse>* = 0) { if (m_i) { m_i->pop(); } } template <typename Recurse = void> void disable_recursion_pending(recurse_only_t<Recurse>* = 0) { if (m_i) { m_i->skip_descendants(); } } // Extensions basic_iterator& operator++(int); static constexpr directory_options default_options() { return Traits::defaults; } }; template <class Traits> inline basic_iterator<Traits>::basic_iterator(const path& p) : basic_iterator<Traits>::basic_iterator(p, default_options()) { } template <class Traits> inline basic_iterator<Traits>::basic_iterator(const path& p, directory_options opts, error_code& ec) : m_i(ifilesystem::make_iterator_state(p, ifilesystem::make_options<Traits>(opts), ec, Traits{})) { increment(ec); clear_if_denied(ec); } template <class Traits> inline basic_iterator<Traits>::basic_iterator(const path& p, error_code& ec) : basic_iterator<Traits>::basic_iterator(p, default_options(), ec) { } template <class Traits> const directory_entry& basic_iterator<Traits>::operator*() const { static const directory_entry empty{}; return m_i ? m_i->current() : empty; } template <class Traits> inline const directory_entry* basic_iterator<Traits>::operator->() const { return &operator*(); } template <class Traits> directory_options basic_iterator<Traits>::options() const { return m_i ? make_public(m_i->options()) : directory_options::none; } template <class Traits> basic_iterator<Traits>& basic_iterator<Traits>::increment(error_code& ec) { if (m_i) { m_i->increment(ec); if (m_i->at_end()) { m_i.reset(); // become end } } return *this; } template <class Traits> bool basic_iterator<Traits>::operator==(const basic_iterator<Traits>& other) const { auto ti = m_i.get(); auto oi = other.m_i.get(); return ti == oi || (ti && oi && ti->equal_to(oi)); } template <class Traits> inline bool operator!=(const basic_iterator<Traits>& lhs, const basic_iterator<Traits>& rhs) { return !lhs.operator==(rhs); } template <class Traits> inline basic_iterator<Traits> begin(basic_iterator<Traits> i) { return i; } template <class Traits> inline basic_iterator<Traits> end(const basic_iterator<Traits>&) { return basic_iterator<Traits>{}; } // Private template <class Traits> void basic_iterator<Traits>::clear_if_denied(error_code& ec) const { if (is_set(options() & directory_options::skip_permission_denied) && ec == ifilesystem::permission_denied_error(Traits{})) { ec.clear(); } } // Extensions template <class Traits> inline basic_iterator<Traits>& basic_iterator<Traits>::operator++(int) { return operator++(); // // XXX: Input iter one-pass semantics. } } // v1 } // filesystem } // prosoft #endif // PS_CORE_FILESYSTEM_ITERATOR_HPP <commit_msg>Add path() rvalue member<commit_after>// Copyright © 2016-2017, Prosoft Engineering, Inc. (A.K.A "Prosoft") // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Prosoft nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL PROSOFT ENGINEERING, INC. BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef PS_CORE_FILESYSTEM_ITERATOR_HPP #define PS_CORE_FILESYSTEM_ITERATOR_HPP #include <iterator> #include <memory> #include <type_traits> namespace prosoft { namespace filesystem { inline namespace v1 { class file_status; class directory_entry { // C++ states that a name within a scope must have a unique meaning. // Therefore path() conflicts with the use of the 'path' type from our namespace and is ambigous. // GCC warns about this, clang does not. using path_type = prosoft::filesystem::path; path_type m_path; public: directory_entry() noexcept(std::is_nothrow_constructible<path_type>::value) : m_path() {} ~directory_entry() = default; PS_DEFAULT_COPY(directory_entry); PS_DEFAULT_MOVE(directory_entry); explicit directory_entry(const path_type& p) : m_path(p) {} // Extensions // explicit directory_entry(path_type&& p) noexcept(std::is_nothrow_move_constructible<path_type>::value) : m_path(std::move(p)) {} void assign(path_type&& p) { m_path = std::move(p); } // Extensions // void assign(const path_type& p) { m_path = p; } void replace_filename(const path_type& p) { m_path.replace_filename(p); } operator const path_type&() const noexcept { return this->path(); } const path_type& path() const & noexcept { return m_path; } path_type path() && noexcept(std::is_nothrow_move_constructible<path_type>::value) { return path_type{std::move(m_path)}; } file_status status() const; file_status status(error_code&) const noexcept; file_status symlink_status() const; file_status symlink_status(error_code&) const noexcept; }; enum class directory_options : unsigned { none, follow_directory_symlink, skip_permission_denied, // Extensions skip_subdirectory_descendants = 1U<<20, skip_hidden_descendants = 1U<<21, skip_package_descendants = 1U<<22, // macOS follow_mountpoints = 1U<<23, include_postorder_directories = 1U<<24, // By default, we mimic the behavior of NSDirectoryEnumerator and skip "._" files. // However, unlike NSDE, we only skip "._" files that have a sibling of the same name. Orphan "._" files are always returned. // If for some reason you want paired "._" files too, set this. Normally it should not be set as the system automatically handles pairs. include_apple_double_files = 1U<<25, // macOS // Internal state reserved_state_skip_descendants = 1U<<30, reserved_state_postorder = 1U<<31, reserved_state_mask = 0xf0000000, }; PS_ENUM_BITMASK_OPS(directory_options); constexpr directory_options make_public(directory_options opts) { return opts & ~directory_options::reserved_state_mask; } using iterator_depth_type = int; namespace ifilesystem { class iterator_state { path m_root; directory_entry m_current; directory_options m_opts; protected: virtual path next(error_code&) = 0; void set(directory_options opts) noexcept { m_opts |= opts & directory_options::reserved_state_mask; } void clear(directory_options opts) noexcept { m_opts &= ~(opts & directory_options::reserved_state_mask); } public: iterator_state() = default; iterator_state(const path& p, directory_options opts, error_code&) : m_root(p) , m_current() , m_opts(opts) {} virtual ~iterator_state() = default; const path& root() const noexcept { return m_root; } const directory_entry& current() const noexcept { return m_current; } directory_options options() const noexcept { return m_opts; } void increment(error_code& ec) { m_current = directory_entry{next(ec)}; } virtual bool equal_to(const iterator_state*) const; virtual void pop() {} virtual iterator_depth_type depth() const noexcept { return 0; } virtual void skip_descendants() {} virtual bool at_end() const { return m_current.path().empty(); } }; using iterator_state_ptr = std::shared_ptr<ifilesystem::iterator_state>; struct iterator_traits { static constexpr directory_options required = directory_options::skip_subdirectory_descendants; static constexpr directory_options not_supported = directory_options::none; static constexpr directory_options defaults = required; }; struct recursive_iterator_traits { static constexpr directory_options required = directory_options::none; static constexpr directory_options not_supported = directory_options::skip_subdirectory_descendants; static constexpr directory_options defaults = required; }; template <class Traits> struct is_recursive { static constexpr bool value = is_set(Traits::not_supported & directory_options::skip_subdirectory_descendants); }; static_assert(!is_recursive<iterator_traits>::value, "WTF?"); static_assert(is_recursive<recursive_iterator_traits>::value, "WTF?"); iterator_state_ptr make_iterator_state(const path&, directory_options, error_code&, iterator_traits); inline iterator_state_ptr make_iterator_state(const path& p, directory_options opts, error_code& ec, recursive_iterator_traits) { return make_iterator_state(p, opts, ec, iterator_traits{}); } const error_code& permission_denied_error(iterator_traits); inline const error_code& permission_denied_error(recursive_iterator_traits) { return permission_denied_error(iterator_traits{}); } template <class Traits> constexpr directory_options make_options(directory_options opts) { return (make_public(opts) | Traits::required) & ~Traits::not_supported; } } // ifilesystem template <class Traits> class basic_iterator { ifilesystem::iterator_state_ptr m_i; const path& root_or_empty() const { static const path empty; return m_i ? m_i->root() : empty; } void clear_if_denied(error_code& ec) const; template <typename Recurse> struct resurse_only : public std::enable_if<ifilesystem::is_recursive<Traits>::value, Recurse> {}; template <typename Recurse> using recurse_only_t = typename resurse_only<Recurse>::type; public: using value_type = directory_entry; using difference_type = ptrdiff_t; using pointer = const value_type*; using reference = const value_type&; using iterator_category = std::input_iterator_tag; basic_iterator() noexcept(std::is_nothrow_constructible<decltype(m_i)>::value) = default; explicit basic_iterator(const path&); basic_iterator(const path& p, directory_options options); basic_iterator(const path& p, directory_options options, error_code& ec); basic_iterator(const path& p, error_code& ec); basic_iterator(const basic_iterator&) = default; basic_iterator(basic_iterator&&) noexcept(std::is_nothrow_move_constructible<decltype(m_i)>::value) = default; ~basic_iterator() = default; directory_options options() const; const directory_entry& operator*() const; const directory_entry* operator->() const; basic_iterator& operator=(const basic_iterator&) = default; basic_iterator& operator=(basic_iterator&&) noexcept(std::is_nothrow_move_constructible<decltype(m_i)>::value) = default; basic_iterator& operator++(); basic_iterator& increment(error_code&); bool operator==(const basic_iterator&) const; // Recursive only template <typename Recurse = void> iterator_depth_type depth(recurse_only_t<Recurse>* = 0) const noexcept { return m_i ? m_i->depth() : iterator_depth_type{}; } template <typename Recurse = void> bool recursion_pending(recurse_only_t<Recurse>* = 0) const noexcept { return m_i ? !is_set(m_i->options() & directory_options::reserved_state_skip_descendants) : false; } template <typename Recurse = void> void pop(recurse_only_t<Recurse>* = 0) { if (m_i) { m_i->pop(); } } template <typename Recurse = void> void disable_recursion_pending(recurse_only_t<Recurse>* = 0) { if (m_i) { m_i->skip_descendants(); } } // Extensions basic_iterator& operator++(int); static constexpr directory_options default_options() { return Traits::defaults; } }; template <class Traits> inline basic_iterator<Traits>::basic_iterator(const path& p) : basic_iterator<Traits>::basic_iterator(p, default_options()) { } template <class Traits> inline basic_iterator<Traits>::basic_iterator(const path& p, directory_options opts, error_code& ec) : m_i(ifilesystem::make_iterator_state(p, ifilesystem::make_options<Traits>(opts), ec, Traits{})) { increment(ec); clear_if_denied(ec); } template <class Traits> inline basic_iterator<Traits>::basic_iterator(const path& p, error_code& ec) : basic_iterator<Traits>::basic_iterator(p, default_options(), ec) { } template <class Traits> const directory_entry& basic_iterator<Traits>::operator*() const { static const directory_entry empty{}; return m_i ? m_i->current() : empty; } template <class Traits> inline const directory_entry* basic_iterator<Traits>::operator->() const { return &operator*(); } template <class Traits> directory_options basic_iterator<Traits>::options() const { return m_i ? make_public(m_i->options()) : directory_options::none; } template <class Traits> basic_iterator<Traits>& basic_iterator<Traits>::increment(error_code& ec) { if (m_i) { m_i->increment(ec); if (m_i->at_end()) { m_i.reset(); // become end } } return *this; } template <class Traits> bool basic_iterator<Traits>::operator==(const basic_iterator<Traits>& other) const { auto ti = m_i.get(); auto oi = other.m_i.get(); return ti == oi || (ti && oi && ti->equal_to(oi)); } template <class Traits> inline bool operator!=(const basic_iterator<Traits>& lhs, const basic_iterator<Traits>& rhs) { return !lhs.operator==(rhs); } template <class Traits> inline basic_iterator<Traits> begin(basic_iterator<Traits> i) { return i; } template <class Traits> inline basic_iterator<Traits> end(const basic_iterator<Traits>&) { return basic_iterator<Traits>{}; } // Private template <class Traits> void basic_iterator<Traits>::clear_if_denied(error_code& ec) const { if (is_set(options() & directory_options::skip_permission_denied) && ec == ifilesystem::permission_denied_error(Traits{})) { ec.clear(); } } // Extensions template <class Traits> inline basic_iterator<Traits>& basic_iterator<Traits>::operator++(int) { return operator++(); // // XXX: Input iter one-pass semantics. } } // v1 } // filesystem } // prosoft #endif // PS_CORE_FILESYSTEM_ITERATOR_HPP <|endoftext|>
<commit_before>// // Copyright (c) 2015 Terry Seyler // // Distributed under the MIT License // See accompanying file LICENSE.md // #include <string> #include <core/protocol/net_parse_routines.hpp> #include <core/protocol/http/http_parse_routines.hpp> #include <core/protocol/http/http_request_parser.hpp> namespace proto_net { using namespace data; namespace protocol { namespace http { http_parse_result http_request_parser::protocol_parse(const proto_net_string_data& formed, http_request_message& parsed) { // Step 1: get http header size_t pos = message_body_position(formed); proto_net_data http_header(formed.data(), pos, data_text); // pos is size of header // Step 2: convert to lines lines_t lines; get_lines(http_header.to_string(), lines); // Step 3: validate http_parse_result res = validate_http_request(lines, parsed); // Step 4: add the message body if we validated the header if (HTTP_PARSE_SUCCEEDED(res)) { char* msg_body = formed.data() + pos; // offset ptr to message body size_t content_length = parsed.content_length(); proto_net_data msg_data(msg_body, content_length, data_text); proto_net_string_data msg_string_data(msg_data); parsed.body(msg_string_data); } return res; } http_parse_result http_request_parser::protocol_form(const http_request_message &parsed, proto_net_string_data& formed) { formed = parsed.to_net_data(); return http_parse_success; } http_parse_result http_request_parser::validate_http_request(const lines_t &lines, http_request_message &parsed) { http_parse_result res(http_parse_success); // 5.1 Request-Line Request-Line = Method SP Request-URI SP HTTP-Version CRLF matches_t request_line_tokens; // method, request_uri, http_version tokenize_http_line(lines[0], request_line_tokens); // needs to be first line res = validate_request_line(request_line_tokens); if (HTTP_PARSE_SUCCEEDED(res)) { // request line validated so update parsed parsed.method(request_line_tokens[0]); // method parsed.request_uri(request_line_tokens[1]); // request-uri parsed.http_version(request_line_tokens[2]); // http version // get header field lines lines_t header_field_lines; get_header_field_lines(lines, header_field_lines); // if we have header fields if (header_field_lines.size() > 0) res = validate_http_headers(header_field_lines, parsed.get_headers()); } return res; } } } } <commit_msg>Fixed a seg fault in http_parse_routines in the request parser.<commit_after>// // Copyright (c) 2015 Terry Seyler // // Distributed under the MIT License // See accompanying file LICENSE.md // #include <string> #include <core/protocol/net_parse_routines.hpp> #include <core/protocol/http/http_parse_routines.hpp> #include <core/protocol/http/http_request_parser.hpp> namespace proto_net { using namespace data; namespace protocol { namespace http { http_parse_result http_request_parser::protocol_parse(const proto_net_string_data& formed, http_request_message& parsed) { // Step 1: get http header size_t pos = message_body_position(formed); proto_net_data http_header(formed.data(), pos, data_text); // pos is size of header // Step 2: convert to lines lines_t lines; get_lines(http_header.to_string(), lines); // Step 3: validate http_parse_result res = validate_http_request(lines, parsed); // Step 4: add the message body if we validated the header if (HTTP_PARSE_SUCCEEDED(res)) { char* msg_body = formed.data() + pos; // offset ptr to message body size_t content_length = parsed.content_length(); proto_net_data msg_data(msg_body, content_length, data_text); proto_net_string_data msg_string_data(msg_data); parsed.body(msg_string_data); } return res; } http_parse_result http_request_parser::protocol_form(const http_request_message &parsed, proto_net_string_data& formed) { formed = parsed.to_net_data(); return http_parse_success; } http_parse_result http_request_parser::validate_http_request(const lines_t &lines, http_request_message &parsed) { http_parse_result res = lines.size() ? http_parse_success : http_parse_internal_error; if (HTTP_PARSE_SUCCEEDED(res)) { // 5.1 Request-Line Request-Line = Method SP Request-URI SP HTTP-Version CRLF matches_t request_line_tokens; // method, request_uri, http_version tokenize_http_line(lines[0], request_line_tokens); // needs to be first line res = validate_request_line(request_line_tokens); if (HTTP_PARSE_SUCCEEDED(res)) { // request line validated so update parsed parsed.method(request_line_tokens[0]); // method parsed.request_uri(request_line_tokens[1]); // request-uri parsed.http_version(request_line_tokens[2]); // http version // get header field lines lines_t header_field_lines; get_header_field_lines(lines, header_field_lines); // if we have header fields if (header_field_lines.size() > 0) res = validate_http_headers(header_field_lines, parsed.get_headers()); } } return res; } } } } <|endoftext|>
<commit_before>/* Copyright (c) 2014, The Cinder Project This code is intended to be used with the Cinder C++ library, http://libcinder.org Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "cinder/audio/Node.h" #include "cinder/audio/DelayNode.h" #include "cinder/audio/Context.h" #include "cinder/audio/dsp/Dsp.h" #include "cinder/audio/dsp/Converter.h" #include "cinder/audio/Debug.h" #include "cinder/CinderAssert.h" #include "cinder/System.h" #include <limits> using namespace std; namespace cinder { namespace audio { // ---------------------------------------------------------------------------------------------------- // MARK: - Node // ---------------------------------------------------------------------------------------------------- Node::Node( const Format &format ) : mInitialized( false ), mEnabled( false ), mChannelMode( format.getChannelMode() ), mNumChannels( 1 ), mAutoEnabled( true ), mProcessInPlace( true ), mLastProcessedFrame( numeric_limits<uint64_t>::max() ) { if( format.getChannels() ) { mNumChannels = format.getChannels(); mChannelMode = ChannelMode::SPECIFIED; } if( ! boost::indeterminate( format.getAutoEnable() ) ) setAutoEnabled( format.getAutoEnable() ); } Node::~Node() { } void Node::connect( const NodeRef &output ) { // make a reference to ourselves so that we aren't deallocated in the case of the last owner // disconnecting us, which we may need later anyway NodeRef thisRef = shared_from_this(); if( ! output->canConnectToInput( thisRef ) ) return; if( checkCycle( thisRef, output ) ) throw NodeCycleExc( thisRef, output ); mOutputs.push_back( output ); // set output first, so that it is visible in configureConnections() output->connectInput( thisRef ); output->notifyConnectionsDidChange(); } void Node::disconnect( const NodeRef &output ) { if( ! output ) return; for( auto weakOutIt = mOutputs.begin(); weakOutIt != mOutputs.end(); ++weakOutIt ) { if( weakOutIt->lock() == output ) { mOutputs.erase( weakOutIt ); break; } } output->disconnectInput( shared_from_this() ); output->notifyConnectionsDidChange(); } void Node::disconnectAll() { disconnectAllInputs(); disconnectAllOutputs(); } void Node::disconnectAllOutputs() { NodeRef thisRef = shared_from_this(); auto outputs = getOutputs(); // first make a copy of only the still-alive NodeRef's for( const auto &output : outputs ) disconnect( output ); } void Node::disconnectAllInputs() { NodeRef thisRef = shared_from_this(); for( auto &input : mInputs ) input->disconnectOutput( thisRef ); mInputs.clear(); notifyConnectionsDidChange(); } void Node::connectInput( const NodeRef &input ) { lock_guard<mutex> lock( getContext()->getMutex() ); mInputs.insert( input ); configureConnections(); } void Node::disconnectInput( const NodeRef &input ) { lock_guard<mutex> lock( getContext()->getMutex() ); for( auto inIt = mInputs.begin(); inIt != mInputs.end(); ++inIt ) { if( *inIt == input ) { mInputs.erase( inIt ); break; } } } void Node::disconnectOutput( const NodeRef &output ) { lock_guard<mutex> lock( getContext()->getMutex() ); for( auto outIt = mOutputs.begin(); outIt != mOutputs.end(); ++outIt ) { if( outIt->lock() == output ) { mOutputs.erase( outIt ); break; } } } vector<NodeRef> Node::getOutputs() const { vector<NodeRef> result; for( const weak_ptr<Node> &outputWeak : mOutputs ) { NodeRef output = outputWeak.lock(); if( output ) result.push_back( output ); } return result; } void Node::enable() { if( ! mInitialized ) initializeImpl(); if( mEnabled ) return; mEnabled = true; enableProcessing(); } void Node::disable() { if( ! mEnabled ) return; mEnabled = false; disableProcessing(); } void Node::setEnabled( bool b ) { if( b ) enable(); else disable(); } size_t Node::getNumConnectedInputs() const { return mInputs.size(); } size_t Node::getNumConnectedOutputs() const { return mOutputs.size(); } void Node::initializeImpl() { if( mInitialized ) return; initialize(); mInitialized = true; if( mAutoEnabled ) enable(); } void Node::uninitializeImpl() { if( ! mInitialized ) return; disable(); uninitialize(); mInitialized = false; } void Node::setNumChannels( size_t numChannels ) { if( mNumChannels == numChannels ) return; uninitializeImpl(); mNumChannels = numChannels; } void Node::setChannelMode( ChannelMode mode ) { CI_ASSERT_MSG( ! mInitialized, "setting the channel mode must be done before initializing" ); if( mChannelMode == mode ) return; mChannelMode = mode; } size_t Node::getMaxNumInputChannels() const { size_t result = 0; for( auto &in : mInputs ) result = max( result, in->getNumChannels() ); return result; } size_t Node::getSampleRate() const { return getContext()->getSampleRate(); } size_t Node::getFramesPerBlock() const { return getContext()->getFramesPerBlock(); } // TODO: Checking for DelayNode below is a kludge and will not work for other types that want to support feedback. // With more investigation it might be possible to avoid this, or at least define some interface that // specifies whether this input needs to be summed. void Node::configureConnections() { CI_ASSERT( getContext() ); mProcessInPlace = supportsProcessInPlace(); if( getNumConnectedInputs() > 1 || getNumConnectedOutputs() > 1 ) mProcessInPlace = false; bool isDelay = ( dynamic_cast<DelayNode *>( this ) != nullptr ); // see note above for( auto &input : mInputs ) { bool inputProcessInPlace = true; size_t inputNumChannels = input->getNumChannels(); if( ! supportsInputNumChannels( inputNumChannels ) ) { if( mChannelMode == ChannelMode::MATCHES_INPUT ) setNumChannels( getMaxNumInputChannels() ); else if( input->getChannelMode() == ChannelMode::MATCHES_OUTPUT ) { input->setNumChannels( mNumChannels ); input->configureConnections(); } else { mProcessInPlace = false; inputProcessInPlace = false; } } // inputs with more than one output cannot process in-place, so make them sum if( input->getProcessInPlace() && input->getNumConnectedOutputs() > 1 ) inputProcessInPlace = false; // if we're unable to process in-place and we're a DelayNode, its possible that the input may be part of a feedback loop, in which case input must sum. if( ! mProcessInPlace && isDelay ) inputProcessInPlace = false; if( ! inputProcessInPlace ) input->setupProcessWithSumming(); input->initializeImpl(); } for( auto &out : mOutputs ) { NodeRef output = out.lock(); if( ! output ) continue; if( ! output->supportsInputNumChannels( mNumChannels ) ) { if( output->getChannelMode() == ChannelMode::MATCHES_INPUT ) { output->setNumChannels( mNumChannels ); output->configureConnections(); } else mProcessInPlace = false; } } if( ! mProcessInPlace ) setupProcessWithSumming(); initializeImpl(); } void Node::pullInputs( Buffer *inPlaceBuffer ) { CI_ASSERT( getContext() ); if( mProcessInPlace ) { if( mInputs.empty() ) { // Fastest route: no inputs and process in-place. If disabled, get rid of any previously processsed samples. if( mEnabled ) process( inPlaceBuffer ); else inPlaceBuffer->zero(); } else { // First pull the input (can only be one when in-place), then run process() if input did any processing. const NodeRef &input = *mInputs.begin(); input->pullInputs( inPlaceBuffer ); if( ! input->getProcessInPlace() ) dsp::mixBuffers( input->getInternalBuffer(), inPlaceBuffer ); if( mEnabled ) process( inPlaceBuffer ); } } else { // Pull and sum all enabled inputs. Only do this once per processing block, which is checked by the current number of processed frames. uint64_t numProcessedFrames = getContext()->getNumProcessedFrames(); if( mLastProcessedFrame != numProcessedFrames ) { mLastProcessedFrame = numProcessedFrames; mSummingBuffer.zero(); sumInputs(); } } } void Node::sumInputs() { // Pull all inputs, summing the results from the buffer that input used for processing. // mInternalBuffer is not zero'ed before pulling inputs to allow for feedback. for( auto &input : mInputs ) { input->pullInputs( &mInternalBuffer ); const Buffer *processedBuffer = input->getProcessInPlace() ? &mInternalBuffer : input->getInternalBuffer(); dsp::sumBuffers( processedBuffer, &mSummingBuffer ); } // Process the summed results if enabled. if( mEnabled ) process( &mSummingBuffer ); // copy summed buffer back to internal so downstream can get it. dsp::mixBuffers( &mSummingBuffer, &mInternalBuffer ); } void Node::setupProcessWithSumming() { CI_ASSERT( getContext() ); mProcessInPlace = false; size_t framesPerBlock = getFramesPerBlock(); mInternalBuffer.setSize( framesPerBlock, mNumChannels ); mSummingBuffer.setSize( framesPerBlock, mNumChannels ); } bool Node::checkCycle( const NodeRef &sourceNode, const NodeRef &destNode ) const { if( sourceNode == destNode ) return true; if( sourceNode->supportsCycles() || destNode->supportsCycles() ) return false; for( const auto &input : sourceNode->getInputs() ) { if( checkCycle( input, destNode ) ) return true; } return false; } void Node::notifyConnectionsDidChange() { getContext()->connectionsDidChange( shared_from_this() ); } bool Node::canConnectToInput( const NodeRef &input ) { if( ! input || input == shared_from_this() ) return false; for( const auto& in : mInputs ) if( input == in ) return false; return true; } std::string Node::getName() { return ! mName.empty() ? mName : System::demangleTypeName( typeid( *this ).name() ); } // ---------------------------------------------------------------------------------------------------- // MARK: - NodeAutoPullable // ---------------------------------------------------------------------------------------------------- NodeAutoPullable::NodeAutoPullable( const Format &format ) : Node( format ), mIsPulledByContext( false ) { } NodeAutoPullable::~NodeAutoPullable() { } void NodeAutoPullable::connect( const NodeRef &output ) { Node::connect( output ); updatePullMethod(); } void NodeAutoPullable::connectInput( const NodeRef &input ) { Node::connectInput( input ); updatePullMethod(); } void NodeAutoPullable::disconnectInput( const NodeRef &input ) { Node::disconnectInput( input ); updatePullMethod(); } void NodeAutoPullable::disconnectAllOutputs() { Node::disconnectAllOutputs(); if( mIsPulledByContext ) { mIsPulledByContext = false; getContext()->removeAutoPulledNode( shared_from_this() ); } } void NodeAutoPullable::updatePullMethod() { bool hasOutputs = ! getOutputs().empty(); if( ! hasOutputs && ! mIsPulledByContext ) { mIsPulledByContext = true; getContext()->addAutoPulledNode( shared_from_this() ); } else if( hasOutputs && mIsPulledByContext ) { mIsPulledByContext = false; getContext()->removeAutoPulledNode( shared_from_this() ); } } // ---------------------------------------------------------------------------------------------------- // MARK: - ScopedEnableNode // ---------------------------------------------------------------------------------------------------- ScopedEnableNode::ScopedEnableNode( const NodeRef &node, bool enable ) : mNode( node ) { mWasEnabled = ( mNode ? mNode->isEnabled() : false ); } ScopedEnableNode::~ScopedEnableNode() { if( mNode ) mNode->setEnabled( mWasEnabled ); } // ---------------------------------------------------------------------------------------------------- // MARK: - Exceptions // ---------------------------------------------------------------------------------------------------- NodeCycleExc::NodeCycleExc( const NodeRef &sourceNode, const NodeRef &destNode ) : AudioExc( string( "cyclical connection between source: " ) + sourceNode->getName() + string( " and dest: " ) + destNode->getName() ) { } } } // namespace cinder::audio <commit_msg>ensure that if Node declares it cannot process inplace that its internal buffers are allocated<commit_after>/* Copyright (c) 2014, The Cinder Project This code is intended to be used with the Cinder C++ library, http://libcinder.org Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "cinder/audio/Node.h" #include "cinder/audio/DelayNode.h" #include "cinder/audio/Context.h" #include "cinder/audio/dsp/Dsp.h" #include "cinder/audio/dsp/Converter.h" #include "cinder/audio/Debug.h" #include "cinder/CinderAssert.h" #include "cinder/System.h" #include <limits> using namespace std; namespace cinder { namespace audio { // ---------------------------------------------------------------------------------------------------- // MARK: - Node // ---------------------------------------------------------------------------------------------------- Node::Node( const Format &format ) : mInitialized( false ), mEnabled( false ), mChannelMode( format.getChannelMode() ), mNumChannels( 1 ), mAutoEnabled( true ), mProcessInPlace( true ), mLastProcessedFrame( numeric_limits<uint64_t>::max() ) { if( format.getChannels() ) { mNumChannels = format.getChannels(); mChannelMode = ChannelMode::SPECIFIED; } if( ! boost::indeterminate( format.getAutoEnable() ) ) setAutoEnabled( format.getAutoEnable() ); } Node::~Node() { } void Node::connect( const NodeRef &output ) { // make a reference to ourselves so that we aren't deallocated in the case of the last owner // disconnecting us, which we may need later anyway NodeRef thisRef = shared_from_this(); if( ! output->canConnectToInput( thisRef ) ) return; if( checkCycle( thisRef, output ) ) throw NodeCycleExc( thisRef, output ); mOutputs.push_back( output ); // set output first, so that it is visible in configureConnections() output->connectInput( thisRef ); output->notifyConnectionsDidChange(); } void Node::disconnect( const NodeRef &output ) { if( ! output ) return; for( auto weakOutIt = mOutputs.begin(); weakOutIt != mOutputs.end(); ++weakOutIt ) { if( weakOutIt->lock() == output ) { mOutputs.erase( weakOutIt ); break; } } output->disconnectInput( shared_from_this() ); output->notifyConnectionsDidChange(); } void Node::disconnectAll() { disconnectAllInputs(); disconnectAllOutputs(); } void Node::disconnectAllOutputs() { NodeRef thisRef = shared_from_this(); auto outputs = getOutputs(); // first make a copy of only the still-alive NodeRef's for( const auto &output : outputs ) disconnect( output ); } void Node::disconnectAllInputs() { NodeRef thisRef = shared_from_this(); for( auto &input : mInputs ) input->disconnectOutput( thisRef ); mInputs.clear(); notifyConnectionsDidChange(); } void Node::connectInput( const NodeRef &input ) { lock_guard<mutex> lock( getContext()->getMutex() ); mInputs.insert( input ); configureConnections(); } void Node::disconnectInput( const NodeRef &input ) { lock_guard<mutex> lock( getContext()->getMutex() ); for( auto inIt = mInputs.begin(); inIt != mInputs.end(); ++inIt ) { if( *inIt == input ) { mInputs.erase( inIt ); break; } } } void Node::disconnectOutput( const NodeRef &output ) { lock_guard<mutex> lock( getContext()->getMutex() ); for( auto outIt = mOutputs.begin(); outIt != mOutputs.end(); ++outIt ) { if( outIt->lock() == output ) { mOutputs.erase( outIt ); break; } } } vector<NodeRef> Node::getOutputs() const { vector<NodeRef> result; for( const weak_ptr<Node> &outputWeak : mOutputs ) { NodeRef output = outputWeak.lock(); if( output ) result.push_back( output ); } return result; } void Node::enable() { if( ! mInitialized ) initializeImpl(); if( mEnabled ) return; mEnabled = true; enableProcessing(); } void Node::disable() { if( ! mEnabled ) return; mEnabled = false; disableProcessing(); } void Node::setEnabled( bool b ) { if( b ) enable(); else disable(); } size_t Node::getNumConnectedInputs() const { return mInputs.size(); } size_t Node::getNumConnectedOutputs() const { return mOutputs.size(); } void Node::initializeImpl() { if( mInitialized ) return; if( mProcessInPlace && ! supportsProcessInPlace() ) setupProcessWithSumming(); initialize(); mInitialized = true; if( mAutoEnabled ) enable(); } void Node::uninitializeImpl() { if( ! mInitialized ) return; disable(); uninitialize(); mInitialized = false; } void Node::setNumChannels( size_t numChannels ) { if( mNumChannels == numChannels ) return; uninitializeImpl(); mNumChannels = numChannels; } void Node::setChannelMode( ChannelMode mode ) { CI_ASSERT_MSG( ! mInitialized, "setting the channel mode must be done before initializing" ); if( mChannelMode == mode ) return; mChannelMode = mode; } size_t Node::getMaxNumInputChannels() const { size_t result = 0; for( auto &in : mInputs ) result = max( result, in->getNumChannels() ); return result; } size_t Node::getSampleRate() const { return getContext()->getSampleRate(); } size_t Node::getFramesPerBlock() const { return getContext()->getFramesPerBlock(); } // TODO: Checking for DelayNode below is a kludge and will not work for other types that want to support feedback. // With more investigation it might be possible to avoid this, or at least define some interface that // specifies whether this input needs to be summed. void Node::configureConnections() { CI_ASSERT( getContext() ); mProcessInPlace = supportsProcessInPlace(); if( getNumConnectedInputs() > 1 || getNumConnectedOutputs() > 1 ) mProcessInPlace = false; bool isDelay = ( dynamic_cast<DelayNode *>( this ) != nullptr ); // see note above for( auto &input : mInputs ) { bool inputProcessInPlace = true; size_t inputNumChannels = input->getNumChannels(); if( ! supportsInputNumChannels( inputNumChannels ) ) { if( mChannelMode == ChannelMode::MATCHES_INPUT ) setNumChannels( getMaxNumInputChannels() ); else if( input->getChannelMode() == ChannelMode::MATCHES_OUTPUT ) { input->setNumChannels( mNumChannels ); input->configureConnections(); } else { mProcessInPlace = false; inputProcessInPlace = false; } } // inputs with more than one output cannot process in-place, so make them sum if( input->getProcessInPlace() && input->getNumConnectedOutputs() > 1 ) inputProcessInPlace = false; // if we're unable to process in-place and we're a DelayNode, its possible that the input may be part of a feedback loop, in which case input must sum. if( ! mProcessInPlace && isDelay ) inputProcessInPlace = false; if( ! inputProcessInPlace ) input->setupProcessWithSumming(); input->initializeImpl(); } for( auto &out : mOutputs ) { NodeRef output = out.lock(); if( ! output ) continue; if( ! output->supportsInputNumChannels( mNumChannels ) ) { if( output->getChannelMode() == ChannelMode::MATCHES_INPUT ) { output->setNumChannels( mNumChannels ); output->configureConnections(); } else mProcessInPlace = false; } } if( ! mProcessInPlace ) setupProcessWithSumming(); initializeImpl(); } void Node::pullInputs( Buffer *inPlaceBuffer ) { CI_ASSERT( getContext() ); if( mProcessInPlace ) { if( mInputs.empty() ) { // Fastest route: no inputs and process in-place. If disabled, get rid of any previously processsed samples. if( mEnabled ) process( inPlaceBuffer ); else inPlaceBuffer->zero(); } else { // First pull the input (can only be one when in-place), then run process() if input did any processing. const NodeRef &input = *mInputs.begin(); input->pullInputs( inPlaceBuffer ); if( ! input->getProcessInPlace() ) dsp::mixBuffers( input->getInternalBuffer(), inPlaceBuffer ); if( mEnabled ) process( inPlaceBuffer ); } } else { // Pull and sum all enabled inputs. Only do this once per processing block, which is checked by the current number of processed frames. uint64_t numProcessedFrames = getContext()->getNumProcessedFrames(); if( mLastProcessedFrame != numProcessedFrames ) { mLastProcessedFrame = numProcessedFrames; mSummingBuffer.zero(); sumInputs(); } } } void Node::sumInputs() { // Pull all inputs, summing the results from the buffer that input used for processing. // mInternalBuffer is not zero'ed before pulling inputs to allow for feedback. for( auto &input : mInputs ) { input->pullInputs( &mInternalBuffer ); const Buffer *processedBuffer = input->getProcessInPlace() ? &mInternalBuffer : input->getInternalBuffer(); dsp::sumBuffers( processedBuffer, &mSummingBuffer ); } // Process the summed results if enabled. if( mEnabled ) process( &mSummingBuffer ); // copy summed buffer back to internal so downstream can get it. dsp::mixBuffers( &mSummingBuffer, &mInternalBuffer ); } void Node::setupProcessWithSumming() { CI_ASSERT( getContext() ); mProcessInPlace = false; size_t framesPerBlock = getFramesPerBlock(); mInternalBuffer.setSize( framesPerBlock, mNumChannels ); mSummingBuffer.setSize( framesPerBlock, mNumChannels ); } bool Node::checkCycle( const NodeRef &sourceNode, const NodeRef &destNode ) const { if( sourceNode == destNode ) return true; if( sourceNode->supportsCycles() || destNode->supportsCycles() ) return false; for( const auto &input : sourceNode->getInputs() ) { if( checkCycle( input, destNode ) ) return true; } return false; } void Node::notifyConnectionsDidChange() { getContext()->connectionsDidChange( shared_from_this() ); } bool Node::canConnectToInput( const NodeRef &input ) { if( ! input || input == shared_from_this() ) return false; for( const auto& in : mInputs ) if( input == in ) return false; return true; } std::string Node::getName() { return ! mName.empty() ? mName : System::demangleTypeName( typeid( *this ).name() ); } // ---------------------------------------------------------------------------------------------------- // MARK: - NodeAutoPullable // ---------------------------------------------------------------------------------------------------- NodeAutoPullable::NodeAutoPullable( const Format &format ) : Node( format ), mIsPulledByContext( false ) { } NodeAutoPullable::~NodeAutoPullable() { } void NodeAutoPullable::connect( const NodeRef &output ) { Node::connect( output ); updatePullMethod(); } void NodeAutoPullable::connectInput( const NodeRef &input ) { Node::connectInput( input ); updatePullMethod(); } void NodeAutoPullable::disconnectInput( const NodeRef &input ) { Node::disconnectInput( input ); updatePullMethod(); } void NodeAutoPullable::disconnectAllOutputs() { Node::disconnectAllOutputs(); if( mIsPulledByContext ) { mIsPulledByContext = false; getContext()->removeAutoPulledNode( shared_from_this() ); } } void NodeAutoPullable::updatePullMethod() { bool hasOutputs = ! getOutputs().empty(); if( ! hasOutputs && ! mIsPulledByContext ) { mIsPulledByContext = true; getContext()->addAutoPulledNode( shared_from_this() ); } else if( hasOutputs && mIsPulledByContext ) { mIsPulledByContext = false; getContext()->removeAutoPulledNode( shared_from_this() ); } } // ---------------------------------------------------------------------------------------------------- // MARK: - ScopedEnableNode // ---------------------------------------------------------------------------------------------------- ScopedEnableNode::ScopedEnableNode( const NodeRef &node, bool enable ) : mNode( node ) { mWasEnabled = ( mNode ? mNode->isEnabled() : false ); } ScopedEnableNode::~ScopedEnableNode() { if( mNode ) mNode->setEnabled( mWasEnabled ); } // ---------------------------------------------------------------------------------------------------- // MARK: - Exceptions // ---------------------------------------------------------------------------------------------------- NodeCycleExc::NodeCycleExc( const NodeRef &sourceNode, const NodeRef &destNode ) : AudioExc( string( "cyclical connection between source: " ) + sourceNode->getName() + string( " and dest: " ) + destNode->getName() ) { } } } // namespace cinder::audio <|endoftext|>
<commit_before> #include <atomic> #include <chrono> #include <iostream> #include <thread> #include <cppassist/cmdline/CommandLineAction.h> #include <cppassist/cmdline/CommandLineOption.h> #include <cppassist/cmdline/CommandLineParameter.h> #include <cppassist/cmdline/CommandLineProgram.h> #include <cppassist/cmdline/CommandLineSwitch.h> #include <cppfs/FileHandle.h> #include <cppfs/FileIterator.h> #include <cppfs/FileWatcher.h> #include <cppfs/LoginCredentials.h> #include <cppfs/cppfs-version.h> #include <cppfs/fs.h> using namespace cppassist; using namespace cppfs; int main(int argc, char * argv[]) { // Declare program CommandLineProgram program( "cppfs-watch", "cppfs-watch " CPPFS_VERSION, "Listen to events in the file system and print them to the console." ); CommandLineAction action("watch", "Watch files in directory"); program.add(&action); CommandLineSwitch swHelp("--help", "-h", "Print help text", CommandLineSwitch::Optional); action.add(&swHelp); CommandLineOption opConfig("--config", "-c", "file", "Load configuration from file", CommandLineOption::Optional); action.add(&opConfig); CommandLineOption opTime("--time", "-t", "seconds", "Stop watch loop after given time", CommandLineOption::Optional); action.add(&opTime); CommandLineParameter paramPath("path", CommandLineParameter::Optional); action.add(&paramPath); // Parse command line program.parse(argc, argv); if (program.hasErrors() || swHelp.activated()) { // Print help and exit program.print(program.help()); return 0; } try { // Get login credentials LoginCredentials login; std::string configFile = opConfig.value(); if (!configFile.empty()) { login.load(configFile); } // Get path std::string path = paramPath.value(); if (path.empty()) path = "."; // Open directory FileHandle dir = fs::open(path, &login); if (dir.isDirectory()) { // Watch directory FileWatcher watcher = dir.watch(); // Create file event handler watcher.addHandler([] (FileHandle & fh, FileEvent event) { // Get file type std::string type = (fh.isDirectory() ? "directory" : "file"); // Get operation std::string operation = ( (event & FileCreated) ? "created" : ( (event & FileRemoved) ? "removed" : "modified" ) ); // Log event std::cout << "The " << type << " '" << fh.path() << "' was " << operation << "." << std::endl; }); // Begin watching and printing events std::string t = opTime.value(); if (t.empty()) { while (true) { watcher.watch(); } } else { auto t_sleep = std::stoi(t); std::cout << "Will stop watching after " << t_sleep << " seconds..." << std::endl; // Execute watch loop in a separate thread std::atomic<bool> stop_thread{false}; std::thread thrd([&] { while (!stop_thread) { watcher.watch(50); // Timeout 50 ms, so we can poll stop_thread variable } }); // Zzzzz.... std::this_thread::sleep_for(std::chrono::seconds(t_sleep)); // Join watcher thread stop_thread = true; thrd.join(); } } else { std::cout << "'" << path << "' is not a valid directory." << std::endl; } } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; return -1; } // Done return 0; } <commit_msg>cppfs-watch: As file watchers are only available for the local file system, remove configuration option for remote login<commit_after> #include <atomic> #include <chrono> #include <iostream> #include <thread> #include <cppassist/cmdline/CommandLineAction.h> #include <cppassist/cmdline/CommandLineOption.h> #include <cppassist/cmdline/CommandLineParameter.h> #include <cppassist/cmdline/CommandLineProgram.h> #include <cppassist/cmdline/CommandLineSwitch.h> #include <cppfs/FileHandle.h> #include <cppfs/FileIterator.h> #include <cppfs/FileWatcher.h> #include <cppfs/LoginCredentials.h> #include <cppfs/cppfs-version.h> #include <cppfs/fs.h> using namespace cppassist; using namespace cppfs; int main(int argc, char * argv[]) { // Declare program CommandLineProgram program( "cppfs-watch", "cppfs-watch " CPPFS_VERSION, "Listen to events in the file system and print them to the console." ); CommandLineAction action("watch", "Watch files in directory"); program.add(&action); CommandLineSwitch swHelp("--help", "-h", "Print help text", CommandLineSwitch::Optional); action.add(&swHelp); CommandLineOption opConfig("--config", "-c", "file", "Load configuration from file", CommandLineOption::Optional); action.add(&opConfig); CommandLineOption opTime("--timeout", "-t", "seconds", "Stop watch loop after given time", CommandLineOption::Optional); action.add(&opTime); CommandLineParameter paramPath("path", CommandLineParameter::Optional); action.add(&paramPath); // Parse command line program.parse(argc, argv); if (program.hasErrors() || swHelp.activated()) { // Print help and exit program.print(program.help()); return 0; } try { // Get path std::string path = paramPath.value(); if (path.empty()) path = "."; // Open directory FileHandle dir = fs::open(path); if (dir.isDirectory()) { // Watch directory FileWatcher watcher = dir.watch(); // Create file event handler watcher.addHandler([] (FileHandle & fh, FileEvent event) { // Get file type std::string type = (fh.isDirectory() ? "directory" : "file"); // Get operation std::string operation = ( (event & FileCreated) ? "created" : ( (event & FileRemoved) ? "removed" : "modified" ) ); // Log event std::cout << "The " << type << " '" << fh.path() << "' was " << operation << "." << std::endl; }); // Begin watching and printing events std::string t = opTime.value(); if (t.empty()) { while (true) { watcher.watch(); } } else { auto t_sleep = std::stoi(t); std::cout << "Will stop watching after " << t_sleep << " seconds..." << std::endl; // Execute watch loop in a separate thread std::atomic<bool> stop_thread{false}; std::thread thrd([&] { while (!stop_thread) { watcher.watch(50); // Timeout 50 ms, so we can poll stop_thread variable } }); // Zzzzz.... std::this_thread::sleep_for(std::chrono::seconds(t_sleep)); // Join watcher thread stop_thread = true; thrd.join(); } } else { std::cout << "'" << path << "' is not a valid directory." << std::endl; } } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; return -1; } // Done return 0; } <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/quic/core/quic_flow_controller.h" #include <cstdint> #include "net/third_party/quiche/src/quic/core/quic_connection.h" #include "net/third_party/quiche/src/quic/core/quic_packets.h" #include "net/third_party/quiche/src/quic/core/quic_session.h" #include "net/third_party/quiche/src/quic/core/quic_utils.h" #include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h" #include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h" #include "net/third_party/quiche/src/quic/platform/api/quic_flags.h" #include "net/third_party/quiche/src/quic/platform/api/quic_logging.h" #include "net/third_party/quiche/src/common/platform/api/quiche_str_cat.h" namespace quic { #define ENDPOINT \ (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ") std::string QuicFlowController::LogLabel() { if (is_connection_flow_controller_) { return "connection"; } return quiche::QuicheStrCat("stream ", id_); } QuicFlowController::QuicFlowController( QuicSession* session, QuicStreamId id, bool is_connection_flow_controller, QuicStreamOffset send_window_offset, QuicStreamOffset receive_window_offset, QuicByteCount receive_window_size_limit, bool should_auto_tune_receive_window, QuicFlowControllerInterface* session_flow_controller) : session_(session), connection_(session->connection()), id_(id), is_connection_flow_controller_(is_connection_flow_controller), perspective_(session->perspective()), bytes_sent_(0), send_window_offset_(send_window_offset), bytes_consumed_(0), highest_received_byte_offset_(0), receive_window_offset_(receive_window_offset), receive_window_size_(receive_window_offset), receive_window_size_limit_(receive_window_size_limit), auto_tune_receive_window_(should_auto_tune_receive_window), session_flow_controller_(session_flow_controller), last_blocked_send_window_offset_(0), prev_window_update_time_(QuicTime::Zero()) { DCHECK_LE(receive_window_size_, receive_window_size_limit_); DCHECK_EQ( is_connection_flow_controller_, QuicUtils::GetInvalidStreamId(session_->transport_version()) == id_); QUIC_DVLOG(1) << ENDPOINT << "Created flow controller for " << LogLabel() << ", setting initial receive window offset to: " << receive_window_offset_ << ", max receive window to: " << receive_window_size_ << ", max receive window limit to: " << receive_window_size_limit_ << ", setting send window offset to: " << send_window_offset_; } void QuicFlowController::AddBytesConsumed(QuicByteCount bytes_consumed) { bytes_consumed_ += bytes_consumed; QUIC_DVLOG(1) << ENDPOINT << LogLabel() << " consumed " << bytes_consumed_ << " bytes."; MaybeSendWindowUpdate(); } bool QuicFlowController::UpdateHighestReceivedOffset( QuicStreamOffset new_offset) { // Only update if offset has increased. if (new_offset <= highest_received_byte_offset_) { return false; } QUIC_DVLOG(1) << ENDPOINT << LogLabel() << " highest byte offset increased from " << highest_received_byte_offset_ << " to " << new_offset; highest_received_byte_offset_ = new_offset; return true; } void QuicFlowController::AddBytesSent(QuicByteCount bytes_sent) { if (bytes_sent_ + bytes_sent > send_window_offset_) { QUIC_BUG << ENDPOINT << LogLabel() << " Trying to send an extra " << bytes_sent << " bytes, when bytes_sent = " << bytes_sent_ << ", and send_window_offset_ = " << send_window_offset_; bytes_sent_ = send_window_offset_; // This is an error on our side, close the connection as soon as possible. connection_->CloseConnection( QUIC_FLOW_CONTROL_SENT_TOO_MUCH_DATA, quiche::QuicheStrCat(send_window_offset_ - (bytes_sent_ + bytes_sent), "bytes over send window offset"), ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } bytes_sent_ += bytes_sent; QUIC_DVLOG(1) << ENDPOINT << LogLabel() << " sent " << bytes_sent_ << " bytes."; } bool QuicFlowController::FlowControlViolation() { if (highest_received_byte_offset_ > receive_window_offset_) { QUIC_DLOG(INFO) << ENDPOINT << "Flow control violation on " << LogLabel() << ", receive window offset: " << receive_window_offset_ << ", highest received byte offset: " << highest_received_byte_offset_; return true; } return false; } void QuicFlowController::MaybeIncreaseMaxWindowSize() { // Core of receive window auto tuning. This method should be called before a // WINDOW_UPDATE frame is sent. Ideally, window updates should occur close to // once per RTT. If a window update happens much faster than RTT, it implies // that the flow control window is imposing a bottleneck. To prevent this, // this method will increase the receive window size (subject to a reasonable // upper bound). For simplicity this algorithm is deliberately asymmetric, in // that it may increase window size but never decreases. // Keep track of timing between successive window updates. QuicTime now = connection_->clock()->ApproximateNow(); QuicTime prev = prev_window_update_time_; prev_window_update_time_ = now; if (!prev.IsInitialized()) { QUIC_DVLOG(1) << ENDPOINT << "first window update for " << LogLabel(); return; } if (!auto_tune_receive_window_) { return; } // Get outbound RTT. QuicTime::Delta rtt = connection_->sent_packet_manager().GetRttStats()->smoothed_rtt(); if (rtt.IsZero()) { QUIC_DVLOG(1) << ENDPOINT << "rtt zero for " << LogLabel(); return; } // Now we can compare timing of window updates with RTT. QuicTime::Delta since_last = now - prev; QuicTime::Delta two_rtt = 2 * rtt; if (since_last >= two_rtt) { // If interval between window updates is sufficiently large, there // is no need to increase receive_window_size_. return; } QuicByteCount old_window = receive_window_size_; IncreaseWindowSize(); if (receive_window_size_ > old_window) { QUIC_DVLOG(1) << ENDPOINT << "New max window increase for " << LogLabel() << " after " << since_last.ToMicroseconds() << " us, and RTT is " << rtt.ToMicroseconds() << "us. max wndw: " << receive_window_size_; if (session_flow_controller_ != nullptr) { session_flow_controller_->EnsureWindowAtLeast( kSessionFlowControlMultiplier * receive_window_size_); } } else { // TODO(ckrasic) - add a varz to track this (?). QUIC_LOG_FIRST_N(INFO, 1) << ENDPOINT << "Max window at limit for " << LogLabel() << " after " << since_last.ToMicroseconds() << " us, and RTT is " << rtt.ToMicroseconds() << "us. Limit size: " << receive_window_size_; } } void QuicFlowController::IncreaseWindowSize() { receive_window_size_ *= 2; receive_window_size_ = std::min(receive_window_size_, receive_window_size_limit_); } QuicByteCount QuicFlowController::WindowUpdateThreshold() { return receive_window_size_ / 2; } void QuicFlowController::MaybeSendWindowUpdate() { // Send WindowUpdate to increase receive window if // (receive window offset - consumed bytes) < (max window / 2). // This is behaviour copied from SPDY. DCHECK_LE(bytes_consumed_, receive_window_offset_); QuicStreamOffset available_window = receive_window_offset_ - bytes_consumed_; QuicByteCount threshold = WindowUpdateThreshold(); if (!prev_window_update_time_.IsInitialized()) { // Treat the initial window as if it is a window update, so if 1/2 the // window is used in less than 2 RTTs, the window is increased. prev_window_update_time_ = connection_->clock()->ApproximateNow(); } if (available_window >= threshold) { QUIC_DVLOG(1) << ENDPOINT << "Not sending WindowUpdate for " << LogLabel() << ", available window: " << available_window << " >= threshold: " << threshold; return; } MaybeIncreaseMaxWindowSize(); UpdateReceiveWindowOffsetAndSendWindowUpdate(available_window); } void QuicFlowController::UpdateReceiveWindowOffsetAndSendWindowUpdate( QuicStreamOffset available_window) { // Update our receive window. receive_window_offset_ += (receive_window_size_ - available_window); QUIC_DVLOG(1) << ENDPOINT << "Sending WindowUpdate frame for " << LogLabel() << ", consumed bytes: " << bytes_consumed_ << ", available window: " << available_window << ", and threshold: " << WindowUpdateThreshold() << ", and receive window size: " << receive_window_size_ << ". New receive window offset is: " << receive_window_offset_; SendWindowUpdate(); } bool QuicFlowController::ShouldSendBlocked() { if (SendWindowSize() != 0 || last_blocked_send_window_offset_ >= send_window_offset_) { return false; } QUIC_DLOG(INFO) << ENDPOINT << LogLabel() << " is flow control blocked. " << "Send window: " << SendWindowSize() << ", bytes sent: " << bytes_sent_ << ", send limit: " << send_window_offset_; // The entire send_window has been consumed, we are now flow control // blocked. // Keep track of when we last sent a BLOCKED frame so that we only send one // at a given send offset. last_blocked_send_window_offset_ = send_window_offset_; return true; } bool QuicFlowController::UpdateSendWindowOffset( QuicStreamOffset new_send_window_offset) { // Only update if send window has increased. if (new_send_window_offset <= send_window_offset_) { return false; } QUIC_DVLOG(1) << ENDPOINT << "UpdateSendWindowOffset for " << LogLabel() << " with new offset " << new_send_window_offset << " current offset: " << send_window_offset_ << " bytes_sent: " << bytes_sent_; // The flow is now unblocked but could have also been unblocked // before. Return true iff this update caused a change from blocked // to unblocked. const bool was_previously_blocked = IsBlocked(); send_window_offset_ = new_send_window_offset; return was_previously_blocked; } void QuicFlowController::EnsureWindowAtLeast(QuicByteCount window_size) { if (receive_window_size_limit_ >= window_size) { return; } QuicStreamOffset available_window = receive_window_offset_ - bytes_consumed_; IncreaseWindowSize(); UpdateReceiveWindowOffsetAndSendWindowUpdate(available_window); } bool QuicFlowController::IsBlocked() const { return SendWindowSize() == 0; } uint64_t QuicFlowController::SendWindowSize() const { if (bytes_sent_ > send_window_offset_) { return 0; } return send_window_offset_ - bytes_sent_; } void QuicFlowController::UpdateReceiveWindowSize(QuicStreamOffset size) { DCHECK_LE(size, receive_window_size_limit_); QUIC_DVLOG(1) << ENDPOINT << "UpdateReceiveWindowSize for " << LogLabel() << ": " << size; if (receive_window_size_ != receive_window_offset_) { QUIC_BUG << "receive_window_size_:" << receive_window_size_ << " != receive_window_offset:" << receive_window_offset_; return; } receive_window_size_ = size; receive_window_offset_ = size; } void QuicFlowController::SendWindowUpdate() { QuicStreamId id = id_; if (is_connection_flow_controller_) { id = QuicUtils::GetInvalidStreamId(connection_->transport_version()); } session_->SendWindowUpdate(id, receive_window_offset_); } } // namespace quic <commit_msg>gfe-relnote: In QUIC, do not send WINDOW_UPDATE if connection has been disconnected. Protected by ENABLED gfe2_reloadable_flag_quic_no_window_update_if_disconnected.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/quic/core/quic_flow_controller.h" #include <cstdint> #include "net/third_party/quiche/src/quic/core/quic_connection.h" #include "net/third_party/quiche/src/quic/core/quic_packets.h" #include "net/third_party/quiche/src/quic/core/quic_session.h" #include "net/third_party/quiche/src/quic/core/quic_utils.h" #include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h" #include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h" #include "net/third_party/quiche/src/quic/platform/api/quic_flags.h" #include "net/third_party/quiche/src/quic/platform/api/quic_logging.h" #include "net/third_party/quiche/src/common/platform/api/quiche_str_cat.h" namespace quic { #define ENDPOINT \ (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ") std::string QuicFlowController::LogLabel() { if (is_connection_flow_controller_) { return "connection"; } return quiche::QuicheStrCat("stream ", id_); } QuicFlowController::QuicFlowController( QuicSession* session, QuicStreamId id, bool is_connection_flow_controller, QuicStreamOffset send_window_offset, QuicStreamOffset receive_window_offset, QuicByteCount receive_window_size_limit, bool should_auto_tune_receive_window, QuicFlowControllerInterface* session_flow_controller) : session_(session), connection_(session->connection()), id_(id), is_connection_flow_controller_(is_connection_flow_controller), perspective_(session->perspective()), bytes_sent_(0), send_window_offset_(send_window_offset), bytes_consumed_(0), highest_received_byte_offset_(0), receive_window_offset_(receive_window_offset), receive_window_size_(receive_window_offset), receive_window_size_limit_(receive_window_size_limit), auto_tune_receive_window_(should_auto_tune_receive_window), session_flow_controller_(session_flow_controller), last_blocked_send_window_offset_(0), prev_window_update_time_(QuicTime::Zero()) { DCHECK_LE(receive_window_size_, receive_window_size_limit_); DCHECK_EQ( is_connection_flow_controller_, QuicUtils::GetInvalidStreamId(session_->transport_version()) == id_); QUIC_DVLOG(1) << ENDPOINT << "Created flow controller for " << LogLabel() << ", setting initial receive window offset to: " << receive_window_offset_ << ", max receive window to: " << receive_window_size_ << ", max receive window limit to: " << receive_window_size_limit_ << ", setting send window offset to: " << send_window_offset_; } void QuicFlowController::AddBytesConsumed(QuicByteCount bytes_consumed) { bytes_consumed_ += bytes_consumed; QUIC_DVLOG(1) << ENDPOINT << LogLabel() << " consumed " << bytes_consumed_ << " bytes."; MaybeSendWindowUpdate(); } bool QuicFlowController::UpdateHighestReceivedOffset( QuicStreamOffset new_offset) { // Only update if offset has increased. if (new_offset <= highest_received_byte_offset_) { return false; } QUIC_DVLOG(1) << ENDPOINT << LogLabel() << " highest byte offset increased from " << highest_received_byte_offset_ << " to " << new_offset; highest_received_byte_offset_ = new_offset; return true; } void QuicFlowController::AddBytesSent(QuicByteCount bytes_sent) { if (bytes_sent_ + bytes_sent > send_window_offset_) { QUIC_BUG << ENDPOINT << LogLabel() << " Trying to send an extra " << bytes_sent << " bytes, when bytes_sent = " << bytes_sent_ << ", and send_window_offset_ = " << send_window_offset_; bytes_sent_ = send_window_offset_; // This is an error on our side, close the connection as soon as possible. connection_->CloseConnection( QUIC_FLOW_CONTROL_SENT_TOO_MUCH_DATA, quiche::QuicheStrCat(send_window_offset_ - (bytes_sent_ + bytes_sent), "bytes over send window offset"), ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } bytes_sent_ += bytes_sent; QUIC_DVLOG(1) << ENDPOINT << LogLabel() << " sent " << bytes_sent_ << " bytes."; } bool QuicFlowController::FlowControlViolation() { if (highest_received_byte_offset_ > receive_window_offset_) { QUIC_DLOG(INFO) << ENDPOINT << "Flow control violation on " << LogLabel() << ", receive window offset: " << receive_window_offset_ << ", highest received byte offset: " << highest_received_byte_offset_; return true; } return false; } void QuicFlowController::MaybeIncreaseMaxWindowSize() { // Core of receive window auto tuning. This method should be called before a // WINDOW_UPDATE frame is sent. Ideally, window updates should occur close to // once per RTT. If a window update happens much faster than RTT, it implies // that the flow control window is imposing a bottleneck. To prevent this, // this method will increase the receive window size (subject to a reasonable // upper bound). For simplicity this algorithm is deliberately asymmetric, in // that it may increase window size but never decreases. // Keep track of timing between successive window updates. QuicTime now = connection_->clock()->ApproximateNow(); QuicTime prev = prev_window_update_time_; prev_window_update_time_ = now; if (!prev.IsInitialized()) { QUIC_DVLOG(1) << ENDPOINT << "first window update for " << LogLabel(); return; } if (!auto_tune_receive_window_) { return; } // Get outbound RTT. QuicTime::Delta rtt = connection_->sent_packet_manager().GetRttStats()->smoothed_rtt(); if (rtt.IsZero()) { QUIC_DVLOG(1) << ENDPOINT << "rtt zero for " << LogLabel(); return; } // Now we can compare timing of window updates with RTT. QuicTime::Delta since_last = now - prev; QuicTime::Delta two_rtt = 2 * rtt; if (since_last >= two_rtt) { // If interval between window updates is sufficiently large, there // is no need to increase receive_window_size_. return; } QuicByteCount old_window = receive_window_size_; IncreaseWindowSize(); if (receive_window_size_ > old_window) { QUIC_DVLOG(1) << ENDPOINT << "New max window increase for " << LogLabel() << " after " << since_last.ToMicroseconds() << " us, and RTT is " << rtt.ToMicroseconds() << "us. max wndw: " << receive_window_size_; if (session_flow_controller_ != nullptr) { session_flow_controller_->EnsureWindowAtLeast( kSessionFlowControlMultiplier * receive_window_size_); } } else { // TODO(ckrasic) - add a varz to track this (?). QUIC_LOG_FIRST_N(INFO, 1) << ENDPOINT << "Max window at limit for " << LogLabel() << " after " << since_last.ToMicroseconds() << " us, and RTT is " << rtt.ToMicroseconds() << "us. Limit size: " << receive_window_size_; } } void QuicFlowController::IncreaseWindowSize() { receive_window_size_ *= 2; receive_window_size_ = std::min(receive_window_size_, receive_window_size_limit_); } QuicByteCount QuicFlowController::WindowUpdateThreshold() { return receive_window_size_ / 2; } void QuicFlowController::MaybeSendWindowUpdate() { if (GetQuicReloadableFlag(quic_no_window_update_if_disconnected) && !session_->connection()->connected()) { QUIC_RELOADABLE_FLAG_COUNT(quic_no_window_update_if_disconnected); return; } // Send WindowUpdate to increase receive window if // (receive window offset - consumed bytes) < (max window / 2). // This is behaviour copied from SPDY. DCHECK_LE(bytes_consumed_, receive_window_offset_); QuicStreamOffset available_window = receive_window_offset_ - bytes_consumed_; QuicByteCount threshold = WindowUpdateThreshold(); if (!prev_window_update_time_.IsInitialized()) { // Treat the initial window as if it is a window update, so if 1/2 the // window is used in less than 2 RTTs, the window is increased. prev_window_update_time_ = connection_->clock()->ApproximateNow(); } if (available_window >= threshold) { QUIC_DVLOG(1) << ENDPOINT << "Not sending WindowUpdate for " << LogLabel() << ", available window: " << available_window << " >= threshold: " << threshold; return; } MaybeIncreaseMaxWindowSize(); UpdateReceiveWindowOffsetAndSendWindowUpdate(available_window); } void QuicFlowController::UpdateReceiveWindowOffsetAndSendWindowUpdate( QuicStreamOffset available_window) { // Update our receive window. receive_window_offset_ += (receive_window_size_ - available_window); QUIC_DVLOG(1) << ENDPOINT << "Sending WindowUpdate frame for " << LogLabel() << ", consumed bytes: " << bytes_consumed_ << ", available window: " << available_window << ", and threshold: " << WindowUpdateThreshold() << ", and receive window size: " << receive_window_size_ << ". New receive window offset is: " << receive_window_offset_; SendWindowUpdate(); } bool QuicFlowController::ShouldSendBlocked() { if (SendWindowSize() != 0 || last_blocked_send_window_offset_ >= send_window_offset_) { return false; } QUIC_DLOG(INFO) << ENDPOINT << LogLabel() << " is flow control blocked. " << "Send window: " << SendWindowSize() << ", bytes sent: " << bytes_sent_ << ", send limit: " << send_window_offset_; // The entire send_window has been consumed, we are now flow control // blocked. // Keep track of when we last sent a BLOCKED frame so that we only send one // at a given send offset. last_blocked_send_window_offset_ = send_window_offset_; return true; } bool QuicFlowController::UpdateSendWindowOffset( QuicStreamOffset new_send_window_offset) { // Only update if send window has increased. if (new_send_window_offset <= send_window_offset_) { return false; } QUIC_DVLOG(1) << ENDPOINT << "UpdateSendWindowOffset for " << LogLabel() << " with new offset " << new_send_window_offset << " current offset: " << send_window_offset_ << " bytes_sent: " << bytes_sent_; // The flow is now unblocked but could have also been unblocked // before. Return true iff this update caused a change from blocked // to unblocked. const bool was_previously_blocked = IsBlocked(); send_window_offset_ = new_send_window_offset; return was_previously_blocked; } void QuicFlowController::EnsureWindowAtLeast(QuicByteCount window_size) { if (receive_window_size_limit_ >= window_size) { return; } QuicStreamOffset available_window = receive_window_offset_ - bytes_consumed_; IncreaseWindowSize(); UpdateReceiveWindowOffsetAndSendWindowUpdate(available_window); } bool QuicFlowController::IsBlocked() const { return SendWindowSize() == 0; } uint64_t QuicFlowController::SendWindowSize() const { if (bytes_sent_ > send_window_offset_) { return 0; } return send_window_offset_ - bytes_sent_; } void QuicFlowController::UpdateReceiveWindowSize(QuicStreamOffset size) { DCHECK_LE(size, receive_window_size_limit_); QUIC_DVLOG(1) << ENDPOINT << "UpdateReceiveWindowSize for " << LogLabel() << ": " << size; if (receive_window_size_ != receive_window_offset_) { QUIC_BUG << "receive_window_size_:" << receive_window_size_ << " != receive_window_offset:" << receive_window_offset_; return; } receive_window_size_ = size; receive_window_offset_ = size; } void QuicFlowController::SendWindowUpdate() { QuicStreamId id = id_; if (is_connection_flow_controller_) { id = QuicUtils::GetInvalidStreamId(connection_->transport_version()); } session_->SendWindowUpdate(id, receive_window_offset_); } } // namespace quic <|endoftext|>
<commit_before>#include "Node.h" Node::Node(char d, int s, Node_type t) { //make a leaf type = t; data = d; frequency = s; left = NULL; right = NULL; } Node::Node(Node* l, Node* r, Node_type t) { //make a bind type = t; data = 0; frequency = l->getFrequency() + r->getFrequency(); left = l; right = r; } Node::~Node() { delete left; delete right; } int Node::getFrequency() { //frequency of a node return frequency; } char Node::getData() { return data; } <commit_msg>changed char to unsigned char<commit_after>#include "Node.h" Node::Node(unsigned char d, int s, Node_type t) { //make a leaf type = t; data = d; frequency = s; left = NULL; right = NULL; } Node::Node(Node* l, Node* r, Node_type t) { //make a bind type = t; data = 0; frequency = l->getFrequency() + r->getFrequency(); left = l; right = r; } Node::~Node() { delete left; delete right; } int Node::getFrequency() { //frequency of a node return frequency; } char Node::getData() { return data; } <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License version 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #ifndef JUBATUS_CORE_STAT_STAT_HPP_ #define JUBATUS_CORE_STAT_STAT_HPP_ #include <stdint.h> #include <algorithm> #include <cstdlib> #include <deque> #include <string> #include <utility> #include "jubatus/util/concurrent/rwmutex.h" #include "jubatus/util/data/serialization.h" #include "jubatus/util/data/serialization/unordered_map.h" #include "jubatus/util/data/unordered_map.h" #include "jubatus/util/lang/enable_shared_from_this.h" #include "jubatus/util/lang/shared_ptr.h" #include "../common/version.hpp" #include "../common/exception.hpp" #include "../common/unordered_map.hpp" #include "../framework/mixable.hpp" namespace jubatus { namespace core { namespace stat { class stat_error : public common::exception::jubaexception<stat_error> { public: explicit stat_error(const std::string& msg) : msg_(msg) { } ~stat_error() throw() { } const char* what() const throw() { return msg_.c_str(); } private: std::string msg_; }; class stat : public jubatus::util::lang::enable_shared_from_this<stat> { public: explicit stat(size_t window_size); virtual ~stat(); virtual void get_diff(std::pair<double, size_t>& ret) const; virtual bool put_diff(const std::pair<double, size_t>&); virtual void mix( const std::pair<double, size_t>& lhs, std::pair<double, size_t>& ret) const; void push(const std::string& key, double val); double sum(const std::string& key) const; double stddev(const std::string& key) const; double max(const std::string& key) const; double min(const std::string& key) const; virtual double entropy() const; double moment(const std::string& key, int n, double c) const; virtual void clear(); storage::version get_version() const { return storage::version(); } virtual void pack(msgpack::packer<msgpack::sbuffer>& packer) const; virtual void unpack(msgpack::object o); std::string type() const; virtual void register_mixables_to_holder( framework::mixable_holder& holder) const; protected: struct stat_val { stat_val() : n_(0), sum_(0), sum2_(0), max_(0), min_(0) { } void add(double d) { n_ += 1; sum_ += d; sum2_ += d * d; if (n_ > 1) { max_ = std::max(max_, d); } else { max_ = d; } if (n_ > 1) { min_ = std::min(min_, d); } else { min_ = d; } } void rem(double d, const std::string& key, stat& st) { n_ -= 1; sum_ -= d; sum2_ -= d * d; if (max_ == d) { if (n_ > 0) { bool first = true; for (size_t i = 0; i < st.window_.size(); ++i) { if (st.window_[i].second.first != key) { continue; } double d = st.window_[i].second.second; if (first) { max_ = d; first = false; } else { max_ = std::max(max_, d); } } } else { max_ = 0; } } if (min_ == d) { if (n_ > 0) { bool first = true; for (size_t i = 0; i < st.window_.size(); ++i) { if (st.window_[i].second.first != key) { continue; } double d = st.window_[i].second.second; if (first) { min_ = d; first = false; } else { min_ = std::min(min_, d); } } } else { min_ = 0; } } } friend class jubatus::util::data::serialization::access; template<class Archive> void serialize(Archive& ar) { ar & n_ & sum_ & sum2_ & max_ & min_; } size_t n_; double sum_, sum2_; double max_; double min_; MSGPACK_DEFINE(n_, sum_, sum2_, max_, min_); }; std::deque<std::pair<uint64_t, std::pair<std::string, double> > > window_; jubatus::util::data::unordered_map<std::string, stat_val> stats_; private: friend class jubatus::util::data::serialization::access; template<class Archive> void serialize(Archive& ar) { ar & window_size_ & window_ & stats_ & e_ & n_; } size_t window_size_; double e_; double n_; public: MSGPACK_DEFINE(window_size_, window_, stats_, e_, n_); }; typedef framework::delegating_mixable<stat, std::pair<double, size_t> > mixable_stat; } // namespace stat } // namespace core } // namespace jubatus #endif // JUBATUS_CORE_STAT_STAT_HPP_ <commit_msg>Fix stat to use mixable_helper<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License version 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #ifndef JUBATUS_CORE_STAT_STAT_HPP_ #define JUBATUS_CORE_STAT_STAT_HPP_ #include <stdint.h> #include <algorithm> #include <cstdlib> #include <deque> #include <string> #include <utility> #include "jubatus/util/concurrent/rwmutex.h" #include "jubatus/util/data/serialization.h" #include "jubatus/util/data/serialization/unordered_map.h" #include "jubatus/util/data/unordered_map.h" #include "jubatus/util/lang/enable_shared_from_this.h" #include "jubatus/util/lang/shared_ptr.h" #include "../common/version.hpp" #include "../common/exception.hpp" #include "../common/unordered_map.hpp" #include "../framework/mixable_helper.hpp" namespace jubatus { namespace core { namespace stat { class stat_error : public common::exception::jubaexception<stat_error> { public: explicit stat_error(const std::string& msg) : msg_(msg) { } ~stat_error() throw() { } const char* what() const throw() { return msg_.c_str(); } private: std::string msg_; }; class stat : public jubatus::util::lang::enable_shared_from_this<stat> { public: explicit stat(size_t window_size); virtual ~stat(); virtual void get_diff(std::pair<double, size_t>& ret) const; virtual bool put_diff(const std::pair<double, size_t>&); virtual void mix( const std::pair<double, size_t>& lhs, std::pair<double, size_t>& ret) const; void push(const std::string& key, double val); double sum(const std::string& key) const; double stddev(const std::string& key) const; double max(const std::string& key) const; double min(const std::string& key) const; virtual double entropy() const; double moment(const std::string& key, int n, double c) const; virtual void clear(); storage::version get_version() const { return storage::version(); } virtual void pack(msgpack::packer<msgpack::sbuffer>& packer) const; virtual void unpack(msgpack::object o); std::string type() const; virtual void register_mixables_to_holder( framework::mixable_holder& holder) const; protected: struct stat_val { stat_val() : n_(0), sum_(0), sum2_(0), max_(0), min_(0) { } void add(double d) { n_ += 1; sum_ += d; sum2_ += d * d; if (n_ > 1) { max_ = std::max(max_, d); } else { max_ = d; } if (n_ > 1) { min_ = std::min(min_, d); } else { min_ = d; } } void rem(double d, const std::string& key, stat& st) { n_ -= 1; sum_ -= d; sum2_ -= d * d; if (max_ == d) { if (n_ > 0) { bool first = true; for (size_t i = 0; i < st.window_.size(); ++i) { if (st.window_[i].second.first != key) { continue; } double d = st.window_[i].second.second; if (first) { max_ = d; first = false; } else { max_ = std::max(max_, d); } } } else { max_ = 0; } } if (min_ == d) { if (n_ > 0) { bool first = true; for (size_t i = 0; i < st.window_.size(); ++i) { if (st.window_[i].second.first != key) { continue; } double d = st.window_[i].second.second; if (first) { min_ = d; first = false; } else { min_ = std::min(min_, d); } } } else { min_ = 0; } } } friend class jubatus::util::data::serialization::access; template<class Archive> void serialize(Archive& ar) { ar & n_ & sum_ & sum2_ & max_ & min_; } size_t n_; double sum_, sum2_; double max_; double min_; MSGPACK_DEFINE(n_, sum_, sum2_, max_, min_); }; std::deque<std::pair<uint64_t, std::pair<std::string, double> > > window_; jubatus::util::data::unordered_map<std::string, stat_val> stats_; private: friend class jubatus::util::data::serialization::access; template<class Archive> void serialize(Archive& ar) { ar & window_size_ & window_ & stats_ & e_ & n_; } size_t window_size_; double e_; double n_; public: MSGPACK_DEFINE(window_size_, window_, stats_, e_, n_); }; typedef framework::linear_mixable_helper<stat, std::pair<double, size_t> > mixable_stat; } // namespace stat } // namespace core } // namespace jubatus #endif // JUBATUS_CORE_STAT_STAT_HPP_ <|endoftext|>
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <grpcpp/grpcpp.h> #include <cstring> #include <iostream> #include <string> #include "api/Compiler.hh" #include "api/DataFile.hh" #include "api/Decoder.hh" #include "api/Encoder.hh" #include "api/Generic.hh" #include "api/Specific.hh" #include "api/ValidSchema.hh" #include "google/cloud/bigquery/storage/v1beta1/storage.grpc.pb.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/lib/core/threadpool.h" #include "tensorflow/core/lib/strings/stringprintf.h" #include "tensorflow/core/public/version.h" #include "tensorflow_io/bigquery/kernels/bigquery_lib.h" namespace tensorflow { namespace { namespace apiv1beta1 = ::google::cloud::bigquery::storage::v1beta1; static constexpr int kMaxReceiveMessageSize = 1 << 24; // 16 MBytes class BigQueryClientOp : public OpKernel { public: explicit BigQueryClientOp(OpKernelConstruction* ctx) : OpKernel(ctx) {} ~BigQueryClientOp() override { if (cinfo_.resource_is_private_to_kernel()) { if (!cinfo_.resource_manager() ->Delete<BigQueryClientResource>(cinfo_.container(), cinfo_.name()) .ok()) { // Do nothing; the resource can have been deleted by session resets. } } } void Compute(OpKernelContext* ctx) override TF_LOCKS_EXCLUDED(mu_) { mutex_lock l(mu_); if (!initialized_) { ResourceMgr* mgr = ctx->resource_manager(); OP_REQUIRES_OK(ctx, cinfo_.Init(mgr, def())); BigQueryClientResource* resource; OP_REQUIRES_OK( ctx, mgr->LookupOrCreate<BigQueryClientResource>( cinfo_.container(), cinfo_.name(), &resource, [this, ctx](BigQueryClientResource** ret) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { std::string server_name = "dns:///bigquerystorage.googleapis.com"; auto creds = ::grpc::GoogleDefaultCredentials(); grpc::ChannelArguments args; args.SetMaxReceiveMessageSize(kMaxReceiveMessageSize); args.SetUserAgentPrefix( strings::StrCat("tensorflow-", TF_VERSION_STRING)); args.SetInt(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, 0); args.SetInt(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, 60 * 1000); auto channel = ::grpc::CreateCustomChannel(server_name, creds, args); VLOG(3) << "Creating GRPC channel"; auto stub = absl::make_unique<apiv1beta1::BigQueryStorage::Stub>( channel); VLOG(3) << "Done creating GRPC channel"; *ret = new BigQueryClientResource(std::move(stub)); return Status::OK(); })); core::ScopedUnref resource_cleanup(resource); initialized_ = true; } OP_REQUIRES_OK(ctx, MakeResourceHandleToOutput( ctx, 0, cinfo_.container(), cinfo_.name(), TypeIndex::Make<BigQueryClientResource>())); } private: mutex mu_; ContainerInfo cinfo_ TF_GUARDED_BY(mu_); bool initialized_ TF_GUARDED_BY(mu_) = false; }; REGISTER_KERNEL_BUILDER(Name("IO>BigQueryClient").Device(DEVICE_CPU), BigQueryClientOp); class BigQueryReadSessionOp : public OpKernel { public: explicit BigQueryReadSessionOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("parent", &parent_)); OP_REQUIRES(ctx, !parent_.empty(), errors::InvalidArgument("parent must be non-empty")); OP_REQUIRES_OK(ctx, ctx->GetAttr("project_id", &project_id_)); OP_REQUIRES(ctx, !project_id_.empty(), errors::InvalidArgument("project_id must be non-empty")); OP_REQUIRES_OK(ctx, ctx->GetAttr("table_id", &table_id_)); OP_REQUIRES(ctx, !table_id_.empty(), errors::InvalidArgument("table_id must be non-empty")); OP_REQUIRES_OK(ctx, ctx->GetAttr("dataset_id", &dataset_id_)); OP_REQUIRES(ctx, !dataset_id_.empty(), errors::InvalidArgument("dataset_id must be non-empty")); OP_REQUIRES_OK(ctx, ctx->GetAttr("selected_fields", &selected_fields_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("output_types", &output_types_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("row_restriction", &row_restriction_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("requested_streams", &requested_streams_)); string data_format_str; OP_REQUIRES_OK(ctx, ctx->GetAttr("data_format", &data_format_str)); OP_REQUIRES_OK(ctx, GetDataFormat(data_format_str, &data_format_)); } void Compute(OpKernelContext* ctx) override TF_LOCKS_EXCLUDED(mu_) { mutex_lock l(mu_); ResourceMgr* mgr = ctx->resource_manager(); OP_REQUIRES_OK(ctx, cinfo_.Init(mgr, def())); BigQueryClientResource* client_resource; OP_REQUIRES_OK( ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &client_resource)); core::ScopedUnref scoped_unref(client_resource); apiv1beta1::CreateReadSessionRequest createReadSessionRequest; createReadSessionRequest.mutable_table_reference()->set_project_id( project_id_); createReadSessionRequest.mutable_table_reference()->set_dataset_id( dataset_id_); createReadSessionRequest.mutable_table_reference()->set_table_id(table_id_); createReadSessionRequest.set_parent(parent_); *createReadSessionRequest.mutable_read_options() ->mutable_selected_fields() = {selected_fields_.begin(), selected_fields_.end()}; createReadSessionRequest.mutable_read_options()->set_row_restriction( row_restriction_); createReadSessionRequest.set_requested_streams(requested_streams_); createReadSessionRequest.set_sharding_strategy( apiv1beta1::ShardingStrategy::BALANCED); createReadSessionRequest.set_format(data_format_); VLOG(3) << "createReadSessionRequest: " << createReadSessionRequest.DebugString(); ::grpc::ClientContext context; context.AddMetadata( "x-goog-request-params", strings::Printf("table_reference.dataset_id=%s&table_" "reference.project_id=%s", dataset_id_.c_str(), project_id_.c_str())); context.set_deadline(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_seconds(60, GPR_TIMESPAN))); std::shared_ptr<apiv1beta1::ReadSession> readSessionResponse = std::make_shared<apiv1beta1::ReadSession>(); VLOG(3) << "calling readSession"; ::grpc::Status status = client_resource->get_stub()->CreateReadSession( &context, createReadSessionRequest, readSessionResponse.get()); if (!status.ok()) { VLOG(3) << "readSession status:" << GrpcStatusToString(status); ctx->CtxFailure(GrpcStatusToTfStatus(status)); return; } VLOG(3) << "readSession response:" << readSessionResponse->DebugString(); Tensor* streams_t = nullptr; OP_REQUIRES_OK( ctx, ctx->allocate_output( "streams", {readSessionResponse->streams_size()}, &streams_t)); auto streams_vec = streams_t->vec<tstring>(); for (int i = 0; i < readSessionResponse->streams_size(); i++) { streams_vec(i) = readSessionResponse->streams(i).name(); } Tensor* avro_schema_t = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output("schema", {}, &avro_schema_t)); if (data_format_ == apiv1beta1::DataFormat::AVRO) { OP_REQUIRES(ctx, readSessionResponse->has_avro_schema(), errors::InvalidArgument("AVRO schema is missing")); VLOG(3) << "avro schema:" << readSessionResponse->avro_schema().schema(); avro_schema_t->scalar<tstring>()() = readSessionResponse->avro_schema().schema(); } else if (data_format_ == apiv1beta1::DataFormat::ARROW) { OP_REQUIRES(ctx, readSessionResponse->has_arrow_schema(), errors::InvalidArgument("AVRO schema is missing")); VLOG(3) << "arrow schema:" << readSessionResponse->arrow_schema().serialized_schema(); avro_schema_t->scalar<tstring>()() = readSessionResponse->arrow_schema().serialized_schema(); } else { ctx->CtxFailure(errors::InvalidArgument("Invalid data_format")); } } private: // Note: these fields are const after construction. string parent_; string project_id_; string table_id_; string dataset_id_; std::vector<string> selected_fields_; std::vector<DataType> output_types_; string row_restriction_; int requested_streams_; apiv1beta1::DataFormat data_format_; mutex mu_; ContainerInfo cinfo_ TF_GUARDED_BY(mu_); bool initialized_ TF_GUARDED_BY(mu_) = false; }; REGISTER_KERNEL_BUILDER(Name("IO>BigQueryReadSession").Device(DEVICE_CPU), BigQueryReadSessionOp); } // namespace } // namespace tensorflow <commit_msg>Fix typos for Avro->Arrow (#1078)<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <grpcpp/grpcpp.h> #include <cstring> #include <iostream> #include <string> #include "api/Compiler.hh" #include "api/DataFile.hh" #include "api/Decoder.hh" #include "api/Encoder.hh" #include "api/Generic.hh" #include "api/Specific.hh" #include "api/ValidSchema.hh" #include "google/cloud/bigquery/storage/v1beta1/storage.grpc.pb.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/lib/core/threadpool.h" #include "tensorflow/core/lib/strings/stringprintf.h" #include "tensorflow/core/public/version.h" #include "tensorflow_io/bigquery/kernels/bigquery_lib.h" namespace tensorflow { namespace { namespace apiv1beta1 = ::google::cloud::bigquery::storage::v1beta1; static constexpr int kMaxReceiveMessageSize = 1 << 24; // 16 MBytes class BigQueryClientOp : public OpKernel { public: explicit BigQueryClientOp(OpKernelConstruction* ctx) : OpKernel(ctx) {} ~BigQueryClientOp() override { if (cinfo_.resource_is_private_to_kernel()) { if (!cinfo_.resource_manager() ->Delete<BigQueryClientResource>(cinfo_.container(), cinfo_.name()) .ok()) { // Do nothing; the resource can have been deleted by session resets. } } } void Compute(OpKernelContext* ctx) override TF_LOCKS_EXCLUDED(mu_) { mutex_lock l(mu_); if (!initialized_) { ResourceMgr* mgr = ctx->resource_manager(); OP_REQUIRES_OK(ctx, cinfo_.Init(mgr, def())); BigQueryClientResource* resource; OP_REQUIRES_OK( ctx, mgr->LookupOrCreate<BigQueryClientResource>( cinfo_.container(), cinfo_.name(), &resource, [this, ctx](BigQueryClientResource** ret) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { std::string server_name = "dns:///bigquerystorage.googleapis.com"; auto creds = ::grpc::GoogleDefaultCredentials(); grpc::ChannelArguments args; args.SetMaxReceiveMessageSize(kMaxReceiveMessageSize); args.SetUserAgentPrefix( strings::StrCat("tensorflow-", TF_VERSION_STRING)); args.SetInt(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, 0); args.SetInt(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, 60 * 1000); auto channel = ::grpc::CreateCustomChannel(server_name, creds, args); VLOG(3) << "Creating GRPC channel"; auto stub = absl::make_unique<apiv1beta1::BigQueryStorage::Stub>( channel); VLOG(3) << "Done creating GRPC channel"; *ret = new BigQueryClientResource(std::move(stub)); return Status::OK(); })); core::ScopedUnref resource_cleanup(resource); initialized_ = true; } OP_REQUIRES_OK(ctx, MakeResourceHandleToOutput( ctx, 0, cinfo_.container(), cinfo_.name(), TypeIndex::Make<BigQueryClientResource>())); } private: mutex mu_; ContainerInfo cinfo_ TF_GUARDED_BY(mu_); bool initialized_ TF_GUARDED_BY(mu_) = false; }; REGISTER_KERNEL_BUILDER(Name("IO>BigQueryClient").Device(DEVICE_CPU), BigQueryClientOp); class BigQueryReadSessionOp : public OpKernel { public: explicit BigQueryReadSessionOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("parent", &parent_)); OP_REQUIRES(ctx, !parent_.empty(), errors::InvalidArgument("parent must be non-empty")); OP_REQUIRES_OK(ctx, ctx->GetAttr("project_id", &project_id_)); OP_REQUIRES(ctx, !project_id_.empty(), errors::InvalidArgument("project_id must be non-empty")); OP_REQUIRES_OK(ctx, ctx->GetAttr("table_id", &table_id_)); OP_REQUIRES(ctx, !table_id_.empty(), errors::InvalidArgument("table_id must be non-empty")); OP_REQUIRES_OK(ctx, ctx->GetAttr("dataset_id", &dataset_id_)); OP_REQUIRES(ctx, !dataset_id_.empty(), errors::InvalidArgument("dataset_id must be non-empty")); OP_REQUIRES_OK(ctx, ctx->GetAttr("selected_fields", &selected_fields_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("output_types", &output_types_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("row_restriction", &row_restriction_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("requested_streams", &requested_streams_)); string data_format_str; OP_REQUIRES_OK(ctx, ctx->GetAttr("data_format", &data_format_str)); OP_REQUIRES_OK(ctx, GetDataFormat(data_format_str, &data_format_)); } void Compute(OpKernelContext* ctx) override TF_LOCKS_EXCLUDED(mu_) { mutex_lock l(mu_); ResourceMgr* mgr = ctx->resource_manager(); OP_REQUIRES_OK(ctx, cinfo_.Init(mgr, def())); BigQueryClientResource* client_resource; OP_REQUIRES_OK( ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &client_resource)); core::ScopedUnref scoped_unref(client_resource); apiv1beta1::CreateReadSessionRequest createReadSessionRequest; createReadSessionRequest.mutable_table_reference()->set_project_id( project_id_); createReadSessionRequest.mutable_table_reference()->set_dataset_id( dataset_id_); createReadSessionRequest.mutable_table_reference()->set_table_id(table_id_); createReadSessionRequest.set_parent(parent_); *createReadSessionRequest.mutable_read_options() ->mutable_selected_fields() = {selected_fields_.begin(), selected_fields_.end()}; createReadSessionRequest.mutable_read_options()->set_row_restriction( row_restriction_); createReadSessionRequest.set_requested_streams(requested_streams_); createReadSessionRequest.set_sharding_strategy( apiv1beta1::ShardingStrategy::BALANCED); createReadSessionRequest.set_format(data_format_); VLOG(3) << "createReadSessionRequest: " << createReadSessionRequest.DebugString(); ::grpc::ClientContext context; context.AddMetadata( "x-goog-request-params", strings::Printf("table_reference.dataset_id=%s&table_" "reference.project_id=%s", dataset_id_.c_str(), project_id_.c_str())); context.set_deadline(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_seconds(60, GPR_TIMESPAN))); std::shared_ptr<apiv1beta1::ReadSession> readSessionResponse = std::make_shared<apiv1beta1::ReadSession>(); VLOG(3) << "calling readSession"; ::grpc::Status status = client_resource->get_stub()->CreateReadSession( &context, createReadSessionRequest, readSessionResponse.get()); if (!status.ok()) { VLOG(3) << "readSession status:" << GrpcStatusToString(status); ctx->CtxFailure(GrpcStatusToTfStatus(status)); return; } VLOG(3) << "readSession response:" << readSessionResponse->DebugString(); Tensor* streams_t = nullptr; OP_REQUIRES_OK( ctx, ctx->allocate_output( "streams", {readSessionResponse->streams_size()}, &streams_t)); auto streams_vec = streams_t->vec<tstring>(); for (int i = 0; i < readSessionResponse->streams_size(); i++) { streams_vec(i) = readSessionResponse->streams(i).name(); } Tensor* schema_t = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output("schema", {}, &schema_t)); if (data_format_ == apiv1beta1::DataFormat::AVRO) { OP_REQUIRES(ctx, readSessionResponse->has_avro_schema(), errors::InvalidArgument("AVRO schema is missing")); VLOG(3) << "avro schema:" << readSessionResponse->avro_schema().schema(); schema_t->scalar<tstring>()() = readSessionResponse->avro_schema().schema(); } else if (data_format_ == apiv1beta1::DataFormat::ARROW) { OP_REQUIRES(ctx, readSessionResponse->has_arrow_schema(), errors::InvalidArgument("ARROW schema is missing")); VLOG(3) << "arrow schema:" << readSessionResponse->arrow_schema().serialized_schema(); schema_t->scalar<tstring>()() = readSessionResponse->arrow_schema().serialized_schema(); } else { ctx->CtxFailure(errors::InvalidArgument("Invalid data_format")); } } private: // Note: these fields are const after construction. string parent_; string project_id_; string table_id_; string dataset_id_; std::vector<string> selected_fields_; std::vector<DataType> output_types_; string row_restriction_; int requested_streams_; apiv1beta1::DataFormat data_format_; mutex mu_; ContainerInfo cinfo_ TF_GUARDED_BY(mu_); bool initialized_ TF_GUARDED_BY(mu_) = false; }; REGISTER_KERNEL_BUILDER(Name("IO>BigQueryReadSession").Device(DEVICE_CPU), BigQueryReadSessionOp); } // namespace } // namespace tensorflow <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include <mapnik/json/properties_generator_grammar.hpp> namespace mapnik { namespace json { namespace karma = boost::spirit::karma; template <typename OutputIterator> escaped_string<OutputIterator>::escaped_string() : escaped_string::base_type(esc_str) { karma::lit_type lit; karma::_r1_type _r1; karma::char_type char_; esc_char.add ('\a', "\\a") ('\b', "\\b") ('\f', "\\f") ('\n', "\\n") ('\r', "\\r") ('\t', "\\t") ('\v', "\\v") ('"', "\\\"") ; esc_str = lit(_r1) << *(esc_char | char_) << lit(_r1) ; } template <typename OutputIterator, typename KeyValueStore> properties_generator_grammar<OutputIterator,KeyValueStore>::properties_generator_grammar() : properties_generator_grammar::base_type(properties), quote_("\"") { boost::spirit::karma::lit_type lit; boost::spirit::karma::_val_type _val; boost::spirit::karma::_1_type _1; boost::spirit::karma::string_type kstring; boost::spirit::karma::eps_type eps; using boost::phoenix::at_c; properties = lit('{') << -(pair % lit(',')) << lit('}') ; pair = lit('"') << kstring[_1 = boost::phoenix::at_c<0>(_val)] << lit('"') << lit(':') << value[_1 = extract_string_(at_c<1>(_val))] ; value = eps(at_c<1>(_val)) << escaped_string_(quote_.c_str())[_1 = at_c<0>(_val)] | kstring[_1 = at_c<0>(_val)] ; // FIXME http://boost-spirit.com/home/articles/karma-examples/creating-your-own-generator-component-for-spirit-karma/ //value = (value_null_| bool_ | int__ | double_ | ustring)//[_1 = value_base_(_r1)] // ; //value_null_ = kstring[_1 = "null"] // ; //ustring = escaped_string_(quote_.c_str())[_1 = utf8_(_val)] // ; } }} <commit_msg>fix json output escaping to match json spec<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include <mapnik/json/properties_generator_grammar.hpp> namespace mapnik { namespace json { namespace karma = boost::spirit::karma; template <typename OutputIterator> escaped_string<OutputIterator>::escaped_string() : escaped_string::base_type(esc_str) { karma::lit_type lit; karma::_r1_type _r1; karma::char_type char_; esc_char.add ('\a', "\\u0007") ('\b', "\\b") ('\f', "\\f") ('\n', "\\n") ('\r', "\\r") ('\t', "\\t") ('\v', "\\u000b") ('"', "\\\"") ('\\', "\\\\") ; esc_str = lit(_r1) << *(esc_char | char_) << lit(_r1) ; } template <typename OutputIterator, typename KeyValueStore> properties_generator_grammar<OutputIterator,KeyValueStore>::properties_generator_grammar() : properties_generator_grammar::base_type(properties), quote_("\"") { boost::spirit::karma::lit_type lit; boost::spirit::karma::_val_type _val; boost::spirit::karma::_1_type _1; boost::spirit::karma::string_type kstring; boost::spirit::karma::eps_type eps; using boost::phoenix::at_c; properties = lit('{') << -(pair % lit(',')) << lit('}') ; pair = lit('"') << kstring[_1 = boost::phoenix::at_c<0>(_val)] << lit('"') << lit(':') << value[_1 = extract_string_(at_c<1>(_val))] ; value = eps(at_c<1>(_val)) << escaped_string_(quote_.c_str())[_1 = at_c<0>(_val)] | kstring[_1 = at_c<0>(_val)] ; // FIXME http://boost-spirit.com/home/articles/karma-examples/creating-your-own-generator-component-for-spirit-karma/ //value = (value_null_| bool_ | int__ | double_ | ustring)//[_1 = value_base_(_r1)] // ; //value_null_ = kstring[_1 = "null"] // ; //ustring = escaped_string_(quote_.c_str())[_1 = utf8_(_val)] // ; } }} <|endoftext|>
<commit_before>// RUN: %clang_cc1 -std=c++11 -S -emit-llvm -o - %s | FileCheck %s struct S { S(int x) { } S(int x, double y, double z) { } }; void fn1() { // CHECK: define void @_Z3fn1v S s { 1 }; // CHECK: alloca %struct.S, align 1 // CHECK: call void @_ZN1SC1Ei(%struct.S* %s, i32 1) } void fn2() { // CHECK: define void @_Z3fn2v S s { 1, 2.0, 3.0 }; // CHECK: alloca %struct.S, align 1 // CHECK: call void @_ZN1SC1Eidd(%struct.S* %s, i32 1, double 2.000000e+00, double 3.000000e+00) } void fn3() { // CHECK: define void @_Z3fn3v S sa[] { { 1 }, { 2 }, { 3 } }; // CHECK: alloca [3 x %struct.S], align 1 // CHECK: call void @_ZN1SC1Ei(%struct.S* %arrayinit.begin, i32 1) // CHECK: call void @_ZN1SC1Ei(%struct.S* %arrayinit.element, i32 2) // CHECK: call void @_ZN1SC1Ei(%struct.S* %arrayinit.element1, i32 3) } void fn4() { // CHECK: define void @_Z3fn4v S sa[] { { 1, 2.0, 3.0 }, { 4, 5.0, 6.0 } }; // CHECK: alloca [2 x %struct.S], align 1 // CHECK: call void @_ZN1SC1Eidd(%struct.S* %arrayinit.begin, i32 1, double 2.000000e+00, double 3.000000e+00) // CHECK: call void @_ZN1SC1Eidd(%struct.S* %arrayinit.element, i32 4, double 5.000000e+00, double 6.000000e+00) } <commit_msg>clang/test/CodeGenCXX/cxx0x-initializer-constructors.cpp: Fixup for -Asserts.<commit_after>// RUN: %clang_cc1 -std=c++11 -S -emit-llvm -o - %s | FileCheck %s struct S { S(int x) { } S(int x, double y, double z) { } }; void fn1() { // CHECK: define void @_Z3fn1v S s { 1 }; // CHECK: alloca %struct.S, align 1 // CHECK: call void @_ZN1SC1Ei(%struct.S* %s, i32 1) } void fn2() { // CHECK: define void @_Z3fn2v S s { 1, 2.0, 3.0 }; // CHECK: alloca %struct.S, align 1 // CHECK: call void @_ZN1SC1Eidd(%struct.S* %s, i32 1, double 2.000000e+00, double 3.000000e+00) } void fn3() { // CHECK: define void @_Z3fn3v S sa[] { { 1 }, { 2 }, { 3 } }; // CHECK: alloca [3 x %struct.S], align 1 // CHECK: call void @_ZN1SC1Ei(%struct.S* %{{.+}}, i32 1) // CHECK: call void @_ZN1SC1Ei(%struct.S* %{{.+}}, i32 2) // CHECK: call void @_ZN1SC1Ei(%struct.S* %{{.+}}, i32 3) } void fn4() { // CHECK: define void @_Z3fn4v S sa[] { { 1, 2.0, 3.0 }, { 4, 5.0, 6.0 } }; // CHECK: alloca [2 x %struct.S], align 1 // CHECK: call void @_ZN1SC1Eidd(%struct.S* %{{.+}}, i32 1, double 2.000000e+00, double 3.000000e+00) // CHECK: call void @_ZN1SC1Eidd(%struct.S* %{{.+}}, i32 4, double 5.000000e+00, double 6.000000e+00) } <|endoftext|>
<commit_before>#include <cstdlib> #include <csignal> #include <cerrno> #include <fcntl.h> #include <unistd.h> #include <sched.h> #include <vector> #include <sys/syscall.h> #include <sys/prctl.h> #include <sys/mount.h> #include <sys/wait.h> // NUKE #include <termios.h> #include <sys/types.h> #include <dirent.h> #include "appc/os/mkdir.h" #include "appc/image/image.h" #include "appc/util/status.h" #include "nosecone/executor/container/linux.h" namespace nosecone { namespace executor { namespace container { namespace linux { inline Status Errno(const std::string& where, int err) { return Error(where + strerror(err)); } inline char** c_env_array(const std::map<std::string, std::string>& environment) { const size_t env_size = environment.size() + 1; char** environment_array = static_cast<char**>(calloc(env_size, sizeof(char*))); off_t i = 0; for (const auto& pair : environment) { auto assignment = pair.first + "=" + pair.second; environment_array[i++] = const_cast<char*>(assignment.c_str()); } environment_array[i] = NULL; return environment_array; } inline char** c_array(const std::vector<std::string>& strings) { const size_t array_size = strings.size() + 1; char** array = static_cast<char**>(calloc(array_size, sizeof(char*))); off_t i = 0; for (const auto& str : strings) { array[i++] = const_cast<char*>(str.c_str()); } array[i] = NULL; return array; } inline char** c_array(const appc::schema::Exec& exec) { std::vector<std::string> strings{}; for (const auto& arg : exec) { strings.push_back(arg.value); } return c_array(strings); } Status Container::Impl::create_rootfs() { std::cerr << "Creating rootfs: " << rootfs_path << std::endl; const auto made_container_root = appc::os::mkdir(rootfs_path, 0755, true); if (!made_container_root) { std::string where{"Could not create directory for container: "}; return Error(where + made_container_root.message); } for (auto& image : images) { auto extracted = image.image.extract_rootfs_to(rootfs_path); if (!extracted) { std::string where{"Could not create rootfs for container: "}; return Error(where + extracted.message); } } return Success(); } #ifdef __linux__ pid_t Container::Impl::clone_pid() const { return pid; } int Container::Impl::console_fd() const { return console_master_fd; } Status await(const Container& container) { const pid_t pid = container.clone_pid(); if (pid == 0) { return Error("Cannot call wait from within container."); } if (waitpid(pid, NULL, __WALL) == -1) { return Errno("Could not wait on clone: ", errno); } return Success(); } bool parent_of(const Container& container) { return container.clone_pid() > 0; } Status Container::Impl::create_pty() { console_master_fd = posix_openpt(O_RDWR|O_NOCTTY|O_CLOEXEC); if (console_master_fd < 0) { Errno("Could not create pseudoterminal for container: ", errno); } char slave_buff[100]; if (ptsname_r(console_master_fd, slave_buff, sizeof(slave_buff) - 1 ) != 0) { Errno("Failed to determine tty name: ", errno); } console_slave_name = std::string{slave_buff}; std::cerr << "Slave PTY: " << console_slave_name << std::endl; if (grantpt(console_master_fd) != 0) { Errno("Failed to change tty owner: ", errno); } if (unlockpt(console_master_fd) != 0) { Errno("Failed to unlock tty: ", errno); } return Success(); } Status Container::Impl::start() { auto app_image = images[0]; if (!app_image.manifest.app) { return Error("Image is not startable, no app specified."); } auto app = from_some(app_image.manifest.app); auto clone_flags = CLONE_NEWIPC | CLONE_NEWPID | CLONE_NEWUTS | CLONE_NEWNS; // CLONE_NEWNET? O_o // No signal is sent to parent. pid = syscall(__NR_clone, clone_flags, NULL); if (pid == -1) { return Errno("Failed to clone: ", errno); } if (pid > 0) return Success("parent"); if (console_master_fd > STDERR_FILENO) { close(console_master_fd); close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); auto console_slave_fd = open(console_slave_name.c_str(), O_RDWR); if (console_slave_fd == -1) { return Errno("Could not open terminal: ", errno); } if (console_slave_fd != 0) { return Errno("Extraneous file handles open when creating terminal: ", errno); } dup2(STDIN_FILENO, STDOUT_FILENO); dup2(STDIN_FILENO, STDERR_FILENO); if (console_slave_fd > STDERR_FILENO) { close(console_slave_fd); } } if (setsid() == -1) { return Errno("Failed to create new session: ", errno); } ioctl(0, TIOCSCTTY, 1); // Set PDEATHSIG? // Remount / as slave if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL) != 0) { return Errno("Failed to mount / as slave: ", errno); } if (mount(rootfs_path.c_str(), rootfs_path.c_str(), "bind", MS_BIND|MS_REC, NULL) != 0) { return Errno("Failed to bind mount rootfs: ", errno); } // TODO test status auto proc_dir = pathname::join(rootfs_path, "proc"); appc::os::mkdir(proc_dir, 0755, true); if (mount("proc", proc_dir.c_str(), "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL) != 0) { return Errno("Failed to mount /proc: ", errno); } auto proc_sys_dir = pathname::join(rootfs_path, "proc", "sys"); appc::os::mkdir(proc_sys_dir, 0755, true); mount("/proc/sys", proc_sys_dir.c_str(), NULL, MS_BIND, NULL); mount(NULL, proc_sys_dir.c_str(), NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, NULL); auto sys_dir = pathname::join(rootfs_path, "sys"); appc::os::mkdir(sys_dir, 0755, true); mount("sysfs", sys_dir.c_str(), "sysfs", MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL); auto dev_dir = pathname::join(rootfs_path, "dev"); appc::os::mkdir(dev_dir, 0755, true); mount("tmpfs", dev_dir.c_str(), "tmpfs", MS_NOSUID|MS_STRICTATIME, "mode=755"); auto pts_dir = pathname::join(rootfs_path, "dev", "pts"); appc::os::mkdir(pts_dir, 0755, true); mount("devpts", pts_dir.c_str(), "devpts", MS_NOSUID|MS_NOEXEC, NULL); auto new_stdin = pathname::join(rootfs_path, "dev", "stdin"); auto new_stdout = pathname::join(rootfs_path, "dev", "stdout"); auto new_stderr = pathname::join(rootfs_path, "dev", "stderr"); symlink("/proc/self/fd/0", new_stdin.c_str()); symlink("/proc/self/fd/1", new_stdout.c_str()); symlink("/proc/self/fd/2", new_stderr.c_str()); // copy dev nodes // set seccomp // mknod dev/console // add kmsg? // locale? // timezone? // set resolv.conf // bind mounts RW // bind mounts RO // mount tmpfs // Signal parent to enforce cgroups if (chdir(rootfs_path.c_str()) != 0) { return Errno("Failed to chdir to rootfs: ", errno); } if (mount(rootfs_path.c_str(), "/", NULL, MS_MOVE, NULL) != 0) { return Errno("Failed to move mount /: ", errno); } if (chroot(".") != 0) { return Errno("chroot failed: ", errno); } if (chdir("/") != 0) { return Errno("chdir failed: ", errno); } // Set up network if (sethostname(uuid.c_str(), uuid.length()) != 0) { return Errno("Could not set hostname: ", errno); } // Drop Capabilities // Set SE Linux context umask(0022); gid_t gid = stoi(app.group.value); if (setgid(gid) != 0) { return Errno("setgid failed: ", errno); } uid_t uid = stoi(app.user.value); if (setuid(uid) != 0) { return Errno("setuid failed: ", errno); } std::map<std::string, std::string> environment{}; environment["USER"] = app.user.value; environment["LOGNAME"] = app.user.value; environment["PATH"] = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; environment["HOME"] = "/"; // TODO environment["SHELL"] = "/bin/bash"; // TODO if (app.environment) { for (const auto& pair : from_some(app.environment)) { environment[pair.name] = pair.value; } } char** environment_array = c_env_array(environment); char** exec_arguments_array = c_array(app.exec); // REM free allocated arrays if exec isn't called. if (execvpe(exec_arguments_array[0], exec_arguments_array, environment_array) == -1) { return Errno("execvpe failed: ", errno); } return Success("child"); } #endif } // namespace linux } // namespace container } // namespace executor } // namespace nosecone <commit_msg>container: Move __linux__ guard around linux implementation.<commit_after>#include <cerrno> #include <csignal> #include <cstdlib> #include <vector> #include <dirent.h> #include <fcntl.h> #include <sched.h> #include <sys/mount.h> #include <sys/syscall.h> #include <sys/types.h> #include <sys/wait.h> // TODO decide on term attrs #include <termios.h> #include <unistd.h> #include "appc/image/image.h" #include "appc/os/mkdir.h" #include "appc/util/status.h" #include "nosecone/executor/container/linux.h" #ifdef __linux__ #include <sys/prctl.h> namespace nosecone { namespace executor { namespace container { namespace linux { inline Status Errno(const std::string& where, int err) { return Error(where + strerror(err)); } inline char** c_env_array(const std::map<std::string, std::string>& environment) { const size_t env_size = environment.size() + 1; char** environment_array = static_cast<char**>(calloc(env_size, sizeof(char*))); off_t i = 0; for (const auto& pair : environment) { auto assignment = pair.first + "=" + pair.second; environment_array[i++] = const_cast<char*>(assignment.c_str()); } environment_array[i] = NULL; return environment_array; } inline char** c_array(const std::vector<std::string>& strings) { const size_t array_size = strings.size() + 1; char** array = static_cast<char**>(calloc(array_size, sizeof(char*))); off_t i = 0; for (const auto& str : strings) { array[i++] = const_cast<char*>(str.c_str()); } array[i] = NULL; return array; } inline char** c_array(const appc::schema::Exec& exec) { std::vector<std::string> strings{}; for (const auto& arg : exec) { strings.push_back(arg.value); } return c_array(strings); } Status Container::Impl::create_rootfs() { std::cerr << "Creating rootfs: " << rootfs_path << std::endl; const auto made_container_root = appc::os::mkdir(rootfs_path, 0755, true); if (!made_container_root) { std::string where{"Could not create directory for container: "}; return Error(where + made_container_root.message); } for (auto& image : images) { auto extracted = image.image.extract_rootfs_to(rootfs_path); if (!extracted) { std::string where{"Could not create rootfs for container: "}; return Error(where + extracted.message); } } return Success(); } pid_t Container::Impl::clone_pid() const { return pid; } int Container::Impl::console_fd() const { return console_master_fd; } Status await(const Container& container) { const pid_t pid = container.clone_pid(); if (pid == 0) { return Error("Cannot call wait from within container."); } if (waitpid(pid, NULL, __WALL) == -1) { return Errno("Could not wait on clone: ", errno); } return Success(); } bool parent_of(const Container& container) { return container.clone_pid() > 0; } Status Container::Impl::create_pty() { console_master_fd = posix_openpt(O_RDWR|O_NOCTTY|O_CLOEXEC); if (console_master_fd < 0) { Errno("Could not create pseudoterminal for container: ", errno); } char slave_buff[100]; if (ptsname_r(console_master_fd, slave_buff, sizeof(slave_buff) - 1 ) != 0) { Errno("Failed to determine tty name: ", errno); } console_slave_name = std::string{slave_buff}; std::cerr << "Slave PTY: " << console_slave_name << std::endl; if (grantpt(console_master_fd) != 0) { Errno("Failed to change tty owner: ", errno); } if (unlockpt(console_master_fd) != 0) { Errno("Failed to unlock tty: ", errno); } return Success(); } Status Container::Impl::start() { auto app_image = images[0]; if (!app_image.manifest.app) { return Error("Image is not startable, no app specified."); } auto app = from_some(app_image.manifest.app); auto clone_flags = CLONE_NEWIPC | CLONE_NEWPID | CLONE_NEWUTS | CLONE_NEWNS; // CLONE_NEWNET? O_o // No signal is sent to parent. pid = syscall(__NR_clone, clone_flags, NULL); if (pid == -1) { return Errno("Failed to clone: ", errno); } if (pid > 0) return Success("parent"); if (console_master_fd > STDERR_FILENO) { close(console_master_fd); close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); auto console_slave_fd = open(console_slave_name.c_str(), O_RDWR); if (console_slave_fd == -1) { return Errno("Could not open terminal: ", errno); } if (console_slave_fd != 0) { return Errno("Extraneous file handles open when creating terminal: ", errno); } dup2(STDIN_FILENO, STDOUT_FILENO); dup2(STDIN_FILENO, STDERR_FILENO); if (console_slave_fd > STDERR_FILENO) { close(console_slave_fd); } } if (setsid() == -1) { return Errno("Failed to create new session: ", errno); } ioctl(0, TIOCSCTTY, 1); // Set PDEATHSIG? // Remount / as slave if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL) != 0) { return Errno("Failed to mount / as slave: ", errno); } if (mount(rootfs_path.c_str(), rootfs_path.c_str(), "bind", MS_BIND|MS_REC, NULL) != 0) { return Errno("Failed to bind mount rootfs: ", errno); } // TODO test status auto proc_dir = pathname::join(rootfs_path, "proc"); appc::os::mkdir(proc_dir, 0755, true); if (mount("proc", proc_dir.c_str(), "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL) != 0) { return Errno("Failed to mount /proc: ", errno); } auto proc_sys_dir = pathname::join(rootfs_path, "proc", "sys"); appc::os::mkdir(proc_sys_dir, 0755, true); mount("/proc/sys", proc_sys_dir.c_str(), NULL, MS_BIND, NULL); mount(NULL, proc_sys_dir.c_str(), NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, NULL); auto sys_dir = pathname::join(rootfs_path, "sys"); appc::os::mkdir(sys_dir, 0755, true); mount("sysfs", sys_dir.c_str(), "sysfs", MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL); auto dev_dir = pathname::join(rootfs_path, "dev"); appc::os::mkdir(dev_dir, 0755, true); mount("tmpfs", dev_dir.c_str(), "tmpfs", MS_NOSUID|MS_STRICTATIME, "mode=755"); auto pts_dir = pathname::join(rootfs_path, "dev", "pts"); appc::os::mkdir(pts_dir, 0755, true); mount("devpts", pts_dir.c_str(), "devpts", MS_NOSUID|MS_NOEXEC, NULL); auto new_stdin = pathname::join(rootfs_path, "dev", "stdin"); auto new_stdout = pathname::join(rootfs_path, "dev", "stdout"); auto new_stderr = pathname::join(rootfs_path, "dev", "stderr"); symlink("/proc/self/fd/0", new_stdin.c_str()); symlink("/proc/self/fd/1", new_stdout.c_str()); symlink("/proc/self/fd/2", new_stderr.c_str()); // copy dev nodes // set seccomp // mknod dev/console // add kmsg? // locale? // timezone? // set resolv.conf // bind mounts RW // bind mounts RO // mount tmpfs // Signal parent to enforce cgroups if (chdir(rootfs_path.c_str()) != 0) { return Errno("Failed to chdir to rootfs: ", errno); } if (mount(rootfs_path.c_str(), "/", NULL, MS_MOVE, NULL) != 0) { return Errno("Failed to move mount /: ", errno); } if (chroot(".") != 0) { return Errno("chroot failed: ", errno); } if (chdir("/") != 0) { return Errno("chdir failed: ", errno); } // Set up network if (sethostname(uuid.c_str(), uuid.length()) != 0) { return Errno("Could not set hostname: ", errno); } // Drop Capabilities // Set SE Linux context umask(0022); gid_t gid = stoi(app.group.value); if (setgid(gid) != 0) { return Errno("setgid failed: ", errno); } uid_t uid = stoi(app.user.value); if (setuid(uid) != 0) { return Errno("setuid failed: ", errno); } std::map<std::string, std::string> environment{}; environment["USER"] = app.user.value; environment["LOGNAME"] = app.user.value; environment["PATH"] = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; environment["HOME"] = "/"; // TODO environment["SHELL"] = "/bin/bash"; // TODO if (app.environment) { for (const auto& pair : from_some(app.environment)) { environment[pair.name] = pair.value; } } char** environment_array = c_env_array(environment); char** exec_arguments_array = c_array(app.exec); // REM free allocated arrays if exec isn't called. if (execvpe(exec_arguments_array[0], exec_arguments_array, environment_array) == -1) { return Errno("execvpe failed: ", errno); } return Success("child"); } } // namespace linux } // namespace container } // namespace executor } // namespace nosecone #endif <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "structfieldvalue.h" #include "fieldvaluewriter.h" #include "document.h" #include <vespa/document/repo/fixedtyperepo.h> #include <vespa/document/serialization/vespadocumentdeserializer.h> #include <vespa/vespalib/objects/nbostream.h> #include <vespa/vespalib/util/crc.h> #include <vespa/document/datatype/positiondatatype.h> #include <vespa/document/util/serializableexceptions.h> #include <vespa/document/base/exceptions.h> #include <vespa/document/util/bytebuffer.h> #include <vespa/vespalib/util/xmlstream.h> #include <algorithm> #include <vespa/log/log.h> LOG_SETUP(".document.structfieldvalue"); using std::vector; using vespalib::nbostream; using vespalib::nbostream_longlivedbuf; using vespalib::make_string; using vespalib::compression::CompressionConfig; using namespace vespalib::xml; namespace document { IMPLEMENT_IDENTIFIABLE_ABSTRACT(StructFieldValue, StructuredFieldValue); StructFieldValue::StructFieldValue(const DataType &type) : StructuredFieldValue(type), _repo(NULL), _doc_type(NULL), _version(Document::getNewestSerializationVersion()), _hasChanged(true) { } StructFieldValue::~StructFieldValue() { } StructFieldValue::Chunks::~Chunks() { } void StructFieldValue::Chunks::push_back(SerializableArray::UP item) { assert(_sz < 2); _chunks[_sz++].reset(item.release()); } void StructFieldValue::Chunks::clear() { _chunks[0].reset(); _chunks[1].reset(); _sz = 0; } void StructFieldValue::Chunks::swap(Chunks & rhs) { _chunks[0].swap(rhs._chunks[0]); _chunks[1].swap(rhs._chunks[1]); std::swap(_sz, rhs._sz); } void StructFieldValue::swap(StructFieldValue & rhs) { StructuredFieldValue::swap(rhs); std::swap(_chunks, rhs._chunks); std::swap(_hasChanged, rhs._hasChanged); std::swap(_repo, rhs._repo); std::swap(_doc_type, rhs._doc_type); std::swap(_version, _version); } const StructDataType & StructFieldValue::getStructType() const { return static_cast<const StructDataType &>(getType()); } const CompressionConfig & StructFieldValue::getCompressionConfig() const { return getStructType().getCompressionConfig(); } void StructFieldValue::lazyDeserialize(const FixedTypeRepo &repo, uint16_t version, SerializableArray::EntryMap && fm, ByteBuffer::UP buffer, CompressionConfig::Type comp_type, int32_t uncompressed_length) { _repo = &repo.getDocumentTypeRepo(); _doc_type = &repo.getDocumentType(); _version = version; _chunks.push_back(SerializableArray::UP(new SerializableArray())); _chunks.back().assign(fm, std::move(buffer), comp_type, uncompressed_length); _hasChanged = false; } bool StructFieldValue::serializeField(int field_id, uint16_t version, FieldValueWriter &writer) const { if (version == _version) { for (int i = _chunks.size() - 1; i >= 0; --i) { vespalib::ConstBufferRef buf = _chunks[i].get(field_id); if ( buf.size() != 0) { writer.writeSerializedData(buf.data(), buf.size()); break; } } return true; } try { const Field &f = getStructType().getField(field_id); writer.writeFieldValue(*getFieldValue(f)); return true; } catch (FieldNotFoundException &) { LOG(info, "Dropping field %d when serializing to a newer version", field_id); return false; } } void StructFieldValue::getRawFieldIds(vector<int> &raw_ids) const { raw_ids.clear(); size_t count(0); for (uint32_t i = 0; i < _chunks.size(); ++i) { count += _chunks[i].getEntries().size(); } raw_ids.reserve(count); for (uint32_t i = 0; i < _chunks.size(); ++i) { const SerializableArray::EntryMap & entries = _chunks[i].getEntries(); for (const SerializableArray::Entry & entry : entries) { raw_ids.emplace_back(entry.id()); } } sort(raw_ids.begin(), raw_ids.end()); raw_ids.erase(unique(raw_ids.begin(), raw_ids.end()), raw_ids.end()); } void StructFieldValue::getRawFieldIds(vector<int> &raw_ids, const FieldSet& fieldSet) const { raw_ids.clear(); for (uint32_t i = 0; i < _chunks.size(); ++i) { const SerializableArray::EntryMap & entries = _chunks[i].getEntries(); for (const SerializableArray::Entry & entry : entries) { if (fieldSet.contains(getStructType().getField(entry.id()))) { raw_ids.push_back(entry.id()); } } } sort(raw_ids.begin(), raw_ids.end()); raw_ids.erase(unique(raw_ids.begin(), raw_ids.end()), raw_ids.end()); } bool StructFieldValue::hasField(const vespalib::stringref & name) const { return getStructType().hasField(name); } const Field& StructFieldValue::getField(const vespalib::stringref & name) const { return getStructType().getField(name); } namespace { void createFV(FieldValue & value, const DocumentTypeRepo & repo, nbostream & stream, const DocumentType & doc_type, uint32_t version) { FixedTypeRepo frepo(repo, doc_type); VespaDocumentDeserializer deserializer(frepo, stream, version); deserializer.read(value); } } FieldValue::UP StructFieldValue::getFieldValue(const Field& field) const { int fieldId = field.getId(); for (int i = _chunks.size() - 1; i >= 0; --i) { vespalib::ConstBufferRef buf = _chunks[i].get(fieldId); if (buf.size() != 0) { nbostream stream(buf.c_str(), buf.size()); FieldValue::UP value(field.getDataType().createFieldValue()); if ((_repo == NULL) && (_doc_type != NULL)) { DocumentTypeRepo::UP tmpRepo(new DocumentTypeRepo(*_doc_type)); createFV(*value, *tmpRepo, stream, *_doc_type, _version); } else { createFV(*value, *_repo, stream, *_doc_type, _version); } return value; } } return FieldValue::UP(); } vespalib::ConstBufferRef StructFieldValue::getRawField(uint32_t id) const { for (int i = _chunks.size() - 1; i >= 0; --i) { vespalib::ConstBufferRef buf = _chunks[i].get(id); if (buf.size() > 0) { return buf; } } return vespalib::ConstBufferRef(); } bool StructFieldValue::getFieldValue(const Field& field, FieldValue& value) const { int fieldId = field.getId(); vespalib::ConstBufferRef buf = getRawField(fieldId); if (buf.size() > 0) { nbostream_longlivedbuf stream(buf.c_str(), buf.size()); if ((_repo == NULL) && (_doc_type != NULL)) { DocumentTypeRepo::UP tmpRepo(new DocumentTypeRepo(*_doc_type)); createFV(value, *tmpRepo, stream, *_doc_type, _version); } else { createFV(value, *_repo, stream, *_doc_type, _version); } return true; } return false; } bool StructFieldValue::hasFieldValue(const Field& field) const { for (int i = _chunks.size() - 1; i >= 0; --i) { if (_chunks[i].has(field.getId())) { return true; } } return false; } void StructFieldValue::setFieldValue(const Field& field, FieldValue::UP value) { int fieldId = field.getId(); std::unique_ptr<ByteBuffer> serialized(value->serialize()); if (serialized->getLength() >= 0x4000000) { // Max 64 MB fields. throw SerializeException(make_string("Field value for field %i larger than 64 MB", fieldId), VESPA_STRLOC); } serialized->flip(); if (_chunks.empty()) { _chunks.push_back(SerializableArray::UP(new SerializableArray())); } _chunks.back().set(fieldId, std::move(serialized)); _hasChanged = true; } void StructFieldValue::removeFieldValue(const Field& field) { for (uint32_t i = 0; i < _chunks.size(); ++i) { _chunks[i].clear(field.getId()); } _hasChanged = true; } void StructFieldValue::clear() { _chunks.clear(); _hasChanged = true; } // FieldValue implementation. FieldValue& StructFieldValue::assign(const FieldValue& value) { const StructFieldValue& other(dynamic_cast<const StructFieldValue&>(value)); return operator=(other); } int StructFieldValue::compare(const FieldValue& otherOrg) const { int comp = StructuredFieldValue::compare(otherOrg); if (comp != 0) { return comp; } const StructFieldValue& other = static_cast<const StructFieldValue&>(otherOrg); std::vector<int> a; getRawFieldIds(a); std::vector<int> b; other.getRawFieldIds(b); for (size_t i(0); i < std::min(a.size(), b.size()); i++) { if (a[i] != b[i]) { return a[i] < b[i] ? -1 : 1; } vespalib::ConstBufferRef ar = getRawField(a[i]); vespalib::ConstBufferRef br = other.getRawField(a[i]); comp = memcmp(ar.c_str(), br.c_str(), std::min(ar.size(), br.size())); if (comp != 0) { return comp; } if ( ar.size() != br.size()) { return ar.size() < br.size() ? -1 : 1; } } if (a.size() != b.size()) { return a.size() < b.size() ? -1 : 1; } return 0; } uint32_t StructFieldValue::calculateChecksum() const { ByteBuffer::UP buffer(serialize()); vespalib::crc_32_type calculator; calculator.process_bytes(buffer->getBuffer(), buffer->getPos()); return calculator.checksum(); } void StructFieldValue::printXml(XmlOutputStream& xos) const { if (getType() == PositionDataType::getInstance() && getFieldValue(getField(PositionDataType::FIELD_Y)) && getFieldValue(getField(PositionDataType::FIELD_X))) { double ns = getFieldValue(getField(PositionDataType::FIELD_Y))->getAsInt() / 1.0e6; double ew = getFieldValue(getField(PositionDataType::FIELD_X))->getAsInt() / 1.0e6; vespalib::string buf = make_string("%s%.6f;%s%.6f", (ns < 0 ? "S" : "N"), (ns < 0 ? (-ns) : ns), (ew < 0 ? "W" : "E"), (ew < 0 ? (-ew) : ew)); xos << buf; return; } for (const_iterator it = begin(); it != end(); ++it) { xos << XmlTag(it.field().getName()); getValue(it.field())->printXml(xos); xos << XmlEndTag(); } } void StructFieldValue::print(std::ostream& out, bool verbose, const std::string& indent) const { out << "Struct " << getDataType()->getName() << "("; int count = 0; for (const_iterator it = begin(); it != end(); ++it) { if (count++ != 0) { out << ","; } out << "\n" << indent << " " << it.field().getName() << " - "; getValue(it.field())->print(out, verbose, indent + " "); } if (count > 0) out << "\n" << indent; out << ")"; } bool StructFieldValue::empty() const { for (uint32_t i = 0; i < _chunks.size(); ++i) { if (!_chunks[i].empty()) { return false; } } return true; } void StructFieldValue::reset() { clear(); _hasChanged = false; } struct StructFieldValue::FieldIterator : public StructuredIterator { const StructFieldValue& _struct; std::vector<int> _ids; std::vector<int>::iterator _cur; FieldIterator(const StructFieldValue& s) : _struct(s), _ids(), _cur(_ids.begin()) { s.getRawFieldIds(_ids); _cur = _ids.begin(); } void skipTo(int fieldId) { while (_cur != _ids.end() && fieldId != *_cur) { ++_cur; } } const Field* getNextField() override { while (_cur != _ids.end()) { int id = *_cur++; try { return &_struct.getStructType().getField(id); } catch (FieldNotFoundException& e) { // Should not get this exception until after we've moved the iterator. LOG(debug, "exception for id %d", id); LOG(debug, "struct data type: %s", _struct.getType().toString(true).c_str()); } } return 0; } }; StructuredFieldValue::StructuredIterator::UP StructFieldValue::getIterator(const Field* toFind) const { StructuredIterator::UP ret; FieldIterator *fi = new FieldIterator(*this); ret.reset(fi); if (toFind != NULL) { fi->skipTo(toFind->getId()); } return ret; } void StructFieldValue::setType(const DataType& type) { clear(); StructuredFieldValue::setType(type); } } // document <commit_msg>Remove assert that is not valid. This might have been the case at some point in time, but no longer.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "structfieldvalue.h" #include "fieldvaluewriter.h" #include "document.h" #include <vespa/document/repo/fixedtyperepo.h> #include <vespa/document/serialization/vespadocumentdeserializer.h> #include <vespa/vespalib/objects/nbostream.h> #include <vespa/vespalib/util/crc.h> #include <vespa/document/datatype/positiondatatype.h> #include <vespa/document/util/serializableexceptions.h> #include <vespa/document/base/exceptions.h> #include <vespa/document/util/bytebuffer.h> #include <vespa/vespalib/util/xmlstream.h> #include <algorithm> #include <vespa/log/log.h> LOG_SETUP(".document.structfieldvalue"); using std::vector; using vespalib::nbostream; using vespalib::nbostream_longlivedbuf; using vespalib::make_string; using vespalib::compression::CompressionConfig; using namespace vespalib::xml; namespace document { IMPLEMENT_IDENTIFIABLE_ABSTRACT(StructFieldValue, StructuredFieldValue); StructFieldValue::StructFieldValue(const DataType &type) : StructuredFieldValue(type), _repo(NULL), _doc_type(NULL), _version(Document::getNewestSerializationVersion()), _hasChanged(true) { } StructFieldValue::~StructFieldValue() { } StructFieldValue::Chunks::~Chunks() { } void StructFieldValue::Chunks::push_back(SerializableArray::UP item) { assert(_sz < 2); _chunks[_sz++].reset(item.release()); } void StructFieldValue::Chunks::clear() { _chunks[0].reset(); _chunks[1].reset(); _sz = 0; } void StructFieldValue::Chunks::swap(Chunks & rhs) { _chunks[0].swap(rhs._chunks[0]); _chunks[1].swap(rhs._chunks[1]); std::swap(_sz, rhs._sz); } void StructFieldValue::swap(StructFieldValue & rhs) { StructuredFieldValue::swap(rhs); std::swap(_chunks, rhs._chunks); std::swap(_hasChanged, rhs._hasChanged); std::swap(_repo, rhs._repo); std::swap(_doc_type, rhs._doc_type); std::swap(_version, _version); } const StructDataType & StructFieldValue::getStructType() const { return static_cast<const StructDataType &>(getType()); } const CompressionConfig & StructFieldValue::getCompressionConfig() const { return getStructType().getCompressionConfig(); } void StructFieldValue::lazyDeserialize(const FixedTypeRepo &repo, uint16_t version, SerializableArray::EntryMap && fm, ByteBuffer::UP buffer, CompressionConfig::Type comp_type, int32_t uncompressed_length) { _repo = &repo.getDocumentTypeRepo(); _doc_type = &repo.getDocumentType(); _version = version; _chunks.push_back(SerializableArray::UP(new SerializableArray())); _chunks.back().assign(fm, std::move(buffer), comp_type, uncompressed_length); _hasChanged = false; } bool StructFieldValue::serializeField(int field_id, uint16_t version, FieldValueWriter &writer) const { if (version == _version) { for (int i = _chunks.size() - 1; i >= 0; --i) { vespalib::ConstBufferRef buf = _chunks[i].get(field_id); if ( buf.size() != 0) { writer.writeSerializedData(buf.data(), buf.size()); break; } } return true; } try { const Field &f = getStructType().getField(field_id); writer.writeFieldValue(*getFieldValue(f)); return true; } catch (FieldNotFoundException &) { LOG(info, "Dropping field %d when serializing to a newer version", field_id); return false; } } void StructFieldValue::getRawFieldIds(vector<int> &raw_ids) const { raw_ids.clear(); size_t count(0); for (uint32_t i = 0; i < _chunks.size(); ++i) { count += _chunks[i].getEntries().size(); } raw_ids.reserve(count); for (uint32_t i = 0; i < _chunks.size(); ++i) { const SerializableArray::EntryMap & entries = _chunks[i].getEntries(); for (const SerializableArray::Entry & entry : entries) { raw_ids.emplace_back(entry.id()); } } sort(raw_ids.begin(), raw_ids.end()); raw_ids.erase(unique(raw_ids.begin(), raw_ids.end()), raw_ids.end()); } void StructFieldValue::getRawFieldIds(vector<int> &raw_ids, const FieldSet& fieldSet) const { raw_ids.clear(); for (uint32_t i = 0; i < _chunks.size(); ++i) { const SerializableArray::EntryMap & entries = _chunks[i].getEntries(); for (const SerializableArray::Entry & entry : entries) { if (fieldSet.contains(getStructType().getField(entry.id()))) { raw_ids.push_back(entry.id()); } } } sort(raw_ids.begin(), raw_ids.end()); raw_ids.erase(unique(raw_ids.begin(), raw_ids.end()), raw_ids.end()); } bool StructFieldValue::hasField(const vespalib::stringref & name) const { return getStructType().hasField(name); } const Field& StructFieldValue::getField(const vespalib::stringref & name) const { return getStructType().getField(name); } namespace { void createFV(FieldValue & value, const DocumentTypeRepo & repo, nbostream & stream, const DocumentType & doc_type, uint32_t version) { FixedTypeRepo frepo(repo, doc_type); VespaDocumentDeserializer deserializer(frepo, stream, version); deserializer.read(value); } } FieldValue::UP StructFieldValue::getFieldValue(const Field& field) const { int fieldId = field.getId(); for (int i = _chunks.size() - 1; i >= 0; --i) { vespalib::ConstBufferRef buf = _chunks[i].get(fieldId); if (buf.size() != 0) { nbostream stream(buf.c_str(), buf.size()); FieldValue::UP value(field.getDataType().createFieldValue()); if ((_repo == NULL) && (_doc_type != NULL)) { DocumentTypeRepo::UP tmpRepo(new DocumentTypeRepo(*_doc_type)); createFV(*value, *tmpRepo, stream, *_doc_type, _version); } else { createFV(*value, *_repo, stream, *_doc_type, _version); } return value; } } return FieldValue::UP(); } vespalib::ConstBufferRef StructFieldValue::getRawField(uint32_t id) const { for (int i = _chunks.size() - 1; i >= 0; --i) { vespalib::ConstBufferRef buf = _chunks[i].get(id); if (buf.size() > 0) { return buf; } } return vespalib::ConstBufferRef(); } bool StructFieldValue::getFieldValue(const Field& field, FieldValue& value) const { int fieldId = field.getId(); vespalib::ConstBufferRef buf = getRawField(fieldId); if (buf.size() > 0) { nbostream_longlivedbuf stream(buf.c_str(), buf.size()); if ((_repo == NULL) && (_doc_type != NULL)) { DocumentTypeRepo::UP tmpRepo(new DocumentTypeRepo(*_doc_type)); createFV(value, *tmpRepo, stream, *_doc_type, _version); } else { createFV(value, *_repo, stream, *_doc_type, _version); } return true; } return false; } bool StructFieldValue::hasFieldValue(const Field& field) const { for (int i = _chunks.size() - 1; i >= 0; --i) { if (_chunks[i].has(field.getId())) { return true; } } return false; } void StructFieldValue::setFieldValue(const Field& field, FieldValue::UP value) { int fieldId = field.getId(); std::unique_ptr<ByteBuffer> serialized(value->serialize()); serialized->flip(); if (_chunks.empty()) { _chunks.push_back(SerializableArray::UP(new SerializableArray())); } _chunks.back().set(fieldId, std::move(serialized)); _hasChanged = true; } void StructFieldValue::removeFieldValue(const Field& field) { for (uint32_t i = 0; i < _chunks.size(); ++i) { _chunks[i].clear(field.getId()); } _hasChanged = true; } void StructFieldValue::clear() { _chunks.clear(); _hasChanged = true; } // FieldValue implementation. FieldValue& StructFieldValue::assign(const FieldValue& value) { const StructFieldValue& other(dynamic_cast<const StructFieldValue&>(value)); return operator=(other); } int StructFieldValue::compare(const FieldValue& otherOrg) const { int comp = StructuredFieldValue::compare(otherOrg); if (comp != 0) { return comp; } const StructFieldValue& other = static_cast<const StructFieldValue&>(otherOrg); std::vector<int> a; getRawFieldIds(a); std::vector<int> b; other.getRawFieldIds(b); for (size_t i(0); i < std::min(a.size(), b.size()); i++) { if (a[i] != b[i]) { return a[i] < b[i] ? -1 : 1; } vespalib::ConstBufferRef ar = getRawField(a[i]); vespalib::ConstBufferRef br = other.getRawField(a[i]); comp = memcmp(ar.c_str(), br.c_str(), std::min(ar.size(), br.size())); if (comp != 0) { return comp; } if ( ar.size() != br.size()) { return ar.size() < br.size() ? -1 : 1; } } if (a.size() != b.size()) { return a.size() < b.size() ? -1 : 1; } return 0; } uint32_t StructFieldValue::calculateChecksum() const { ByteBuffer::UP buffer(serialize()); vespalib::crc_32_type calculator; calculator.process_bytes(buffer->getBuffer(), buffer->getPos()); return calculator.checksum(); } void StructFieldValue::printXml(XmlOutputStream& xos) const { if (getType() == PositionDataType::getInstance() && getFieldValue(getField(PositionDataType::FIELD_Y)) && getFieldValue(getField(PositionDataType::FIELD_X))) { double ns = getFieldValue(getField(PositionDataType::FIELD_Y))->getAsInt() / 1.0e6; double ew = getFieldValue(getField(PositionDataType::FIELD_X))->getAsInt() / 1.0e6; vespalib::string buf = make_string("%s%.6f;%s%.6f", (ns < 0 ? "S" : "N"), (ns < 0 ? (-ns) : ns), (ew < 0 ? "W" : "E"), (ew < 0 ? (-ew) : ew)); xos << buf; return; } for (const_iterator it = begin(); it != end(); ++it) { xos << XmlTag(it.field().getName()); getValue(it.field())->printXml(xos); xos << XmlEndTag(); } } void StructFieldValue::print(std::ostream& out, bool verbose, const std::string& indent) const { out << "Struct " << getDataType()->getName() << "("; int count = 0; for (const_iterator it = begin(); it != end(); ++it) { if (count++ != 0) { out << ","; } out << "\n" << indent << " " << it.field().getName() << " - "; getValue(it.field())->print(out, verbose, indent + " "); } if (count > 0) out << "\n" << indent; out << ")"; } bool StructFieldValue::empty() const { for (uint32_t i = 0; i < _chunks.size(); ++i) { if (!_chunks[i].empty()) { return false; } } return true; } void StructFieldValue::reset() { clear(); _hasChanged = false; } struct StructFieldValue::FieldIterator : public StructuredIterator { const StructFieldValue& _struct; std::vector<int> _ids; std::vector<int>::iterator _cur; FieldIterator(const StructFieldValue& s) : _struct(s), _ids(), _cur(_ids.begin()) { s.getRawFieldIds(_ids); _cur = _ids.begin(); } void skipTo(int fieldId) { while (_cur != _ids.end() && fieldId != *_cur) { ++_cur; } } const Field* getNextField() override { while (_cur != _ids.end()) { int id = *_cur++; try { return &_struct.getStructType().getField(id); } catch (FieldNotFoundException& e) { // Should not get this exception until after we've moved the iterator. LOG(debug, "exception for id %d", id); LOG(debug, "struct data type: %s", _struct.getType().toString(true).c_str()); } } return 0; } }; StructuredFieldValue::StructuredIterator::UP StructFieldValue::getIterator(const Field* toFind) const { StructuredIterator::UP ret; FieldIterator *fi = new FieldIterator(*this); ret.reset(fi); if (toFind != NULL) { fi->skipTo(toFind->getId()); } return ret; } void StructFieldValue::setType(const DataType& type) { clear(); StructuredFieldValue::setType(type); } } // document <|endoftext|>
<commit_before>#ifndef PYTHONIC_BUILTIN_STR_HPP #define PYTHONIC_BUILTIN_STR_HPP #include "pythonic/include/__builtin__/str.hpp" #include "pythonic/types/str.hpp" #include "pythonic/utils/functor.hpp" #include <sstream> namespace pythonic { namespace __builtin__ { namespace anonymous { template <class T> types::str str(T &&t) { std::ostringstream oss; oss << t; return oss.str(); } inline types::str str(long value) { /* adapted from http://www.jb.man.ac.uk/~slowe/cpp/itoa.html#performance */ thread_local static char buffer[8 * (1 << sizeof(value))]; // this buffer is large enough to // hold the binary representation, // so the decimal representation // will be ok char *ptr = buffer, *ptr1 = buffer, tmp_char; long tmp_value; do { tmp_value = value; value /= 10; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmn" "opqrstuvwxyz"[35 + (tmp_value - value * 10)]; } while (value); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while (ptr1 < ptr) { tmp_char = *ptr; *ptr-- = *ptr1; *ptr1++ = tmp_char; } return buffer; } inline types::str str(double l) { thread_local static char buffer[8 * (1 << sizeof(l))]; // when using %g, // only 6 // significant // bits are used, // so this should // be enough. Use // snprintf // though snprintf(buffer, sizeof(buffer), "%g", l); return buffer; } } DEFINE_FUNCTOR(pythonic::__builtin__::anonymous, str); } } #endif <commit_msg>Remove TLS dependency for better portability<commit_after>#ifndef PYTHONIC_BUILTIN_STR_HPP #define PYTHONIC_BUILTIN_STR_HPP #include "pythonic/include/__builtin__/str.hpp" #include "pythonic/types/str.hpp" #include "pythonic/utils/functor.hpp" #include <sstream> namespace pythonic { namespace __builtin__ { namespace anonymous { template <class T> types::str str(T &&t) { std::ostringstream oss; oss << t; return oss.str(); } inline types::str str(long value) { /* adapted from http://www.jb.man.ac.uk/~slowe/cpp/itoa.html#performance */ // this buffer is large enough to hold the binary representation, so // the decimal representation will be ok char buffer[8 * (1 << sizeof(value))]; char *ptr = buffer, *ptr1 = buffer, tmp_char; long tmp_value; do { tmp_value = value; value /= 10; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmn" "opqrstuvwxyz"[35 + (tmp_value - value * 10)]; } while (value); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while (ptr1 < ptr) { tmp_char = *ptr; *ptr-- = *ptr1; *ptr1++ = tmp_char; } return buffer; } inline types::str str(double l) { // when using %g, only 6 significant bits are used, so this should be // enough. // Use snprintf though char buffer[8 * (1 << sizeof(l))]; snprintf(buffer, sizeof(buffer), "%g", l); return buffer; } } DEFINE_FUNCTOR(pythonic::__builtin__::anonymous, str); } } #endif <|endoftext|>
<commit_before>#include "descriptor_loader.hpp" #include <openMVG/sfm/sfm_data_io.hpp> #include <openMVG/logger.hpp> #include <boost/algorithm/string/predicate.hpp> namespace openMVG { namespace voctree { void getInfoBinFile(const std::string &path, int dim, size_t &numDescriptors, int &bytesPerElement) { std::fstream fs; // the file is supposed to have the number of descriptors as first element and then // the set of descriptors of dimension dim either as chars or floats // Open file and get the number of descriptors fs.open(path, std::ios::in | std::ios::binary); if(!fs.is_open()) { OPENMVG_CERR("Error while opening " << path); OPENMVG_CERR("Error while opening " + path); } // go to the end of the file fs.seekg(0, fs.end); // get the length in byte of the file //@fixeme we are ignoring the first element of the file which is the number of // feature. However given the large amount of data of the feature this is mitigate // by the integer division in bytepd later int length = fs.tellg(); // go back to the beginning of the file fs.seekg(0, fs.beg); // get the number of descriptors fs.read((char*) &numDescriptors, sizeof (size_t)); if(numDescriptors > 0) { // get the number of bytes per descriptor element bytesPerElement = (length / numDescriptors) / dim; } else { bytesPerElement = 0; } } void getListOfDescriptorFiles(const std::string &fileFullPath, std::map<IndexT, std::string> &descriptorsFiles) { namespace bfs = boost::filesystem; std::ifstream fs; bfs::path pathToFiles; descriptorsFiles.clear(); bfs::path bp(fileFullPath); // If the input is a directory, list all .desc files recursively. if(bfs::is_directory(bp)) { std::size_t viewId = 0; for(bfs::recursive_directory_iterator it(bp), end; it != end; ++it) { if(!bfs::is_directory(*it) && it->path().extension() == ".desc") { descriptorsFiles[viewId++] = it->path().string(); } } return; } if(!bp.has_extension()) { OPENMVG_CERR("File without extension not recognized! " << fileFullPath); OPENMVG_CERR("The file " + fileFullPath + " is neither a JSON nor a txt file"); throw std::invalid_argument("Unrecognized extension for " + fileFullPath); } // get the extension of the file and put it lowercase std::string ext = bp.extension().string(); boost::to_lower(ext); // two cases, either the input file is a text file with the relative paths or // it is a JSON file from OpenMVG // in the two cases we fill a vector with paths to the descriptors files if(ext == ".txt") { // processing a file .txt containing the relative paths // Extract the folder path from the list file path pathToFiles = bfs::path(fileFullPath).parent_path(); // Open file fs.open(fileFullPath, std::ios::in); if(!fs.is_open()) { OPENMVG_CERR("Error while opening " << fileFullPath); throw std::invalid_argument("Error while opening " + fileFullPath); } // read the file line by line and store in the vector the descriptors paths std::string line; IndexT viewId = 0; while(getline(fs, line)) { // extract the filename without extension and create on with .desc as extension const std::string filename = bfs::path(line).stem().string() + ".desc"; const std::string filepath = (pathToFiles / filename).string(); // add the filepath in the vector descriptorsFiles[viewId++] = filepath; } } else { // processing a JSON file containing sfm_data // open the sfm_data file sfm::SfM_Data sfmdata; sfm::Load(sfmdata, fileFullPath, sfm::ESfM_Data::VIEWS); // get the number of files to load size_t numberOfFiles = sfmdata.GetViews().size(); if(numberOfFiles == 0) { OPENMVG_CERR("It seems like there are no views in " << fileFullPath); return; } // get the base path for the files pathToFiles = bfs::path(fileFullPath).parent_path(); // explore the sfm_data container to get the files path for(const auto &view : sfmdata.GetViews()) { // generate the equivalent .desc file path const std::string filepath = bfs::path(pathToFiles / (std::to_string(view.first) + ".desc")).string(); // add the filepath in the vector descriptorsFiles[view.first] = filepath; } } } } } <commit_msg>[voctree] quick fix for a bug introduced by the multi-descriptor support<commit_after>#include "descriptor_loader.hpp" #include <openMVG/sfm/sfm_data_io.hpp> #include <openMVG/logger.hpp> #include <boost/algorithm/string/predicate.hpp> namespace openMVG { namespace voctree { void getInfoBinFile(const std::string &path, int dim, size_t &numDescriptors, int &bytesPerElement) { std::fstream fs; // the file is supposed to have the number of descriptors as first element and then // the set of descriptors of dimension dim either as chars or floats // Open file and get the number of descriptors fs.open(path, std::ios::in | std::ios::binary); if(!fs.is_open()) { OPENMVG_CERR("Error while opening " << path); OPENMVG_CERR("Error while opening " + path); } // go to the end of the file fs.seekg(0, fs.end); // get the length in byte of the file //@fixeme we are ignoring the first element of the file which is the number of // feature. However given the large amount of data of the feature this is mitigate // by the integer division in bytepd later int length = fs.tellg(); // go back to the beginning of the file fs.seekg(0, fs.beg); // get the number of descriptors fs.read((char*) &numDescriptors, sizeof (size_t)); if(numDescriptors > 0) { // get the number of bytes per descriptor element bytesPerElement = (length / numDescriptors) / dim; } else { bytesPerElement = 0; } } void getListOfDescriptorFiles(const std::string &fileFullPath, std::map<IndexT, std::string> &descriptorsFiles) { namespace bfs = boost::filesystem; std::ifstream fs; bfs::path pathToFiles; descriptorsFiles.clear(); bfs::path bp(fileFullPath); // If the input is a directory, list all .desc files recursively. if(bfs::is_directory(bp)) { std::size_t viewId = 0; for(bfs::recursive_directory_iterator it(bp), end; it != end; ++it) { if(!bfs::is_directory(*it) && it->path().extension() == ".desc") { descriptorsFiles[viewId++] = it->path().string(); } } return; } if(!bp.has_extension()) { OPENMVG_CERR("File without extension not recognized! " << fileFullPath); OPENMVG_CERR("The file " + fileFullPath + " is neither a JSON nor a txt file"); throw std::invalid_argument("Unrecognized extension for " + fileFullPath); } // get the extension of the file and put it lowercase std::string ext = bp.extension().string(); boost::to_lower(ext); // two cases, either the input file is a text file with the relative paths or // it is a JSON file from OpenMVG // in the two cases we fill a vector with paths to the descriptors files if(ext == ".txt") { // processing a file .txt containing the relative paths // Extract the folder path from the list file path pathToFiles = bfs::path(fileFullPath).parent_path(); // Open file fs.open(fileFullPath, std::ios::in); if(!fs.is_open()) { OPENMVG_CERR("Error while opening " << fileFullPath); throw std::invalid_argument("Error while opening " + fileFullPath); } // read the file line by line and store in the vector the descriptors paths std::string line; IndexT viewId = 0; while(getline(fs, line)) { // extract the filename without extension and create on with .desc as extension const std::string filename = bfs::path(line).stem().string() + ".desc"; const std::string filepath = (pathToFiles / filename).string(); // add the filepath in the vector descriptorsFiles[viewId++] = filepath; } } else { // processing a JSON file containing sfm_data // open the sfm_data file sfm::SfM_Data sfmdata; sfm::Load(sfmdata, fileFullPath, sfm::ESfM_Data::VIEWS); // get the number of files to load size_t numberOfFiles = sfmdata.GetViews().size(); if(numberOfFiles == 0) { OPENMVG_CERR("It seems like there are no views in " << fileFullPath); return; } // get the base path for the files pathToFiles = bfs::path(fileFullPath).parent_path(); // explore the sfm_data container to get the files path for(const auto &view : sfmdata.GetViews()) { // generate the equivalent .desc file path const std::string filepath = bfs::path(pathToFiles / (std::to_string(view.first) + ".SIFT.desc")).string(); // add the filepath in the vector descriptorsFiles[view.first] = filepath; } } } } } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2010 G-Truc Creation (www.g-truc.net) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2006-11-13 // Updated : 2010-01-28 // Licence : This source is under MIT License // File : glm/setup.hpp /////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef glm_setup #define glm_setup /////////////////////////////////////////////////////////////////////////////////////////////////// // Version #define GLM_VERSION 90 #define GLM_VERSION_MAJOR 0 #define GLM_VERSION_MINOR 9 #define GLM_VERSION_PATCH 0 #define GLM_VERSION_REVISION 4 /////////////////////////////////////////////////////////////////////////////////////////////////// // Common values #define GLM_DISABLE 0x00000000 #define GLM_ENABLE 0x00000001 /////////////////////////////////////////////////////////////////////////////////////////////////// // Message #define GLM_MESSAGE_QUIET 0x00000000 #define GLM_MESSAGE_WARNING 0x00000001 #define GLM_MESSAGE_NOTIFICATION 0x00000002 #define GLM_MESSAGE_CORE 0x00000004 #define GLM_MESSAGE_EXTS 0x00000008 #define GLM_MESSAGE_SETUP 0x00000010 #define GLM_MESSAGE_ALL GLM_MESSAGE_WARNING | GLM_MESSAGE_NOTIFICATION | GLM_MESSAGE_CORE | GLM_MESSAGE_EXTS | GLM_MESSAGE_SETUP //! By default: // #define GLM_MESSAGE GLM_MESSAGE_QUIET /////////////////////////////////////////////////////////////////////////////////////////////////// // Precision #define GLM_PRECISION_NONE 0x00000000 #define GLM_PRECISION_LOWP_FLOAT 0x00000011 #define GLM_PRECISION_MEDIUMP_FLOAT 0x00000012 #define GLM_PRECISION_HIGHP_FLOAT 0x00000013 #define GLM_PRECISION_LOWP_INT 0x00001100 #define GLM_PRECISION_MEDIUMP_INT 0x00001200 #define GLM_PRECISION_HIGHP_INT 0x00001300 #define GLM_PRECISION_LOWP_UINT 0x00110000 #define GLM_PRECISION_MEDIUMP_UINT 0x00120000 #define GLM_PRECISION_HIGHP_UINT 0x00130000 /////////////////////////////////////////////////////////////////////////////////////////////////// // Compiler #define GLM_COMPILER_UNKNOWNED 0x00000000 // Visual C++ defines #define GLM_COMPILER_VC 0x01000000 #define GLM_COMPILER_VC2005 0x01000010 #define GLM_COMPILER_VC2008 0x01000020 #define GLM_COMPILER_VC2010 0x01000040 // GCC defines #define GLM_COMPILER_GCC 0x02000000 #define GLM_COMPILER_GCC32 0x02000040 #define GLM_COMPILER_GCC33 0x02000080 #define GLM_COMPILER_GCC34 0x02000100 #define GLM_COMPILER_GCC35 0x02000200 #define GLM_COMPILER_GCC40 0x02000400 #define GLM_COMPILER_GCC41 0x02000800 #define GLM_COMPILER_GCC42 0x02001000 #define GLM_COMPILER_GCC43 0x02002000 #define GLM_COMPILER_GCC44 0x02004000 #define GLM_COMPILER_GCC45 0x02008000 #define GLM_COMPILER_GCC46 0x02010000 #define GLM_COMPILER_GCC50 0x02020000 // Borland C++ defines. How to identify BC? #define GLM_COMPILER_BC 0x03000000 #define GLM_COMPILER_BCB4 0x03000400 #define GLM_COMPILER_BCB5 0x03000800 #define GLM_COMPILER_BCB6 0x03001000 //#define GLM_COMPILER_BCBX 0x03002000 // What's the version value? #define GLM_COMPILER_BCB2009 0x03004000 #define GLM_MODEL_32 0x00000010 #define GLM_MODEL_64 0x00000020 #ifndef GLM_COMPILER // CodeWarrior #define GLM_COMPILER_CODEWARRIOR 0x04000000 ///////////////// // Visual C++ // #ifdef _MSC_VER #if defined(_WIN64) #define GLM_MODEL GLM_MODEL_64 #else #define GLM_MODEL GLM_MODEL_32 #endif//_WIN64 #if _MSC_VER == 1400 #define GLM_COMPILER GLM_COMPILER_VC2005 #elif _MSC_VER == 1500 #define GLM_COMPILER GLM_COMPILER_VC2008 #elif _MSC_VER == 1600 #define GLM_COMPILER GLM_COMPILER_VC2010 #else//_MSC_VER #define GLM_COMPILER GLM_COMPILER_VC #endif//_MSC_VER ////////////////// // GCC defines // #elif defined(__GNUC__) #if(defined(__WORDSIZE) && (__WORDSIZE == 64)) || defined(__arch64__) #define GLM_MODEL GLM_MODEL_64 #else #define GLM_MODEL GLM_MODEL_32 #endif// #if (__GNUC__ == 3) && (__GNUC_MINOR__ == 2) #define GLM_COMPILER GLM_COMPILER_GCC32 #elif (__GNUC__ == 3) && (__GNUC_MINOR__ == 3) #define GLM_COMPILER GLM_COMPILER_GCC33 #elif (__GNUC__ == 3) && (__GNUC_MINOR__ == 4) #define GLM_COMPILER GLM_COMPILER_GCC34 #elif (__GNUC__ == 3) && (__GNUC_MINOR__ == 5) #define GLM_COMPILER GLM_COMPILER_GCC35 #elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 0) #define GLM_COMPILER GLM_COMPILER_GCC40 #elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 1) #define GLM_COMPILER GLM_COMPILER_GCC41 #elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 2) #define GLM_COMPILER GLM_COMPILER_GCC42 #elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 3) #define GLM_COMPILER GLM_COMPILER_GCC43 #elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 4) #define GLM_COMPILER GLM_COMPILER_GCC44 #elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 5) #define GLM_COMPILER GLM_COMPILER_GCC45 #elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 6) #define GLM_COMPILER GLM_COMPILER_GCC46 #elif (__GNUC__ == 5) && (__GNUC_MINOR__ == 0) #define GLM_COMPILER GLM_COMPILER_GCC50 #else #define GLM_COMPILER GLM_COMPILER_GCC #endif #elif defined(_BORLANDC_) #if defined(VER125) #define GLM_COMPILER GLM_COMPILER_BCB4 #elif defined(VER130) #define GLM_COMPILER GLM_COMPILER_BCB5 #elif defined(VER140) #define GLM_COMPILER GLM_COMPILER_BCB6 #elif defined(VER200) #define GLM_COMPILER GLM_COMPILER_BCB2009 #else #define GLM_COMPILER GLM_COMPILER_BC #endif #elif defined(__MWERKS__) #define GLM_COMPILER GLM_COMPILER_CODEWARRIOR #else #define GLM_COMPILER GLM_COMPILER_UNKNOWNED #endif//__GNUC__ #endif//GLM_COMPILER #ifndef GLM_COMPILER #error "GLM_COMPILER undefined, your compiler may not be supported by GLM. Add #define GLM_COMPILER 0 to ignore this message." #endif//GLM_COMPILER #if(!defined(GLM_MODEL) && GLM_COMPILER != 0) #error "GLM_MODEL undefined, your compiler may not be supported by GLM. Add #define GLM_MODEL 0 to ignore this message." #endif//GLM_MODEL #if(defined(GLM_MESSAGE) && (GLM_MESSAGE & (GLM_MESSAGE_SETUP | GLM_MESSAGE_NOTIFICATION))) # if(defined(GLM_COMPILER) && GLM_COMPILER & GLM_COMPILER_VC) # pragma message("GLM message: Compiled with Visual C++") # elif(defined(GLM_COMPILER) && GLM_COMPILER & GLM_COMPILER_GCC) # pragma message("GLM message: Compiled with GCC") # else # pragma message("GLM warning: Compiler not detected") # endif #endif//GLM_MESSAGE #if(defined(GLM_MESSAGE) && (GLM_MESSAGE & (GLM_MESSAGE_SETUP | GLM_MESSAGE_NOTIFICATION))) # if(GLM_MODEL == GLM_MODEL_64) # pragma message("GLM message: 64 bits model") # elif(GLM_MODEL == GLM_MODEL_32) # pragma message("GLM message: 32 bits model") # endif//GLM_MODEL #endif//GLM_MESSAGE /////////////////////////////////////////////////////////////////////////////////////////////////// // Swizzle operators #define GLM_SWIZZLE_NONE 0x00000000 #define GLM_SWIZZLE_XYZW 0x00000002 #define GLM_SWIZZLE_RGBA 0x00000004 #define GLM_SWIZZLE_STQP 0x00000008 #define GLM_SWIZZLE_FULL (GLM_SWIZZLE_XYZW | GLM_SWIZZLE_RGBA | GLM_SWIZZLE_STQP) //! By default: // #define GLM_SWIZZLE GLM_SWIZZLE_NONE #if(defined(GLM_MESSAGE) && (GLM_MESSAGE & (GLM_MESSAGE_SETUP | GLM_MESSAGE_NOTIFICATION))) # if !defined(GLM_SWIZZLE)|| (defined(GLM_SWIZZLE) && GLM_SWIZZLE == GLM_SWIZZLE_NONE) # pragma message("GLM message: No swizzling operator used") # elif(defined(GLM_SWIZZLE) && GLM_SWIZZLE == GLM_SWIZZLE_FULL) # pragma message("GLM message: Full swizzling operator support enabled") # elif(defined(GLM_SWIZZLE) && GLM_SWIZZLE & GLM_SWIZZLE_FULL) # pragma message("GLM message: Partial swizzling operator support enabled") # endif//GLM_SWIZZLE #endif//GLM_MESSAGE /////////////////////////////////////////////////////////////////////////////////////////////////// // Use options // To disable multiple vector component names access. // GLM_USE_ONLY_XYZW // To use anonymous union to provide multiple component names access for class valType. Visual C++ only. // GLM_USE_ANONYMOUS_UNION #if(defined(GLM_USE_ANONYMOUS_UNION) && !(GLM_COMPILER & GLM_COMPILER_VC)) #error "GLM_USE_ANONYMOUS_UNION is defined to use anonymous union implementation of vector types. Anonymous unions can't be used with GCC." #endif//GLM_USE_ANONYMOUS_UNION /////////////////////////////////////////////////////////////////////////////////////////////////// // Static assert #if(GLM_COMPILER >= GLM_COMPILER_VC2010 || GLM_COMPILER >= GLM_COMPILER_GCC45) #define GLM_STATIC_ASSERT(x, message) static_assert(x, message) #elif(defined(BOOST_STATIC_ASSERT)) #define GLM_STATIC_ASSERT(x, message) BOOST_STATIC_ASSERT(x) #else #define GLM_STATIC_ASSERT(x, message) typedef char __CASSERT__##__LINE__[(x) ? 1 : -1] #endif//GLM_DEPENDENCE /////////////////////////////////////////////////////////////////////////////////////////////////// #endif//glm_setup <commit_msg>Fixed static_assert on GCC<commit_after>/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2010 G-Truc Creation (www.g-truc.net) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2006-11-13 // Updated : 2010-01-28 // Licence : This source is under MIT License // File : glm/setup.hpp /////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef glm_setup #define glm_setup /////////////////////////////////////////////////////////////////////////////////////////////////// // Version #define GLM_VERSION 90 #define GLM_VERSION_MAJOR 0 #define GLM_VERSION_MINOR 9 #define GLM_VERSION_PATCH 0 #define GLM_VERSION_REVISION 4 /////////////////////////////////////////////////////////////////////////////////////////////////// // Common values #define GLM_DISABLE 0x00000000 #define GLM_ENABLE 0x00000001 /////////////////////////////////////////////////////////////////////////////////////////////////// // Message #define GLM_MESSAGE_QUIET 0x00000000 #define GLM_MESSAGE_WARNING 0x00000001 #define GLM_MESSAGE_NOTIFICATION 0x00000002 #define GLM_MESSAGE_CORE 0x00000004 #define GLM_MESSAGE_EXTS 0x00000008 #define GLM_MESSAGE_SETUP 0x00000010 #define GLM_MESSAGE_ALL GLM_MESSAGE_WARNING | GLM_MESSAGE_NOTIFICATION | GLM_MESSAGE_CORE | GLM_MESSAGE_EXTS | GLM_MESSAGE_SETUP //! By default: // #define GLM_MESSAGE GLM_MESSAGE_QUIET /////////////////////////////////////////////////////////////////////////////////////////////////// // Precision #define GLM_PRECISION_NONE 0x00000000 #define GLM_PRECISION_LOWP_FLOAT 0x00000011 #define GLM_PRECISION_MEDIUMP_FLOAT 0x00000012 #define GLM_PRECISION_HIGHP_FLOAT 0x00000013 #define GLM_PRECISION_LOWP_INT 0x00001100 #define GLM_PRECISION_MEDIUMP_INT 0x00001200 #define GLM_PRECISION_HIGHP_INT 0x00001300 #define GLM_PRECISION_LOWP_UINT 0x00110000 #define GLM_PRECISION_MEDIUMP_UINT 0x00120000 #define GLM_PRECISION_HIGHP_UINT 0x00130000 /////////////////////////////////////////////////////////////////////////////////////////////////// // Compiler #define GLM_COMPILER_UNKNOWNED 0x00000000 // Visual C++ defines #define GLM_COMPILER_VC 0x01000000 #define GLM_COMPILER_VC2005 0x01000010 #define GLM_COMPILER_VC2008 0x01000020 #define GLM_COMPILER_VC2010 0x01000040 // GCC defines #define GLM_COMPILER_GCC 0x02000000 #define GLM_COMPILER_GCC32 0x02000040 #define GLM_COMPILER_GCC33 0x02000080 #define GLM_COMPILER_GCC34 0x02000100 #define GLM_COMPILER_GCC35 0x02000200 #define GLM_COMPILER_GCC40 0x02000400 #define GLM_COMPILER_GCC41 0x02000800 #define GLM_COMPILER_GCC42 0x02001000 #define GLM_COMPILER_GCC43 0x02002000 #define GLM_COMPILER_GCC44 0x02004000 #define GLM_COMPILER_GCC45 0x02008000 #define GLM_COMPILER_GCC46 0x02010000 #define GLM_COMPILER_GCC50 0x02020000 // Borland C++ defines. How to identify BC? #define GLM_COMPILER_BC 0x03000000 #define GLM_COMPILER_BCB4 0x03000400 #define GLM_COMPILER_BCB5 0x03000800 #define GLM_COMPILER_BCB6 0x03001000 //#define GLM_COMPILER_BCBX 0x03002000 // What's the version value? #define GLM_COMPILER_BCB2009 0x03004000 #define GLM_MODEL_32 0x00000010 #define GLM_MODEL_64 0x00000020 #ifndef GLM_COMPILER // CodeWarrior #define GLM_COMPILER_CODEWARRIOR 0x04000000 ///////////////// // Visual C++ // #ifdef _MSC_VER #if defined(_WIN64) #define GLM_MODEL GLM_MODEL_64 #else #define GLM_MODEL GLM_MODEL_32 #endif//_WIN64 #if _MSC_VER == 1400 #define GLM_COMPILER GLM_COMPILER_VC2005 #elif _MSC_VER == 1500 #define GLM_COMPILER GLM_COMPILER_VC2008 #elif _MSC_VER == 1600 #define GLM_COMPILER GLM_COMPILER_VC2010 #else//_MSC_VER #define GLM_COMPILER GLM_COMPILER_VC #endif//_MSC_VER ////////////////// // GCC defines // #elif defined(__GNUC__) #if(defined(__WORDSIZE) && (__WORDSIZE == 64)) || defined(__arch64__) #define GLM_MODEL GLM_MODEL_64 #else #define GLM_MODEL GLM_MODEL_32 #endif// #if (__GNUC__ == 3) && (__GNUC_MINOR__ == 2) #define GLM_COMPILER GLM_COMPILER_GCC32 #elif (__GNUC__ == 3) && (__GNUC_MINOR__ == 3) #define GLM_COMPILER GLM_COMPILER_GCC33 #elif (__GNUC__ == 3) && (__GNUC_MINOR__ == 4) #define GLM_COMPILER GLM_COMPILER_GCC34 #elif (__GNUC__ == 3) && (__GNUC_MINOR__ == 5) #define GLM_COMPILER GLM_COMPILER_GCC35 #elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 0) #define GLM_COMPILER GLM_COMPILER_GCC40 #elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 1) #define GLM_COMPILER GLM_COMPILER_GCC41 #elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 2) #define GLM_COMPILER GLM_COMPILER_GCC42 #elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 3) #define GLM_COMPILER GLM_COMPILER_GCC43 #elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 4) #define GLM_COMPILER GLM_COMPILER_GCC44 #elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 5) #define GLM_COMPILER GLM_COMPILER_GCC45 #elif (__GNUC__ == 4) && (__GNUC_MINOR__ == 6) #define GLM_COMPILER GLM_COMPILER_GCC46 #elif (__GNUC__ == 5) && (__GNUC_MINOR__ == 0) #define GLM_COMPILER GLM_COMPILER_GCC50 #else #define GLM_COMPILER GLM_COMPILER_GCC #endif #elif defined(_BORLANDC_) #if defined(VER125) #define GLM_COMPILER GLM_COMPILER_BCB4 #elif defined(VER130) #define GLM_COMPILER GLM_COMPILER_BCB5 #elif defined(VER140) #define GLM_COMPILER GLM_COMPILER_BCB6 #elif defined(VER200) #define GLM_COMPILER GLM_COMPILER_BCB2009 #else #define GLM_COMPILER GLM_COMPILER_BC #endif #elif defined(__MWERKS__) #define GLM_COMPILER GLM_COMPILER_CODEWARRIOR #else #define GLM_COMPILER GLM_COMPILER_UNKNOWNED #endif//__GNUC__ #endif//GLM_COMPILER #ifndef GLM_COMPILER #error "GLM_COMPILER undefined, your compiler may not be supported by GLM. Add #define GLM_COMPILER 0 to ignore this message." #endif//GLM_COMPILER #if(!defined(GLM_MODEL) && GLM_COMPILER != 0) #error "GLM_MODEL undefined, your compiler may not be supported by GLM. Add #define GLM_MODEL 0 to ignore this message." #endif//GLM_MODEL #if(defined(GLM_MESSAGE) && (GLM_MESSAGE & (GLM_MESSAGE_SETUP | GLM_MESSAGE_NOTIFICATION))) # if(defined(GLM_COMPILER) && GLM_COMPILER & GLM_COMPILER_VC) # pragma message("GLM message: Compiled with Visual C++") # elif(defined(GLM_COMPILER) && GLM_COMPILER & GLM_COMPILER_GCC) # pragma message("GLM message: Compiled with GCC") # else # pragma message("GLM warning: Compiler not detected") # endif #endif//GLM_MESSAGE #if(defined(GLM_MESSAGE) && (GLM_MESSAGE & (GLM_MESSAGE_SETUP | GLM_MESSAGE_NOTIFICATION))) # if(GLM_MODEL == GLM_MODEL_64) # pragma message("GLM message: 64 bits model") # elif(GLM_MODEL == GLM_MODEL_32) # pragma message("GLM message: 32 bits model") # endif//GLM_MODEL #endif//GLM_MESSAGE /////////////////////////////////////////////////////////////////////////////////////////////////// // Swizzle operators #define GLM_SWIZZLE_NONE 0x00000000 #define GLM_SWIZZLE_XYZW 0x00000002 #define GLM_SWIZZLE_RGBA 0x00000004 #define GLM_SWIZZLE_STQP 0x00000008 #define GLM_SWIZZLE_FULL (GLM_SWIZZLE_XYZW | GLM_SWIZZLE_RGBA | GLM_SWIZZLE_STQP) //! By default: // #define GLM_SWIZZLE GLM_SWIZZLE_NONE #if(defined(GLM_MESSAGE) && (GLM_MESSAGE & (GLM_MESSAGE_SETUP | GLM_MESSAGE_NOTIFICATION))) # if !defined(GLM_SWIZZLE)|| (defined(GLM_SWIZZLE) && GLM_SWIZZLE == GLM_SWIZZLE_NONE) # pragma message("GLM message: No swizzling operator used") # elif(defined(GLM_SWIZZLE) && GLM_SWIZZLE == GLM_SWIZZLE_FULL) # pragma message("GLM message: Full swizzling operator support enabled") # elif(defined(GLM_SWIZZLE) && GLM_SWIZZLE & GLM_SWIZZLE_FULL) # pragma message("GLM message: Partial swizzling operator support enabled") # endif//GLM_SWIZZLE #endif//GLM_MESSAGE /////////////////////////////////////////////////////////////////////////////////////////////////// // Use options // To disable multiple vector component names access. // GLM_USE_ONLY_XYZW // To use anonymous union to provide multiple component names access for class valType. Visual C++ only. // GLM_USE_ANONYMOUS_UNION #if(defined(GLM_USE_ANONYMOUS_UNION) && !(GLM_COMPILER & GLM_COMPILER_VC)) #error "GLM_USE_ANONYMOUS_UNION is defined to use anonymous union implementation of vector types. Anonymous unions can't be used with GCC." #endif//GLM_USE_ANONYMOUS_UNION /////////////////////////////////////////////////////////////////////////////////////////////////// // Static assert #if((GLM_COMPILER & GLM_COMPILER_VC && GLM_COMPILER >= GLM_COMPILER_VC2010) || (GLM_COMPILER & GLM_COMPILER_GCC && GLM_COMPILER >= GLM_COMPILER_GCC45)) #define GLM_STATIC_ASSERT(x, message) static_assert(x, message) #elif(defined(BOOST_STATIC_ASSERT)) #define GLM_STATIC_ASSERT(x, message) BOOST_STATIC_ASSERT(x) #else #define GLM_STATIC_ASSERT(x, message) typedef char __CASSERT__##__LINE__[(x) ? 1 : -1] #endif//GLM_DEPENDENCE /////////////////////////////////////////////////////////////////////////////////////////////////// #endif//glm_setup <|endoftext|>
<commit_before>#include <iostream> int main(){ double sum{0.0}; for(int i = 50; i <= 100; ++i){ sum += i; } std::cout << "Result: " << sum << std::endl; return 0; }<commit_msg>Added file ex1_13.cpp<commit_after>#include <iostream> void exercise09() // Exercise 1_09 using for statement { double sum{0.0}; for(int i = 50; i <= 100; ++i){ sum += i; } std::cout << "Result: " << sum << std::endl; } void exercise10() // Exercise 1_10 using for statement { for(int i = 10; i >= 0; --i){ std::cout << i << std::endl; } } void print_range(int low, int high) // Function used in exercise11 { for(int i = low; i <= high; ++i){ std::cout << i << std::endl; } } void exercise11() // Exercise 1_11 using for statement { int num1{0}, num2{0}; std::cout << "Enter two numbers: " << std::endl; std::cin >> num1 >> num2; if(num1 > num2){ print_range(num2, num1); } else if(num2 > num1) { print_range(num1,num2); } else { std::cout << "This numbers are equals." << std::endl; } } int main(){ std::cout << "Exercise 1_09: " << std::endl; exercise09(); std::cout << "Exercise 1_10: " << std::endl; exercise10(); std::cout << "Exercise 1_11: " << std::endl; exercise11(); return 0; }<|endoftext|>
<commit_before>/* $Id$ */ /* * $Log$ * Revision 1.1 2001/06/26 15:19:39 curt * Added tr.cxx / tr.h, Brian Paul's LGPL'd tiled rendering support libs for * rendering ultra high res "tiled" screen shots. * * Revision 1.9 1998/01/29 16:56:54 brianp * allow trOrtho() and trFrustum() to be called at any time, minor clean-up * * Revision 1.8 1998/01/28 19:47:39 brianp * minor clean-up for C++ * * Revision 1.7 1997/07/21 17:34:38 brianp * added tile borders * * Revision 1.6 1997/07/21 15:47:35 brianp * renamed all "near" and "far" variables * * Revision 1.5 1997/04/26 21:23:25 brianp * added trRasterPos3f function * * Revision 1.4 1997/04/26 19:59:36 brianp * set CurrentTile to -1 before first tile and after last tile * * Revision 1.3 1997/04/22 23:51:15 brianp * added WIN32 header stuff, removed tabs * * Revision 1.2 1997/04/19 23:26:10 brianp * many API changes * * Revision 1.1 1997/04/18 21:53:05 brianp * Initial revision * */ /* * Tiled Rendering library * Version 1.1 * Copyright (C) Brian Paul */ #include <assert.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #ifdef WIN32 #include <windows.h> #endif #include <GL/gl.h> #include <GL/glu.h> #include <plib/ssg.h> #include "tr.h" #define DEFAULT_TILE_WIDTH 256 #define DEFAULT_TILE_HEIGHT 256 #define DEFAULT_TILE_BORDER 0 struct _TRctx { /* Final image parameters */ GLint ImageWidth, ImageHeight; GLenum ImageFormat, ImageType; GLvoid *ImageBuffer; /* Tile parameters */ GLint TileWidth, TileHeight; GLint TileWidthNB, TileHeightNB; GLint TileBorder; GLenum TileFormat, TileType; GLvoid *TileBuffer; /* Projection parameters */ GLboolean Perspective; GLdouble Left; GLdouble Right; GLdouble Bottom; GLdouble Top; GLdouble Near; GLdouble Far; /* Misc */ TRenum RowOrder; GLint Rows, Columns; GLint CurrentTile; GLint CurrentTileWidth, CurrentTileHeight; GLint CurrentRow, CurrentColumn; GLint ViewportSave[4]; }; /* * Misc setup including computing number of tiles (rows and columns). */ static void Setup(TRcontext *tr) { if (!tr) return; tr->Columns = (tr->ImageWidth + tr->TileWidthNB - 1) / tr->TileWidthNB; tr->Rows = (tr->ImageHeight + tr->TileHeightNB - 1) / tr->TileHeightNB; tr->CurrentTile = 0; assert(tr->Columns >= 0); assert(tr->Rows >= 0); } TRcontext *trNew(void) { TRcontext *tr = (TRcontext *) calloc(1, sizeof(TRcontext)); if (tr) { tr->TileWidth = DEFAULT_TILE_WIDTH; tr->TileHeight = DEFAULT_TILE_HEIGHT; tr->TileBorder = DEFAULT_TILE_BORDER; tr->RowOrder = TR_BOTTOM_TO_TOP; tr->CurrentTile = -1; } return (TRcontext *) tr; } void trDelete(TRcontext *tr) { if (tr) free(tr); } void trTileSize(TRcontext *tr, GLint width, GLint height, GLint border) { if (!tr) return; assert(border >= 0); assert(width >= 1); assert(height >= 1); assert(width >= 2*border); assert(height >= 2*border); tr->TileBorder = border; tr->TileWidth = width; tr->TileHeight = height; tr->TileWidthNB = width - 2 * border; tr->TileHeightNB = height - 2 * border; Setup(tr); } void trTileBuffer(TRcontext *tr, GLenum format, GLenum type, GLvoid *image) { if (!tr) return; tr->TileFormat = format; tr->TileType = type; tr->TileBuffer = image; } void trImageSize(TRcontext *tr, GLint width, GLint height) { if (!tr) return; tr->ImageWidth = width; tr->ImageHeight = height; Setup(tr); } void trImageBuffer(TRcontext *tr, GLenum format, GLenum type, GLvoid *image) { if (!tr) return; tr->ImageFormat = format; tr->ImageType = type; tr->ImageBuffer = image; } GLint trGet(TRcontext *tr, TRenum param) { if (!tr) return 0; switch (param) { case TR_TILE_WIDTH: return tr->TileWidth; case TR_TILE_HEIGHT: return tr->TileHeight; case TR_TILE_BORDER: return tr->TileBorder; case TR_IMAGE_WIDTH: return tr->ImageWidth; case TR_IMAGE_HEIGHT: return tr->ImageHeight; case TR_ROWS: return tr->Rows; case TR_COLUMNS: return tr->Columns; case TR_CURRENT_ROW: if (tr->CurrentTile<0) return -1; else return tr->CurrentRow; case TR_CURRENT_COLUMN: if (tr->CurrentTile<0) return -1; else return tr->CurrentColumn; case TR_CURRENT_TILE_WIDTH: return tr->CurrentTileWidth; case TR_CURRENT_TILE_HEIGHT: return tr->CurrentTileHeight; case TR_ROW_ORDER: return (GLint) tr->RowOrder; default: return 0; } } GLdouble trGetD(TRcontext *tr, TRenum param) { if (!tr) return 0.0; switch (param) { case TR_LEFT: return tr->Left; case TR_RIGHT: return tr->Right; case TR_BOTTOM: return tr->Bottom; case TR_TOP: return tr->Top; case TR_NEAR: return tr->Near; case TR_FAR: return tr->Far; default: return 0.0; } } void trRowOrder(TRcontext *tr, TRenum order) { if (!tr) return; if (order==TR_TOP_TO_BOTTOM || order==TR_BOTTOM_TO_TOP) tr->RowOrder = order; } void trOrtho(TRcontext *tr, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar) { if (!tr) return; tr->Perspective = GL_FALSE; tr->Left = left; tr->Right = right; tr->Bottom = bottom; tr->Top = top; tr->Near = zNear; tr->Far = zFar; } void trFrustum(TRcontext *tr, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar) { if (!tr) return; tr->Perspective = GL_TRUE; tr->Left = left; tr->Right = right; tr->Bottom = bottom; tr->Top = top; tr->Near = zNear; tr->Far = zFar; } void trPerspective(TRcontext *tr, GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar ) { GLdouble xmin, xmax, ymin, ymax; ymax = zNear * tan(fovy * 3.14159265 / 360.0); ymin = -ymax; xmin = ymin * aspect; xmax = ymax * aspect; trFrustum(tr, xmin, xmax, ymin, ymax, zNear, zFar); } void trBeginTile(TRcontext *tr) { GLint matrixMode; GLint tileWidth, tileHeight, border; GLdouble left, right, bottom, top; if (!tr) return; if (tr->CurrentTile <= 0) { Setup(tr); /* Save user's viewport, will be restored after last tile rendered */ glGetIntegerv(GL_VIEWPORT, tr->ViewportSave); } /* which tile (by row and column) we're about to render */ if (tr->RowOrder==TR_BOTTOM_TO_TOP) { tr->CurrentRow = tr->CurrentTile / tr->Columns; tr->CurrentColumn = tr->CurrentTile % tr->Columns; } else if (tr->RowOrder==TR_TOP_TO_BOTTOM) { tr->CurrentRow = tr->Rows - (tr->CurrentTile / tr->Columns) - 1; tr->CurrentColumn = tr->CurrentTile % tr->Columns; } else { /* This should never happen */ abort(); } assert(tr->CurrentRow < tr->Rows); assert(tr->CurrentColumn < tr->Columns); border = tr->TileBorder; /* Compute actual size of this tile with border */ if (tr->CurrentRow < tr->Rows-1) tileHeight = tr->TileHeight; else tileHeight = tr->ImageHeight - (tr->Rows-1) * (tr->TileHeightNB) + 2 * border; if (tr->CurrentColumn < tr->Columns-1) tileWidth = tr->TileWidth; else tileWidth = tr->ImageWidth - (tr->Columns-1) * (tr->TileWidthNB) + 2 * border; /* Save tile size, with border */ tr->CurrentTileWidth = tileWidth; tr->CurrentTileHeight = tileHeight; glViewport(0, 0, tileWidth, tileHeight); /* tile size including border */ /* save current matrix mode */ glGetIntegerv(GL_MATRIX_MODE, &matrixMode); glMatrixMode(GL_PROJECTION); glLoadIdentity(); /* compute projection parameters */ left = tr->Left + (tr->Right - tr->Left) * (tr->CurrentColumn * tr->TileWidthNB - border) / tr->ImageWidth; right = left + (tr->Right - tr->Left) * tileWidth / tr->ImageWidth; bottom = tr->Bottom + (tr->Top - tr->Bottom) * (tr->CurrentRow * tr->TileHeightNB - border) / tr->ImageHeight; top = bottom + (tr->Top - tr->Bottom) * tileHeight / tr->ImageHeight; ssgSetFrustum ( left, right, bottom, top, tr->Near, tr->Far ); /* restore user's matrix mode */ glMatrixMode(matrixMode); } int trEndTile(TRcontext *tr) { GLint prevRowLength, prevSkipRows, prevSkipPixels /*, prevAlignment */; if (!tr) return 0; assert(tr->CurrentTile>=0); /* be sure OpenGL rendering is finished */ glFlush(); /* save current glPixelStore values */ glGetIntegerv(GL_PACK_ROW_LENGTH, &prevRowLength); glGetIntegerv(GL_PACK_SKIP_ROWS, &prevSkipRows); glGetIntegerv(GL_PACK_SKIP_PIXELS, &prevSkipPixels); /*glGetIntegerv(GL_PACK_ALIGNMENT, &prevAlignment);*/ if (tr->TileBuffer) { GLint srcX = tr->TileBorder; GLint srcY = tr->TileBorder; GLint srcWidth = tr->TileWidthNB; GLint srcHeight = tr->TileHeightNB; glReadPixels(srcX, srcY, srcWidth, srcHeight, tr->TileFormat, tr->TileType, tr->TileBuffer); } if (tr->ImageBuffer) { GLint srcX = tr->TileBorder; GLint srcY = tr->TileBorder; GLint srcWidth = tr->CurrentTileWidth - 2 * tr->TileBorder; GLint srcHeight = tr->CurrentTileHeight - 2 * tr->TileBorder; GLint destX = tr->TileWidthNB * tr->CurrentColumn; GLint destY = tr->TileHeightNB * tr->CurrentRow; /* setup pixel store for glReadPixels */ glPixelStorei(GL_PACK_ROW_LENGTH, tr->ImageWidth); glPixelStorei(GL_PACK_SKIP_ROWS, destY); glPixelStorei(GL_PACK_SKIP_PIXELS, destX); /*glPixelStorei(GL_PACK_ALIGNMENT, 1);*/ /* read the tile into the final image */ glReadPixels(srcX, srcY, srcWidth, srcHeight, tr->ImageFormat, tr->ImageType, tr->ImageBuffer); } /* restore previous glPixelStore values */ glPixelStorei(GL_PACK_ROW_LENGTH, prevRowLength); glPixelStorei(GL_PACK_SKIP_ROWS, prevSkipRows); glPixelStorei(GL_PACK_SKIP_PIXELS, prevSkipPixels); /*glPixelStorei(GL_PACK_ALIGNMENT, prevAlignment);*/ /* increment tile counter, return 1 if more tiles left to render */ tr->CurrentTile++; if (tr->CurrentTile >= tr->Rows * tr->Columns) { /* restore user's viewport */ glViewport(tr->ViewportSave[0], tr->ViewportSave[1], tr->ViewportSave[2], tr->ViewportSave[3]); tr->CurrentTile = -1; /* all done */ return 0; } else return 1; } /* * Replacement for glRastePos3f() which avoids the problem with invalid * raster pos. */ void trRasterPos3f(TRcontext *tr, GLfloat x, GLfloat y, GLfloat z) { if (tr->CurrentTile<0) { /* not doing tile rendering right now. Let OpenGL do this. */ glRasterPos3f(x, y, z); } else { GLdouble modelview[16], proj[16]; GLint viewport[4]; GLdouble winX, winY, winZ; /* Get modelview, projection and viewport */ glGetDoublev(GL_MODELVIEW_MATRIX, modelview); glGetDoublev(GL_PROJECTION_MATRIX, proj); viewport[0] = 0; viewport[1] = 0; viewport[2] = tr->CurrentTileWidth; viewport[3] = tr->CurrentTileHeight; /* Project object coord to window coordinate */ if (gluProject(x, y, z, modelview, proj, viewport, &winX, &winY, &winZ)){ /* set raster pos to window coord (0,0) */ glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0.0, tr->CurrentTileWidth, 0.0, tr->CurrentTileHeight, 0.0, 1.0); glRasterPos3f(0.0, 0.0, -winZ); /* Now use empty bitmap to adjust raster position to (winX,winY) */ { GLubyte bitmap[1] = {0}; glBitmap(1, 1, 0.0, 0.0, winX, winY, bitmap); } /* restore original matrices */ glPopMatrix(); /*proj*/ glMatrixMode(GL_MODELVIEW); glPopMatrix(); } #ifdef DEBUG if (glGetError()) printf("GL error!\n"); #endif } } <commit_msg>Fixed a type conversion bug that could trip up some of the pickier compilers out there.<commit_after>/* $Id$ */ /* * $Log$ * Revision 1.2 2001/06/27 02:48:01 curt * Fixed a type conversion bug that could trip up some of the pickier compilers * out there. * * Revision 1.1 2001/06/26 15:19:39 curt * Added tr.cxx / tr.h, Brian Paul's LGPL'd tiled rendering support libs for * rendering ultra high res "tiled" screen shots. * * Revision 1.9 1998/01/29 16:56:54 brianp * allow trOrtho() and trFrustum() to be called at any time, minor clean-up * * Revision 1.8 1998/01/28 19:47:39 brianp * minor clean-up for C++ * * Revision 1.7 1997/07/21 17:34:38 brianp * added tile borders * * Revision 1.6 1997/07/21 15:47:35 brianp * renamed all "near" and "far" variables * * Revision 1.5 1997/04/26 21:23:25 brianp * added trRasterPos3f function * * Revision 1.4 1997/04/26 19:59:36 brianp * set CurrentTile to -1 before first tile and after last tile * * Revision 1.3 1997/04/22 23:51:15 brianp * added WIN32 header stuff, removed tabs * * Revision 1.2 1997/04/19 23:26:10 brianp * many API changes * * Revision 1.1 1997/04/18 21:53:05 brianp * Initial revision * */ /* * Tiled Rendering library * Version 1.1 * Copyright (C) Brian Paul */ #include <assert.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #ifdef WIN32 #include <windows.h> #endif #include <GL/gl.h> #include <GL/glu.h> #include <plib/ssg.h> #include "tr.h" #define DEFAULT_TILE_WIDTH 256 #define DEFAULT_TILE_HEIGHT 256 #define DEFAULT_TILE_BORDER 0 struct _TRctx { /* Final image parameters */ GLint ImageWidth, ImageHeight; GLenum ImageFormat, ImageType; GLvoid *ImageBuffer; /* Tile parameters */ GLint TileWidth, TileHeight; GLint TileWidthNB, TileHeightNB; GLint TileBorder; GLenum TileFormat, TileType; GLvoid *TileBuffer; /* Projection parameters */ GLboolean Perspective; GLdouble Left; GLdouble Right; GLdouble Bottom; GLdouble Top; GLdouble Near; GLdouble Far; /* Misc */ TRenum RowOrder; GLint Rows, Columns; GLint CurrentTile; GLint CurrentTileWidth, CurrentTileHeight; GLint CurrentRow, CurrentColumn; GLint ViewportSave[4]; }; /* * Misc setup including computing number of tiles (rows and columns). */ static void Setup(TRcontext *tr) { if (!tr) return; tr->Columns = (tr->ImageWidth + tr->TileWidthNB - 1) / tr->TileWidthNB; tr->Rows = (tr->ImageHeight + tr->TileHeightNB - 1) / tr->TileHeightNB; tr->CurrentTile = 0; assert(tr->Columns >= 0); assert(tr->Rows >= 0); } TRcontext *trNew(void) { TRcontext *tr = (TRcontext *) calloc(1, sizeof(TRcontext)); if (tr) { tr->TileWidth = DEFAULT_TILE_WIDTH; tr->TileHeight = DEFAULT_TILE_HEIGHT; tr->TileBorder = DEFAULT_TILE_BORDER; tr->RowOrder = TR_BOTTOM_TO_TOP; tr->CurrentTile = -1; } return (TRcontext *) tr; } void trDelete(TRcontext *tr) { if (tr) free(tr); } void trTileSize(TRcontext *tr, GLint width, GLint height, GLint border) { if (!tr) return; assert(border >= 0); assert(width >= 1); assert(height >= 1); assert(width >= 2*border); assert(height >= 2*border); tr->TileBorder = border; tr->TileWidth = width; tr->TileHeight = height; tr->TileWidthNB = width - 2 * border; tr->TileHeightNB = height - 2 * border; Setup(tr); } void trTileBuffer(TRcontext *tr, GLenum format, GLenum type, GLvoid *image) { if (!tr) return; tr->TileFormat = format; tr->TileType = type; tr->TileBuffer = image; } void trImageSize(TRcontext *tr, GLint width, GLint height) { if (!tr) return; tr->ImageWidth = width; tr->ImageHeight = height; Setup(tr); } void trImageBuffer(TRcontext *tr, GLenum format, GLenum type, GLvoid *image) { if (!tr) return; tr->ImageFormat = format; tr->ImageType = type; tr->ImageBuffer = image; } GLint trGet(TRcontext *tr, TRenum param) { if (!tr) return 0; switch (param) { case TR_TILE_WIDTH: return tr->TileWidth; case TR_TILE_HEIGHT: return tr->TileHeight; case TR_TILE_BORDER: return tr->TileBorder; case TR_IMAGE_WIDTH: return tr->ImageWidth; case TR_IMAGE_HEIGHT: return tr->ImageHeight; case TR_ROWS: return tr->Rows; case TR_COLUMNS: return tr->Columns; case TR_CURRENT_ROW: if (tr->CurrentTile<0) return -1; else return tr->CurrentRow; case TR_CURRENT_COLUMN: if (tr->CurrentTile<0) return -1; else return tr->CurrentColumn; case TR_CURRENT_TILE_WIDTH: return tr->CurrentTileWidth; case TR_CURRENT_TILE_HEIGHT: return tr->CurrentTileHeight; case TR_ROW_ORDER: return (GLint) tr->RowOrder; default: return 0; } } GLdouble trGetD(TRcontext *tr, TRenum param) { if (!tr) return 0.0; switch (param) { case TR_LEFT: return tr->Left; case TR_RIGHT: return tr->Right; case TR_BOTTOM: return tr->Bottom; case TR_TOP: return tr->Top; case TR_NEAR: return tr->Near; case TR_FAR: return tr->Far; default: return 0.0; } } void trRowOrder(TRcontext *tr, TRenum order) { if (!tr) return; if (order==TR_TOP_TO_BOTTOM || order==TR_BOTTOM_TO_TOP) tr->RowOrder = order; } void trOrtho(TRcontext *tr, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar) { if (!tr) return; tr->Perspective = GL_FALSE; tr->Left = left; tr->Right = right; tr->Bottom = bottom; tr->Top = top; tr->Near = zNear; tr->Far = zFar; } void trFrustum(TRcontext *tr, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar) { if (!tr) return; tr->Perspective = GL_TRUE; tr->Left = left; tr->Right = right; tr->Bottom = bottom; tr->Top = top; tr->Near = zNear; tr->Far = zFar; } void trPerspective(TRcontext *tr, GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar ) { GLdouble xmin, xmax, ymin, ymax; ymax = zNear * tan(fovy * 3.14159265 / 360.0); ymin = -ymax; xmin = ymin * aspect; xmax = ymax * aspect; trFrustum(tr, xmin, xmax, ymin, ymax, zNear, zFar); } void trBeginTile(TRcontext *tr) { GLint matrixMode; GLint tileWidth, tileHeight, border; GLdouble left, right, bottom, top; if (!tr) return; if (tr->CurrentTile <= 0) { Setup(tr); /* Save user's viewport, will be restored after last tile rendered */ glGetIntegerv(GL_VIEWPORT, tr->ViewportSave); } /* which tile (by row and column) we're about to render */ if (tr->RowOrder==TR_BOTTOM_TO_TOP) { tr->CurrentRow = tr->CurrentTile / tr->Columns; tr->CurrentColumn = tr->CurrentTile % tr->Columns; } else if (tr->RowOrder==TR_TOP_TO_BOTTOM) { tr->CurrentRow = tr->Rows - (tr->CurrentTile / tr->Columns) - 1; tr->CurrentColumn = tr->CurrentTile % tr->Columns; } else { /* This should never happen */ abort(); } assert(tr->CurrentRow < tr->Rows); assert(tr->CurrentColumn < tr->Columns); border = tr->TileBorder; /* Compute actual size of this tile with border */ if (tr->CurrentRow < tr->Rows-1) tileHeight = tr->TileHeight; else tileHeight = tr->ImageHeight - (tr->Rows-1) * (tr->TileHeightNB) + 2 * border; if (tr->CurrentColumn < tr->Columns-1) tileWidth = tr->TileWidth; else tileWidth = tr->ImageWidth - (tr->Columns-1) * (tr->TileWidthNB) + 2 * border; /* Save tile size, with border */ tr->CurrentTileWidth = tileWidth; tr->CurrentTileHeight = tileHeight; glViewport(0, 0, tileWidth, tileHeight); /* tile size including border */ /* save current matrix mode */ glGetIntegerv(GL_MATRIX_MODE, &matrixMode); glMatrixMode(GL_PROJECTION); glLoadIdentity(); /* compute projection parameters */ left = tr->Left + (tr->Right - tr->Left) * (tr->CurrentColumn * tr->TileWidthNB - border) / tr->ImageWidth; right = left + (tr->Right - tr->Left) * tileWidth / tr->ImageWidth; bottom = tr->Bottom + (tr->Top - tr->Bottom) * (tr->CurrentRow * tr->TileHeightNB - border) / tr->ImageHeight; top = bottom + (tr->Top - tr->Bottom) * tileHeight / tr->ImageHeight; ssgSetFrustum ( left, right, bottom, top, tr->Near, tr->Far ); /* restore user's matrix mode */ glMatrixMode( (GLenum)matrixMode ); } int trEndTile(TRcontext *tr) { GLint prevRowLength, prevSkipRows, prevSkipPixels /*, prevAlignment */; if (!tr) return 0; assert(tr->CurrentTile>=0); /* be sure OpenGL rendering is finished */ glFlush(); /* save current glPixelStore values */ glGetIntegerv(GL_PACK_ROW_LENGTH, &prevRowLength); glGetIntegerv(GL_PACK_SKIP_ROWS, &prevSkipRows); glGetIntegerv(GL_PACK_SKIP_PIXELS, &prevSkipPixels); /*glGetIntegerv(GL_PACK_ALIGNMENT, &prevAlignment);*/ if (tr->TileBuffer) { GLint srcX = tr->TileBorder; GLint srcY = tr->TileBorder; GLint srcWidth = tr->TileWidthNB; GLint srcHeight = tr->TileHeightNB; glReadPixels(srcX, srcY, srcWidth, srcHeight, tr->TileFormat, tr->TileType, tr->TileBuffer); } if (tr->ImageBuffer) { GLint srcX = tr->TileBorder; GLint srcY = tr->TileBorder; GLint srcWidth = tr->CurrentTileWidth - 2 * tr->TileBorder; GLint srcHeight = tr->CurrentTileHeight - 2 * tr->TileBorder; GLint destX = tr->TileWidthNB * tr->CurrentColumn; GLint destY = tr->TileHeightNB * tr->CurrentRow; /* setup pixel store for glReadPixels */ glPixelStorei(GL_PACK_ROW_LENGTH, tr->ImageWidth); glPixelStorei(GL_PACK_SKIP_ROWS, destY); glPixelStorei(GL_PACK_SKIP_PIXELS, destX); /*glPixelStorei(GL_PACK_ALIGNMENT, 1);*/ /* read the tile into the final image */ glReadPixels(srcX, srcY, srcWidth, srcHeight, tr->ImageFormat, tr->ImageType, tr->ImageBuffer); } /* restore previous glPixelStore values */ glPixelStorei(GL_PACK_ROW_LENGTH, prevRowLength); glPixelStorei(GL_PACK_SKIP_ROWS, prevSkipRows); glPixelStorei(GL_PACK_SKIP_PIXELS, prevSkipPixels); /*glPixelStorei(GL_PACK_ALIGNMENT, prevAlignment);*/ /* increment tile counter, return 1 if more tiles left to render */ tr->CurrentTile++; if (tr->CurrentTile >= tr->Rows * tr->Columns) { /* restore user's viewport */ glViewport(tr->ViewportSave[0], tr->ViewportSave[1], tr->ViewportSave[2], tr->ViewportSave[3]); tr->CurrentTile = -1; /* all done */ return 0; } else return 1; } /* * Replacement for glRastePos3f() which avoids the problem with invalid * raster pos. */ void trRasterPos3f(TRcontext *tr, GLfloat x, GLfloat y, GLfloat z) { if (tr->CurrentTile<0) { /* not doing tile rendering right now. Let OpenGL do this. */ glRasterPos3f(x, y, z); } else { GLdouble modelview[16], proj[16]; GLint viewport[4]; GLdouble winX, winY, winZ; /* Get modelview, projection and viewport */ glGetDoublev(GL_MODELVIEW_MATRIX, modelview); glGetDoublev(GL_PROJECTION_MATRIX, proj); viewport[0] = 0; viewport[1] = 0; viewport[2] = tr->CurrentTileWidth; viewport[3] = tr->CurrentTileHeight; /* Project object coord to window coordinate */ if (gluProject(x, y, z, modelview, proj, viewport, &winX, &winY, &winZ)){ /* set raster pos to window coord (0,0) */ glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0.0, tr->CurrentTileWidth, 0.0, tr->CurrentTileHeight, 0.0, 1.0); glRasterPos3f(0.0, 0.0, -winZ); /* Now use empty bitmap to adjust raster position to (winX,winY) */ { GLubyte bitmap[1] = {0}; glBitmap(1, 1, 0.0, 0.0, winX, winY, bitmap); } /* restore original matrices */ glPopMatrix(); /*proj*/ glMatrixMode(GL_MODELVIEW); glPopMatrix(); } #ifdef DEBUG if (glGetError()) printf("GL error!\n"); #endif } } <|endoftext|>
<commit_before>// // ex7_01.cpp // Exercise 7.1 // // Created by pezy on 14/10/30. // Copyright (c) 2014 pezy. All rights reserved. // #include <iostream> #include <string> using std::cin; using std::cout; using std::endl; using std::string; struct Sales_data{ string bookNo; unsigned units_sold = 0; double revenue = 0.0; }; int main() { Sales_data total; if (cin >> total.bookNo >> total.units_sold >> total.revenue) { Sales_data trans; while (cin >> trans.bookNo >> trans.units_sold >> trans.revenue) { if (total.bookNo == trans.bookNo) { total.units_sold += trans.units_sold; total.revenue += trans.revenue; } else { cout << total.bookNo << " " << total.units_sold << " " << total.revenue << endl; total = trans; } } cout << total.bookNo << " " << total.units_sold << " " << total.revenue << endl; } else { std::cerr << "No data?!" << std::endl; return -1; } return 0; } <commit_msg>Update ex7_01.cpp<commit_after>// // ex7_01.cpp // Exercise 7.1 // // Created by pezy on 14/10/30. // Copyright (c) 2014 pezy. All rights reserved. // #include <iostream> #include <string> using std::cin; using std::cout; using std::endl; using std::string; struct Sales_data { string bookNo; unsigned units_sold = 0; double revenue = 0.0; }; int main() { Sales_data total; if (cin >> total.bookNo >> total.units_sold >> total.revenue) { Sales_data trans; while (cin >> trans.bookNo >> trans.units_sold >> trans.revenue) { if (total.bookNo == trans.bookNo) { total.units_sold += trans.units_sold; total.revenue += trans.revenue; } else { cout << total.bookNo << " " << total.units_sold << " " << total.revenue << endl; total = trans; } } cout << total.bookNo << " " << total.units_sold << " " << total.revenue << endl; } else { std::cerr << "No data?!" << std::endl; return -1; } return 0; } <|endoftext|>
<commit_before><commit_msg>fdo#72125: GetTextWidth() can get very expensive.<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SpellAttrib.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2006-06-19 14:58:15 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif #ifndef _SVX_SPELL_ATTRIB #include <SpellAttrib.hxx> #endif #ifndef _SV_FONT_HXX #include <vcl/font.hxx> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_LINGUISTIC2_XSPELLALTERNATIVES_HPP_ #include <com/sun/star/linguistic2/XSpellAlternatives.hpp> #endif using namespace svx; using namespace com::sun::star::linguistic2; using namespace com::sun::star::uno; /*-- 10.09.2003 12:54:34--------------------------------------------------- -----------------------------------------------------------------------*/ SpellErrorAttrib::SpellErrorAttrib(Reference<XSpellAlternatives> xAlt) : TextAttrib(TEXTATTR_SPELL_ERROR), m_xAlternatives(xAlt) { } /*-- 10.09.2003 12:54:34--------------------------------------------------- -----------------------------------------------------------------------*/ SpellErrorAttrib::SpellErrorAttrib( const SpellErrorAttrib& rAttr ) : TextAttrib(TEXTATTR_SPELL_ERROR), m_xAlternatives( rAttr.m_xAlternatives ) { } /*-- 10.09.2003 12:54:34--------------------------------------------------- -----------------------------------------------------------------------*/ SpellErrorAttrib::~SpellErrorAttrib() { } /*-- 10.09.2003 12:54:35--------------------------------------------------- -----------------------------------------------------------------------*/ void SpellErrorAttrib::SetFont( Font& ) const { //this attribute doesn't have a visual effect } /*-- 10.09.2003 12:54:35--------------------------------------------------- -----------------------------------------------------------------------*/ TextAttrib* SpellErrorAttrib::Clone() const { return new SpellErrorAttrib(*this); } /*-- 10.09.2003 12:54:35--------------------------------------------------- -----------------------------------------------------------------------*/ int SpellErrorAttrib::operator==( const TextAttrib& rAttr ) const { return Which() == rAttr.Which() && m_xAlternatives.get() == static_cast<const SpellErrorAttrib&>(rAttr).m_xAlternatives.get(); } /*-- 10.09.2003 14:27:43--------------------------------------------------- -----------------------------------------------------------------------*/ SpellLanguageAttrib::SpellLanguageAttrib(LanguageType eLang) : TextAttrib(TEXTATTR_SPELL_LANGUAGE), m_eLanguage(eLang) { } /*-- 10.09.2003 14:27:43--------------------------------------------------- -----------------------------------------------------------------------*/ SpellLanguageAttrib::SpellLanguageAttrib( const SpellLanguageAttrib& rAttr ) : TextAttrib(TEXTATTR_SPELL_LANGUAGE), m_eLanguage(rAttr.m_eLanguage) { } /*-- 10.09.2003 14:27:43--------------------------------------------------- -----------------------------------------------------------------------*/ SpellLanguageAttrib::~SpellLanguageAttrib() { } /*-- 10.09.2003 14:27:43--------------------------------------------------- -----------------------------------------------------------------------*/ void SpellLanguageAttrib::SetFont( Font& ) const { //no visual effect } /*-- 10.09.2003 14:27:44--------------------------------------------------- -----------------------------------------------------------------------*/ TextAttrib* SpellLanguageAttrib::Clone() const { return new SpellLanguageAttrib(*this); } /*-- 10.09.2003 14:27:44--------------------------------------------------- -----------------------------------------------------------------------*/ int SpellLanguageAttrib::operator==( const TextAttrib& rAttr ) const { return Which() == rAttr.Which() && m_eLanguage == static_cast<const SpellLanguageAttrib&>(rAttr).m_eLanguage; } /*-- 31.10.2003 16:07:45--------------------------------------------------- -----------------------------------------------------------------------*/ SpellBackgroundAttrib::SpellBackgroundAttrib(const Color& rCol) : TextAttrib(TEXTATTR_SPELL_BACKGROUND), m_aBackgroundColor(rCol) { } /*-- 31.10.2003 16:07:45--------------------------------------------------- -----------------------------------------------------------------------*/ SpellBackgroundAttrib::SpellBackgroundAttrib( const SpellBackgroundAttrib& rAttr ) : TextAttrib(TEXTATTR_SPELL_BACKGROUND), m_aBackgroundColor(rAttr.m_aBackgroundColor) { } /*-- 31.10.2003 16:07:46--------------------------------------------------- -----------------------------------------------------------------------*/ SpellBackgroundAttrib::~SpellBackgroundAttrib() { } /*-- 31.10.2003 16:07:46--------------------------------------------------- -----------------------------------------------------------------------*/ void SpellBackgroundAttrib::SetFont( Font& rFont ) const { rFont.SetFillColor(m_aBackgroundColor); } /*-- 31.10.2003 16:07:46--------------------------------------------------- -----------------------------------------------------------------------*/ TextAttrib* SpellBackgroundAttrib::Clone() const { return new SpellBackgroundAttrib(*this); } /*-- 31.10.2003 16:07:47--------------------------------------------------- -----------------------------------------------------------------------*/ int SpellBackgroundAttrib::operator==( const TextAttrib& rAttr ) const { return Which() == rAttr.Which() && m_aBackgroundColor == static_cast<const SpellBackgroundAttrib&>(rAttr).m_aBackgroundColor; } <commit_msg>INTEGRATION: CWS pchfix02 (1.5.116); FILE MERGED 2006/09/01 17:46:03 kaib 1.5.116.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SpellAttrib.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2006-09-17 04:08:22 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif #ifndef _SVX_SPELL_ATTRIB #include <SpellAttrib.hxx> #endif #ifndef _SV_FONT_HXX #include <vcl/font.hxx> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_LINGUISTIC2_XSPELLALTERNATIVES_HPP_ #include <com/sun/star/linguistic2/XSpellAlternatives.hpp> #endif using namespace svx; using namespace com::sun::star::linguistic2; using namespace com::sun::star::uno; /*-- 10.09.2003 12:54:34--------------------------------------------------- -----------------------------------------------------------------------*/ SpellErrorAttrib::SpellErrorAttrib(Reference<XSpellAlternatives> xAlt) : TextAttrib(TEXTATTR_SPELL_ERROR), m_xAlternatives(xAlt) { } /*-- 10.09.2003 12:54:34--------------------------------------------------- -----------------------------------------------------------------------*/ SpellErrorAttrib::SpellErrorAttrib( const SpellErrorAttrib& rAttr ) : TextAttrib(TEXTATTR_SPELL_ERROR), m_xAlternatives( rAttr.m_xAlternatives ) { } /*-- 10.09.2003 12:54:34--------------------------------------------------- -----------------------------------------------------------------------*/ SpellErrorAttrib::~SpellErrorAttrib() { } /*-- 10.09.2003 12:54:35--------------------------------------------------- -----------------------------------------------------------------------*/ void SpellErrorAttrib::SetFont( Font& ) const { //this attribute doesn't have a visual effect } /*-- 10.09.2003 12:54:35--------------------------------------------------- -----------------------------------------------------------------------*/ TextAttrib* SpellErrorAttrib::Clone() const { return new SpellErrorAttrib(*this); } /*-- 10.09.2003 12:54:35--------------------------------------------------- -----------------------------------------------------------------------*/ int SpellErrorAttrib::operator==( const TextAttrib& rAttr ) const { return Which() == rAttr.Which() && m_xAlternatives.get() == static_cast<const SpellErrorAttrib&>(rAttr).m_xAlternatives.get(); } /*-- 10.09.2003 14:27:43--------------------------------------------------- -----------------------------------------------------------------------*/ SpellLanguageAttrib::SpellLanguageAttrib(LanguageType eLang) : TextAttrib(TEXTATTR_SPELL_LANGUAGE), m_eLanguage(eLang) { } /*-- 10.09.2003 14:27:43--------------------------------------------------- -----------------------------------------------------------------------*/ SpellLanguageAttrib::SpellLanguageAttrib( const SpellLanguageAttrib& rAttr ) : TextAttrib(TEXTATTR_SPELL_LANGUAGE), m_eLanguage(rAttr.m_eLanguage) { } /*-- 10.09.2003 14:27:43--------------------------------------------------- -----------------------------------------------------------------------*/ SpellLanguageAttrib::~SpellLanguageAttrib() { } /*-- 10.09.2003 14:27:43--------------------------------------------------- -----------------------------------------------------------------------*/ void SpellLanguageAttrib::SetFont( Font& ) const { //no visual effect } /*-- 10.09.2003 14:27:44--------------------------------------------------- -----------------------------------------------------------------------*/ TextAttrib* SpellLanguageAttrib::Clone() const { return new SpellLanguageAttrib(*this); } /*-- 10.09.2003 14:27:44--------------------------------------------------- -----------------------------------------------------------------------*/ int SpellLanguageAttrib::operator==( const TextAttrib& rAttr ) const { return Which() == rAttr.Which() && m_eLanguage == static_cast<const SpellLanguageAttrib&>(rAttr).m_eLanguage; } /*-- 31.10.2003 16:07:45--------------------------------------------------- -----------------------------------------------------------------------*/ SpellBackgroundAttrib::SpellBackgroundAttrib(const Color& rCol) : TextAttrib(TEXTATTR_SPELL_BACKGROUND), m_aBackgroundColor(rCol) { } /*-- 31.10.2003 16:07:45--------------------------------------------------- -----------------------------------------------------------------------*/ SpellBackgroundAttrib::SpellBackgroundAttrib( const SpellBackgroundAttrib& rAttr ) : TextAttrib(TEXTATTR_SPELL_BACKGROUND), m_aBackgroundColor(rAttr.m_aBackgroundColor) { } /*-- 31.10.2003 16:07:46--------------------------------------------------- -----------------------------------------------------------------------*/ SpellBackgroundAttrib::~SpellBackgroundAttrib() { } /*-- 31.10.2003 16:07:46--------------------------------------------------- -----------------------------------------------------------------------*/ void SpellBackgroundAttrib::SetFont( Font& rFont ) const { rFont.SetFillColor(m_aBackgroundColor); } /*-- 31.10.2003 16:07:46--------------------------------------------------- -----------------------------------------------------------------------*/ TextAttrib* SpellBackgroundAttrib::Clone() const { return new SpellBackgroundAttrib(*this); } /*-- 31.10.2003 16:07:47--------------------------------------------------- -----------------------------------------------------------------------*/ int SpellBackgroundAttrib::operator==( const TextAttrib& rAttr ) const { return Which() == rAttr.Which() && m_aBackgroundColor == static_cast<const SpellBackgroundAttrib&>(rAttr).m_aBackgroundColor; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: cuifmsearch.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2004-02-03 18:21:13 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CUI_FMSEARCH_HXX #define _CUI_FMSEARCH_HXX #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #include "fmsearch.hxx" //CHINA001 #define _SVSTDARR_STRINGSDTOR #include <svtools/svstdarr.hxx> #ifndef _DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _EDIT_HXX //autogen #include <vcl/edit.hxx> #endif #ifndef _SV_COMBOBOX_HXX //autogen #include <vcl/combobox.hxx> #endif #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _LINK_HXX //autogen #include <tools/link.hxx> #endif #ifndef _SFXCFGITEM_HXX //autogen #include <sfx2/cfgitem.hxx> #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif // =================================================================================================== // = class FmSearchDialog - Dialog fuer Suchen in Formularen/Tabellen // =================================================================================================== class FmSearchDialog : public ModalDialog { friend class FmSearchEngine; // meine ganzen Controls FixedLine m_flSearchFor; RadioButton m_rbSearchForText; RadioButton m_rbSearchForNull; RadioButton m_rbSearchForNotNull; ComboBox m_cmbSearchText; FixedLine m_flWhere; FixedText m_ftForm; ListBox m_lbForm; RadioButton m_rbAllFields; RadioButton m_rbSingleField; ListBox m_lbField; FixedLine m_flOptions; FixedText m_ftPosition; ListBox m_lbPosition; CheckBox m_cbUseFormat; CheckBox m_cbCase; CheckBox m_cbBackwards; CheckBox m_cbStartOver; CheckBox m_cbWildCard; CheckBox m_cbRegular; CheckBox m_cbApprox; PushButton m_pbApproxSettings; CheckBox m_aHalfFullFormsCJK; CheckBox m_aSoundsLikeCJK; PushButton m_aSoundsLikeCJKSettings; FixedLine m_flState; FixedText m_ftRecordLabel; FixedText m_ftRecord; FixedText m_ftHint; PushButton m_pbSearchAgain; CancelButton m_pbClose; HelpButton m_pbHelp; Window* m_pPreSearchFocus; Link m_lnkFoundHandler; // Handler fuer "gefunden" Link m_lnkCanceledNotFoundHdl; // Handler fuer Positionierung des Cursors Link m_lnkContextSupplier; // fuer Suche in verschiedenen Kontexten // ein Array, in dem ich mir fuer jeden Kontext das aktuell selektierte Feld merke ::std::vector<String> m_arrContextFields; // fuer die eigentliche Arbeit ... FmSearchEngine* m_pSearchEngine; Timer m_aDelayedPaint; // siehe EnableSearchUI ::svxform::FmSearchConfigItem* m_pConfig; public: /** die drei moeglichen Such-Modi : SM_BRUTE sucht einfach nur ... da wird das Office in der Zeit wohl stehen SM_ALLOWSCHEDULE ruft nach jedem durchsuchten Feld ein Application::Reschedule auf, so dass die Suche zwar im aufrufenden Thread laeuft, aber die Office-UI wenigstens noch funktionieren sollte. Soweit das den Dialog angeht, achtet der selber darauf, dass keine Inkonsistenzen entstehen, was dabei ausserhalb des Dialoges liegt, muss natuerlich vom Aufrufer erledigt werden (Was nicht allzu kompliziert sein duerfte, da der Dialog hier ja modal sein sollte) SM_USETHREAD startet einen eigenen Thread, der die Suche erledigt, so dass also die UI auch hier weiterhin funktioniert. */ //CHINA001 enum SEARCH_MODE { SM_BRUTE, SM_ALLOWSCHEDULE, SM_USETHREAD }; /** Constructor 1: gesucht wird mittels des uebergebenen Iterators, wenn man also seinen Original-Cursor nicht bewegen will, muss man hier einen Clone uebergeben strVisibleFields muss eine (durch ; getrennte) Liste aller Felder, die zur Auswahl stehen sollen, enthalten xFormatter wird benutzt, wenn die Daten aus den Feldern vor dem Vergleich entsprechend ihrem FormatKey formatiert werden sollen Zu eMode siehe SEARCH_MODE. */ FmSearchDialog(Window* pParent, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet>& xCursor, const String& strVisibleFields, const String& strInitialText, const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier>& xFormatSupplier, FMSEARCH_MODE eMode = SM_ALLOWSCHEDULE); /** Constructor 2: hiermit kann in verschiedenen Saetzen von Feldern gesucht werden. Es gibt eine Reihe von Kontexten, deren Namen in strContexts stehen (getrennt durch ';'), der Benutzer kann einen davon auswaehlen. Wenn der Benutzer einen Kontext auswaehlt, wird lnkContextSupplier aufgerufen, er bekommt einen Zeiger auf eine FmSearchContext-Struktur, die gefuellt werden muss. Fuer die Suche gilt dann : a) bei formatierter Suche wird der Iterator selber verwendet (wie beim ersten Constructor auch) b) bei formatierter Suche wird NICHT der FormatKey an den Fields des Iterators verwendet, sondern die entsprechende TextComponent wird gefragt (deshalb auch die Verwendung des originalen Iterator, durch dessen Move werden hoffentlich die hinter den TextComponent-Interfaces stehenden Controls geupdatet) c) bei nicht formatierter Suche wird ein Clone des Iterators verwendet (da ich hier die TextComponent-Interfaces nicht fragen muss) (natuerlich zwingend erforderlich : der String Nummer i in strUsedFields eines Kontexts muss mit dem Interface Nummer i in arrFields des Kontexts korrespondieren) */ FmSearchDialog(Window* pParent, const String& strInitialText, const String& strContexts, sal_Int16 nInitialContext, const Link& lnkContextSupplier, FMSEARCH_MODE eMode = SM_ALLOWSCHEDULE); virtual ~FmSearchDialog(); /** der Found-Handler bekommt im "gefunden"-Fall einen Zeiger auf eine FmFoundRecordInformation-Struktur (dieser ist nur im Handler gueltig, wenn man sich also die Daten merken muss, nicht den Zeiger, sondern die Struktur kopieren) Dieser Handler MUSS gesetzt werden. Ausserdem sollte beachtet werden, dass waehrend des Handlers der Suchdialog immer noch modal ist */ void SetFoundHandler(const Link& lnk) { m_lnkFoundHandler = lnk; } /** Wenn die Suche abgebrochen oder erfolglos beendet wurde, wird im Suchdialog immer der aktuelle Datensatz angezeigt Damit das mit der eventuellen Anzeige des Aufrufers synchron geht, existiert dieser Handler (der nicht undbedingt gesetzt werden muss). Der dem Handler uebergebene Zeiger zeigt auf eine FmFoundRecordInformation-Struktur, bei der aPosition und eventuell (bei Suche mit Kontexten) nContext gueltig sind. */ void SetCanceledNotFoundHdl(const Link& lnk) { m_lnkCanceledNotFoundHdl = lnk; } inline void SetActiveField(const String& strField); protected: virtual sal_Bool Close(); void Init(const String& strVisibleFields, const String& strInitialText); // nur von den Constructoren aus zu verwenden void OnFound(const ::com::sun::star::uno::Any& aCursorPos, sal_Int16 nFieldPos); void EnableSearchUI(sal_Bool bEnable); // beim Suchen in einem eigenen Thread moechte ich natuerlich die UI zum Starten/Parameter-Setzen der Suche disablen // Bei bEnable == sal_False wird fuer alle betroffenen Controls das Painten kurz aus- und mittels m_aDelayedPaint nach // einer kurzen Weile wieder angeschaltet. Wenn inzwischen eine Anforderung mit bEnable==sal_True kommt, wird der Timer gestoppt // und das Painten gleich wieder angeschaltet. Als Konsequenz dieses umstaendlichen Vorgehens ist kein Flackern zu sehen, // wenn man schnell hintereinander aus- und wieder einschaltet. void EnableSearchForDependees(sal_Bool bEnable); void EnableControlPaint(sal_Bool bEnable); // enabled (disabled) fuer alle wichtigen Controls ihr Paint void InitContext(sal_Int16 nContext); void LoadParams(); void SaveParams() const; private: // Handler fuer die Controls DECL_LINK( OnClickedFieldRadios, Button* ); DECL_LINK( OnClickedSearchAgain, Button* ); DECL_LINK( OnClickedSpecialSettings, Button* ); DECL_LINK( OnSearchTextModified, ComboBox* ); DECL_LINK( OnPositionSelected, ListBox* ); DECL_LINK( OnFieldSelected, ListBox* ); DECL_LINK( OnCheckBoxToggled, CheckBox* ); DECL_LINK( OnContextSelection, ListBox* ); // um sich den Fokus nach einem Found wiederzuholen ... (wenn der Found-Handler das entsprechende Flag zurueckgibt) DECL_LINK( AsyncGrabFocus, void* ); // Such-Fortschritt DECL_LINK( OnSearchProgress, FmSearchProgress* ); DECL_LINK( OnDelayedPaint, void* ); // siehe EnableSearchUI void implMoveControls(Control** _ppControls, sal_Int32 _nControls, sal_Int32 _nUp, Control* _pToResize); void initCommon( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet >& _rxCursor ); }; inline void FmSearchDialog::SetActiveField(const String& strField) { sal_uInt16 nInitialField = m_lbField.GetEntryPos(strField); if (nInitialField == COMBOBOX_ENTRY_NOTFOUND) nInitialField = 0; m_lbField.SelectEntryPos(nInitialField); LINK(this, FmSearchDialog, OnFieldSelected).Call(&m_lbField); } #endif // _CUI_FMSEARCH_HXX <commit_msg>INTEGRATION: CWS fwkbugfix04 (1.2.546); FILE MERGED 2004/12/15 06:09:58 mba 1.2.546.1: removed obsolete headers<commit_after>/************************************************************************* * * $RCSfile: cuifmsearch.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2005-01-18 15:32:44 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CUI_FMSEARCH_HXX #define _CUI_FMSEARCH_HXX #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #include "fmsearch.hxx" //CHINA001 #define _SVSTDARR_STRINGSDTOR #include <svtools/svstdarr.hxx> #ifndef _DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _EDIT_HXX //autogen #include <vcl/edit.hxx> #endif #ifndef _SV_COMBOBOX_HXX //autogen #include <vcl/combobox.hxx> #endif #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _LINK_HXX //autogen #include <tools/link.hxx> #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif // =================================================================================================== // = class FmSearchDialog - Dialog fuer Suchen in Formularen/Tabellen // =================================================================================================== class FmSearchDialog : public ModalDialog { friend class FmSearchEngine; // meine ganzen Controls FixedLine m_flSearchFor; RadioButton m_rbSearchForText; RadioButton m_rbSearchForNull; RadioButton m_rbSearchForNotNull; ComboBox m_cmbSearchText; FixedLine m_flWhere; FixedText m_ftForm; ListBox m_lbForm; RadioButton m_rbAllFields; RadioButton m_rbSingleField; ListBox m_lbField; FixedLine m_flOptions; FixedText m_ftPosition; ListBox m_lbPosition; CheckBox m_cbUseFormat; CheckBox m_cbCase; CheckBox m_cbBackwards; CheckBox m_cbStartOver; CheckBox m_cbWildCard; CheckBox m_cbRegular; CheckBox m_cbApprox; PushButton m_pbApproxSettings; CheckBox m_aHalfFullFormsCJK; CheckBox m_aSoundsLikeCJK; PushButton m_aSoundsLikeCJKSettings; FixedLine m_flState; FixedText m_ftRecordLabel; FixedText m_ftRecord; FixedText m_ftHint; PushButton m_pbSearchAgain; CancelButton m_pbClose; HelpButton m_pbHelp; Window* m_pPreSearchFocus; Link m_lnkFoundHandler; // Handler fuer "gefunden" Link m_lnkCanceledNotFoundHdl; // Handler fuer Positionierung des Cursors Link m_lnkContextSupplier; // fuer Suche in verschiedenen Kontexten // ein Array, in dem ich mir fuer jeden Kontext das aktuell selektierte Feld merke ::std::vector<String> m_arrContextFields; // fuer die eigentliche Arbeit ... FmSearchEngine* m_pSearchEngine; Timer m_aDelayedPaint; // siehe EnableSearchUI ::svxform::FmSearchConfigItem* m_pConfig; public: /** die drei moeglichen Such-Modi : SM_BRUTE sucht einfach nur ... da wird das Office in der Zeit wohl stehen SM_ALLOWSCHEDULE ruft nach jedem durchsuchten Feld ein Application::Reschedule auf, so dass die Suche zwar im aufrufenden Thread laeuft, aber die Office-UI wenigstens noch funktionieren sollte. Soweit das den Dialog angeht, achtet der selber darauf, dass keine Inkonsistenzen entstehen, was dabei ausserhalb des Dialoges liegt, muss natuerlich vom Aufrufer erledigt werden (Was nicht allzu kompliziert sein duerfte, da der Dialog hier ja modal sein sollte) SM_USETHREAD startet einen eigenen Thread, der die Suche erledigt, so dass also die UI auch hier weiterhin funktioniert. */ //CHINA001 enum SEARCH_MODE { SM_BRUTE, SM_ALLOWSCHEDULE, SM_USETHREAD }; /** Constructor 1: gesucht wird mittels des uebergebenen Iterators, wenn man also seinen Original-Cursor nicht bewegen will, muss man hier einen Clone uebergeben strVisibleFields muss eine (durch ; getrennte) Liste aller Felder, die zur Auswahl stehen sollen, enthalten xFormatter wird benutzt, wenn die Daten aus den Feldern vor dem Vergleich entsprechend ihrem FormatKey formatiert werden sollen Zu eMode siehe SEARCH_MODE. */ FmSearchDialog(Window* pParent, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet>& xCursor, const String& strVisibleFields, const String& strInitialText, const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier>& xFormatSupplier, FMSEARCH_MODE eMode = SM_ALLOWSCHEDULE); /** Constructor 2: hiermit kann in verschiedenen Saetzen von Feldern gesucht werden. Es gibt eine Reihe von Kontexten, deren Namen in strContexts stehen (getrennt durch ';'), der Benutzer kann einen davon auswaehlen. Wenn der Benutzer einen Kontext auswaehlt, wird lnkContextSupplier aufgerufen, er bekommt einen Zeiger auf eine FmSearchContext-Struktur, die gefuellt werden muss. Fuer die Suche gilt dann : a) bei formatierter Suche wird der Iterator selber verwendet (wie beim ersten Constructor auch) b) bei formatierter Suche wird NICHT der FormatKey an den Fields des Iterators verwendet, sondern die entsprechende TextComponent wird gefragt (deshalb auch die Verwendung des originalen Iterator, durch dessen Move werden hoffentlich die hinter den TextComponent-Interfaces stehenden Controls geupdatet) c) bei nicht formatierter Suche wird ein Clone des Iterators verwendet (da ich hier die TextComponent-Interfaces nicht fragen muss) (natuerlich zwingend erforderlich : der String Nummer i in strUsedFields eines Kontexts muss mit dem Interface Nummer i in arrFields des Kontexts korrespondieren) */ FmSearchDialog(Window* pParent, const String& strInitialText, const String& strContexts, sal_Int16 nInitialContext, const Link& lnkContextSupplier, FMSEARCH_MODE eMode = SM_ALLOWSCHEDULE); virtual ~FmSearchDialog(); /** der Found-Handler bekommt im "gefunden"-Fall einen Zeiger auf eine FmFoundRecordInformation-Struktur (dieser ist nur im Handler gueltig, wenn man sich also die Daten merken muss, nicht den Zeiger, sondern die Struktur kopieren) Dieser Handler MUSS gesetzt werden. Ausserdem sollte beachtet werden, dass waehrend des Handlers der Suchdialog immer noch modal ist */ void SetFoundHandler(const Link& lnk) { m_lnkFoundHandler = lnk; } /** Wenn die Suche abgebrochen oder erfolglos beendet wurde, wird im Suchdialog immer der aktuelle Datensatz angezeigt Damit das mit der eventuellen Anzeige des Aufrufers synchron geht, existiert dieser Handler (der nicht undbedingt gesetzt werden muss). Der dem Handler uebergebene Zeiger zeigt auf eine FmFoundRecordInformation-Struktur, bei der aPosition und eventuell (bei Suche mit Kontexten) nContext gueltig sind. */ void SetCanceledNotFoundHdl(const Link& lnk) { m_lnkCanceledNotFoundHdl = lnk; } inline void SetActiveField(const String& strField); protected: virtual sal_Bool Close(); void Init(const String& strVisibleFields, const String& strInitialText); // nur von den Constructoren aus zu verwenden void OnFound(const ::com::sun::star::uno::Any& aCursorPos, sal_Int16 nFieldPos); void EnableSearchUI(sal_Bool bEnable); // beim Suchen in einem eigenen Thread moechte ich natuerlich die UI zum Starten/Parameter-Setzen der Suche disablen // Bei bEnable == sal_False wird fuer alle betroffenen Controls das Painten kurz aus- und mittels m_aDelayedPaint nach // einer kurzen Weile wieder angeschaltet. Wenn inzwischen eine Anforderung mit bEnable==sal_True kommt, wird der Timer gestoppt // und das Painten gleich wieder angeschaltet. Als Konsequenz dieses umstaendlichen Vorgehens ist kein Flackern zu sehen, // wenn man schnell hintereinander aus- und wieder einschaltet. void EnableSearchForDependees(sal_Bool bEnable); void EnableControlPaint(sal_Bool bEnable); // enabled (disabled) fuer alle wichtigen Controls ihr Paint void InitContext(sal_Int16 nContext); void LoadParams(); void SaveParams() const; private: // Handler fuer die Controls DECL_LINK( OnClickedFieldRadios, Button* ); DECL_LINK( OnClickedSearchAgain, Button* ); DECL_LINK( OnClickedSpecialSettings, Button* ); DECL_LINK( OnSearchTextModified, ComboBox* ); DECL_LINK( OnPositionSelected, ListBox* ); DECL_LINK( OnFieldSelected, ListBox* ); DECL_LINK( OnCheckBoxToggled, CheckBox* ); DECL_LINK( OnContextSelection, ListBox* ); // um sich den Fokus nach einem Found wiederzuholen ... (wenn der Found-Handler das entsprechende Flag zurueckgibt) DECL_LINK( AsyncGrabFocus, void* ); // Such-Fortschritt DECL_LINK( OnSearchProgress, FmSearchProgress* ); DECL_LINK( OnDelayedPaint, void* ); // siehe EnableSearchUI void implMoveControls(Control** _ppControls, sal_Int32 _nControls, sal_Int32 _nUp, Control* _pToResize); void initCommon( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet >& _rxCursor ); }; inline void FmSearchDialog::SetActiveField(const String& strField) { sal_uInt16 nInitialField = m_lbField.GetEntryPos(strField); if (nInitialField == COMBOBOX_ENTRY_NOTFOUND) nInitialField = 0; m_lbField.SelectEntryPos(nInitialField); LINK(this, FmSearchDialog, OnFieldSelected).Call(&m_lbField); } #endif // _CUI_FMSEARCH_HXX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: accpage.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2007-09-27 08:23:07 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _ACCPAGE_HXX #define _ACCPAGE_HXX #ifndef _ACCCONTEXT_HXX #include "acccontext.hxx" #endif /** * accessibility implementation for the page (SwPageFrm) * The page is _only_ visible in the page preview. For the regular * document view, it doesn't make sense to add this additional element * into the hierarchy. For the page preview, however, the page is the * important. */ class SwAccessiblePage : public SwAccessibleContext { sal_Bool bIsSelected; // protected by base class mutex sal_Bool IsSelected(); protected: // return the bounding box for the page in page preview mode using SwAccessibleFrame::GetBounds; SwRect GetBounds( /* const SwFrm *pFrm =0 */ ); // Set states for getAccessibleStateSet. // This drived class additionaly sets // FOCUSABLE(1) and FOCUSED(+) virtual void GetStates( ::utl::AccessibleStateSetHelper& rStateSet ); virtual void _InvalidateCursorPos(); virtual void _InvalidateFocus(); virtual ~SwAccessiblePage(); public: // convenience constructor to avoid typecast; // may only be called with SwPageFrm argument SwAccessiblePage( SwAccessibleMap* pInitMap, const SwFrm* pFrame ); // // XAccessibleContext methods that need to be overridden // virtual ::rtl::OUString SAL_CALL getAccessibleDescription (void) throw (::com::sun::star::uno::RuntimeException); // // XServiceInfo // virtual ::rtl::OUString SAL_CALL getImplementationName (void) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService ( const ::rtl::OUString& sServiceName) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames (void) throw (::com::sun::star::uno::RuntimeException); //===== XTypeProvider ==================================================== virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool HasCursor(); // required by map to remember that object }; #endif <commit_msg>INTEGRATION: CWS swusing (1.7.38); FILE MERGED 2007/10/10 14:15:08 tl 1.7.38.1: #i82476# make newly added 'using' declarations private<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: accpage.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: vg $ $Date: 2007-10-22 15:10:11 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _ACCPAGE_HXX #define _ACCPAGE_HXX #ifndef _ACCCONTEXT_HXX #include "acccontext.hxx" #endif /** * accessibility implementation for the page (SwPageFrm) * The page is _only_ visible in the page preview. For the regular * document view, it doesn't make sense to add this additional element * into the hierarchy. For the page preview, however, the page is the * important. */ class SwAccessiblePage : public SwAccessibleContext { sal_Bool bIsSelected; // protected by base class mutex sal_Bool IsSelected(); using SwAccessibleFrame::GetBounds; protected: // return the bounding box for the page in page preview mode SwRect GetBounds( /* const SwFrm *pFrm =0 */ ); // Set states for getAccessibleStateSet. // This drived class additionaly sets // FOCUSABLE(1) and FOCUSED(+) virtual void GetStates( ::utl::AccessibleStateSetHelper& rStateSet ); virtual void _InvalidateCursorPos(); virtual void _InvalidateFocus(); virtual ~SwAccessiblePage(); public: // convenience constructor to avoid typecast; // may only be called with SwPageFrm argument SwAccessiblePage( SwAccessibleMap* pInitMap, const SwFrm* pFrame ); // // XAccessibleContext methods that need to be overridden // virtual ::rtl::OUString SAL_CALL getAccessibleDescription (void) throw (::com::sun::star::uno::RuntimeException); // // XServiceInfo // virtual ::rtl::OUString SAL_CALL getImplementationName (void) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService ( const ::rtl::OUString& sServiceName) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames (void) throw (::com::sun::star::uno::RuntimeException); //===== XTypeProvider ==================================================== virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool HasCursor(); // required by map to remember that object }; #endif <|endoftext|>
<commit_before>#include <StdAfx.h> #include <MrMapi/MMNamedProps.h> #include <MrMapi/mmcli.h> #include <core/mapi/processor/mapiProcessor.h> #include <core/mapi/extraPropTags.h> #include <core/smartview/SmartView.h> #include <core/utility/strings.h> #include <core/utility/registry.h> #include <core/utility/output.h> #include <core/mapi/mapiFunctions.h> void PrintGuid(const GUID& lpGuid) { wprintf( L"%.8lX-%.4X-%.4X-%.2X%.2X-%.2X%.2X%.2X%.2X%.2X%.2X", lpGuid.Data1, lpGuid.Data2, lpGuid.Data3, lpGuid.Data4[0], lpGuid.Data4[1], lpGuid.Data4[2], lpGuid.Data4[3], lpGuid.Data4[4], lpGuid.Data4[5], lpGuid.Data4[6], lpGuid.Data4[7]); } class NamedPropEntry { public: NamedPropEntry(ULONG propTag, LPGUID lpGuid, LPWSTR name) { this->Kind = MNID_STRING; this->PropTag = propTag; this->PropSetGuid = *lpGuid; this->PropName = name; } NamedPropEntry(ULONG propTag, LPGUID lpGuid, ULONG id) { this->Kind = MNID_ID; this->PropTag = propTag; this->PropSetGuid = *lpGuid; this->PropId = id; } ULONG PropTag = 0; GUID PropSetGuid = { 0 }; ULONG Kind = 0; std::wstring PropName; ULONG PropId = 0; }; void DoNamedProps(_In_opt_ LPMDB lpMDB) { auto hRes = S_OK; wprintf(L"Dumping named properties...\n"); ULONG cPropNames = 0; LPSPropTagArray pProps = nullptr; LPMAPINAMEID* pNames = nullptr; hRes = WC_MAPI(lpMDB->GetNamesFromIDs(&pProps, nullptr, 0, &cPropNames, &pNames)); if (SUCCEEDED(hRes)) { wprintf(L"\n"); std::vector<NamedPropEntry> props; for (std::uint32_t i = 0; i < cPropNames; i++) { switch (pNames[i]->ulKind) { case MNID_STRING: props.emplace_back(pProps->aulPropTag[i], pNames[i]->lpguid, pNames[i]->Kind.lpwstrName); break; case MNID_ID: props.emplace_back(pProps->aulPropTag[i], pNames[i]->lpguid, pNames[i]->Kind.lID); break; } } std::sort(props.begin(), props.end(), [](NamedPropEntry& i, NamedPropEntry& j) { // If the Property set GUIDs don't match, sort by that auto res = memcmp(&i.PropSetGuid, &j.PropSetGuid, sizeof(GUID)); if (res) return res < 0; // If they are different kinds, use that next if (i.Kind != j.Kind) { return i.Kind < j.Kind; } switch (i.Kind) { case MNID_ID: return i.PropId < j.PropId; case MNID_STRING: return i.PropName < j.PropName; } // This shouldn't ever actually hit return i.PropTag < j.PropTag; }); for (int i = 0; i < props.size(); i++) { wprintf(L"[%08x] (", props[i].PropTag); PrintGuid(props[i].PropSetGuid); switch (props[i].Kind) { case MNID_ID: wprintf(L":0x%08x)\n", props[i].PropId); break; case MNID_STRING: wprintf(L":%ws)\n", props[i].PropName.c_str()); break; } } } else { wprintf(L"FAILED. Error 0x%x\n", hRes); } if (pProps) MAPIFreeBuffer(pProps); if (pNames) MAPIFreeBuffer(pNames); }<commit_msg>fix iterator type<commit_after>#include <StdAfx.h> #include <MrMapi/MMNamedProps.h> #include <MrMapi/mmcli.h> #include <core/mapi/processor/mapiProcessor.h> #include <core/mapi/extraPropTags.h> #include <core/smartview/SmartView.h> #include <core/utility/strings.h> #include <core/utility/registry.h> #include <core/utility/output.h> #include <core/mapi/mapiFunctions.h> void PrintGuid(const GUID& lpGuid) { wprintf( L"%.8lX-%.4X-%.4X-%.2X%.2X-%.2X%.2X%.2X%.2X%.2X%.2X", lpGuid.Data1, lpGuid.Data2, lpGuid.Data3, lpGuid.Data4[0], lpGuid.Data4[1], lpGuid.Data4[2], lpGuid.Data4[3], lpGuid.Data4[4], lpGuid.Data4[5], lpGuid.Data4[6], lpGuid.Data4[7]); } class NamedPropEntry { public: NamedPropEntry(ULONG propTag, LPGUID lpGuid, LPWSTR name) { this->Kind = MNID_STRING; this->PropTag = propTag; this->PropSetGuid = *lpGuid; this->PropName = name; } NamedPropEntry(ULONG propTag, LPGUID lpGuid, ULONG id) { this->Kind = MNID_ID; this->PropTag = propTag; this->PropSetGuid = *lpGuid; this->PropId = id; } ULONG PropTag = 0; GUID PropSetGuid = { 0 }; ULONG Kind = 0; std::wstring PropName; ULONG PropId = 0; }; void DoNamedProps(_In_opt_ LPMDB lpMDB) { auto hRes = S_OK; wprintf(L"Dumping named properties...\n"); ULONG cPropNames = 0; LPSPropTagArray pProps = nullptr; LPMAPINAMEID* pNames = nullptr; hRes = WC_MAPI(lpMDB->GetNamesFromIDs(&pProps, nullptr, 0, &cPropNames, &pNames)); if (SUCCEEDED(hRes)) { wprintf(L"\n"); std::vector<NamedPropEntry> props; for (std::uint32_t i = 0; i < cPropNames; i++) { switch (pNames[i]->ulKind) { case MNID_STRING: props.emplace_back(pProps->aulPropTag[i], pNames[i]->lpguid, pNames[i]->Kind.lpwstrName); break; case MNID_ID: props.emplace_back(pProps->aulPropTag[i], pNames[i]->lpguid, pNames[i]->Kind.lID); break; } } std::sort(props.begin(), props.end(), [](NamedPropEntry& i, NamedPropEntry& j) { // If the Property set GUIDs don't match, sort by that auto res = memcmp(&i.PropSetGuid, &j.PropSetGuid, sizeof(GUID)); if (res) return res < 0; // If they are different kinds, use that next if (i.Kind != j.Kind) { return i.Kind < j.Kind; } switch (i.Kind) { case MNID_ID: return i.PropId < j.PropId; case MNID_STRING: return i.PropName < j.PropName; } // This shouldn't ever actually hit return i.PropTag < j.PropTag; }); for (size_t i = 0; i < props.size(); i++) { wprintf(L"[%08x] (", props[i].PropTag); PrintGuid(props[i].PropSetGuid); switch (props[i].Kind) { case MNID_ID: wprintf(L":0x%08x)\n", props[i].PropId); break; case MNID_STRING: wprintf(L":%ws)\n", props[i].PropName.c_str()); break; } } } else { wprintf(L"FAILED. Error 0x%x\n", hRes); } if (pProps) MAPIFreeBuffer(pProps); if (pNames) MAPIFreeBuffer(pNames); }<|endoftext|>
<commit_before>#include <iostream> #include <array> #include <iostream> #include "Astar.hpp" #include "Map.hpp" #include "WeightedAstar.hpp" int main() { Map setmap; Map::gridMatrix map_info = setmap.getGridmap(3); Astar::coordinate start = setmap.SetStart(0, 4); Astar::coordinate goal = setmap.SetGoal(9, 5); std::stack<Astar::coordinate> Path; int weight = 2; WeightedAstar w_astar; Path = w_astar.WeightedA(map_info, start, goal, weight); return 0; } <commit_msg>Add comments and add header of OpenCv -User Stroy #9<commit_after>/** *@file main.cpp *@Copyright (C) 2017 Zejiang Zeng - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, please visit : https://github.com/zzjkf2009/Midterm_Astar/blob/master/LICENSE *@brief This is the main source file that combine the Astar path palng project */ #include <iostream> #include <array> #include <iostream> #include <opencv2/opencv.hpp> #include "Astar.hpp" #include "Map.hpp" #include"BuildingMap.hpp" #include "WeightedAstar.hpp" int main() { Map setmap; Map::gridMatrix map_info = setmap.getGridmap(3); Astar::coordinate start = setmap.SetStart(2, 3); Astar::coordinate goal = setmap.SetGoal(7, 7); std::stack<Astar::coordinate> Path; int weight = 2; WeightedAstar w_astar; Path = w_astar.WeightedA(map_info, start, goal, weight); Buildingmap build; cv::Mat Map = build.drawGrids(map_info, start, goal); cv::Mat PathIm = build.drawPath(Path, Map); if(! PathIm.data ) // Check for invalid input { std::cout << "Could not open or find the image" << std::endl ; return -1; } imwrite( "Image.jpg", PathIm ); return 0; } <|endoftext|>
<commit_before><commit_msg>use getCells()<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlitemi.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: hr $ $Date: 2007-09-27 10:12:17 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include <hintids.hxx> #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _RSCSFX_HXX #include <rsc/rscsfx.hxx> #endif #ifndef _XMLITMAP_HXX #include "xmlitmap.hxx" #endif #ifndef _XMLIMPIT_HXX #include "xmlimpit.hxx" #endif #ifndef _XMLITEM_HXX #include "xmlitem.hxx" #endif #ifndef _XMLOFF_I18NMAP_HXX #include <xmloff/i18nmap.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _XMLOFF_FAMILIES_HXX #include <xmloff/families.hxx> #endif #ifndef _SVX_UNOMID_HXX #include <svx/unomid.hxx> #endif #ifndef _SVX_BOXITEM_HXX #include <svx/boxitem.hxx> #endif #ifndef _SVX_FONTITEM_HXX #include <svx/fontitem.hxx> #endif #ifndef _SVX_TSPTITEM_HXX #include <svx/tstpitem.hxx> #endif #ifndef _SVX_BOXITEM_HXX #include <svx/boxitem.hxx> #endif #ifndef _SVX_BRSHITEM_HXX #include <svx/brshitem.hxx> #endif #ifndef _SVX_LANGITEM_HXX #include <svx/langitem.hxx> #endif #ifndef _XMLOFF_XMLTABI_HXX //#include <xmloff/xmltabi.hxx> #endif #ifndef _XMLBRSHI_HXX #include "xmlbrshi.hxx" #endif #ifndef _PARATR_HXX #include <paratr.hxx> #endif #ifndef _DOC_HXX //autogen wg. SwDoc #include <doc.hxx> #endif #ifndef _UNOMID_H #include <unomid.h> #endif #ifndef _XMLIMP_HXX #include "xmlimp.hxx" #endif using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; extern SvXMLItemMapEntry aXMLTableItemMap[]; extern SvXMLItemMapEntry aXMLTableColItemMap[]; extern SvXMLItemMapEntry aXMLTableRowItemMap[]; extern SvXMLItemMapEntry aXMLTableCellItemMap[]; class SwXMLImportTableItemMapper_Impl: public SvXMLImportItemMapper { public: SwXMLImportTableItemMapper_Impl( SvXMLItemMapEntriesRef rMapEntries ); virtual ~SwXMLImportTableItemMapper_Impl(); virtual sal_Bool handleSpecialItem( const SvXMLItemMapEntry& rEntry, SfxPoolItem& rItem, SfxItemSet& rSet, const OUString& rValue, const SvXMLUnitConverter& rUnitConverter, const SvXMLNamespaceMap& rNamespaceMap ) const; virtual void finished( SfxItemSet& rSet ) const; }; SwXMLImportTableItemMapper_Impl::SwXMLImportTableItemMapper_Impl( SvXMLItemMapEntriesRef rMapEntries ) : SvXMLImportItemMapper( rMapEntries, RES_UNKNOWNATR_CONTAINER) { } SwXMLImportTableItemMapper_Impl::~SwXMLImportTableItemMapper_Impl() { } sal_Bool SwXMLImportTableItemMapper_Impl::handleSpecialItem( const SvXMLItemMapEntry& rEntry, SfxPoolItem& rItem, SfxItemSet& rItemSet, const OUString& rValue, const SvXMLUnitConverter& rUnitConv, const SvXMLNamespaceMap& ) const { sal_Bool bRet = sal_False; sal_uInt16 nMemberId = static_cast< sal_Int16 >(rEntry.nMemberId & MID_SW_FLAG_MASK); switch( rItem.Which() ) { case RES_FRM_SIZE: switch( nMemberId ) { case MID_FRMSIZE_COL_WIDTH: // If the item is existing already, a relative value has been set // already that must be preserved. if( SFX_ITEM_SET != rItemSet.GetItemState( RES_FRM_SIZE, sal_False ) ) bRet = SvXMLImportItemMapper::PutXMLValue( rItem, rValue, nMemberId, rUnitConv ); break; } } return bRet; } void SwXMLImportTableItemMapper_Impl::finished( SfxItemSet& /*rSet*/ ) const { } // --------------------------------------------------------------------- class SwXMLItemSetContext_Impl : public SvXMLItemSetContext { SvXMLImportContextRef xBackground; public: SwXMLItemSetContext_Impl( SwXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const Reference< xml::sax::XAttributeList > & xAttrList, SfxItemSet& rItemSet, const SvXMLImportItemMapper& rIMapper, const SvXMLUnitConverter& rUnitConv ); virtual ~SwXMLItemSetContext_Impl(); using SvXMLItemSetContext::CreateChildContext; virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const ::uno::Reference< xml::sax::XAttributeList > & xAttrList, SfxItemSet& rItemSet, const SvXMLItemMapEntry& rEntry, const SvXMLUnitConverter& rUnitConv ); }; SwXMLItemSetContext_Impl::SwXMLItemSetContext_Impl( SwXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const Reference< xml::sax::XAttributeList > & xAttrList, SfxItemSet& _rItemSet, const SvXMLImportItemMapper& _rIMapper, const SvXMLUnitConverter& _rUnitConv ) : SvXMLItemSetContext( rImport, nPrfx, rLName, xAttrList, _rItemSet, _rIMapper, _rUnitConv ) { } SwXMLItemSetContext_Impl::~SwXMLItemSetContext_Impl() { if( xBackground.Is() ) { const SvxBrushItem& rItem = ((SwXMLBrushItemImportContext*)&xBackground)->GetItem(); rItemSet.Put( rItem ); } } SvXMLImportContext *SwXMLItemSetContext_Impl::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList, SfxItemSet& _rItemSet, const SvXMLItemMapEntry& rEntry, const SvXMLUnitConverter& _rUnitConv ) { SvXMLImportContext *pContext = 0; switch( rEntry.nWhichId ) { case RES_BACKGROUND: { const SfxPoolItem *pItem; if( SFX_ITEM_SET == _rItemSet.GetItemState( RES_BACKGROUND, sal_False, &pItem ) ) { pContext = new SwXMLBrushItemImportContext( GetImport(), nPrefix, rLocalName, xAttrList, _rUnitConv, *(const SvxBrushItem *)pItem ); } else { pContext = new SwXMLBrushItemImportContext( GetImport(), nPrefix, rLocalName, xAttrList, _rUnitConv, RES_BACKGROUND ); } xBackground = pContext; } break; } if( !pContext ) pContext = SvXMLItemSetContext::CreateChildContext( nPrefix, rLocalName, xAttrList, _rItemSet, rEntry, _rUnitConv ); return pContext; } // --------------------------------------------------------------------- void SwXMLImport::_InitItemImport() { // #110680# pTwipUnitConv = new SvXMLUnitConverter( MAP_TWIP, MAP_TWIP, getServiceFactory() ); xTableItemMap = new SvXMLItemMapEntries( aXMLTableItemMap ); xTableColItemMap = new SvXMLItemMapEntries( aXMLTableColItemMap ); xTableRowItemMap = new SvXMLItemMapEntries( aXMLTableRowItemMap ); xTableCellItemMap = new SvXMLItemMapEntries( aXMLTableCellItemMap ); pTableItemMapper = new SwXMLImportTableItemMapper_Impl( xTableItemMap ); } void SwXMLImport::_FinitItemImport() { delete pTableItemMapper; delete pTwipUnitConv; } SvXMLImportContext *SwXMLImport::CreateTableItemImportContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList, sal_uInt16 nFamily, SfxItemSet& rItemSet ) { SvXMLItemMapEntriesRef xItemMap; switch( nFamily ) { case XML_STYLE_FAMILY_TABLE_TABLE: xItemMap = xTableItemMap; break; case XML_STYLE_FAMILY_TABLE_COLUMN: xItemMap = xTableColItemMap; break; case XML_STYLE_FAMILY_TABLE_ROW: xItemMap = xTableRowItemMap; break; case XML_STYLE_FAMILY_TABLE_CELL: xItemMap = xTableCellItemMap; break; } pTableItemMapper->setMapEntries( xItemMap ); return new SwXMLItemSetContext_Impl( *this, nPrefix, rLocalName, xAttrList, rItemSet, GetTableItemMapper(), GetTwipUnitConverter() ); } <commit_msg>INTEGRATION: CWS swusing (1.11.38); FILE MERGED 2007/10/10 14:15:09 tl 1.11.38.1: #i82476# make newly added 'using' declarations private<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlitemi.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: vg $ $Date: 2007-10-22 15:13:27 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include <hintids.hxx> #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _RSCSFX_HXX #include <rsc/rscsfx.hxx> #endif #ifndef _XMLITMAP_HXX #include "xmlitmap.hxx" #endif #ifndef _XMLIMPIT_HXX #include "xmlimpit.hxx" #endif #ifndef _XMLITEM_HXX #include "xmlitem.hxx" #endif #ifndef _XMLOFF_I18NMAP_HXX #include <xmloff/i18nmap.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _XMLOFF_FAMILIES_HXX #include <xmloff/families.hxx> #endif #ifndef _SVX_UNOMID_HXX #include <svx/unomid.hxx> #endif #ifndef _SVX_BOXITEM_HXX #include <svx/boxitem.hxx> #endif #ifndef _SVX_FONTITEM_HXX #include <svx/fontitem.hxx> #endif #ifndef _SVX_TSPTITEM_HXX #include <svx/tstpitem.hxx> #endif #ifndef _SVX_BOXITEM_HXX #include <svx/boxitem.hxx> #endif #ifndef _SVX_BRSHITEM_HXX #include <svx/brshitem.hxx> #endif #ifndef _SVX_LANGITEM_HXX #include <svx/langitem.hxx> #endif #ifndef _XMLOFF_XMLTABI_HXX //#include <xmloff/xmltabi.hxx> #endif #ifndef _XMLBRSHI_HXX #include "xmlbrshi.hxx" #endif #ifndef _PARATR_HXX #include <paratr.hxx> #endif #ifndef _DOC_HXX //autogen wg. SwDoc #include <doc.hxx> #endif #ifndef _UNOMID_H #include <unomid.h> #endif #ifndef _XMLIMP_HXX #include "xmlimp.hxx" #endif using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; extern SvXMLItemMapEntry aXMLTableItemMap[]; extern SvXMLItemMapEntry aXMLTableColItemMap[]; extern SvXMLItemMapEntry aXMLTableRowItemMap[]; extern SvXMLItemMapEntry aXMLTableCellItemMap[]; class SwXMLImportTableItemMapper_Impl: public SvXMLImportItemMapper { public: SwXMLImportTableItemMapper_Impl( SvXMLItemMapEntriesRef rMapEntries ); virtual ~SwXMLImportTableItemMapper_Impl(); virtual sal_Bool handleSpecialItem( const SvXMLItemMapEntry& rEntry, SfxPoolItem& rItem, SfxItemSet& rSet, const OUString& rValue, const SvXMLUnitConverter& rUnitConverter, const SvXMLNamespaceMap& rNamespaceMap ) const; virtual void finished( SfxItemSet& rSet ) const; }; SwXMLImportTableItemMapper_Impl::SwXMLImportTableItemMapper_Impl( SvXMLItemMapEntriesRef rMapEntries ) : SvXMLImportItemMapper( rMapEntries, RES_UNKNOWNATR_CONTAINER) { } SwXMLImportTableItemMapper_Impl::~SwXMLImportTableItemMapper_Impl() { } sal_Bool SwXMLImportTableItemMapper_Impl::handleSpecialItem( const SvXMLItemMapEntry& rEntry, SfxPoolItem& rItem, SfxItemSet& rItemSet, const OUString& rValue, const SvXMLUnitConverter& rUnitConv, const SvXMLNamespaceMap& ) const { sal_Bool bRet = sal_False; sal_uInt16 nMemberId = static_cast< sal_Int16 >(rEntry.nMemberId & MID_SW_FLAG_MASK); switch( rItem.Which() ) { case RES_FRM_SIZE: switch( nMemberId ) { case MID_FRMSIZE_COL_WIDTH: // If the item is existing already, a relative value has been set // already that must be preserved. if( SFX_ITEM_SET != rItemSet.GetItemState( RES_FRM_SIZE, sal_False ) ) bRet = SvXMLImportItemMapper::PutXMLValue( rItem, rValue, nMemberId, rUnitConv ); break; } } return bRet; } void SwXMLImportTableItemMapper_Impl::finished( SfxItemSet& /*rSet*/ ) const { } // --------------------------------------------------------------------- class SwXMLItemSetContext_Impl : public SvXMLItemSetContext { SvXMLImportContextRef xBackground; using SvXMLItemSetContext::CreateChildContext; public: SwXMLItemSetContext_Impl( SwXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const Reference< xml::sax::XAttributeList > & xAttrList, SfxItemSet& rItemSet, const SvXMLImportItemMapper& rIMapper, const SvXMLUnitConverter& rUnitConv ); virtual ~SwXMLItemSetContext_Impl(); virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName, const ::uno::Reference< xml::sax::XAttributeList > & xAttrList, SfxItemSet& rItemSet, const SvXMLItemMapEntry& rEntry, const SvXMLUnitConverter& rUnitConv ); }; SwXMLItemSetContext_Impl::SwXMLItemSetContext_Impl( SwXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const Reference< xml::sax::XAttributeList > & xAttrList, SfxItemSet& _rItemSet, const SvXMLImportItemMapper& _rIMapper, const SvXMLUnitConverter& _rUnitConv ) : SvXMLItemSetContext( rImport, nPrfx, rLName, xAttrList, _rItemSet, _rIMapper, _rUnitConv ) { } SwXMLItemSetContext_Impl::~SwXMLItemSetContext_Impl() { if( xBackground.Is() ) { const SvxBrushItem& rItem = ((SwXMLBrushItemImportContext*)&xBackground)->GetItem(); rItemSet.Put( rItem ); } } SvXMLImportContext *SwXMLItemSetContext_Impl::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList, SfxItemSet& _rItemSet, const SvXMLItemMapEntry& rEntry, const SvXMLUnitConverter& _rUnitConv ) { SvXMLImportContext *pContext = 0; switch( rEntry.nWhichId ) { case RES_BACKGROUND: { const SfxPoolItem *pItem; if( SFX_ITEM_SET == _rItemSet.GetItemState( RES_BACKGROUND, sal_False, &pItem ) ) { pContext = new SwXMLBrushItemImportContext( GetImport(), nPrefix, rLocalName, xAttrList, _rUnitConv, *(const SvxBrushItem *)pItem ); } else { pContext = new SwXMLBrushItemImportContext( GetImport(), nPrefix, rLocalName, xAttrList, _rUnitConv, RES_BACKGROUND ); } xBackground = pContext; } break; } if( !pContext ) pContext = SvXMLItemSetContext::CreateChildContext( nPrefix, rLocalName, xAttrList, _rItemSet, rEntry, _rUnitConv ); return pContext; } // --------------------------------------------------------------------- void SwXMLImport::_InitItemImport() { // #110680# pTwipUnitConv = new SvXMLUnitConverter( MAP_TWIP, MAP_TWIP, getServiceFactory() ); xTableItemMap = new SvXMLItemMapEntries( aXMLTableItemMap ); xTableColItemMap = new SvXMLItemMapEntries( aXMLTableColItemMap ); xTableRowItemMap = new SvXMLItemMapEntries( aXMLTableRowItemMap ); xTableCellItemMap = new SvXMLItemMapEntries( aXMLTableCellItemMap ); pTableItemMapper = new SwXMLImportTableItemMapper_Impl( xTableItemMap ); } void SwXMLImport::_FinitItemImport() { delete pTableItemMapper; delete pTwipUnitConv; } SvXMLImportContext *SwXMLImport::CreateTableItemImportContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList, sal_uInt16 nFamily, SfxItemSet& rItemSet ) { SvXMLItemMapEntriesRef xItemMap; switch( nFamily ) { case XML_STYLE_FAMILY_TABLE_TABLE: xItemMap = xTableItemMap; break; case XML_STYLE_FAMILY_TABLE_COLUMN: xItemMap = xTableColItemMap; break; case XML_STYLE_FAMILY_TABLE_ROW: xItemMap = xTableRowItemMap; break; case XML_STYLE_FAMILY_TABLE_CELL: xItemMap = xTableCellItemMap; break; } pTableItemMapper->setMapEntries( xItemMap ); return new SwXMLItemSetContext_Impl( *this, nPrefix, rLocalName, xAttrList, rItemSet, GetTableItemMapper(), GetTwipUnitConverter() ); } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "formeditorwidget.h" #include <QWheelEvent> #include <cmath> #include <QCoreApplication> #include <QPushButton> #include <QFile> #include <QVBoxLayout> #include <QActionGroup> #include <QGraphicsView> #include <toolbox.h> #include <zoomaction.h> #include <formeditorgraphicsview.h> #include <formeditorscene.h> #include <formeditorview.h> #include "numberseriesaction.h" namespace QmlDesigner { FormEditorWidget::FormEditorWidget(FormEditorView *view) : QWidget(), m_formEditorView(view) { QFile file(":/qmldesigner/stylesheet.css"); file.open(QFile::ReadOnly); QString styleSheet = QLatin1String(file.readAll()); setStyleSheet(styleSheet); QVBoxLayout *fillLayout = new QVBoxLayout(this); fillLayout->setMargin(0); fillLayout->setSpacing(0); setLayout(fillLayout); m_toolActionGroup = new QActionGroup(this); m_transformToolAction = m_toolActionGroup->addAction("Transform Tool (Press Key Q)"); m_transformToolAction->setShortcut(Qt::Key_Q); m_transformToolAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); m_transformToolAction->setCheckable(true); m_transformToolAction->setChecked(true); m_transformToolAction->setIcon(QPixmap(":/icon/tool/transform.png")); connect(m_transformToolAction.data(), SIGNAL(triggered(bool)), SLOT(changeTransformTool(bool))); m_anchorToolAction = m_toolActionGroup->addAction("Anchor Tool (Press Key W)"); m_anchorToolAction->setShortcut(Qt::Key_W); m_anchorToolAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); m_anchorToolAction->setCheckable(true); m_anchorToolAction->setIcon(QPixmap(":/icon/tool/anchor.png")); connect(m_anchorToolAction.data(), SIGNAL(triggered(bool)), SLOT(changeAnchorTool(bool))); addActions(m_toolActionGroup->actions()); QActionGroup *layoutActionGroup = new QActionGroup(this); layoutActionGroup->setExclusive(false); m_snappingToolAction = layoutActionGroup->addAction("Toogle Snapping (Press Key E)"); m_snappingToolAction->setShortcut(Qt::Key_E); m_snappingToolAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); m_snappingToolAction->setCheckable(true); m_snappingToolAction->setChecked(true); m_snappingToolAction->setIcon(QPixmap(":/icon/layout/snapping.png")); connect(m_snappingToolAction.data(), SIGNAL(triggered(bool)), SLOT(changeSnappingTool(bool))); m_showBoundingRectAction = layoutActionGroup->addAction("Toogle Bounding Rectangles (Press Key R)"); m_showBoundingRectAction->setShortcut(Qt::Key_R); m_showBoundingRectAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); m_showBoundingRectAction->setCheckable(true); m_showBoundingRectAction->setChecked(true); m_showBoundingRectAction->setIcon(QPixmap(":/icon/layout/boundingrect.png")); m_snappingMarginAction = new NumberSeriesAction(layoutActionGroup); m_snappingMarginAction->addEntry("no margins (0)", 0); m_snappingMarginAction->addEntry("small margin (2)", 2); m_snappingMarginAction->addEntry("medium margin (6)", 6); m_snappingMarginAction->addEntry("all in margin (10)", 10); m_snappingMarginAction->setCurrentEntryIndex(3); layoutActionGroup->addAction(m_snappingMarginAction.data()); addActions(layoutActionGroup->actions()); m_snappingSpacingAction = new NumberSeriesAction(layoutActionGroup); m_snappingSpacingAction->addEntry("no spacing (0)", 0); m_snappingSpacingAction->addEntry("small spacing (2)", 2); m_snappingSpacingAction->addEntry("medium spacing (4)", 4); m_snappingSpacingAction->addEntry("all in spacing (6)", 6); m_snappingSpacingAction->setCurrentEntryIndex(1); layoutActionGroup->addAction(m_snappingSpacingAction.data()); addActions(layoutActionGroup->actions()); m_zoomAction = new ZoomAction(toolActionGroup()); connect(m_zoomAction.data(), SIGNAL(zoomLevelChanged(double)), SLOT(setZoomLevel(double))); addAction(m_zoomAction.data()); QAction *separatorAction = new QAction(this); separatorAction->setSeparator(true); addAction(separatorAction); m_selectOnlyContentItemsAction = layoutActionGroup->addAction("Select Only Items with Content (Press Key T)"); m_selectOnlyContentItemsAction->setShortcut(Qt::Key_T); m_selectOnlyContentItemsAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); m_selectOnlyContentItemsAction->setCheckable(true); m_selectOnlyContentItemsAction->setChecked(true); m_selectOnlyContentItemsAction->setIcon(QPixmap(":/icon/selection/selectonlycontentitems.png")); addAction(m_selectOnlyContentItemsAction.data()); separatorAction = new QAction(toolActionGroup()); separatorAction->setSeparator(true); addAction(separatorAction); m_toolBox = new ToolBox(this); toolBox()->setActions(actions()); fillLayout->addWidget(toolBox()); m_graphicsView = new FormEditorGraphicsView(this); fillLayout->addWidget(m_graphicsView.data()); } void FormEditorWidget::enterEvent(QEvent *event) { setFocus(); QWidget::enterEvent(event); } void FormEditorWidget::changeTransformTool(bool checked) { if (checked) m_formEditorView->changeToTransformTools(); } void FormEditorWidget::changeAnchorTool(bool checked) { if (checked && m_formEditorView->currentState().isBaseState()) m_formEditorView->changeToAnchorTool(); } void FormEditorWidget::changeSnappingTool(bool /*checked*/) { // TODO } void FormEditorWidget::wheelEvent(QWheelEvent *event) { if (event->modifiers().testFlag(Qt::ControlModifier)) { if (event->delta() > 0) { zoomAction()->zoomIn(); } else { zoomAction()->zoomOut(); } event->accept(); } else { QWidget::wheelEvent(event); } } ZoomAction *FormEditorWidget::zoomAction() const { return m_zoomAction.data(); } QAction *FormEditorWidget::anchorToolAction() const { return m_anchorToolAction.data(); } QAction *FormEditorWidget::transformToolAction() const { return m_transformToolAction.data(); } QAction *FormEditorWidget::showBoundingRectAction() const { return m_showBoundingRectAction.data(); } QAction *FormEditorWidget::selectOnlyContentItemsAction() const { return m_selectOnlyContentItemsAction.data(); } void FormEditorWidget::setZoomLevel(double zoomLevel) { m_graphicsView->resetTransform(); m_graphicsView->scale(zoomLevel, zoomLevel); } void FormEditorWidget::setScene(FormEditorScene *scene) { m_graphicsView->setScene(scene); } QActionGroup *FormEditorWidget::toolActionGroup() const { return m_toolActionGroup.data(); } ToolBox *FormEditorWidget::toolBox() const { return m_toolBox.data(); } bool FormEditorWidget::isSnapButtonChecked() const { return m_snappingToolAction->isChecked(); } double FormEditorWidget::spacing() const { return m_snappingSpacingAction->currentValue().toDouble(); } double FormEditorWidget::margins() const { return m_snappingMarginAction->currentValue().toDouble(); } } <commit_msg>Set the focus to the graphics view<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "formeditorwidget.h" #include <QWheelEvent> #include <cmath> #include <QCoreApplication> #include <QPushButton> #include <QFile> #include <QVBoxLayout> #include <QActionGroup> #include <QGraphicsView> #include <toolbox.h> #include <zoomaction.h> #include <formeditorgraphicsview.h> #include <formeditorscene.h> #include <formeditorview.h> #include "numberseriesaction.h" namespace QmlDesigner { FormEditorWidget::FormEditorWidget(FormEditorView *view) : QWidget(), m_formEditorView(view) { QFile file(":/qmldesigner/stylesheet.css"); file.open(QFile::ReadOnly); QString styleSheet = QLatin1String(file.readAll()); setStyleSheet(styleSheet); QVBoxLayout *fillLayout = new QVBoxLayout(this); fillLayout->setMargin(0); fillLayout->setSpacing(0); setLayout(fillLayout); m_toolActionGroup = new QActionGroup(this); m_transformToolAction = m_toolActionGroup->addAction("Transform Tool (Press Key Q)"); m_transformToolAction->setShortcut(Qt::Key_Q); m_transformToolAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); m_transformToolAction->setCheckable(true); m_transformToolAction->setChecked(true); m_transformToolAction->setIcon(QPixmap(":/icon/tool/transform.png")); connect(m_transformToolAction.data(), SIGNAL(triggered(bool)), SLOT(changeTransformTool(bool))); m_anchorToolAction = m_toolActionGroup->addAction("Anchor Tool (Press Key W)"); m_anchorToolAction->setShortcut(Qt::Key_W); m_anchorToolAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); m_anchorToolAction->setCheckable(true); m_anchorToolAction->setIcon(QPixmap(":/icon/tool/anchor.png")); connect(m_anchorToolAction.data(), SIGNAL(triggered(bool)), SLOT(changeAnchorTool(bool))); addActions(m_toolActionGroup->actions()); QActionGroup *layoutActionGroup = new QActionGroup(this); layoutActionGroup->setExclusive(false); m_snappingToolAction = layoutActionGroup->addAction("Toogle Snapping (Press Key E)"); m_snappingToolAction->setShortcut(Qt::Key_E); m_snappingToolAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); m_snappingToolAction->setCheckable(true); m_snappingToolAction->setChecked(true); m_snappingToolAction->setIcon(QPixmap(":/icon/layout/snapping.png")); connect(m_snappingToolAction.data(), SIGNAL(triggered(bool)), SLOT(changeSnappingTool(bool))); m_showBoundingRectAction = layoutActionGroup->addAction("Toogle Bounding Rectangles (Press Key R)"); m_showBoundingRectAction->setShortcut(Qt::Key_R); m_showBoundingRectAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); m_showBoundingRectAction->setCheckable(true); m_showBoundingRectAction->setChecked(true); m_showBoundingRectAction->setIcon(QPixmap(":/icon/layout/boundingrect.png")); m_snappingMarginAction = new NumberSeriesAction(layoutActionGroup); m_snappingMarginAction->addEntry("no margins (0)", 0); m_snappingMarginAction->addEntry("small margin (2)", 2); m_snappingMarginAction->addEntry("medium margin (6)", 6); m_snappingMarginAction->addEntry("all in margin (10)", 10); m_snappingMarginAction->setCurrentEntryIndex(3); layoutActionGroup->addAction(m_snappingMarginAction.data()); addActions(layoutActionGroup->actions()); m_snappingSpacingAction = new NumberSeriesAction(layoutActionGroup); m_snappingSpacingAction->addEntry("no spacing (0)", 0); m_snappingSpacingAction->addEntry("small spacing (2)", 2); m_snappingSpacingAction->addEntry("medium spacing (4)", 4); m_snappingSpacingAction->addEntry("all in spacing (6)", 6); m_snappingSpacingAction->setCurrentEntryIndex(1); layoutActionGroup->addAction(m_snappingSpacingAction.data()); addActions(layoutActionGroup->actions()); m_zoomAction = new ZoomAction(toolActionGroup()); connect(m_zoomAction.data(), SIGNAL(zoomLevelChanged(double)), SLOT(setZoomLevel(double))); addAction(m_zoomAction.data()); QAction *separatorAction = new QAction(this); separatorAction->setSeparator(true); addAction(separatorAction); m_selectOnlyContentItemsAction = layoutActionGroup->addAction("Select Only Items with Content (Press Key T)"); m_selectOnlyContentItemsAction->setShortcut(Qt::Key_T); m_selectOnlyContentItemsAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); m_selectOnlyContentItemsAction->setCheckable(true); m_selectOnlyContentItemsAction->setChecked(true); m_selectOnlyContentItemsAction->setIcon(QPixmap(":/icon/selection/selectonlycontentitems.png")); addAction(m_selectOnlyContentItemsAction.data()); separatorAction = new QAction(toolActionGroup()); separatorAction->setSeparator(true); addAction(separatorAction); m_toolBox = new ToolBox(this); toolBox()->setActions(actions()); fillLayout->addWidget(toolBox()); m_graphicsView = new FormEditorGraphicsView(this); fillLayout->addWidget(m_graphicsView.data()); } void FormEditorWidget::enterEvent(QEvent *event) { m_graphicsView->setFocus(); QWidget::enterEvent(event); } void FormEditorWidget::changeTransformTool(bool checked) { if (checked) m_formEditorView->changeToTransformTools(); } void FormEditorWidget::changeAnchorTool(bool checked) { if (checked && m_formEditorView->currentState().isBaseState()) m_formEditorView->changeToAnchorTool(); } void FormEditorWidget::changeSnappingTool(bool /*checked*/) { // TODO } void FormEditorWidget::wheelEvent(QWheelEvent *event) { if (event->modifiers().testFlag(Qt::ControlModifier)) { if (event->delta() > 0) { zoomAction()->zoomIn(); } else { zoomAction()->zoomOut(); } event->accept(); } else { QWidget::wheelEvent(event); } } ZoomAction *FormEditorWidget::zoomAction() const { return m_zoomAction.data(); } QAction *FormEditorWidget::anchorToolAction() const { return m_anchorToolAction.data(); } QAction *FormEditorWidget::transformToolAction() const { return m_transformToolAction.data(); } QAction *FormEditorWidget::showBoundingRectAction() const { return m_showBoundingRectAction.data(); } QAction *FormEditorWidget::selectOnlyContentItemsAction() const { return m_selectOnlyContentItemsAction.data(); } void FormEditorWidget::setZoomLevel(double zoomLevel) { m_graphicsView->resetTransform(); m_graphicsView->scale(zoomLevel, zoomLevel); } void FormEditorWidget::setScene(FormEditorScene *scene) { m_graphicsView->setScene(scene); } QActionGroup *FormEditorWidget::toolActionGroup() const { return m_toolActionGroup.data(); } ToolBox *FormEditorWidget::toolBox() const { return m_toolBox.data(); } bool FormEditorWidget::isSnapButtonChecked() const { return m_snappingToolAction->isChecked(); } double FormEditorWidget::spacing() const { return m_snappingSpacingAction->currentValue().toDouble(); } double FormEditorWidget::margins() const { return m_snappingMarginAction->currentValue().toDouble(); } } <|endoftext|>
<commit_before>#include <pybind11/pybind11.h> #include <iostream> #include <sstream> #include <pybind11/numpy.h> #include "nifty/python/graph/undirected_list_graph.hxx" #include "nifty/python/graph/edge_contraction_graph.hxx" #include "nifty/python/graph/lifted_multicut/lifted_multicut_objective.hxx" #include "nifty/python/converter.hxx" namespace py = pybind11; namespace nifty{ namespace graph{ namespace lifted_multicut{ template<class GRAPH> void exportLiftedMulticutObjectiveT(py::module & liftedMulticutModule) { typedef GRAPH Graph; typedef LiftedMulticutObjective<Graph, double> ObjectiveType; typedef typename ObjectiveType::LiftedGraphType LiftedGraphType; const auto clsName = LiftedMulticutObjectiveName<ObjectiveType>::name(); auto liftedMulticutObjectiveCls = py::class_<ObjectiveType>(liftedMulticutModule, clsName.c_str()); liftedMulticutObjectiveCls .def_readonly("numberOfLiftedEdges", &ObjectiveType::numberOfLiftedEdges) .def("setCost", &ObjectiveType::setCost, py::arg("u"), py::arg("v"), py::arg("weight"), py::arg("overwrite") = false ) .def("setCosts",[] ( ObjectiveType & objective, nifty::marray::PyView<uint64_t> uvIds, nifty::marray::PyView<double> weights, bool overwrite = false ){ NIFTY_CHECK_OP(uvIds.dimension(),==,2,"wrong dimensions"); NIFTY_CHECK_OP(weights.dimension(),==,1,"wrong dimensions"); NIFTY_CHECK_OP(uvIds.shape(1),==,2,"wrong shape"); NIFTY_CHECK_OP(uvIds.shape(0),==,weights.shape(0),"wrong shape"); for(size_t i=0; i<uvIds.shape(0); ++i){ objective.setCost(uvIds(i,0), uvIds(i,1), weights(i)); } }) .def("evalNodeLabels",[](const ObjectiveType & objective, nifty::marray::PyView<uint64_t> array){ const auto & g = objective.graph(); NIFTY_CHECK_OP(array.dimension(),==,1,"wrong dimensions"); NIFTY_CHECK_OP(array.shape(0),==,g.nodeIdUpperBound()+1,"wrong shape"); double sum = static_cast<double>(0.0); const auto & w = objective.weights(); for(const auto edge: g.edges()){ const auto uv = g.uv(edge); if(array(uv.first) != array(uv.second)){ sum += w[edge]; } } return sum; }) .def_property_readonly("graph", &ObjectiveType::graph) .def_property_readonly("liftedGraph", [](const ObjectiveType & self) -> const LiftedGraphType & { return self.liftedGraph(); }, py::return_value_policy::reference_internal ) .def("_insertLiftedEdgesBfs", [](ObjectiveType & self, const uint32_t maxDistance){ self.insertLiftedEdgesBfs(maxDistance); }, py::arg("maxDistance") ) .def("_insertLiftedEdgesBfsReturnDist", [](ObjectiveType & self, const uint32_t maxDistance){ std::vector<uint32_t> dist; self.insertLiftedEdgesBfs(maxDistance, dist); nifty::marray::PyView<uint64_t> array({dist.size()}); for(size_t i=0; i<dist.size(); ++i){ array(i) = dist[i]; } return array; }, py::arg("maxDistance") ) ; liftedMulticutModule.def("liftedMulticutObjective", [](const Graph & graph){ auto obj = new ObjectiveType(graph); return obj; }, py::return_value_policy::take_ownership, py::keep_alive<0, 1>(), py::arg("graph") ); } void exportLiftedMulticutObjective(py::module & liftedMulticutModule) { { typedef PyUndirectedGraph GraphType; exportLiftedMulticutObjectiveT<GraphType>(liftedMulticutModule); } } } } } <commit_msg>LiftedMulticutObjective<commit_after>#include <pybind11/pybind11.h> #include <iostream> #include <sstream> #include <pybind11/numpy.h> #include "nifty/python/graph/undirected_list_graph.hxx" #include "nifty/python/graph/edge_contraction_graph.hxx" #include "nifty/python/graph/lifted_multicut/lifted_multicut_objective.hxx" #include "nifty/python/converter.hxx" namespace py = pybind11; namespace nifty{ namespace graph{ namespace lifted_multicut{ template<class GRAPH> void exportLiftedMulticutObjectiveT(py::module & liftedMulticutModule) { typedef GRAPH Graph; typedef LiftedMulticutObjective<Graph, double> ObjectiveType; typedef typename ObjectiveType::LiftedGraphType LiftedGraphType; const auto clsName = LiftedMulticutObjectiveName<ObjectiveType>::name(); auto liftedMulticutObjectiveCls = py::class_<ObjectiveType>(liftedMulticutModule, clsName.c_str()); liftedMulticutObjectiveCls .def_property_readonly("numberOfLiftedEdges", &ObjectiveType::numberOfLiftedEdges) .def("setCost", &ObjectiveType::setCost, py::arg("u"), py::arg("v"), py::arg("weight"), py::arg("overwrite") = false ) .def("setCosts",[] ( ObjectiveType & objective, nifty::marray::PyView<uint64_t> uvIds, nifty::marray::PyView<double> weights, bool overwrite = false ){ NIFTY_CHECK_OP(uvIds.dimension(),==,2,"wrong dimensions"); NIFTY_CHECK_OP(weights.dimension(),==,1,"wrong dimensions"); NIFTY_CHECK_OP(uvIds.shape(1),==,2,"wrong shape"); NIFTY_CHECK_OP(uvIds.shape(0),==,weights.shape(0),"wrong shape"); for(size_t i=0; i<uvIds.shape(0); ++i){ objective.setCost(uvIds(i,0), uvIds(i,1), weights(i)); } }) .def("evalNodeLabels",[](const ObjectiveType & objective, nifty::marray::PyView<uint64_t> array){ const auto & g = objective.graph(); NIFTY_CHECK_OP(array.dimension(),==,1,"wrong dimensions"); NIFTY_CHECK_OP(array.shape(0),==,g.nodeIdUpperBound()+1,"wrong shape"); double sum = static_cast<double>(0.0); const auto & w = objective.weights(); for(const auto edge: g.edges()){ const auto uv = g.uv(edge); if(array(uv.first) != array(uv.second)){ sum += w[edge]; } } return sum; }) .def_property_readonly("graph", &ObjectiveType::graph) .def_property_readonly("liftedGraph", [](const ObjectiveType & self) -> const LiftedGraphType & { return self.liftedGraph(); }, py::return_value_policy::reference_internal ) .def("_insertLiftedEdgesBfs", [](ObjectiveType & self, const uint32_t maxDistance){ self.insertLiftedEdgesBfs(maxDistance); }, py::arg("maxDistance") ) .def("_insertLiftedEdgesBfsReturnDist", [](ObjectiveType & self, const uint32_t maxDistance){ std::vector<uint32_t> dist; self.insertLiftedEdgesBfs(maxDistance, dist); nifty::marray::PyView<uint64_t> array({dist.size()}); for(size_t i=0; i<dist.size(); ++i){ array(i) = dist[i]; } return array; }, py::arg("maxDistance") ) ; liftedMulticutModule.def("liftedMulticutObjective", [](const Graph & graph){ auto obj = new ObjectiveType(graph); return obj; }, py::return_value_policy::take_ownership, py::keep_alive<0, 1>(), py::arg("graph") ); } void exportLiftedMulticutObjective(py::module & liftedMulticutModule) { { typedef PyUndirectedGraph GraphType; exportLiftedMulticutObjectiveT<GraphType>(liftedMulticutModule); } } } } } <|endoftext|>
<commit_before><commit_msg>Remove another NOTIMPLEMENTED<commit_after><|endoftext|>
<commit_before>// C++ code to reverse a string #include <bits/stdc++.h> using namespace std; // Reverse the string string RevString(string s[], int l) { // Check if number of words is even if (l % 2 == 0) { // Find the middle word int j = l / 2; // Starting from the middle // start swapping words at // jth position and l-1-j position while (j <= l - 1) { string temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } // Check if number of words is odd else { // Find the middle word int j = (l / 2) + 1; // Starting from the middle start // swapping the words at jth // position and l-1-j position while (j <= l - 1) { string temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } string S = s[0]; // Return the reversed sentence for(int i = 1; i < 9; i++) { S = S + " " + s[i]; } return S; } int main() { string s = "getting good at coding " "needs a lot of practice"; string words[] = { "getting", "good", "at", "coding", "needs", "a", "lot", "of", "practice"}; cout << RevString(words, 9) << endl; return 0; } // Time Complexity: O(n) // Output // practice of lot a needs coding at good getting <commit_msg>Added Reverse_words_in_a_given_string.cpp<commit_after>// C++ code to reverse a string /* Test Cases: 1. Input: S = i like this program very much Output: much very program this like i Explanation: After reversing the whole string(not individual words), the input string becomes much very program this like i 2. Input: S = pqr mno Output: mno pqr Explanation: After reversing the whole string , the input string becomes mno pqr */ #include <bits/stdc++.h> using namespace std; // Reverse the string string RevString(string s[], int l) { // Check if number of words is even if (l % 2 == 0) { // Find the middle word int j = l / 2; // Starting from the middle // start swapping words at // jth position and l-1-j position while (j <= l - 1) { string temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } // Check if number of words is odd else { // Find the middle word int j = (l / 2) + 1; // Starting from the middle start // swapping the words at jth // position and l-1-j position while (j <= l - 1) { string temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } string S = s[0]; // Return the reversed sentence for(int i = 1; i < 9; i++) { S = S + " " + s[i]; } return S; } int main() { string s = "getting good at coding " "needs a lot of practice"; string words[] = { "getting", "good", "at", "coding", "needs", "a", "lot", "of", "practice"}; cout << RevString(words, 9) << endl; return 0; } // Time Complexity: O(n) // Output // practice of lot a needs coding at good getting <|endoftext|>
<commit_before>// This header intentionally has no include guards. class extracted_ptree { public: extracted_ptree(const xml_compiler& xml_compiler, const pqrs::string::replacement& replacement, const boost::property_tree::ptree& pt, const std::string& xml_file_path) : xml_compiler_(xml_compiler), replacement_(replacement), pt_(pt), included_files_ptr_(new std::deque<std::string>), included_files_(*included_files_ptr_) { included_files_.push_back(xml_file_path); } class node { public: node(const boost::property_tree::ptree::value_type& node, const extracted_ptree& extracted_ptree, const pqrs::string::replacement& replacement) : node_(node), extracted_ptree_(extracted_ptree), replacement_(replacement) {} const std::string& get_tag_name(void) const { return node_.first; } const std::string& get_data(void) const { return node_.second.data(); } boost::optional<std::string> get_optional(const std::string& path) const { return node_.second.get_optional<std::string>(path); } bool children_empty(void) const { return node_.second.empty(); } extracted_ptree children_extracted_ptree(void) const { return extracted_ptree(extracted_ptree_, replacement_, node_.second); } private: const boost::property_tree::ptree::value_type& node_; const extracted_ptree& extracted_ptree_; const pqrs::string::replacement& replacement_; }; class extracted_ptree_iterator : public boost::iterator_facade<extracted_ptree_iterator, const node, boost::forward_traversal_tag> { public: extracted_ptree_iterator(const extracted_ptree& extracted_ptree) : extracted_ptree_(extracted_ptree) {} extracted_ptree_iterator(const extracted_ptree& extracted_ptree, const pqrs::string::replacement& replacement, const boost::property_tree::ptree& pt) : extracted_ptree_(extracted_ptree) { if (! pt.empty()) { stack_.push(stack_data(pt, replacement)); extract_include_(); } } private: friend class boost::iterator_core_access; void increment(void); const node dereference(void) const; bool equal(const extracted_ptree_iterator const& other) const; void extract_include_(void); void collapse_(void); class stack_data { public: stack_data(const boost::property_tree::ptree& pt, const pqrs::string::replacement& r) : it(pt.begin()), end(pt.end()), parent_replacement(r) {} // For extracted ptree. stack_data(const ptree_ptr& p, const std::tr1::shared_ptr<pqrs::string::replacement>& r, const boost::property_tree::ptree& root_children) : it(root_children.begin()), end(root_children.end()), parent_replacement(*r), pt_ptr_(p), replacement_ptr_(r) {} boost::property_tree::ptree::const_iterator it; boost::property_tree::ptree::const_iterator end; const pqrs::string::replacement& parent_replacement; bool extracted(void) const { return pt_ptr_; } private: // Keep extracted ptree_ptr, replacement_ptr until we finish traversing. const ptree_ptr pt_ptr_; const std::tr1::shared_ptr<pqrs::string::replacement> replacement_ptr_; }; const extracted_ptree& extracted_ptree_; std::stack<stack_data> stack_; }; extracted_ptree_iterator begin(void) const { return extracted_ptree_iterator(*this, replacement_, pt_); } extracted_ptree_iterator end(void) const { return extracted_ptree_iterator(*this); } private: extracted_ptree(const extracted_ptree& extracted_ptree, const pqrs::string::replacement& replacement, const boost::property_tree::ptree& pt) : xml_compiler_(extracted_ptree.xml_compiler_), replacement_(replacement), pt_(pt), included_files_(extracted_ptree.included_files_) {} const xml_compiler& xml_compiler_; const pqrs::string::replacement& replacement_; const boost::property_tree::ptree& pt_; // shared_ptr for included_files_. std::tr1::shared_ptr<std::deque<std::string> > included_files_ptr_; mutable std::deque<std::string> included_files_; }; <commit_msg>improved xml_compiler around extracted_ptree<commit_after>// This header intentionally has no include guards. class extracted_ptree { public: extracted_ptree(const xml_compiler& xml_compiler, const pqrs::string::replacement& replacement, const boost::property_tree::ptree& pt, const std::string& xml_file_path) : xml_compiler_(xml_compiler), replacement_(replacement), pt_(pt), included_files_ptr_(new std::deque<std::string>), included_files_(*included_files_ptr_) { included_files_.push_back(xml_file_path); } class node { public: node(const boost::property_tree::ptree::value_type& node, const extracted_ptree& extracted_ptree, const pqrs::string::replacement& replacement) : node_(node), extracted_ptree_(extracted_ptree), replacement_(replacement) {} const std::string& get_tag_name(void) const { return node_.first; } const std::string& get_data(void) const { return node_.second.data(); } boost::optional<std::string> get_optional(const std::string& path) const { return node_.second.get_optional<std::string>(path); } bool children_empty(void) const { return node_.second.empty(); } extracted_ptree children_extracted_ptree(void) const { return extracted_ptree(extracted_ptree_, replacement_, node_.second); } private: const boost::property_tree::ptree::value_type& node_; const extracted_ptree& extracted_ptree_; const pqrs::string::replacement& replacement_; }; class extracted_ptree_iterator : public boost::iterator_facade<extracted_ptree_iterator, const node, boost::forward_traversal_tag> { public: extracted_ptree_iterator(const extracted_ptree& extracted_ptree) : extracted_ptree_(extracted_ptree) {} extracted_ptree_iterator(const extracted_ptree& extracted_ptree, const pqrs::string::replacement& replacement, const boost::property_tree::ptree& pt) : extracted_ptree_(extracted_ptree) { if (! pt.empty()) { stack_.push(stack_data(pt, replacement)); extract_include_(); } } private: friend class boost::iterator_core_access; void increment(void); const node dereference(void) const; bool equal(const extracted_ptree_iterator const& other) const; void extract_include_(void); void collapse_(void); class stack_data { public: stack_data(const boost::property_tree::ptree& pt, const pqrs::string::replacement& r) : it(pt.begin()), end(pt.end()), parent_replacement(r) {} // For extracted ptree. stack_data(const ptree_ptr& p, const std::tr1::shared_ptr<pqrs::string::replacement>& r, const boost::property_tree::ptree& root_children) : it(root_children.begin()), end(root_children.end()), parent_replacement(*r), pt_ptr_(p), replacement_ptr_(r) {} boost::property_tree::ptree::const_iterator it; boost::property_tree::ptree::const_iterator end; const pqrs::string::replacement& parent_replacement; bool extracted(void) const { return pt_ptr_; } private: // Keep extracted ptree_ptr, replacement_ptr until we finish traversing. const ptree_ptr pt_ptr_; const std::tr1::shared_ptr<pqrs::string::replacement> replacement_ptr_; }; const extracted_ptree& extracted_ptree_; std::stack<stack_data> stack_; }; extracted_ptree_iterator begin(void) const { return extracted_ptree_iterator(*this, replacement_, pt_); } extracted_ptree_iterator end(void) const { return extracted_ptree_iterator(*this); } private: extracted_ptree(const extracted_ptree& extracted_ptree, const pqrs::string::replacement& replacement, const boost::property_tree::ptree& pt) : xml_compiler_(extracted_ptree.xml_compiler_), replacement_(replacement), pt_(pt), included_files_(extracted_ptree.included_files_) {} const xml_compiler& xml_compiler_; const pqrs::string::replacement& replacement_; const boost::property_tree::ptree& pt_; // shared_ptr for included_files_. std::tr1::shared_ptr<std::deque<std::string> > included_files_ptr_; std::deque<std::string>& included_files_; }; <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2003-2012 \file chart_doc.cpp \author \date 20.02.2003 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH #include "app/rdo_studio/pch/stdpch.h" // ----------------------------------------------------------------------- INCLUDES #include <algorithm> #include <boost/bind.hpp> #include <boost/range/algorithm/find_if.hpp> #include <boost/range/algorithm/for_each.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "app/rdo_studio/src/tracer/chart/chart_doc.h" #include "app/rdo_studio/src/tracer/chart/chart_view.h" #include "app/rdo_studio/src/tracer/tracer.h" #include "app/rdo_studio/src/tracer/tracer_serie.h" #include "app/rdo_studio/src/tracer/tracer_values.h" #include "app/rdo_studio/src/application.h" #include "app/rdo_studio/src/main_windows_base.h" // -------------------------------------------------------------------------------- #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif using namespace rdo::gui::tracer; ruint ChartDoc::s_titleIndex = 0; ChartDoc::ChartDoc(const rbool preview) : m_minTimeOffset(1.7E+308) , m_ticksCount(0) , m_previewMode(preview) { if (!m_previewMode) { g_pTracer->addChart(this); } } ChartDoc::~ChartDoc() { for (std::vector<ChartSerie*>::iterator it = m_serieList.begin(); it != m_serieList.end(); it++) { (*it)->getSerie()->removeFromDoc(this); } if (!m_previewMode) { g_pTracer->removeChart(this); } } CREF(ChartDoc::TimesList) ChartDoc::getTimes() const { return m_docTimes; } CREF(ChartDoc::SerieList) ChartDoc::getSerieList() const { return m_serieList; } void ChartDoc::attachView(ChartView* pView) { m_viewList.push_back(pView); } ChartView* ChartDoc::getFirstView() { return m_viewList.empty() ? NULL : m_viewList.front(); } void ChartDoc::setStyle(ChartViewStyle* pStyle) { ASSERT(pStyle); boost::range::for_each(m_viewList, boost::bind(&ChartView::setStyle, _1, pStyle, true)); } void ChartDoc::updateAllViews() { boost::range::for_each(m_viewList, boost::bind(&ChartView::updateView, _1)); } int ChartDoc::getSerieIndex(ChartSerie* serie) const { int res = -1; int index = 0; for (std::vector<ChartSerie*>::const_iterator it = m_serieList.begin(); it != m_serieList.end(); it++) { if (serie == (*it)) { res = index; } index++; } return res; } void ChartDoc::incTimeEventsCount(Time* time) { if (!m_docTimes.empty() && m_docTimes.back() == time) { m_ticksCount++; updateChartViews (UPDATE_TIMETICKS); } } rbool ChartDoc::newValueToSerieAdded(Value* val) { if (m_docTimes.empty()) { m_docTimes.push_back(val->getModelTime()); m_ticksCount += val->getModelTime()->eventCount; } else { Time* last = m_docTimes.back(); if (last != val->getModelTime()) { m_docTimes.push_back(val->getModelTime()); m_ticksCount += val->getModelTime()->eventCount; double off = val->getModelTime()->time - last->time; if (off < m_minTimeOffset) { m_minTimeOffset = off; } } } updateChartViews (UPDATE_NEWVALUE); return true; } int ChartDoc::getMaxMarkerSize() const { int res = 0; for (std::vector<ChartSerie*>::const_iterator it = m_serieList.begin(); it != m_serieList.end(); it++) { if ((*it)->options().markerNeedDraw && (*it)->options().markerSize > res) { res = (*it)->options().markerSize; } } return res; } int ChartDoc::getTicksCount() const { return m_ticksCount; } double ChartDoc::getMinTimeOffset() const { return m_minTimeOffset; } void ChartDoc::addToViews(ChartView* pWidget) { m_widgetList.push_back(pWidget); } void ChartDoc::removeFromViews(ChartView* pWidget) { std::vector<ChartView*>::iterator it = std::find(m_widgetList.begin(), m_widgetList.end(), pWidget); if (it != m_widgetList.end()) { m_widgetList.erase(it); } } void ChartDoc::updateChartViews(ruint updateType) const { boost::range::for_each(m_widgetList, boost::bind(&ChartView::onUserUpdateChartView, _1, updateType)); } void ChartDoc::addSerie(CREF(LPSerie) pSerie) { if (pSerie && !serieExists(pSerie)) { ChartSerie* pDocSerie = new ChartSerie(pSerie); ChartSerie::Options options(pDocSerie->options()); options.color = selectColor(); options.markerType = selectMarker(); pDocSerie->setOptions(options); m_serieList.push_back(pDocSerie); m_insertedIt = m_docTimes.begin(); if (!m_docTimes.empty() && !pSerie->empty()) { TimesList::iterator lastDocIt = m_docTimes.end(); --lastDocIt; Serie::ValuesList::const_iterator first_serie = pSerie->begin(); if ((*first_serie)->getModelTime()->time >= (*lastDocIt)->time) { m_insertedIt = m_docTimes.end(); if ((*first_serie)->getModelTime()->time == (*lastDocIt)->time) { m_insertedIt = lastDocIt; } } } try { studioApp.BeginWaitCursor(); std::for_each(pSerie->begin(), pSerie->end(), boost::bind(&ChartDoc::insertValue, this, _1)); studioApp.EndWaitCursor(); } catch (...) { studioApp.EndWaitCursor(); } pSerie->addToDoc(this); if (m_serieList.size() == 1) { ChartView* pView = getFirstView(); ASSERT(pView); pView->setYAxis(pDocSerie); } updateChartViews(UPDATE_NEWSERIE); } } COLORREF ChartDoc::selectColor() { int count = m_serieList.size(); int mul = count / 15; int index = count - mul * 16; COLORREF res = RGB(0, 0, 0); switch (index) { case 0: res = RGB(0x00, 0x80, 0x00); break; case 1: res = RGB(0x00, 0x00, 0x80); break; case 2: res = RGB(0x80, 0x80, 0x80); break; case 3: res = RGB(0x80, 0x00, 0x80); break; case 4: res = RGB(0xFF, 0x00, 0x00); break; case 5: res = RGB(0x00, 0xFF, 0x00); break; case 6: res = RGB(0x00, 0x00, 0x00); break; case 7: res = RGB(0x80, 0x80, 0x00); break; case 8: res = RGB(0xC0, 0xC0, 0xC0); break; case 9: res = RGB(0x80, 0x00, 0x00); break; case 10: res = RGB(0x00, 0x80, 0x80); break; case 11: res = RGB(0xFF, 0xFF, 0x00); break; case 12: res = RGB(0x00, 0x00, 0xFF); break; case 13: res = RGB(0xFF, 0x00, 0xFF); break; case 14: res = RGB(0x00, 0xFF, 0xFF); break; }; return res; } Serie::Marker ChartDoc::selectMarker() { int count = m_serieList.size(); int mul = count / 4; int index = count - mul * 4; Serie::Marker res = Serie::M_CIRCLE; switch (index) { case 0: res = Serie::M_CIRCLE; break; case 1: res = Serie::M_SQUARE; break; case 2: res = Serie::M_TRIANG; break; case 3: res = Serie::M_CROSS; break; }; return res; } rbool ChartDoc::serieExists(CREF(LPSerie) pSerie) const { return boost::range::find_if(m_serieList, boost::bind(&ChartSerie::isTracerSerie, _1, pSerie)) != m_serieList.end(); } tstring ChartDoc::getTitle() const { return m_title; } void ChartDoc::setTitle(CREF(tstring) title) { this->m_title = title; getFirstView()->parentWidget()->setWindowTitle(QString::fromLocal8Bit(rdo::format(IDS_CHART_TITLE, this->m_title.c_str()).c_str())); } void ChartDoc::autoTitle() { tstring title = rdo::format("%d", ++s_titleIndex); setTitle(title); } void ChartDoc::resetTitleIndex() { s_titleIndex = 0; } void ChartDoc::insertValue(Value* pValue) { if (pValue) { ChartDoc::TimesList::iterator it = std::find_if(m_insertedIt, m_docTimes.end(), std::bind2nd(std::mem_fun1(&Time::compareTimes), pValue->getModelTime())); if (it == m_docTimes.end() || (*it) != pValue->getModelTime()) { m_insertedIt = m_docTimes.insert(it, pValue->getModelTime()); m_ticksCount += pValue->getModelTime()->eventCount; double offl = 1.7E+308; double offr = 1.7E+308; if (it != m_docTimes.end()) { offr = (*it)->time - (*m_insertedIt)->time; } if (m_insertedIt != m_docTimes.begin()) { offl = (*m_insertedIt)->time; TimesList::iterator prev_it = m_insertedIt; prev_it--; offl -= (*prev_it)->time; } double minoff = std::min(offl, offr); if (minoff < m_minTimeOffset) { m_minTimeOffset = minoff; } } } } <commit_msg> - tstring -> QString<commit_after>/*! \copyright (c) RDO-Team, 2003-2012 \file chart_doc.cpp \author \date 20.02.2003 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH #include "app/rdo_studio/pch/stdpch.h" // ----------------------------------------------------------------------- INCLUDES #include <algorithm> #include <boost/bind.hpp> #include <boost/range/algorithm/find_if.hpp> #include <boost/range/algorithm/for_each.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "app/rdo_studio/src/tracer/chart/chart_doc.h" #include "app/rdo_studio/src/tracer/chart/chart_view.h" #include "app/rdo_studio/src/tracer/tracer.h" #include "app/rdo_studio/src/tracer/tracer_serie.h" #include "app/rdo_studio/src/tracer/tracer_values.h" #include "app/rdo_studio/src/application.h" #include "app/rdo_studio/src/main_windows_base.h" // -------------------------------------------------------------------------------- #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif using namespace rdo::gui::tracer; ruint ChartDoc::s_titleIndex = 0; ChartDoc::ChartDoc(const rbool preview) : m_minTimeOffset(1.7E+308) , m_ticksCount(0) , m_previewMode(preview) { if (!m_previewMode) { g_pTracer->addChart(this); } } ChartDoc::~ChartDoc() { for (std::vector<ChartSerie*>::iterator it = m_serieList.begin(); it != m_serieList.end(); it++) { (*it)->getSerie()->removeFromDoc(this); } if (!m_previewMode) { g_pTracer->removeChart(this); } } CREF(ChartDoc::TimesList) ChartDoc::getTimes() const { return m_docTimes; } CREF(ChartDoc::SerieList) ChartDoc::getSerieList() const { return m_serieList; } void ChartDoc::attachView(ChartView* pView) { m_viewList.push_back(pView); } ChartView* ChartDoc::getFirstView() { return m_viewList.empty() ? NULL : m_viewList.front(); } void ChartDoc::setStyle(ChartViewStyle* pStyle) { ASSERT(pStyle); boost::range::for_each(m_viewList, boost::bind(&ChartView::setStyle, _1, pStyle, true)); } void ChartDoc::updateAllViews() { boost::range::for_each(m_viewList, boost::bind(&ChartView::updateView, _1)); } int ChartDoc::getSerieIndex(ChartSerie* serie) const { int res = -1; int index = 0; for (std::vector<ChartSerie*>::const_iterator it = m_serieList.begin(); it != m_serieList.end(); it++) { if (serie == (*it)) { res = index; } index++; } return res; } void ChartDoc::incTimeEventsCount(Time* time) { if (!m_docTimes.empty() && m_docTimes.back() == time) { m_ticksCount++; updateChartViews (UPDATE_TIMETICKS); } } rbool ChartDoc::newValueToSerieAdded(Value* val) { if (m_docTimes.empty()) { m_docTimes.push_back(val->getModelTime()); m_ticksCount += val->getModelTime()->eventCount; } else { Time* last = m_docTimes.back(); if (last != val->getModelTime()) { m_docTimes.push_back(val->getModelTime()); m_ticksCount += val->getModelTime()->eventCount; double off = val->getModelTime()->time - last->time; if (off < m_minTimeOffset) { m_minTimeOffset = off; } } } updateChartViews (UPDATE_NEWVALUE); return true; } int ChartDoc::getMaxMarkerSize() const { int res = 0; for (std::vector<ChartSerie*>::const_iterator it = m_serieList.begin(); it != m_serieList.end(); it++) { if ((*it)->options().markerNeedDraw && (*it)->options().markerSize > res) { res = (*it)->options().markerSize; } } return res; } int ChartDoc::getTicksCount() const { return m_ticksCount; } double ChartDoc::getMinTimeOffset() const { return m_minTimeOffset; } void ChartDoc::addToViews(ChartView* pWidget) { m_widgetList.push_back(pWidget); } void ChartDoc::removeFromViews(ChartView* pWidget) { std::vector<ChartView*>::iterator it = std::find(m_widgetList.begin(), m_widgetList.end(), pWidget); if (it != m_widgetList.end()) { m_widgetList.erase(it); } } void ChartDoc::updateChartViews(ruint updateType) const { boost::range::for_each(m_widgetList, boost::bind(&ChartView::onUserUpdateChartView, _1, updateType)); } void ChartDoc::addSerie(CREF(LPSerie) pSerie) { if (pSerie && !serieExists(pSerie)) { ChartSerie* pDocSerie = new ChartSerie(pSerie); ChartSerie::Options options(pDocSerie->options()); options.color = selectColor(); options.markerType = selectMarker(); pDocSerie->setOptions(options); m_serieList.push_back(pDocSerie); m_insertedIt = m_docTimes.begin(); if (!m_docTimes.empty() && !pSerie->empty()) { TimesList::iterator lastDocIt = m_docTimes.end(); --lastDocIt; Serie::ValuesList::const_iterator first_serie = pSerie->begin(); if ((*first_serie)->getModelTime()->time >= (*lastDocIt)->time) { m_insertedIt = m_docTimes.end(); if ((*first_serie)->getModelTime()->time == (*lastDocIt)->time) { m_insertedIt = lastDocIt; } } } try { studioApp.BeginWaitCursor(); std::for_each(pSerie->begin(), pSerie->end(), boost::bind(&ChartDoc::insertValue, this, _1)); studioApp.EndWaitCursor(); } catch (...) { studioApp.EndWaitCursor(); } pSerie->addToDoc(this); if (m_serieList.size() == 1) { ChartView* pView = getFirstView(); ASSERT(pView); pView->setYAxis(pDocSerie); } updateChartViews(UPDATE_NEWSERIE); } } COLORREF ChartDoc::selectColor() { int count = m_serieList.size(); int mul = count / 15; int index = count - mul * 16; COLORREF res = RGB(0, 0, 0); switch (index) { case 0: res = RGB(0x00, 0x80, 0x00); break; case 1: res = RGB(0x00, 0x00, 0x80); break; case 2: res = RGB(0x80, 0x80, 0x80); break; case 3: res = RGB(0x80, 0x00, 0x80); break; case 4: res = RGB(0xFF, 0x00, 0x00); break; case 5: res = RGB(0x00, 0xFF, 0x00); break; case 6: res = RGB(0x00, 0x00, 0x00); break; case 7: res = RGB(0x80, 0x80, 0x00); break; case 8: res = RGB(0xC0, 0xC0, 0xC0); break; case 9: res = RGB(0x80, 0x00, 0x00); break; case 10: res = RGB(0x00, 0x80, 0x80); break; case 11: res = RGB(0xFF, 0xFF, 0x00); break; case 12: res = RGB(0x00, 0x00, 0xFF); break; case 13: res = RGB(0xFF, 0x00, 0xFF); break; case 14: res = RGB(0x00, 0xFF, 0xFF); break; }; return res; } Serie::Marker ChartDoc::selectMarker() { int count = m_serieList.size(); int mul = count / 4; int index = count - mul * 4; Serie::Marker res = Serie::M_CIRCLE; switch (index) { case 0: res = Serie::M_CIRCLE; break; case 1: res = Serie::M_SQUARE; break; case 2: res = Serie::M_TRIANG; break; case 3: res = Serie::M_CROSS; break; }; return res; } rbool ChartDoc::serieExists(CREF(LPSerie) pSerie) const { return boost::range::find_if(m_serieList, boost::bind(&ChartSerie::isTracerSerie, _1, pSerie)) != m_serieList.end(); } tstring ChartDoc::getTitle() const { return m_title; } void ChartDoc::setTitle(CREF(tstring) title) { this->m_title = title; getFirstView()->parentWidget()->setWindowTitle(QString::fromStdWString(L": %1").arg(this->m_title.c_str())); } void ChartDoc::autoTitle() { tstring title = rdo::format("%d", ++s_titleIndex); setTitle(title); } void ChartDoc::resetTitleIndex() { s_titleIndex = 0; } void ChartDoc::insertValue(Value* pValue) { if (pValue) { ChartDoc::TimesList::iterator it = std::find_if(m_insertedIt, m_docTimes.end(), std::bind2nd(std::mem_fun1(&Time::compareTimes), pValue->getModelTime())); if (it == m_docTimes.end() || (*it) != pValue->getModelTime()) { m_insertedIt = m_docTimes.insert(it, pValue->getModelTime()); m_ticksCount += pValue->getModelTime()->eventCount; double offl = 1.7E+308; double offr = 1.7E+308; if (it != m_docTimes.end()) { offr = (*it)->time - (*m_insertedIt)->time; } if (m_insertedIt != m_docTimes.begin()) { offl = (*m_insertedIt)->time; TimesList::iterator prev_it = m_insertedIt; prev_it--; offl -= (*prev_it)->time; } double minoff = std::min(offl, offr); if (minoff < m_minTimeOffset) { m_minTimeOffset = minoff; } } } } <|endoftext|>
<commit_before><commit_msg>am 931f6f87: Merge "Fix another off-by-one error in ZipFileRO" into klp-dev<commit_after><|endoftext|>
<commit_before>/* This file is part of kdepim. Copyright (c) 2004 Cornelius Schumacher <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <interfaces/bodypartformatter.h> #include <interfaces/bodypart.h> #include <interfaces/bodyparturlhandler.h> #include <khtmlparthtmlwriter.h> #include <libkcal/calendarlocal.h> #include <libkcal/icalformat.h> #include <libkcal/attendee.h> #include <libkcal/incidence.h> #include <libkcal/incidenceformatter.h> #include <kpimprefs.h> // for the timezone #include <kmail/callback.h> #include <kmail/kmmessage.h> #include <kmail/kmcommands.h> #include <email.h> #include <kglobal.h> #include <klocale.h> #include <kstringhandler.h> #include <kglobalsettings.h> #include <kiconloader.h> #include <kdebug.h> #include <kdcopservicestarter.h> #include <kmessagebox.h> #include <kstandarddirs.h> #include <kapplication.h> #include <ktempfile.h> #include <qurl.h> #include <qdir.h> #include <qtextstream.h> #include <kdepimmacros.h> #include <dcopclient.h> #include <dcopref.h> using namespace KCal; namespace { class KMInvitationFormatterHelper : public KCal::InvitationFormatterHelper { public: KMInvitationFormatterHelper( KMail::Interface::BodyPart *bodyPart ) : mBodyPart( bodyPart ) {} virtual QString generateLinkURL( const QString &id ) { return mBodyPart->makeLink( id ); } private: KMail::Interface::BodyPart *mBodyPart; }; class Formatter : public KMail::Interface::BodyPartFormatter { public: Result format( KMail::Interface::BodyPart *bodyPart, KMail::HtmlWriter *writer ) const { if ( !writer ) // Guard against crashes in createReply() return Ok; CalendarLocal cl( KPimPrefs::timezone() ); KMInvitationFormatterHelper helper( bodyPart ); QString source; /* If the bodypart does not have a charset specified, we need to fall back to utf8, not the KMail fallback encoding, so get the contents as binary and decode explicitely. */ if ( bodyPart->contentTypeParameter( "charset").isEmpty() ) { const QByteArray &ba = bodyPart->asBinary(); source = QString::fromUtf8(ba); } else { source = bodyPart->asText(); } QString html = IncidenceFormatter::formatICalInvitation( source, &cl, &helper ); if ( html.isEmpty() ) return AsIcon; writer->queue( html ); return Ok; } }; class UrlHandler : public KMail::Interface::BodyPartURLHandler { public: UrlHandler() { kdDebug() << "UrlHandler() (iCalendar)" << endl; } Incidence* icalToString( const QString& iCal ) const { CalendarLocal calendar( KPimPrefs::timezone() ) ; ICalFormat format; ScheduleMessage *message = format.parseScheduleMessage( &calendar, iCal ); if ( !message ) //TODO: Error message? return 0; return dynamic_cast<Incidence*>( message->event() ); } Attendee *findMyself( Incidence* incidence, const QString& receiver ) const { Attendee::List attendees = incidence->attendees(); Attendee::List::ConstIterator it; Attendee* myself = 0; // Find myself. There will always be all attendees listed, even if // only I need to answer it. if ( attendees.count() == 1 ) // Only one attendee, that must be me myself = *attendees.begin(); else { for ( it = attendees.begin(); it != attendees.end(); ++it ) { // match only the email part, not the name if( KPIM::compareEmail( (*it)->email(), receiver, false ) ) { // We are the current one, and even the receiver, note // this and quit searching. myself = (*it); break; } } } return myself; } static bool heuristicalRSVP( Incidence *incidence ) { bool rsvp = true; // better send superfluously than not at all Attendee::List attendees = incidence->attendees(); Attendee::List::ConstIterator it; for ( it = attendees.begin(); it != attendees.end(); ++it ) { if ( it == attendees.begin() ) { rsvp = (*it)->RSVP(); // use what the first one has } else { if ( (*it)->RSVP() != rsvp ) { rsvp = true; // they differ, default break; } } } return rsvp; } static Attendee::Role heuristicalRole( Incidence *incidence ) { Attendee::Role role = Attendee::OptParticipant; Attendee::List attendees = incidence->attendees(); Attendee::List::ConstIterator it; for ( it = attendees.begin(); it != attendees.end(); ++it ) { if ( it == attendees.begin() ) { role = (*it)->role(); // use what the first one has } else { if ( (*it)->role() != role ) { role = Attendee::OptParticipant; // they differ, default break; } } } return role; } void setStatusOnMyself( Incidence* incidence, Attendee* myself, Attendee::PartStat status, const QString &receiver ) const { Attendee* newMyself = 0; QString name; QString email; KPIM::getNameAndMail( receiver, name, email ); if ( name.isEmpty() && myself ) name = myself->name(); if ( email.isEmpty()&& myself ) email = myself->email(); Q_ASSERT( !email.isEmpty() ); // delivery must be possible newMyself = new Attendee( name, email, true, // RSVP, otherwise we would not be here status, myself ? myself->role() : heuristicalRole( incidence ), myself ? myself->uid() : QString::null ); // Make sure only ourselves is in the event incidence->clearAttendees(); if( newMyself ) incidence->addAttendee( newMyself ); } bool mail( Incidence* incidence, KMail::Callback& callback ) const { ICalFormat format; format.setTimeZone( KPimPrefs::timezone(), false ); QString msg = format.createScheduleMessage( incidence, Scheduler::Reply ); QString subject; if ( !incidence->summary().isEmpty() ) subject = i18n( "Answer: %1" ).arg( incidence->summary() ); else subject = i18n( "Answer: Incidence with no summary" ); return callback.mailICal( incidence->organizer().fullName(), msg, subject ); } bool saveFile( const QString& receiver, const QString& iCal, const QString& type ) const { KTempFile file( locateLocal( "data", "korganizer/income." + type + '/', true ) ); QTextStream* ts = file.textStream(); if ( !ts ) { KMessageBox::error( 0, i18n("Could not save file to KOrganizer") ); return false; } ts->setEncoding( QTextStream::UnicodeUTF8 ); (*ts) << receiver << '\n' << iCal; file.close(); // Now ensure that korganizer is running; otherwise start it, to prevent surprises // (https://intevation.de/roundup/kolab/issue758) QString error; QCString dcopService; int result = KDCOPServiceStarter::self()->findServiceFor( "DCOP/Organizer", QString::null, QString::null, &error, &dcopService ); if ( result == 0 ) { // OK, so korganizer (or kontact) is running. Now ensure the object we want is available // [that's not the case when kontact was already running, but korganizer not loaded into it...] static const char* const dcopObjectId = "KOrganizerIface"; QCString dummy; if ( !kapp->dcopClient()->findObject( dcopService, dcopObjectId, "", QByteArray(), dummy, dummy ) ) { DCOPRef ref( dcopService, dcopService ); // talk to the KUniqueApplication or its kontact wrapper DCOPReply reply = ref.call( "load()" ); if ( reply.isValid() && (bool)reply ) { kdDebug() << "Loaded " << dcopService << " successfully" << endl; Q_ASSERT( kapp->dcopClient()->findObject( dcopService, dcopObjectId, "", QByteArray(), dummy, dummy ) ); } else kdWarning() << "Error loading " << dcopService << endl; } // We don't do anything with it, we just need it to be running so that it handles // the incoming directory. } else kdWarning() << "Couldn't start DCOP/Organizer: " << dcopService << " " << error << endl; return true; } bool handleInvitation( const QString& iCal, Attendee::PartStat status, KMail::Callback &callback ) const { bool ok = true; const QString receiver = callback.receiver(); if ( receiver.isEmpty() ) // Must be some error. Still return true though, since we did handle it return true; // First, save it for KOrganizer to handle QString dir; if ( status == Attendee::Accepted ) dir = "accepted"; else if ( status == Attendee::Tentative ) dir = "tentative"; else if ( status == Attendee::Declined ) dir = "cancel"; else return true; // unknown status saveFile( receiver, iCal, dir ); // Now produce the return message Incidence* incidence = icalToString( iCal ); if( !incidence ) return false; Attendee *myself = findMyself( incidence, receiver ); if ( ( myself && myself->RSVP() ) || heuristicalRSVP( incidence ) ) { setStatusOnMyself( incidence, myself, status, receiver ); ok = mail( incidence, callback ); } else { ( new KMDeleteMsgCommand( callback.getMsg()->getMsgSerNum() ) )->start(); } delete incidence; return ok; } bool handleIgnore( const QString&, KMail::Callback& c ) const { // simply move the message to trash ( new KMDeleteMsgCommand( c.getMsg()->getMsgSerNum() ) )->start(); return true; } bool handleClick( KMail::Interface::BodyPart *part, const QString &path, KMail::Callback& c ) const { QString iCal = part->asText(); bool result = false; if ( path == "accept" ) result = handleInvitation( iCal, Attendee::Accepted, c ); if ( path == "accept_conditionally" ) result = handleInvitation( iCal, Attendee::Tentative, c ); if ( path == "ignore" ) result = handleIgnore( iCal, c ); if ( path == "decline" ) result = handleInvitation( iCal, Attendee::Declined, c ); if ( path == "reply" || path == "cancel" ) { // These should just be saved with their type as the dir if ( saveFile( "Receiver Not Searched", iCal, path ) ) { ( new KMDeleteMsgCommand( c.getMsg()->getMsgSerNum() ) )->start(); } } if ( result ) c.closeIfSecondaryWindow(); return result; } bool handleContextMenuRequest( KMail::Interface::BodyPart *, const QString &, const QPoint & ) const { return false; } QString statusBarMessage( KMail::Interface::BodyPart *, const QString &path ) const { if ( !path.isEmpty() ) { if ( path == "accept" ) return i18n("Accept incidence"); if ( path == "accept_conditionally" ) return i18n( "Accept incidence conditionally" ); if ( path == "ignore" ) return i18n( "Throw mail away" ); if ( path == "decline" ) return i18n( "Decline incidence" ); if ( path == "check_calendar" ) return i18n("Check my calendar..." ); if ( path == "reply" ) return i18n( "Enter incidence into my calendar" ); if ( path == "cancel" ) return i18n( "Remove incidence from my calendar" ); } return QString::null; } }; class Plugin : public KMail::Interface::BodyPartFormatterPlugin { public: const KMail::Interface::BodyPartFormatter *bodyPartFormatter( int idx ) const { if ( idx == 0 ) return new Formatter(); else return 0; } const char *type( int idx ) const { if ( idx == 0 ) return "text"; else return 0; } const char *subtype( int idx ) const { if ( idx == 0 ) return "calendar"; else return 0; } const KMail::Interface::BodyPartURLHandler * urlHandler( int idx ) const { if ( idx == 0 ) return new UrlHandler(); else return 0; } }; } extern "C" KDE_EXPORT KMail::Interface::BodyPartFormatterPlugin * libkmail_bodypartformatter_text_calendar_create_bodypart_formatter_plugin() { KGlobal::locale()->insertCatalogue( "kmail_text_calendar_plugin" ); return new Plugin(); } <commit_msg>Cross port from proko2: Make sure external reader windows are closed if the users cancels an appointment from them.<commit_after>/* This file is part of kdepim. Copyright (c) 2004 Cornelius Schumacher <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <interfaces/bodypartformatter.h> #include <interfaces/bodypart.h> #include <interfaces/bodyparturlhandler.h> #include <khtmlparthtmlwriter.h> #include <libkcal/calendarlocal.h> #include <libkcal/icalformat.h> #include <libkcal/attendee.h> #include <libkcal/incidence.h> #include <libkcal/incidenceformatter.h> #include <kpimprefs.h> // for the timezone #include <kmail/callback.h> #include <kmail/kmmessage.h> #include <kmail/kmcommands.h> #include <email.h> #include <kglobal.h> #include <klocale.h> #include <kstringhandler.h> #include <kglobalsettings.h> #include <kiconloader.h> #include <kdebug.h> #include <kdcopservicestarter.h> #include <kmessagebox.h> #include <kstandarddirs.h> #include <kapplication.h> #include <ktempfile.h> #include <qurl.h> #include <qdir.h> #include <qtextstream.h> #include <kdepimmacros.h> #include <dcopclient.h> #include <dcopref.h> using namespace KCal; namespace { class KMInvitationFormatterHelper : public KCal::InvitationFormatterHelper { public: KMInvitationFormatterHelper( KMail::Interface::BodyPart *bodyPart ) : mBodyPart( bodyPart ) {} virtual QString generateLinkURL( const QString &id ) { return mBodyPart->makeLink( id ); } private: KMail::Interface::BodyPart *mBodyPart; }; class Formatter : public KMail::Interface::BodyPartFormatter { public: Result format( KMail::Interface::BodyPart *bodyPart, KMail::HtmlWriter *writer ) const { if ( !writer ) // Guard against crashes in createReply() return Ok; CalendarLocal cl( KPimPrefs::timezone() ); KMInvitationFormatterHelper helper( bodyPart ); QString source; /* If the bodypart does not have a charset specified, we need to fall back to utf8, not the KMail fallback encoding, so get the contents as binary and decode explicitely. */ if ( bodyPart->contentTypeParameter( "charset").isEmpty() ) { const QByteArray &ba = bodyPart->asBinary(); source = QString::fromUtf8(ba); } else { source = bodyPart->asText(); } QString html = IncidenceFormatter::formatICalInvitation( source, &cl, &helper ); if ( html.isEmpty() ) return AsIcon; writer->queue( html ); return Ok; } }; class UrlHandler : public KMail::Interface::BodyPartURLHandler { public: UrlHandler() { kdDebug() << "UrlHandler() (iCalendar)" << endl; } Incidence* icalToString( const QString& iCal ) const { CalendarLocal calendar( KPimPrefs::timezone() ) ; ICalFormat format; ScheduleMessage *message = format.parseScheduleMessage( &calendar, iCal ); if ( !message ) //TODO: Error message? return 0; return dynamic_cast<Incidence*>( message->event() ); } Attendee *findMyself( Incidence* incidence, const QString& receiver ) const { Attendee::List attendees = incidence->attendees(); Attendee::List::ConstIterator it; Attendee* myself = 0; // Find myself. There will always be all attendees listed, even if // only I need to answer it. if ( attendees.count() == 1 ) // Only one attendee, that must be me myself = *attendees.begin(); else { for ( it = attendees.begin(); it != attendees.end(); ++it ) { // match only the email part, not the name if( KPIM::compareEmail( (*it)->email(), receiver, false ) ) { // We are the current one, and even the receiver, note // this and quit searching. myself = (*it); break; } } } return myself; } static bool heuristicalRSVP( Incidence *incidence ) { bool rsvp = true; // better send superfluously than not at all Attendee::List attendees = incidence->attendees(); Attendee::List::ConstIterator it; for ( it = attendees.begin(); it != attendees.end(); ++it ) { if ( it == attendees.begin() ) { rsvp = (*it)->RSVP(); // use what the first one has } else { if ( (*it)->RSVP() != rsvp ) { rsvp = true; // they differ, default break; } } } return rsvp; } static Attendee::Role heuristicalRole( Incidence *incidence ) { Attendee::Role role = Attendee::OptParticipant; Attendee::List attendees = incidence->attendees(); Attendee::List::ConstIterator it; for ( it = attendees.begin(); it != attendees.end(); ++it ) { if ( it == attendees.begin() ) { role = (*it)->role(); // use what the first one has } else { if ( (*it)->role() != role ) { role = Attendee::OptParticipant; // they differ, default break; } } } return role; } void setStatusOnMyself( Incidence* incidence, Attendee* myself, Attendee::PartStat status, const QString &receiver ) const { Attendee* newMyself = 0; QString name; QString email; KPIM::getNameAndMail( receiver, name, email ); if ( name.isEmpty() && myself ) name = myself->name(); if ( email.isEmpty()&& myself ) email = myself->email(); Q_ASSERT( !email.isEmpty() ); // delivery must be possible newMyself = new Attendee( name, email, true, // RSVP, otherwise we would not be here status, myself ? myself->role() : heuristicalRole( incidence ), myself ? myself->uid() : QString::null ); // Make sure only ourselves is in the event incidence->clearAttendees(); if( newMyself ) incidence->addAttendee( newMyself ); } bool mail( Incidence* incidence, KMail::Callback& callback ) const { ICalFormat format; format.setTimeZone( KPimPrefs::timezone(), false ); QString msg = format.createScheduleMessage( incidence, Scheduler::Reply ); QString subject; if ( !incidence->summary().isEmpty() ) subject = i18n( "Answer: %1" ).arg( incidence->summary() ); else subject = i18n( "Answer: Incidence with no summary" ); return callback.mailICal( incidence->organizer().fullName(), msg, subject ); } bool saveFile( const QString& receiver, const QString& iCal, const QString& type ) const { KTempFile file( locateLocal( "data", "korganizer/income." + type + '/', true ) ); QTextStream* ts = file.textStream(); if ( !ts ) { KMessageBox::error( 0, i18n("Could not save file to KOrganizer") ); return false; } ts->setEncoding( QTextStream::UnicodeUTF8 ); (*ts) << receiver << '\n' << iCal; file.close(); // Now ensure that korganizer is running; otherwise start it, to prevent surprises // (https://intevation.de/roundup/kolab/issue758) QString error; QCString dcopService; int result = KDCOPServiceStarter::self()->findServiceFor( "DCOP/Organizer", QString::null, QString::null, &error, &dcopService ); if ( result == 0 ) { // OK, so korganizer (or kontact) is running. Now ensure the object we want is available // [that's not the case when kontact was already running, but korganizer not loaded into it...] static const char* const dcopObjectId = "KOrganizerIface"; QCString dummy; if ( !kapp->dcopClient()->findObject( dcopService, dcopObjectId, "", QByteArray(), dummy, dummy ) ) { DCOPRef ref( dcopService, dcopService ); // talk to the KUniqueApplication or its kontact wrapper DCOPReply reply = ref.call( "load()" ); if ( reply.isValid() && (bool)reply ) { kdDebug() << "Loaded " << dcopService << " successfully" << endl; Q_ASSERT( kapp->dcopClient()->findObject( dcopService, dcopObjectId, "", QByteArray(), dummy, dummy ) ); } else kdWarning() << "Error loading " << dcopService << endl; } // We don't do anything with it, we just need it to be running so that it handles // the incoming directory. } else kdWarning() << "Couldn't start DCOP/Organizer: " << dcopService << " " << error << endl; return true; } bool handleInvitation( const QString& iCal, Attendee::PartStat status, KMail::Callback &callback ) const { bool ok = true; const QString receiver = callback.receiver(); if ( receiver.isEmpty() ) // Must be some error. Still return true though, since we did handle it return true; // First, save it for KOrganizer to handle QString dir; if ( status == Attendee::Accepted ) dir = "accepted"; else if ( status == Attendee::Tentative ) dir = "tentative"; else if ( status == Attendee::Declined ) dir = "cancel"; else return true; // unknown status saveFile( receiver, iCal, dir ); // Now produce the return message Incidence* incidence = icalToString( iCal ); if( !incidence ) return false; Attendee *myself = findMyself( incidence, receiver ); if ( ( myself && myself->RSVP() ) || heuristicalRSVP( incidence ) ) { setStatusOnMyself( incidence, myself, status, receiver ); ok = mail( incidence, callback ); } else { ( new KMDeleteMsgCommand( callback.getMsg()->getMsgSerNum() ) )->start(); } delete incidence; return ok; } bool handleIgnore( const QString&, KMail::Callback& c ) const { // simply move the message to trash ( new KMDeleteMsgCommand( c.getMsg()->getMsgSerNum() ) )->start(); return true; } bool handleClick( KMail::Interface::BodyPart *part, const QString &path, KMail::Callback& c ) const { QString iCal = part->asText(); bool result = false; if ( path == "accept" ) result = handleInvitation( iCal, Attendee::Accepted, c ); if ( path == "accept_conditionally" ) result = handleInvitation( iCal, Attendee::Tentative, c ); if ( path == "ignore" ) result = handleIgnore( iCal, c ); if ( path == "decline" ) result = handleInvitation( iCal, Attendee::Declined, c ); if ( path == "reply" || path == "cancel" ) { // These should just be saved with their type as the dir if ( saveFile( "Receiver Not Searched", iCal, path ) ) { ( new KMDeleteMsgCommand( c.getMsg()->getMsgSerNum() ) )->start(); result = true; } } if ( result ) c.closeIfSecondaryWindow(); return result; } bool handleContextMenuRequest( KMail::Interface::BodyPart *, const QString &, const QPoint & ) const { return false; } QString statusBarMessage( KMail::Interface::BodyPart *, const QString &path ) const { if ( !path.isEmpty() ) { if ( path == "accept" ) return i18n("Accept incidence"); if ( path == "accept_conditionally" ) return i18n( "Accept incidence conditionally" ); if ( path == "ignore" ) return i18n( "Throw mail away" ); if ( path == "decline" ) return i18n( "Decline incidence" ); if ( path == "check_calendar" ) return i18n("Check my calendar..." ); if ( path == "reply" ) return i18n( "Enter incidence into my calendar" ); if ( path == "cancel" ) return i18n( "Remove incidence from my calendar" ); } return QString::null; } }; class Plugin : public KMail::Interface::BodyPartFormatterPlugin { public: const KMail::Interface::BodyPartFormatter *bodyPartFormatter( int idx ) const { if ( idx == 0 ) return new Formatter(); else return 0; } const char *type( int idx ) const { if ( idx == 0 ) return "text"; else return 0; } const char *subtype( int idx ) const { if ( idx == 0 ) return "calendar"; else return 0; } const KMail::Interface::BodyPartURLHandler * urlHandler( int idx ) const { if ( idx == 0 ) return new UrlHandler(); else return 0; } }; } extern "C" KDE_EXPORT KMail::Interface::BodyPartFormatterPlugin * libkmail_bodypartformatter_text_calendar_create_bodypart_formatter_plugin() { KGlobal::locale()->insertCatalogue( "kmail_text_calendar_plugin" ); return new Plugin(); } <|endoftext|>
<commit_before>#include "configfile.hpp" #include <algorithm> #include <limits> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> ConfigFile::ConfigFile() : vars_(), data_(0), datasz_(0), dataalloc_(0), sorted_(true) { } ConfigFile::~ConfigFile() { free(data_); } void ConfigFile::dump() { std::vector<Var>::iterator i = vars_.begin(), e = vars_.end(); for (; i != e; ++i) printf("%s.%s = %s\n", i->sec, i->key, i->val); } void ConfigFile::putKey(char const *sec, char const *key, char const *val) { // FIXME sanitize sec / key if (val) { Var z = { 0, 0, 0 }; vars_.push_back(z); try { Var &v = vars_.back(); v.sec = putStr(sec); v.key = putStr(key); v.val = val ? putStr(val) : 0; sorted_ = false; } catch (...) { vars_.pop_back(); throw; } } else { Var *p = getVar(sec, key); if (p) p->val = 0; } } char const *ConfigFile::getKey(char const *sec, char const *key) { Var *p = getVar(sec, key); return p ? p->val : 0; } void ConfigFile::putLong(char const *sec, char const *key, long val) { char buf[32]; snprintf(buf, sizeof(buf), "%ld", val); putKey(sec, key, buf); } void ConfigFile::putString(char const *sec, char const *key, std::string const &val) { // FIXME sanitize putKey(sec, key, val.c_str()); } void ConfigFile::putStringArray(char const *sec, char const *key, std::vector<std::string> const &val) { // FIXME sanitize std::vector<std::string>::const_iterator b = val.begin(), i, e = val.end(); size_t sz = 0; for (i = b; i != e; ++i) { size_t ssz = i->size(); if (!ssz) continue; if (ssz > std::numeric_limits<size_t>::max() - sz) throw std::bad_alloc(); sz += ssz; } Var z = { 0, 0, 0 }; vars_.push_back(z); try { Var &v = vars_.back(); v.sec = putStr(sec); v.key = putStr(key); if (sz) { char *p = alloc(sz); v.val = p; for (i = b; i != e; ++i) { size_t ssz = i->size(); if (!ssz) continue; memcpy(p, i->data(), ssz); p[ssz] = ':'; p += ssz + 1; } p[-1] = '\0'; } else v.val = ""; } catch (...) { vars_.pop_back(); throw; } } void ConfigFile::putBool(char const *sec, char const *key, bool val) { putKey(sec, key, val ? "true" : "false"); } void ConfigFile::putDouble(char const *sec, char const *key, double val) { char buf[32]; snprintf(buf, sizeof(buf), "%g", val); putKey(sec, key, buf); } bool ConfigFile::getLong(char const *sec, char const *key, long &val) { // FIXME check for overflow? Or do we even care? char const *v = getKey(sec, key); if (!v) return false; char *e; long r = strtol(v, &e, 0); if (*e) return false; // FIXME warning? val = r; return true; } bool ConfigFile::getString(char const *sec, char const *key, std::string &val) { char const *v = getKey(sec, key); if (!v) return false; val = v; return true; } bool ConfigFile::getStringArray(char const *sec, char const *key, std::vector<std::string> &val) { char const *v = getKey(sec, key), *s = v, *p; if (!v) return false; while (1) { for (p = s; *p && *p != ':'; ++p); if (s != p) val.push_back(std::string(s, p)); if (*p == ':') s = p + 1; else break; } return true; } bool ConfigFile::getBool(char const *sec, char const *key, bool &val) { char const *v = getKey(sec, key); if (!v) return false; char tmp[6]; unsigned int i; for (i = 0; i < 6 && v[i]; ++i) tmp[i] = v[i] & ~('a' ^ 'A'); for (; i < 6; ++i) tmp[i] = '\0'; bool r; if (!memcmp(tmp, "TRUE", 5)) r = true; else if (!memcmp(tmp, "FALSE", 6)) r = false; else if (!memcmp(tmp, "YES", 4)) r = true; else if (!memcmp(tmp, "NO", 3)) r = false; else if (!memcmp(tmp, "ON", 3)) r = true; else if (!memcmp(tmp, "OFF", 4)) r = false; else return false; // FIXME warning? val = r; return true; } bool ConfigFile::getDouble(char const *sec, char const *key, double val) { // FIXME check for overflow? Or do we even care? char const *v = getKey(sec, key); if (!v) return false; char *e; double r = strtod(v, &e); if (*e) return false; // FIXME warning? val = r; return true; } struct ConfigVarCmp { bool operator()(ConfigFile::Var const &x, ConfigFile::Var const &y) { int v; v = strcmp(x.sec, y.sec); if (v < 0) return true; if (v > 0) return false; v = strcmp(x.key, y.key); return v < 0; } }; ConfigFile::Var *ConfigFile::getVar(char const *sec, char const *key) { if (!sorted_) sort(); std::vector<Var>::iterator i; Var v; v.sec = sec; v.key = key; i = std::lower_bound(vars_.begin(), vars_.end(), v, ConfigVarCmp()); if (i != vars_.end() && !strcmp(i->sec, sec) && !strcmp(i->key, key)) return &*i; return 0; } char *ConfigFile::alloc(size_t len) { if (len > std::numeric_limits<size_t>::max()/2 - dataalloc_) throw std::bad_alloc(); if (dataalloc_ < datasz_ + len) { size_t nalloc = dataalloc_ ? dataalloc_ : 4*1024; while (nalloc < datasz_ + len) nalloc *= 2; char *ndata = reinterpret_cast<char *>(malloc(nalloc)); if (!ndata) throw std::bad_alloc(); size_t off = 0; std::vector<Var>::iterator i = vars_.begin(), e = vars_.end(); for (; i != e; ++i) { char const *s[3] = { i->sec, i->key, i->val }; for (unsigned int j = 0; j < 3; ++j) { char const *str = s[j]; if (!str) continue; size_t ssz = strlen(str) + 1; s[j] = ndata + off; memcpy(ndata + off, str, ssz); off += ssz; } i->sec = s[0]; i->key = s[1]; i->val = s[2]; } free(data_); assert(off + len <= nalloc); datasz_ = off; data_ = ndata; dataalloc_ = nalloc; } char *dest = data_ + datasz_; datasz_ += len; return dest; } char *ConfigFile::putStr(char const *str) { size_t len = strlen(str) + 1; char *dest = alloc(len); memcpy(dest, str, len); return dest; } static bool varEq(ConfigFile::Var &x, ConfigFile::Var &y) { return !strcmp(x.sec, y.sec) && !strcmp(x.key, y.key); } void ConfigFile::sort() { if (sorted_) return; if (vars_.empty()) { sorted_ = true; return; } std::vector<Var>::iterator b = vars_.begin(), e = vars_.end(), i, o; std::stable_sort(b, e, ConfigVarCmp()); for (i = b + 1; i != e; ++i) { if (varEq(*i, *(i - 1))) break; } if (i != e) { o = i - 1; while (i != e) { do ++i; while (i != e && varEq(*i, *(i - 1))); if ((i - 1)->val) { *o = *(i - 1); ++o; } } vars_.resize(o - b); } sorted_ = true; }; <commit_msg>Wrote simple ConfigFile::write implementation, fixed ConfigFile::sort.<commit_after>#include "configfile.hpp" #include <algorithm> #include <limits> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <err.h> ConfigFile::ConfigFile() : vars_(), data_(0), datasz_(0), dataalloc_(0), sorted_(true) { } ConfigFile::~ConfigFile() { free(data_); } void ConfigFile::write(char const *path) { if (!sorted_) sort(); FILE *f = fopen(path, "wb"); if (!f) goto error; try { char const *sec = ""; std::vector<Var>::const_iterator i = vars_.begin(), e = vars_.end(); for (; i != e; ++i) { Var v = *i; if (strcmp(v.sec, sec)) { fprintf(f, "[%s]\n", v.sec); sec = v.sec; } fprintf(f, "%s = %s\n", v.key, v.val); } } catch (...) { fclose(f); throw; } return; error: warn("Could not write config file '%s'", path); return; } void ConfigFile::dump() { std::vector<Var>::iterator i = vars_.begin(), e = vars_.end(); for (; i != e; ++i) printf("%s.%s = %s\n", i->sec, i->key, i->val); } void ConfigFile::putKey(char const *sec, char const *key, char const *val) { // FIXME sanitize sec / key if (val) { Var z = { 0, 0, 0 }; vars_.push_back(z); try { Var &v = vars_.back(); v.sec = putStr(sec); v.key = putStr(key); v.val = val ? putStr(val) : 0; sorted_ = false; } catch (...) { vars_.pop_back(); throw; } } else { Var *p = getVar(sec, key); if (p) p->val = 0; } } char const *ConfigFile::getKey(char const *sec, char const *key) { Var *p = getVar(sec, key); return p ? p->val : 0; } void ConfigFile::putLong(char const *sec, char const *key, long val) { char buf[32]; snprintf(buf, sizeof(buf), "%ld", val); putKey(sec, key, buf); } void ConfigFile::putString(char const *sec, char const *key, std::string const &val) { // FIXME sanitize putKey(sec, key, val.c_str()); } void ConfigFile::putStringArray(char const *sec, char const *key, std::vector<std::string> const &val) { // FIXME sanitize std::vector<std::string>::const_iterator b = val.begin(), i, e = val.end(); size_t sz = 0; for (i = b; i != e; ++i) { size_t ssz = i->size(); if (!ssz) continue; if (ssz > std::numeric_limits<size_t>::max() - sz) throw std::bad_alloc(); sz += ssz; } Var z = { 0, 0, 0 }; vars_.push_back(z); try { Var &v = vars_.back(); v.sec = putStr(sec); v.key = putStr(key); if (sz) { char *p = alloc(sz); v.val = p; for (i = b; i != e; ++i) { size_t ssz = i->size(); if (!ssz) continue; memcpy(p, i->data(), ssz); p[ssz] = ':'; p += ssz + 1; } p[-1] = '\0'; } else v.val = ""; } catch (...) { vars_.pop_back(); throw; } } void ConfigFile::putBool(char const *sec, char const *key, bool val) { putKey(sec, key, val ? "true" : "false"); } void ConfigFile::putDouble(char const *sec, char const *key, double val) { char buf[32]; snprintf(buf, sizeof(buf), "%g", val); putKey(sec, key, buf); } bool ConfigFile::getLong(char const *sec, char const *key, long &val) { // FIXME check for overflow? Or do we even care? char const *v = getKey(sec, key); if (!v) return false; char *e; long r = strtol(v, &e, 0); if (*e) return false; // FIXME warning? val = r; return true; } bool ConfigFile::getString(char const *sec, char const *key, std::string &val) { char const *v = getKey(sec, key); if (!v) return false; val = v; return true; } bool ConfigFile::getStringArray(char const *sec, char const *key, std::vector<std::string> &val) { char const *v = getKey(sec, key), *s = v, *p; if (!v) return false; while (1) { for (p = s; *p && *p != ':'; ++p); if (s != p) val.push_back(std::string(s, p)); if (*p == ':') s = p + 1; else break; } return true; } bool ConfigFile::getBool(char const *sec, char const *key, bool &val) { char const *v = getKey(sec, key); if (!v) return false; char tmp[6]; unsigned int i; for (i = 0; i < 6 && v[i]; ++i) tmp[i] = v[i] & ~('a' ^ 'A'); for (; i < 6; ++i) tmp[i] = '\0'; bool r; if (!memcmp(tmp, "TRUE", 5)) r = true; else if (!memcmp(tmp, "FALSE", 6)) r = false; else if (!memcmp(tmp, "YES", 4)) r = true; else if (!memcmp(tmp, "NO", 3)) r = false; else if (!memcmp(tmp, "ON", 3)) r = true; else if (!memcmp(tmp, "OFF", 4)) r = false; else return false; // FIXME warning? val = r; return true; } bool ConfigFile::getDouble(char const *sec, char const *key, double val) { // FIXME check for overflow? Or do we even care? char const *v = getKey(sec, key); if (!v) return false; char *e; double r = strtod(v, &e); if (*e) return false; // FIXME warning? val = r; return true; } struct ConfigVarCmp { bool operator()(ConfigFile::Var const &x, ConfigFile::Var const &y) { int v; v = strcmp(x.sec, y.sec); if (v < 0) return true; if (v > 0) return false; v = strcmp(x.key, y.key); return v < 0; } }; ConfigFile::Var *ConfigFile::getVar(char const *sec, char const *key) { if (!sorted_) sort(); std::vector<Var>::iterator i; Var v; v.sec = sec; v.key = key; i = std::lower_bound(vars_.begin(), vars_.end(), v, ConfigVarCmp()); if (i != vars_.end() && !strcmp(i->sec, sec) && !strcmp(i->key, key)) return &*i; return 0; } char *ConfigFile::alloc(size_t len) { if (len > std::numeric_limits<size_t>::max()/2 - dataalloc_) throw std::bad_alloc(); if (dataalloc_ < datasz_ + len) { size_t nalloc = dataalloc_ ? dataalloc_ : 4*1024; while (nalloc < datasz_ + len) nalloc *= 2; char *ndata = reinterpret_cast<char *>(malloc(nalloc)); if (!ndata) throw std::bad_alloc(); size_t off = 0; std::vector<Var>::iterator i = vars_.begin(), e = vars_.end(); for (; i != e; ++i) { char const *s[3] = { i->sec, i->key, i->val }; for (unsigned int j = 0; j < 3; ++j) { char const *str = s[j]; if (!str) continue; size_t ssz = strlen(str) + 1; s[j] = ndata + off; memcpy(ndata + off, str, ssz); off += ssz; } i->sec = s[0]; i->key = s[1]; i->val = s[2]; } free(data_); assert(off + len <= nalloc); datasz_ = off; data_ = ndata; dataalloc_ = nalloc; } char *dest = data_ + datasz_; datasz_ += len; return dest; } char *ConfigFile::putStr(char const *str) { size_t len = strlen(str) + 1; char *dest = alloc(len); memcpy(dest, str, len); return dest; } static bool varEq(ConfigFile::Var &x, ConfigFile::Var &y) { return !strcmp(x.sec, y.sec) && !strcmp(x.key, y.key); } void ConfigFile::sort() { if (sorted_) return; if (vars_.empty()) { sorted_ = true; return; } std::vector<Var>::iterator b = vars_.begin(), e = vars_.end(), i, o; std::stable_sort(b, e, ConfigVarCmp()); for (o = b, i = b; i != e; ) { do ++i; while (i != e && varEq(*i, *(i - 1))); if ((i - 1)->val) { *o = *(i - 1); ++o; } } vars_.resize(o - b); sorted_ = true; }; <|endoftext|>
<commit_before>/* * Copyright 2015 Gustaf Räntilä * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef LIBQ_OPTIONS_HPP #define LIBQ_OPTIONS_HPP #include <q/type_traits.hpp> namespace q { template< typename T > struct required { typedef T type; }; namespace detail { template< typename T > struct _is_required : std::false_type { }; template< typename T > struct _is_required< ::q::required< T > > : std::true_type { }; } // namespace detail template< typename T > struct is_required : detail::_is_required< typename std::decay< T >::type > { }; template< typename T > struct strip_required { typedef T type; }; template< typename T > struct strip_required< required< T > > { typedef T type; }; namespace detail { template< typename T > struct single_option { typedef single_option< T > this_type; single_option( ) : set_( false ) { } template< typename Tuple, typename std::enable_if< tuple_arguments< typename std::decay< Tuple >::type > ::template index_of< T >::value != -1 >::type* = nullptr > single_option( Tuple&& tuple ) : set_( true ) , val_( std::move( get_tuple_element< T >( tuple ) ) ) { } template< typename Tuple, typename std::enable_if< tuple_arguments< typename std::decay< Tuple >::type > ::template index_of< T >::value == -1 >::type* = nullptr > single_option( Tuple&& tuple ) : set_( false ) { } single_option( T&& t ) : set_( true ) , val_( std::move( t ) ) { } single_option( const T& t ) : set_( true ) , val_( t ) { } single_option( this_type&& ref ) = default; single_option( const this_type& ref ) = default; this_type& operator=( this_type&& ) = default; this_type& operator=( const this_type& ) = default; bool has( ) const { return set_; } const T& get( ) const { return val_; } T move( ) { return std::move( val_ ); } private: bool set_; T val_; }; template< typename... Args > struct options; template< typename First, typename... Rest > struct options< First, Rest... > : detail::single_option< First > , options< Rest... > { typedef options< First, Rest... > this_type; template< typename Tuple > options( Tuple&& tuple ) : detail::single_option< First >( tuple ) , options< Rest... >( tuple ) { } options( this_type&& options ) = default; options( const this_type& options ) = default; }; template< > struct options< > { template< typename Tuple > options( Tuple&& tuple ) { } }; } // namespace detail template< typename... T > class options : public detail::options< typename strip_required< T >::type... > { public: typedef arguments< typename strip_required< T >::type... > stripped_arguments; typedef typename arguments< T... > ::template filter< is_required >::type ::template map< strip_required >::type ::template map< std::decay >::type required_arguments; static_assert( are_all_unique< typename strip_required< T >::type... >::value, "option types must be unique" ); template< typename... Args > options( Args&&... args ) : detail::options< typename strip_required< T >::type... >( std::make_tuple( std::forward< Args >( args )... ) ) { static_assert( arguments< typename std::decay< Args >::type... > ::template contains_all< required_arguments >::value, "All required options not provided" ); } template< typename U > typename std::enable_if< stripped_arguments::template index_of< U >::value != -1, bool >::type has( ) const { typedef detail::single_option< U > base_type; return static_cast< const base_type& >( *this ).has( ); } template< typename U > typename std::enable_if< stripped_arguments::template index_of< U >::value != -1, U >::type get( ) const { typedef detail::single_option< U > base_type; return static_cast< const base_type& >( *this ).get( ); } template< typename U > typename std::enable_if< stripped_arguments::template index_of< U >::value != -1, U >::type get( ) { typedef detail::single_option< U > base_type; return static_cast< base_type& >( *this ).get( ); } template< typename U > typename std::enable_if< stripped_arguments::template index_of< U >::value != -1, U >::type get( U _default ) const { typedef detail::single_option< U > base_type; return static_cast< const base_type& >( *this ).has( ) ? static_cast< const base_type& >( *this ).get( ) : _default; } template< typename U > typename std::enable_if< stripped_arguments::template index_of< U >::value != -1, U >::type get( U _default ) { typedef detail::single_option< U > base_type; return static_cast< base_type& >( *this ).has( ) ? static_cast< base_type& >( *this ).get( ) : _default; } template< typename U > typename std::enable_if< stripped_arguments::template index_of< U >::value != -1, U >::type move( ) { typedef detail::single_option< U > base_type; return static_cast< base_type& >( *this ).move( ); } template< typename U > typename std::enable_if< stripped_arguments::template index_of< U >::value != -1, U >::type move( U _default ) { typedef detail::single_option< U > base_type; return static_cast< base_type& >( *this ).has( ) ? static_cast< base_type& >( *this ).move( ) : _default; } }; } // namespace q #endif // LIBQ_OPTIONS_HPP <commit_msg>q::options much more storage efficient<commit_after>/* * Copyright 2015 Gustaf Räntilä * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef LIBQ_OPTIONS_HPP #define LIBQ_OPTIONS_HPP #include <q/type_traits.hpp> #include <q/bit_flags.hpp> namespace q { template< typename T > struct required { typedef T type; }; namespace detail { template< typename T > struct _is_required : std::false_type { }; template< typename T > struct _is_required< ::q::required< T > > : std::true_type { }; } // namespace detail template< typename T > struct is_required : detail::_is_required< typename std::decay< T >::type > { }; template< typename T > struct strip_required { typedef T type; }; template< typename T > struct strip_required< required< T > > { typedef T type; }; namespace detail { template< typename T > struct single_option { typedef single_option< T > this_type; single_option( ) { } template< typename Tuple, typename std::enable_if< tuple_arguments< typename std::decay< Tuple >::type > ::template index_of< T >::value != -1 >::type* = nullptr > single_option( Tuple&& tuple ) : val_( std::move( get_tuple_element< T >( tuple ) ) ) { } template< typename Tuple, typename std::enable_if< tuple_arguments< typename std::decay< Tuple >::type > ::template index_of< T >::value == -1 >::type* = nullptr > single_option( Tuple&& tuple ) { } single_option( T&& t ) : val_( std::move( t ) ) { } single_option( const T& t ) : val_( t ) { } single_option( this_type&& ref ) = default; single_option( const this_type& ref ) = default; this_type& operator=( this_type&& ) = default; this_type& operator=( const this_type& ) = default; const T& get( ) const { return val_; } T move( ) { return std::move( val_ ); } private: T val_; }; template< typename... Args > struct options; template< typename First, typename... Rest > struct options< First, Rest... > : detail::single_option< First > , options< Rest... > { typedef options< First, Rest... > this_type; template< typename Tuple > options( Tuple&& tuple ) : detail::single_option< First >( tuple ) , options< Rest... >( tuple ) { } options( this_type&& options ) = default; options( const this_type& options ) = default; }; template< > struct options< > { template< typename Tuple > options( Tuple&& tuple ) { } }; } // namespace detail template< typename... T > class options : public detail::options< typename strip_required< T >::type... > { public: typedef arguments< typename strip_required< T >::type... > stripped_arguments; typedef typename arguments< T... > ::template filter< is_required >::type ::template map< strip_required >::type ::template map< std::decay >::type required_arguments; typedef bit_flags_of_types< typename strip_required< T >::type... > bit_flags_type; static_assert( are_all_unique< typename strip_required< T >::type... >::value, "option types must be unique" ); template< typename... Args > options( Args&&... args ) : detail::options< typename strip_required< T >::type... >( std::make_tuple( std::forward< Args >( args )... ) ) { static_assert( arguments< typename std::decay< Args >::type... > ::template contains_all< required_arguments >::value, "All required options not provided" ); set_.template set_by_type< Args... >( ); } template< typename U > typename std::enable_if< stripped_arguments::template index_of< U >::value != -1, bool >::type has( ) const { return set_.template is_set_by_type< U >( ); } template< typename U > typename std::enable_if< stripped_arguments::template index_of< U >::value != -1, U >::type get( ) const { typedef detail::single_option< U > base_type; return static_cast< const base_type& >( *this ).get( ); } template< typename U > typename std::enable_if< stripped_arguments::template index_of< U >::value != -1, U >::type get( ) { typedef detail::single_option< U > base_type; return static_cast< base_type& >( *this ).get( ); } template< typename U > typename std::enable_if< stripped_arguments::template index_of< U >::value != -1, U >::type get( U _default ) const { typedef detail::single_option< U > base_type; return has< U >( ) ? static_cast< const base_type& >( *this ).get( ) : _default; } template< typename U > typename std::enable_if< stripped_arguments::template index_of< U >::value != -1, U >::type get( U _default ) { typedef detail::single_option< U > base_type; return has< U >( ) ? static_cast< base_type& >( *this ).get( ) : _default; } template< typename U > typename std::enable_if< stripped_arguments::template index_of< U >::value != -1, U >::type move( ) { typedef detail::single_option< U > base_type; return static_cast< base_type& >( *this ).move( ); } template< typename U > typename std::enable_if< stripped_arguments::template index_of< U >::value != -1, U >::type move( U _default ) { typedef detail::single_option< U > base_type; return has< U >( ) ? static_cast< base_type& >( *this ).move( ) : _default; } private: bit_flags_type set_; }; } // namespace q #endif // LIBQ_OPTIONS_HPP <|endoftext|>
<commit_before>#include <utils/tcpRobotCommunicator.h> #include <QtNetwork/QHostAddress> #include <QtCore/QFileInfo> #include <qrkernel/settingsManager.h> #include <qrkernel/exception/exception.h> #include <qrkernel/logging.h> #include <qrutils/inFile.h> using namespace utils; static uint const controlPort = 8888; static uint const telemetryPort = 9000; TcpRobotCommunicator::TcpRobotCommunicator(QString const &settings) : mErrorReporter(nullptr) , mControlConnection(controlPort) , mTelemetryConnection(telemetryPort) , mSettings(settings) { QObject::connect(&mControlConnection, SIGNAL(messageReceived(QString)) , this, SLOT(processControlMessage(QString))); QObject::connect(&mTelemetryConnection, SIGNAL(messageReceived(QString)) , this, SLOT(processTelemetryMessage(QString))); } TcpRobotCommunicator::~TcpRobotCommunicator() { disconnect(); } bool TcpRobotCommunicator::uploadProgram(QString const &programName) { if (programName.isEmpty()) { return false; } QString fileContents; try { fileContents = utils::InFile::readAll(programName); } catch (qReal::Exception const &) { return false; } connect(); if (!mControlConnection.isConnected()) { return false; } QString const &fileNameOnARobot = QFileInfo(programName).fileName(); mControlConnection.send("file:" + fileNameOnARobot + ":" + fileContents); return true; } bool TcpRobotCommunicator::runProgram(QString const &programName) { connect(); if (!mControlConnection.isConnected()) { return false; } mControlConnection.send("run:" + programName); return true; } bool TcpRobotCommunicator::runDirectCommand(QString const &directCommand) { if (!mControlConnection.isConnected()) { return false; } mControlConnection.send("direct:" + directCommand); return true; } bool TcpRobotCommunicator::stopRobot() { connect(); if (!mControlConnection.isConnected()) { return false; } mControlConnection.send("stop"); return true; } void TcpRobotCommunicator::requestData(QString const &sensor) { if (!mTelemetryConnection.isConnected()) { return; } mTelemetryConnection.send("sensor:" + sensor); } void TcpRobotCommunicator::setErrorReporter(qReal::ErrorReporterInterface *errorReporter) { mErrorReporter = errorReporter; } void TcpRobotCommunicator::processControlMessage(QString const &message) { QString const errorMarker("error: "); QString const infoMarker("info: "); if (message.startsWith(errorMarker) && mErrorReporter) { mErrorReporter->addError(message.mid(errorMarker.length())); } else if (message.startsWith(infoMarker) && mErrorReporter) { mErrorReporter->addInformation(message.mid(infoMarker.length())); } else { QLOG_INFO() << "Incoming message of unknown type: " << message; } } void TcpRobotCommunicator::processTelemetryMessage(QString const &message) { QString const sensorMarker("sensor:"); if (message.startsWith(sensorMarker)){ QString data(message); data.remove(0, sensorMarker.length()); QStringList portAndValue = data.split(":"); if (portAndValue[1].startsWith('(')) { portAndValue[1].remove(0, 1); portAndValue[1].remove(portAndValue[1].length() - 1, 1); QStringList stringValues = portAndValue[1].split(","); QVector<int> values; for (QString const &value : stringValues) { values.push_back(value.toInt()); } emit newVectorSensorData(portAndValue[0], values); } else { emit newScalarSensorData(portAndValue[0], portAndValue[1].toInt()); } } else { QLOG_INFO() << "Incoming message of unknown type: " << message; } } void TcpRobotCommunicator::connect() { QString const server = qReal::SettingsManager::value(mSettings).toString(); QHostAddress hostAddress(server); if (hostAddress.isNull()) { QLOG_ERROR() << "Unable to resolve host."; return; } if (mControlConnection.isConnected() && mTelemetryConnection.isConnected()) { return; } bool const result = mControlConnection.connect(hostAddress) && mTelemetryConnection.connect(hostAddress); emit connected(result); } void TcpRobotCommunicator::disconnect() { mControlConnection.disconnect(); mTelemetryConnection.disconnect(); emit disconnected(); } <commit_msg>dont connect to a robot at start<commit_after>#include <utils/tcpRobotCommunicator.h> #include <QtNetwork/QHostAddress> #include <QtCore/QFileInfo> #include <qrkernel/settingsManager.h> #include <qrkernel/exception/exception.h> #include <qrkernel/logging.h> #include <qrutils/inFile.h> using namespace utils; static uint const controlPort = 8888; static uint const telemetryPort = 9000; TcpRobotCommunicator::TcpRobotCommunicator(QString const &settings) : mErrorReporter(nullptr) , mControlConnection(controlPort) , mTelemetryConnection(telemetryPort) , mSettings(settings) { QObject::connect(&mControlConnection, SIGNAL(messageReceived(QString)) , this, SLOT(processControlMessage(QString))); QObject::connect(&mTelemetryConnection, SIGNAL(messageReceived(QString)) , this, SLOT(processTelemetryMessage(QString))); } TcpRobotCommunicator::~TcpRobotCommunicator() { disconnect(); } bool TcpRobotCommunicator::uploadProgram(QString const &programName) { if (programName.isEmpty()) { return false; } QString fileContents; try { fileContents = utils::InFile::readAll(programName); } catch (qReal::Exception const &) { return false; } connect(); if (!mControlConnection.isConnected()) { return false; } QString const &fileNameOnARobot = QFileInfo(programName).fileName(); mControlConnection.send("file:" + fileNameOnARobot + ":" + fileContents); return true; } bool TcpRobotCommunicator::runProgram(QString const &programName) { connect(); if (!mControlConnection.isConnected()) { return false; } mControlConnection.send("run:" + programName); return true; } bool TcpRobotCommunicator::runDirectCommand(QString const &directCommand) { if (!mControlConnection.isConnected()) { return false; } mControlConnection.send("direct:" + directCommand); return true; } bool TcpRobotCommunicator::stopRobot() { if (!mControlConnection.isConnected()) { return false; } mControlConnection.send("stop"); return true; } void TcpRobotCommunicator::requestData(QString const &sensor) { if (!mTelemetryConnection.isConnected()) { return; } mTelemetryConnection.send("sensor:" + sensor); } void TcpRobotCommunicator::setErrorReporter(qReal::ErrorReporterInterface *errorReporter) { mErrorReporter = errorReporter; } void TcpRobotCommunicator::processControlMessage(QString const &message) { QString const errorMarker("error: "); QString const infoMarker("info: "); if (message.startsWith(errorMarker) && mErrorReporter) { mErrorReporter->addError(message.mid(errorMarker.length())); } else if (message.startsWith(infoMarker) && mErrorReporter) { mErrorReporter->addInformation(message.mid(infoMarker.length())); } else { QLOG_INFO() << "Incoming message of unknown type: " << message; } } void TcpRobotCommunicator::processTelemetryMessage(QString const &message) { QString const sensorMarker("sensor:"); if (message.startsWith(sensorMarker)){ QString data(message); data.remove(0, sensorMarker.length()); QStringList portAndValue = data.split(":"); if (portAndValue[1].startsWith('(')) { portAndValue[1].remove(0, 1); portAndValue[1].remove(portAndValue[1].length() - 1, 1); QStringList stringValues = portAndValue[1].split(","); QVector<int> values; for (QString const &value : stringValues) { values.push_back(value.toInt()); } emit newVectorSensorData(portAndValue[0], values); } else { emit newScalarSensorData(portAndValue[0], portAndValue[1].toInt()); } } else { QLOG_INFO() << "Incoming message of unknown type: " << message; } } void TcpRobotCommunicator::connect() { QString const server = qReal::SettingsManager::value(mSettings).toString(); QHostAddress hostAddress(server); if (hostAddress.isNull()) { QLOG_ERROR() << "Unable to resolve host."; return; } if (mControlConnection.isConnected() && mTelemetryConnection.isConnected()) { return; } bool const result = mControlConnection.connect(hostAddress) && mTelemetryConnection.connect(hostAddress); emit connected(result); } void TcpRobotCommunicator::disconnect() { mControlConnection.disconnect(); mTelemetryConnection.disconnect(); emit disconnected(); } <|endoftext|>
<commit_before>// Copyright (c) 2013, Cloudera, inc. #include <boost/foreach.hpp> #include <gflags/gflags.h> #include <glog/logging.h> #include <iostream> #include <vector> #include "common/row_operations.h" #include "common/wire_protocol.h" #include "consensus/consensus.pb.h" #include "consensus/log_reader.h" #include "gutil/stl_util.h" #include "gutil/strings/numbers.h" #include "util/env.h" #include "util/pb_util.h" DEFINE_bool(print_headers, true, "print the log segment headers"); DEFINE_string(print_entries, "decoded", "How to print entries:\n" " false|0|no = don't print\n" " true|1|yes|decoded = print them decoded\n" " pb = print the raw protobuf\n" " id = print only their ids"); DEFINE_int32(truncate_data, 100, "Truncate the data fields to the given number of bytes " "before printing. Set to 0 to disable"); namespace kudu { namespace log { using consensus::OperationPB; using consensus::OperationType; using consensus::ReplicateMsg; using tserver::WriteRequestPB; using std::string; using std::vector; using std::cout; using std::endl; enum PrintEntryType { DONT_PRINT, PRINT_PB, PRINT_DECODED, PRINT_ID }; static PrintEntryType ParsePrintType() { if (ParseLeadingBoolValue(FLAGS_print_entries.c_str(), true) == false) { return DONT_PRINT; } else if (ParseLeadingBoolValue(FLAGS_print_entries.c_str(), false) == true || FLAGS_print_entries == "decoded") { return PRINT_DECODED; } else if (FLAGS_print_entries == "pb") { return PRINT_PB; } else if (FLAGS_print_entries == "id") { return PRINT_ID; } else { LOG(FATAL) << "Unknown value for --print_entries: " << FLAGS_print_entries; } } void PrintIdOnly(const LogEntryPB& entry) { cout << entry.operation().id().term() << "." << entry.operation().id().index() << "\t"; if (entry.operation().has_commit()) { cout << "COMMIT " << entry.operation().commit().commited_op_id().term() << "." << entry.operation().commit().commited_op_id().index(); } else if (entry.operation().has_replicate()) { cout << "REPLICATE " << OperationType_Name(entry.operation().replicate().op_type()); } else { cout << "UNKNOWN"; } cout << endl; } void PrintDecodedWriteRequestPB(const string& indent, const WriteRequestPB& write) { Schema s; CHECK_OK(SchemaFromPB(write.schema(), &s)); Arena arena(32 * 1024, 1024 * 1024); RowOperationsPBDecoder dec(&write.row_operations(), &s, &s, &arena); vector<DecodedRowOperation> ops; CHECK_OK(dec.DecodeOperations(&ops)); cout << indent << "Tablet: " << write.tablet_id() << endl; cout << indent << "Consistency: " << ExternalConsistencyMode_Name(write.external_consistency_mode()) << endl; if (write.has_propagated_timestamp()) { cout << indent << "Propagated TS: " << write.propagated_timestamp() << endl; } int i = 0; BOOST_FOREACH(const DecodedRowOperation& op, ops) { cout << indent << "op " << (i++) << ": " << op.ToString(s) << endl; } } void PrintDecoded(const LogEntryPB& entry) { CHECK_EQ(entry.type(), log::OPERATION); PrintIdOnly(entry); const string indent = "\t"; if (entry.operation().has_replicate()) { // We can actually decode REPLICATE messages. const ReplicateMsg& replicate = entry.operation().replicate(); if (replicate.op_type() == consensus::WRITE_OP) { PrintDecodedWriteRequestPB(indent, replicate.write_request()); } else { cout << indent << replicate.ShortDebugString() << endl; } } else if (entry.operation().has_commit()) { // For COMMIT we'll just dump the PB cout << indent << entry.operation().commit().ShortDebugString() << endl; } } void PrintSegment(const scoped_refptr<ReadableLogSegment>& segment) { PrintEntryType print_type = ParsePrintType(); if (FLAGS_print_headers) { cout << "Header:\n" << segment->header().DebugString(); } vector<LogEntryPB*> entries; CHECK_OK(segment->ReadEntries(&entries)); if (print_type == DONT_PRINT) return; BOOST_FOREACH(LogEntryPB* entry, entries) { if (print_type == PRINT_PB) { if (FLAGS_truncate_data > 0) { pb_util::TruncateFields(entry, FLAGS_truncate_data); } cout << "Entry:\n" << entry->DebugString(); } else if (print_type == PRINT_DECODED) { PrintDecoded(*entry); } else if (print_type == PRINT_ID) { PrintIdOnly(*entry); } } } void DumpLog(const string &tserver_root_path, const string& tablet_oid) { Env *env = Env::Default(); gscoped_ptr<LogReader> reader; FsManager fs_manager(env, tserver_root_path); CHECK_OK(LogReader::Open(&fs_manager, tablet_oid, &reader)); vector<LogEntryPB*> entries; ElementDeleter deleter(&entries); BOOST_FOREACH(const ReadableLogSegmentMap::value_type& entry, reader->segments()) { PrintSegment(entry.second); } } void DumpSegment(const string &segment_path) { Env *env = Env::Default(); gscoped_ptr<LogReader> reader; scoped_refptr<ReadableLogSegment> segment; CHECK_OK(ReadableLogSegment::Open(env, segment_path, &segment)); CHECK(segment); PrintSegment(segment); } } // namespace log } // namespace kudu int main(int argc, char **argv) { google::InitGoogleLogging(argv[0]); google::ParseCommandLineFlags(&argc, &argv, true); if (argc < 2 || argc > 3) { std::cerr << "usage: " << argv[0] << " <tserver root path> <tablet_name>" " | <log segment path> " << std::endl; return 1; } if (argc == 2) { kudu::log::DumpSegment(argv[1]); } else { kudu::log::DumpLog(argv[1], argv[2]); } return 0; } <commit_msg>KUDU-222 log-dump tool dumps core when log file does not exist<commit_after>// Copyright (c) 2013, Cloudera, inc. #include <boost/foreach.hpp> #include <gflags/gflags.h> #include <glog/logging.h> #include <iostream> #include <vector> #include "common/row_operations.h" #include "common/wire_protocol.h" #include "consensus/consensus.pb.h" #include "consensus/log_reader.h" #include "gutil/stl_util.h" #include "gutil/strings/numbers.h" #include "util/env.h" #include "util/pb_util.h" DEFINE_bool(print_headers, true, "print the log segment headers"); DEFINE_string(print_entries, "decoded", "How to print entries:\n" " false|0|no = don't print\n" " true|1|yes|decoded = print them decoded\n" " pb = print the raw protobuf\n" " id = print only their ids"); DEFINE_int32(truncate_data, 100, "Truncate the data fields to the given number of bytes " "before printing. Set to 0 to disable"); namespace kudu { namespace log { using consensus::OperationPB; using consensus::OperationType; using consensus::ReplicateMsg; using tserver::WriteRequestPB; using std::string; using std::vector; using std::cout; using std::endl; enum PrintEntryType { DONT_PRINT, PRINT_PB, PRINT_DECODED, PRINT_ID }; static PrintEntryType ParsePrintType() { if (ParseLeadingBoolValue(FLAGS_print_entries.c_str(), true) == false) { return DONT_PRINT; } else if (ParseLeadingBoolValue(FLAGS_print_entries.c_str(), false) == true || FLAGS_print_entries == "decoded") { return PRINT_DECODED; } else if (FLAGS_print_entries == "pb") { return PRINT_PB; } else if (FLAGS_print_entries == "id") { return PRINT_ID; } else { LOG(FATAL) << "Unknown value for --print_entries: " << FLAGS_print_entries; } } void PrintIdOnly(const LogEntryPB& entry) { cout << entry.operation().id().term() << "." << entry.operation().id().index() << "\t"; if (entry.operation().has_commit()) { cout << "COMMIT " << entry.operation().commit().commited_op_id().term() << "." << entry.operation().commit().commited_op_id().index(); } else if (entry.operation().has_replicate()) { cout << "REPLICATE " << OperationType_Name(entry.operation().replicate().op_type()); } else { cout << "UNKNOWN"; } cout << endl; } void PrintDecodedWriteRequestPB(const string& indent, const WriteRequestPB& write) { Schema s; CHECK_OK(SchemaFromPB(write.schema(), &s)); Arena arena(32 * 1024, 1024 * 1024); RowOperationsPBDecoder dec(&write.row_operations(), &s, &s, &arena); vector<DecodedRowOperation> ops; CHECK_OK(dec.DecodeOperations(&ops)); cout << indent << "Tablet: " << write.tablet_id() << endl; cout << indent << "Consistency: " << ExternalConsistencyMode_Name(write.external_consistency_mode()) << endl; if (write.has_propagated_timestamp()) { cout << indent << "Propagated TS: " << write.propagated_timestamp() << endl; } int i = 0; BOOST_FOREACH(const DecodedRowOperation& op, ops) { cout << indent << "op " << (i++) << ": " << op.ToString(s) << endl; } } void PrintDecoded(const LogEntryPB& entry) { CHECK_EQ(entry.type(), log::OPERATION); PrintIdOnly(entry); const string indent = "\t"; if (entry.operation().has_replicate()) { // We can actually decode REPLICATE messages. const ReplicateMsg& replicate = entry.operation().replicate(); if (replicate.op_type() == consensus::WRITE_OP) { PrintDecodedWriteRequestPB(indent, replicate.write_request()); } else { cout << indent << replicate.ShortDebugString() << endl; } } else if (entry.operation().has_commit()) { // For COMMIT we'll just dump the PB cout << indent << entry.operation().commit().ShortDebugString() << endl; } } void PrintSegment(const scoped_refptr<ReadableLogSegment>& segment) { PrintEntryType print_type = ParsePrintType(); if (FLAGS_print_headers) { cout << "Header:\n" << segment->header().DebugString(); } vector<LogEntryPB*> entries; CHECK_OK(segment->ReadEntries(&entries)); if (print_type == DONT_PRINT) return; BOOST_FOREACH(LogEntryPB* entry, entries) { if (print_type == PRINT_PB) { if (FLAGS_truncate_data > 0) { pb_util::TruncateFields(entry, FLAGS_truncate_data); } cout << "Entry:\n" << entry->DebugString(); } else if (print_type == PRINT_DECODED) { PrintDecoded(*entry); } else if (print_type == PRINT_ID) { PrintIdOnly(*entry); } } } void DumpLog(const string &tserver_root_path, const string& tablet_oid) { Env *env = Env::Default(); gscoped_ptr<LogReader> reader; FsManager fs_manager(env, tserver_root_path); CHECK_OK(LogReader::Open(&fs_manager, tablet_oid, &reader)); vector<LogEntryPB*> entries; ElementDeleter deleter(&entries); BOOST_FOREACH(const ReadableLogSegmentMap::value_type& entry, reader->segments()) { PrintSegment(entry.second); } } void DumpSegment(const string &segment_path) { Env *env = Env::Default(); gscoped_ptr<LogReader> reader; scoped_refptr<ReadableLogSegment> segment; CHECK_OK(ReadableLogSegment::Open(env, segment_path, &segment)); CHECK(segment); PrintSegment(segment); } } // namespace log } // namespace kudu int main(int argc, char **argv) { google::InitGoogleLogging(argv[0]); google::ParseCommandLineFlags(&argc, &argv, true); if (argc < 2 || argc > 3) { std::cerr << "usage: " << argv[0] << " <tserver root path> <tablet_name>" " | <log segment path> " << std::endl; return 1; } if (argc == 2) { if (!kudu::Env::Default()->FileExists(argv[1])) { std::cerr << "Specified file \"" << argv[1] << "\" does not exist" << std::endl; return 1; } kudu::log::DumpSegment(argv[1]); } else { kudu::log::DumpLog(argv[1], argv[2]); } return 0; } <|endoftext|>
<commit_before>#pragma once #include <array> #include <cmath> #include <string> #include <memory> #include <typeinfo> #include <typeindex> #include "./debugger.hpp" namespace darwin { enum class status { null,ready,busy,leisure,error }; enum class results { null,success,failure }; enum class colors { white,black,red,green,blue,pink,yellow,cyan }; enum class attris { bright,underline }; enum class commands { echo_on,echo_off,reset_cursor,reset_attri,clrscr }; class pixel final { char mChar=' '; std::array<bool,2> mAttris= {{false,false}}; std::array<colors,2> mColors= {{colors::white,colors::black}}; public: pixel()=default; pixel(const pixel&)=default; pixel(char ch,bool bright,bool underline,colors fcolor,colors bcolor):mChar(ch),mAttris( { bright,underline }),mColors({fcolor,bcolor}) {} ~pixel()=default; void set_char(char c) { mChar=c; } char get_char() const { return mChar; } void set_front_color(colors c) { mColors[0]=c; } colors get_front_color() const { return mColors[0]; } void set_back_color(colors c) { mColors[1]=c; } colors get_back_color() const { return mColors[1]; } void set_colors(const std::array<colors,2>& c) { mColors=c; } const std::array<colors,2>& get_colors() const { return mColors; } void set_bright(bool value) { mAttris[0]=value; } bool is_bright() const { return mAttris[0]; } void set_underline(bool value) { mAttris[1]=value; } bool is_underline() const { return mAttris[1]; } void set_attris(const std::array<bool,2>& a) { mAttris=a; } const std::array<bool,2>& get_attris() const { return mAttris; } }; class drawable { public: static double draw_line_precision; drawable()=default; drawable(const drawable&)=default; virtual ~drawable()=default; virtual std::type_index get_type() const final { return typeid(*this); } virtual std::shared_ptr<drawable> clone() noexcept { return nullptr; } virtual bool usable() const noexcept=0; virtual void clear()=0; virtual void fill(const pixel&)=0; virtual void resize(std::size_t,std::size_t)=0; virtual std::size_t get_width() const=0; virtual std::size_t get_height() const=0; virtual const pixel& get_pixel(std::size_t,std::size_t) const=0; virtual void draw_pixel(int,int,const pixel&)=0; virtual void draw_line(int p0x,int p0y,int p1x,int p1y,const pixel& pix) { if(!this->usable()) Darwin_Error("Use of not available object."); if(p0x<0||p0y<0||p1x<0||p1y<0||p0x>this->get_width()-1||p0y>this->get_height()-1||p1x>this->get_width()-1||p1y>this->get_height()-1) Darwin_Warning("Out of range."); long w(p1x-p0x),h(p1y-p0y); double distance(std::sqrt(std::pow(w,2)+std::pow(h,2))*draw_line_precision); for(double c=0; c<=1; c+=1.0/distance) this->draw_pixel(static_cast<int>(p0x+w*c),static_cast<int>(p0y+h*c),pix); this->draw_pixel(p0x,p0y,pix); this->draw_pixel(p1x,p1y,pix); } virtual void draw_rect(int x,int y,int w,int h,const pixel& pix) { if(!this->usable()) Darwin_Error("Use of not available object."); if(x<0||y<0||x>this->get_width()-1||y>this->get_height()-1||x+w>this->get_width()||y+h>this->get_height()) Darwin_Warning("Out of range."); for(int i=0; i<w; w>0?++i:--i) { this->draw_pixel(x+i,y,pix); this->draw_pixel(x+i,y+h-1,pix); } for(int i=1; i<h-1; h>0?++i:--i) { this->draw_pixel(x,y+i,pix); this->draw_pixel(x+w-1,y+i,pix); } } virtual void fill_rect(int x,int y,int w,int h,const pixel& pix) { if(!this->usable()) Darwin_Error("Use of not available object."); if(x<0||y<0||x>this->get_width()-1||y>this->get_height()-1||x+w>this->get_width()||y+h>this->get_height()) Darwin_Warning("Out of range."); for(int cy=0; cy<h; h>0?++cy:--cy) for(int cx=0; cx<w; w>0?++cx:--cx) this->draw_pixel(x+cx,y+cy,pix); } virtual void draw_triangle(int x1,int y1,int x2,int y2,int x3,int y3,const pixel& pix) { if(!this->usable()) Darwin_Error("Use of not available object."); this->draw_line(x1,y1,x2,y2,pix); this->draw_line(x2,y2,x3,y3,pix); this->draw_line(x3,y3,x1,y1,pix); } virtual void fill_triangle(int x1,int y1,int x2,int y2,int x3,int y3,const pixel& pix) { if(!this->usable()) Darwin_Error("Use of not available object."); int v1x(x2-x1),v1y(y2-y1),v2x(x3-x2),v2y(y3-y2); if(v1x*v2y-v2x*v1y==0) Darwin_Warning("Three points in a line."); if(y2<y1) { std::swap(y1,y2); std::swap(x1,x2); } if(y3<y2) { std::swap(y2,y3); std::swap(x2,x3); } if(y2<y1) { std::swap(y1,y2); std::swap(x1,x2); } if(y1==y2) { double k1(double(x3-x1)/double(y3-y1)),k2(double(x3-x2)/double(y3-y2)); for(int y=0; y<=y3-y2; ++y) this->draw_line(x1+k1*y,y1+y,x2+k2*y,y2+y,pix); } else if(y2==y3) { double k1(double(x3-x1)/double(y3-y1)),k2(double(x2-x1)/double(y2-y1)); for(int y=0; y<=y2-y1; ++y) this->draw_line(x1+k1*y,y1+y,x1+k2*y,y1+y,pix); } else { double k1(double(x3-x1)/double(y3-y1)),k2(double(x3-x2)/double(y3-y2)),k3(double(x2-x1)/double(y2-y1)); for(int y=0; y<=y3-y1; ++y) { if(y<y2-y1) this->draw_line(x1+k1*y,y1+y,x1+k3*y,y1+y,pix); else this->draw_line(x1+k1*y,y1+y,x2+k2*(y-(y2-y1)),y1+y,pix); } } } virtual void draw_string(int x,int y,const std::string& str,const pixel& pix) { if(!this->usable()) Darwin_Error("Use of not available object."); if(x<0||y<0||x>this->get_width()-1||y>this->get_height()-1||x+str.size()>this->get_width()) Darwin_Warning("Out of range."); pixel p=pix; for(int i=0; i<str.size(); ++i) { p.set_char(str.at(i)); this->draw_pixel(x+i,y,p); } } virtual void draw_picture(int col,int row,const drawable& pic) { if(!this->usable()||!pic.usable()) Darwin_Error("Use of not available object."); if(col<0||row<0||col>this->get_width()-1||row>this->get_height()-1) Darwin_Warning("Out of range."); int y0(row>=0?row:0),y1(row>=0?0:-row); while(y0<this->get_height()&&y1<pic.get_height()) { int x0(col>=0?col:0),x1(col>=0?0:-col); while(x0<this->get_width()&&x1<pic.get_width()) { this->draw_pixel(x0,y0,pic.get_pixel(x1,y1)); ++x0; ++x1; } ++y0; ++y1; } } }; double drawable::draw_line_precision=1.5; }<commit_msg>Fix some issure<commit_after>#pragma once #include <array> #include <cmath> #include <string> #include <memory> #include <typeinfo> #include <typeindex> #include "./debugger.hpp" namespace darwin { enum class status { null,ready,busy,leisure,error }; enum class results { null,success,failure }; enum class colors { white,black,red,green,blue,pink,yellow,cyan }; enum class attris { bright,underline }; enum class commands { echo_on,echo_off,reset_cursor,reset_attri,clrscr }; class pixel final { char mChar=' '; std::array<bool,2> mAttris= {{false,false}}; std::array<colors,2> mColors= {{colors::white,colors::black}}; public: pixel()=default; pixel(const pixel&)=default; pixel(char ch,bool bright,bool underline,colors fcolor,colors bcolor):mChar(ch),mAttris( { bright,underline }),mColors({fcolor,bcolor}) { if(ch<=31||ch>=127) mChar='\?'; } ~pixel()=default; void set_char(char c) { if(c>31&&c<127) mChar=c; else mChar='\?'; } char get_char() const { return mChar; } void set_front_color(colors c) { mColors[0]=c; } colors get_front_color() const { return mColors[0]; } void set_back_color(colors c) { mColors[1]=c; } colors get_back_color() const { return mColors[1]; } void set_colors(const std::array<colors,2>& c) { mColors=c; } const std::array<colors,2>& get_colors() const { return mColors; } void set_bright(bool value) { mAttris[0]=value; } bool is_bright() const { return mAttris[0]; } void set_underline(bool value) { mAttris[1]=value; } bool is_underline() const { return mAttris[1]; } void set_attris(const std::array<bool,2>& a) { mAttris=a; } const std::array<bool,2>& get_attris() const { return mAttris; } }; class drawable { public: static double draw_line_precision; drawable()=default; drawable(const drawable&)=default; virtual ~drawable()=default; virtual std::type_index get_type() const final { return typeid(*this); } virtual std::shared_ptr<drawable> clone() noexcept { return nullptr; } virtual bool usable() const noexcept=0; virtual void clear()=0; virtual void fill(const pixel&)=0; virtual void resize(std::size_t,std::size_t)=0; virtual std::size_t get_width() const=0; virtual std::size_t get_height() const=0; virtual const pixel& get_pixel(std::size_t,std::size_t) const=0; virtual void draw_pixel(int,int,const pixel&)=0; virtual void draw_line(int p0x,int p0y,int p1x,int p1y,const pixel& pix) { if(!this->usable()) Darwin_Error("Use of not available object."); if(p0x<0||p0y<0||p1x<0||p1y<0||p0x>this->get_width()-1||p0y>this->get_height()-1||p1x>this->get_width()-1||p1y>this->get_height()-1) Darwin_Warning("Out of range."); long w(p1x-p0x),h(p1y-p0y); double distance(std::sqrt(std::pow(w,2)+std::pow(h,2))*draw_line_precision); for(double c=0; c<=1; c+=1.0/distance) this->draw_pixel(static_cast<int>(p0x+w*c),static_cast<int>(p0y+h*c),pix); this->draw_pixel(p0x,p0y,pix); this->draw_pixel(p1x,p1y,pix); } virtual void draw_rect(int x,int y,int w,int h,const pixel& pix) { if(!this->usable()) Darwin_Error("Use of not available object."); if(x<0||y<0||x>this->get_width()-1||y>this->get_height()-1||x+w>this->get_width()||y+h>this->get_height()) Darwin_Warning("Out of range."); for(int i=0; i<w; w>0?++i:--i) { this->draw_pixel(x+i,y,pix); this->draw_pixel(x+i,y+h-1,pix); } for(int i=1; i<h-1; h>0?++i:--i) { this->draw_pixel(x,y+i,pix); this->draw_pixel(x+w-1,y+i,pix); } } virtual void fill_rect(int x,int y,int w,int h,const pixel& pix) { if(!this->usable()) Darwin_Error("Use of not available object."); if(x<0||y<0||x>this->get_width()-1||y>this->get_height()-1||x+w>this->get_width()||y+h>this->get_height()) Darwin_Warning("Out of range."); for(int cy=0; cy<h; h>0?++cy:--cy) for(int cx=0; cx<w; w>0?++cx:--cx) this->draw_pixel(x+cx,y+cy,pix); } virtual void draw_triangle(int x1,int y1,int x2,int y2,int x3,int y3,const pixel& pix) { if(!this->usable()) Darwin_Error("Use of not available object."); this->draw_line(x1,y1,x2,y2,pix); this->draw_line(x2,y2,x3,y3,pix); this->draw_line(x3,y3,x1,y1,pix); } virtual void fill_triangle(int x1,int y1,int x2,int y2,int x3,int y3,const pixel& pix) { if(!this->usable()) Darwin_Error("Use of not available object."); int v1x(x2-x1),v1y(y2-y1),v2x(x3-x2),v2y(y3-y2); if(v1x*v2y-v2x*v1y==0) Darwin_Warning("Three points in a line."); if(y2<y1) { std::swap(y1,y2); std::swap(x1,x2); } if(y3<y2) { std::swap(y2,y3); std::swap(x2,x3); } if(y2<y1) { std::swap(y1,y2); std::swap(x1,x2); } if(y1==y2) { double k1(double(x3-x1)/double(y3-y1)),k2(double(x3-x2)/double(y3-y2)); for(int y=0; y<=y3-y2; ++y) this->draw_line(x1+k1*y,y1+y,x2+k2*y,y2+y,pix); } else if(y2==y3) { double k1(double(x3-x1)/double(y3-y1)),k2(double(x2-x1)/double(y2-y1)); for(int y=0; y<=y2-y1; ++y) this->draw_line(x1+k1*y,y1+y,x1+k2*y,y1+y,pix); } else { double k1(double(x3-x1)/double(y3-y1)),k2(double(x3-x2)/double(y3-y2)),k3(double(x2-x1)/double(y2-y1)); for(int y=0; y<=y3-y1; ++y) { if(y<y2-y1) this->draw_line(x1+k1*y,y1+y,x1+k3*y,y1+y,pix); else this->draw_line(x1+k1*y,y1+y,x2+k2*(y-(y2-y1)),y1+y,pix); } } } virtual void draw_string(int x,int y,const std::string& str,const pixel& pix) { if(!this->usable()) Darwin_Error("Use of not available object."); if(x<0||y<0||x>this->get_width()-1||y>this->get_height()-1||x+str.size()>this->get_width()) Darwin_Warning("Out of range."); pixel p=pix; for(int i=0; i<str.size(); ++i) { p.set_char(str.at(i)); this->draw_pixel(x+i,y,p); } } virtual void draw_picture(int col,int row,const drawable& pic) { if(!this->usable()||!pic.usable()) Darwin_Error("Use of not available object."); if(col<0||row<0||col>this->get_width()-1||row>this->get_height()-1) Darwin_Warning("Out of range."); int y0(row>=0?row:0),y1(row>=0?0:-row); while(y0<this->get_height()&&y1<pic.get_height()) { int x0(col>=0?col:0),x1(col>=0?0:-col); while(x0<this->get_width()&&x1<pic.get_width()) { this->draw_pixel(x0,y0,pic.get_pixel(x1,y1)); ++x0; ++x1; } ++y0; ++y1; } } }; double drawable::draw_line_precision=1.5; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Espers"); // Client version number #define CLIENT_VERSION_SUFFIX " Alpha" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "Patch 7" # define GIT_COMMIT_DATE "May 19, 2019" //$Format:%cD #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <commit_msg>Espers v0.8.7.5 Update-16 Patch-7<commit_after>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Espers"); // Client version number #define CLIENT_VERSION_SUFFIX " Alpha" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "../build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "Patch 7" # define GIT_COMMIT_DATE "May 19, 2019" //$Format:%cD #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <|endoftext|>
<commit_before>#include "TMC2130Stepper.h" #define REG_CHOPCONF 0x6C /////////////////////////////////////////////////////////////////////////////////////// // REG_CHOPCONF uint32_t TMC2130Stepper::CHOPCONF() { uint32_t data = 0x0; send2130(READ|REG_CHOPCONF, &data, 0x0, 0x0); return data; } void TMC2130Stepper::CHOPCONF(uint32_t value) { #ifdef TMC2130DEBUG Serial.print("Set CHOPCONF: "); Serial.println(value); #endif send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, value, 0xFFFFFFFF); } uint8_t TMC2130Stepper::off_time() {return val_toff;} void TMC2130Stepper::off_time(uint8_t value) { #ifdef TMC2130DEBUG Serial.print("Set toff: "); Serial.println(value); #endif if (value > 15) value = 15; val_toff = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, value, 0xF); } uint8_t TMC2130Stepper::hysterisis_start() {return val_hstrt;} void TMC2130Stepper::hysterisis_start(uint8_t value) { #ifdef TMC2130DEBUG Serial.print("Set hstrt: "); Serial.println(value); #endif if (val_chm == 0) { if (value < 1) value = 1; else if (value > 8) value = 8; val_hstrt = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (value-1) << 4, 0x70); } #ifdef TMC2130DEBUG else {Serial.println("chopper_mode bit is set to 1 -> fast_decay_time is in use. No change made.");} #endif } uint8_t TMC2130Stepper::fast_decay_time() {return val_tfd;} void TMC2130Stepper::fast_decay_time(uint8_t value) { #ifdef TMC2130DEBUG Serial.print("Set tfd: "); Serial.println(value); #endif if (val_chm == 1) { if (value > 15) value = 15; val_tfd = value; value = ((uint32_t)value << 4) | (value & 0b111); // Create space between MSB and the bits 0..2 send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 4, 0x870); } #ifdef TMC2130DEBUG else {Serial.println("chopper_mode bit is set to 0 -> hysterisis_start is in use. No change made.");} #endif } int8_t TMC2130Stepper::hysterisis_low() {return val_hend;} void TMC2130Stepper::hysterisis_low(int8_t value) { #ifdef TMC2130DEBUG Serial.print("Set hend: "); Serial.println(value); #endif if (val_chm == 0) { if (value < -3) value = -3; if (value > 12) value = 12; val_hend = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (value+3) << 7, 0x780); } #ifdef TMC2130DEBUG else {Serial.println("chopper_mode bit is set to 1 -> sine_offset is in use. No change made.");} #endif } int8_t TMC2130Stepper::sine_offset() {return val_offset;} void TMC2130Stepper::sine_offset(int8_t value) { #ifdef TMC2130DEBUG Serial.print("Set offset: "); Serial.println(value); #endif if (val_chm == 1) { if (value < -3) value = -3; if (value > 12) value = 12; val_hend = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (value+3) << 7, 0x780); } #ifdef TMC2130DEBUG else {Serial.println("chopper_mode bit is set to 0 -> hysterisis_low is in use. No change made.");} #endif } bool TMC2130Stepper::disable_I_comparator() {return val_disfdcc;} void TMC2130Stepper::disable_I_comparator(bool value) { #ifdef TMC2130DEBUG Serial.print("Set disfdcc: "); Serial.println(value); #endif if (val_chm == 1) { if (value > 1) value = 1; val_disfdcc = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 12, (uint32_t)0b1 << 12); } #ifdef TMC2130DEBUG else {Serial.println("chopper_mode bit is set to 0 -> No change made.");} #endif } bool TMC2130Stepper::random_off_time() {return val_rndtf;} void TMC2130Stepper::random_off_time(bool value) { #ifdef TMC2130DEBUG Serial.print("Set rndtf: "); Serial.println(value); #endif if (value > 1) value = 1; val_rndtf = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 13, (uint32_t)0b1 << 13); } uint8_t TMC2130Stepper::chopper_mode() {return val_chm;} void TMC2130Stepper::chopper_mode(uint8_t value) { #ifdef TMC2130DEBUG Serial.print("Set chm: "); Serial.println(value); #endif if (value > 1) value = 1; val_chm = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 14, (uint32_t)0b1 << 14); } uint8_t TMC2130Stepper::blank_time() {return val_tbl;} void TMC2130Stepper::blank_time(uint8_t value) { #ifdef TMC2130DEBUG Serial.print("Set tbl: "); Serial.println(value); #endif uint8_t valid[] = {54, 36, 24, 16}; if (value < valid[3]) value = valid[3]; // Make sure we find a match for low values for (int i = 0; i<4; i++) { if (value >= valid[i]) { value = valid[i]; break; } } val_tbl = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 15, 0x18000); } bool TMC2130Stepper::high_sense_R() {return val_vsense;} void TMC2130Stepper::high_sense_R(bool value) { #ifdef TMC2130DEBUG Serial.print("Set vsense: "); Serial.println(value); #endif if (value > 1) value = 1; val_vsense = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 17, (uint32_t)0b1 << 17); } bool TMC2130Stepper::fullstep_threshold() {return val_vhighfs;} void TMC2130Stepper::fullstep_threshold(bool value) { #ifdef TMC2130DEBUG Serial.print("Set vhighfs: "); Serial.println(value); #endif if (value > 1) value = 1; val_vhighfs = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 18, (uint32_t)0b1 << 18); } bool TMC2130Stepper::high_speed_mode() {return val_vhighchm;} void TMC2130Stepper::high_speed_mode(bool value) { #ifdef TMC2130DEBUG Serial.print("Set vhighchm: "); Serial.println(value); #endif if (value > 1) value = 1; val_vhighchm = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 19, (uint32_t)0b1 << 19); } uint8_t TMC2130Stepper::sync_phases() {return val_sync;} void TMC2130Stepper::sync_phases(uint8_t value) { #ifdef TMC2130DEBUG Serial.print("Set sync: "); Serial.println(value); #endif if (value > 15) value = 15; val_sync = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 20, 0xF00000); } uint8_t TMC2130Stepper::microsteps() {return val_mres;} void TMC2130Stepper::microsteps(uint8_t value) { #ifdef TMC2130DEBUG Serial.print("Set mres: "); Serial.println(value); #endif int valid[] = { 256, 128, 64, 32, 16, 8, 4, 2, 0 }; uint32_t _hex[] = { 0b0000, 0b0001, 0b0010, 0b0011, 0b0100, 0b0101, 0b0110, 0b0111, 0b1000 }; for (int i = 0; i<9; i++) { if (value >= valid[i]) { val_mres = valid[i]; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, _hex[i] << 24, 0xF000000); break; } } } bool TMC2130Stepper::interpolate() {return val_intpol;} void TMC2130Stepper::interpolate(bool value) { #ifdef TMC2130DEBUG Serial.print("Set intpol: "); Serial.println(value); #endif if (value > 1) value = 1; val_intpol = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 28, (uint32_t)0b1 << 28); } bool TMC2130Stepper::double_edge_step() {return val_dedge;} void TMC2130Stepper::double_edge_step(bool value) { #ifdef TMC2130DEBUG Serial.print("Set dedge: "); Serial.println(value); #endif if (value > 1) value = 1; val_dedge = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 29, (uint32_t)0b1 << 29); } bool TMC2130Stepper::disable_short_protection() {return val_diss2g;} void TMC2130Stepper::disable_short_protection(bool value) { #ifdef TMC2130DEBUG Serial.print("Set diss2g: "); Serial.println(value); #endif if (value > 1) value = 1; val_diss2g = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 30, (uint32_t)0b1 << 30); }<commit_msg>Fix blank time value sent<commit_after>#include "TMC2130Stepper.h" #define REG_CHOPCONF 0x6C /////////////////////////////////////////////////////////////////////////////////////// // REG_CHOPCONF uint32_t TMC2130Stepper::CHOPCONF() { uint32_t data = 0x0; send2130(READ|REG_CHOPCONF, &data, 0x0, 0x0); return data; } void TMC2130Stepper::CHOPCONF(uint32_t value) { #ifdef TMC2130DEBUG Serial.print("Set CHOPCONF: "); Serial.println(value); #endif send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, value, 0xFFFFFFFF); } uint8_t TMC2130Stepper::off_time() {return val_toff;} void TMC2130Stepper::off_time(uint8_t value) { #ifdef TMC2130DEBUG Serial.print("Set toff: "); Serial.println(value); #endif if (value > 15) value = 15; val_toff = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, value, 0xF); } uint8_t TMC2130Stepper::hysterisis_start() {return val_hstrt;} void TMC2130Stepper::hysterisis_start(uint8_t value) { #ifdef TMC2130DEBUG Serial.print("Set hstrt: "); Serial.println(value); #endif if (val_chm == 0) { if (value < 1) value = 1; else if (value > 8) value = 8; val_hstrt = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (value-1) << 4, 0x70); } #ifdef TMC2130DEBUG else {Serial.println("chopper_mode bit is set to 1 -> fast_decay_time is in use. No change made.");} #endif } uint8_t TMC2130Stepper::fast_decay_time() {return val_tfd;} void TMC2130Stepper::fast_decay_time(uint8_t value) { #ifdef TMC2130DEBUG Serial.print("Set tfd: "); Serial.println(value); #endif if (val_chm == 1) { if (value > 15) value = 15; val_tfd = value; value = ((uint32_t)value << 4) | (value & 0b111); // Create space between MSB and the bits 0..2 send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 4, 0x870); } #ifdef TMC2130DEBUG else {Serial.println("chopper_mode bit is set to 0 -> hysterisis_start is in use. No change made.");} #endif } int8_t TMC2130Stepper::hysterisis_low() {return val_hend;} void TMC2130Stepper::hysterisis_low(int8_t value) { #ifdef TMC2130DEBUG Serial.print("Set hend: "); Serial.println(value); #endif if (val_chm == 0) { if (value < -3) value = -3; if (value > 12) value = 12; val_hend = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (value+3) << 7, 0x780); } #ifdef TMC2130DEBUG else {Serial.println("chopper_mode bit is set to 1 -> sine_offset is in use. No change made.");} #endif } int8_t TMC2130Stepper::sine_offset() {return val_offset;} void TMC2130Stepper::sine_offset(int8_t value) { #ifdef TMC2130DEBUG Serial.print("Set offset: "); Serial.println(value); #endif if (val_chm == 1) { if (value < -3) value = -3; if (value > 12) value = 12; val_hend = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (value+3) << 7, 0x780); } #ifdef TMC2130DEBUG else {Serial.println("chopper_mode bit is set to 0 -> hysterisis_low is in use. No change made.");} #endif } bool TMC2130Stepper::disable_I_comparator() {return val_disfdcc;} void TMC2130Stepper::disable_I_comparator(bool value) { #ifdef TMC2130DEBUG Serial.print("Set disfdcc: "); Serial.println(value); #endif if (val_chm == 1) { if (value > 1) value = 1; val_disfdcc = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 12, (uint32_t)0b1 << 12); } #ifdef TMC2130DEBUG else {Serial.println("chopper_mode bit is set to 0 -> No change made.");} #endif } bool TMC2130Stepper::random_off_time() {return val_rndtf;} void TMC2130Stepper::random_off_time(bool value) { #ifdef TMC2130DEBUG Serial.print("Set rndtf: "); Serial.println(value); #endif if (value > 1) value = 1; val_rndtf = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 13, (uint32_t)0b1 << 13); } uint8_t TMC2130Stepper::chopper_mode() {return val_chm;} void TMC2130Stepper::chopper_mode(uint8_t value) { #ifdef TMC2130DEBUG Serial.print("Set chm: "); Serial.println(value); #endif if (value > 1) value = 1; val_chm = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 14, (uint32_t)0b1 << 14); } uint8_t TMC2130Stepper::blank_time() {return val_tbl;} void TMC2130Stepper::blank_time(uint8_t value) { #ifdef TMC2130DEBUG Serial.print("Set tbl: "); Serial.println(value); #endif uint8_t valid[] = {54, 36, 24, 16}; if (value < valid[3]) value = valid[3]; // Make sure we find a match for low values for (int i = 0; i<4; i++) { if (value >= valid[i]) { value = valid[i]; val_tbl = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)i << 15, 0x18000); break; } } } bool TMC2130Stepper::high_sense_R() {return val_vsense;} void TMC2130Stepper::high_sense_R(bool value) { #ifdef TMC2130DEBUG Serial.print("Set vsense: "); Serial.println(value); #endif if (value > 1) value = 1; val_vsense = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 17, (uint32_t)0b1 << 17); } bool TMC2130Stepper::fullstep_threshold() {return val_vhighfs;} void TMC2130Stepper::fullstep_threshold(bool value) { #ifdef TMC2130DEBUG Serial.print("Set vhighfs: "); Serial.println(value); #endif if (value > 1) value = 1; val_vhighfs = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 18, (uint32_t)0b1 << 18); } bool TMC2130Stepper::high_speed_mode() {return val_vhighchm;} void TMC2130Stepper::high_speed_mode(bool value) { #ifdef TMC2130DEBUG Serial.print("Set vhighchm: "); Serial.println(value); #endif if (value > 1) value = 1; val_vhighchm = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 19, (uint32_t)0b1 << 19); } uint8_t TMC2130Stepper::sync_phases() {return val_sync;} void TMC2130Stepper::sync_phases(uint8_t value) { #ifdef TMC2130DEBUG Serial.print("Set sync: "); Serial.println(value); #endif if (value > 15) value = 15; val_sync = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 20, 0xF00000); } uint8_t TMC2130Stepper::microsteps() {return val_mres;} void TMC2130Stepper::microsteps(uint8_t value) { #ifdef TMC2130DEBUG Serial.print("Set mres: "); Serial.println(value); #endif int valid[] = { 256, 128, 64, 32, 16, 8, 4, 2, 0 }; uint32_t _hex[] = { 0b0000, 0b0001, 0b0010, 0b0011, 0b0100, 0b0101, 0b0110, 0b0111, 0b1000 }; for (int i = 0; i<9; i++) { if (value >= valid[i]) { val_mres = valid[i]; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, _hex[i] << 24, 0xF000000); break; } } } bool TMC2130Stepper::interpolate() {return val_intpol;} void TMC2130Stepper::interpolate(bool value) { #ifdef TMC2130DEBUG Serial.print("Set intpol: "); Serial.println(value); #endif if (value > 1) value = 1; val_intpol = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 28, (uint32_t)0b1 << 28); } bool TMC2130Stepper::double_edge_step() {return val_dedge;} void TMC2130Stepper::double_edge_step(bool value) { #ifdef TMC2130DEBUG Serial.print("Set dedge: "); Serial.println(value); #endif if (value > 1) value = 1; val_dedge = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 29, (uint32_t)0b1 << 29); } bool TMC2130Stepper::disable_short_protection() {return val_diss2g;} void TMC2130Stepper::disable_short_protection(bool value) { #ifdef TMC2130DEBUG Serial.print("Set diss2g: "); Serial.println(value); #endif if (value > 1) value = 1; val_diss2g = value; send2130(WRITE|REG_CHOPCONF, &cur_CHOPCONF, (uint32_t)value << 30, (uint32_t)0b1 << 30); }<|endoftext|>
<commit_before>// // This file is part of khmer, http://github.com/ged-lab/khmer/, and is // Copyright (C) Michigan State University, 2009-2013. It is licensed under // the three-clause BSD license; see doc/LICENSE.txt. Contact: [email protected] // #ifndef HASHBITS_HH #define HASHBITS_HH #include <vector> #include "hashtable.hh" #include "subset.hh" #define next_f(kmer_f, ch) ((((kmer_f) << 2) & bitmask) | (twobit_repr(ch))) #define next_r(kmer_r, ch) (((kmer_r) >> 2) | (twobit_comp(ch) << rc_left_shift)) #define prev_f(kmer_f, ch) ((kmer_f) >> 2 | twobit_repr(ch) << rc_left_shift) #define prev_r(kmer_r, ch) ((((kmer_r) << 2) & bitmask) | (twobit_comp(ch))) #define set_contains(s, e) ((s).find(e) != (s).end()) namespace khmer { class CountingHash; class Hashbits : public khmer::Hashtable { friend class SubsetPartition; protected: std::vector<HashIntoType> _tablesizes; unsigned int _n_tables; unsigned int _tag_density; HashIntoType _occupied_bins; HashIntoType _n_unique_kmers; HashIntoType _n_overlap_kmers; Byte ** _counts; virtual void _allocate_counters() { _n_tables = _tablesizes.size(); HashIntoType tablebytes; HashIntoType tablesize; _counts = new Byte*[_n_tables]; for (unsigned int i = 0; i < _n_tables; i++) { tablesize = _tablesizes[i]; tablebytes = tablesize / 8 + 1; _counts[i] = new Byte[tablebytes]; memset(_counts[i], 0, tablebytes); } } void _clear_all_partitions() { if (partition != NULL) { partition->_clear_all_partitions(); } } uint32_t _all_tags_spin_lock; public: SubsetPartition * partition; SeenSet all_tags; SeenSet stop_tags; SeenSet repart_small_tags; void _validate_pmap() { if (partition) { partition->_validate_pmap(); } } Hashbits(WordLength ksize, std::vector<HashIntoType>& tablesizes) : khmer::Hashtable(ksize), _tablesizes(tablesizes), _all_tags_spin_lock( 0 ) { _tag_density = DEFAULT_TAG_DENSITY; assert(_tag_density % 2 == 0); partition = new SubsetPartition(this); _occupied_bins = 0; _n_unique_kmers = 0; _n_overlap_kmers = 0; _allocate_counters(); } ~Hashbits() { if (_counts) { for (unsigned int i = 0; i < _n_tables; i++) { delete _counts[i]; _counts[i] = NULL; } delete _counts; _counts = NULL; _n_tables = 0; } _clear_all_partitions(); } std::vector<HashIntoType> get_tablesizes() const { return _tablesizes; } virtual void save(std::string); virtual void load(std::string); virtual void save_tagset(std::string); virtual void load_tagset(std::string, bool clear_tags=true); // for debugging/testing purposes only! void _set_tag_density(unsigned int d) { assert(d % 2 == 0); // must be even assert(all_tags.size() == 0); // no tags exist! _tag_density = d; } unsigned int _get_tag_density() const { return _tag_density; } void add_tag(HashIntoType tag) { all_tags.insert(tag); } void add_stop_tag(HashIntoType tag) { stop_tags.insert(tag); } void calc_connected_graph_size(const char * kmer, unsigned long long& count, SeenSet& keeper, const unsigned long long threshold=0, bool break_on_circum=false) const{ HashIntoType r, f; _hash(kmer, _ksize, f, r); calc_connected_graph_size(f, r, count, keeper, threshold, break_on_circum); } void calc_connected_graph_size(const HashIntoType kmer_f, const HashIntoType kmer_r, unsigned long long& count, SeenSet& keeper, const unsigned long long threshold=0, bool break_on_circum=false) const; typedef void (*kmer_cb)(const char * k, unsigned int n_reads, void *data); // Partitioning stuff. unsigned int n_tags() const { return all_tags.size(); } void divide_tags_into_subsets(unsigned int subset_size, SeenSet& divvy); void add_kmer_to_tags(HashIntoType kmer) { all_tags.insert(kmer); } void clear_tags() { all_tags.clear(); } // Count every k-mer in a FASTA or FASTQ file. // Tag certain ones on the connectivity graph. void consume_fasta_and_tag( std::string const &filename, unsigned int &total_reads, unsigned long long &n_consumed, CallbackFn callback = NULL, void * callback_data = NULL ); // Count every k-mer from a stream of FASTA or FASTQ reads, // using the supplied parser. // Tag certain ones on the connectivity graph. void consume_fasta_and_tag( read_parsers:: IParser * parser, unsigned int &total_reads, unsigned long long &n_consumed, CallbackFn callback = NULL, void * callback_data = NULL ); void consume_sequence_and_tag(const std::string& seq, unsigned long long& n_consumed, SeenSet * new_tags = 0); void consume_fasta_and_tag_with_stoptags(const std::string &filename, unsigned int &total_reads, unsigned long long &n_consumed, CallbackFn callback = 0, void * callback_data = 0); void consume_fasta_and_traverse(const std::string &filename, unsigned int distance, unsigned int big_threshold, unsigned int transfer_threshold, CountingHash &counting); void consume_partitioned_fasta(const std::string &filename, unsigned int &total_reads, unsigned long long &n_consumed, CallbackFn callback = 0, void * callback_data = 0); // for overlap k-mer counting void consume_fasta_overlap(const std::string &filename,HashIntoType curve[2][100], khmer::Hashbits &ht2, unsigned int &total_reads, unsigned long long &n_consumed, CallbackFn callback, void * callback_data); // just for overlap k-mer counting! unsigned int check_and_process_read_overlap(std::string &read, bool &is_valid, khmer::Hashbits &ht2); // for overlap k-mer counting! unsigned int consume_string_overlap(const std::string &s, khmer::Hashbits &ht2); unsigned int kmer_degree(HashIntoType kmer_f, HashIntoType kmer_r) const; unsigned int kmer_degree(const char * kmer_s) const { HashIntoType kmer_f, kmer_r; _hash(kmer_s, _ksize, kmer_f, kmer_r); return kmer_degree(kmer_f, kmer_r); } // count number of occupied bins virtual const HashIntoType n_occupied(HashIntoType start=0, HashIntoType stop=0) const { // @@ CTB need to be able to *save* this... return _occupied_bins/_n_tables; } virtual const HashIntoType n_kmers(HashIntoType start=0, HashIntoType stop=0) const { return _n_unique_kmers; // @@ CTB need to be able to *save* this... } // Get and set the hashbits for the given kmer. inline virtual const BoundedCounterType test_and_set_bits(const char * kmer) { HashIntoType hash = _hash(kmer, _ksize); return test_and_set_bits(hash); } // Get and set the hashbits for the given kmer hash. // Generally, it is better to keep tests and mutations separate, // but, in the interests of efficiency and thread safety, // tests and mutations are being blended here against conventional // software engineering wisdom. inline virtual const bool test_and_set_bits( HashIntoType khash ) { bool is_new_kmer = false; for (unsigned int i = 0; i < _n_tables; i++) { HashIntoType bin = khash % _tablesizes[i]; HashIntoType byte = bin / 8; unsigned char bit = (unsigned char)(1 << (bin % 8)); unsigned char bits_orig = __sync_fetch_and_or( *(_counts + i) + byte, bit ); if (!(bits_orig & bit)) { __sync_add_and_fetch( &_occupied_bins, 1 ); is_new_kmer = true; } } // iteration over hashtables if (is_new_kmer) { __sync_add_and_fetch( &_n_unique_kmers, 1 ); return true; // kmer not seen before } return false; // kmer already seen } // test_and_set_bits virtual const HashIntoType n_overlap_kmers(HashIntoType start=0, HashIntoType stop=0) const { return _n_overlap_kmers; // @@ CTB need to be able to *save* this... } virtual void count(const char * kmer) { HashIntoType hash = _hash(kmer, _ksize); count(hash); } virtual void count(HashIntoType khash) { bool is_new_kmer = false; for (unsigned int i = 0; i < _n_tables; i++) { HashIntoType bin = khash % _tablesizes[i]; HashIntoType byte = bin / 8; unsigned char bit = bin % 8; if (!( _counts[i][byte] & (1<<bit))) { _occupied_bins += 1; is_new_kmer = true; } _counts[i][byte] |= (1 << bit); } if (is_new_kmer) { _n_unique_kmers +=1; } } virtual bool check_overlap(HashIntoType khash, Hashbits &ht2) { for (unsigned int i = 0; i < ht2._n_tables; i++) { HashIntoType bin = khash % ht2._tablesizes[i]; HashIntoType byte = bin / 8; unsigned char bit = bin % 8; if (!( ht2._counts[i][byte] & (1<<bit))) { return false; } } return true; } virtual void count_overlap(const char * kmer, Hashbits &ht2) { HashIntoType hash = _hash(kmer, _ksize); count_overlap(hash,ht2); } virtual void count_overlap(HashIntoType khash, Hashbits &ht2) { bool is_new_kmer = false; for (unsigned int i = 0; i < _n_tables; i++) { HashIntoType bin = khash % _tablesizes[i]; HashIntoType byte = bin / 8; unsigned char bit = bin % 8; if (!( _counts[i][byte] & (1<<bit))) { _occupied_bins += 1; is_new_kmer = true; } _counts[i][byte] |= (1 << bit); } if (is_new_kmer) { _n_unique_kmers +=1; if (check_overlap(khash,ht2)){ _n_overlap_kmers +=1; } } } // get the count for the given k-mer. virtual const BoundedCounterType get_count(const char * kmer) const { HashIntoType hash = _hash(kmer, _ksize); return get_count(hash); } // get the count for the given k-mer hash. virtual const BoundedCounterType get_count(HashIntoType khash) const { for (unsigned int i = 0; i < _n_tables; i++) { HashIntoType bin = khash % _tablesizes[i]; HashIntoType byte = bin / 8; unsigned char bit = bin % 8; if (!(_counts[i][byte] & (1 << bit))) { return 0; } } return 1; } void filter_if_present(const std::string infilename, const std::string outputfilename, CallbackFn callback=0, void * callback_data=0); unsigned int count_kmers_within_radius(HashIntoType kmer_f, HashIntoType kmer_r, unsigned int radius, unsigned int max_count, const SeenSet * seen=0) const; unsigned int count_kmers_within_depth(HashIntoType kmer_f, HashIntoType kmer_r, unsigned int depth, unsigned int max_count, SeenSet * seen) const; unsigned int find_radius_for_volume(HashIntoType kmer_f, HashIntoType kmer_r, unsigned int max_count, unsigned int max_radius) const; unsigned int count_kmers_on_radius(HashIntoType kmer_f, HashIntoType kmer_r, unsigned int radius, unsigned int max_volume) const; unsigned int trim_on_degree(std::string sequence, unsigned int max_degree) const; unsigned int trim_on_sodd(std::string sequence, unsigned int max_degree) const; unsigned int trim_on_density_explosion(std::string sequence, unsigned int radius, unsigned int max_volume) const; unsigned int trim_on_stoptags(std::string sequence) const; void traverse_from_tags(unsigned int distance, unsigned int threshold, unsigned int num_high_todo, CountingHash &counting); unsigned int traverse_from_kmer(HashIntoType start, unsigned int radius, SeenSet &keeper) const; unsigned int count_and_transfer_to_stoptags(SeenSet &keeper, unsigned int threshold, CountingHash &counting); void traverse_from_reads(std::string filename, unsigned int radius, unsigned int big_threshold, unsigned int transfer_threshold, CountingHash &counting); void hitraverse_to_stoptags(std::string filename, CountingHash &counting, unsigned int cutoff); virtual void print_tagset(std::string); virtual void print_stop_tags(std::string); virtual void save_stop_tags(std::string); void load_stop_tags(std::string filename, bool clear_tags=true); void identify_stop_tags_by_position(std::string sequence, std::vector<unsigned int> &posns) const; void extract_unique_paths(std::string seq, unsigned int min_length, float min_unique_f, std::vector<std::string> &results); }; }; #define ACQUIRE_ALL_TAGS_SPIN_LOCK \ while (!__sync_bool_compare_and_swap( &_all_tags_spin_lock, 0, 1 )); #define RELEASE_ALL_TAGS_SPIN_LOCK \ __sync_bool_compare_and_swap( &_all_tags_spin_lock, 1, 0 ); #include "counting.hh" #endif // HASHBITS_HH // vim: set sts=2 sw=2: <commit_msg>CID 1054818: Resource leak in object (CTOR_DTOR_LEAK)<commit_after>// // This file is part of khmer, http://github.com/ged-lab/khmer/, and is // Copyright (C) Michigan State University, 2009-2013. It is licensed under // the three-clause BSD license; see doc/LICENSE.txt. Contact: [email protected] // #ifndef HASHBITS_HH #define HASHBITS_HH #include <vector> #include "hashtable.hh" #include "subset.hh" #define next_f(kmer_f, ch) ((((kmer_f) << 2) & bitmask) | (twobit_repr(ch))) #define next_r(kmer_r, ch) (((kmer_r) >> 2) | (twobit_comp(ch) << rc_left_shift)) #define prev_f(kmer_f, ch) ((kmer_f) >> 2 | twobit_repr(ch) << rc_left_shift) #define prev_r(kmer_r, ch) ((((kmer_r) << 2) & bitmask) | (twobit_comp(ch))) #define set_contains(s, e) ((s).find(e) != (s).end()) namespace khmer { class CountingHash; class Hashbits : public khmer::Hashtable { friend class SubsetPartition; protected: std::vector<HashIntoType> _tablesizes; unsigned int _n_tables; unsigned int _tag_density; HashIntoType _occupied_bins; HashIntoType _n_unique_kmers; HashIntoType _n_overlap_kmers; Byte ** _counts; virtual void _allocate_counters() { _n_tables = _tablesizes.size(); HashIntoType tablebytes; HashIntoType tablesize; _counts = new Byte*[_n_tables]; for (unsigned int i = 0; i < _n_tables; i++) { tablesize = _tablesizes[i]; tablebytes = tablesize / 8 + 1; _counts[i] = new Byte[tablebytes]; memset(_counts[i], 0, tablebytes); } } void _clear_all_partitions() { if (partition != NULL) { partition->_clear_all_partitions(); } } uint32_t _all_tags_spin_lock; public: SubsetPartition * partition; SeenSet all_tags; SeenSet stop_tags; SeenSet repart_small_tags; void _validate_pmap() { if (partition) { partition->_validate_pmap(); } } Hashbits(WordLength ksize, std::vector<HashIntoType>& tablesizes) : khmer::Hashtable(ksize), _tablesizes(tablesizes), _all_tags_spin_lock( 0 ) { _tag_density = DEFAULT_TAG_DENSITY; assert(_tag_density % 2 == 0); partition = new SubsetPartition(this); _occupied_bins = 0; _n_unique_kmers = 0; _n_overlap_kmers = 0; _allocate_counters(); } ~Hashbits() { if (_counts) { for (unsigned int i = 0; i < _n_tables; i++) { delete _counts[i]; _counts[i] = NULL; } delete _counts; _counts = NULL; _n_tables = 0; } _clear_all_partitions(); delete partition; } std::vector<HashIntoType> get_tablesizes() const { return _tablesizes; } virtual void save(std::string); virtual void load(std::string); virtual void save_tagset(std::string); virtual void load_tagset(std::string, bool clear_tags=true); // for debugging/testing purposes only! void _set_tag_density(unsigned int d) { assert(d % 2 == 0); // must be even assert(all_tags.size() == 0); // no tags exist! _tag_density = d; } unsigned int _get_tag_density() const { return _tag_density; } void add_tag(HashIntoType tag) { all_tags.insert(tag); } void add_stop_tag(HashIntoType tag) { stop_tags.insert(tag); } void calc_connected_graph_size(const char * kmer, unsigned long long& count, SeenSet& keeper, const unsigned long long threshold=0, bool break_on_circum=false) const{ HashIntoType r, f; _hash(kmer, _ksize, f, r); calc_connected_graph_size(f, r, count, keeper, threshold, break_on_circum); } void calc_connected_graph_size(const HashIntoType kmer_f, const HashIntoType kmer_r, unsigned long long& count, SeenSet& keeper, const unsigned long long threshold=0, bool break_on_circum=false) const; typedef void (*kmer_cb)(const char * k, unsigned int n_reads, void *data); // Partitioning stuff. unsigned int n_tags() const { return all_tags.size(); } void divide_tags_into_subsets(unsigned int subset_size, SeenSet& divvy); void add_kmer_to_tags(HashIntoType kmer) { all_tags.insert(kmer); } void clear_tags() { all_tags.clear(); } // Count every k-mer in a FASTA or FASTQ file. // Tag certain ones on the connectivity graph. void consume_fasta_and_tag( std::string const &filename, unsigned int &total_reads, unsigned long long &n_consumed, CallbackFn callback = NULL, void * callback_data = NULL ); // Count every k-mer from a stream of FASTA or FASTQ reads, // using the supplied parser. // Tag certain ones on the connectivity graph. void consume_fasta_and_tag( read_parsers:: IParser * parser, unsigned int &total_reads, unsigned long long &n_consumed, CallbackFn callback = NULL, void * callback_data = NULL ); void consume_sequence_and_tag(const std::string& seq, unsigned long long& n_consumed, SeenSet * new_tags = 0); void consume_fasta_and_tag_with_stoptags(const std::string &filename, unsigned int &total_reads, unsigned long long &n_consumed, CallbackFn callback = 0, void * callback_data = 0); void consume_fasta_and_traverse(const std::string &filename, unsigned int distance, unsigned int big_threshold, unsigned int transfer_threshold, CountingHash &counting); void consume_partitioned_fasta(const std::string &filename, unsigned int &total_reads, unsigned long long &n_consumed, CallbackFn callback = 0, void * callback_data = 0); // for overlap k-mer counting void consume_fasta_overlap(const std::string &filename,HashIntoType curve[2][100], khmer::Hashbits &ht2, unsigned int &total_reads, unsigned long long &n_consumed, CallbackFn callback, void * callback_data); // just for overlap k-mer counting! unsigned int check_and_process_read_overlap(std::string &read, bool &is_valid, khmer::Hashbits &ht2); // for overlap k-mer counting! unsigned int consume_string_overlap(const std::string &s, khmer::Hashbits &ht2); unsigned int kmer_degree(HashIntoType kmer_f, HashIntoType kmer_r) const; unsigned int kmer_degree(const char * kmer_s) const { HashIntoType kmer_f, kmer_r; _hash(kmer_s, _ksize, kmer_f, kmer_r); return kmer_degree(kmer_f, kmer_r); } // count number of occupied bins virtual const HashIntoType n_occupied(HashIntoType start=0, HashIntoType stop=0) const { // @@ CTB need to be able to *save* this... return _occupied_bins/_n_tables; } virtual const HashIntoType n_kmers(HashIntoType start=0, HashIntoType stop=0) const { return _n_unique_kmers; // @@ CTB need to be able to *save* this... } // Get and set the hashbits for the given kmer. inline virtual const BoundedCounterType test_and_set_bits(const char * kmer) { HashIntoType hash = _hash(kmer, _ksize); return test_and_set_bits(hash); } // Get and set the hashbits for the given kmer hash. // Generally, it is better to keep tests and mutations separate, // but, in the interests of efficiency and thread safety, // tests and mutations are being blended here against conventional // software engineering wisdom. inline virtual const bool test_and_set_bits( HashIntoType khash ) { bool is_new_kmer = false; for (unsigned int i = 0; i < _n_tables; i++) { HashIntoType bin = khash % _tablesizes[i]; HashIntoType byte = bin / 8; unsigned char bit = (unsigned char)(1 << (bin % 8)); unsigned char bits_orig = __sync_fetch_and_or( *(_counts + i) + byte, bit ); if (!(bits_orig & bit)) { __sync_add_and_fetch( &_occupied_bins, 1 ); is_new_kmer = true; } } // iteration over hashtables if (is_new_kmer) { __sync_add_and_fetch( &_n_unique_kmers, 1 ); return true; // kmer not seen before } return false; // kmer already seen } // test_and_set_bits virtual const HashIntoType n_overlap_kmers(HashIntoType start=0, HashIntoType stop=0) const { return _n_overlap_kmers; // @@ CTB need to be able to *save* this... } virtual void count(const char * kmer) { HashIntoType hash = _hash(kmer, _ksize); count(hash); } virtual void count(HashIntoType khash) { bool is_new_kmer = false; for (unsigned int i = 0; i < _n_tables; i++) { HashIntoType bin = khash % _tablesizes[i]; HashIntoType byte = bin / 8; unsigned char bit = bin % 8; if (!( _counts[i][byte] & (1<<bit))) { _occupied_bins += 1; is_new_kmer = true; } _counts[i][byte] |= (1 << bit); } if (is_new_kmer) { _n_unique_kmers +=1; } } virtual bool check_overlap(HashIntoType khash, Hashbits &ht2) { for (unsigned int i = 0; i < ht2._n_tables; i++) { HashIntoType bin = khash % ht2._tablesizes[i]; HashIntoType byte = bin / 8; unsigned char bit = bin % 8; if (!( ht2._counts[i][byte] & (1<<bit))) { return false; } } return true; } virtual void count_overlap(const char * kmer, Hashbits &ht2) { HashIntoType hash = _hash(kmer, _ksize); count_overlap(hash,ht2); } virtual void count_overlap(HashIntoType khash, Hashbits &ht2) { bool is_new_kmer = false; for (unsigned int i = 0; i < _n_tables; i++) { HashIntoType bin = khash % _tablesizes[i]; HashIntoType byte = bin / 8; unsigned char bit = bin % 8; if (!( _counts[i][byte] & (1<<bit))) { _occupied_bins += 1; is_new_kmer = true; } _counts[i][byte] |= (1 << bit); } if (is_new_kmer) { _n_unique_kmers +=1; if (check_overlap(khash,ht2)){ _n_overlap_kmers +=1; } } } // get the count for the given k-mer. virtual const BoundedCounterType get_count(const char * kmer) const { HashIntoType hash = _hash(kmer, _ksize); return get_count(hash); } // get the count for the given k-mer hash. virtual const BoundedCounterType get_count(HashIntoType khash) const { for (unsigned int i = 0; i < _n_tables; i++) { HashIntoType bin = khash % _tablesizes[i]; HashIntoType byte = bin / 8; unsigned char bit = bin % 8; if (!(_counts[i][byte] & (1 << bit))) { return 0; } } return 1; } void filter_if_present(const std::string infilename, const std::string outputfilename, CallbackFn callback=0, void * callback_data=0); unsigned int count_kmers_within_radius(HashIntoType kmer_f, HashIntoType kmer_r, unsigned int radius, unsigned int max_count, const SeenSet * seen=0) const; unsigned int count_kmers_within_depth(HashIntoType kmer_f, HashIntoType kmer_r, unsigned int depth, unsigned int max_count, SeenSet * seen) const; unsigned int find_radius_for_volume(HashIntoType kmer_f, HashIntoType kmer_r, unsigned int max_count, unsigned int max_radius) const; unsigned int count_kmers_on_radius(HashIntoType kmer_f, HashIntoType kmer_r, unsigned int radius, unsigned int max_volume) const; unsigned int trim_on_degree(std::string sequence, unsigned int max_degree) const; unsigned int trim_on_sodd(std::string sequence, unsigned int max_degree) const; unsigned int trim_on_density_explosion(std::string sequence, unsigned int radius, unsigned int max_volume) const; unsigned int trim_on_stoptags(std::string sequence) const; void traverse_from_tags(unsigned int distance, unsigned int threshold, unsigned int num_high_todo, CountingHash &counting); unsigned int traverse_from_kmer(HashIntoType start, unsigned int radius, SeenSet &keeper) const; unsigned int count_and_transfer_to_stoptags(SeenSet &keeper, unsigned int threshold, CountingHash &counting); void traverse_from_reads(std::string filename, unsigned int radius, unsigned int big_threshold, unsigned int transfer_threshold, CountingHash &counting); void hitraverse_to_stoptags(std::string filename, CountingHash &counting, unsigned int cutoff); virtual void print_tagset(std::string); virtual void print_stop_tags(std::string); virtual void save_stop_tags(std::string); void load_stop_tags(std::string filename, bool clear_tags=true); void identify_stop_tags_by_position(std::string sequence, std::vector<unsigned int> &posns) const; void extract_unique_paths(std::string seq, unsigned int min_length, float min_unique_f, std::vector<std::string> &results); }; }; #define ACQUIRE_ALL_TAGS_SPIN_LOCK \ while (!__sync_bool_compare_and_swap( &_all_tags_spin_lock, 0, 1 )); #define RELEASE_ALL_TAGS_SPIN_LOCK \ __sync_bool_compare_and_swap( &_all_tags_spin_lock, 1, 0 ); #include "counting.hh" #endif // HASHBITS_HH // vim: set sts=2 sw=2: <|endoftext|>
<commit_before>// Module: Log4CPLUS // File: global-init.cxx // Created: 5/2003 // Author: Tad E. Smith // // // Copyright 2003-2010 Tad E. Smith // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <log4cplus/config.hxx> #include <log4cplus/config/windowsh-inc.h> #include <log4cplus/logger.h> #include <log4cplus/ndc.h> #include <log4cplus/mdc.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/internal/internal.h> #include <log4cplus/thread/impl/tls.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/spi/factory.h> #include <log4cplus/hierarchy.h> #include <cstdio> #include <iostream> #include <stdexcept> // Forward Declarations namespace log4cplus { #ifdef UNICODE LOG4CPLUS_EXPORT tostream & tcout = std::wcout; LOG4CPLUS_EXPORT tostream & tcerr = std::wcerr; #else LOG4CPLUS_EXPORT tostream & tcout = std::cout; LOG4CPLUS_EXPORT tostream & tcerr = std::cerr; #endif // UNICODE namespace { //! Default context. struct DefaultContext { helpers::LogLog loglog; LogLevelManager log_level_manager; helpers::Time TTCCLayout_time_base; NDC ndc; MDC mdc; Hierarchy hierarchy; spi::AppenderFactoryRegistry appender_factory_registry; spi::LayoutFactoryRegistry layout_factory_registry; spi::FilterFactoryRegistry filter_factory_registry; }; enum DCState { DC_UNINITIALIZED, DC_INITIALIZED, DC_DESTROYED }; static DCState default_context_state; static DefaultContext * default_context; struct destroy_default_context { ~destroy_default_context () { delete default_context; default_context = 0; default_context_state = DC_DESTROYED; } } static destroy_default_context_; static void alloc_dc () { assert (! default_context); assert (default_context_state == DC_UNINITIALIZED); if (default_context) throw std::logic_error ( "alloc_dc() called with non-NULL default_context."); if (default_context_state == DC_INITIALIZED) throw std::logic_error ("alloc_dc() called in DC_INITIALIZED state."); default_context = new DefaultContext; if (default_context_state == DC_DESTROYED) default_context->loglog.error ( LOG4CPLUS_TEXT ("Re-initializing default context after it has") LOG4CPLUS_TEXT (" already been destroyed.\n") LOG4CPLUS_TEXT ("The memory will be leaked.")); default_context_state = DC_INITIALIZED; } static DefaultContext * get_dc (bool alloc = true) { if (! default_context && alloc) alloc_dc (); return default_context; } } // namespace namespace helpers { LogLog & getLogLog () { return get_dc ()->loglog; } } // namespace helpers helpers::Time const & getTTCCLayoutTimeBase () { return get_dc ()->TTCCLayout_time_base; } LogLevelManager & getLogLevelManager () { return get_dc ()->log_level_manager; } Hierarchy & getDefaultHierarchy () { return get_dc ()->hierarchy; } NDC & getNDC () { return get_dc ()->ndc; } MDC & getMDC () { return get_dc ()->mdc; } namespace spi { AppenderFactoryRegistry & getAppenderFactoryRegistry () { return get_dc ()->appender_factory_registry; } LayoutFactoryRegistry & getLayoutFactoryRegistry () { return get_dc ()->layout_factory_registry; } FilterFactoryRegistry & getFilterFactoryRegistry () { return get_dc ()->filter_factory_registry; } } // namespace spi namespace internal { gft_scratch_pad::gft_scratch_pad () : uc_q_str_valid (false) , q_str_valid (false) , s_str_valid (false) { } gft_scratch_pad::~gft_scratch_pad () { } appender_sratch_pad::appender_sratch_pad () { } appender_sratch_pad::~appender_sratch_pad () { } per_thread_data::per_thread_data () : fnull (0) { } per_thread_data::~per_thread_data () { if (fnull) std::fclose (fnull); } log4cplus::thread::impl::tls_key_type tls_storage_key; #if ! defined (LOG4CPLUS_SINGLE_THREADED) \ && defined (LOG4CPLUS_THREAD_LOCAL_VAR) LOG4CPLUS_THREAD_LOCAL_VAR per_thread_data * ptd = 0; per_thread_data * alloc_ptd () { per_thread_data * tmp = new per_thread_data; set_ptd (tmp); // This is a special hack. We set the keys' value to non-NULL to // get the ptd_cleanup_func to execute when this thread ends. The // cast is safe; the associated value will never be used if read // again using the key. thread::impl::tls_set_value (tls_storage_key, reinterpret_cast<void *>(1)); return tmp; } # else per_thread_data * alloc_ptd () { per_thread_data * tmp = new per_thread_data; set_ptd (tmp); return tmp; } # endif } // namespace internal void initializeFactoryRegistry(); //! Thread local storage clean up function for POSIX threads. static void ptd_cleanup_func (void * arg) { // Either it is a dummy value or it should be the per thread data // pointer we get from internal::get_ptd(). assert (arg == reinterpret_cast<void *>(1) || arg == internal::get_ptd ()); (void)arg; threadCleanup (); // Setting the value through the key here is necessary in case we // are using TLS using __thread or __declspec(thread) or similar // constructs with POSIX threads. Otherwise POSIX calls this cleanup // routine more than once if the value stays non-NULL after it returns. thread::impl::tls_set_value (internal::tls_storage_key, 0); } void initializeLog4cplus() { static bool initialized = false; if (initialized) return; internal::tls_storage_key = thread::impl::tls_init (ptd_cleanup_func); get_dc (true); Logger::getRoot(); initializeFactoryRegistry(); initialized = true; } static void threadSetup () { internal::get_ptd (true); } void threadCleanup () { // Do thread-specific cleanup. internal::per_thread_data * ptd = internal::get_ptd (false); delete ptd; internal::set_ptd (0); } } // namespace log4cplus #if defined (_WIN32) && defined (LOG4CPLUS_BUILD_DLL) BOOL WINAPI DllMain(LOG4CPLUS_DLLMAIN_HINSTANCE hinstDLL, // handle to DLL module DWORD fdwReason, // reason for calling function LPVOID lpReserved ) // reserved { // Perform actions based on the reason for calling. switch( fdwReason ) { case DLL_PROCESS_ATTACH: { log4cplus::initializeLog4cplus(); // Do thread-specific initialization for the main thread. log4cplus::threadSetup (); break; } case DLL_THREAD_ATTACH: { // Do thread-specific initialization. log4cplus::threadSetup (); break; } case DLL_THREAD_DETACH: { // Do thread-specific cleanup. log4cplus::threadCleanup (); break; } case DLL_PROCESS_DETACH: { // Perform any necessary cleanup. // Do thread-specific cleanup. log4cplus::threadCleanup (); #if ! defined (LOG4CPLUS_THREAD_LOCAL_VAR) log4cplus::thread::impl::tls_cleanup ( log4cplus::internal::tls_storage_key); #endif break; } } return TRUE; // Successful DLL_PROCESS_ATTACH. } #else namespace { struct _static_log4cplus_initializer { _static_log4cplus_initializer () { log4cplus::initializeLog4cplus(); } ~_static_log4cplus_initializer () { // Last thread cleanup. log4cplus::threadCleanup (); } } static initializer; } #endif <commit_msg>global-init.cxx (initializeLog4cplus): Initialize DefaultContext::TTCCLayout_time_base.<commit_after>// Module: Log4CPLUS // File: global-init.cxx // Created: 5/2003 // Author: Tad E. Smith // // // Copyright 2003-2010 Tad E. Smith // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <log4cplus/config.hxx> #include <log4cplus/config/windowsh-inc.h> #include <log4cplus/logger.h> #include <log4cplus/ndc.h> #include <log4cplus/mdc.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/internal/internal.h> #include <log4cplus/thread/impl/tls.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/spi/factory.h> #include <log4cplus/hierarchy.h> #include <cstdio> #include <iostream> #include <stdexcept> // Forward Declarations namespace log4cplus { #ifdef UNICODE LOG4CPLUS_EXPORT tostream & tcout = std::wcout; LOG4CPLUS_EXPORT tostream & tcerr = std::wcerr; #else LOG4CPLUS_EXPORT tostream & tcout = std::cout; LOG4CPLUS_EXPORT tostream & tcerr = std::cerr; #endif // UNICODE namespace { //! Default context. struct DefaultContext { helpers::LogLog loglog; LogLevelManager log_level_manager; helpers::Time TTCCLayout_time_base; NDC ndc; MDC mdc; Hierarchy hierarchy; spi::AppenderFactoryRegistry appender_factory_registry; spi::LayoutFactoryRegistry layout_factory_registry; spi::FilterFactoryRegistry filter_factory_registry; }; enum DCState { DC_UNINITIALIZED, DC_INITIALIZED, DC_DESTROYED }; static DCState default_context_state; static DefaultContext * default_context; struct destroy_default_context { ~destroy_default_context () { delete default_context; default_context = 0; default_context_state = DC_DESTROYED; } } static destroy_default_context_; static void alloc_dc () { assert (! default_context); assert (default_context_state == DC_UNINITIALIZED); if (default_context) throw std::logic_error ( "alloc_dc() called with non-NULL default_context."); if (default_context_state == DC_INITIALIZED) throw std::logic_error ("alloc_dc() called in DC_INITIALIZED state."); default_context = new DefaultContext; if (default_context_state == DC_DESTROYED) default_context->loglog.error ( LOG4CPLUS_TEXT ("Re-initializing default context after it has") LOG4CPLUS_TEXT (" already been destroyed.\n") LOG4CPLUS_TEXT ("The memory will be leaked.")); default_context_state = DC_INITIALIZED; } static DefaultContext * get_dc (bool alloc = true) { if (! default_context && alloc) alloc_dc (); return default_context; } } // namespace namespace helpers { LogLog & getLogLog () { return get_dc ()->loglog; } } // namespace helpers helpers::Time const & getTTCCLayoutTimeBase () { return get_dc ()->TTCCLayout_time_base; } LogLevelManager & getLogLevelManager () { return get_dc ()->log_level_manager; } Hierarchy & getDefaultHierarchy () { return get_dc ()->hierarchy; } NDC & getNDC () { return get_dc ()->ndc; } MDC & getMDC () { return get_dc ()->mdc; } namespace spi { AppenderFactoryRegistry & getAppenderFactoryRegistry () { return get_dc ()->appender_factory_registry; } LayoutFactoryRegistry & getLayoutFactoryRegistry () { return get_dc ()->layout_factory_registry; } FilterFactoryRegistry & getFilterFactoryRegistry () { return get_dc ()->filter_factory_registry; } } // namespace spi namespace internal { gft_scratch_pad::gft_scratch_pad () : uc_q_str_valid (false) , q_str_valid (false) , s_str_valid (false) { } gft_scratch_pad::~gft_scratch_pad () { } appender_sratch_pad::appender_sratch_pad () { } appender_sratch_pad::~appender_sratch_pad () { } per_thread_data::per_thread_data () : fnull (0) { } per_thread_data::~per_thread_data () { if (fnull) std::fclose (fnull); } log4cplus::thread::impl::tls_key_type tls_storage_key; #if ! defined (LOG4CPLUS_SINGLE_THREADED) \ && defined (LOG4CPLUS_THREAD_LOCAL_VAR) LOG4CPLUS_THREAD_LOCAL_VAR per_thread_data * ptd = 0; per_thread_data * alloc_ptd () { per_thread_data * tmp = new per_thread_data; set_ptd (tmp); // This is a special hack. We set the keys' value to non-NULL to // get the ptd_cleanup_func to execute when this thread ends. The // cast is safe; the associated value will never be used if read // again using the key. thread::impl::tls_set_value (tls_storage_key, reinterpret_cast<void *>(1)); return tmp; } # else per_thread_data * alloc_ptd () { per_thread_data * tmp = new per_thread_data; set_ptd (tmp); return tmp; } # endif } // namespace internal void initializeFactoryRegistry(); //! Thread local storage clean up function for POSIX threads. static void ptd_cleanup_func (void * arg) { // Either it is a dummy value or it should be the per thread data // pointer we get from internal::get_ptd(). assert (arg == reinterpret_cast<void *>(1) || arg == internal::get_ptd ()); (void)arg; threadCleanup (); // Setting the value through the key here is necessary in case we // are using TLS using __thread or __declspec(thread) or similar // constructs with POSIX threads. Otherwise POSIX calls this cleanup // routine more than once if the value stays non-NULL after it returns. thread::impl::tls_set_value (internal::tls_storage_key, 0); } void initializeLog4cplus() { static bool initialized = false; if (initialized) return; internal::tls_storage_key = thread::impl::tls_init (ptd_cleanup_func); DefaultContext * dc = get_dc (true); dc->TTCCLayout_time_base = helpers::Time::gettimeofday (); Logger::getRoot(); initializeFactoryRegistry(); initialized = true; } static void threadSetup () { internal::get_ptd (true); } void threadCleanup () { // Do thread-specific cleanup. internal::per_thread_data * ptd = internal::get_ptd (false); delete ptd; internal::set_ptd (0); } } // namespace log4cplus #if defined (_WIN32) && defined (LOG4CPLUS_BUILD_DLL) BOOL WINAPI DllMain(LOG4CPLUS_DLLMAIN_HINSTANCE hinstDLL, // handle to DLL module DWORD fdwReason, // reason for calling function LPVOID lpReserved ) // reserved { // Perform actions based on the reason for calling. switch( fdwReason ) { case DLL_PROCESS_ATTACH: { log4cplus::initializeLog4cplus(); // Do thread-specific initialization for the main thread. log4cplus::threadSetup (); break; } case DLL_THREAD_ATTACH: { // Do thread-specific initialization. log4cplus::threadSetup (); break; } case DLL_THREAD_DETACH: { // Do thread-specific cleanup. log4cplus::threadCleanup (); break; } case DLL_PROCESS_DETACH: { // Perform any necessary cleanup. // Do thread-specific cleanup. log4cplus::threadCleanup (); #if ! defined (LOG4CPLUS_THREAD_LOCAL_VAR) log4cplus::thread::impl::tls_cleanup ( log4cplus::internal::tls_storage_key); #endif break; } } return TRUE; // Successful DLL_PROCESS_ATTACH. } #else namespace { struct _static_log4cplus_initializer { _static_log4cplus_initializer () { log4cplus::initializeLog4cplus(); } ~_static_log4cplus_initializer () { // Last thread cleanup. log4cplus::threadCleanup (); } } static initializer; } #endif <|endoftext|>
<commit_before>#pragma once #include "ims/ims.hpp" #include <libxml2/libxml/xmlreader.h> #include <cstdint> #include <map> #include <string> #include <vector> #include <fstream> namespace imzml{ class Metadata { static const std::map<std::string, std::string> supported_accessions_; std::map<std::string, std::string> dict_; public: Metadata() {} void processNode(xmlTextReaderPtr reader); const std::map<std::string, std::string>& dict() const { return dict_; } }; struct LibXmlString { xmlChar* str; LibXmlString(xmlChar* str) : str(str) { } bool operator==(const char* other) { return !xmlStrcmp(str, (xmlChar*)other); } bool operator==(const std::string& other) { return this->operator==(other.c_str()); } bool operator!=(const char* other) { return !this->operator==(other); } bool operator!=(const std::string& other) { return !this->operator==(other); } operator std::string() const { return std::string((const char*)str); } ~LibXmlString() { xmlFree(str); } }; LibXmlString getAttribute(xmlTextReaderPtr, const char*); class ImzmlReader final : public ims::AbstractReader { Metadata metadata_; std::string filename_; std::string ibd_filename_; xmlTextReaderPtr xml_reader_; int ret; bool have_next_; std::string mz_group_name_, intensity_group_name_; struct ExternalArray { uint64_t file_offset; uint32_t length; uint32_t encoded_length; }; ExternalArray mzs_; ExternalArray intensities_; LibXmlString getAttribute(const char* attribute); template <typename T> T getIntValue() { auto value = getAttribute("value"); return static_cast<T>(std::atoll((const char*)value.str)); } template <typename T> void readIntValue(T& value) { value = getIntValue<T>(); } bool isNodeStart() const { return xmlTextReaderNodeType(xml_reader_) == XML_READER_TYPE_ELEMENT; } template <typename T> void readExternalArray(const ExternalArray& array, std::vector<T>& buffer) { if (array.encoded_length / array.length == 4) readExternalArrayHelper<float, T>(array, buffer); else if (array.encoded_length / array.length == 8) readExternalArrayHelper<double, T>(array, buffer); } template <typename T, typename U> void readExternalArrayHelper(const ExternalArray& array, std::vector<U>& buffer) { std::ifstream in(ibd_filename_); in.seekg(array.file_offset); // FIXME: endianness? std::vector<T> vec(array.length); in.read(reinterpret_cast<char*>(&vec[0]), array.encoded_length); buffer.resize(array.length); std::copy(vec.begin(), vec.end(), buffer.begin()); } void readMetadata(); public: ImzmlReader(const std::string& filename); bool readNextSpectrum(ims::Spectrum& spectrum); const std::map<std::string, std::string>& dict() const; uint32_t height() const; uint32_t width() const; ~ImzmlReader(); }; } <commit_msg>handle empty spectra in .imzML<commit_after>#pragma once #include "ims/ims.hpp" #include <libxml2/libxml/xmlreader.h> #include <cstdint> #include <map> #include <string> #include <vector> #include <fstream> namespace imzml{ class Metadata { static const std::map<std::string, std::string> supported_accessions_; std::map<std::string, std::string> dict_; public: Metadata() {} void processNode(xmlTextReaderPtr reader); const std::map<std::string, std::string>& dict() const { return dict_; } }; struct LibXmlString { xmlChar* str; LibXmlString(xmlChar* str) : str(str) { } bool operator==(const char* other) { return !xmlStrcmp(str, (xmlChar*)other); } bool operator==(const std::string& other) { return this->operator==(other.c_str()); } bool operator!=(const char* other) { return !this->operator==(other); } bool operator!=(const std::string& other) { return !this->operator==(other); } operator std::string() const { return std::string((const char*)str); } ~LibXmlString() { xmlFree(str); } }; LibXmlString getAttribute(xmlTextReaderPtr, const char*); class ImzmlReader final : public ims::AbstractReader { Metadata metadata_; std::string filename_; std::string ibd_filename_; xmlTextReaderPtr xml_reader_; int ret; bool have_next_; std::string mz_group_name_, intensity_group_name_; struct ExternalArray { uint64_t file_offset; uint32_t length; uint32_t encoded_length; }; ExternalArray mzs_; ExternalArray intensities_; LibXmlString getAttribute(const char* attribute); template <typename T> T getIntValue() { auto value = getAttribute("value"); return static_cast<T>(std::atoll((const char*)value.str)); } template <typename T> void readIntValue(T& value) { value = getIntValue<T>(); } bool isNodeStart() const { return xmlTextReaderNodeType(xml_reader_) == XML_READER_TYPE_ELEMENT; } template <typename T> void readExternalArray(const ExternalArray& array, std::vector<T>& buffer) { if (array.length == 0) { buffer.resize(0); return; } if (array.encoded_length / array.length == 4) readExternalArrayHelper<float, T>(array, buffer); else if (array.encoded_length / array.length == 8) readExternalArrayHelper<double, T>(array, buffer); } template <typename T, typename U> void readExternalArrayHelper(const ExternalArray& array, std::vector<U>& buffer) { std::ifstream in(ibd_filename_); in.seekg(array.file_offset); // FIXME: endianness? std::vector<T> vec(array.length); in.read(reinterpret_cast<char*>(&vec[0]), array.encoded_length); buffer.resize(array.length); std::copy(vec.begin(), vec.end(), buffer.begin()); } void readMetadata(); public: ImzmlReader(const std::string& filename); bool readNextSpectrum(ims::Spectrum& spectrum); const std::map<std::string, std::string>& dict() const; uint32_t height() const; uint32_t width() const; ~ImzmlReader(); }; } <|endoftext|>
<commit_before>/* * Copyright deipi.com LLC and contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <fcntl.h> #include <netinet/in.h> #include <sys/socket.h> #include <assert.h> #include <xapian.h> #include "utils.h" #include "xapiand.h" #include "server.h" #include "client_http.h" #include "client_binary.h" const int MSECS_IDLE_TIMEOUT_DEFAULT = 60000; const int MSECS_ACTIVE_TIMEOUT_DEFAULT = 15000; // // Xapian Server // int XapiandServer::total_clients = 0; XapiandServer::XapiandServer(XapiandManager *manager_, ev::loop_ref *loop_, int http_sock_, int binary_sock_, DatabasePool *database_pool_, ThreadPool *thread_pool_) : manager(manager_), iterator(manager_->attach_server(this)), loop(loop_ ? loop_: &dynamic_loop), http_io(*loop), binary_io(*loop), break_loop(*loop), http_sock(http_sock_), binary_sock(binary_sock_), database_pool(database_pool_), thread_pool(thread_pool_) { pthread_mutex_init(&clients_mutex, 0); break_loop.set<XapiandServer, &XapiandServer::break_loop_cb>(this); break_loop.start(); http_io.set<XapiandServer, &XapiandServer::io_accept_http>(this); http_io.start(http_sock, ev::READ); binary_io.set<XapiandServer, &XapiandServer::io_accept_binary>(this); binary_io.start(binary_sock, ev::READ); LOG_OBJ(this, "CREATED SERVER!\n"); } XapiandServer::~XapiandServer() { http_io.stop(); binary_io.stop(); break_loop.stop(); pthread_mutex_destroy(&clients_mutex); manager->detach_server(this); LOG_OBJ(this, "DELETED SERVER!\n"); } void XapiandServer::run() { LOG_OBJ(this, "Starting server loop...\n"); loop->run(0); LOG_OBJ(this, "Server loop ended!\n"); } void XapiandServer::io_accept_http(ev::io &watcher, int revents) { if (EV_ERROR & revents) { LOG_EV(this, "ERROR: got invalid http event (sock=%d): %s\n", http_sock, strerror(errno)); return; } struct sockaddr_in client_addr; socklen_t client_len = sizeof(client_addr); int client_sock = ::accept(watcher.fd, (struct sockaddr *)&client_addr, &client_len); if (client_sock < 0) { if (errno != EAGAIN) { LOG_CONN(this, "ERROR: accept http error (sock=%d): %s\n", http_sock, strerror(errno)); } } else { fcntl(client_sock, F_SETFL, fcntl(client_sock, F_GETFL, 0) | O_NONBLOCK); double active_timeout = MSECS_ACTIVE_TIMEOUT_DEFAULT * 1e-3; double idle_timeout = MSECS_IDLE_TIMEOUT_DEFAULT * 1e-3; new HttpClient(this, loop, client_sock, database_pool, thread_pool, active_timeout, idle_timeout); } } void XapiandServer::io_accept_binary(ev::io &watcher, int revents) { if (EV_ERROR & revents) { LOG_EV(this, "ERROR: got invalid binary event (sock=%d): %s\n", binary_sock, strerror(errno)); return; } struct sockaddr_in client_addr; socklen_t client_len = sizeof(client_addr); int client_sock = ::accept(watcher.fd, (struct sockaddr *)&client_addr, &client_len); if (client_sock < 0) { if (errno != EAGAIN) { LOG_CONN(this, "ERROR: accept binary error (sock=%d): %s\n", binary_sock, strerror(errno)); } } else { fcntl(client_sock, F_SETFL, fcntl(client_sock, F_GETFL, 0) | O_NONBLOCK); double active_timeout = MSECS_ACTIVE_TIMEOUT_DEFAULT * 1e-3; double idle_timeout = MSECS_IDLE_TIMEOUT_DEFAULT * 1e-3; new BinaryClient(this, loop, client_sock, database_pool, thread_pool, active_timeout, idle_timeout); } } void XapiandServer::destroy() { if (http_sock == -1 && binary_sock == -1) { return; } http_sock = -1; binary_sock = -1; http_io.stop(); binary_io.stop(); // http and binary sockets are closed in the manager. LOG_OBJ(this, "DESTROYED SERVER!\n"); } void XapiandServer::break_loop_cb(ev::async &watcher, int revents) { LOG_OBJ(this, "Breaking server loop!\n"); loop->break_loop(); } std::list<BaseClient *>::const_iterator XapiandServer::attach_client(BaseClient *client) { pthread_mutex_lock(&clients_mutex); std::list<BaseClient *>::const_iterator iterator = clients.insert(clients.end(), client); pthread_mutex_unlock(&clients_mutex); return iterator; } void XapiandServer::detach_client(BaseClient *client) { pthread_mutex_lock(&clients_mutex); if (client->iterator != clients.end()) { clients.erase(client->iterator); client->iterator = clients.end(); } pthread_mutex_unlock(&clients_mutex); } void XapiandServer::shutdown() { std::list<BaseClient *>::const_iterator it(clients.begin()); while (it != clients.end()) { (*it)->shutdown(); it = clients.begin(); } if (manager->shutdown_asap) { destroy(); if (total_clients == 0) { manager->shutdown_now = manager->shutdown_asap; } } if (manager->shutdown_now) { break_loop.send(); } } <commit_msg>Destroy server after setting shutdown_now (if set)<commit_after>/* * Copyright deipi.com LLC and contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <fcntl.h> #include <netinet/in.h> #include <sys/socket.h> #include <assert.h> #include <xapian.h> #include "utils.h" #include "xapiand.h" #include "server.h" #include "client_http.h" #include "client_binary.h" const int MSECS_IDLE_TIMEOUT_DEFAULT = 60000; const int MSECS_ACTIVE_TIMEOUT_DEFAULT = 15000; // // Xapian Server // int XapiandServer::total_clients = 0; XapiandServer::XapiandServer(XapiandManager *manager_, ev::loop_ref *loop_, int http_sock_, int binary_sock_, DatabasePool *database_pool_, ThreadPool *thread_pool_) : manager(manager_), iterator(manager_->attach_server(this)), loop(loop_ ? loop_: &dynamic_loop), http_io(*loop), binary_io(*loop), break_loop(*loop), http_sock(http_sock_), binary_sock(binary_sock_), database_pool(database_pool_), thread_pool(thread_pool_) { pthread_mutex_init(&clients_mutex, 0); break_loop.set<XapiandServer, &XapiandServer::break_loop_cb>(this); break_loop.start(); http_io.set<XapiandServer, &XapiandServer::io_accept_http>(this); http_io.start(http_sock, ev::READ); binary_io.set<XapiandServer, &XapiandServer::io_accept_binary>(this); binary_io.start(binary_sock, ev::READ); LOG_OBJ(this, "CREATED SERVER!\n"); } XapiandServer::~XapiandServer() { http_io.stop(); binary_io.stop(); break_loop.stop(); pthread_mutex_destroy(&clients_mutex); manager->detach_server(this); LOG_OBJ(this, "DELETED SERVER!\n"); } void XapiandServer::run() { LOG_OBJ(this, "Starting server loop...\n"); loop->run(0); LOG_OBJ(this, "Server loop ended!\n"); } void XapiandServer::io_accept_http(ev::io &watcher, int revents) { if (EV_ERROR & revents) { LOG_EV(this, "ERROR: got invalid http event (sock=%d): %s\n", http_sock, strerror(errno)); return; } struct sockaddr_in client_addr; socklen_t client_len = sizeof(client_addr); int client_sock = ::accept(watcher.fd, (struct sockaddr *)&client_addr, &client_len); if (client_sock < 0) { if (errno != EAGAIN) { LOG_CONN(this, "ERROR: accept http error (sock=%d): %s\n", http_sock, strerror(errno)); } } else { fcntl(client_sock, F_SETFL, fcntl(client_sock, F_GETFL, 0) | O_NONBLOCK); double active_timeout = MSECS_ACTIVE_TIMEOUT_DEFAULT * 1e-3; double idle_timeout = MSECS_IDLE_TIMEOUT_DEFAULT * 1e-3; new HttpClient(this, loop, client_sock, database_pool, thread_pool, active_timeout, idle_timeout); } } void XapiandServer::io_accept_binary(ev::io &watcher, int revents) { if (EV_ERROR & revents) { LOG_EV(this, "ERROR: got invalid binary event (sock=%d): %s\n", binary_sock, strerror(errno)); return; } struct sockaddr_in client_addr; socklen_t client_len = sizeof(client_addr); int client_sock = ::accept(watcher.fd, (struct sockaddr *)&client_addr, &client_len); if (client_sock < 0) { if (errno != EAGAIN) { LOG_CONN(this, "ERROR: accept binary error (sock=%d): %s\n", binary_sock, strerror(errno)); } } else { fcntl(client_sock, F_SETFL, fcntl(client_sock, F_GETFL, 0) | O_NONBLOCK); double active_timeout = MSECS_ACTIVE_TIMEOUT_DEFAULT * 1e-3; double idle_timeout = MSECS_IDLE_TIMEOUT_DEFAULT * 1e-3; new BinaryClient(this, loop, client_sock, database_pool, thread_pool, active_timeout, idle_timeout); } } void XapiandServer::destroy() { if (http_sock == -1 && binary_sock == -1) { return; } http_sock = -1; binary_sock = -1; http_io.stop(); binary_io.stop(); // http and binary sockets are closed in the manager. LOG_OBJ(this, "DESTROYED SERVER!\n"); } void XapiandServer::break_loop_cb(ev::async &watcher, int revents) { LOG_OBJ(this, "Breaking server loop!\n"); loop->break_loop(); } std::list<BaseClient *>::const_iterator XapiandServer::attach_client(BaseClient *client) { pthread_mutex_lock(&clients_mutex); std::list<BaseClient *>::const_iterator iterator = clients.insert(clients.end(), client); pthread_mutex_unlock(&clients_mutex); return iterator; } void XapiandServer::detach_client(BaseClient *client) { pthread_mutex_lock(&clients_mutex); if (client->iterator != clients.end()) { clients.erase(client->iterator); client->iterator = clients.end(); } pthread_mutex_unlock(&clients_mutex); } void XapiandServer::shutdown() { std::list<BaseClient *>::const_iterator it(clients.begin()); while (it != clients.end()) { (*it)->shutdown(); it = clients.begin(); } if (manager->shutdown_asap) { if (total_clients == 0) { manager->shutdown_now = manager->shutdown_asap; } destroy(); } if (manager->shutdown_now) { break_loop.send(); } } <|endoftext|>
<commit_before>#include <string> #include "ccspec/core.h" #include "ccspec/expectation.h" #include "ccspec/matchers.h" using std::string; using ccspec::core::before; using ccspec::core::context; using ccspec::core::describe; using ccspec::core::it; using ccspec::expect; using ccspec::matchers::be_falsey; using ccspec::matchers::be_truthy; using ccspec::matchers::be; using ccspec::matchers::eq; namespace spec { namespace matchers { auto be_compared_to_spec = describe("BeComparedTo", [] { context("with < comparator", [] { it("matches if actual const temp char is < expected", [] { expect((be < 'b').match('a')).to(be_truthy); }); it("matches if actual char is < expected", [] { char c0 = 'x', c1 = 'y'; expect((be < c1).match(c0)).to(be_truthy); }); it("does not match if actual char is > expected", [] { char c0 = 'b', c1 = 'a'; expect((be < c1).match(c0)).to(be_falsey); }); it("does not match if actual char is == expected", [] { char c0 = 'b', c1 = 'b'; expect((be < c1).match(c0)).to(be_falsey); }); it("matches if actual const temp int is < expected", [] { expect((be < 42).match(41)).to(be_truthy); }); it("matches if actual int is < expected", [] { int i0 = 32767, i1 = 32768; expect((be < i1).match(i0)).to(be_truthy); }); it("does not match if actual int is > expected", [] { int i0 = 42, i1 = -42; expect((be < i1).match(i0)).to(be_falsey); }); it("does not match if actual int is == expected", [] { int i0 = 42, i1 = 42; expect((be < i1).match(i0)).to(be_falsey); }); it("matches if actual const temp double is < expected", [] { expect((be < 3.14).match(3.1)).to(be_truthy); }); it("matches if actual double is < expected", [] { double d0 = 8.86, d1 = 8.87; expect((be < d1).match(d0)).to(be_truthy); }); it("does not match if actual double is > expected", [] { double d0 = 3.14, d1 = -3.14; expect((be < d1).match(d0)).to(be_falsey); }); it("does not match if actual double is == expected", [] { double d0 = 3.14, d1 = 3.14; expect((be < d1).match(d0)).to(be_falsey); }); it("matches if actual const temp string is < expected", [] { expect((be < string("abc")).match(string("ab"))).to(be_truthy); }); it("matches if actual string is < expected", [] { string s0 = "xyy", s1 = "xyz"; expect((be < s1).match(s0)).to(be_truthy); }); it("does not match if actual string is > expected", [] { string s0 = "abc", s1 = "abb"; expect((be < s1).match(s0)).to(be_falsey); }); it("does not match if actual string is == expected", [] { string s0 = "abc", s1 = "abc"; expect((be < s1).match(s0)).to(be_falsey); }); }); context("when used for arbitrary types", [] { class T { public: explicit T(int i) : i_(i) {} bool operator <(const T& t) const { return i_ < t.i_; } private: int i_; }; context("with < comparator", [] { it("matches if actual const temp instance is < expected", [] { expect((be < T(3)).match(T(2))).to(be_truthy); }); it("matches if actual instance is < expected", [] { T t0(0), t1(1); expect((be < t1).match(t0)).to(be_truthy); }); it("does not match if actual instance is > expected", [] { T t0(1), t1(0); expect((be < t1).match(t0)).to(be_falsey); }); it("does not match if actual instance is == expected", [] { T t0(1), t1(1); expect((be < t1).match(t0)).to(be_falsey); }); }); }); describe("#desc", [] { context("with < comparator", [] { it("says '< $c' when expecting char", [] { expect((be < 'x').desc()).to(eq("be < x")); }); it("says '< $i' when expecting int", [] { expect((be < 42).desc()).to(eq("be < 42")); }); it("says '< $d' when expecting double", [] { expect((be < 3.14).desc()).to(eq("be < 3.14")); }); it("says '< $s' when expecting string", [] { expect((be < string("test")).desc()).to(eq("be < test")); }); }); }); }); } // namespace matchers } // namespace spec <commit_msg>Add spec for BeComparedTo with <= operator<commit_after>#include <string> #include "ccspec/core.h" #include "ccspec/expectation.h" #include "ccspec/matchers.h" using std::string; using ccspec::core::before; using ccspec::core::context; using ccspec::core::describe; using ccspec::core::it; using ccspec::expect; using ccspec::matchers::be_falsey; using ccspec::matchers::be_truthy; using ccspec::matchers::be; using ccspec::matchers::eq; namespace spec { namespace matchers { auto be_compared_to_spec = describe("BeComparedTo", [] { context("with < comparator", [] { it("matches if actual const temp char is < expected", [] { expect((be < 'b').match('a')).to(be_truthy); }); it("matches if actual char is < expected", [] { char c0 = 'x', c1 = 'y'; expect((be < c1).match(c0)).to(be_truthy); }); it("does not match if actual char is > expected", [] { char c0 = 'b', c1 = 'a'; expect((be < c1).match(c0)).to(be_falsey); }); it("does not match if actual char is == expected", [] { char c0 = 'b', c1 = 'b'; expect((be < c1).match(c0)).to(be_falsey); }); it("matches if actual const temp int is < expected", [] { expect((be < 42).match(41)).to(be_truthy); }); it("matches if actual int is < expected", [] { int i0 = 32767, i1 = 32768; expect((be < i1).match(i0)).to(be_truthy); }); it("does not match if actual int is > expected", [] { int i0 = 42, i1 = -42; expect((be < i1).match(i0)).to(be_falsey); }); it("does not match if actual int is == expected", [] { int i0 = 42, i1 = 42; expect((be < i1).match(i0)).to(be_falsey); }); it("matches if actual const temp double is < expected", [] { expect((be < 3.14).match(3.1)).to(be_truthy); }); it("matches if actual double is < expected", [] { double d0 = 8.86, d1 = 8.87; expect((be < d1).match(d0)).to(be_truthy); }); it("does not match if actual double is > expected", [] { double d0 = 3.14, d1 = -3.14; expect((be < d1).match(d0)).to(be_falsey); }); it("does not match if actual double is == expected", [] { double d0 = 3.14, d1 = 3.14; expect((be < d1).match(d0)).to(be_falsey); }); it("matches if actual const temp string is < expected", [] { expect((be < string("abc")).match(string("ab"))).to(be_truthy); }); it("matches if actual string is < expected", [] { string s0 = "xyy", s1 = "xyz"; expect((be < s1).match(s0)).to(be_truthy); }); it("does not match if actual string is > expected", [] { string s0 = "abc", s1 = "abb"; expect((be < s1).match(s0)).to(be_falsey); }); it("does not match if actual string is == expected", [] { string s0 = "abc", s1 = "abc"; expect((be < s1).match(s0)).to(be_falsey); }); }); context("with <= comparator", [] { it("matches if actual const temp char is <= expected", [] { expect((be <= 'b').match('a')).to(be_truthy); }); it("matches if actual char is < expected", [] { char c0 = 'x', c1 = 'y'; expect((be <= c1).match(c0)).to(be_truthy); }); it("matches if actual char is == expected", [] { char c0 = 'x', c1 = 'x'; expect((be <= c1).match(c0)).to(be_truthy); }); it("does not match if actual char is > expected", [] { char c0 = 'b', c1 = 'a'; expect((be <= c1).match(c0)).to(be_falsey); }); it("matches if actual const temp int is <= expected", [] { expect((be <= 42).match(41)).to(be_truthy); }); it("matches if actual int is < expected", [] { int i0 = 32767, i1 = 32768; expect((be <= i1).match(i0)).to(be_truthy); }); it("matches if actual int is == expected", [] { int i0 = 32767, i1 = 32767; expect((be <= i1).match(i0)).to(be_truthy); }); it("does not match if actual int is > expected", [] { int i0 = 42, i1 = -42; expect((be <= i1).match(i0)).to(be_falsey); }); it("matches if actual const temp double is <= expected", [] { expect((be <= 3.14).match(3.1)).to(be_truthy); }); it("matches if actual double is < expected", [] { double d0 = 8.86, d1 = 8.87; expect((be <= d1).match(d0)).to(be_truthy); }); it("matches if actual double is == expected", [] { double d0 = 8.86, d1 = 8.86; expect((be <= d1).match(d0)).to(be_truthy); }); it("does not match if actual double is > expected", [] { double d0 = 3.14, d1 = -3.14; expect((be <= d1).match(d0)).to(be_falsey); }); it("matches if actual const temp string is <= expected", [] { expect((be <= string("abc")).match(string("ab"))).to(be_truthy); }); it("matches if actual string is < expected", [] { string s0 = "xyy", s1 = "xyz"; expect((be <= s1).match(s0)).to(be_truthy); }); it("matches if actual string is == expected", [] { string s0 = "xyz", s1 = "xyz"; expect((be <= s1).match(s0)).to(be_truthy); }); it("does not match if actual string is > expected", [] { string s0 = "abc", s1 = "abb"; expect((be <= s1).match(s0)).to(be_falsey); }); }); context("when used for arbitrary types", [] { class T { public: explicit T(int i) : i_(i) {} bool operator <(const T& t) const { return i_ < t.i_; } private: int i_; }; context("with < comparator", [] { it("matches if actual const temp instance is < expected", [] { expect((be < T(3)).match(T(2))).to(be_truthy); }); it("matches if actual instance is < expected", [] { T t0(0), t1(1); expect((be < t1).match(t0)).to(be_truthy); }); it("does not match if actual instance is > expected", [] { T t0(1), t1(0); expect((be < t1).match(t0)).to(be_falsey); }); it("does not match if actual instance is == expected", [] { T t0(1), t1(1); expect((be < t1).match(t0)).to(be_falsey); }); }); }); describe("#desc", [] { context("with < comparator", [] { it("says '< $c' when expecting char", [] { expect((be < 'x').desc()).to(eq("be < x")); }); it("says '< $i' when expecting int", [] { expect((be < 42).desc()).to(eq("be < 42")); }); it("says '< $d' when expecting double", [] { expect((be < 3.14).desc()).to(eq("be < 3.14")); }); it("says '< $s' when expecting string", [] { expect((be < string("test")).desc()).to(eq("be < test")); }); }); }); }); } // namespace matchers } // namespace spec <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ /* History of cvs commits: * * $Log$ * Revision 1.9 2007/10/10 09:05:10 schutz * Changing name QualAss to QA * * Revision 1.8 2007/08/28 12:55:08 policheh * Loaders removed from the reconstruction code (C.Cheshkov) * * Revision 1.7 2007/08/07 14:12:03 kharlov * Quality assurance added (Yves Schutz) * * Revision 1.6 2007/08/03 14:41:37 cvetan * Missing header files * * Revision 1.5 2007/08/03 13:52:16 kharlov * Working skeleton of matching the ESD tracks and ESD clusters (Iouri Belikov) * */ #include <TClonesArray.h> #include <TMath.h> #include <AliLog.h> #include "AliPHOSTracker.h" #include "AliPHOSEmcRecPoint.h" #include "AliESDEvent.h" #include "AliESDtrack.h" #include "AliPHOSTrackSegmentMakerv1.h" #include "AliPHOSPIDv1.h" //------------------------------------------------------------------------- // PHOS tracker. // Matches ESD tracks with the PHOS and makes the PID. // //------------------------------------------------------------------------- ClassImp(AliPHOSTracker) Bool_t AliPHOSTracker::fgDebug = kFALSE ; // ***** Some geometrical constants (used in PropagateBack) const Double_t kR=460.+ 9; // Radial coord. of the centre of EMC module (cm) const Double_t kAlpha=20.*TMath::Pi()/180.; // Segmentation angle (rad) const Double_t kYmax=kR*TMath::Tan(0.5*kAlpha); // Maximal possible y-coord.(cm) const Double_t kZmax=65.; // Approximately: the maximal possible z-coord.(cm) //____________________________________________________________________________ AliPHOSTracker::AliPHOSTracker(): AliTracker() { //-------------------------------------------------------------------- // The default constructor //-------------------------------------------------------------------- for (Int_t i=0; i<5; i++) fModules[i]=new TClonesArray("AliPHOSEmcRecPoint",777); } //____________________________________________________________________________ AliPHOSTracker::~AliPHOSTracker() { //-------------------------------------------------------------------- // The destructor //-------------------------------------------------------------------- for (Int_t i=0; i<5; i++) { (fModules[i])->Delete(); delete fModules[i]; } } //____________________________________________________________________________ Int_t AliPHOSTracker::LoadClusters(TTree *cTree) { //-------------------------------------------------------------------- // This function loads the PHOS clusters //-------------------------------------------------------------------- TObjArray *arr=NULL; TBranch *branch=cTree->GetBranch("PHOSEmcRP"); if (branch==0) { AliError("No branch with the EMC clusters found !"); return 1; } branch->SetAddress(&arr); Int_t nclusters=0; Int_t nentr=(Int_t)branch->GetEntries(); for (Int_t i=0; i<nentr; i++) { if (!branch->GetEvent(i)) continue; Int_t ncl=arr->GetEntriesFast(); while (ncl--) { AliPHOSEmcRecPoint *cl=(AliPHOSEmcRecPoint*)arr->UncheckedAt(ncl); Int_t m=cl->GetPHOSMod(); if ((m<1)||(m>5)) { AliError("Wrong module index !"); return 1; } // Here is how the alignment is treated if (!cl->Misalign()) AliWarning("Can't misalign this cluster !"); cl->SetBit(14,kFALSE); // The clusters are not yet attached to any track TClonesArray &module=*fModules[m-1]; Int_t idx=module.GetEntriesFast(); new (module[idx]) AliPHOSEmcRecPoint(*cl); nclusters++; } } arr->Delete(); Info("LoadClusters","Number of loaded clusters: %d",nclusters); return 0; } //____________________________________________________________________________ Int_t AliPHOSTracker::PropagateBack(AliESDEvent *esd) { //-------------------------------------------------------------------- // Called by AliReconstruction // Performs the track matching with the PHOS modules // Makes the PID //-------------------------------------------------------------------- Int_t nt=esd->GetNumberOfTracks(); // *** Select and sort the ESD track in accordance with their quality Double_t *quality=new Double_t[nt]; Int_t *index=new Int_t[nt]; for (Int_t i=0; i<nt; i++) { AliESDtrack *esdTrack=esd->GetTrack(i); quality[i] = esdTrack->GetSigmaY2() + esdTrack->GetSigmaZ2(); } TMath::Sort(nt,quality,index,kFALSE); // *** Start the matching Double_t bz=GetBz(); Int_t matched=0; for (Int_t i=0; i<nt; i++) { AliESDtrack *esdTrack=esd->GetTrack(index[i]); // Skip the tracks having "wrong" status (has to be checked/tuned) ULong_t status = esdTrack->GetStatus(); if ((status & AliESDtrack::kTRDout) == 0) continue; if ((status & AliESDtrack::kTRDrefit) == 1) continue; AliExternalTrackParam t(*esdTrack); Int_t isec=Int_t(t.GetAlpha()/kAlpha); Int_t imod=-isec-2; // PHOS module Double_t y; // Some tracks do not reach the PHOS if (!t.GetYAt(kR,bz,y)) continue; // because of the bending Double_t z; t.GetZAt(kR,bz,z); if (TMath::Abs(z) > kZmax) continue; // Some tracks miss the PHOS in Z Bool_t ok=kTRUE; while (TMath::Abs(y) > kYmax) { // Find the matching module Double_t alp=t.GetAlpha(); if (y > kYmax) { if (!t.Rotate(alp+kAlpha)) {ok=kFALSE; break;} imod--; } else if (y < -kYmax) { if (!t.Rotate(alp-kAlpha)) {ok=kFALSE; break;} imod++; } if (!t.GetYAt(kR,bz,y)) {ok=kFALSE; break;} } if (!ok) continue; // Track rotation failed if ((imod<0)||(imod>4)) continue; // Some tracks miss the PHOS in azimuth //t.CorrectForMaterial(...); // Correct for the TOF material, if needed t.PropagateTo(kR,bz); // Propagate to the matching module // *** Search for the "best" cluster (can be improved) TClonesArray &cArray=*fModules[imod]; Int_t ncl=cArray.GetEntriesFast(); AliPHOSEmcRecPoint *bestCluster=0; // The "best" cluster Double_t maxd2=400; // (cm^2) for (Int_t j=0; j<ncl; j++) { AliPHOSEmcRecPoint *c=(AliPHOSEmcRecPoint *)cArray.UncheckedAt(j); if (c->TestBit(14)) continue; // This clusters is "used" Double_t dy = t.GetY() - c->GetY(), dz = t.GetZ() - c->GetZ(); Double_t d2 = dy*dy + dz*dz; if (d2 < maxd2) { maxd2=d2; bestCluster=c; } } if (!bestCluster) continue; // No reasonable matching found bestCluster->SetBit(14,kTRUE); // This clusters is now attached to a track matched++; // *** Now, do the PID with the "bestCluster" // and add the corresponding info to the ESD track pointed by "esdTrack" /* printf("%e %e %e %e\n",t.GetSign(), t.GetX() - bestCluster->GetX(), t.GetY() - bestCluster->GetY(), t.GetZ() - bestCluster->GetZ()); */ } Info("PropagateBack","Number of matched tracks: %d",matched); delete[] quality; delete[] index; return 0; } //____________________________________________________________________________ AliCluster *AliPHOSTracker::GetCluster(Int_t index) const { //-------------------------------------------------------------------- // Returns the pointer to a given cluster //-------------------------------------------------------------------- Int_t m=(index & 0xf0000000) >> 28; // Module number Int_t i=(index & 0x0fffffff) >> 00; // Index within the module return (AliCluster*)(fModules[m])->UncheckedAt(i); } //____________________________________________________________________________ void AliPHOSTracker::UnloadClusters() { //-------------------------------------------------------------------- // This function unloads the PHOS clusters //-------------------------------------------------------------------- for (Int_t i=0; i<5; i++) (fModules[i])->Delete(); } <commit_msg>Can not store result of track matching here, Moved to TrackSegmentMaker<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ /* History of cvs commits: * * $Log$ * Revision 1.9 2007/10/10 09:05:10 schutz * Changing name QualAss to QA * * Revision 1.8 2007/08/28 12:55:08 policheh * Loaders removed from the reconstruction code (C.Cheshkov) * * Revision 1.7 2007/08/07 14:12:03 kharlov * Quality assurance added (Yves Schutz) * * Revision 1.6 2007/08/03 14:41:37 cvetan * Missing header files * * Revision 1.5 2007/08/03 13:52:16 kharlov * Working skeleton of matching the ESD tracks and ESD clusters (Iouri Belikov) * */ #include <TClonesArray.h> #include <TMath.h> #include <AliLog.h> #include "AliPHOSTracker.h" #include "AliPHOSEmcRecPoint.h" #include "AliESDEvent.h" #include "AliESDtrack.h" #include "AliPHOSTrackSegmentMakerv1.h" #include "AliPHOSPIDv1.h" //------------------------------------------------------------------------- // PHOS tracker. // Matches ESD tracks with the PHOS and makes the PID. // //------------------------------------------------------------------------- ClassImp(AliPHOSTracker) Bool_t AliPHOSTracker::fgDebug = kFALSE ; // ***** Some geometrical constants (used in PropagateBack) const Double_t kR=460.+ 9; // Radial coord. of the centre of EMC module (cm) const Double_t kAlpha=20.*TMath::Pi()/180.; // Segmentation angle (rad) const Double_t kYmax=kR*TMath::Tan(0.5*kAlpha); // Maximal possible y-coord.(cm) const Double_t kZmax=65.; // Approximately: the maximal possible z-coord.(cm) //____________________________________________________________________________ AliPHOSTracker::AliPHOSTracker(): AliTracker() { //-------------------------------------------------------------------- // The default constructor //-------------------------------------------------------------------- for (Int_t i=0; i<5; i++) fModules[i]=new TClonesArray("AliPHOSEmcRecPoint",777); } //____________________________________________________________________________ AliPHOSTracker::~AliPHOSTracker() { //-------------------------------------------------------------------- // The destructor //-------------------------------------------------------------------- for (Int_t i=0; i<5; i++) { (fModules[i])->Delete(); delete fModules[i]; } } //____________________________________________________________________________ Int_t AliPHOSTracker::LoadClusters(TTree *cTree) { //-------------------------------------------------------------------- // This function loads the PHOS clusters //-------------------------------------------------------------------- return 0 ; //At this stage we can not strore result // the closest track and distance to it //We perform same task later in AliPHOSTrackSegmentMakerv1 /* TObjArray *arr=NULL; TBranch *branch=cTree->GetBranch("PHOSEmcRP"); if (branch==0) { AliError("No branch with the EMC clusters found !"); return 1; } branch->SetAddress(&arr); Int_t nclusters=0; Int_t nentr=(Int_t)branch->GetEntries(); for (Int_t i=0; i<nentr; i++) { if (!branch->GetEvent(i)) continue; Int_t ncl=arr->GetEntriesFast(); while (ncl--) { AliPHOSEmcRecPoint *cl=(AliPHOSEmcRecPoint*)arr->UncheckedAt(ncl); Int_t m=cl->GetPHOSMod(); if ((m<1)||(m>5)) { AliError("Wrong module index !"); return 1; } // Here is how the alignment is treated // Misalignment is already in cluster coordinates // if (!cl->Misalign()) AliWarning("Can't misalign this cluster !"); cl->SetBit(14,kFALSE); // The clusters are not yet attached to any track TClonesArray &module=*fModules[m-1]; Int_t idx=module.GetEntriesFast(); new (module[idx]) AliPHOSEmcRecPoint(*cl); nclusters++; } } arr->Delete(); Info("LoadClusters","Number of loaded clusters: %d",nclusters); return 0; */ } //____________________________________________________________________________ Int_t AliPHOSTracker::PropagateBack(AliESDEvent *esd) { //-------------------------------------------------------------------- // Called by AliReconstruction // Performs the track matching with the PHOS modules // Makes the PID //-------------------------------------------------------------------- return 0 ; //At this stage we can not strore result // the closest track and distance to it //We perform same task later in AliPHOSTrackSegmentMakerv1 /* Int_t nt=esd->GetNumberOfTracks(); // *** Select and sort the ESD track in accordance with their quality Double_t *quality=new Double_t[nt]; Int_t *index=new Int_t[nt]; for (Int_t i=0; i<nt; i++) { AliESDtrack *esdTrack=esd->GetTrack(i); quality[i] = esdTrack->GetSigmaY2() + esdTrack->GetSigmaZ2(); } TMath::Sort(nt,quality,index,kFALSE); // *** Start the matching Double_t bz = GetGz() ; //For approximate matching Double_t b[3]; GetBxByBz(b); //For final matching Int_t matched=0; for (Int_t i=0; i<nt; i++) { AliESDtrack *esdTrack=esd->GetTrack(index[i]); // // Skip the tracks having "wrong" status (has to be checked/tuned) // ULong_t status = esdTrack->GetStatus(); // if ((status & AliESDtrack::kTRDout) == 0) continue; // if ((status & AliESDtrack::kTRDrefit) == 1) continue; AliExternalTrackParam t(*esdTrack); Int_t isec=Int_t(t.GetAlpha()/kAlpha); Int_t imod=-isec-2; // PHOS module Double_t y; // Some tracks do not reach the PHOS if (!t.GetYAt(kR,bz,y)) continue; // because of the bending Double_t z; t.GetZAt(kR,bz,z); if (TMath::Abs(z) > kZmax) continue; // Some tracks miss the PHOS in Z Bool_t ok=kTRUE; while (TMath::Abs(y) > kYmax) { // Find the matching module Double_t alp=t.GetAlpha(); if (y > kYmax) { if (!t.Rotate(alp+kAlpha)) {ok=kFALSE; break;} imod--; } else if (y < -kYmax) { if (!t.Rotate(alp-kAlpha)) {ok=kFALSE; break;} imod++; } if (!t.GetYAt(kR,bz,y)) {ok=kFALSE; break;} } if (!ok) continue; // Track rotation failed if ((imod<0)||(imod>4)) continue; // Some tracks miss the PHOS in azimuth //t.CorrectForMaterial(...); // Correct for the TOF material, if needed t.PropagateToBxByBz(kR,b); // Propagate to the matching module // *** Search for the "best" cluster (can be improved) TClonesArray &cArray=*fModules[imod]; Int_t ncl=cArray.GetEntriesFast(); AliPHOSEmcRecPoint *bestCluster=0; // The "best" cluster Double_t maxd2=400; // (cm^2) for (Int_t j=0; j<ncl; j++) { AliPHOSEmcRecPoint *c=(AliPHOSEmcRecPoint *)cArray.UncheckedAt(j); //we looking at the closest track to the cluster, //not closest cluster to the track. // if (c->TestBit(14)) continue; // This clusters is "used" Double_t dy = t.GetY() - c->GetY(), dz = t.GetZ() - c->GetZ(); Double_t d2 = dy*dy + dz*dz; if (d2 < maxd2) { maxd2=d2; bestCluster=c; } } if (!bestCluster) continue; // No reasonable matching found // bestCluster->SetBit(14,kTRUE); // This clusters is now attached to a track matched++; // *** Now, do the PID with the "bestCluster" // and add the corresponding info to the ESD track pointed by "esdTrack" // printf("%e %e %e %e\n",t.GetSign(), t.GetX() - bestCluster->GetX(), // t.GetY() - bestCluster->GetY(), // t.GetZ() - bestCluster->GetZ()); } Info("PropagateBack","Number of matched tracks: %d",matched); delete[] quality; delete[] index; return 0; */ } //____________________________________________________________________________ AliCluster *AliPHOSTracker::GetCluster(Int_t index) const { //-------------------------------------------------------------------- // Returns the pointer to a given cluster //-------------------------------------------------------------------- Int_t m=(index & 0xf0000000) >> 28; // Module number Int_t i=(index & 0x0fffffff) >> 00; // Index within the module return (AliCluster*)(fModules[m])->UncheckedAt(i); } //____________________________________________________________________________ void AliPHOSTracker::UnloadClusters() { //-------------------------------------------------------------------- // This function unloads the PHOS clusters //-------------------------------------------------------------------- // for (Int_t i=0; i<5; i++) (fModules[i])->Delete(); } <|endoftext|>
<commit_before>#include "rapid_manipulation/tuck_arms.h" #include "actionlib/client/simple_client_goal_state.h" #include "pr2_common_action_msgs/TuckArmsAction.h" #include "ros/ros.h" #include "rapid_ros/action_client.h" using actionlib::SimpleClientGoalState; using pr2_common_action_msgs::TuckArmsAction; using pr2_common_action_msgs::TuckArmsGoal; using rapid_ros::ActionClientInterface; namespace rapid { namespace manipulation { Pr2TuckArms::Pr2TuckArms(ActionClientInterface<TuckArmsAction>* client) : client_(client), server_wait_time_(5) {} bool Pr2TuckArms::TuckArms() { return ExecuteAction(true, true); } bool Pr2TuckArms::DeployLeft() { return ExecuteAction(false, true); } bool Pr2TuckArms::DeployRight() { return ExecuteAction(true, false); } bool Pr2TuckArms::DeployArms() { return ExecuteAction(false, false); } bool Pr2TuckArms::ExecuteAction(bool tuck_left, bool tuck_right) { bool success = client_->waitForServer(ros::Duration(server_wait_time_)); if (!success) { ROS_ERROR("Didn't connect to tuck arms server after %f seconds.", server_wait_time_); return false; } TuckArmsGoal goal; goal.tuck_left = tuck_left; goal.tuck_right = tuck_right; client_->sendGoal(goal); success = client_->waitForResult(ros::Duration(server_wait_time_)); if (!success) { ROS_ERROR("Tuck arms server didn't return result after %f seconds.", server_wait_time_); return false; } SimpleClientGoalState state = client_->getState(); if (state != SimpleClientGoalState::SUCCEEDED) { ROS_WARN("Tuck arms action ended in state %s", state.toString().c_str()); } return true; } void Pr2TuckArms::set_server_wait_time(double server_wait_time) { server_wait_time_ = server_wait_time; } } // namespace manipulation } // namespace rapid <commit_msg>Increased time to wait for tuck arms to finish. (#65)<commit_after>#include "rapid_manipulation/tuck_arms.h" #include "actionlib/client/simple_client_goal_state.h" #include "pr2_common_action_msgs/TuckArmsAction.h" #include "ros/ros.h" #include "rapid_ros/action_client.h" using actionlib::SimpleClientGoalState; using pr2_common_action_msgs::TuckArmsAction; using pr2_common_action_msgs::TuckArmsGoal; using rapid_ros::ActionClientInterface; namespace rapid { namespace manipulation { Pr2TuckArms::Pr2TuckArms(ActionClientInterface<TuckArmsAction>* client) : client_(client), server_wait_time_(10) {} bool Pr2TuckArms::TuckArms() { return ExecuteAction(true, true); } bool Pr2TuckArms::DeployLeft() { return ExecuteAction(false, true); } bool Pr2TuckArms::DeployRight() { return ExecuteAction(true, false); } bool Pr2TuckArms::DeployArms() { return ExecuteAction(false, false); } bool Pr2TuckArms::ExecuteAction(bool tuck_left, bool tuck_right) { bool success = client_->waitForServer(ros::Duration(server_wait_time_)); if (!success) { ROS_ERROR("Didn't connect to tuck arms server after %f seconds.", server_wait_time_); return false; } TuckArmsGoal goal; goal.tuck_left = tuck_left; goal.tuck_right = tuck_right; client_->sendGoal(goal); success = client_->waitForResult(ros::Duration(server_wait_time_)); if (!success) { ROS_ERROR("Tuck arms server didn't return result after %f seconds.", server_wait_time_); return false; } SimpleClientGoalState state = client_->getState(); if (state != SimpleClientGoalState::SUCCEEDED) { ROS_WARN("Tuck arms action ended in state %s", state.toString().c_str()); } return true; } void Pr2TuckArms::set_server_wait_time(double server_wait_time) { server_wait_time_ = server_wait_time; } } // namespace manipulation } // namespace rapid <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ppapi/shared_impl/ppb_audio_config_shared.h" #include "ppapi/thunk/enter.h" #include "ppapi/thunk/ppb_instance_api.h" namespace ppapi { PPB_AudioConfig_Shared::PPB_AudioConfig_Shared(ResourceObjectType type, PP_Instance instance) : Resource(type, instance), sample_rate_(PP_AUDIOSAMPLERATE_NONE), sample_frame_count_(0) { } PPB_AudioConfig_Shared::~PPB_AudioConfig_Shared() { } PP_Resource PPB_AudioConfig_Shared::Create( ResourceObjectType type, PP_Instance instance, PP_AudioSampleRate sample_rate, uint32_t sample_frame_count) { scoped_refptr<PPB_AudioConfig_Shared> object( new PPB_AudioConfig_Shared(type, instance)); if (!object->Init(sample_rate, sample_frame_count)) return 0; return object->GetReference(); } // static uint32_t PPB_AudioConfig_Shared::RecommendSampleFrameCount_1_0( PP_AudioSampleRate sample_rate, uint32_t requested_sample_frame_count) { // Version 1.0: Don't actually query to get a value from the // hardware; instead return the input for in-range values. if (requested_sample_frame_count < PP_AUDIOMINSAMPLEFRAMECOUNT) return PP_AUDIOMINSAMPLEFRAMECOUNT; if (requested_sample_frame_count > PP_AUDIOMAXSAMPLEFRAMECOUNT) return PP_AUDIOMAXSAMPLEFRAMECOUNT; return requested_sample_frame_count; } // static uint32_t PPB_AudioConfig_Shared::RecommendSampleFrameCount_1_1( PP_Instance instance, PP_AudioSampleRate sample_rate, uint32_t sample_frame_count) { // Version 1.1: Query the back-end hardware for sample rate and buffer size, // and recommend a best fit based on request. thunk::EnterInstanceNoLock enter(instance); if (enter.failed()) return 0; // Get the hardware config. PP_AudioSampleRate hardware_sample_rate = static_cast<PP_AudioSampleRate>( enter.functions()->GetAudioHardwareOutputSampleRate(instance)); uint32_t hardware_sample_frame_count = enter.functions()->GetAudioHardwareOutputBufferSize(instance); if (sample_frame_count < PP_AUDIOMINSAMPLEFRAMECOUNT) sample_frame_count = PP_AUDIOMINSAMPLEFRAMECOUNT; // If client is using same sample rate as audio hardware, then recommend a // multiple of the audio hardware's sample frame count. if (hardware_sample_rate == sample_rate && hardware_sample_frame_count > 0) { // Round up input sample_frame_count to nearest multiple. uint32_t multiple = (sample_frame_count + hardware_sample_frame_count - 1) / hardware_sample_frame_count; uint32_t recommendation = hardware_sample_frame_count * multiple; if (recommendation > PP_AUDIOMAXSAMPLEFRAMECOUNT) recommendation = PP_AUDIOMAXSAMPLEFRAMECOUNT; return recommendation; } // Otherwise, recommend a conservative 30ms buffer based on sample rate. const uint32_t kDefault30msAt44100kHz = 1323; const uint32_t kDefault30msAt48000kHz = 1440; switch (sample_rate) { case PP_AUDIOSAMPLERATE_44100: return kDefault30msAt44100kHz; case PP_AUDIOSAMPLERATE_48000: return kDefault30msAt48000kHz; case PP_AUDIOSAMPLERATE_NONE: return 0; } // Unable to make a recommendation. return 0; } // static PP_AudioSampleRate PPB_AudioConfig_Shared::RecommendSampleRate( PP_Instance instance) { thunk::EnterInstanceNoLock enter(instance); if (enter.failed()) return PP_AUDIOSAMPLERATE_NONE; PP_AudioSampleRate hardware_sample_rate = static_cast<PP_AudioSampleRate>( enter.functions()->GetAudioHardwareOutputSampleRate(instance)); return hardware_sample_rate; } thunk::PPB_AudioConfig_API* PPB_AudioConfig_Shared::AsPPB_AudioConfig_API() { return this; } PP_AudioSampleRate PPB_AudioConfig_Shared::GetSampleRate() { return sample_rate_; } uint32_t PPB_AudioConfig_Shared::GetSampleFrameCount() { return sample_frame_count_; } bool PPB_AudioConfig_Shared::Init(PP_AudioSampleRate sample_rate, uint32_t sample_frame_count) { // TODO(brettw): Currently we don't actually check what the hardware // supports, so just allow sample rates of the "guaranteed working" ones. if (sample_rate != PP_AUDIOSAMPLERATE_44100 && sample_rate != PP_AUDIOSAMPLERATE_48000) return false; // TODO(brettw): Currently we don't actually query to get a value from the // hardware, so just validate the range. if (sample_frame_count > PP_AUDIOMAXSAMPLEFRAMECOUNT || sample_frame_count < PP_AUDIOMINSAMPLEFRAMECOUNT) return false; sample_rate_ = sample_rate; sample_frame_count_ = sample_frame_count; return true; } } // namespace ppapi <commit_msg>Increase default buffer size when back end can't recommend one. This should help avoid stuttering on older XP machines, or vista machines where hardware sample rate != application sample rate. The downside is audio latency will be higher. Old value was for 30ms buffers. New value is for 50ms buffers. TEST=verify w/ [email protected] once in canary BUG=http://code.google.com/p/chromium/issues/detail?id=133393<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ppapi/shared_impl/ppb_audio_config_shared.h" #include "ppapi/thunk/enter.h" #include "ppapi/thunk/ppb_instance_api.h" namespace ppapi { PPB_AudioConfig_Shared::PPB_AudioConfig_Shared(ResourceObjectType type, PP_Instance instance) : Resource(type, instance), sample_rate_(PP_AUDIOSAMPLERATE_NONE), sample_frame_count_(0) { } PPB_AudioConfig_Shared::~PPB_AudioConfig_Shared() { } PP_Resource PPB_AudioConfig_Shared::Create( ResourceObjectType type, PP_Instance instance, PP_AudioSampleRate sample_rate, uint32_t sample_frame_count) { scoped_refptr<PPB_AudioConfig_Shared> object( new PPB_AudioConfig_Shared(type, instance)); if (!object->Init(sample_rate, sample_frame_count)) return 0; return object->GetReference(); } // static uint32_t PPB_AudioConfig_Shared::RecommendSampleFrameCount_1_0( PP_AudioSampleRate sample_rate, uint32_t requested_sample_frame_count) { // Version 1.0: Don't actually query to get a value from the // hardware; instead return the input for in-range values. if (requested_sample_frame_count < PP_AUDIOMINSAMPLEFRAMECOUNT) return PP_AUDIOMINSAMPLEFRAMECOUNT; if (requested_sample_frame_count > PP_AUDIOMAXSAMPLEFRAMECOUNT) return PP_AUDIOMAXSAMPLEFRAMECOUNT; return requested_sample_frame_count; } // static uint32_t PPB_AudioConfig_Shared::RecommendSampleFrameCount_1_1( PP_Instance instance, PP_AudioSampleRate sample_rate, uint32_t sample_frame_count) { // Version 1.1: Query the back-end hardware for sample rate and buffer size, // and recommend a best fit based on request. thunk::EnterInstanceNoLock enter(instance); if (enter.failed()) return 0; // Get the hardware config. PP_AudioSampleRate hardware_sample_rate = static_cast<PP_AudioSampleRate>( enter.functions()->GetAudioHardwareOutputSampleRate(instance)); uint32_t hardware_sample_frame_count = enter.functions()->GetAudioHardwareOutputBufferSize(instance); if (sample_frame_count < PP_AUDIOMINSAMPLEFRAMECOUNT) sample_frame_count = PP_AUDIOMINSAMPLEFRAMECOUNT; // If client is using same sample rate as audio hardware, then recommend a // multiple of the audio hardware's sample frame count. if (hardware_sample_rate == sample_rate && hardware_sample_frame_count > 0) { // Round up input sample_frame_count to nearest multiple. uint32_t multiple = (sample_frame_count + hardware_sample_frame_count - 1) / hardware_sample_frame_count; uint32_t recommendation = hardware_sample_frame_count * multiple; if (recommendation > PP_AUDIOMAXSAMPLEFRAMECOUNT) recommendation = PP_AUDIOMAXSAMPLEFRAMECOUNT; return recommendation; } // Otherwise, recommend a conservative 50ms buffer based on sample rate. const uint32_t kDefault50msAt44100kHz = 2205; const uint32_t kDefault50msAt48000kHz = 2400; switch (sample_rate) { case PP_AUDIOSAMPLERATE_44100: return kDefault50msAt44100kHz; case PP_AUDIOSAMPLERATE_48000: return kDefault50msAt48000kHz; case PP_AUDIOSAMPLERATE_NONE: return 0; } // Unable to make a recommendation. return 0; } // static PP_AudioSampleRate PPB_AudioConfig_Shared::RecommendSampleRate( PP_Instance instance) { thunk::EnterInstanceNoLock enter(instance); if (enter.failed()) return PP_AUDIOSAMPLERATE_NONE; PP_AudioSampleRate hardware_sample_rate = static_cast<PP_AudioSampleRate>( enter.functions()->GetAudioHardwareOutputSampleRate(instance)); return hardware_sample_rate; } thunk::PPB_AudioConfig_API* PPB_AudioConfig_Shared::AsPPB_AudioConfig_API() { return this; } PP_AudioSampleRate PPB_AudioConfig_Shared::GetSampleRate() { return sample_rate_; } uint32_t PPB_AudioConfig_Shared::GetSampleFrameCount() { return sample_frame_count_; } bool PPB_AudioConfig_Shared::Init(PP_AudioSampleRate sample_rate, uint32_t sample_frame_count) { // TODO(brettw): Currently we don't actually check what the hardware // supports, so just allow sample rates of the "guaranteed working" ones. if (sample_rate != PP_AUDIOSAMPLERATE_44100 && sample_rate != PP_AUDIOSAMPLERATE_48000) return false; // TODO(brettw): Currently we don't actually query to get a value from the // hardware, so just validate the range. if (sample_frame_count > PP_AUDIOMAXSAMPLEFRAMECOUNT || sample_frame_count < PP_AUDIOMINSAMPLEFRAMECOUNT) return false; sample_rate_ = sample_rate; sample_frame_count_ = sample_frame_count; return true; } } // namespace ppapi <|endoftext|>
<commit_before>// Copyright 2019 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "sandboxed_api/sandbox2/logserver.h" #include <string> #include <glog/logging.h> #include "sandboxed_api/sandbox2/logserver.pb.h" namespace sandbox2 { LogServer::LogServer(int fd) : comms_(fd) {} void LogServer::Run() { namespace logging = ::google; LogMessage msg; while (comms_.RecvProtoBuf(&msg)) { logging::LogSeverity severity = msg.severity(); const char* fatal_string = ""; if (severity == logging::FATAL) { // We don't want to trigger an abort() in the executor for FATAL logs. severity = logging::ERROR; fatal_string = " FATAL"; } logging::LogMessage log_message(msg.path().c_str(), msg.line(), severity); log_message.stream() << "(sandboxee " << msg.pid() << fatal_string << "): " << msg.message(); } LOG(INFO) << "Receive failed, shutting down LogServer"; } } // namespace sandbox2 <commit_msg>Internal change.<commit_after>// Copyright 2019 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "sandboxed_api/sandbox2/logserver.h" #include <string> #include <glog/logging.h> #include "sandboxed_api/sandbox2/logserver.pb.h" namespace sandbox2 { LogServer::LogServer(int fd) : comms_(fd) {} void LogServer::Run() { namespace logging = ::google; LogMessage msg; while (comms_.RecvProtoBuf(&msg)) { logging::LogSeverity severity = msg.severity(); const char* fatal_string = ""; if (severity == logging::FATAL) { // We don't want to trigger an abort() in the executor for FATAL logs. severity = logging::ERROR; fatal_string = " FATAL"; } logging::LogMessage(msg.path().c_str(), msg.line(), severity); log_message.stream() << "(sandboxee " << msg.pid() << fatal_string << "): " << msg.message(); } LOG(INFO) << "Receive failed, shutting down LogServer"; } } // namespace sandbox2 <|endoftext|>
<commit_before>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2014 Crytek * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "os/os_specific.h" #include "common/string_utils.h" #include <windows.h> #include <tlhelp32.h> #include <vector> #include <map> using std::vector; using std::map; struct FunctionHook { FunctionHook(const char *f, void **o, void *d) : function(f), origptr(o), hookptr(d), excludeModule(NULL) {} bool operator <(const FunctionHook &h) { return function < h.function; } void ApplyHook(void **IATentry) { DWORD oldProtection = PAGE_EXECUTE; BOOL success = TRUE; success = VirtualProtect(IATentry, sizeof(void*), PAGE_READWRITE, &oldProtection); if(!success) { RDCERR("Failed to make IAT entry writeable 0x%p", IATentry); return; } if(origptr && *origptr == NULL && *IATentry != hookptr) *origptr = *IATentry; *IATentry = hookptr; success = VirtualProtect(IATentry, sizeof(void*), oldProtection, &oldProtection); if(!success) { RDCERR("Failed to restore IAT entry protection 0x%p", IATentry); return; } } string function; void **origptr; void *hookptr; HMODULE excludeModule; }; struct DllHookset { DllHookset() : module(NULL) {} HMODULE module; vector<FunctionHook> FunctionHooks; }; struct CachedHookData { map<string, DllHookset> DllHooks; HMODULE module; void ApplyHooks(const char *modName, HMODULE module) { string name = strlower(string(modName)); // set module pointer if we are hooking exports from this module for(auto it=DllHooks.begin(); it != DllHooks.end(); ++it) if(it->first == name) it->second.module = module; byte *baseAddress = (byte *)module; PIMAGE_DOS_HEADER dosheader = (PIMAGE_DOS_HEADER)baseAddress; if(dosheader->e_magic != 0x5a4d) { RDCDEBUG("Ignoring module %s, since magic is 0x%04x not 0x%04x", modName, (uint32_t)dosheader->e_magic, 0x5a4dU); return; } char *PE00 = (char *)(baseAddress + dosheader->e_lfanew); PIMAGE_FILE_HEADER fileHeader = (PIMAGE_FILE_HEADER)(PE00+4); PIMAGE_OPTIONAL_HEADER optHeader = (PIMAGE_OPTIONAL_HEADER)((BYTE *)fileHeader+sizeof(IMAGE_FILE_HEADER)); DWORD iatSize = optHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size; DWORD iatOffset = optHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress; IMAGE_IMPORT_DESCRIPTOR *importDesc = (IMAGE_IMPORT_DESCRIPTOR *)(baseAddress + iatOffset); while(iatOffset && importDesc->FirstThunk) { string dllName = strlower(string((const char *)(baseAddress + importDesc->Name))); DllHookset *hookset = NULL; for(auto it=DllHooks.begin(); it != DllHooks.end(); ++it) if(it->first == dllName) hookset = &it->second; if(hookset) { IMAGE_THUNK_DATA *origFirst = (IMAGE_THUNK_DATA *)(baseAddress + importDesc->OriginalFirstThunk); IMAGE_THUNK_DATA *first = (IMAGE_THUNK_DATA *)(baseAddress + importDesc->FirstThunk); while(origFirst->u1.AddressOfData) { #ifdef WIN64 if(origFirst->u1.AddressOfData & 0x8000000000000000) #else if(origFirst->u1.AddressOfData & 0x80000000) #endif { // low bits of origFirst->u1.AddressOfData contain an ordinal origFirst++; first++; continue; } IMAGE_IMPORT_BY_NAME *import = (IMAGE_IMPORT_BY_NAME *)(baseAddress + origFirst->u1.AddressOfData); void **IATentry = (void **)&first->u1.AddressOfData; FunctionHook search(import->Name, NULL, NULL); auto found = std::lower_bound(hookset->FunctionHooks.begin(), hookset->FunctionHooks.end(), search); if(found != hookset->FunctionHooks.end() && !(search < *found) && found->excludeModule != module) found->ApplyHook(IATentry); origFirst++; first++; } } importDesc++; } } }; static CachedHookData *s_HookData = NULL; HMODULE WINAPI Hooked_LoadLibraryExA(LPCSTR lpLibFileName, HANDLE fileHandle, DWORD flags) { // we can use the function naked, as when setting up the hook for LoadLibraryExA, our own module // was excluded from IAT patching HMODULE mod = LoadLibraryExA(lpLibFileName, fileHandle, flags); if(mod) s_HookData->ApplyHooks(lpLibFileName, mod); return mod; } HMODULE WINAPI Hooked_LoadLibraryExW(LPCWSTR lpLibFileName, HANDLE fileHandle, DWORD flags) { // we can use the function naked, as when setting up the hook for LoadLibraryExA, our own module // was excluded from IAT patching HMODULE mod = LoadLibraryExW(lpLibFileName, fileHandle, flags); if(mod) s_HookData->ApplyHooks(narrow(wstring(lpLibFileName)).c_str(), mod); return mod; } HMODULE WINAPI Hooked_LoadLibraryA(LPCSTR lpLibFileName) { return Hooked_LoadLibraryExA(lpLibFileName, NULL, 0); } HMODULE WINAPI Hooked_LoadLibraryW(LPCWSTR lpLibFileName) { return Hooked_LoadLibraryExW(lpLibFileName, NULL, 0); } static bool OrdinalAsString(void *func) { return uint64_t(func) <= 0xffff; } FARPROC WINAPI Hooked_GetProcAddress(HMODULE mod, LPCSTR func) { if(mod == s_HookData->module || mod == NULL || func == NULL || OrdinalAsString((void *)func)) return GetProcAddress(mod, func); for(auto it=s_HookData->DllHooks.begin(); it != s_HookData->DllHooks.end(); ++it) { if(mod == it->second.module) { FunctionHook search(func, NULL, NULL); for(size_t i=0; i < it->second.FunctionHooks.size(); i++) { auto found = std::lower_bound(it->second.FunctionHooks.begin(), it->second.FunctionHooks.end(), search); if(found != it->second.FunctionHooks.end() && !(search < *found)) { if(found->origptr && *found->origptr == NULL) *found->origptr = (void *)GetProcAddress(mod, func); return (FARPROC)found->hookptr; } } } } return GetProcAddress(mod, func); } void Win32_IAT_BeginHooks() { s_HookData = new CachedHookData; RDCASSERT(s_HookData->DllHooks.empty()); s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("LoadLibraryA", NULL, &Hooked_LoadLibraryA)); s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("LoadLibraryW", NULL, &Hooked_LoadLibraryW)); s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("LoadLibraryExA", NULL, &Hooked_LoadLibraryExA)); s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("LoadLibraryExW", NULL, &Hooked_LoadLibraryExW)); s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("GetProcAddress", NULL, &Hooked_GetProcAddress)); GetModuleHandleEx( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCTSTR)&s_HookData, &s_HookData->module); for(auto it=s_HookData->DllHooks.begin(); it != s_HookData->DllHooks.end(); ++it) for(size_t i=0; i < it->second.FunctionHooks.size(); i++) it->second.FunctionHooks[i].excludeModule = s_HookData->module; } // hook all functions for currently loaded modules. // some of these hooks (as above) will hook LoadLibrary/GetProcAddress, to protect void Win32_IAT_EndHooks() { for(auto it=s_HookData->DllHooks.begin(); it != s_HookData->DllHooks.end(); ++it) std::sort(it->second.FunctionHooks.begin(), it->second.FunctionHooks.end()); HANDLE hModuleSnap = INVALID_HANDLE_VALUE; // up to 10 retries for(int i=0; i < 10; i++) { hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId()); if(hModuleSnap == INVALID_HANDLE_VALUE) { DWORD err = GetLastError(); RDCWARN("CreateToolhelp32Snapshot() -> 0x%08x", err); // retry if error is ERROR_BAD_LENGTH if(err == ERROR_BAD_LENGTH) continue; } // didn't retry, or succeeded break; } if(hModuleSnap == INVALID_HANDLE_VALUE) { RDCERR("Couldn't create toolhelp dump of modules in process"); return; } #ifdef UNICODE #undef MODULEENTRY32 #undef Module32First #undef Module32Next #endif MODULEENTRY32 me32; RDCEraseEl(me32); me32.dwSize = sizeof(MODULEENTRY32); BOOL success = Module32First(hModuleSnap, &me32); if(success == FALSE) { DWORD err = GetLastError(); RDCERR("Couldn't get first module in process: 0x%08x", err); CloseHandle(hModuleSnap); return; } uintptr_t ret = 0; int numModules = 0; do { s_HookData->ApplyHooks(me32.szModule, me32.hModule); } while(ret == 0 && Module32Next(hModuleSnap, &me32)); CloseHandle(hModuleSnap); } bool Win32_IAT_Hook(void **orig_function_ptr, const char *module_name, const char *function, void *destination_function_ptr) { if(!_stricmp(module_name, "kernel32.dll")) { if(!strcmp(function, "LoadLibraryA") || !strcmp(function, "LoadLibraryW") || !strcmp(function, "LoadLibraryExA") || !strcmp(function, "LoadLibraryExW") || !strcmp(function, "GetProcAddress")) { RDCERR("Cannot hook LoadLibrary* or GetProcAddress, as these are hooked internally"); return false; } } s_HookData->DllHooks[strlower(string(module_name))].FunctionHooks.push_back(FunctionHook(function, orig_function_ptr, destination_function_ptr)); return true; } <commit_msg>Skip hooking fraps via IAT for compatibility reasons<commit_after>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2014 Crytek * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "os/os_specific.h" #include "common/string_utils.h" #include <windows.h> #include <tlhelp32.h> #include <vector> #include <map> using std::vector; using std::map; struct FunctionHook { FunctionHook(const char *f, void **o, void *d) : function(f), origptr(o), hookptr(d), excludeModule(NULL) {} bool operator <(const FunctionHook &h) { return function < h.function; } void ApplyHook(void **IATentry) { DWORD oldProtection = PAGE_EXECUTE; BOOL success = TRUE; success = VirtualProtect(IATentry, sizeof(void*), PAGE_READWRITE, &oldProtection); if(!success) { RDCERR("Failed to make IAT entry writeable 0x%p", IATentry); return; } if(origptr && *origptr == NULL && *IATentry != hookptr) *origptr = *IATentry; *IATentry = hookptr; success = VirtualProtect(IATentry, sizeof(void*), oldProtection, &oldProtection); if(!success) { RDCERR("Failed to restore IAT entry protection 0x%p", IATentry); return; } } string function; void **origptr; void *hookptr; HMODULE excludeModule; }; struct DllHookset { DllHookset() : module(NULL) {} HMODULE module; vector<FunctionHook> FunctionHooks; }; struct CachedHookData { map<string, DllHookset> DllHooks; HMODULE module; void ApplyHooks(const char *modName, HMODULE module) { string name = strlower(string(modName)); // fraps seems to non-safely modify the assembly around the hook function, if // we modify its import descriptors it leads to a crash as it hooks OUR functions. // instead, skip modifying the import descriptors, it will hook the 'real' d3d functions // and we can call them and have fraps + renderdoc playing nicely together if(name.find("fraps") != string::npos) return; // set module pointer if we are hooking exports from this module for(auto it=DllHooks.begin(); it != DllHooks.end(); ++it) if(it->first == name) it->second.module = module; byte *baseAddress = (byte *)module; PIMAGE_DOS_HEADER dosheader = (PIMAGE_DOS_HEADER)baseAddress; if(dosheader->e_magic != 0x5a4d) { RDCDEBUG("Ignoring module %s, since magic is 0x%04x not 0x%04x", modName, (uint32_t)dosheader->e_magic, 0x5a4dU); return; } char *PE00 = (char *)(baseAddress + dosheader->e_lfanew); PIMAGE_FILE_HEADER fileHeader = (PIMAGE_FILE_HEADER)(PE00+4); PIMAGE_OPTIONAL_HEADER optHeader = (PIMAGE_OPTIONAL_HEADER)((BYTE *)fileHeader+sizeof(IMAGE_FILE_HEADER)); DWORD iatSize = optHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size; DWORD iatOffset = optHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress; IMAGE_IMPORT_DESCRIPTOR *importDesc = (IMAGE_IMPORT_DESCRIPTOR *)(baseAddress + iatOffset); while(iatOffset && importDesc->FirstThunk) { string dllName = strlower(string((const char *)(baseAddress + importDesc->Name))); DllHookset *hookset = NULL; for(auto it=DllHooks.begin(); it != DllHooks.end(); ++it) if(it->first == dllName) hookset = &it->second; if(hookset) { IMAGE_THUNK_DATA *origFirst = (IMAGE_THUNK_DATA *)(baseAddress + importDesc->OriginalFirstThunk); IMAGE_THUNK_DATA *first = (IMAGE_THUNK_DATA *)(baseAddress + importDesc->FirstThunk); while(origFirst->u1.AddressOfData) { #ifdef WIN64 if(origFirst->u1.AddressOfData & 0x8000000000000000) #else if(origFirst->u1.AddressOfData & 0x80000000) #endif { // low bits of origFirst->u1.AddressOfData contain an ordinal origFirst++; first++; continue; } IMAGE_IMPORT_BY_NAME *import = (IMAGE_IMPORT_BY_NAME *)(baseAddress + origFirst->u1.AddressOfData); void **IATentry = (void **)&first->u1.AddressOfData; FunctionHook search(import->Name, NULL, NULL); auto found = std::lower_bound(hookset->FunctionHooks.begin(), hookset->FunctionHooks.end(), search); if(found != hookset->FunctionHooks.end() && !(search < *found) && found->excludeModule != module) found->ApplyHook(IATentry); origFirst++; first++; } } importDesc++; } } }; static CachedHookData *s_HookData = NULL; HMODULE WINAPI Hooked_LoadLibraryExA(LPCSTR lpLibFileName, HANDLE fileHandle, DWORD flags) { // we can use the function naked, as when setting up the hook for LoadLibraryExA, our own module // was excluded from IAT patching HMODULE mod = LoadLibraryExA(lpLibFileName, fileHandle, flags); if(mod) s_HookData->ApplyHooks(lpLibFileName, mod); return mod; } HMODULE WINAPI Hooked_LoadLibraryExW(LPCWSTR lpLibFileName, HANDLE fileHandle, DWORD flags) { // we can use the function naked, as when setting up the hook for LoadLibraryExA, our own module // was excluded from IAT patching HMODULE mod = LoadLibraryExW(lpLibFileName, fileHandle, flags); if(mod) s_HookData->ApplyHooks(narrow(wstring(lpLibFileName)).c_str(), mod); return mod; } HMODULE WINAPI Hooked_LoadLibraryA(LPCSTR lpLibFileName) { return Hooked_LoadLibraryExA(lpLibFileName, NULL, 0); } HMODULE WINAPI Hooked_LoadLibraryW(LPCWSTR lpLibFileName) { return Hooked_LoadLibraryExW(lpLibFileName, NULL, 0); } static bool OrdinalAsString(void *func) { return uint64_t(func) <= 0xffff; } FARPROC WINAPI Hooked_GetProcAddress(HMODULE mod, LPCSTR func) { if(mod == s_HookData->module || mod == NULL || func == NULL || OrdinalAsString((void *)func)) return GetProcAddress(mod, func); for(auto it=s_HookData->DllHooks.begin(); it != s_HookData->DllHooks.end(); ++it) { if(mod == it->second.module) { FunctionHook search(func, NULL, NULL); for(size_t i=0; i < it->second.FunctionHooks.size(); i++) { auto found = std::lower_bound(it->second.FunctionHooks.begin(), it->second.FunctionHooks.end(), search); if(found != it->second.FunctionHooks.end() && !(search < *found)) { if(found->origptr && *found->origptr == NULL) *found->origptr = (void *)GetProcAddress(mod, func); return (FARPROC)found->hookptr; } } } } return GetProcAddress(mod, func); } void Win32_IAT_BeginHooks() { s_HookData = new CachedHookData; RDCASSERT(s_HookData->DllHooks.empty()); s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("LoadLibraryA", NULL, &Hooked_LoadLibraryA)); s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("LoadLibraryW", NULL, &Hooked_LoadLibraryW)); s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("LoadLibraryExA", NULL, &Hooked_LoadLibraryExA)); s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("LoadLibraryExW", NULL, &Hooked_LoadLibraryExW)); s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("GetProcAddress", NULL, &Hooked_GetProcAddress)); GetModuleHandleEx( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCTSTR)&s_HookData, &s_HookData->module); for(auto it=s_HookData->DllHooks.begin(); it != s_HookData->DllHooks.end(); ++it) for(size_t i=0; i < it->second.FunctionHooks.size(); i++) it->second.FunctionHooks[i].excludeModule = s_HookData->module; } // hook all functions for currently loaded modules. // some of these hooks (as above) will hook LoadLibrary/GetProcAddress, to protect void Win32_IAT_EndHooks() { for(auto it=s_HookData->DllHooks.begin(); it != s_HookData->DllHooks.end(); ++it) std::sort(it->second.FunctionHooks.begin(), it->second.FunctionHooks.end()); HANDLE hModuleSnap = INVALID_HANDLE_VALUE; // up to 10 retries for(int i=0; i < 10; i++) { hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId()); if(hModuleSnap == INVALID_HANDLE_VALUE) { DWORD err = GetLastError(); RDCWARN("CreateToolhelp32Snapshot() -> 0x%08x", err); // retry if error is ERROR_BAD_LENGTH if(err == ERROR_BAD_LENGTH) continue; } // didn't retry, or succeeded break; } if(hModuleSnap == INVALID_HANDLE_VALUE) { RDCERR("Couldn't create toolhelp dump of modules in process"); return; } #ifdef UNICODE #undef MODULEENTRY32 #undef Module32First #undef Module32Next #endif MODULEENTRY32 me32; RDCEraseEl(me32); me32.dwSize = sizeof(MODULEENTRY32); BOOL success = Module32First(hModuleSnap, &me32); if(success == FALSE) { DWORD err = GetLastError(); RDCERR("Couldn't get first module in process: 0x%08x", err); CloseHandle(hModuleSnap); return; } uintptr_t ret = 0; int numModules = 0; do { s_HookData->ApplyHooks(me32.szModule, me32.hModule); } while(ret == 0 && Module32Next(hModuleSnap, &me32)); CloseHandle(hModuleSnap); } bool Win32_IAT_Hook(void **orig_function_ptr, const char *module_name, const char *function, void *destination_function_ptr) { if(!_stricmp(module_name, "kernel32.dll")) { if(!strcmp(function, "LoadLibraryA") || !strcmp(function, "LoadLibraryW") || !strcmp(function, "LoadLibraryExA") || !strcmp(function, "LoadLibraryExW") || !strcmp(function, "GetProcAddress")) { RDCERR("Cannot hook LoadLibrary* or GetProcAddress, as these are hooked internally"); return false; } } s_HookData->DllHooks[strlower(string(module_name))].FunctionHooks.push_back(FunctionHook(function, orig_function_ptr, destination_function_ptr)); return true; } <|endoftext|>
<commit_before>/* yahooconferencemessagemanager.h - Yahoo Conference Message Manager Copyright (c) 2003 by Duncan Mac-Vicar <[email protected]> Kopete (c) 2002-2003 by the Kopete developers <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kdebug.h> #include <klineeditdlg.h> #include <klocale.h> #include <kmessagebox.h> #include <kpopupmenu.h> #include <kconfig.h> #include "kopetecontactaction.h" #include "kopetecontactlist.h" #include "kopetecontact.h" #include "kopetechatsessionmanager.h" #include "yahooconferencemessagemanager.h" #include "yahoocontact.h" #include "yahooaccount.h" YahooConferenceChatSession::YahooConferenceChatSession( const QString & yahooRoom, Kopete::Protocol *protocol, const Kopete::Contact *user, Kopete::ContactPtrList others, const char *name ) : Kopete::ChatSession( user, others, protocol, name ) { Kopete::ChatSessionManager::self()->registerChatSession( this ); connect ( this, SIGNAL( messageSent ( Kopete::Message &, Kopete::ChatSession * ) ), SLOT( slotMessageSent ( Kopete::Message &, Kopete::ChatSession * ) ) ); m_yahooRoom = yahooRoom; } YahooConferenceChatSession::~YahooConferenceChatSession() { emit leavingConference( this ); } const QString &YahooConferenceChatSession::room() { return m_yahooRoom; } void YahooConferenceChatSession::joined( YahooContact *c ) { addContact( c ); } void YahooConferenceChatSession::left( YahooContact *c ) { removeContact( c, i18n("%1 has left the conference.").arg(c->userId()) ); } void YahooConferenceChatSession::slotMessageSent( Kopete::Message & message, Kopete::ChatSession * ) { kdDebug ( 14180 ) << k_funcinfo << endl; YahooAccount *acc = dynamic_cast< YahooAccount *>( account() ); if( acc ) acc->sendConfMessage( this, message ); appendMessage( message ); messageSucceeded(); } #include "yahooconferencemessagemanager.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg>That is not the reason to be displayed.<commit_after>/* yahooconferencemessagemanager.h - Yahoo Conference Message Manager Copyright (c) 2003 by Duncan Mac-Vicar <[email protected]> Kopete (c) 2002-2003 by the Kopete developers <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kdebug.h> #include <klineeditdlg.h> #include <klocale.h> #include <kmessagebox.h> #include <kpopupmenu.h> #include <kconfig.h> #include "kopetecontactaction.h" #include "kopetecontactlist.h" #include "kopetecontact.h" #include "kopetechatsessionmanager.h" #include "yahooconferencemessagemanager.h" #include "yahoocontact.h" #include "yahooaccount.h" YahooConferenceChatSession::YahooConferenceChatSession( const QString & yahooRoom, Kopete::Protocol *protocol, const Kopete::Contact *user, Kopete::ContactPtrList others, const char *name ) : Kopete::ChatSession( user, others, protocol, name ) { Kopete::ChatSessionManager::self()->registerChatSession( this ); connect ( this, SIGNAL( messageSent ( Kopete::Message &, Kopete::ChatSession * ) ), SLOT( slotMessageSent ( Kopete::Message &, Kopete::ChatSession * ) ) ); m_yahooRoom = yahooRoom; } YahooConferenceChatSession::~YahooConferenceChatSession() { emit leavingConference( this ); } const QString &YahooConferenceChatSession::room() { return m_yahooRoom; } void YahooConferenceChatSession::joined( YahooContact *c ) { addContact( c ); } void YahooConferenceChatSession::left( YahooContact *c ) { removeContact( c ); } void YahooConferenceChatSession::slotMessageSent( Kopete::Message & message, Kopete::ChatSession * ) { kdDebug ( 14180 ) << k_funcinfo << endl; YahooAccount *acc = dynamic_cast< YahooAccount *>( account() ); if( acc ) acc->sendConfMessage( this, message ); appendMessage( message ); messageSucceeded(); } #include "yahooconferencemessagemanager.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before><commit_msg>dr78: #i43040# removed german umlauts and utf8 bom accidentially added by too smart editor<commit_after><|endoftext|>
<commit_before>// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "pal.h" #include "args.h" #include "trace.h" #include "deps_resolver.h" #include "utils.h" #include "coreclr.h" enum StatusCode { Failure = 0x87FF0000, InvalidArgFailure = Failure | 0x1, CoreClrResolveFailure = Failure | 0x2, CoreClrBindFailure = Failure | 0x3, CoreClrInitFailure = Failure | 0x4, CoreClrExeFailure = Failure | 0x5, ResolverInitFailure = Failure | 0x6, ResolverResolveFailure = Failure | 0x7, }; // ---------------------------------------------------------------------- // resolve_clr_path: Resolve CLR Path in priority order // // Description: // Check if CoreCLR library exists in runtime servicing dir or app // local or DOTNET_HOME directory in that order of priority. If these // fail to locate CoreCLR, then check platform-specific search. // // Returns: // "true" if path to the CoreCLR dir can be resolved in "clr_path" // parameter. Else, returns "false" with "clr_path" unmodified. // bool resolve_clr_path(const arguments_t& args, pal::string_t* clr_path) { const pal::string_t* dirs[] = { &args.dotnet_runtime_servicing, // DOTNET_RUNTIME_SERVICING &args.app_dir, // APP LOCAL &args.dotnet_home // DOTNET_HOME }; for (int i = 0; i < sizeof(dirs) / sizeof(dirs[0]); ++i) { if (dirs[i]->empty()) { continue; } // App dir should contain coreclr, so skip appending path. pal::string_t cur_dir = *dirs[i]; if (dirs[i] != &args.app_dir) { append_path(&cur_dir, _X("runtime")); append_path(&cur_dir, _X("coreclr")); } // Found coreclr in priority order. if (coreclr_exists_in_dir(cur_dir)) { clr_path->assign(cur_dir); return true; } } // Use platform-specific search algorithm pal::string_t home_dir = args.dotnet_home; if (pal::find_coreclr(&home_dir)) { clr_path->assign(home_dir); return true; } return false; } int run(const arguments_t& args, const pal::string_t& clr_path) { // Load the deps resolver deps_resolver_t resolver(args); if (!resolver.valid()) { trace::error(_X("Invalid .deps file")); return StatusCode::ResolverInitFailure; } // Add packages directory pal::string_t packages_dir = args.dotnet_packages; if (!pal::directory_exists(packages_dir)) { (void)pal::get_default_packages_directory(&packages_dir); } trace::info(_X("Package directory: %s"), packages_dir.empty() ? _X("not specified") : packages_dir.c_str()); probe_paths_t probe_paths; if (!resolver.resolve_probe_paths(args.app_dir, packages_dir, args.dotnet_packages_cache, clr_path, &probe_paths)) { return StatusCode::ResolverResolveFailure; } // Build CoreCLR properties const char* property_keys[] = { "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "APP_NI_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", "PLATFORM_RESOURCE_ROOTS", "AppDomainCompatSwitch", // TODO: pipe this from corehost.json "SERVER_GC", }; auto tpa_paths_cstr = pal::to_stdstring(probe_paths.tpa); auto app_base_cstr = pal::to_stdstring(args.app_dir); auto native_dirs_cstr = pal::to_stdstring(probe_paths.native); auto culture_dirs_cstr = pal::to_stdstring(probe_paths.culture); // Workaround for dotnet/cli Issue #488 and #652 pal::string_t server_gc; std::string server_gc_cstr = (pal::getenv(_X("COREHOST_SERVER_GC"), &server_gc)) ? pal::to_stdstring(server_gc) : "1"; const char* property_values[] = { // TRUSTED_PLATFORM_ASSEMBLIES tpa_paths_cstr.c_str(), // APP_PATHS app_base_cstr.c_str(), // APP_NI_PATHS app_base_cstr.c_str(), // NATIVE_DLL_SEARCH_DIRECTORIES native_dirs_cstr.c_str(), // PLATFORM_RESOURCE_ROOTS culture_dirs_cstr.c_str(), // AppDomainCompatSwitch "UseLatestBehaviorWhenTFMNotSpecified", // SERVER_GC server_gc_cstr.c_str(), }; size_t property_size = sizeof(property_keys) / sizeof(property_keys[0]); // Bind CoreCLR if (!coreclr::bind(clr_path)) { trace::error(_X("Failed to bind to coreclr")); return StatusCode::CoreClrBindFailure; } // Verbose logging if (trace::is_enabled()) { for (size_t i = 0; i < property_size; ++i) { pal::string_t key, val; pal::to_palstring(property_keys[i], &key); pal::to_palstring(property_values[i], &val); trace::verbose(_X("Property %s = %s"), key.c_str(), val.c_str()); } } std::string own_path; pal::to_stdstring(args.own_path.c_str(), &own_path); // Initialize CoreCLR coreclr::host_handle_t host_handle; coreclr::domain_id_t domain_id; auto hr = coreclr::initialize( own_path.c_str(), "clrhost", property_keys, property_values, property_size, &host_handle, &domain_id); if (!SUCCEEDED(hr)) { trace::error(_X("Failed to initialize CoreCLR, HRESULT: 0x%X"), hr); return StatusCode::CoreClrInitFailure; } if (trace::is_enabled()) { pal::string_t arg_str; for (int i = 0; i < args.app_argc; i++) { arg_str.append(args.app_argv[i]); arg_str.append(_X(",")); } trace::info(_X("Launch host: %s app: %s, argc: %d args: %s"), args.own_path.c_str(), args.managed_application.c_str(), args.app_argc, arg_str.c_str()); } // Initialize with empty strings std::vector<std::string> argv_strs(args.app_argc); std::vector<const char*> argv(args.app_argc); for (int i = 0; i < args.app_argc; i++) { pal::to_stdstring(args.app_argv[i], &argv_strs[i]); argv[i] = argv_strs[i].c_str(); } // Execute the application unsigned int exit_code = 1; hr = coreclr::execute_assembly( host_handle, domain_id, argv.size(), argv.data(), pal::to_stdstring(args.managed_application).c_str(), &exit_code); if (!SUCCEEDED(hr)) { trace::error(_X("Failed to execute managed app, HRESULT: 0x%X"), hr); return StatusCode::CoreClrExeFailure; } // Shut down the CoreCLR hr = coreclr::shutdown(host_handle, domain_id); if (!SUCCEEDED(hr)) { trace::warning(_X("Failed to shut down CoreCLR, HRESULT: 0x%X"), hr); } coreclr::unload(); return exit_code; } #if defined(_WIN32) int __cdecl wmain(const int argc, const pal::char_t* argv[]) #else int main(const int argc, const pal::char_t* argv[]) #endif { // Take care of arguments arguments_t args; if (!parse_arguments(argc, argv, args)) { return StatusCode::InvalidArgFailure; } // Resolve CLR path pal::string_t clr_path; if (!resolve_clr_path(args, &clr_path)) { trace::error(_X("Could not resolve coreclr path")); return StatusCode::CoreClrResolveFailure; } return run(args, clr_path); } <commit_msg>Fix bug as getenv returns true on empty env var<commit_after>// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "pal.h" #include "args.h" #include "trace.h" #include "deps_resolver.h" #include "utils.h" #include "coreclr.h" enum StatusCode { Failure = 0x87FF0000, InvalidArgFailure = Failure | 0x1, CoreClrResolveFailure = Failure | 0x2, CoreClrBindFailure = Failure | 0x3, CoreClrInitFailure = Failure | 0x4, CoreClrExeFailure = Failure | 0x5, ResolverInitFailure = Failure | 0x6, ResolverResolveFailure = Failure | 0x7, }; // ---------------------------------------------------------------------- // resolve_clr_path: Resolve CLR Path in priority order // // Description: // Check if CoreCLR library exists in runtime servicing dir or app // local or DOTNET_HOME directory in that order of priority. If these // fail to locate CoreCLR, then check platform-specific search. // // Returns: // "true" if path to the CoreCLR dir can be resolved in "clr_path" // parameter. Else, returns "false" with "clr_path" unmodified. // bool resolve_clr_path(const arguments_t& args, pal::string_t* clr_path) { const pal::string_t* dirs[] = { &args.dotnet_runtime_servicing, // DOTNET_RUNTIME_SERVICING &args.app_dir, // APP LOCAL &args.dotnet_home // DOTNET_HOME }; for (int i = 0; i < sizeof(dirs) / sizeof(dirs[0]); ++i) { if (dirs[i]->empty()) { continue; } // App dir should contain coreclr, so skip appending path. pal::string_t cur_dir = *dirs[i]; if (dirs[i] != &args.app_dir) { append_path(&cur_dir, _X("runtime")); append_path(&cur_dir, _X("coreclr")); } // Found coreclr in priority order. if (coreclr_exists_in_dir(cur_dir)) { clr_path->assign(cur_dir); return true; } } // Use platform-specific search algorithm pal::string_t home_dir = args.dotnet_home; if (pal::find_coreclr(&home_dir)) { clr_path->assign(home_dir); return true; } return false; } int run(const arguments_t& args, const pal::string_t& clr_path) { // Load the deps resolver deps_resolver_t resolver(args); if (!resolver.valid()) { trace::error(_X("Invalid .deps file")); return StatusCode::ResolverInitFailure; } // Add packages directory pal::string_t packages_dir = args.dotnet_packages; if (!pal::directory_exists(packages_dir)) { (void)pal::get_default_packages_directory(&packages_dir); } trace::info(_X("Package directory: %s"), packages_dir.empty() ? _X("not specified") : packages_dir.c_str()); probe_paths_t probe_paths; if (!resolver.resolve_probe_paths(args.app_dir, packages_dir, args.dotnet_packages_cache, clr_path, &probe_paths)) { return StatusCode::ResolverResolveFailure; } // Build CoreCLR properties const char* property_keys[] = { "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "APP_NI_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", "PLATFORM_RESOURCE_ROOTS", "AppDomainCompatSwitch", // TODO: pipe this from corehost.json "SERVER_GC", }; auto tpa_paths_cstr = pal::to_stdstring(probe_paths.tpa); auto app_base_cstr = pal::to_stdstring(args.app_dir); auto native_dirs_cstr = pal::to_stdstring(probe_paths.native); auto culture_dirs_cstr = pal::to_stdstring(probe_paths.culture); // Workaround for dotnet/cli Issue #488 and #652 pal::string_t server_gc; std::string server_gc_cstr = (pal::getenv(_X("COREHOST_SERVER_GC"), &server_gc) && !server_gc.empty()) ? pal::to_stdstring(server_gc) : "1"; const char* property_values[] = { // TRUSTED_PLATFORM_ASSEMBLIES tpa_paths_cstr.c_str(), // APP_PATHS app_base_cstr.c_str(), // APP_NI_PATHS app_base_cstr.c_str(), // NATIVE_DLL_SEARCH_DIRECTORIES native_dirs_cstr.c_str(), // PLATFORM_RESOURCE_ROOTS culture_dirs_cstr.c_str(), // AppDomainCompatSwitch "UseLatestBehaviorWhenTFMNotSpecified", // SERVER_GC server_gc_cstr.c_str(), }; size_t property_size = sizeof(property_keys) / sizeof(property_keys[0]); // Bind CoreCLR if (!coreclr::bind(clr_path)) { trace::error(_X("Failed to bind to coreclr")); return StatusCode::CoreClrBindFailure; } // Verbose logging if (trace::is_enabled()) { for (size_t i = 0; i < property_size; ++i) { pal::string_t key, val; pal::to_palstring(property_keys[i], &key); pal::to_palstring(property_values[i], &val); trace::verbose(_X("Property %s = %s"), key.c_str(), val.c_str()); } } std::string own_path; pal::to_stdstring(args.own_path.c_str(), &own_path); // Initialize CoreCLR coreclr::host_handle_t host_handle; coreclr::domain_id_t domain_id; auto hr = coreclr::initialize( own_path.c_str(), "clrhost", property_keys, property_values, property_size, &host_handle, &domain_id); if (!SUCCEEDED(hr)) { trace::error(_X("Failed to initialize CoreCLR, HRESULT: 0x%X"), hr); return StatusCode::CoreClrInitFailure; } if (trace::is_enabled()) { pal::string_t arg_str; for (int i = 0; i < args.app_argc; i++) { arg_str.append(args.app_argv[i]); arg_str.append(_X(",")); } trace::info(_X("Launch host: %s app: %s, argc: %d args: %s"), args.own_path.c_str(), args.managed_application.c_str(), args.app_argc, arg_str.c_str()); } // Initialize with empty strings std::vector<std::string> argv_strs(args.app_argc); std::vector<const char*> argv(args.app_argc); for (int i = 0; i < args.app_argc; i++) { pal::to_stdstring(args.app_argv[i], &argv_strs[i]); argv[i] = argv_strs[i].c_str(); } // Execute the application unsigned int exit_code = 1; hr = coreclr::execute_assembly( host_handle, domain_id, argv.size(), argv.data(), pal::to_stdstring(args.managed_application).c_str(), &exit_code); if (!SUCCEEDED(hr)) { trace::error(_X("Failed to execute managed app, HRESULT: 0x%X"), hr); return StatusCode::CoreClrExeFailure; } // Shut down the CoreCLR hr = coreclr::shutdown(host_handle, domain_id); if (!SUCCEEDED(hr)) { trace::warning(_X("Failed to shut down CoreCLR, HRESULT: 0x%X"), hr); } coreclr::unload(); return exit_code; } #if defined(_WIN32) int __cdecl wmain(const int argc, const pal::char_t* argv[]) #else int main(const int argc, const pal::char_t* argv[]) #endif { // Take care of arguments arguments_t args; if (!parse_arguments(argc, argv, args)) { return StatusCode::InvalidArgFailure; } // Resolve CLR path pal::string_t clr_path; if (!resolve_clr_path(args, &clr_path)) { trace::error(_X("Could not resolve coreclr path")); return StatusCode::CoreClrResolveFailure; } return run(args, clr_path); } <|endoftext|>
<commit_before>#include "CardiacMechanicsMaterial.h" #include "ColumnMajorMatrix.h" #include "CardiacSolidMechanicsMaterial.h" #include "SymmOrthotropicElasticityTensor.h" #include "VolumetricModel.h" #include "TensorHelpers.h" using namespace TensorHelpers; template<> InputParameters validParams<CardiacMechanicsMaterial>() { InputParameters params = validParams<Material>(); params.addRequiredCoupledVar("displacements", "The x, y, and z displacement"); params.addCoupledVar("Ta", 0, "The (position dependent) active tension in fibre direction that will finally drive contraction, see (8) in [Whiteley, 2007]. Unit: kPa. Default is Ta=0, i.e. no active tension anywhere."); params.addParam<FunctionName>("Ta_function", "A function that describes the (position dependent) active tension in fibre direction that will finally drive contraction, see (8) in [Whiteley, 2007]. Unit: kPa."); params.addCoupledVar("p", 0, "Hydrostatic pressure that acts as a Lagrange multiplier to ensure incompressibility. Unit: kPa. Works best with CardiacMechanicsIncompressibilityLagrangeMultiplier kernel. Default: 0. (no hydrostatic pressure)."); params.set<bool>("use_displaced_mesh") = false; return params; } CardiacMechanicsMaterial::CardiacMechanicsMaterial(const std::string & name, InputParameters parameters) :Material(name, parameters), _stress(declareProperty<SymmTensor>("Kirchhoff_stress")), _stress_derivative(declareProperty<SymmGenericElasticityTensor>("Kirchhoff_stress_derivative")), _F(declareProperty<RealTensorValue>("displacement_gradient")), _J(declareProperty<Real>("det_displacement_gradient")), _Cinv(declareProperty<SymmTensor>("Cinv")), _W(declareProperty<Real>("elastic_energy_density")), _Rf(getMaterialProperty<RealTensorValue>("R_fibre")), _Ef(getMaterialProperty<RealVectorValue>("E_fibre")), _Es(getMaterialProperty<RealVectorValue>("E_sheet")), _En(getMaterialProperty<RealVectorValue>("E_normal")), _has_Ta(isCoupled("Ta")), _Ta(_has_Ta ? coupledValue("Ta") : _zero), _has_Ta_function(isParamValid("Ta_function")), _Ta_function( _has_Ta_function ? &getFunction("Ta_function") : NULL ), _has_p(isCoupled("p")), _p(_has_p ? coupledValue("p") : _zero), _id(scaledID(1)) { if (_has_Ta && _has_Ta_function) mooseError("CardiacMechanicsMaterial: Only Ta or Ta_function may be given, not both of them."); // see http://mooseframework.org/wiki/Faq/#coupling-to-an-arbitrary-number-of-variables-back-to-top for details on this magic _grad_disp.resize(coupledComponents("displacements")); mooseAssert(_grad_disp.size() == 3, "CardiacMechanicsMaterial: displacements must have exactly 3 components"); for (unsigned int i=0; i<_grad_disp.size(); ++i) _grad_disp[i] = &coupledGradient("displacements", i); } void CardiacMechanicsMaterial::computeQpProperties() { // local deformation gradient tensor: F(ij) = dx(i)/dX(j) // Note that the nonlinear variables are displacements u(i)=x(i)-X(i), thus dx(i)/dX(j) = du(i)/dX(j) + delta(ij) _F[_qp] = RealTensorValue((*_grad_disp[0])[_qp], (*_grad_disp[1])[_qp], (*_grad_disp[2])[_qp]); _F[_qp](0,0) += 1; _F[_qp](1,1) += 1; _F[_qp](2,2) += 1; // ...its determinant is a measure for local volume changes (is needed in kernel that ensures incompressibility via hydrostatic pressure/Lagrange multiplier p) _J[_qp] = _F[_qp].det(); // From here on, we go over to fibre coordinates, i.e. for C, E, T // Cauchy-Green deformation tensor in fibre coordinates: C* = R^T F^T F R const SymmTensor C(symmProd(_Rf[_qp], symmProd(_F[_qp]))); // Lagrange-Green strain tensor const SymmTensor E( (C - _id) * 0.5 ); // in the rotated system compute _stress[_qp], _stress_derivative[_qp], and _W[_qp] computeQpStressProperties(C, E); // Add hydrostatic pressure and active tension // The following steps render // T asymmetric, i.e. we need a general (non-symmetric) tensor here // D asymmetric wrt. (MN)<->(PQ), i.e. we need the full fourth order tensor here. if (_has_p || _has_Ta || _has_Ta_function) { // Inverse of the Cauchy Green deformation tensor (note that det(C_fibre) = det(C) = det(F^T)*det(F) = det(F)^2, since det(R)==1 ) const SymmTensor Cinv( symmInv(C, _J[_qp]*_J[_qp]) ); // Add hydrostatic pressure as Lagrange multiplier to ensure incompressibility if (_has_p) { // _stress(MN) += p*Cinv(MN) _stress[_qp] -= Cinv * _p[_qp]; // for the derivative of T, things do become slightly complicated as we have to do // _stress_derivative(MNPQ) += 2 * p * Cinv(M,P) * Cinv(Q,N) SymmGenericElasticityTensor sdp(0); for (int M=0;M<3;M++) for (int N=M;N<3;N++) for (int P=M;P<3;P++) for (int Q=P;Q<3;Q++) { sdp(M,N,P,Q) = 2 * _p[_qp] * Cinv(M,P) * Cinv(Q,N); } _stress_derivative[_qp] += sdp; // no energy contribution from a Lagrange multiplier // _W[_qp] += 0 // the inverse of C in outer coordinates is required for the kernel's Jacobian matrix element wrt. pressure _Cinv[_qp] = symmProd(_Rf[_qp].transpose(), Cinv); } // Add active tension in fibre direction if (_has_Ta || _has_Ta_function) { Real Ta; if (_has_Ta) Ta = _Ta[_qp]; else Ta = _Ta_function->value(_t, _q_point[_qp]); // _stress(MN) += _Ta * delta(M1) delta(N1) * invC(M,N) const int M(0); const int N(0); _stress[_qp](M,N) += Ta*Cinv(M,N); // _stress_derivative(MNPQ) += -2 * _Ta * delta(M1) delta(N1) * invC(M,P) * invC(Q,N); SymmGenericElasticityTensor sda(0); for (int P=0;P<3;P++) for (int Q=P;Q<3;Q++) sda(M,N,P,Q) = -2 * Ta * Cinv(M,P) * Cinv(Q,N); _stress_derivative[_qp] += sda; /// @todo TODO: how does this go into the elastic energy ? // _W[_qp] += ?? } } // rotate back into the outer coordinate system _stress[_qp] = symmProd(_Rf[_qp].transpose(), _stress[_qp]); _stress_derivative[_qp] = _stress_derivative[_qp].quadProduct(_Rf[_qp]); } <commit_msg>renamed parameters of CardiacMechanicsMaterial for better readibility<commit_after>#include "CardiacMechanicsMaterial.h" #include "ColumnMajorMatrix.h" #include "CardiacSolidMechanicsMaterial.h" #include "SymmOrthotropicElasticityTensor.h" #include "VolumetricModel.h" #include "TensorHelpers.h" using namespace TensorHelpers; template<> InputParameters validParams<CardiacMechanicsMaterial>() { InputParameters params = validParams<Material>(); params.addRequiredCoupledVar("displacements", "The x, y, and z displacement"); params.addCoupledVar("active_tension", "The (position dependent) active tension in fibre direction that will finally drive contraction, see (8) in [Whiteley, 2007]. Unit: kPa. Default is Ta=0, i.e. no active tension anywhere."); params.addParam<FunctionName>("active_tension_function", "A function that describes the (position dependent) active tension in fibre direction that will finally drive contraction, see (8) in [Whiteley, 2007]. Unit: kPa."); params.addCoupledVar("hydrostatic_pressure", "Hydrostatic pressure that acts as a Lagrange multiplier to ensure incompressibility. Unit: kPa. Works best with CardiacMechanicsIncompressibilityLagrangeMultiplier kernel. Default: 0. (no hydrostatic pressure)."); params.set<bool>("use_displaced_mesh") = false; // we restrict output to Imem to avoid warnings about KirchhoffStress being impossible to be used in output std::vector<std::string> output_properties; output_properties.push_back("displacement_gradient det_displacement_gradient"); params.set<std::vector<std::string> >("output_properties") = output_properties; return params; } CardiacMechanicsMaterial::CardiacMechanicsMaterial(const std::string & name, InputParameters parameters) :Material(name, parameters), _stress(declareProperty<SymmTensor>("Kirchhoff_stress")), _stress_derivative(declareProperty<SymmGenericElasticityTensor>("Kirchhoff_stress_derivative")), _F(declareProperty<RealTensorValue>("displacement_gradient")), _J(declareProperty<Real>("det_displacement_gradient")), _Cinv(declareProperty<SymmTensor>("Cinv")), _W(declareProperty<Real>("elastic_energy_density")), _Rf(getMaterialProperty<RealTensorValue>("R_fibre")), _Ef(getMaterialProperty<RealVectorValue>("E_fibre")), _Es(getMaterialProperty<RealVectorValue>("E_sheet")), _En(getMaterialProperty<RealVectorValue>("E_normal")), _has_Ta(isCoupled("active_tension")), _Ta(_has_Ta ? coupledValue("active_tension") : _zero), _has_Ta_function(isParamValid("active_tension_function")), _Ta_function( _has_Ta_function ? &getFunction("active_tension_function") : NULL ), _has_p(isCoupled("hydrostatic_pressure")), _p(_has_p ? coupledValue("hydrostatic_pressure") : _zero), _id(scaledID(1)) { if (_has_Ta && _has_Ta_function) mooseError("CardiacMechanicsMaterial: Only Ta or Ta_function may be given, not both of them."); // see http://mooseframework.org/wiki/Faq/#coupling-to-an-arbitrary-number-of-variables-back-to-top for details on this magic _grad_disp.resize(coupledComponents("displacements")); mooseAssert(_grad_disp.size() == 3, "CardiacMechanicsMaterial: displacements must have exactly 3 components"); for (unsigned int i=0; i<_grad_disp.size(); ++i) _grad_disp[i] = &coupledGradient("displacements", i); } void CardiacMechanicsMaterial::computeQpProperties() { // local deformation gradient tensor: F(ij) = dx(i)/dX(j) // Note that the nonlinear variables are displacements u(i)=x(i)-X(i), thus dx(i)/dX(j) = du(i)/dX(j) + delta(ij) _F[_qp] = RealTensorValue((*_grad_disp[0])[_qp], (*_grad_disp[1])[_qp], (*_grad_disp[2])[_qp]); _F[_qp](0,0) += 1; _F[_qp](1,1) += 1; _F[_qp](2,2) += 1; // ...its determinant is a measure for local volume changes (is needed in kernel that ensures incompressibility via hydrostatic pressure/Lagrange multiplier p) _J[_qp] = _F[_qp].det(); // From here on, we go over to fibre coordinates, i.e. for C, E, T // Cauchy-Green deformation tensor in fibre coordinates: C* = R^T F^T F R const SymmTensor C(symmProd(_Rf[_qp], symmProd(_F[_qp]))); // Lagrange-Green strain tensor const SymmTensor E( (C - _id) * 0.5 ); // in the rotated system compute _stress[_qp], _stress_derivative[_qp], and _W[_qp] computeQpStressProperties(C, E); // Add hydrostatic pressure and active tension if (_has_p || _has_Ta || _has_Ta_function) { // Inverse of the Cauchy Green deformation tensor (note that det(C_fibre) = det(C) = det(F^T)*det(F) = det(F)^2, since det(R)==1 ) const SymmTensor Cinv( symmInv(C, _J[_qp]*_J[_qp]) ); // Add hydrostatic pressure as Lagrange multiplier to ensure incompressibility if (_has_p) { // _stress(MN) += p*Cinv(MN) _stress[_qp] -= Cinv * _p[_qp]; // for the derivative of T, things do become slightly complicated as we have to do // _stress_derivative(MNPQ) += 2 * p * Cinv(M,P) * Cinv(Q,N) SymmGenericElasticityTensor sdp(0); for (int M=0;M<3;M++) for (int N=M;N<3;N++) for (int P=M;P<3;P++) for (int Q=P;Q<3;Q++) { sdp(M,N,P,Q) = 2 * _p[_qp] * Cinv(M,P) * Cinv(Q,N); } _stress_derivative[_qp] += sdp; // no energy contribution from a Lagrange multiplier // _W[_qp] += 0 // the inverse of C in outer coordinates is required for the kernel's Jacobian matrix element wrt. pressure _Cinv[_qp] = symmProd(_Rf[_qp].transpose(), Cinv); } // Add active tension in fibre direction if (_has_Ta || _has_Ta_function) { Real Ta; if (_has_Ta) Ta = _Ta[_qp]; else Ta = _Ta_function->value(_t, _q_point[_qp]); // _stress(MN) += _Ta * delta(M1) delta(N1) * invC(M,N) const int M(0); const int N(0); _stress[_qp](M,N) += Ta*Cinv(M,N); // _stress_derivative(MNPQ) += -2 * _Ta * delta(M1) delta(N1) * invC(M,P) * invC(Q,N); SymmGenericElasticityTensor sda(0); for (int P=0;P<3;P++) for (int Q=P;Q<3;Q++) sda(M,N,P,Q) = -2 * Ta * Cinv(M,P) * Cinv(Q,N); _stress_derivative[_qp] += sda; /// @todo TODO: how does this go into the elastic energy ? // _W[_qp] += ?? } } // rotate back into the outer coordinate system _stress[_qp] = symmProd(_Rf[_qp].transpose(), _stress[_qp]); _stress_derivative[_qp] = _stress_derivative[_qp].quadProduct(_Rf[_qp]); } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2013-2017 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef DATA_H #define DATA_H #include "cpp_utils/assert.hpp" #include "config.hpp" #include "utils.hpp" namespace budget { template<typename T> struct data_handler { size_t next_id; std::vector<T> data; data_handler(const char* path) : path(path) {}; //data_handler should never be copied data_handler(const data_handler& rhs) = delete; data_handler& operator=(const data_handler& rhs) = delete; bool is_changed() const { return changed; } void set_changed(){ changed = true; } template<typename Functor> void load(Functor f){ auto file_path = path_to_budget_file(path); if(!file_exists(file_path)){ next_id = 1; } else { std::ifstream file(file_path); if(file.is_open()){ if(file.good()){ //Make sure to clear the data first, as load_data can be called //several times data.clear(); // We do not use the next_id saved anymore size_t fake; file >> fake; file.get(); next_id = 1; std::string line; while(file.good() && getline(file, line)){ auto parts = split(line, ':'); T entry; f(parts, entry); if(entry.id >= next_id){ next_id = entry.id + 1; } data.push_back(std::move(entry)); } } } } } void load(){ load([](std::vector<std::string>& parts, T& entry){ parts >> entry; }); } void save() { if (is_changed()) { if (budget::config_contains("random")) { std::cerr << "budget: error: Saving is disabled in random mode" << std::endl; return; } auto file_path = path_to_budget_file(path); std::ofstream file(file_path); // We still save the file ID so that it's still compatible with older versions for now file << next_id << std::endl; for (auto& entry : data) { file << entry << std::endl; } } } size_t size() const { return data.size(); } decltype(auto) begin() { return data.begin(); } decltype(auto) begin() const { return data.begin(); } decltype(auto) end() { return data.end(); } decltype(auto) end() const { return data.end(); } private: const char* path; bool changed = false; }; template<typename T> bool exists(const data_handler<T>& data, size_t id){ for(auto& entry : data.data){ if(entry.id == id){ return true; } } return false; } template<typename T> void remove(data_handler<T>& data, size_t id){ data.data.erase(std::remove_if(data.data.begin(), data.data.end(), [id](const T& entry){ return entry.id == id; }), data.data.end()); data.set_changed(); } template<typename T> T& get(data_handler<T>& data, size_t id){ for(auto& value : data.data){ if(value.id == id){ return value; } } cpp_unreachable("The data must exists"); } template<typename T> size_t add_data(data_handler<T>& data, T&& entry){ entry.id = data.next_id++; data.data.push_back(std::forward<T>(entry)); data.set_changed(); return entry.id; } } //end of namespace budget #endif <commit_msg>Save directly to file in server mode<commit_after>//======================================================================= // Copyright (c) 2013-2017 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef DATA_H #define DATA_H #include "cpp_utils/assert.hpp" #include "config.hpp" #include "utils.hpp" #include "server.hpp" namespace budget { template<typename T> struct data_handler { size_t next_id; std::vector<T> data; data_handler(const char* path) : path(path) {}; //data_handler should never be copied data_handler(const data_handler& rhs) = delete; data_handler& operator=(const data_handler& rhs) = delete; bool is_changed() const { return changed; } void set_changed() { if (is_server_mode()) { force_save(); } else { changed = true; } } template<typename Functor> void load(Functor f){ auto file_path = path_to_budget_file(path); if(!file_exists(file_path)){ next_id = 1; } else { std::ifstream file(file_path); if(file.is_open()){ if(file.good()){ //Make sure to clear the data first, as load_data can be called //several times data.clear(); // We do not use the next_id saved anymore size_t fake; file >> fake; file.get(); next_id = 1; std::string line; while(file.good() && getline(file, line)){ auto parts = split(line, ':'); T entry; f(parts, entry); if(entry.id >= next_id){ next_id = entry.id + 1; } data.push_back(std::move(entry)); } } } } } void load(){ load([](std::vector<std::string>& parts, T& entry){ parts >> entry; }); } void force_save() { if (budget::config_contains("random")) { std::cerr << "budget: error: Saving is disabled in random mode" << std::endl; return; } auto file_path = path_to_budget_file(path); std::ofstream file(file_path); // We still save the file ID so that it's still compatible with older versions for now file << next_id << std::endl; for (auto& entry : data) { file << entry << std::endl; } changed = false; } void save() { if (is_changed()) { force_save(); } } size_t size() const { return data.size(); } decltype(auto) begin() { return data.begin(); } decltype(auto) begin() const { return data.begin(); } decltype(auto) end() { return data.end(); } decltype(auto) end() const { return data.end(); } private: const char* path; bool changed = false; }; template<typename T> bool exists(const data_handler<T>& data, size_t id){ for(auto& entry : data.data){ if(entry.id == id){ return true; } } return false; } template<typename T> void remove(data_handler<T>& data, size_t id){ data.data.erase(std::remove_if(data.data.begin(), data.data.end(), [id](const T& entry){ return entry.id == id; }), data.data.end()); data.set_changed(); } template<typename T> T& get(data_handler<T>& data, size_t id){ for(auto& value : data.data){ if(value.id == id){ return value; } } cpp_unreachable("The data must exists"); } template<typename T> size_t add_data(data_handler<T>& data, T&& entry){ entry.id = data.next_id++; data.data.push_back(std::forward<T>(entry)); data.set_changed(); return entry.id; } } //end of namespace budget #endif <|endoftext|>
<commit_before>/*------------------------------- PASA LA CALCULADORA Autores: Jaime Sevilla Molina Victor Gonzalez Fecha 2014/11 Version: 1.0 ---------------------------------*/ //BIBLIOTECAS #include <iostream> #include <cstdlib> #include <string> #include <ctime> #include <cmath> #include <fstream> #include <iomanip> using namespace std; //TIPOS PROPIOS typedef enum tJugador { Nadie, Jugador, Automata }; //FUNCIONES //FUNCIONES DE JUEGO void saludar (); //Dependiendo de quien gane, la despedida sera distinta void despedirse (tJugador ganador); //Muestra un menu que permite al jugador jugar, salir, o ver las reglas del juego int menu(); //Muestra las instrucciones del juego, siempre que su archivo no contenga errores bool acerca(); //Conduce el desarrollo del juego y devuelve el ganador. //Si se abandona, devuelve Nadie. tJugador pasaCalculadora(); //Decide aleatoriamente quien empieza. tJugador quienEmpieza(); //Devuelve true si nuevo esta en la misma fila que ultimo bool mismaFila(int ultimo, int nuevo); //Devuelve true si nuevo esta en la misma columna que ultimo bool mismaColumna(int ultimo, int nuevo); //Devuelve true si nuevo cumple las reglas del juego con respecto a ultimo //Si ultimo == 0, este es el primer digito de la partida, y devuelve true bool digitoValido(int ultimo, int nuevo); //FUNCIONES DE IA NIVEL 1 //Devuelve un digito del 1 al 9 int digitoAleatorio(); //Devuelve un digito que cumpla las reglas del juego con respecto a ultimo. int digitoAutomata(int ultimo); //FUNCIONES DE JUGADOR //Pide un digito al jugador. Solo devolvera un valor valido (entre 0 y 9). //Para un valor no valido, mostrara un error. int digitoPersona(); //Pide un digito al jugador mostrando el teclado. Solo devolvera un valor //que cumpla las reglas del juego o 0. Para un valor no valido, mostrara un error. int digitoPersona(int ultimo); //Determina si el numero de la calculadora se muestra o no, en funcion de si es valido char mNumero(int ultimo, int n); //Muestra los botones de la calculadora (solo los que se pueden pulsar en cada turno) void mostrarCalculadora(int ultimo); /* Las funciones a continuacion se implementaran en un futuro //FUNCIONES DE INFORME //Actualiza el archivo informePC.txt con los tres argumentos. En caso de no encontrar //el archivo, lo crea y devuelve false; en otro caso devuelve true. bool actInforme(int jugadas, int ganadas, int abandonos); //FUNCIONES DE DIFICULTAD AVANZADA int botDificil(int ultimo); -----------------------------------------------------------------------------------*/ int main(){ tJugador ganador; int opcion; saludar(); //Bucle Menu do{ opcion = menu(); if(opcion == 1){ ganador = pasaCalculadora(); despedirse(ganador); } else if(opcion == 2) acerca(); }while(opcion != 0); cout << "Hasta la proxima (pulsa enter)"; cin; return 0; } //Saluda al jugador y le pregunta su nombre void saludar(){ string nombre; cout << "Bienvenido a Pasa la calculadora!" << endl; cout << "Como te llamas? "; cin >> nombre; cout << "Hola " << nombre << endl << endl; } //Se despide del jugador, la despedida varia segun gane el jugador, el automata o ninguno de ellos (el jugador abandone) void despedirse(tJugador ganador){ string nombre; if (ganador == Nadie){ cout << "¿Abandonas? Ohhh..." << endl; } else if (ganador == Jugador){ cout << "Enhorabuena, has ganado" << endl; } else /*if (ganador == Automata)*/{ cout << "Lo siento, he ganado" << endl; } } //Proporciona al jugador la posibilidad de jugar, ver las instrucciones del juego o salir. int menu(){ int seleccionar; cout << "1 - Jugar" << endl; cout << "2 - Acerca de" << endl; cout << "0 - Salir" << endl; do{ try{ cin.sync(); //Por si quedan datos basura en el buffer cin >> seleccionar; if (seleccionar < 0 || seleccionar > 2) throw; //No funciona como se esperaba }catch(...){ cout << "Error! Introduce un digito entre 0 y 2"; seleccionar = -1; } }while (seleccionar == -1); return seleccionar; } //Muestra el archivo "acerca.txt" siempre que este no contenga errores bool acerca(){ bool ok; ifstream acerca; char c; acerca.open("acerca.txt"); if(acerca.is_open()) { acerca.get(c); //Lee el primer caracter while(!acerca.fail()) //Mientras la lectura no falle { cout << c; acerca.get(c); //Lee el siguiente caracter } ok = true; } else { ok = false; cout << "Error, el archivo 'acerca.txt' no existe" << endl; } return ok; } //Conduce el desarrollo del juego y devuelve el ganador. //Si se abandona, devuelve Nadie. tJugador pasaCalculadora(){ //Variables tJugador turno; int total = 0, ultimoDigito = 0; const int META=31; //Inicializar partida srand(time(NULL));//Semilla turno = quienEmpieza(); //Bucle de juego do { //Turno jugador if (turno == Jugador) { ultimoDigito = digitoPersona(ultimoDigito); turno = Automata; } //Turno bot else /*if (turno == Automata)*/ { ultimoDigito = digitoAutomata(ultimoDigito); turno = Jugador; } total += ultimoDigito; cout << "Total = " << total << endl; } while ((total < META) && (ultimoDigito != 0)); if (ultimoDigito == 0) turno = Nadie; //Si el jugador abandona, no gana nadie return turno; } //Decide aleatoriamente quien empieza la partida, si el automata o el jugador tJugador quienEmpieza(){ if (rand() % 2) { cout << "Tu empiezas" << endl; return Jugador; } else { cout << "Empiezo yo" << endl; return Automata; } } //Define que numeros se encuentran en la misma fila que el ultimo pulsado bool mismaFila(int ultimo, int nuevo) { double filaUltimo, filaNuevo; filaUltimo = (ultimo/3); filaNuevo = (nuevo/3); return ceil(filaUltimo) == ceil(filaNuevo); } //Define que numeros se encuentran en la misma columna que el ultimo bool mismaColumna(int ultimo, int nuevo) { int columnaUltimo, columnaNuevo; columnaUltimo = (ultimo % 3); columnaNuevo = (nuevo % 3); return columnaUltimo == columnaNuevo; } //Determina que digitos se pueden pulsar en funcion de las reglas del juego bool digitoValido(int ultimo, int nuevo) //hay un bug { if (ultimo == 0) return true;//Si es el primer turno, todos los numeros valen return ((mismaFila(ultimo, nuevo))||(mismaColumna(ultimo, nuevo)))&&(ultimo!=nuevo); } //Genera un digito aleatorio int digitoAleatorio() { return (rand() % 9) + 1; } //Devuelve un digito que cumpla las reglas del juego con respecto a ultimo. int digitoAutomata(int ultimo) { int digito; do { digito = digitoAleatorio(); } while (!digitoValido(ultimo, digito)); cout << "Elijo el numero " << digito << endl; return digito; } //Pide un digito al jugador. Solo devolvera un valor valido (entre 0 y 9). //Para un valor no valido, mostrara un error. int digitoPersona() { int digito = -1; do { cin.sync(); //Por si quedan datos basura en el buffer cin >> digito; if (digito < 0 || digito > 9) { cout << "Error! Introduce un digito entre 0 y 9"; digito = -1; } else if (cin.fail()) { cout << "Error! Introduce un digito"; cin.clear(); } } while (digito == -1); return digito; } //Pide un digito al jugador mostrando el teclado. Solo devolvera un valor //que cumpla las reglas del juego o 0. Para un valor no valido, mostrara un error. int digitoPersona(int ultimo) { int digito; //-1 es mi error flag mostrarCalculadora(ultimo); do { try { digito = digitoPersona(); if (!digitoValido(ultimo, digito)) throw; } catch(...) { cout << "Error! El digito debe estar en la misma fila y columna que el ultimo" << endl; digito = -1; } } while (digito == -1); cout << "Has elegido el " << digito << endl; return digito; } //Determina si el numero de la calculadora se muestra o no, en funcion de si es valido char mNumero(int ultimo, int n) { if(digitoValido(ultimo, n)) return char (n+int('0')); else return ' '; } //Muestra los botones de la calculadora (solo los que se pueden pulsar en cada turno) void mostrarCalculadora(int ultimo) { for (int i = 7; i<10; i++) { cout << setw(3) << mNumero(ultimo, i); } cout << endl; for (int i = 4; i<7; i++) { cout << setw(3) << mNumero(ultimo, i); } cout << endl; for (int i = 1; i<4; i++) { cout << setw(3) << mNumero(ultimo, i); } cout << endl; } <commit_msg>Matando duendes<commit_after>/*------------------------------- PASA LA CALCULADORA Autores: Jaime Sevilla Molina Victor Gonzalez Fecha 2014/11 Version: 1.0 ---------------------------------*/ //BIBLIOTECAS #include <iostream> #include <cstdlib> #include <string> #include <ctime> #include <cmath> #include <fstream> #include <iomanip> using namespace std; //TIPOS PROPIOS typedef enum tJugador { Nadie, Jugador, Automata }; //FUNCIONES //FUNCIONES DE JUEGO void saludar (); //Dependiendo de quien gane, la despedida sera distinta void despedirse (tJugador ganador); //Muestra un menu que permite al jugador jugar, salir, o ver las reglas del juego int menu(); //Muestra las instrucciones del juego, siempre que su archivo no contenga errores bool acerca(); //Conduce el desarrollo del juego y devuelve el ganador. //Si se abandona, devuelve Nadie. tJugador pasaCalculadora(); //Decide aleatoriamente quien empieza. tJugador quienEmpieza(); //Devuelve true si nuevo esta en la misma fila que ultimo bool mismaFila(int ultimo, int nuevo); //Devuelve true si nuevo esta en la misma columna que ultimo bool mismaColumna(int ultimo, int nuevo); //Devuelve true si nuevo cumple las reglas del juego con respecto a ultimo //Si ultimo == 0, este es el primer digito de la partida, y devuelve true bool digitoValido(int ultimo, int nuevo); //FUNCIONES DE IA NIVEL 1 //Devuelve un digito del 1 al 9 int digitoAleatorio(); //Devuelve un digito que cumpla las reglas del juego con respecto a ultimo. int digitoAutomata(int ultimo); //FUNCIONES DE JUGADOR //Pide un digito al jugador. Solo devolvera un valor valido (entre 0 y 9). //Para un valor no valido, mostrara un error. int digitoPersona(); //Pide un digito al jugador mostrando el teclado. Solo devolvera un valor //que cumpla las reglas del juego o 0. Para un valor no valido, mostrara un error. int digitoPersona(int ultimo); //Determina si el numero de la calculadora se muestra o no, en funcion de si es valido char mNumero(int ultimo, int n); //Muestra los botones de la calculadora (solo los que se pueden pulsar en cada turno) void mostrarCalculadora(int ultimo); /* Las funciones a continuacion se implementaran en un futuro //FUNCIONES DE INFORME //Actualiza el archivo informePC.txt con los tres argumentos. En caso de no encontrar //el archivo, lo crea y devuelve false; en otro caso devuelve true. bool actInforme(int jugadas, int ganadas, int abandonos); //FUNCIONES DE DIFICULTAD AVANZADA int botDificil(int ultimo); -----------------------------------------------------------------------------------*/ int main(){ tJugador ganador; int opcion; saludar(); //Bucle Menu do{ opcion = menu(); if(opcion == 1){ ganador = pasaCalculadora(); despedirse(ganador); } else if(opcion == 2) acerca(); }while(opcion != 0); cout << "Hasta la proxima (pulsa enter)"; cin; return 0; } //Saluda al jugador y le pregunta su nombre void saludar(){ string nombre; cout << "Bienvenido a Pasa la calculadora!" << endl; cout << "Como te llamas? "; cin >> nombre; cout << "Hola " << nombre << endl << endl; } //Se despide del jugador, la despedida varia segun gane el jugador, el automata o ninguno de ellos (el jugador abandone) void despedirse(tJugador ganador){ string nombre; if (ganador == Nadie){ cout << "¿Abandonas? Ohhh..." << endl; } else if (ganador == Jugador){ cout << "Enhorabuena, has ganado" << endl; } else /*if (ganador == Automata)*/{ cout << "Lo siento, he ganado" << endl; } } //Proporciona al jugador la posibilidad de jugar, ver las instrucciones del juego o salir. int menu(){ int seleccionar; cout << "1 - Jugar" << endl; cout << "2 - Acerca de" << endl; cout << "0 - Salir" << endl; do{ cin.sync(); //Por si quedan datos basura en el buffer cin >> seleccionar; if (seleccionar < 0 || seleccionar > 2) { cout << "Error! Introduce un digito entre 0 y 2" << endl; seleccionar = -1; } else if(cin.fail()) { cout << "Error! Introduce un digito" << endl; cin.clear(); } }while (seleccionar == -1); return seleccionar; } //Muestra el archivo "acerca.txt" siempre que este no contenga errores bool acerca(){ bool ok; ifstream acerca; char c; acerca.open("acerca.txt"); if(acerca.is_open()) { acerca.get(c); //Lee el primer caracter while(!acerca.fail()) //Mientras la lectura no falle { cout << c; acerca.get(c); //Lee el siguiente caracter } ok = true; acerca.close(); } else { ok = false; cout << "Error, el archivo 'acerca.txt' no existe" << endl; } return ok; } //Conduce el desarrollo del juego y devuelve el ganador. //Si se abandona, devuelve Nadie. tJugador pasaCalculadora(){ //Variables tJugador turno; int total = 0, ultimoDigito = 0; const int META=31; //Inicializar partida srand(time(NULL));//Semilla turno = quienEmpieza(); //Bucle de juego do { //Turno jugador if (turno == Jugador) { ultimoDigito = digitoPersona(ultimoDigito); turno = Automata; } //Turno bot else /*if (turno == Automata)*/ { ultimoDigito = digitoAutomata(ultimoDigito); turno = Jugador; } total += ultimoDigito; cout << "Total = " << total << endl; } while ((total < META) && (ultimoDigito != 0)); if (ultimoDigito == 0) turno = Nadie; //Si el jugador abandona, no gana nadie return turno; } //Decide aleatoriamente quien empieza la partida, si el automata o el jugador tJugador quienEmpieza(){ if (rand() % 2) { cout << "Tu empiezas" << endl; return Jugador; } else { cout << "Empiezo yo" << endl; return Automata; } } //Define que numeros se encuentran en la misma fila que el ultimo pulsado bool mismaFila(int ultimo, int nuevo) { double filaUltimo, filaNuevo; filaUltimo = (ultimo/3); filaNuevo = (nuevo/3); return ceil(filaUltimo) == ceil(filaNuevo); } //Define que numeros se encuentran en la misma columna que el ultimo bool mismaColumna(int ultimo, int nuevo) { int columnaUltimo, columnaNuevo; columnaUltimo = (ultimo % 3); columnaNuevo = (nuevo % 3); return columnaUltimo == columnaNuevo; } //Determina que digitos se pueden pulsar en funcion de las reglas del juego bool digitoValido(int ultimo, int nuevo) //hay un bug { if (ultimo == 0) return true;//Si es el primer turno, todos los numeros valen return ((mismaFila(ultimo, nuevo))||(mismaColumna(ultimo, nuevo)))&&(ultimo!=nuevo); } //Genera un digito aleatorio int digitoAleatorio() { return (rand() % 9) + 1; } //Devuelve un digito que cumpla las reglas del juego con respecto a ultimo. int digitoAutomata(int ultimo) { int digito; do { digito = digitoAleatorio(); } while (!digitoValido(ultimo, digito)); cout << "Elijo el numero " << digito << endl; return digito; } //Pide un digito al jugador. Solo devolvera un valor valido (entre 0 y 9). //Para un valor no valido, mostrara un error. int digitoPersona() { int digito = -1; do { cin.sync(); //Por si quedan datos basura en el buffer cin >> digito; if (digito < 0 || digito > 9) { cout << "Error! Introduce un digito entre 0 y 9" << endl; digito = -1; } else if (cin.fail()) { cout << "Error! Introduce un digito" << endl; cin.clear(); } } while (digito == -1); return digito; } //Pide un digito al jugador mostrando el teclado. Solo devolvera un valor //que cumpla las reglas del juego o 0. Para un valor no valido, mostrara un error. int digitoPersona(int ultimo) { int digito; //-1 es mi error flag mostrarCalculadora(ultimo); do { digito = digitoPersona(); if (!digitoValido(ultimo, digito)) { cout << "Error! El digito debe estar en la misma fila y columna que el ultimo" << endl; digito = -1; } } while (digito == -1); cout << "Has elegido el " << digito << endl; return digito; } //Determina si el numero de la calculadora se muestra o no, en funcion de si es valido char mNumero(int ultimo, int n) { if(digitoValido(ultimo, n)) return char (n+int('0')); else return ' '; } //Muestra los botones de la calculadora (solo los que se pueden pulsar en cada turno) void mostrarCalculadora(int ultimo) { for (int i = 7; i<10; i++) { cout << setw(3) << mNumero(ultimo, i); } cout << endl; for (int i = 4; i<7; i++) { cout << setw(3) << mNumero(ultimo, i); } cout << endl; for (int i = 1; i<4; i++) { cout << setw(3) << mNumero(ultimo, i); } cout << endl; } <|endoftext|>
<commit_before>// // EnvelopeGenerator.hpp // Clock Signal // // Created by Thomas Harte on 01/05/2020. // Copyright © 2020 Thomas Harte. All rights reserved. // #ifndef EnvelopeGenerator_h #define EnvelopeGenerator_h #include <optional> #include <functional> namespace Yamaha { namespace OPL { /*! Models an OPL-style envelope generator. Damping is optional; if damping is enabled then if there is a transition to key-on while attenuation is less than maximum then attenuation will be quickly transitioned to maximum before the attack phase can begin. in real hardware damping is used by the envelope generators associated with carriers, with phases being reset upon the transition from damping to attack. This code considers application of tremolo to be a function of the envelope generator; this is largely for logical conformity with the phase generator that necessarily has to apply vibrato. */ template <int envelope_precision, int period_precision> class EnvelopeGenerator { public: /*! Advances the envelope generator a single step, given the current state of the low-frequency oscillator, @c oscillator. */ void update(const LowFrequencyOscillator &oscillator) { // Apply tremolo, which is fairly easy. tremolo_ = tremolo_enable_ * oscillator.tremolo << 4; // Something something something... const int key_scaling_rate = key_scale_rate_ >> key_scale_rate_shift_; switch(phase_) { case Phase::Damp: update_decay(oscillator, 12); if(attenuation_ == 511) { will_attack_(); phase_ = Phase::Attack; } break; case Phase::Attack: update_attack(oscillator, attack_rate_ + key_scaling_rate); // Two possible terminating conditions: (i) the attack rate is 15; (ii) full volume has been reached. if((attack_rate_ + key_scaling_rate) > 60 || attenuation_ <= 0) { attenuation_ = 0; phase_ = Phase::Decay; } break; case Phase::Decay: update_decay(oscillator, decay_rate_ + key_scaling_rate); if(attenuation_ >= sustain_level_) { attenuation_ = sustain_level_; phase_ = use_sustain_level_ ? Phase::Sustain : Phase::Release; } break; case Phase::Sustain: // Nothing to do. break; case Phase::Release: update_decay(oscillator, release_rate_ + key_scaling_rate); break; } } /*! @returns The current attenuation from this envelope generator. */ int attenuation() const { return attenuation_ + tremolo_; } /*! Enables or disables damping on this envelope generator. If damping is enabled then this envelope generator will use the damping phase when necessary (i.e. when transitioning to key on if attenuation is not already at maximum) and in any case will call @c will_attack before transitioning from any other state to attack. @param will_attack Supply a will_attack callback to enable damping mode; supply nullopt to disable damping mode. */ void set_should_damp(const std::optional<std::function<void(void)>> &will_attack) { will_attack_ = will_attack; } /*! Sets the current state of the key-on input. */ void set_key_on(bool key_on) { // Do nothing if this is not a leading or trailing edge. if(key_on == key_on_) return; key_on_ = key_on; // Always transition to release upon a key off. if(!key_on_) { phase_ = Phase::Release; return; } // On key on: if this is an envelope generator with damping, and damping is required, // schedule that. If damping is not required, announce a pending attack now and // transition to attack. if(will_attack_) { if(attenuation_ != 511) { phase_ = Phase::Damp; return; } will_attack_(); } phase_ = Phase::Attack; } /*! Sets the attack rate, which should be in the range 0–15. */ void set_attack_rate(int rate) { attack_rate_ = rate << 2; } /*! Sets the decay rate, which should be in the range 0–15. */ void set_decay_rate(int rate) { decay_rate_ = rate << 2; } /*! Sets the release rate, which should be in the range 0–15. */ void set_release_rate(int rate) { release_rate_ = rate << 2; } /*! Sets the sustain level, which should be in the range 0–15. */ void set_sustain_level(int level) { sustain_level_ = level << 3; // TODO: verify the shift level here. Especially re: precision. } /*! Enables or disables use of the sustain level. If this is disabled, the envelope proceeds directly from decay to release. */ void set_use_sustain_level(bool use) { use_sustain_level_ = use; } /*! Enables or disables key-rate scaling. */ void set_key_scaling_rate_enabled(bool enabled) { key_scale_rate_shift_ = int(enabled) * 2; } /*! Enables or disables application of the low-frequency oscillator's tremolo. */ void set_tremolo_enabled(bool enabled) { tremolo_enable_ = int(enabled); } /*! Sets the current period associated with the channel that owns this envelope generator; this is used to select a key scaling rate if key-rate scaling is enabled. */ void set_period(int period, int octave) { key_scale_rate_ = (octave << 1) | (period >> (period_precision - 1)); } private: enum class Phase { Attack, Decay, Sustain, Release, Damp } phase_ = Phase::Attack; int attenuation_ = 511, tremolo_ = 0; bool key_on_ = false; std::optional<std::function<void(void)>> will_attack_; int key_scale_rate_ = 0; int key_scale_rate_shift_ = 0; int tremolo_enable_ = 0; int attack_rate_ = 0; int decay_rate_ = 0; int release_rate_ = 0; int sustain_level_ = 0; bool use_sustain_level_ = false; void update_attack(const LowFrequencyOscillator &oscillator, int rate) { // Rules: // // An attack rate of '13' has 32 samples in the attack phase; a rate of '12' has the same 32 steps, but spread out over 64 samples, etc. // An attack rate of '14' uses a divide by four instead of two. // 15 is instantaneous. if(rate >= 56) { attenuation_ -= (attenuation_ >> 2) - 1; } else { const int sample_length = 1 << (14 - (rate >> 2)); // TODO: don't throw away KSR bits. if(!(oscillator.counter & (sample_length - 1))) { attenuation_ -= (attenuation_ >> 3) - 1; } } } void update_decay(const LowFrequencyOscillator &oscillator, int rate) { // Rules: // // (relative to a 511 scale) // // A rate of 0 is no decay at all. // A rate of 1 means increase 4 per cycle. // A rate of 2 means increase 2 per cycle. // A rate of 3 means increase 1 per cycle. // A rate of 4 means increase 1 every other cycle. // A rate of 5 means increase once every fourth cycle. // etc. // eighth, sixteenth, 32nd, 64th, 128th, 256th, 512th, 1024th, 2048th, 4096th, 8192th if(rate) { // TODO: don't throw away low two bits of the rate. switch(rate >> 2) { case 1: attenuation_ += 32; break; case 2: attenuation_ += 16; break; default: { const int sample_length = 1 << ((rate >> 2) - 4); if(!(oscillator.counter & (sample_length - 1))) { attenuation_ += 8; } } break; } // Clamp to the proper range. attenuation_ = std::min(attenuation_, 511); } } }; } } #endif /* EnvelopeGenerator_h */ <commit_msg>Ensures proper dereferencing of the std::optional.<commit_after>// // EnvelopeGenerator.hpp // Clock Signal // // Created by Thomas Harte on 01/05/2020. // Copyright © 2020 Thomas Harte. All rights reserved. // #ifndef EnvelopeGenerator_h #define EnvelopeGenerator_h #include <optional> #include <functional> namespace Yamaha { namespace OPL { /*! Models an OPL-style envelope generator. Damping is optional; if damping is enabled then if there is a transition to key-on while attenuation is less than maximum then attenuation will be quickly transitioned to maximum before the attack phase can begin. in real hardware damping is used by the envelope generators associated with carriers, with phases being reset upon the transition from damping to attack. This code considers application of tremolo to be a function of the envelope generator; this is largely for logical conformity with the phase generator that necessarily has to apply vibrato. */ template <int envelope_precision, int period_precision> class EnvelopeGenerator { public: /*! Advances the envelope generator a single step, given the current state of the low-frequency oscillator, @c oscillator. */ void update(const LowFrequencyOscillator &oscillator) { // Apply tremolo, which is fairly easy. tremolo_ = tremolo_enable_ * oscillator.tremolo << 4; // Something something something... const int key_scaling_rate = key_scale_rate_ >> key_scale_rate_shift_; switch(phase_) { case Phase::Damp: update_decay(oscillator, 12); if(attenuation_ == 511) { (*will_attack_)(); phase_ = Phase::Attack; } break; case Phase::Attack: update_attack(oscillator, attack_rate_ + key_scaling_rate); // Two possible terminating conditions: (i) the attack rate is 15; (ii) full volume has been reached. if((attack_rate_ + key_scaling_rate) > 60 || attenuation_ <= 0) { attenuation_ = 0; phase_ = Phase::Decay; } break; case Phase::Decay: update_decay(oscillator, decay_rate_ + key_scaling_rate); if(attenuation_ >= sustain_level_) { attenuation_ = sustain_level_; phase_ = use_sustain_level_ ? Phase::Sustain : Phase::Release; } break; case Phase::Sustain: // Nothing to do. break; case Phase::Release: update_decay(oscillator, release_rate_ + key_scaling_rate); break; } } /*! @returns The current attenuation from this envelope generator. */ int attenuation() const { return attenuation_ + tremolo_; } /*! Enables or disables damping on this envelope generator. If damping is enabled then this envelope generator will use the damping phase when necessary (i.e. when transitioning to key on if attenuation is not already at maximum) and in any case will call @c will_attack before transitioning from any other state to attack. @param will_attack Supply a will_attack callback to enable damping mode; supply nullopt to disable damping mode. */ void set_should_damp(const std::optional<std::function<void(void)>> &will_attack) { will_attack_ = will_attack; } /*! Sets the current state of the key-on input. */ void set_key_on(bool key_on) { // Do nothing if this is not a leading or trailing edge. if(key_on == key_on_) return; key_on_ = key_on; // Always transition to release upon a key off. if(!key_on_) { phase_ = Phase::Release; return; } // On key on: if this is an envelope generator with damping, and damping is required, // schedule that. If damping is not required, announce a pending attack now and // transition to attack. if(will_attack_) { if(attenuation_ != 511) { phase_ = Phase::Damp; return; } (*will_attack_)(); } phase_ = Phase::Attack; } /*! Sets the attack rate, which should be in the range 0–15. */ void set_attack_rate(int rate) { attack_rate_ = rate << 2; } /*! Sets the decay rate, which should be in the range 0–15. */ void set_decay_rate(int rate) { decay_rate_ = rate << 2; } /*! Sets the release rate, which should be in the range 0–15. */ void set_release_rate(int rate) { release_rate_ = rate << 2; } /*! Sets the sustain level, which should be in the range 0–15. */ void set_sustain_level(int level) { sustain_level_ = level << 3; // TODO: verify the shift level here. Especially re: precision. } /*! Enables or disables use of the sustain level. If this is disabled, the envelope proceeds directly from decay to release. */ void set_use_sustain_level(bool use) { use_sustain_level_ = use; } /*! Enables or disables key-rate scaling. */ void set_key_scaling_rate_enabled(bool enabled) { key_scale_rate_shift_ = int(enabled) * 2; } /*! Enables or disables application of the low-frequency oscillator's tremolo. */ void set_tremolo_enabled(bool enabled) { tremolo_enable_ = int(enabled); } /*! Sets the current period associated with the channel that owns this envelope generator; this is used to select a key scaling rate if key-rate scaling is enabled. */ void set_period(int period, int octave) { key_scale_rate_ = (octave << 1) | (period >> (period_precision - 1)); } private: enum class Phase { Attack, Decay, Sustain, Release, Damp } phase_ = Phase::Attack; int attenuation_ = 511, tremolo_ = 0; bool key_on_ = false; std::optional<std::function<void(void)>> will_attack_; int key_scale_rate_ = 0; int key_scale_rate_shift_ = 0; int tremolo_enable_ = 0; int attack_rate_ = 0; int decay_rate_ = 0; int release_rate_ = 0; int sustain_level_ = 0; bool use_sustain_level_ = false; void update_attack(const LowFrequencyOscillator &oscillator, int rate) { // Rules: // // An attack rate of '13' has 32 samples in the attack phase; a rate of '12' has the same 32 steps, but spread out over 64 samples, etc. // An attack rate of '14' uses a divide by four instead of two. // 15 is instantaneous. if(rate >= 56) { attenuation_ -= (attenuation_ >> 2) - 1; } else { const int sample_length = 1 << (14 - (rate >> 2)); // TODO: don't throw away KSR bits. if(!(oscillator.counter & (sample_length - 1))) { attenuation_ -= (attenuation_ >> 3) - 1; } } } void update_decay(const LowFrequencyOscillator &oscillator, int rate) { // Rules: // // (relative to a 511 scale) // // A rate of 0 is no decay at all. // A rate of 1 means increase 4 per cycle. // A rate of 2 means increase 2 per cycle. // A rate of 3 means increase 1 per cycle. // A rate of 4 means increase 1 every other cycle. // A rate of 5 means increase once every fourth cycle. // etc. // eighth, sixteenth, 32nd, 64th, 128th, 256th, 512th, 1024th, 2048th, 4096th, 8192th if(rate) { // TODO: don't throw away low two bits of the rate. switch(rate >> 2) { case 1: attenuation_ += 32; break; case 2: attenuation_ += 16; break; default: { const int sample_length = 1 << ((rate >> 2) - 4); if(!(oscillator.counter & (sample_length - 1))) { attenuation_ += 8; } } break; } // Clamp to the proper range. attenuation_ = std::min(attenuation_, 511); } } }; } } #endif /* EnvelopeGenerator_h */ <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief VS1063 VLSI Audio Codec ドライバー @author 平松邦仁 ([email protected]) */ //=====================================================================// #include <cstdint> #include "G13/port.hpp" #include "common/csi_io.hpp" #include "common/delay.hpp" #include "common/format.hpp" #include "ff12a/src/ff.h" extern "C" { char sci_getch(void); uint16_t sci_length(); } namespace chip { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief VS1063 テンプレートクラス @param[in] CSI CSI(SPI) 制御クラス @param[in] SEL /xCS 制御クラス @param[in] DCS /xDCS 制御クラス @param[in] REQ DREQ 入力クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class CSI, class SEL, class DCS, class REQ> class VS1063 { CSI& csi_; uint8_t frame_; uint8_t buff_[256]; /// VS1063a コマンド表 enum class CMD { MODE, ///< モード制御 STATUS, ///< ステータス BASS, ///< 内臓の低音/高音強調 CLOCKF, ///< クロック周波数+逓倍器 DECODE_TIME, ///< 再生時間[秒] AUDATA, ///< 各種オーディオ・データ WRAM, ///< RAM リード/ライト WRAMADDR, ///< RAM リード/ライト・アドレス HDAT0, ///< ストリーム・ヘッダ・データ0 HDAT1, ///< ストリーム・ヘッダ・データ1 AIADDR, ///< アプリケーション開始アドレス VOL, ///< ボリューム制御 AICTRL0, ///< アプリケーション制御レジスタ0 AICTRL1, ///< アプリケーション制御レジスタ1 AICTRL2, ///< アプリケーション制御レジスタ2 AICTRL3 ///< アプリケーション制御レジスタ3 }; inline void sleep_() { asm("nop"); } inline bool get_status_() { return REQ::P(); } inline void wait_ready_() { while(REQ::P() == 0) sleep_(); } void write_(CMD cmd, uint16_t data) { wait_ready_(); SEL::P = 0; csi_.xchg(0x02); // Write command (0x02) csi_.xchg(static_cast<uint8_t>(cmd)); csi_.xchg(data >> 8); csi_.xchg(data & 0xff); SEL::P = 1; } uint16_t read_(CMD cmd) { wait_ready_(); uint16_t data; SEL::P = 0; csi_.xchg(0x03); // Read command (0x03) csi_.xchg(static_cast<uint8_t>(cmd)); data = static_cast<uint16_t>(CSI::xchg()) << 8; data |= csi_.xchg(); SEL::P = 1; return data; } bool probe_mp3_(FIL* fp) { UINT len; if(f_read(fp, buff_, 10, &len) != FR_OK) { return false; } if(len != 10) { return false; } if(buff_[0] == 'I' && buff_[1] == 'D' && buff_[2] == '3') ; else { return false; } // skip TAG uint32_t ofs = static_cast<uint32_t>(buff_[6]) << 21; ofs |= static_cast<uint32_t>(buff_[7]) << 14; ofs |= static_cast<uint32_t>(buff_[8]) << 7; ofs |= static_cast<uint32_t>(buff_[9]); f_lseek(fp, ofs); utils::format("Find ID3 tag skip: %d\n") % ofs; return true; } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// VS1063(CSI& csi) : csi_(csi), frame_(0) { } //-----------------------------------------------------------------// /*! @brief 開始(初期化) */ //-----------------------------------------------------------------// void start() { SEL::PM = 0; SEL::PU = 0; DCS::PM = 0; DCS::PU = 0; REQ::PM = 1; REQ::PU = 0; SEL::P = 1; // /xCS = H DCS::P = 1; // /xDCS = H uint8_t intr_level = 0; if(!csi_.start(500000, CSI::PHASE::TYPE4, intr_level)) { utils::format("CSI1 Start fail ! (Clock spped over range)\n"); return; } /// write_(CMD::MODE, 0x4840); write_(CMD::MODE, 0x4800); write_(CMD::VOL, 0x4040); // volume // write_(CMD::CLOCKF, 0x9800); write_(CMD::CLOCKF, 0x8BE8); // 12MHz OSC 補正 utils::delay::milli_second(10); if(!csi_.start(8000000, CSI::PHASE::TYPE4, intr_level)) { utils::format("CSI1 Start fail ! (Clock spped over range)\n"); return; } utils::delay::milli_second(10); set_volume(255); } //----------------------------------------------------------------// /*! @brief サービス */ //----------------------------------------------------------------// bool service(FIL* fp) { UINT len; if(f_read(fp, buff_, sizeof(buff_), &len) != FR_OK) { return false; } if(len == 0) return false; const uint8_t* p = buff_; while(len > 0) { while(get_status_() == 0) ; uint16_t l = 32; if(l > len) l = len; csi_.send(p, l); p += l; len -= l; } ++frame_; if(frame_ >= 40) { device::P4.B3 = !device::P4.B3(); frame_ = 0; } if(sci_length()) { auto ch = sci_getch(); if(ch == '>') { return false; } } return true; } //----------------------------------------------------------------// /*! @brief 再生 @param[in] fp ファイル・ディスクリプタ @return エラーなら「false」 */ //----------------------------------------------------------------// bool play(FIL* fp) { if(fp == nullptr) return false; // ファイル・フォーマットを確認 if(!probe_mp3_(fp)) { f_close(fp); return false; } { frame_ = 0; DCS::P = 0; while(service(fp)) { sleep_(); } DCS::P = 1; } f_close(fp); return true; } //----------------------------------------------------------------// /*! @brief ボリュームを設定 @param[in] ボリューム(255が最大、0が最小) */ //----------------------------------------------------------------// void set_volume(uint8_t vol) { vol ^= 0xff; write_(CMD::VOL, (vol << 8) | vol); } //----------------------------------------------------------------// /*! @brief ボリュームを取得 @return ボリューム(255が最大、0が最小) */ //----------------------------------------------------------------// uint8_t get_volume() { return (read_(CMD::VOL) & 255) ^ 0xff; } }; } <commit_msg>fix 12.288MHz<commit_after>#pragma once //=====================================================================// /*! @file @brief VS1063 VLSI Audio Codec ドライバー @author 平松邦仁 ([email protected]) */ //=====================================================================// #include <cstdint> #include "G13/port.hpp" #include "common/csi_io.hpp" #include "common/delay.hpp" #include "common/format.hpp" #include "ff12a/src/ff.h" extern "C" { char sci_getch(void); uint16_t sci_length(); } namespace chip { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief VS1063 テンプレートクラス @param[in] CSI CSI(SPI) 制御クラス @param[in] SEL /xCS 制御クラス @param[in] DCS /xDCS 制御クラス @param[in] REQ DREQ 入力クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class CSI, class SEL, class DCS, class REQ> class VS1063 { CSI& csi_; uint8_t frame_; uint8_t buff_[256]; /// VS1063a コマンド表 enum class CMD { MODE, ///< モード制御 STATUS, ///< ステータス BASS, ///< 内臓の低音/高音強調 CLOCKF, ///< クロック周波数+逓倍器 DECODE_TIME, ///< 再生時間[秒] AUDATA, ///< 各種オーディオ・データ WRAM, ///< RAM リード/ライト WRAMADDR, ///< RAM リード/ライト・アドレス HDAT0, ///< ストリーム・ヘッダ・データ0 HDAT1, ///< ストリーム・ヘッダ・データ1 AIADDR, ///< アプリケーション開始アドレス VOL, ///< ボリューム制御 AICTRL0, ///< アプリケーション制御レジスタ0 AICTRL1, ///< アプリケーション制御レジスタ1 AICTRL2, ///< アプリケーション制御レジスタ2 AICTRL3 ///< アプリケーション制御レジスタ3 }; inline void sleep_() { asm("nop"); } inline bool get_status_() { return REQ::P(); } inline void wait_ready_() { while(REQ::P() == 0) sleep_(); } void write_(CMD cmd, uint16_t data) { wait_ready_(); SEL::P = 0; csi_.xchg(0x02); // Write command (0x02) csi_.xchg(static_cast<uint8_t>(cmd)); csi_.xchg(data >> 8); csi_.xchg(data & 0xff); SEL::P = 1; } uint16_t read_(CMD cmd) { wait_ready_(); uint16_t data; SEL::P = 0; csi_.xchg(0x03); // Read command (0x03) csi_.xchg(static_cast<uint8_t>(cmd)); data = static_cast<uint16_t>(CSI::xchg()) << 8; data |= csi_.xchg(); SEL::P = 1; return data; } bool probe_mp3_(FIL* fp) { UINT len; if(f_read(fp, buff_, 10, &len) != FR_OK) { return false; } if(len != 10) { return false; } if(buff_[0] == 'I' && buff_[1] == 'D' && buff_[2] == '3') ; else { return false; } // skip TAG uint32_t ofs = static_cast<uint32_t>(buff_[6]) << 21; ofs |= static_cast<uint32_t>(buff_[7]) << 14; ofs |= static_cast<uint32_t>(buff_[8]) << 7; ofs |= static_cast<uint32_t>(buff_[9]); f_lseek(fp, ofs); utils::format("Find ID3 tag skip: %d\n") % ofs; return true; } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// VS1063(CSI& csi) : csi_(csi), frame_(0) { } //-----------------------------------------------------------------// /*! @brief 開始(初期化) */ //-----------------------------------------------------------------// void start() { SEL::PM = 0; SEL::PU = 0; DCS::PM = 0; DCS::PU = 0; REQ::PM = 1; REQ::PU = 0; SEL::P = 1; // /xCS = H DCS::P = 1; // /xDCS = H uint8_t intr_level = 0; if(!csi_.start(500000, CSI::PHASE::TYPE4, intr_level)) { utils::format("CSI1 Start fail ! (Clock spped over range)\n"); return; } /// write_(CMD::MODE, 0x4840); write_(CMD::MODE, 0x4800); write_(CMD::VOL, 0x4040); // volume write_(CMD::CLOCKF, 0x9800); // 12.288MHz // write_(CMD::CLOCKF, 0x8BE8); // 12MHz OSC 補正 utils::delay::milli_second(10); if(!csi_.start(8000000, CSI::PHASE::TYPE4, intr_level)) { utils::format("CSI1 Start fail ! (Clock spped over range)\n"); return; } utils::delay::milli_second(10); set_volume(255); } //----------------------------------------------------------------// /*! @brief サービス */ //----------------------------------------------------------------// bool service(FIL* fp) { UINT len; if(f_read(fp, buff_, sizeof(buff_), &len) != FR_OK) { return false; } if(len == 0) return false; const uint8_t* p = buff_; while(len > 0) { while(get_status_() == 0) ; uint16_t l = 32; if(l > len) l = len; csi_.send(p, l); p += l; len -= l; } ++frame_; if(frame_ >= 40) { device::P4.B3 = !device::P4.B3(); frame_ = 0; } if(sci_length()) { auto ch = sci_getch(); if(ch == '>') { return false; } } return true; } //----------------------------------------------------------------// /*! @brief 再生 @param[in] fp ファイル・ディスクリプタ @return エラーなら「false」 */ //----------------------------------------------------------------// bool play(FIL* fp) { if(fp == nullptr) return false; // ファイル・フォーマットを確認 if(!probe_mp3_(fp)) { f_close(fp); return false; } { frame_ = 0; DCS::P = 0; while(service(fp)) { sleep_(); } DCS::P = 1; } f_close(fp); return true; } //----------------------------------------------------------------// /*! @brief ボリュームを設定 @param[in] ボリューム(255が最大、0が最小) */ //----------------------------------------------------------------// void set_volume(uint8_t vol) { vol ^= 0xff; write_(CMD::VOL, (vol << 8) | vol); } //----------------------------------------------------------------// /*! @brief ボリュームを取得 @return ボリューム(255が最大、0が最小) */ //----------------------------------------------------------------// uint8_t get_volume() { return (read_(CMD::VOL) & 255) ^ 0xff; } }; } <|endoftext|>
<commit_before>/* * Copyright 2015 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/lib/cpp2/test/gen-cpp2/Raiser.h> #include <thrift/lib/cpp2/util/ScopedServerInterfaceThread.h> #include <gtest/gtest.h> using namespace std; using namespace folly; using namespace apache::thrift; using namespace apache::thrift::test; class lulz : public exception { public: explicit lulz(string message) noexcept : message_(move(message)) {} const char* what() const noexcept override { return message_.c_str(); } private: string message_; }; namespace { using AppExn = TApplicationException; class HandlerBase : public RaiserSvIf { public: explicit HandlerBase(string message) : message_(move(message)) {} virtual void go(unique_ptr<HandlerCallbackBase> cb) = 0; protected: const string& message() const { return message_; } lulz make_lulz() const { return lulz(message()); } Banal make_banal() const { return Banal(); } Fiery make_fiery() const { Fiery f; f.message = message(); return f; } template <class E> exception_ptr to_eptr(const E& e) { try { throw e; } catch (E&) { return current_exception(); } } void async_tm_doBland(unique_ptr<HandlerCallback<void>> cb) override { go(move(cb)); } void async_tm_doRaise(unique_ptr<HandlerCallback<void>> cb) override { go(move(cb)); } void async_tm_get200(unique_ptr<HandlerCallback<string>> cb) override { go(move(cb)); } void async_tm_get500(unique_ptr<HandlerCallback<string>> cb) override { go(move(cb)); } private: string message_; }; } class ThriftServerExceptionTest : public testing::Test { public: EventBase eb; template <typename T> struct action_traits_impl; template <typename C, typename A> struct action_traits_impl<void(C::*)(A&) const> { using arg_type = A; }; template <typename C, typename A> struct action_traits_impl<void(C::*)(A&)> { using arg_type = A; }; template <typename F> using action_traits = action_traits_impl<decltype(&F::operator())>; template <typename F> using arg = typename action_traits<F>::arg_type; template <class V, class F> bool exn(Future<V> fv, F&& f) { using E = typename std::decay<arg<F>>::type; exception_wrapper wrap = fv.waitVia(&eb).getTry().exception(); return wrap.with_exception<E>(move(f)); } }; TEST_F(ThriftServerExceptionTest, bland_with_exception_ptr) { struct Handler : public HandlerBase { explicit Handler(string message) : HandlerBase(move(message)) {} void go(unique_ptr<HandlerCallbackBase> cb) override { cb->exception(to_eptr(make_lulz())); } }; auto message = string{"rofl"}; auto handler = make_shared<Handler>(message); ScopedServerInterfaceThread runner(handler); auto client = runner.newClient<RaiserAsyncClient>(&eb); auto lulz_w = sformat("lulz: {}", message); EXPECT_TRUE(exn(client->future_doBland(), [&](const AppExn& e) { EXPECT_EQ(AppExn::TApplicationExceptionType::UNKNOWN, e.getType()); EXPECT_EQ(lulz_w, string(e.what())); })); EXPECT_TRUE(exn(client->future_doRaise(), [&](const AppExn& e) { EXPECT_EQ(AppExn::TApplicationExceptionType::UNKNOWN, e.getType()); EXPECT_EQ(lulz_w, string(e.what())); })); EXPECT_TRUE(exn(client->future_get200(), [&](const AppExn& e) { EXPECT_EQ(AppExn::TApplicationExceptionType::UNKNOWN, e.getType()); EXPECT_EQ(lulz_w, string(e.what())); })); EXPECT_TRUE(exn(client->future_get500(), [&](const AppExn& e) { EXPECT_EQ(AppExn::TApplicationExceptionType::UNKNOWN, e.getType()); EXPECT_EQ(lulz_w, string(e.what())); })); } TEST_F(ThriftServerExceptionTest, banal_with_exception_ptr) { struct Handler : public HandlerBase { explicit Handler(string message) : HandlerBase(move(message)) {} void go(unique_ptr<HandlerCallbackBase> cb) override { cb->exception(to_eptr(make_banal())); } }; auto message = string{"rofl"}; auto handler = make_shared<Handler>(message); ScopedServerInterfaceThread runner(handler); auto client = runner.newClient<RaiserAsyncClient>(&eb); auto banal_s = string{"apache::thrift::test::Banal"}; auto banal_w_guess = sformat("{0}: ::{0}", banal_s); auto banal_w_known = sformat(" ::{0}", banal_s); EXPECT_TRUE(exn(client->future_doBland(), [&](const AppExn& e) { EXPECT_EQ(banal_w_guess, string(e.what())); })); EXPECT_TRUE(exn(client->future_doRaise(), [&](const Banal& e) { EXPECT_EQ(banal_w_known, string(e.what())); })); EXPECT_TRUE(exn(client->future_get200(), [&](const AppExn& e) { EXPECT_EQ(banal_w_guess, string(e.what())); })); EXPECT_TRUE(exn(client->future_get500(), [&](const Banal& e) { EXPECT_EQ(banal_w_known, string(e.what())); })); } TEST_F(ThriftServerExceptionTest, fiery_with_exception_ptr) { struct Handler : public HandlerBase { explicit Handler(string message) : HandlerBase(move(message)) {} void go(unique_ptr<HandlerCallbackBase> cb) override { cb->exception(to_eptr(make_fiery())); } }; auto message = string{"rofl"}; auto handler = make_shared<Handler>(message); ScopedServerInterfaceThread runner(handler); auto client = runner.newClient<RaiserAsyncClient>(&eb); auto fiery_s = string{"apache::thrift::test::Fiery"}; auto fiery_w_guess = sformat("{0}: ::{0}", fiery_s); auto fiery_w_known = sformat(" ::{0}", fiery_s); EXPECT_TRUE(exn(client->future_doBland(), [&](const AppExn& e) { EXPECT_EQ(fiery_w_guess, string(e.what())); })); EXPECT_TRUE(exn(client->future_doRaise(), [&](const Fiery& e) { EXPECT_EQ(fiery_w_known, string(e.what())); EXPECT_EQ(message, e.message); })); EXPECT_TRUE(exn(client->future_get200(), [&](const AppExn& e) { EXPECT_EQ(fiery_w_guess, string(e.what())); })); EXPECT_TRUE(exn(client->future_get500(), [&](const Fiery& e) { EXPECT_EQ(fiery_w_known, string(e.what())); EXPECT_EQ(message, e.message); })); } TEST_F(ThriftServerExceptionTest, bland_with_exception_wrapper) { struct Handler : public HandlerBase { explicit Handler(string message) : HandlerBase(move(message)) {} void go(unique_ptr<HandlerCallbackBase> cb) override { cb->exception(exception_wrapper(make_lulz())); } }; auto message = string{"rofl"}; auto handler = make_shared<Handler>(message); ScopedServerInterfaceThread runner(handler); auto client = runner.newClient<RaiserAsyncClient>(&eb); auto lulz_w = sformat("lulz: {}", message); EXPECT_TRUE(exn(client->future_doBland(), [&](const AppExn& e) { EXPECT_EQ(AppExn::TApplicationExceptionType::UNKNOWN, e.getType()); EXPECT_EQ(lulz_w, string(e.what())); })); EXPECT_TRUE(exn(client->future_doRaise(), [&](const AppExn& e) { EXPECT_EQ(AppExn::TApplicationExceptionType::UNKNOWN, e.getType()); EXPECT_EQ(lulz_w, string(e.what())); })); EXPECT_TRUE(exn(client->future_get200(), [&](const AppExn& e) { EXPECT_EQ(AppExn::TApplicationExceptionType::UNKNOWN, e.getType()); EXPECT_EQ(lulz_w, string(e.what())); })); EXPECT_TRUE(exn(client->future_get500(), [&](const AppExn& e) { EXPECT_EQ(AppExn::TApplicationExceptionType::UNKNOWN, e.getType()); EXPECT_EQ(lulz_w, string(e.what())); })); } TEST_F(ThriftServerExceptionTest, banal_with_exception_wrapper) { struct Handler : public HandlerBase { explicit Handler(string message) : HandlerBase(move(message)) {} void go(unique_ptr<HandlerCallbackBase> cb) override { cb->exception(exception_wrapper(make_banal())); } }; auto message = string{"rofl"}; auto handler = make_shared<Handler>(message); ScopedServerInterfaceThread runner(handler); auto client = runner.newClient<RaiserAsyncClient>(&eb); auto banal_s = string{"apache::thrift::test::Banal"}; auto banal_w_guess = sformat("{0}: ::{0}", banal_s); auto banal_w_known = sformat(" ::{0}", banal_s); EXPECT_TRUE(exn(client->future_doBland(), [&](const AppExn& e) { EXPECT_EQ(banal_w_guess, string(e.what())); })); EXPECT_TRUE(exn(client->future_doRaise(), [&](const Banal& e) { EXPECT_EQ(banal_w_known, string(e.what())); })); EXPECT_TRUE(exn(client->future_get200(), [&](const AppExn& e) { EXPECT_EQ(banal_w_guess, string(e.what())); })); EXPECT_TRUE(exn(client->future_get500(), [&](const Banal& e) { EXPECT_EQ(banal_w_known, string(e.what())); })); } TEST_F(ThriftServerExceptionTest, fiery_with_exception_wrapper) { struct Handler : public HandlerBase { explicit Handler(string message) : HandlerBase(move(message)) {} void go(unique_ptr<HandlerCallbackBase> cb) override { cb->exception(exception_wrapper(make_fiery())); } }; auto message = string{"rofl"}; auto handler = make_shared<Handler>(message); ScopedServerInterfaceThread runner(handler); auto client = runner.newClient<RaiserAsyncClient>(&eb); auto fiery_s = string{"apache::thrift::test::Fiery"}; auto fiery_w_guess = sformat("{0}: ::{0}", fiery_s); auto fiery_w_known = sformat(" ::{0}", fiery_s); EXPECT_TRUE(exn(client->future_doBland(), [&](const AppExn& e) { EXPECT_EQ(fiery_w_guess, string(e.what())); })); EXPECT_TRUE(exn(client->future_doRaise(), [&](const Fiery& e) { EXPECT_EQ(fiery_w_known, string(e.what())); EXPECT_EQ(message, e.message); })); EXPECT_TRUE(exn(client->future_get200(), [&](const AppExn& e) { EXPECT_EQ(fiery_w_guess, string(e.what())); })); EXPECT_TRUE(exn(client->future_get500(), [&](const Fiery& e) { EXPECT_EQ(fiery_w_known, string(e.what())); EXPECT_EQ(message, e.message); })); } <commit_msg>Refactor thrift/lib/cpp2/test/ThriftServerExceptionTest.cpp.<commit_after>/* * Copyright 2015 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/lib/cpp2/test/gen-cpp2/Raiser.h> #include <thrift/lib/cpp2/util/ScopedServerInterfaceThread.h> #include <gtest/gtest.h> using namespace std; using namespace folly; using namespace apache::thrift; using namespace apache::thrift::test; class lulz : public exception { public: explicit lulz(string message) noexcept : message_(move(message)) {} const char* what() const noexcept override { return message_.c_str(); } private: string message_; }; namespace { using AppExn = TApplicationException; class RaiserHandler : public RaiserSvIf { public: explicit RaiserHandler(function<exception_ptr()> go) : go_(wrap(move(go))) {} explicit RaiserHandler(function<exception_wrapper()> go) : go_(wrap(move(go))) {} protected: void async_tm_doBland(unique_ptr<HandlerCallback<void>> cb) override { go_(move(cb)); } void async_tm_doRaise(unique_ptr<HandlerCallback<void>> cb) override { go_(move(cb)); } void async_tm_get200(unique_ptr<HandlerCallback<string>> cb) override { go_(move(cb)); } void async_tm_get500(unique_ptr<HandlerCallback<string>> cb) override { go_(move(cb)); } template <typename E> function<void(unique_ptr<HandlerCallbackBase>)> wrap(E e) { auto em = makeMoveWrapper(move(e)); return [=](unique_ptr<HandlerCallbackBase> cb) { cb->exception((*em)()); }; } private: function<void(unique_ptr<HandlerCallbackBase>)> go_; }; } class ThriftServerExceptionTest : public testing::Test { public: EventBase eb; string message { "rofl" }; template <class E> exception_ptr to_eptr(const E& e) { try { throw e; } catch (E&) { return current_exception(); } } template <class E> exception_wrapper to_wrap(const E& e) { return exception_wrapper(e); // just an alias } lulz make_lulz() const { return lulz(message); } Banal make_banal() const { return Banal(); } Fiery make_fiery() const { Fiery f; f.message = message; return f; } template <typename T> struct action_traits_impl; template <typename C, typename A> struct action_traits_impl<void(C::*)(A&) const> { using arg_type = A; }; template <typename C, typename A> struct action_traits_impl<void(C::*)(A&)> { using arg_type = A; }; template <typename F> using action_traits = action_traits_impl<decltype(&F::operator())>; template <typename F> using arg = typename action_traits<F>::arg_type; template <class V, class F> bool exn(Future<V> fv, F&& f) { using E = typename std::decay<arg<F>>::type; exception_wrapper wrap = fv.waitVia(&eb).getTry().exception(); return wrap.with_exception<E>(move(f)); } }; TEST_F(ThriftServerExceptionTest, bland_with_exception_ptr) { auto go = [&] { return to_eptr(make_lulz()); }; auto handler = make_shared<RaiserHandler>(go); ScopedServerInterfaceThread runner(handler); auto client = runner.newClient<RaiserAsyncClient>(&eb); auto lulz_w = sformat("lulz: {}", message); EXPECT_TRUE(exn(client->future_doBland(), [&](const AppExn& e) { EXPECT_EQ(AppExn::TApplicationExceptionType::UNKNOWN, e.getType()); EXPECT_EQ(lulz_w, string(e.what())); })); EXPECT_TRUE(exn(client->future_doRaise(), [&](const AppExn& e) { EXPECT_EQ(AppExn::TApplicationExceptionType::UNKNOWN, e.getType()); EXPECT_EQ(lulz_w, string(e.what())); })); EXPECT_TRUE(exn(client->future_get200(), [&](const AppExn& e) { EXPECT_EQ(AppExn::TApplicationExceptionType::UNKNOWN, e.getType()); EXPECT_EQ(lulz_w, string(e.what())); })); EXPECT_TRUE(exn(client->future_get500(), [&](const AppExn& e) { EXPECT_EQ(AppExn::TApplicationExceptionType::UNKNOWN, e.getType()); EXPECT_EQ(lulz_w, string(e.what())); })); } TEST_F(ThriftServerExceptionTest, banal_with_exception_ptr) { auto go = [&] { return to_eptr(make_banal()); }; auto handler = make_shared<RaiserHandler>(go); ScopedServerInterfaceThread runner(handler); auto client = runner.newClient<RaiserAsyncClient>(&eb); auto banal_s = string{"apache::thrift::test::Banal"}; auto banal_w_guess = sformat("{0}: ::{0}", banal_s); auto banal_w_known = sformat(" ::{0}", banal_s); EXPECT_TRUE(exn(client->future_doBland(), [&](const AppExn& e) { EXPECT_EQ(banal_w_guess, string(e.what())); })); EXPECT_TRUE(exn(client->future_doRaise(), [&](const Banal& e) { EXPECT_EQ(banal_w_known, string(e.what())); })); EXPECT_TRUE(exn(client->future_get200(), [&](const AppExn& e) { EXPECT_EQ(banal_w_guess, string(e.what())); })); EXPECT_TRUE(exn(client->future_get500(), [&](const Banal& e) { EXPECT_EQ(banal_w_known, string(e.what())); })); } TEST_F(ThriftServerExceptionTest, fiery_with_exception_ptr) { auto go = [&] { return to_eptr(make_fiery()); }; auto handler = make_shared<RaiserHandler>(go); ScopedServerInterfaceThread runner(handler); auto client = runner.newClient<RaiserAsyncClient>(&eb); auto fiery_s = string{"apache::thrift::test::Fiery"}; auto fiery_w_guess = sformat("{0}: ::{0}", fiery_s); auto fiery_w_known = sformat(" ::{0}", fiery_s); EXPECT_TRUE(exn(client->future_doBland(), [&](const AppExn& e) { EXPECT_EQ(fiery_w_guess, string(e.what())); })); EXPECT_TRUE(exn(client->future_doRaise(), [&](const Fiery& e) { EXPECT_EQ(fiery_w_known, string(e.what())); EXPECT_EQ(message, e.message); })); EXPECT_TRUE(exn(client->future_get200(), [&](const AppExn& e) { EXPECT_EQ(fiery_w_guess, string(e.what())); })); EXPECT_TRUE(exn(client->future_get500(), [&](const Fiery& e) { EXPECT_EQ(fiery_w_known, string(e.what())); EXPECT_EQ(message, e.message); })); } TEST_F(ThriftServerExceptionTest, bland_with_exception_wrapper) { auto go = [&] { return to_wrap(make_lulz()); }; auto handler = make_shared<RaiserHandler>(go); ScopedServerInterfaceThread runner(handler); auto client = runner.newClient<RaiserAsyncClient>(&eb); auto lulz_w = sformat("lulz: {}", message); EXPECT_TRUE(exn(client->future_doBland(), [&](const AppExn& e) { EXPECT_EQ(AppExn::TApplicationExceptionType::UNKNOWN, e.getType()); EXPECT_EQ(lulz_w, string(e.what())); })); EXPECT_TRUE(exn(client->future_doRaise(), [&](const AppExn& e) { EXPECT_EQ(AppExn::TApplicationExceptionType::UNKNOWN, e.getType()); EXPECT_EQ(lulz_w, string(e.what())); })); EXPECT_TRUE(exn(client->future_get200(), [&](const AppExn& e) { EXPECT_EQ(AppExn::TApplicationExceptionType::UNKNOWN, e.getType()); EXPECT_EQ(lulz_w, string(e.what())); })); EXPECT_TRUE(exn(client->future_get500(), [&](const AppExn& e) { EXPECT_EQ(AppExn::TApplicationExceptionType::UNKNOWN, e.getType()); EXPECT_EQ(lulz_w, string(e.what())); })); } TEST_F(ThriftServerExceptionTest, banal_with_exception_wrapper) { auto go = [&] { return to_wrap(make_banal()); }; auto handler = make_shared<RaiserHandler>(go); ScopedServerInterfaceThread runner(handler); auto client = runner.newClient<RaiserAsyncClient>(&eb); auto banal_s = string{"apache::thrift::test::Banal"}; auto banal_w_guess = sformat("{0}: ::{0}", banal_s); auto banal_w_known = sformat(" ::{0}", banal_s); EXPECT_TRUE(exn(client->future_doBland(), [&](const AppExn& e) { EXPECT_EQ(banal_w_guess, string(e.what())); })); EXPECT_TRUE(exn(client->future_doRaise(), [&](const Banal& e) { EXPECT_EQ(banal_w_known, string(e.what())); })); EXPECT_TRUE(exn(client->future_get200(), [&](const AppExn& e) { EXPECT_EQ(banal_w_guess, string(e.what())); })); EXPECT_TRUE(exn(client->future_get500(), [&](const Banal& e) { EXPECT_EQ(banal_w_known, string(e.what())); })); } TEST_F(ThriftServerExceptionTest, fiery_with_exception_wrapper) { auto go = [&] { return to_wrap(make_fiery()); }; auto handler = make_shared<RaiserHandler>(go); ScopedServerInterfaceThread runner(handler); auto client = runner.newClient<RaiserAsyncClient>(&eb); auto fiery_s = string{"apache::thrift::test::Fiery"}; auto fiery_w_guess = sformat("{0}: ::{0}", fiery_s); auto fiery_w_known = sformat(" ::{0}", fiery_s); EXPECT_TRUE(exn(client->future_doBland(), [&](const AppExn& e) { EXPECT_EQ(fiery_w_guess, string(e.what())); })); EXPECT_TRUE(exn(client->future_doRaise(), [&](const Fiery& e) { EXPECT_EQ(fiery_w_known, string(e.what())); EXPECT_EQ(message, e.message); })); EXPECT_TRUE(exn(client->future_get200(), [&](const AppExn& e) { EXPECT_EQ(fiery_w_guess, string(e.what())); })); EXPECT_TRUE(exn(client->future_get500(), [&](const Fiery& e) { EXPECT_EQ(fiery_w_known, string(e.what())); EXPECT_EQ(message, e.message); })); } <|endoftext|>
<commit_before>// This is free and unencumbered software released into the public domain. // For more information, please refer to <http://unlicense.org/> #include "sagtension/catenary_cable_unloader.h" CatenaryCableUnloader::CatenaryCableUnloader() { is_updated_strainer_ = false; strainer_.set_load_finish(0); } CatenaryCableUnloader::~CatenaryCableUnloader() { } double CatenaryCableUnloader::LengthUnloaded() const { // updates class if necessary if (IsUpdated() == false) { if (Update() == false) { return -999999; } } return strainer_.LengthFinish(); } bool CatenaryCableUnloader::Validate( const bool& is_included_warnings, std::list<std::string>* messages_error) const { bool is_valid = true; /// \todo implement this return is_valid; } CatenaryCable CatenaryCableUnloader::catenary_cable() const { return catenary_cable_; } void CatenaryCableUnloader::set_catenary_cable( const CatenaryCable& catenary_cable) { catenary_cable_ = catenary_cable; is_updated_strainer_ = false; } void CatenaryCableUnloader::set_state_unloaded( const CableState& state_unloaded) { strainer_.set_state_finish(state_unloaded); } CableState CatenaryCableUnloader::state_unloaded() const { return strainer_.state_finish(); } bool CatenaryCableUnloader::IsUpdated() const { if (is_updated_strainer_ == true) { return true; } else { return false; } } bool CatenaryCableUnloader::Update() const { // updates strainer if (is_updated_strainer_ == false) { is_updated_strainer_ = UpdateStrainer(); if (is_updated_strainer_ == false) { return false; } } // if it reaches this point, update was successful return true; } bool CatenaryCableUnloader::UpdateStrainer() const { strainer_.set_cable(catenary_cable_.cable()); strainer_.set_length_start(catenary_cable_.Length()); strainer_.set_load_start(catenary_cable_.TensionAverage()); strainer_.set_state_start(catenary_cable_.state()); return true; } <commit_msg>Added validation to CatenaryCableUnloader.<commit_after>// This is free and unencumbered software released into the public domain. // For more information, please refer to <http://unlicense.org/> #include "sagtension/catenary_cable_unloader.h" CatenaryCableUnloader::CatenaryCableUnloader() { is_updated_strainer_ = false; strainer_.set_load_finish(0); } CatenaryCableUnloader::~CatenaryCableUnloader() { } double CatenaryCableUnloader::LengthUnloaded() const { // updates class if necessary if (IsUpdated() == false) { if (Update() == false) { return -999999; } } return strainer_.LengthFinish(); } bool CatenaryCableUnloader::Validate( const bool& is_included_warnings, std::list<std::string>* messages_error) const { bool is_valid = true; // validates catenary cable if (catenary_cable_.Validate(is_included_warnings, messages_error) == false) { is_valid = false; } // further validates if no errors are present if (is_valid == true) { // validates if class updates if (Update() == false) { is_valid = false; if (messages_error != nullptr) { messages_error->push_back( "CATENARY CABLE UNLOADER - Error updating class"); } } // validates strainer if (strainer_.Validate(is_included_warnings, messages_error) == false) { is_valid = false; } } return is_valid; } CatenaryCable CatenaryCableUnloader::catenary_cable() const { return catenary_cable_; } void CatenaryCableUnloader::set_catenary_cable( const CatenaryCable& catenary_cable) { catenary_cable_ = catenary_cable; is_updated_strainer_ = false; } void CatenaryCableUnloader::set_state_unloaded( const CableState& state_unloaded) { strainer_.set_state_finish(state_unloaded); } CableState CatenaryCableUnloader::state_unloaded() const { return strainer_.state_finish(); } bool CatenaryCableUnloader::IsUpdated() const { if (is_updated_strainer_ == true) { return true; } else { return false; } } bool CatenaryCableUnloader::Update() const { // updates strainer if (is_updated_strainer_ == false) { is_updated_strainer_ = UpdateStrainer(); if (is_updated_strainer_ == false) { return false; } } // if it reaches this point, update was successful return true; } bool CatenaryCableUnloader::UpdateStrainer() const { strainer_.set_cable(catenary_cable_.cable()); strainer_.set_length_start(catenary_cable_.Length()); strainer_.set_load_start(catenary_cable_.TensionAverage()); strainer_.set_state_start(catenary_cable_.state()); return true; } <|endoftext|>
<commit_before>#pragma once #include "ksp_plugin/vessel.hpp" #include <vector> namespace principia { namespace ksp_plugin { inline Vessel::Vessel(not_null<Celestial const*> const parent) : body_(), parent_(parent) {} inline not_null<MasslessBody const*> Vessel::body() const { return &body_; } inline bool Vessel::is_synchronized() const { bool const synchronized = history_ != nullptr; if (synchronized) { CHECK(owned_prolongation_ == nullptr); } return synchronized; } inline bool Vessel::is_initialized() const { bool const initialized = prolongation_ != nullptr; if (!initialized) { CHECK(owned_prolongation_ == nullptr); } return initialized; } inline not_null<Celestial const*> Vessel::parent() const { return parent_; } inline void Vessel::set_parent(not_null<Celestial const*> const parent) { parent_ = parent; } inline DiscreteTrajectory<Barycentric> const& Vessel::history() const { CHECK(is_synchronized()); return *history_; } inline not_null<DiscreteTrajectory<Barycentric>*> Vessel::mutable_history() { CHECK(is_synchronized()); return history_.get(); } inline DiscreteTrajectory<Barycentric> const& Vessel::prolongation() const { CHECK(is_initialized()); return *prolongation_; } inline not_null<DiscreteTrajectory<Barycentric>*> Vessel::mutable_prolongation() { CHECK(is_initialized()); return prolongation_; } inline std::vector<not_null<DiscreteTrajectory<Barycentric>*>> const& Vessel::flight_plan() const { CHECK(is_initialized()); return flight_plan_; } inline bool Vessel::has_flight_plan() const { return !flight_plan_.empty(); } inline DiscreteTrajectory<Barycentric> const& Vessel::prediction() const { CHECK(has_prediction()); return *prediction_; } inline bool Vessel::has_prediction() const { return prediction_ != nullptr; } inline Vessel::Manœuvres const& Vessel::manœuvres() const { return manœuvres_; } inline not_null<Vessel::Manœuvres*> Vessel::mutable_manœuvres() { return &manœuvres_; } inline void Vessel::CreateProlongation( Instant const& time, DegreesOfFreedom<Barycentric> const& degrees_of_freedom) { CHECK(!is_synchronized()); CHECK(!is_initialized()); CHECK(owned_prolongation_ == nullptr); owned_prolongation_ = std::make_unique<DiscreteTrajectory<Barycentric>>(); owned_prolongation_->Append(time, degrees_of_freedom); prolongation_ = owned_prolongation_.get(); } inline void Vessel::CreateHistoryAndForkProlongation( Instant const& time, DegreesOfFreedom<Barycentric> const& degrees_of_freedom) { CHECK(!is_synchronized()); history_ = std::make_unique<DiscreteTrajectory<Barycentric>>(); history_->Append(time, degrees_of_freedom); prolongation_ = history_->NewForkWithCopy(time); owned_prolongation_.reset(); } inline void Vessel::ResetProlongation(Instant const& time) { CHECK(is_initialized()); CHECK(is_synchronized()); CHECK(owned_prolongation_ == nullptr); history_->DeleteFork(&prolongation_); prolongation_ = history_->NewForkWithCopy(time); } inline void Vessel::UpdateFlightPlan( not_null<Ephemeris<Barycentric>*> ephemeris, AdaptiveStepSizeIntegrator< Ephemeris<Barycentric>::NewtonianMotionEquation> const& integrator, Instant const& last_time, Length const& prediction_length_tolerance, Speed const& prediction_speed_tolerance, Length const& prolongation_length_tolerance, Speed const& prolongation_speed_tolerance) { if (!is_synchronized()) { return; } DeleteFlightPlan(); flight_plan_.emplace_back( mutable_history()->NewForkWithCopy(history().last().time())); // If prolongation has no additional points this will do nothing (although it // might warn). flight_plan_.back()->Append(prolongation().last().time(), prolongation().last().degrees_of_freedom()); for (auto const& manœuvre : manœuvres_) { not_null<DiscreteTrajectory<Barycentric>*> const coast_trajectory = flight_plan_.back(); ephemeris->FlowWithAdaptiveStep( coast_trajectory, Ephemeris<Barycentric>::kNoIntrinsicAcceleration, prediction_length_tolerance, prediction_speed_tolerance, integrator, manœuvre->initial_time()); flight_plan_.emplace_back( coast_trajectory->NewForkWithCopy(coast_trajectory->last().time())); not_null<DiscreteTrajectory<Barycentric>*> const burn_trajectory = flight_plan_.back(); ephemeris->FlowWithAdaptiveStep(burn_trajectory, manœuvre->acceleration(), prolongation_length_tolerance, prolongation_speed_tolerance, integrator, manœuvre->final_time()); flight_plan_.emplace_back( burn_trajectory->NewForkWithCopy(burn_trajectory->last().time())); } ephemeris->FlowWithAdaptiveStep( flight_plan_.back(), Ephemeris<Barycentric>::kNoIntrinsicAcceleration, prediction_length_tolerance, prediction_speed_tolerance, integrator, last_time); } inline void Vessel::DeleteFlightPlan() { if (has_flight_plan()) { DiscreteTrajectory<Barycentric>* flight_plan_root = flight_plan_.front(); flight_plan_.clear(); history_->DeleteFork(&flight_plan_root); } } inline void Vessel::UpdatePrediction( not_null<Ephemeris<Barycentric>*> ephemeris, AdaptiveStepSizeIntegrator< Ephemeris<Barycentric>::NewtonianMotionEquation> const& integrator, Instant const& last_time, Length const& prediction_length_tolerance, Speed const& prediction_speed_tolerance) { if (!is_synchronized()) { return; } DeletePrediction(); prediction_ = mutable_history()->NewForkWithCopy(history().last().time()); if (history().last().time() != prolongation().last().time()) { prediction_->Append(prolongation().last().time(), prolongation().last().degrees_of_freedom()); } ephemeris->FlowWithAdaptiveStep( prediction_, Ephemeris<Barycentric>::kNoIntrinsicAcceleration, prediction_length_tolerance, prediction_speed_tolerance, integrator, last_time); } inline void Vessel::DeletePrediction() { if (has_prediction()) { mutable_history()->DeleteFork(&prediction_); } } inline void Vessel::WriteToMessage( not_null<serialization::Vessel*> const message) const { CHECK(is_initialized()); body_.WriteToMessage(message->mutable_body()); if (is_synchronized()) { history_->WriteToMessage( message->mutable_history_and_prolongation()->mutable_history()); prolongation_->WritePointerToMessage( message->mutable_history_and_prolongation()->mutable_prolongation()); } else { owned_prolongation_->WriteToMessage(message->mutable_owned_prolongation()); } } inline not_null<std::unique_ptr<Vessel>> Vessel::ReadFromMessage( serialization::Vessel const& message, not_null<Celestial const*> const parent) { auto vessel = make_not_null_unique<Vessel>(parent); // NOTE(egg): for now we do not read the |MasslessBody| as it can contain no // information. if (message.has_history_and_prolongation()) { vessel->history_ = DiscreteTrajectory<Barycentric>::ReadFromMessage( message.history_and_prolongation().history()); vessel->prolongation_ = DiscreteTrajectory<Barycentric>::ReadPointerFromMessage( message.history_and_prolongation().prolongation(), vessel->history_.get()); } else if (message.has_owned_prolongation()) { vessel->owned_prolongation_ = DiscreteTrajectory<Barycentric>::ReadFromMessage( message.owned_prolongation()); vessel->prolongation_ = vessel->owned_prolongation_.get(); } else { LOG(FATAL) << "message does not represent an initialized Vessel"; base::noreturn(); } return vessel; } } // namespace ksp_plugin } // namespace principia <commit_msg>Fix clients.<commit_after>#pragma once #include "ksp_plugin/vessel.hpp" #include <vector> namespace principia { namespace ksp_plugin { inline Vessel::Vessel(not_null<Celestial const*> const parent) : body_(), parent_(parent) {} inline not_null<MasslessBody const*> Vessel::body() const { return &body_; } inline bool Vessel::is_synchronized() const { bool const synchronized = history_ != nullptr; if (synchronized) { CHECK(owned_prolongation_ == nullptr); } return synchronized; } inline bool Vessel::is_initialized() const { bool const initialized = prolongation_ != nullptr; if (!initialized) { CHECK(owned_prolongation_ == nullptr); } return initialized; } inline not_null<Celestial const*> Vessel::parent() const { return parent_; } inline void Vessel::set_parent(not_null<Celestial const*> const parent) { parent_ = parent; } inline DiscreteTrajectory<Barycentric> const& Vessel::history() const { CHECK(is_synchronized()); return *history_; } inline not_null<DiscreteTrajectory<Barycentric>*> Vessel::mutable_history() { CHECK(is_synchronized()); return history_.get(); } inline DiscreteTrajectory<Barycentric> const& Vessel::prolongation() const { CHECK(is_initialized()); return *prolongation_; } inline not_null<DiscreteTrajectory<Barycentric>*> Vessel::mutable_prolongation() { CHECK(is_initialized()); return prolongation_; } inline std::vector<not_null<DiscreteTrajectory<Barycentric>*>> const& Vessel::flight_plan() const { CHECK(is_initialized()); return flight_plan_; } inline bool Vessel::has_flight_plan() const { return !flight_plan_.empty(); } inline DiscreteTrajectory<Barycentric> const& Vessel::prediction() const { CHECK(has_prediction()); return *prediction_; } inline bool Vessel::has_prediction() const { return prediction_ != nullptr; } inline Vessel::Manœuvres const& Vessel::manœuvres() const { return manœuvres_; } inline not_null<Vessel::Manœuvres*> Vessel::mutable_manœuvres() { return &manœuvres_; } inline void Vessel::CreateProlongation( Instant const& time, DegreesOfFreedom<Barycentric> const& degrees_of_freedom) { CHECK(!is_synchronized()); CHECK(!is_initialized()); CHECK(owned_prolongation_ == nullptr); owned_prolongation_ = std::make_unique<DiscreteTrajectory<Barycentric>>(); owned_prolongation_->Append(time, degrees_of_freedom); prolongation_ = owned_prolongation_.get(); } inline void Vessel::CreateHistoryAndForkProlongation( Instant const& time, DegreesOfFreedom<Barycentric> const& degrees_of_freedom) { CHECK(!is_synchronized()); history_ = std::make_unique<DiscreteTrajectory<Barycentric>>(); history_->Append(time, degrees_of_freedom); prolongation_ = history_->NewForkWithCopy(time); owned_prolongation_.reset(); } inline void Vessel::ResetProlongation(Instant const& time) { CHECK(is_initialized()); CHECK(is_synchronized()); CHECK(owned_prolongation_ == nullptr); history_->DeleteFork(&prolongation_); prolongation_ = history_->NewForkWithCopy(time); } inline void Vessel::UpdateFlightPlan( not_null<Ephemeris<Barycentric>*> ephemeris, AdaptiveStepSizeIntegrator< Ephemeris<Barycentric>::NewtonianMotionEquation> const& integrator, Instant const& last_time, Length const& prediction_length_tolerance, Speed const& prediction_speed_tolerance, Length const& prolongation_length_tolerance, Speed const& prolongation_speed_tolerance) { if (!is_synchronized()) { return; } DeleteFlightPlan(); flight_plan_.emplace_back(mutable_history()->NewForkAtLast()); if (history().last().time() != prolongation().last().time()) { flight_plan_.back()->Append(prolongation().last().time(), prolongation().last().degrees_of_freedom()); } for (auto const& manœuvre : manœuvres_) { not_null<DiscreteTrajectory<Barycentric>*> const coast_trajectory = flight_plan_.back(); ephemeris->FlowWithAdaptiveStep( coast_trajectory, Ephemeris<Barycentric>::kNoIntrinsicAcceleration, prediction_length_tolerance, prediction_speed_tolerance, integrator, manœuvre->initial_time()); flight_plan_.emplace_back( coast_trajectory->NewForkWithCopy(coast_trajectory->last().time())); not_null<DiscreteTrajectory<Barycentric>*> const burn_trajectory = flight_plan_.back(); ephemeris->FlowWithAdaptiveStep(burn_trajectory, manœuvre->acceleration(), prolongation_length_tolerance, prolongation_speed_tolerance, integrator, manœuvre->final_time()); flight_plan_.emplace_back(burn_trajectory->NewForkAtLast()); } ephemeris->FlowWithAdaptiveStep( flight_plan_.back(), Ephemeris<Barycentric>::kNoIntrinsicAcceleration, prediction_length_tolerance, prediction_speed_tolerance, integrator, last_time); } inline void Vessel::DeleteFlightPlan() { if (has_flight_plan()) { DiscreteTrajectory<Barycentric>* flight_plan_root = flight_plan_.front(); flight_plan_.clear(); history_->DeleteFork(&flight_plan_root); } } inline void Vessel::UpdatePrediction( not_null<Ephemeris<Barycentric>*> ephemeris, AdaptiveStepSizeIntegrator< Ephemeris<Barycentric>::NewtonianMotionEquation> const& integrator, Instant const& last_time, Length const& prediction_length_tolerance, Speed const& prediction_speed_tolerance) { if (!is_synchronized()) { return; } DeletePrediction(); prediction_ = mutable_history()->NewForkAtLast(); if (history().last().time() != prolongation().last().time()) { prediction_->Append(prolongation().last().time(), prolongation().last().degrees_of_freedom()); } ephemeris->FlowWithAdaptiveStep( prediction_, Ephemeris<Barycentric>::kNoIntrinsicAcceleration, prediction_length_tolerance, prediction_speed_tolerance, integrator, last_time); } inline void Vessel::DeletePrediction() { if (has_prediction()) { mutable_history()->DeleteFork(&prediction_); } } inline void Vessel::WriteToMessage( not_null<serialization::Vessel*> const message) const { CHECK(is_initialized()); body_.WriteToMessage(message->mutable_body()); if (is_synchronized()) { history_->WriteToMessage( message->mutable_history_and_prolongation()->mutable_history()); prolongation_->WritePointerToMessage( message->mutable_history_and_prolongation()->mutable_prolongation()); } else { owned_prolongation_->WriteToMessage(message->mutable_owned_prolongation()); } } inline not_null<std::unique_ptr<Vessel>> Vessel::ReadFromMessage( serialization::Vessel const& message, not_null<Celestial const*> const parent) { auto vessel = make_not_null_unique<Vessel>(parent); // NOTE(egg): for now we do not read the |MasslessBody| as it can contain no // information. if (message.has_history_and_prolongation()) { vessel->history_ = DiscreteTrajectory<Barycentric>::ReadFromMessage( message.history_and_prolongation().history()); vessel->prolongation_ = DiscreteTrajectory<Barycentric>::ReadPointerFromMessage( message.history_and_prolongation().prolongation(), vessel->history_.get()); } else if (message.has_owned_prolongation()) { vessel->owned_prolongation_ = DiscreteTrajectory<Barycentric>::ReadFromMessage( message.owned_prolongation()); vessel->prolongation_ = vessel->owned_prolongation_.get(); } else { LOG(FATAL) << "message does not represent an initialized Vessel"; base::noreturn(); } return vessel; } } // namespace ksp_plugin } // namespace principia <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: transitiontools.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-17 08:42:55 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_slideshow.hxx" #include <transitiontools.hxx> #ifndef _BGFX_POINT_B2DPOINT_HXX #include <basegfx/point/b2dpoint.hxx> #endif #ifndef _BGFX_POLYGON_B2DPOLYGON_HXX #include <basegfx/polygon/b2dpolygon.hxx> #endif #ifndef _BGFX_POLYGON_B2DPOLYGONTOOLS_HXX #include <basegfx/polygon/b2dpolygontools.hxx> #endif #include "basegfx/matrix/b2dhommatrix.hxx" namespace presentation { namespace internal { // TODO(Q2): Move this to basegfx ::basegfx::B2DPolygon createUnitRect() { return ::basegfx::tools::createPolygonFromRect( ::basegfx::B2DRectangle(0.0,0.0, 1.0,1.0 ) ); } ::basegfx::B2DPolyPolygon flipOnYAxis( ::basegfx::B2DPolyPolygon const & polypoly ) { ::basegfx::B2DPolyPolygon res(polypoly); ::basegfx::B2DHomMatrix aTransform; aTransform.scale( -1.0, 1.0 ); aTransform.translate( 1.0, 0.0 ); res.transform( aTransform ); res.flip(); return res; } ::basegfx::B2DPolyPolygon flipOnXAxis( ::basegfx::B2DPolyPolygon const & polypoly ) { ::basegfx::B2DPolyPolygon res(polypoly); ::basegfx::B2DHomMatrix aTransform; aTransform.scale( 1.0, -1.0 ); aTransform.translate( 0.0, 1.0 ); res.transform( aTransform ); res.flip(); return res; } } } <commit_msg>INTEGRATION: CWS presfixes09 (1.3.18); FILE MERGED 2006/10/18 20:00:04 thb 1.3.18.4: RESYNC: (1.3-1.4); FILE MERGED 2006/04/24 13:25:35 thb 1.3.18.3: #i53194# Unified include statements (local headers always have double quotes; external headers angle brackets); reverted EventMultiplexer pause events to shared_ptr; removed EventMultiplexer::removeViewHandler(), since the handler is held weakly, anyway. 2006/03/24 18:23:27 thb 1.3.18.2: #i37778# Moved whole slideshow engine from namespace presentation (which conflicts with one of the UNO subnamespaces) to slideshow 2006/03/15 15:22:21 thb 1.3.18.1: #i49357# Removed external include guards from all non-export headers (and from the cxx files, anyway)<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: transitiontools.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kz $ $Date: 2006-12-13 15:48:02 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_slideshow.hxx" #include "transitiontools.hxx" #include <basegfx/point/b2dpoint.hxx> #include <basegfx/polygon/b2dpolygon.hxx> #include <basegfx/polygon/b2dpolygontools.hxx> #include <basegfx/matrix/b2dhommatrix.hxx> namespace slideshow { namespace internal { // TODO(Q2): Move this to basegfx ::basegfx::B2DPolygon createUnitRect() { return ::basegfx::tools::createPolygonFromRect( ::basegfx::B2DRectangle(0.0,0.0, 1.0,1.0 ) ); } ::basegfx::B2DPolyPolygon flipOnYAxis( ::basegfx::B2DPolyPolygon const & polypoly ) { ::basegfx::B2DPolyPolygon res(polypoly); ::basegfx::B2DHomMatrix aTransform; aTransform.scale( -1.0, 1.0 ); aTransform.translate( 1.0, 0.0 ); res.transform( aTransform ); res.flip(); return res; } ::basegfx::B2DPolyPolygon flipOnXAxis( ::basegfx::B2DPolyPolygon const & polypoly ) { ::basegfx::B2DPolyPolygon res(polypoly); ::basegfx::B2DHomMatrix aTransform; aTransform.scale( 1.0, -1.0 ); aTransform.translate( 0.0, 1.0 ); res.transform( aTransform ); res.flip(); return res; } } } <|endoftext|>
<commit_before>/* This file is part of the KDE libraries Copyright (C) 2003-2005 Hamish Rodda <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "smartrange.h" #include <QStack> #include "document.h" #include "view.h" #include "attribute.h" #include "rangefeedback.h" #include <kaction.h> #include <kdebug.h> using namespace KTextEditor; SmartRange::SmartRange(SmartCursor* start, SmartCursor* end, SmartRange * parent, InsertBehaviours insertBehaviour ) : Range(start, end) , m_attribute(0L) , m_parentRange(parent) , m_ownsAttribute(false) { setInsertBehaviour(insertBehaviour); if (m_parentRange) { m_parentRange->expandToRange(*this); m_parentRange->insertChildRange(this); } } SmartRange::~SmartRange( ) { deleteChildRanges(); setParentRange(0L); setAttribute(0L); /*if (!m_deleteCursors) { // Save from deletion in the parent m_start = 0L; m_end = 0L; }*/ } bool SmartRange::confineToRange(const Range& range) { if (!Range::confineToRange(range)) // Don't need to check if children should be confined, they already are return false; foreach (SmartRange* child, m_childRanges) child->confineToRange(*this); return true; } bool SmartRange::expandToRange(const Range& range) { if (!Range::expandToRange(range)) // Don't need to check if parents should be expanded, they already are return false; if (parentRange()) parentRange()->expandToRange(*this); return true; } void SmartRange::setRange(const Range& range) { if (range == *this) return; Range old = *this; Range::setRange(range); rangeChanged(0L, old); } const QList<SmartRange*>& SmartRange::childRanges() const { return m_childRanges; } SmartRange * SmartRange::childBefore( const SmartRange * range ) const { int index = m_childRanges.indexOf(const_cast<SmartRange*>(range)); if (index != -1 && --index > 0) return m_childRanges[index]; return 0L; } SmartRange * SmartRange::childAfter( const SmartRange * range ) const { int index = m_childRanges.indexOf(const_cast<SmartRange*>(range)); if (index != -1 && ++index < m_childRanges.count()) return m_childRanges[index]; return 0L; } void SmartRange::insertChildRange( SmartRange * newChild ) { Q_ASSERT(newChild->parentRange() == this); QMutableListIterator<SmartRange*> it = m_childRanges; it.toBack(); while (it.hasPrevious()) { if (it.peekPrevious()->end() <= newChild->start()) { it.insert(newChild); if (it.hasNext() && it.next()->start() < newChild->end()) it.next()->start() = newChild->end(); return; } else if (it.peekPrevious()->start() >= newChild->start()) { it.peekPrevious()->end() = newChild->start(); it.insert(newChild); return; } it.previous(); } m_childRanges.prepend(newChild); } void SmartRange::removeChildRange(SmartRange* newChild) { m_childRanges.remove(newChild); } SmartRange * SmartRange::mostSpecificRange( const Range & input ) const { if (!input.isValid()) return 0L; if (contains(input)) { foreach (SmartRange* r, m_childRanges) if (r->contains(input)) return r->mostSpecificRange(input); return const_cast<SmartRange*>(this); } else if (parentRange()) { return parentRange()->mostSpecificRange(input); } else { return 0L; } } SmartRange * SmartRange::firstRangeContaining( const Cursor & pos ) const { if (!pos.isValid()) return 0L; switch (positionRelativeToCursor(pos)) { case 0: if (parentRange() && parentRange()->contains(pos)) return parentRange()->firstRangeContaining(pos); return const_cast<SmartRange*>(this); case -1: if (!parentRange()) return 0L; if (!parentRange()->contains(pos)) return parentRange()->firstRangeContaining(pos); if (SmartRange* r = parentRange()->childAfter(this)) return r->firstRangeContaining(pos); return 0L; case 1: if (!parentRange()) return 0L; if (!parentRange()->contains(pos)) return parentRange()->firstRangeContaining(pos); if (const SmartRange* r = parentRange()->childBefore(this)) return r->firstRangeContaining(pos); return 0L; default: Q_ASSERT(false); return 0L; } } SmartRange * SmartRange::deepestRangeContaining( const Cursor & pos, QStack<SmartRange*>* rangesEntered, QStack<SmartRange*>* rangesExited ) const { if (!pos.isValid()) return 0L; return deepestRangeContainingInternal(pos, rangesEntered, rangesExited, true); } SmartRange * SmartRange::deepestRangeContainingInternal( const Cursor & pos, QStack<SmartRange*>* rangesEntered, QStack<SmartRange*>* rangesExited, bool first ) const { switch (positionRelativeToCursor(pos)) { case 0: if (!first && rangesEntered) rangesEntered->push(const_cast<SmartRange*>(this)); foreach (SmartRange* r, m_childRanges) if (r->contains(pos)) return r->deepestRangeContainingInternal(pos, rangesEntered, rangesExited); return const_cast<SmartRange*>(this); case -1: if (rangesExited) rangesExited->push(const_cast<SmartRange*>(this)); if (!parentRange()) return 0L; if (!parentRange()->contains(pos)) return parentRange()->deepestRangeContainingInternal(pos, rangesEntered, rangesExited); if (const SmartRange* r = parentRange()->childAfter(this)) return r->deepestRangeContainingInternal(pos, rangesEntered, rangesExited); return 0L; case 1: if (rangesExited) rangesExited->push(const_cast<SmartRange*>(this)); if (!parentRange()) return 0L; if (!parentRange()->contains(pos)) return parentRange()->deepestRangeContainingInternal(pos, rangesEntered, rangesExited); if (const SmartRange* r = parentRange()->childBefore(this)) return r->deepestRangeContainingInternal(pos, rangesEntered, rangesExited); return 0L; default: Q_ASSERT(false); return 0L; } } Document* SmartRange::document( ) const { return smartStart().document(); } void SmartRange::associateAction( KAction * action ) { m_associatedActions.append(action); bool enable = false; if (View* v = document()->activeView()) if (contains(v->cursorPosition())) enable = true; action->setEnabled(enable); if (m_associatedActions.count() == 1) checkFeedback(); } void SmartRange::dissociateAction( KAction * action ) { m_associatedActions.removeAll(action); if (!m_associatedActions.count()) checkFeedback(); } void KTextEditor::SmartRange::clearAssociatedActions( ) { m_associatedActions.clear(); checkFeedback(); } SmartRange::InsertBehaviours SmartRange::insertBehaviour( ) const { return (smartStart().moveOnInsert() ? DoNotExpand : ExpandLeft) | (smartEnd().moveOnInsert() ? ExpandRight : DoNotExpand); } void SmartRange::setInsertBehaviour(SmartRange::InsertBehaviours behaviour) { static_cast<SmartCursor*>(m_start)->setMoveOnInsert(behaviour & ExpandLeft); static_cast<SmartCursor*>(m_end)->setMoveOnInsert(behaviour & ExpandRight); } void SmartRange::clearChildRanges() { foreach (SmartRange* r, m_childRanges) r->removeText(); } void SmartRange::deleteChildRanges() { // FIXME: Probably more efficient to prevent them from unlinking themselves? qDeleteAll(m_childRanges); // i.e. this is probably already clear m_childRanges.clear(); } void KTextEditor::SmartRange::clearAndDeleteChildRanges( ) { // FIXME: Probably more efficient to prevent them from unlinking themselves? foreach (SmartRange* r, m_childRanges) r->removeText(); qDeleteAll(m_childRanges); // i.e. this is probably already clear m_childRanges.clear(); } void SmartRange::setParentRange( SmartRange * r ) { if (m_parentRange) m_parentRange->removeChildRange(this); m_parentRange = r; if (m_parentRange) m_parentRange->insertChildRange(this); } void SmartRange::setAttribute( Attribute * attribute, bool ownsAttribute ) { //if (m_attribute) //m_attribute->removeRange(this); if (m_ownsAttribute) delete m_attribute; m_attribute = attribute; m_ownsAttribute = ownsAttribute; //if (m_attribute) //m_attribute->addRange(this); } Attribute * SmartRange::attribute( ) const { return m_attribute; } QStringList SmartRange::text( bool block ) const { return document()->textLines(*this, block); } bool SmartRange::replaceText( const QStringList & text, bool block ) { return document()->replaceText(*this, text, block); } bool SmartRange::removeText( bool block ) { return document()->removeText(*this, block); } void SmartRange::rangeChanged( Cursor* c, const Range& from ) { Range::rangeChanged(c, from); // Decide whether the parent range has expanded or contracted, if there is one if (parentRange() && (start() < from.start() || end() > from.end())) parentRange()->expandToRange(*this); if (childRanges().count()) { SmartRange* r; QList<SmartRange*>::ConstIterator it; // Start has contracted - adjust from the start of the child ranges int i = 0; if (start() > from.start()) { for (; i < childRanges().count(); ++i) { r = childRanges().at(i); if (r->start() < start()) r->confineToRange(*this); else break; } } // End has contracted - adjust from the start of the child ranges, if they haven't already been adjusted above if (end() < from.end()) { for (int j = childRanges().count() - 1; j >= i; --j) { r = childRanges().at(j); if (r->end() > end()) r->confineToRange(*this); else break; } } } // SmartCursor and its subclasses take care of adjusting ranges if the tree structure is being used. if (hasNotifier() && notifier()->wantsDirectChanges()) { emit notifier()->positionChanged(this); emit notifier()->contentsChanged(this); if (start() == end()) emit notifier()->eliminated(this); } if (watcher() && watcher()->wantsDirectChanges()) { watcher()->positionChanged(this); notifier()->contentsChanged(this); if (start() == end()) notifier()->eliminated(this); } } bool KTextEditor::SmartRange::isSmartRange( ) const { return true; } SmartRange* KTextEditor::SmartRange::toSmartRange( ) const { return const_cast<SmartRange*>(this); } bool KTextEditor::SmartRange::hasParent( SmartRange * parent ) const { if (parentRange() == parent) return true; if (parentRange()) return parentRange()->hasParent(parent); return false; } // kate: space-indent on; indent-width 2; replace-tabs on; <commit_msg>Bug in insertChildRange - use peekNext instead of next Still haven't checked for correctness, but doesn't crash<commit_after>/* This file is part of the KDE libraries Copyright (C) 2003-2005 Hamish Rodda <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "smartrange.h" #include <QStack> #include "document.h" #include "view.h" #include "attribute.h" #include "rangefeedback.h" #include <kaction.h> #include <kdebug.h> using namespace KTextEditor; SmartRange::SmartRange(SmartCursor* start, SmartCursor* end, SmartRange * parent, InsertBehaviours insertBehaviour ) : Range(start, end) , m_attribute(0L) , m_parentRange(parent) , m_ownsAttribute(false) { setInsertBehaviour(insertBehaviour); if (m_parentRange) { m_parentRange->expandToRange(*this); m_parentRange->insertChildRange(this); } } SmartRange::~SmartRange( ) { deleteChildRanges(); setParentRange(0L); setAttribute(0L); /*if (!m_deleteCursors) { // Save from deletion in the parent m_start = 0L; m_end = 0L; }*/ } bool SmartRange::confineToRange(const Range& range) { if (!Range::confineToRange(range)) // Don't need to check if children should be confined, they already are return false; foreach (SmartRange* child, m_childRanges) child->confineToRange(*this); return true; } bool SmartRange::expandToRange(const Range& range) { if (!Range::expandToRange(range)) // Don't need to check if parents should be expanded, they already are return false; if (parentRange()) parentRange()->expandToRange(*this); return true; } void SmartRange::setRange(const Range& range) { if (range == *this) return; Range old = *this; Range::setRange(range); rangeChanged(0L, old); } const QList<SmartRange*>& SmartRange::childRanges() const { return m_childRanges; } SmartRange * SmartRange::childBefore( const SmartRange * range ) const { int index = m_childRanges.indexOf(const_cast<SmartRange*>(range)); if (index != -1 && --index > 0) return m_childRanges[index]; return 0L; } SmartRange * SmartRange::childAfter( const SmartRange * range ) const { int index = m_childRanges.indexOf(const_cast<SmartRange*>(range)); if (index != -1 && ++index < m_childRanges.count()) return m_childRanges[index]; return 0L; } void SmartRange::insertChildRange( SmartRange * newChild ) { Q_ASSERT(newChild->parentRange() == this); QMutableListIterator<SmartRange*> it = m_childRanges; it.toBack(); while (it.hasPrevious()) { if (it.peekPrevious()->end() <= newChild->start()) { it.insert(newChild); if (it.hasNext() && it.peekNext()->start() < newChild->end()) it.peekNext()->start() = newChild->end(); return; } else if (it.peekPrevious()->start() >= newChild->start()) { it.peekPrevious()->end() = newChild->start(); it.insert(newChild); return; } it.previous(); } m_childRanges.prepend(newChild); } void SmartRange::removeChildRange(SmartRange* newChild) { m_childRanges.remove(newChild); } SmartRange * SmartRange::mostSpecificRange( const Range & input ) const { if (!input.isValid()) return 0L; if (contains(input)) { foreach (SmartRange* r, m_childRanges) if (r->contains(input)) return r->mostSpecificRange(input); return const_cast<SmartRange*>(this); } else if (parentRange()) { return parentRange()->mostSpecificRange(input); } else { return 0L; } } SmartRange * SmartRange::firstRangeContaining( const Cursor & pos ) const { if (!pos.isValid()) return 0L; switch (positionRelativeToCursor(pos)) { case 0: if (parentRange() && parentRange()->contains(pos)) return parentRange()->firstRangeContaining(pos); return const_cast<SmartRange*>(this); case -1: if (!parentRange()) return 0L; if (!parentRange()->contains(pos)) return parentRange()->firstRangeContaining(pos); if (SmartRange* r = parentRange()->childAfter(this)) return r->firstRangeContaining(pos); return 0L; case 1: if (!parentRange()) return 0L; if (!parentRange()->contains(pos)) return parentRange()->firstRangeContaining(pos); if (const SmartRange* r = parentRange()->childBefore(this)) return r->firstRangeContaining(pos); return 0L; default: Q_ASSERT(false); return 0L; } } SmartRange * SmartRange::deepestRangeContaining( const Cursor & pos, QStack<SmartRange*>* rangesEntered, QStack<SmartRange*>* rangesExited ) const { if (!pos.isValid()) return 0L; return deepestRangeContainingInternal(pos, rangesEntered, rangesExited, true); } SmartRange * SmartRange::deepestRangeContainingInternal( const Cursor & pos, QStack<SmartRange*>* rangesEntered, QStack<SmartRange*>* rangesExited, bool first ) const { switch (positionRelativeToCursor(pos)) { case 0: if (!first && rangesEntered) rangesEntered->push(const_cast<SmartRange*>(this)); foreach (SmartRange* r, m_childRanges) if (r->contains(pos)) return r->deepestRangeContainingInternal(pos, rangesEntered, rangesExited); return const_cast<SmartRange*>(this); case -1: if (rangesExited) rangesExited->push(const_cast<SmartRange*>(this)); if (!parentRange()) return 0L; if (!parentRange()->contains(pos)) return parentRange()->deepestRangeContainingInternal(pos, rangesEntered, rangesExited); if (const SmartRange* r = parentRange()->childAfter(this)) return r->deepestRangeContainingInternal(pos, rangesEntered, rangesExited); return 0L; case 1: if (rangesExited) rangesExited->push(const_cast<SmartRange*>(this)); if (!parentRange()) return 0L; if (!parentRange()->contains(pos)) return parentRange()->deepestRangeContainingInternal(pos, rangesEntered, rangesExited); if (const SmartRange* r = parentRange()->childBefore(this)) return r->deepestRangeContainingInternal(pos, rangesEntered, rangesExited); return 0L; default: Q_ASSERT(false); return 0L; } } Document* SmartRange::document( ) const { return smartStart().document(); } void SmartRange::associateAction( KAction * action ) { m_associatedActions.append(action); bool enable = false; if (View* v = document()->activeView()) if (contains(v->cursorPosition())) enable = true; action->setEnabled(enable); if (m_associatedActions.count() == 1) checkFeedback(); } void SmartRange::dissociateAction( KAction * action ) { m_associatedActions.removeAll(action); if (!m_associatedActions.count()) checkFeedback(); } void KTextEditor::SmartRange::clearAssociatedActions( ) { m_associatedActions.clear(); checkFeedback(); } SmartRange::InsertBehaviours SmartRange::insertBehaviour( ) const { return (smartStart().moveOnInsert() ? DoNotExpand : ExpandLeft) | (smartEnd().moveOnInsert() ? ExpandRight : DoNotExpand); } void SmartRange::setInsertBehaviour(SmartRange::InsertBehaviours behaviour) { static_cast<SmartCursor*>(m_start)->setMoveOnInsert(behaviour & ExpandLeft); static_cast<SmartCursor*>(m_end)->setMoveOnInsert(behaviour & ExpandRight); } void SmartRange::clearChildRanges() { foreach (SmartRange* r, m_childRanges) r->removeText(); } void SmartRange::deleteChildRanges() { // FIXME: Probably more efficient to prevent them from unlinking themselves? qDeleteAll(m_childRanges); // i.e. this is probably already clear m_childRanges.clear(); } void KTextEditor::SmartRange::clearAndDeleteChildRanges( ) { // FIXME: Probably more efficient to prevent them from unlinking themselves? foreach (SmartRange* r, m_childRanges) r->removeText(); qDeleteAll(m_childRanges); // i.e. this is probably already clear m_childRanges.clear(); } void SmartRange::setParentRange( SmartRange * r ) { if (m_parentRange) m_parentRange->removeChildRange(this); m_parentRange = r; if (m_parentRange) m_parentRange->insertChildRange(this); } void SmartRange::setAttribute( Attribute * attribute, bool ownsAttribute ) { //if (m_attribute) //m_attribute->removeRange(this); if (m_ownsAttribute) delete m_attribute; m_attribute = attribute; m_ownsAttribute = ownsAttribute; //if (m_attribute) //m_attribute->addRange(this); } Attribute * SmartRange::attribute( ) const { return m_attribute; } QStringList SmartRange::text( bool block ) const { return document()->textLines(*this, block); } bool SmartRange::replaceText( const QStringList & text, bool block ) { return document()->replaceText(*this, text, block); } bool SmartRange::removeText( bool block ) { return document()->removeText(*this, block); } void SmartRange::rangeChanged( Cursor* c, const Range& from ) { Range::rangeChanged(c, from); // Decide whether the parent range has expanded or contracted, if there is one if (parentRange() && (start() < from.start() || end() > from.end())) parentRange()->expandToRange(*this); if (childRanges().count()) { SmartRange* r; QList<SmartRange*>::ConstIterator it; // Start has contracted - adjust from the start of the child ranges int i = 0; if (start() > from.start()) { for (; i < childRanges().count(); ++i) { r = childRanges().at(i); if (r->start() < start()) r->confineToRange(*this); else break; } } // End has contracted - adjust from the start of the child ranges, if they haven't already been adjusted above if (end() < from.end()) { for (int j = childRanges().count() - 1; j >= i; --j) { r = childRanges().at(j); if (r->end() > end()) r->confineToRange(*this); else break; } } } // SmartCursor and its subclasses take care of adjusting ranges if the tree structure is being used. if (hasNotifier() && notifier()->wantsDirectChanges()) { emit notifier()->positionChanged(this); emit notifier()->contentsChanged(this); if (start() == end()) emit notifier()->eliminated(this); } if (watcher() && watcher()->wantsDirectChanges()) { watcher()->positionChanged(this); notifier()->contentsChanged(this); if (start() == end()) notifier()->eliminated(this); } } bool KTextEditor::SmartRange::isSmartRange( ) const { return true; } SmartRange* KTextEditor::SmartRange::toSmartRange( ) const { return const_cast<SmartRange*>(this); } bool KTextEditor::SmartRange::hasParent( SmartRange * parent ) const { if (parentRange() == parent) return true; if (parentRange()) return parentRange()->hasParent(parent); return false; } // kate: space-indent on; indent-width 2; replace-tabs on; <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "after_streaming_fixture.h" class VolumeTest : public AfterStreamingFixture { }; TEST_F(VolumeTest, DefaultSpeakerVolumeIsAtMost255) { unsigned int volume = 1000; EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume)); EXPECT_LE(volume, 255u); } TEST_F(VolumeTest, ManualSetVolumeWorks) { unsigned int original_volume = 0; EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(original_volume)); Sleep(1000); TEST_LOG("Setting speaker volume to 0 out of 255.\n"); EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(0)); Sleep(1000); TEST_LOG("Setting speaker volume to 100 out of 255.\n"); EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(100)); Sleep(1000); // Set the volume to 255 very briefly so we don't blast the poor user // listening to this. This is just to test the call succeeds. EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(255)); TEST_LOG("Setting speaker volume to the original %d out of 255.\n", original_volume); EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(original_volume)); Sleep(1000); } #if !defined(MAC_IPHONE) TEST_F(VolumeTest, DefaultMicrophoneVolumeIsAtMost255) { unsigned int volume = 1000; EXPECT_EQ(0, voe_volume_control_->GetMicVolume(volume)); EXPECT_LE(volume, 255u); } TEST_F(VolumeTest, ManualRequiresMicrophoneCanSetMicrophoneVolumeWithAcgOff) { SwitchToManualMicrophone(); EXPECT_EQ(0, voe_apm_->SetAgcStatus(false)); unsigned int original_volume = 0; EXPECT_EQ(0, voe_volume_control_->GetMicVolume(original_volume)); TEST_LOG("Setting microphone volume to 0.\n"); EXPECT_EQ(0, voe_volume_control_->SetMicVolume(channel_)); Sleep(1000); TEST_LOG("Setting microphone volume to 255.\n"); EXPECT_EQ(0, voe_volume_control_->SetMicVolume(255)); Sleep(1000); TEST_LOG("Setting microphone volume back to saved value.\n"); EXPECT_EQ(0, voe_volume_control_->SetMicVolume(original_volume)); Sleep(1000); } TEST_F(VolumeTest, ChannelScalingIsOneByDefault) { float scaling = -1.0f; EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling( channel_, scaling)); EXPECT_FLOAT_EQ(1.0f, scaling); } TEST_F(VolumeTest, ManualCanSetChannelScaling) { EXPECT_EQ(0, voe_volume_control_->SetChannelOutputVolumeScaling( channel_, 0.1f)); float scaling = 1.0f; EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling( channel_, scaling)); EXPECT_FLOAT_EQ(0.1f, scaling); TEST_LOG("Channel scaling set to 0.1: audio should be barely audible.\n"); Sleep(2000); } #endif // !MAC_IPHONE #if !defined(WEBRTC_ANDROID) && !defined(MAC_IPHONE) TEST_F(VolumeTest, InputMutingIsNotEnabledByDefault) { bool is_muted = true; EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted)); EXPECT_FALSE(is_muted); } TEST_F(VolumeTest, ManualInputMutingMutesMicrophone) { SwitchToManualMicrophone(); // Enable muting. EXPECT_EQ(0, voe_volume_control_->SetInputMute(channel_, true)); bool is_muted = false; EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted)); EXPECT_TRUE(is_muted); TEST_LOG("Muted: talk into microphone and verify you can't hear yourself.\n"); Sleep(2000); // Test that we can disable muting. EXPECT_EQ(0, voe_volume_control_->SetInputMute(channel_, false)); EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted)); EXPECT_FALSE(is_muted); TEST_LOG("Unmuted: talk into microphone and verify you can hear yourself.\n"); Sleep(2000); } TEST_F(VolumeTest, SystemInputMutingIsNotEnabledByDefault) { bool is_muted = true; EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted)); EXPECT_FALSE(is_muted); } TEST_F(VolumeTest, ManualSystemInputMutingMutesMicrophone) { SwitchToManualMicrophone(); // Enable system input muting. EXPECT_EQ(0, voe_volume_control_->SetSystemInputMute(true)); bool is_muted = false; EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted)); EXPECT_TRUE(is_muted); TEST_LOG("Muted: talk into microphone and verify you can't hear yourself.\n"); Sleep(2000); // Test that we can disable system input muting. EXPECT_EQ(0, voe_volume_control_->SetSystemInputMute(false)); EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted)); EXPECT_FALSE(is_muted); TEST_LOG("Unmuted: talk into microphone and verify you can hear yourself.\n"); Sleep(2000); } TEST_F(VolumeTest, SystemOutputMutingIsNotEnabledByDefault) { bool is_muted = true; EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted)); EXPECT_FALSE(is_muted); } TEST_F(VolumeTest, ManualSystemOutputMutingMutesOutput) { // Enable muting. EXPECT_EQ(0, voe_volume_control_->SetSystemOutputMute(true)); bool is_muted = false; EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted)); EXPECT_TRUE(is_muted); TEST_LOG("Muted: you should hear no audio.\n"); Sleep(2000); // Test that we can disable muting. EXPECT_EQ(0, voe_volume_control_->SetSystemOutputMute(false)); EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted)); EXPECT_FALSE(is_muted); TEST_LOG("Unmuted: you should hear audio.\n"); Sleep(2000); } TEST_F(VolumeTest, ManualTestInputAndOutputLevels) { SwitchToManualMicrophone(); TEST_LOG("Speak and verify that the following levels look right:\n"); for (int i = 0; i < 5; i++) { Sleep(1000); unsigned int input_level = 0; unsigned int output_level = 0; unsigned int input_level_full_range = 0; unsigned int output_level_full_range = 0; EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevel( input_level)); EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevel( channel_, output_level)); EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevelFullRange( input_level_full_range)); EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevelFullRange( channel_, output_level_full_range)); TEST_LOG(" warped levels (0-9) : in=%5d, out=%5d\n", input_level, output_level); TEST_LOG(" linear levels (0-32768): in=%5d, out=%5d\n", input_level_full_range, output_level_full_range); } } TEST_F(VolumeTest, ChannelsAreNotPannedByDefault) { float left = -1.0; float right = -1.0; EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right)); EXPECT_FLOAT_EQ(1.0, left); EXPECT_FLOAT_EQ(1.0, right); } TEST_F(VolumeTest, ManualTestChannelPanning) { TEST_LOG("Panning left.\n"); EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.8f, 0.1f)); Sleep(1000); TEST_LOG("Back to center.\n"); EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 1.0f, 1.0f)); Sleep(1000); TEST_LOG("Panning right.\n"); EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.1f, 0.8f)); Sleep(1000); // To finish, verify that the getter works. float left = 0.0f; float right = 0.0f; EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right)); EXPECT_FLOAT_EQ(0.1f, left); EXPECT_FLOAT_EQ(0.8f, right); } #endif // !WEBRTC_ANDROID && !MAC_IPHONE <commit_msg>Enabled the volume tests we believe are nonflaky and the vie_auto_test extended tests.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "after_streaming_fixture.h" class VolumeTest : public AfterStreamingFixture { }; TEST_F(VolumeTest, DefaultSpeakerVolumeIsAtMost255) { unsigned int volume = 1000; EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume)); EXPECT_LE(volume, 255u); } TEST_F(VolumeTest, ManualSetVolumeWorks) { unsigned int original_volume = 0; EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(original_volume)); Sleep(1000); TEST_LOG("Setting speaker volume to 0 out of 255.\n"); EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(0)); Sleep(1000); TEST_LOG("Setting speaker volume to 100 out of 255.\n"); EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(100)); Sleep(1000); // Set the volume to 255 very briefly so we don't blast the poor user // listening to this. This is just to test the call succeeds. EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(255)); TEST_LOG("Setting speaker volume to the original %d out of 255.\n", original_volume); EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(original_volume)); Sleep(1000); } #if !defined(MAC_IPHONE) // NOTE(phoglund): This test is flaky because of how the OS works, and is hence // disabled by default. TEST_F(VolumeTest, DISABLED_DefaultMicrophoneVolumeIsAtMost255) { unsigned int volume = 1000; EXPECT_EQ(0, voe_volume_control_->GetMicVolume(volume)); EXPECT_LE(volume, 255u); } TEST_F(VolumeTest, ManualRequiresMicrophoneCanSetMicrophoneVolumeWithAcgOff) { SwitchToManualMicrophone(); EXPECT_EQ(0, voe_apm_->SetAgcStatus(false)); unsigned int original_volume = 0; EXPECT_EQ(0, voe_volume_control_->GetMicVolume(original_volume)); TEST_LOG("Setting microphone volume to 0.\n"); EXPECT_EQ(0, voe_volume_control_->SetMicVolume(channel_)); Sleep(1000); TEST_LOG("Setting microphone volume to 255.\n"); EXPECT_EQ(0, voe_volume_control_->SetMicVolume(255)); Sleep(1000); TEST_LOG("Setting microphone volume back to saved value.\n"); EXPECT_EQ(0, voe_volume_control_->SetMicVolume(original_volume)); Sleep(1000); } TEST_F(VolumeTest, ChannelScalingIsOneByDefault) { float scaling = -1.0f; EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling( channel_, scaling)); EXPECT_FLOAT_EQ(1.0f, scaling); } TEST_F(VolumeTest, ManualCanSetChannelScaling) { EXPECT_EQ(0, voe_volume_control_->SetChannelOutputVolumeScaling( channel_, 0.1f)); float scaling = 1.0f; EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling( channel_, scaling)); EXPECT_FLOAT_EQ(0.1f, scaling); TEST_LOG("Channel scaling set to 0.1: audio should be barely audible.\n"); Sleep(2000); } #endif // !MAC_IPHONE #if !defined(WEBRTC_ANDROID) && !defined(MAC_IPHONE) TEST_F(VolumeTest, InputMutingIsNotEnabledByDefault) { bool is_muted = true; EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted)); EXPECT_FALSE(is_muted); } TEST_F(VolumeTest, ManualInputMutingMutesMicrophone) { SwitchToManualMicrophone(); // Enable muting. EXPECT_EQ(0, voe_volume_control_->SetInputMute(channel_, true)); bool is_muted = false; EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted)); EXPECT_TRUE(is_muted); TEST_LOG("Muted: talk into microphone and verify you can't hear yourself.\n"); Sleep(2000); // Test that we can disable muting. EXPECT_EQ(0, voe_volume_control_->SetInputMute(channel_, false)); EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted)); EXPECT_FALSE(is_muted); TEST_LOG("Unmuted: talk into microphone and verify you can hear yourself.\n"); Sleep(2000); } // NOTE(phoglund): This test is flaky because of how the OS works, and is hence // disabled by default. TEST_F(VolumeTest, DISABLED_SystemInputMutingIsNotEnabledByDefault) { bool is_muted = true; EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted)); EXPECT_FALSE(is_muted); } TEST_F(VolumeTest, ManualSystemInputMutingMutesMicrophone) { SwitchToManualMicrophone(); // Enable system input muting. EXPECT_EQ(0, voe_volume_control_->SetSystemInputMute(true)); bool is_muted = false; EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted)); EXPECT_TRUE(is_muted); TEST_LOG("Muted: talk into microphone and verify you can't hear yourself.\n"); Sleep(2000); // Test that we can disable system input muting. EXPECT_EQ(0, voe_volume_control_->SetSystemInputMute(false)); EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted)); EXPECT_FALSE(is_muted); TEST_LOG("Unmuted: talk into microphone and verify you can hear yourself.\n"); Sleep(2000); } TEST_F(VolumeTest, SystemOutputMutingIsNotEnabledByDefault) { bool is_muted = true; EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted)); EXPECT_FALSE(is_muted); } TEST_F(VolumeTest, ManualSystemOutputMutingMutesOutput) { // Enable muting. EXPECT_EQ(0, voe_volume_control_->SetSystemOutputMute(true)); bool is_muted = false; EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted)); EXPECT_TRUE(is_muted); TEST_LOG("Muted: you should hear no audio.\n"); Sleep(2000); // Test that we can disable muting. EXPECT_EQ(0, voe_volume_control_->SetSystemOutputMute(false)); EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted)); EXPECT_FALSE(is_muted); TEST_LOG("Unmuted: you should hear audio.\n"); Sleep(2000); } TEST_F(VolumeTest, ManualTestInputAndOutputLevels) { SwitchToManualMicrophone(); TEST_LOG("Speak and verify that the following levels look right:\n"); for (int i = 0; i < 5; i++) { Sleep(1000); unsigned int input_level = 0; unsigned int output_level = 0; unsigned int input_level_full_range = 0; unsigned int output_level_full_range = 0; EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevel( input_level)); EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevel( channel_, output_level)); EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevelFullRange( input_level_full_range)); EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevelFullRange( channel_, output_level_full_range)); TEST_LOG(" warped levels (0-9) : in=%5d, out=%5d\n", input_level, output_level); TEST_LOG(" linear levels (0-32768): in=%5d, out=%5d\n", input_level_full_range, output_level_full_range); } } TEST_F(VolumeTest, ChannelsAreNotPannedByDefault) { float left = -1.0; float right = -1.0; EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right)); EXPECT_FLOAT_EQ(1.0, left); EXPECT_FLOAT_EQ(1.0, right); } TEST_F(VolumeTest, ManualTestChannelPanning) { TEST_LOG("Panning left.\n"); EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.8f, 0.1f)); Sleep(1000); TEST_LOG("Back to center.\n"); EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 1.0f, 1.0f)); Sleep(1000); TEST_LOG("Panning right.\n"); EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.1f, 0.8f)); Sleep(1000); // To finish, verify that the getter works. float left = 0.0f; float right = 0.0f; EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right)); EXPECT_FLOAT_EQ(0.1f, left); EXPECT_FLOAT_EQ(0.8f, right); } #endif // !WEBRTC_ANDROID && !MAC_IPHONE <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <[email protected]> //------------------------------------------------------------------------------ #include "cling/Interpreter/DynamicLibraryManager.h" #include "cling/Interpreter/InvocationOptions.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <stdlib.h> #ifdef WIN32 #include <Windows.h> #else #include <limits.h> /* PATH_MAX */ #include <dlfcn.h> #endif namespace cling { DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts) : m_Opts(Opts) { } DynamicLibraryManager::~DynamicLibraryManager() {} static bool isSharedLib(llvm::StringRef LibName, bool& exists) { using namespace llvm::sys::fs; file_magic Magic; llvm::error_code Error = identify_magic(LibName, Magic); exists = (Error == llvm::errc::success); return exists && #ifdef __APPLE__ (Magic == file_magic::macho_fixed_virtual_memory_shared_lib || Magic == file_magic::macho_dynamically_linked_shared_lib || Magic == file_magic::macho_dynamically_linked_shared_lib_stub) #elif defined(LLVM_ON_UNIX) Magic == file_magic::elf_shared_object #elif defined(LLVM_ON_WIN32) # error "Windows DLLs not yet implemented!" //Magic == file_magic::pecoff_executable? #else # error "Unsupported platform." #endif ; } static void findSharedLibrary(llvm::StringRef fileStem, const llvm::SmallVectorImpl<std::string>& Paths, llvm::SmallString<512>& FoundDyLib, bool& exists, bool& isDyLib) { for (llvm::SmallVectorImpl<std::string>::const_iterator IPath = Paths.begin(), EPath = Paths.end(); IPath != EPath; ++IPath) { llvm::SmallString<512> ThisPath(*IPath); llvm::sys::path::append(ThisPath, fileStem); isDyLib = isSharedLib(ThisPath.str(), exists); if (isDyLib) ThisPath.swap(FoundDyLib); if (exists) return; } } #if defined(LLVM_ON_UNIX) static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) { char* env_var = getenv("LD_LIBRARY_PATH"); #if __APPLE__ if (!env_var) env_var = getenv("DYLD_LIBRARY_PATH"); if (!env_var) env_var = getenv("DYLD_FALLBACK_LIBRARY_PATH"); #endif if (env_var != 0) { static const char PathSeparator = ':'; const char* at = env_var; const char* delim = strchr(at, PathSeparator); while (delim != 0) { std::string tmp(at, size_t(delim-at)); if (llvm::sys::fs::is_directory(tmp.c_str())) Paths.push_back(tmp); at = delim + 1; delim = strchr(at, PathSeparator); } if (*at != 0) if (llvm::sys::fs::is_directory(llvm::StringRef(at))) Paths.push_back(at); } Paths.push_back("/usr/local/lib/"); Paths.push_back("/usr/X11R6/lib/"); Paths.push_back("/usr/lib/"); Paths.push_back("/lib/"); } #elif defined(LLVM_ON_WIN32) static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) { char buff[MAX_PATH]; // Generic form of C:\Windows\System32 HRESULT res = SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_SYSTEM, NULL, SHGFP_TYPE_CURRENT, buff); if (res != S_OK) { assert(0 && "Failed to get system directory"); return; } Paths.push_back(buff); // Reset buff. buff[0] = 0; // Generic form of C:\Windows res = SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_WINDOWS, NULL, SHGFP_TYPE_CURRENT, buff); if (res != S_OK) { assert(0 && "Failed to get windows directory"); return; } Paths.push_back(buff); } #else # error "Unsupported platform." #endif DynamicLibraryManager::LoadLibResult DynamicLibraryManager::tryLinker(const std::string& filename, bool permanent, bool isAbsolute, bool& exists, bool& isDyLib) { using namespace llvm::sys; exists = false; isDyLib = false; llvm::SmallString<512> FoundDyLib; if (isAbsolute) { isDyLib = isSharedLib(filename, exists); if (isDyLib) FoundDyLib = filename; } else { llvm::SmallVector<std::string, 16> SearchPaths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end()); GetSystemLibraryPaths(SearchPaths); findSharedLibrary(filename, SearchPaths, FoundDyLib, exists, isDyLib); if (!exists) { // Add DyLib extension: llvm::SmallString<512> filenameWithExt(filename); #if defined(LLVM_ON_UNIX) #ifdef __APPLE__ llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1; #endif static const char* DyLibExt = ".so"; #elif defined(LLVM_ON_WIN32) static const char* DyLibExt = ".dll"; #else # error "Unsupported platform." #endif filenameWithExt += DyLibExt; findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists, isDyLib); #ifdef __APPLE__ if (!exists) { filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end()); filenameWithExt += ".dylib"; findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists, isDyLib); } #endif } } if (!isDyLib) return kLoadLibError; assert(!FoundDyLib.empty() && "The shared lib exists but can't find it!"); // get canonical path name and check if already loaded #ifdef WIN32 llvm::SmallString<_MAX_PATH> FullPath; char *res = _fullpath((char *)FullPath.data(), FoundDyLib.c_str(), _MAX_PATH); #else llvm::SmallString<PATH_MAX+1> FullPath; char *res = realpath(FoundDyLib.c_str(), (char *)FullPath.data()); #endif if (res == 0) { llvm::errs() << "cling::Interpreter::tryLinker(): error getting real (canonical) path\n"; return kLoadLibError; } FullPath.set_size(strlen(res)); if (m_loadedLibraries.find(FullPath) != m_loadedLibraries.end()) return kLoadLibExists; // TODO: !permanent case #ifdef WIN32 # error "Windows DLL opening still needs to be implemented!" void* dyLibHandle = needs to be implemented!; std::string errMsg; #else const void* dyLibHandle = dlopen(FullPath.c_str(), RTLD_LAZY|RTLD_GLOBAL); std::string errMsg; if (const char* DyLibError = dlerror()) { errMsg = DyLibError; } #endif if (!dyLibHandle) { llvm::errs() << "cling::Interpreter::tryLinker(): " << errMsg << '\n'; return kLoadLibError; } std::pair<DyLibs::iterator, bool> insRes = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle, FullPath.str())); if (!insRes.second) return kLoadLibExists; m_loadedLibraries.insert(FullPath); return kLoadLibSuccess; } DynamicLibraryManager::LoadLibResult DynamicLibraryManager::loadLibrary(const std::string& filename, bool permanent, bool* tryCode) { llvm::SmallString<128> Absolute((llvm::StringRef(filename))); llvm::sys::fs::make_absolute(Absolute); bool isAbsolute = filename == Absolute.c_str(); bool exists = false; bool isDyLib = false; LoadLibResult res = tryLinker(filename, permanent, isAbsolute, exists, isDyLib); if (tryCode) { *tryCode = !isDyLib; if (isAbsolute) *tryCode &= exists; } if (exists) return res; if (!isAbsolute && filename.compare(0, 3, "lib")) { // try with "lib" prefix: res = tryLinker("lib" + filename, permanent, false, exists, isDyLib); if (tryCode) { *tryCode = !isDyLib; if (isAbsolute) *tryCode &= exists; } if (res != kLoadLibError) return res; } return kLoadLibError; } bool DynamicLibraryManager::isDynamicLibraryLoaded(llvm::StringRef fullPath) const { // get canonical path name and check if already loaded #ifdef WIN32 char buf[_MAX_PATH]; char *res = _fullpath(buf, fullPath.str().c_str(), _MAX_PATH); #else char buf[PATH_MAX+1]; char *res = realpath(fullPath.str().c_str(), buf); #endif if (res == 0) { llvm::errs() << "cling::Interpreter::isDynamicLibraryLoaded(): error getting real (canonical) path\n"; return false; } if (m_loadedLibraries.find(buf) != m_loadedLibraries.end()) return true; return false; } void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) { llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle)); } } // end namespace cling <commit_msg>Use a llvm::SmallString instead of a char[] to avoid corrupting the stack (thanks Axel)<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <[email protected]> //------------------------------------------------------------------------------ #include "cling/Interpreter/DynamicLibraryManager.h" #include "cling/Interpreter/InvocationOptions.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <stdlib.h> #ifdef WIN32 #include <Windows.h> #else #include <limits.h> /* PATH_MAX */ #include <dlfcn.h> #endif namespace cling { DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts) : m_Opts(Opts) { } DynamicLibraryManager::~DynamicLibraryManager() {} static bool isSharedLib(llvm::StringRef LibName, bool& exists) { using namespace llvm::sys::fs; file_magic Magic; llvm::error_code Error = identify_magic(LibName, Magic); exists = (Error == llvm::errc::success); return exists && #ifdef __APPLE__ (Magic == file_magic::macho_fixed_virtual_memory_shared_lib || Magic == file_magic::macho_dynamically_linked_shared_lib || Magic == file_magic::macho_dynamically_linked_shared_lib_stub) #elif defined(LLVM_ON_UNIX) Magic == file_magic::elf_shared_object #elif defined(LLVM_ON_WIN32) # error "Windows DLLs not yet implemented!" //Magic == file_magic::pecoff_executable? #else # error "Unsupported platform." #endif ; } static void findSharedLibrary(llvm::StringRef fileStem, const llvm::SmallVectorImpl<std::string>& Paths, llvm::SmallString<512>& FoundDyLib, bool& exists, bool& isDyLib) { for (llvm::SmallVectorImpl<std::string>::const_iterator IPath = Paths.begin(), EPath = Paths.end(); IPath != EPath; ++IPath) { llvm::SmallString<512> ThisPath(*IPath); llvm::sys::path::append(ThisPath, fileStem); isDyLib = isSharedLib(ThisPath.str(), exists); if (isDyLib) ThisPath.swap(FoundDyLib); if (exists) return; } } #if defined(LLVM_ON_UNIX) static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) { char* env_var = getenv("LD_LIBRARY_PATH"); #if __APPLE__ if (!env_var) env_var = getenv("DYLD_LIBRARY_PATH"); if (!env_var) env_var = getenv("DYLD_FALLBACK_LIBRARY_PATH"); #endif if (env_var != 0) { static const char PathSeparator = ':'; const char* at = env_var; const char* delim = strchr(at, PathSeparator); while (delim != 0) { std::string tmp(at, size_t(delim-at)); if (llvm::sys::fs::is_directory(tmp.c_str())) Paths.push_back(tmp); at = delim + 1; delim = strchr(at, PathSeparator); } if (*at != 0) if (llvm::sys::fs::is_directory(llvm::StringRef(at))) Paths.push_back(at); } Paths.push_back("/usr/local/lib/"); Paths.push_back("/usr/X11R6/lib/"); Paths.push_back("/usr/lib/"); Paths.push_back("/lib/"); } #elif defined(LLVM_ON_WIN32) static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) { char buff[MAX_PATH]; // Generic form of C:\Windows\System32 HRESULT res = SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_SYSTEM, NULL, SHGFP_TYPE_CURRENT, buff); if (res != S_OK) { assert(0 && "Failed to get system directory"); return; } Paths.push_back(buff); // Reset buff. buff[0] = 0; // Generic form of C:\Windows res = SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_WINDOWS, NULL, SHGFP_TYPE_CURRENT, buff); if (res != S_OK) { assert(0 && "Failed to get windows directory"); return; } Paths.push_back(buff); } #else # error "Unsupported platform." #endif DynamicLibraryManager::LoadLibResult DynamicLibraryManager::tryLinker(const std::string& filename, bool permanent, bool isAbsolute, bool& exists, bool& isDyLib) { using namespace llvm::sys; exists = false; isDyLib = false; llvm::SmallString<512> FoundDyLib; if (isAbsolute) { isDyLib = isSharedLib(filename, exists); if (isDyLib) FoundDyLib = filename; } else { llvm::SmallVector<std::string, 16> SearchPaths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end()); GetSystemLibraryPaths(SearchPaths); findSharedLibrary(filename, SearchPaths, FoundDyLib, exists, isDyLib); if (!exists) { // Add DyLib extension: llvm::SmallString<512> filenameWithExt(filename); #if defined(LLVM_ON_UNIX) #ifdef __APPLE__ llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1; #endif static const char* DyLibExt = ".so"; #elif defined(LLVM_ON_WIN32) static const char* DyLibExt = ".dll"; #else # error "Unsupported platform." #endif filenameWithExt += DyLibExt; findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists, isDyLib); #ifdef __APPLE__ if (!exists) { filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end()); filenameWithExt += ".dylib"; findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists, isDyLib); } #endif } } if (!isDyLib) return kLoadLibError; assert(!FoundDyLib.empty() && "The shared lib exists but can't find it!"); // get canonical path name and check if already loaded #ifdef WIN32 llvm::SmallString<_MAX_PATH> FullPath; char *res = _fullpath((char *)FullPath.data(), FoundDyLib.c_str(), _MAX_PATH); #else llvm::SmallString<PATH_MAX+1> FullPath; char *res = realpath(FoundDyLib.c_str(), (char *)FullPath.data()); #endif if (res == 0) { llvm::errs() << "cling::Interpreter::tryLinker(): error getting real (canonical) path\n"; return kLoadLibError; } FullPath.set_size(strlen(res)); if (m_loadedLibraries.find(FullPath) != m_loadedLibraries.end()) return kLoadLibExists; // TODO: !permanent case #ifdef WIN32 # error "Windows DLL opening still needs to be implemented!" void* dyLibHandle = needs to be implemented!; std::string errMsg; #else const void* dyLibHandle = dlopen(FullPath.c_str(), RTLD_LAZY|RTLD_GLOBAL); std::string errMsg; if (const char* DyLibError = dlerror()) { errMsg = DyLibError; } #endif if (!dyLibHandle) { llvm::errs() << "cling::Interpreter::tryLinker(): " << errMsg << '\n'; return kLoadLibError; } std::pair<DyLibs::iterator, bool> insRes = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle, FullPath.str())); if (!insRes.second) return kLoadLibExists; m_loadedLibraries.insert(FullPath); return kLoadLibSuccess; } DynamicLibraryManager::LoadLibResult DynamicLibraryManager::loadLibrary(const std::string& filename, bool permanent, bool* tryCode) { llvm::SmallString<128> Absolute((llvm::StringRef(filename))); llvm::sys::fs::make_absolute(Absolute); bool isAbsolute = filename == Absolute.c_str(); bool exists = false; bool isDyLib = false; LoadLibResult res = tryLinker(filename, permanent, isAbsolute, exists, isDyLib); if (tryCode) { *tryCode = !isDyLib; if (isAbsolute) *tryCode &= exists; } if (exists) return res; if (!isAbsolute && filename.compare(0, 3, "lib")) { // try with "lib" prefix: res = tryLinker("lib" + filename, permanent, false, exists, isDyLib); if (tryCode) { *tryCode = !isDyLib; if (isAbsolute) *tryCode &= exists; } if (res != kLoadLibError) return res; } return kLoadLibError; } bool DynamicLibraryManager::isDynamicLibraryLoaded(llvm::StringRef fullPath) const { // get canonical path name and check if already loaded #ifdef WIN32 llvm::SmallString<_MAX_PATH> buf; char *res = _fullpath((char *)buf.data(), fullPath.str().c_str(), _MAX_PATH); #else llvm::SmallString<PATH_MAX+1> buf; char *res = realpath(fullPath.str().c_str(), (char *)buf.data()); #endif if (res == 0) { llvm::errs() << "cling::Interpreter::isDynamicLibraryLoaded(): error getting real (canonical) path\n"; return false; } buf.set_size(strlen(res)); if (m_loadedLibraries.find(buf) != m_loadedLibraries.end()) return true; return false; } void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) { llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle)); } } // end namespace cling <|endoftext|>
<commit_before>// Copyright (c) 2000-2021, Heiko Bauke // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. #if !(defined TRNG_ZERO_TRUNCATED_POISSON_DIST_HPP) #define TRNG_ZERO_TRUNCATED_POISSON_DIST_HPP #include <trng/limits.hpp> #include <trng/utility.hpp> #include <trng/math.hpp> #include <trng/special_functions.hpp> #include <ostream> #include <istream> #include <iomanip> #include <vector> #include <ciso646> namespace trng { // non-uniform random number generator class class zero_truncated_poisson_dist { public: using result_type = int; class param_type { private: double mu_{0}; std::vector<double> P_; void calc_probabilities() { P_ = std::vector<double>(); int x{1}; P_.push_back(0); while (x < 7 or x < 2 * mu_) { const double p{(math::exp(mu_) * math::GammaQ(x + 1.0, mu_) - 1) / math::expm1(mu_)}; P_.push_back(p); ++x; } P_.push_back(1); } public: double mu() const { return mu_; } void mu(double mu_new) { mu_ = mu_new; calc_probabilities(); } param_type() = default; explicit param_type(double mu) : mu_{mu} { calc_probabilities(); } friend class zero_truncated_poisson_dist; }; private: param_type P; public: // constructor explicit zero_truncated_poisson_dist(double mu) : P{mu} {} explicit zero_truncated_poisson_dist(const param_type &P) : P{P} {} // reset internal state void reset() {} // random numbers template<typename R> int operator()(R &r) { double p{utility::uniformco<double>(r)}; int x{utility::discrete(p, P.P_.begin(), P.P_.end())}; if (x + 1 == P.P_.size()) { p -= cdf(x); while (p > 0) { ++x; p -= pdf(x); } } return x; } template<typename R> int operator()(R &r, const param_type &p) { zero_truncated_poisson_dist g(p); return g(r); } // property methods int min() const { return 1; } int max() const { return math::numeric_limits<int>::max(); } param_type param() const { return P; } void param(const param_type &P_new) { P = P_new; } double mu() const { return P.mu(); } void mu(double mu_new) { P.mu(mu_new); } // probability density function double pdf(int x) const { return x <= 0 ? 0.0 : math::exp(-math::ln_Gamma(x + 1.0) + x * math::ln(P.mu())) / math::expm1(P.mu()); } // cumulative density function double cdf(int x) const { return x <= 0 ? 0.0 : (math::exp(P.mu()) * math::GammaQ(x + 1.0, P.mu()) - 1) / math::expm1(P.mu()); } }; // ------------------------------------------------------------------- // EqualityComparable concept inline bool operator==(const zero_truncated_poisson_dist::param_type &P1, const zero_truncated_poisson_dist::param_type &P2) { return P1.mu() == P2.mu(); } inline bool operator!=(const zero_truncated_poisson_dist::param_type &P1, const zero_truncated_poisson_dist::param_type &P2) { return not(P1 == P2); } // Streamable concept template<typename char_t, typename traits_t> std::basic_ostream<char_t, traits_t> &operator<<( std::basic_ostream<char_t, traits_t> &out, const zero_truncated_poisson_dist::param_type &P) { std::ios_base::fmtflags flags(out.flags()); out.flags(std::ios_base::dec | std::ios_base::fixed | std::ios_base::left); out << '(' << std::setprecision(17) << P.mu() << ')'; out.flags(flags); return out; } template<typename char_t, typename traits_t> std::basic_istream<char_t, traits_t> &operator>>(std::basic_istream<char_t, traits_t> &in, zero_truncated_poisson_dist::param_type &P) { double mu; std::ios_base::fmtflags flags(in.flags()); in.flags(std::ios_base::dec | std::ios_base::fixed | std::ios_base::left); in >> utility::delim('(') >> mu >> utility::delim(')'); if (in) P = zero_truncated_poisson_dist::param_type(mu); in.flags(flags); return in; } // ------------------------------------------------------------------- // EqualityComparable concept inline bool operator==(const zero_truncated_poisson_dist &g1, const zero_truncated_poisson_dist &g2) { return g1.param() == g2.param(); } inline bool operator!=(const zero_truncated_poisson_dist &g1, const zero_truncated_poisson_dist &g2) { return g1.param() != g2.param(); } // Streamable concept template<typename char_t, typename traits_t> std::basic_ostream<char_t, traits_t> &operator<<(std::basic_ostream<char_t, traits_t> &out, const zero_truncated_poisson_dist &g) { std::ios_base::fmtflags flags(out.flags()); out.flags(std::ios_base::dec | std::ios_base::fixed | std::ios_base::left); out << "[zero-truncated poisson " << g.param() << ']'; out.flags(flags); return out; } template<typename char_t, typename traits_t> std::basic_istream<char_t, traits_t> &operator>>(std::basic_istream<char_t, traits_t> &in, zero_truncated_poisson_dist &g) { zero_truncated_poisson_dist::param_type P; std::ios_base::fmtflags flags(in.flags()); in.flags(std::ios_base::dec | std::ios_base::fixed | std::ios_base::left); in >> utility::ignore_spaces() >> utility::delim("[zero-truncated poisson ") >> P >> utility::delim(']'); if (in) g.param(P); in.flags(flags); return in; } } // namespace trng #endif <commit_msg>avoid integer overflow<commit_after>// Copyright (c) 2000-2021, Heiko Bauke // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. #if !(defined TRNG_ZERO_TRUNCATED_POISSON_DIST_HPP) #define TRNG_ZERO_TRUNCATED_POISSON_DIST_HPP #include <trng/limits.hpp> #include <trng/utility.hpp> #include <trng/math.hpp> #include <trng/special_functions.hpp> #include <ostream> #include <istream> #include <iomanip> #include <vector> #include <ciso646> namespace trng { // non-uniform random number generator class class zero_truncated_poisson_dist { public: using result_type = int; class param_type { private: double mu_{0}; std::vector<double> P_; void calc_probabilities() { P_ = std::vector<double>(); int x{1}; P_.push_back(0); while (x < 7 or x < 2 * mu_) { const double p{(math::exp(mu_) * math::GammaQ(x + 1.0, mu_) - 1) / math::expm1(mu_)}; P_.push_back(p); ++x; } P_.push_back(1); } public: double mu() const { return mu_; } void mu(double mu_new) { mu_ = mu_new; calc_probabilities(); } param_type() = default; explicit param_type(double mu) : mu_{mu} { calc_probabilities(); } friend class zero_truncated_poisson_dist; }; private: param_type P; public: // constructor explicit zero_truncated_poisson_dist(double mu) : P{mu} {} explicit zero_truncated_poisson_dist(const param_type &P) : P{P} {} // reset internal state void reset() {} // random numbers template<typename R> int operator()(R &r) { double p{utility::uniformco<double>(r)}; const std::size_t x{utility::discrete(p, P.P_.begin(), P.P_.end())}; int x_i{static_cast<int>(x)}; if (x + 1 == P.P_.size()) { p -= cdf(x_i); while (p > 0) { ++x_i; p -= pdf(x_i); } } return x_i; } template<typename R> int operator()(R &r, const param_type &p) { zero_truncated_poisson_dist g(p); return g(r); } // property methods int min() const { return 1; } int max() const { return math::numeric_limits<int>::max(); } param_type param() const { return P; } void param(const param_type &P_new) { P = P_new; } double mu() const { return P.mu(); } void mu(double mu_new) { P.mu(mu_new); } // probability density function double pdf(int x) const { return x <= 0 ? 0.0 : math::exp(-math::ln_Gamma(x + 1.0) + x * math::ln(P.mu())) / math::expm1(P.mu()); } // cumulative density function double cdf(int x) const { return x <= 0 ? 0.0 : (math::exp(P.mu()) * math::GammaQ(x + 1.0, P.mu()) - 1) / math::expm1(P.mu()); } }; // ------------------------------------------------------------------- // EqualityComparable concept inline bool operator==(const zero_truncated_poisson_dist::param_type &P1, const zero_truncated_poisson_dist::param_type &P2) { return P1.mu() == P2.mu(); } inline bool operator!=(const zero_truncated_poisson_dist::param_type &P1, const zero_truncated_poisson_dist::param_type &P2) { return not(P1 == P2); } // Streamable concept template<typename char_t, typename traits_t> std::basic_ostream<char_t, traits_t> &operator<<( std::basic_ostream<char_t, traits_t> &out, const zero_truncated_poisson_dist::param_type &P) { std::ios_base::fmtflags flags(out.flags()); out.flags(std::ios_base::dec | std::ios_base::fixed | std::ios_base::left); out << '(' << std::setprecision(17) << P.mu() << ')'; out.flags(flags); return out; } template<typename char_t, typename traits_t> std::basic_istream<char_t, traits_t> &operator>>(std::basic_istream<char_t, traits_t> &in, zero_truncated_poisson_dist::param_type &P) { double mu; std::ios_base::fmtflags flags(in.flags()); in.flags(std::ios_base::dec | std::ios_base::fixed | std::ios_base::left); in >> utility::delim('(') >> mu >> utility::delim(')'); if (in) P = zero_truncated_poisson_dist::param_type(mu); in.flags(flags); return in; } // ------------------------------------------------------------------- // EqualityComparable concept inline bool operator==(const zero_truncated_poisson_dist &g1, const zero_truncated_poisson_dist &g2) { return g1.param() == g2.param(); } inline bool operator!=(const zero_truncated_poisson_dist &g1, const zero_truncated_poisson_dist &g2) { return g1.param() != g2.param(); } // Streamable concept template<typename char_t, typename traits_t> std::basic_ostream<char_t, traits_t> &operator<<(std::basic_ostream<char_t, traits_t> &out, const zero_truncated_poisson_dist &g) { std::ios_base::fmtflags flags(out.flags()); out.flags(std::ios_base::dec | std::ios_base::fixed | std::ios_base::left); out << "[zero-truncated poisson " << g.param() << ']'; out.flags(flags); return out; } template<typename char_t, typename traits_t> std::basic_istream<char_t, traits_t> &operator>>(std::basic_istream<char_t, traits_t> &in, zero_truncated_poisson_dist &g) { zero_truncated_poisson_dist::param_type P; std::ios_base::fmtflags flags(in.flags()); in.flags(std::ios_base::dec | std::ios_base::fixed | std::ios_base::left); in >> utility::ignore_spaces() >> utility::delim("[zero-truncated poisson ") >> P >> utility::delim(']'); if (in) g.param(P); in.flags(flags); return in; } } // namespace trng #endif <|endoftext|>
<commit_before><commit_msg>Squashed commit of the following:<commit_after><|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/planner/open_space/open_space_planner.h" #include <fstream> #include <utility> #include "cyber/common/log.h" #include "cyber/task/task.h" #include "modules/common/util/string_tokenizer.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::math::Box2d; using apollo::common::math::Vec2d; Status OpenSpacePlanner::Init(const PlanningConfig& planning_confgs) { AINFO << "In OpenSpacePlanner::Init()"; // TODO(QiL): integrate open_space planner into task config when refactor done CHECK(common::util::GetProtoFromFile(FLAGS_planner_open_space_config_filename, &planner_open_space_config_)) << "Failed to load open space config file " << FLAGS_planner_open_space_config_filename; current_trajectory_index_ = 0; // initialize open space trajectory generator open_space_trajectory_generator_.reset(new OpenSpaceTrajectoryGenerator()); open_space_trajectory_generator_->Init(planner_open_space_config_); if (FLAGS_enable_open_space_planner_thread) { task_future_ = cyber::Async(&OpenSpacePlanner::GenerateTrajectoryThread, this); } return Status::OK(); } apollo::common::Status OpenSpacePlanner::Plan( const common::TrajectoryPoint& planning_init_point, Frame* frame) { // 1. Build Predicition Environments. predicted_bounding_rectangles_.clear(); if (FLAGS_enable_open_space_planner_thread) { ADEBUG << "Open space plan in multi-threads mode"; BuildPredictedEnvironment(frame->obstacles()); // 2. Update Vehicle information and obstacles information from frame. vehicle_state_ = frame->vehicle_state(); open_space_roi_generator_.reset(new OpenSpaceROI()); if (!open_space_roi_generator_->GenerateRegionOfInterest(frame)) { return Status(ErrorCode::PLANNING_ERROR, "Generate Open Space ROI failed"); } rotate_angle_ = open_space_roi_generator_->origin_heading(); translate_origin_ = open_space_roi_generator_->origin_point(); end_pose_ = open_space_roi_generator_->open_space_end_pose(); obstacles_num_ = open_space_roi_generator_->obstacles_num(); obstacles_edges_num_ = open_space_roi_generator_->obstacles_edges_num(); obstacles_A_ = open_space_roi_generator_->obstacles_A(); obstacles_b_ = open_space_roi_generator_->obstacles_b(); obstalce_list_ = open_space_roi_generator_->openspace_warmstart_obstacles(); XYbounds_ = open_space_roi_generator_->ROI_xy_boundary(); // 3. Check if trajectory updated, if so, update internal // trajectory_partition_; if (trajectory_updated_) { AINFO << "Trajectories have been updated!"; std::lock_guard<std::mutex> lock(open_space_mutex_); trajectory_partition_.Clear(); gear_positions_.clear(); open_space_debug_.Clear(); current_trajectory_index_ = 0; open_space_trajectory_generator_->UpdateTrajectory(&trajectory_partition_, &gear_positions_); open_space_trajectory_generator_->UpdateDebugInfo(&open_space_debug_); ADEBUG << "Trajectory caculation updated, new results : " << trajectory_partition_.ShortDebugString(); } // TODO(Jiaxuan): Choose the current_trajectory in trajectory_partition_ // If the vehicle each the end point of current trajectory and stop // Then move to the next Trajectory if (trajectory_partition_.trajectory_size() == 0) { return Status(ErrorCode::PLANNING_ERROR, "Trajectory partition failed."); } current_trajectory_ = trajectory_partition_.trajectory(current_trajectory_index_); TrajectoryPoint end_point = current_trajectory_.trajectory_point( current_trajectory_.trajectory_point_size() - 1); if (std::sqrt((vehicle_state_.x() - end_point.path_point().x()) * (vehicle_state_.x() - end_point.path_point().x()) + (vehicle_state_.y() - end_point.path_point().y()) * (vehicle_state_.y() - end_point.path_point().y())) < planner_open_space_config_.max_position_error_to_end_point() && std::abs(vehicle_state_.heading() - end_point.path_point().theta()) < planner_open_space_config_.max_theta_error_to_end_point() && (current_trajectory_index_ < trajectory_partition_.trajectory_size() - 1)) { current_trajectory_index_ += 1; } // 4. Collision check for updated trajectory, if pass, update frame, else, // return error status if (IsCollisionFreeTrajectory(current_trajectory_)) { // Convet current trajectory to publishable_trajectory publishable_trajectory_.Clear(); publishable_trajectory_.mutable_trajectory_point()->CopyFrom( *(current_trajectory_.mutable_trajectory_point())); frame->mutable_trajectory()->CopyFrom(publishable_trajectory_); frame->mutable_open_space_debug()->CopyFrom(open_space_debug_); return Status::OK(); } else { // If collision happens, return wrong planning status and estop // trajectory would be sent in std planning return Status(ErrorCode::PLANNING_ERROR, "Collision Check failed in multi-threads"); } } else { // Single thread logic vehicle_state_ = frame->vehicle_state(); open_space_roi_generator_.reset(new OpenSpaceROI()); if (!open_space_roi_generator_->GenerateRegionOfInterest(frame)) { return Status(ErrorCode::PLANNING_ERROR, "Generate Open Space ROI failed"); } rotate_angle_ = open_space_roi_generator_->origin_heading(); translate_origin_ = open_space_roi_generator_->origin_point(); end_pose_ = open_space_roi_generator_->open_space_end_pose(); obstacles_num_ = open_space_roi_generator_->obstacles_num(); obstacles_edges_num_ = open_space_roi_generator_->obstacles_edges_num(); obstacles_A_ = open_space_roi_generator_->obstacles_A(); obstacles_b_ = open_space_roi_generator_->obstacles_b(); obstalce_list_ = open_space_roi_generator_->openspace_warmstart_obstacles(); XYbounds_ = open_space_roi_generator_->ROI_xy_boundary(); // 2. Generate Trajectory; Status status = open_space_trajectory_generator_->Plan( vehicle_state_, XYbounds_, rotate_angle_, translate_origin_, end_pose_, obstacles_num_, obstacles_edges_num_, obstacles_A_, obstacles_b_, obstalce_list_); // 3. If status is OK, update vehicle trajectory; if (status == Status::OK()) { trajectory_partition_.Clear(); gear_positions_.clear(); open_space_debug_.Clear(); current_trajectory_index_ = 0; open_space_trajectory_generator_->UpdateTrajectory(&trajectory_partition_, &gear_positions_); open_space_trajectory_generator_->UpdateDebugInfo(&open_space_debug_); ADEBUG << "Trajectory caculation updated, new results : " << trajectory_partition_.ShortDebugString(); } else { return status; } current_trajectory_ = trajectory_partition_.trajectory(current_trajectory_index_); CHECK_GT(current_trajectory_.trajectory_point_size(), 0); TrajectoryPoint end_point = current_trajectory_.trajectory_point( current_trajectory_.trajectory_point_size() - 1); if (std::sqrt((vehicle_state_.x() - end_point.path_point().x()) * (vehicle_state_.x() - end_point.path_point().x()) + (vehicle_state_.y() - end_point.path_point().y()) * (vehicle_state_.y() - end_point.path_point().y())) < planner_open_space_config_.max_position_error_to_end_point() && std::abs(vehicle_state_.heading() - end_point.path_point().theta()) < planner_open_space_config_.max_theta_error_to_end_point() && (current_trajectory_index_ < trajectory_partition_.trajectory_size() - 1)) { current_trajectory_index_++; } // 4. Collision check for updated trajectory, if pass, update frame, else, // return error status if (IsCollisionFreeTrajectory(current_trajectory_)) { publishable_trajectory_.Clear(); publishable_trajectory_.mutable_trajectory_point()->CopyFrom( *(current_trajectory_.mutable_trajectory_point())); publishable_trajectory_.set_gear( gear_positions_[current_trajectory_index_]); frame->mutable_trajectory()->CopyFrom(publishable_trajectory_); frame->mutable_open_space_debug()->CopyFrom(open_space_debug_); return Status::OK(); } else { // If collision happens, return wrong planning status and estop // trajectory would be sent in std planning return Status(ErrorCode::PLANNING_ERROR, "Collision Check failed"); } } } void OpenSpacePlanner::GenerateTrajectoryThread() { while (!is_stop_) { { ADEBUG << "Open space plan in multi-threads mode : start to generate new " "trajectories"; { std::lock_guard<std::mutex> lock(open_space_mutex_); trajectory_updated_ = false; if (open_space_trajectory_generator_->Plan( vehicle_state_, XYbounds_, rotate_angle_, translate_origin_, end_pose_, obstacles_num_, obstacles_edges_num_, obstacles_A_, obstacles_b_, obstalce_list_) == Status::OK()) { trajectory_updated_ = false; } } } } } void OpenSpacePlanner::Stop() { is_stop_ = true; if (FLAGS_enable_open_space_planner_thread) { task_future_.get(); } } bool OpenSpacePlanner::IsCollisionFreeTrajectory( const apollo::common::Trajectory& trajectory) { const auto& vehicle_config = common::VehicleConfigHelper::Instance()->GetConfig(); double ego_length = vehicle_config.vehicle_param().length(); double ego_width = vehicle_config.vehicle_param().width(); int point_size = trajectory.trajectory_point().size(); for (int i = 0; i < point_size; ++i) { const auto& trajectory_point = trajectory.trajectory_point(i); double ego_theta = trajectory_point.path_point().theta(); Box2d ego_box( {trajectory_point.path_point().x(), trajectory_point.path_point().y()}, ego_theta, ego_length, ego_width); double shift_distance = ego_length / 2.0 - vehicle_config.vehicle_param().back_edge_to_center(); Vec2d shift_vec{shift_distance * std::cos(ego_theta), shift_distance * std::sin(ego_theta)}; ego_box.Shift(shift_vec); if (predicted_bounding_rectangles_.size() != 0) { for (const auto& obstacle_box : predicted_bounding_rectangles_[i]) { if (ego_box.HasOverlap(obstacle_box)) { return false; } } } } return true; } void OpenSpacePlanner::BuildPredictedEnvironment( const std::vector<const Obstacle*>& obstacles) { CHECK(predicted_bounding_rectangles_.empty()); double relative_time = 0.0; while (relative_time < FLAGS_trajectory_time_length) { std::vector<Box2d> predicted_env; for (const Obstacle* obstacle : obstacles) { TrajectoryPoint point = obstacle->GetPointAtTime(relative_time); Box2d box = obstacle->GetBoundingBox(point); predicted_env.push_back(std::move(box)); } predicted_bounding_rectangles_.push_back(std::move(predicted_env)); relative_time += FLAGS_trajectory_time_resolution; } } } // namespace planning } // namespace apollo <commit_msg>Planning : fix update_trajectory status in open space planner<commit_after>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/planner/open_space/open_space_planner.h" #include <fstream> #include <utility> #include "cyber/common/log.h" #include "cyber/task/task.h" #include "modules/common/util/string_tokenizer.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::math::Box2d; using apollo::common::math::Vec2d; Status OpenSpacePlanner::Init(const PlanningConfig& planning_confgs) { AINFO << "In OpenSpacePlanner::Init()"; // TODO(QiL): integrate open_space planner into task config when refactor done CHECK(common::util::GetProtoFromFile(FLAGS_planner_open_space_config_filename, &planner_open_space_config_)) << "Failed to load open space config file " << FLAGS_planner_open_space_config_filename; current_trajectory_index_ = 0; // initialize open space trajectory generator open_space_trajectory_generator_.reset(new OpenSpaceTrajectoryGenerator()); open_space_trajectory_generator_->Init(planner_open_space_config_); if (FLAGS_enable_open_space_planner_thread) { task_future_ = cyber::Async(&OpenSpacePlanner::GenerateTrajectoryThread, this); } return Status::OK(); } apollo::common::Status OpenSpacePlanner::Plan( const common::TrajectoryPoint& planning_init_point, Frame* frame) { // 1. Build Predicition Environments. predicted_bounding_rectangles_.clear(); if (FLAGS_enable_open_space_planner_thread) { ADEBUG << "Open space plan in multi-threads mode"; BuildPredictedEnvironment(frame->obstacles()); // 2. Update Vehicle information and obstacles information from frame. vehicle_state_ = frame->vehicle_state(); open_space_roi_generator_.reset(new OpenSpaceROI()); if (!open_space_roi_generator_->GenerateRegionOfInterest(frame)) { return Status(ErrorCode::PLANNING_ERROR, "Generate Open Space ROI failed"); } rotate_angle_ = open_space_roi_generator_->origin_heading(); translate_origin_ = open_space_roi_generator_->origin_point(); end_pose_ = open_space_roi_generator_->open_space_end_pose(); obstacles_num_ = open_space_roi_generator_->obstacles_num(); obstacles_edges_num_ = open_space_roi_generator_->obstacles_edges_num(); obstacles_A_ = open_space_roi_generator_->obstacles_A(); obstacles_b_ = open_space_roi_generator_->obstacles_b(); obstalce_list_ = open_space_roi_generator_->openspace_warmstart_obstacles(); XYbounds_ = open_space_roi_generator_->ROI_xy_boundary(); // 3. Check if trajectory updated, if so, update internal // trajectory_partition_; if (trajectory_updated_) { AINFO << "Trajectories have been updated!"; std::lock_guard<std::mutex> lock(open_space_mutex_); trajectory_partition_.Clear(); gear_positions_.clear(); open_space_debug_.Clear(); current_trajectory_index_ = 0; open_space_trajectory_generator_->UpdateTrajectory(&trajectory_partition_, &gear_positions_); open_space_trajectory_generator_->UpdateDebugInfo(&open_space_debug_); ADEBUG << "Trajectory caculation updated, new results : " << trajectory_partition_.ShortDebugString(); } // TODO(Jiaxuan): Choose the current_trajectory in trajectory_partition_ // If the vehicle each the end point of current trajectory and stop // Then move to the next Trajectory if (trajectory_partition_.trajectory_size() == 0) { return Status(ErrorCode::PLANNING_ERROR, "Trajectory partition failed."); } current_trajectory_ = trajectory_partition_.trajectory(current_trajectory_index_); TrajectoryPoint end_point = current_trajectory_.trajectory_point( current_trajectory_.trajectory_point_size() - 1); if (std::sqrt((vehicle_state_.x() - end_point.path_point().x()) * (vehicle_state_.x() - end_point.path_point().x()) + (vehicle_state_.y() - end_point.path_point().y()) * (vehicle_state_.y() - end_point.path_point().y())) < planner_open_space_config_.max_position_error_to_end_point() && std::abs(vehicle_state_.heading() - end_point.path_point().theta()) < planner_open_space_config_.max_theta_error_to_end_point() && (current_trajectory_index_ < trajectory_partition_.trajectory_size() - 1)) { current_trajectory_index_ += 1; } // 4. Collision check for updated trajectory, if pass, update frame, else, // return error status if (IsCollisionFreeTrajectory(current_trajectory_)) { // Convet current trajectory to publishable_trajectory publishable_trajectory_.Clear(); publishable_trajectory_.mutable_trajectory_point()->CopyFrom( *(current_trajectory_.mutable_trajectory_point())); frame->mutable_trajectory()->CopyFrom(publishable_trajectory_); frame->mutable_open_space_debug()->CopyFrom(open_space_debug_); return Status::OK(); } else { // If collision happens, return wrong planning status and estop // trajectory would be sent in std planning return Status(ErrorCode::PLANNING_ERROR, "Collision Check failed in multi-threads"); } } else { // Single thread logic vehicle_state_ = frame->vehicle_state(); open_space_roi_generator_.reset(new OpenSpaceROI()); if (!open_space_roi_generator_->GenerateRegionOfInterest(frame)) { return Status(ErrorCode::PLANNING_ERROR, "Generate Open Space ROI failed"); } rotate_angle_ = open_space_roi_generator_->origin_heading(); translate_origin_ = open_space_roi_generator_->origin_point(); end_pose_ = open_space_roi_generator_->open_space_end_pose(); obstacles_num_ = open_space_roi_generator_->obstacles_num(); obstacles_edges_num_ = open_space_roi_generator_->obstacles_edges_num(); obstacles_A_ = open_space_roi_generator_->obstacles_A(); obstacles_b_ = open_space_roi_generator_->obstacles_b(); obstalce_list_ = open_space_roi_generator_->openspace_warmstart_obstacles(); XYbounds_ = open_space_roi_generator_->ROI_xy_boundary(); // 2. Generate Trajectory; Status status = open_space_trajectory_generator_->Plan( vehicle_state_, XYbounds_, rotate_angle_, translate_origin_, end_pose_, obstacles_num_, obstacles_edges_num_, obstacles_A_, obstacles_b_, obstalce_list_); // 3. If status is OK, update vehicle trajectory; if (status == Status::OK()) { trajectory_partition_.Clear(); gear_positions_.clear(); open_space_debug_.Clear(); current_trajectory_index_ = 0; open_space_trajectory_generator_->UpdateTrajectory(&trajectory_partition_, &gear_positions_); open_space_trajectory_generator_->UpdateDebugInfo(&open_space_debug_); ADEBUG << "Trajectory caculation updated, new results : " << trajectory_partition_.ShortDebugString(); } else { return status; } current_trajectory_ = trajectory_partition_.trajectory(current_trajectory_index_); CHECK_GT(current_trajectory_.trajectory_point_size(), 0); TrajectoryPoint end_point = current_trajectory_.trajectory_point( current_trajectory_.trajectory_point_size() - 1); if (std::sqrt((vehicle_state_.x() - end_point.path_point().x()) * (vehicle_state_.x() - end_point.path_point().x()) + (vehicle_state_.y() - end_point.path_point().y()) * (vehicle_state_.y() - end_point.path_point().y())) < planner_open_space_config_.max_position_error_to_end_point() && std::abs(vehicle_state_.heading() - end_point.path_point().theta()) < planner_open_space_config_.max_theta_error_to_end_point() && (current_trajectory_index_ < trajectory_partition_.trajectory_size() - 1)) { current_trajectory_index_++; } // 4. Collision check for updated trajectory, if pass, update frame, else, // return error status if (IsCollisionFreeTrajectory(current_trajectory_)) { publishable_trajectory_.Clear(); publishable_trajectory_.mutable_trajectory_point()->CopyFrom( *(current_trajectory_.mutable_trajectory_point())); publishable_trajectory_.set_gear( gear_positions_[current_trajectory_index_]); frame->mutable_trajectory()->CopyFrom(publishable_trajectory_); frame->mutable_open_space_debug()->CopyFrom(open_space_debug_); return Status::OK(); } else { // If collision happens, return wrong planning status and estop // trajectory would be sent in std planning return Status(ErrorCode::PLANNING_ERROR, "Collision Check failed"); } } } void OpenSpacePlanner::GenerateTrajectoryThread() { while (!is_stop_) { { ADEBUG << "Open space plan in multi-threads mode : start to generate new " "trajectories"; { std::lock_guard<std::mutex> lock(open_space_mutex_); trajectory_updated_ = false; if (open_space_trajectory_generator_->Plan( vehicle_state_, XYbounds_, rotate_angle_, translate_origin_, end_pose_, obstacles_num_, obstacles_edges_num_, obstacles_A_, obstacles_b_, obstalce_list_) == Status::OK()) { trajectory_updated_ = true; } } } } } void OpenSpacePlanner::Stop() { is_stop_ = true; if (FLAGS_enable_open_space_planner_thread) { task_future_.get(); } } bool OpenSpacePlanner::IsCollisionFreeTrajectory( const apollo::common::Trajectory& trajectory) { const auto& vehicle_config = common::VehicleConfigHelper::Instance()->GetConfig(); double ego_length = vehicle_config.vehicle_param().length(); double ego_width = vehicle_config.vehicle_param().width(); int point_size = trajectory.trajectory_point().size(); for (int i = 0; i < point_size; ++i) { const auto& trajectory_point = trajectory.trajectory_point(i); double ego_theta = trajectory_point.path_point().theta(); Box2d ego_box( {trajectory_point.path_point().x(), trajectory_point.path_point().y()}, ego_theta, ego_length, ego_width); double shift_distance = ego_length / 2.0 - vehicle_config.vehicle_param().back_edge_to_center(); Vec2d shift_vec{shift_distance * std::cos(ego_theta), shift_distance * std::sin(ego_theta)}; ego_box.Shift(shift_vec); if (predicted_bounding_rectangles_.size() != 0) { for (const auto& obstacle_box : predicted_bounding_rectangles_[i]) { if (ego_box.HasOverlap(obstacle_box)) { return false; } } } } return true; } void OpenSpacePlanner::BuildPredictedEnvironment( const std::vector<const Obstacle*>& obstacles) { CHECK(predicted_bounding_rectangles_.empty()); double relative_time = 0.0; while (relative_time < FLAGS_trajectory_time_length) { std::vector<Box2d> predicted_env; for (const Obstacle* obstacle : obstacles) { TrajectoryPoint point = obstacle->GetPointAtTime(relative_time); Box2d box = obstacle->GetBoundingBox(point); predicted_env.push_back(std::move(box)); } predicted_bounding_rectangles_.push_back(std::move(predicted_env)); relative_time += FLAGS_trajectory_time_resolution; } } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before> // kuznechik.c // 04-Jan-15 Markku-Juhani O. Saarinen <[email protected]> // main() for testing #include <stdio.h> #include <stdlib.h> #include <time.h> #include "kuznechik.h" // debug print state void print_w128(w128_t *x) { int i; for (i = 0; i < 16; i++) printf(" %02X", x->b[i]); printf("\n"); } // These are here in Big Endian format, as that seems to be the favored // way of representing things. However, it is open if we will have to // flip byte order for the final version or not. const uint8_t testvec_key[32] = { 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF }; void kuz_init(); kuz_key_t encrypt_key; kuz_key_t decrypt_key; void key_init() { kuz_set_encrypt_key(&encrypt_key, testvec_key); kuz_set_decrypt_key(&decrypt_key, testvec_key); } void self_test() { w128_t x; key_init(); const uint8_t testvec_pt[16] = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x00, 0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88 }; const uint8_t testvec_ct[16] = { 0x7F, 0x67, 0x9D, 0x90, 0xBE, 0xBC, 0x24, 0x30, 0x5A, 0x46, 0x8D, 0x42, 0xB9, 0xD4, 0xED, 0xCD }; printf("Self-test:\n"); for (int i = 0; i < 10; i++) { printf("K_%d\t=", i + 1); print_w128(&encrypt_key.k[i]); } for (int i = 0; i < 16; i++) x.b[i] = testvec_pt[i]; printf("PT\t="); print_w128(&x); kuz_encrypt_block(&encrypt_key, &x); printf("CT\t="); print_w128(&x); for (int i = 0; i < 16; i++) { if (testvec_ct[i] != x.b[i]) { fprintf(stderr, "Encryption self-test failure.\n"); exit(-1); } } kuz_decrypt_block(&decrypt_key, &x); printf("PT\t="); print_w128(&x); for (int i = 0; i < 16; i++) { if (testvec_pt[i] != x.b[i]) { fprintf(stderr, "Decryption self-test failure.\n"); exit(-2); } } printf("Self-test OK!\n"); } int main(int argc, char **argv) { printf("Config: bits: %d, optimize mult: %d, use mul table: %d, use tables: %d\n", get_bits(), use_galois(), use_mul_table(), use_tables()); kuz_key_t key; w128_t x; uint32_t buf[0x100]; clock_t tim; kuz_init(); self_test(); // == Speed Test == for (int i = 0; i < 0x100; i++) buf[i] = i; kuz_set_encrypt_key(&key, testvec_key); for (int n = 4000, tim = 0; tim < 2 * CLOCKS_PER_SEC; n <<= 1) { tim = clock(); for (int j = 0; j < n; j++) { for (int i = 0; i < 0x100; i += 4) kuz_encrypt_block(&key, &buf[i]); } tim = clock() - tim; printf("kuz_encrypt_block(): %.3f kB/s (n=%dkB,t=%.3fs)\r", ((double) CLOCKS_PER_SEC * n) / ((double) tim), n, ((double) tim) / ((double) CLOCKS_PER_SEC)); fflush(stdout); } printf("\n"); for (int i = 0; i < 0x100; i++) buf[i] = i; kuz_set_decrypt_key(&key, testvec_key); for (int n = 4000, tim = 0; tim < 2 * CLOCKS_PER_SEC; n <<= 1) { tim = clock(); for (int j = 0; j < n; j++) { for (int i = 0; i < 0x100; i += 4) kuz_decrypt_block(&key, &buf[i]); } tim = clock() - tim; printf("kuz_decrypt_block(): %.3f kB/s (n=%dkB,t=%.3fs)\r", ((double) CLOCKS_PER_SEC * n) / ((double) tim), n, ((double) tim) / ((double) CLOCKS_PER_SEC)); fflush(stdout); } printf("\n"); printf("Tables: %.1fK (encrypt: %.1fK, decrypt: %.1fK)\n", (float)get_used_memory_count() / 1024, (float)get_encrypt_used_memory_count() / 1024, (float)get_decrypt_used_memory_count() / 1024); return 0; } <commit_msg>Remove deprecated credits<commit_after>#include <stdio.h> #include <stdlib.h> #include <time.h> #include "kuznechik.h" // debug print state void print_w128(w128_t *x) { int i; for (i = 0; i < 16; i++) printf(" %02X", x->b[i]); printf("\n"); } // These are here in Big Endian format, as that seems to be the favored // way of representing things. However, it is open if we will have to // flip byte order for the final version or not. const uint8_t testvec_key[32] = { 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF }; void kuz_init(); kuz_key_t encrypt_key; kuz_key_t decrypt_key; void key_init() { kuz_set_encrypt_key(&encrypt_key, testvec_key); kuz_set_decrypt_key(&decrypt_key, testvec_key); } void self_test() { w128_t x; key_init(); const uint8_t testvec_pt[16] = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x00, 0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88 }; const uint8_t testvec_ct[16] = { 0x7F, 0x67, 0x9D, 0x90, 0xBE, 0xBC, 0x24, 0x30, 0x5A, 0x46, 0x8D, 0x42, 0xB9, 0xD4, 0xED, 0xCD }; printf("Self-test:\n"); for (int i = 0; i < 10; i++) { printf("K_%d\t=", i + 1); print_w128(&encrypt_key.k[i]); } for (int i = 0; i < 16; i++) x.b[i] = testvec_pt[i]; printf("PT\t="); print_w128(&x); kuz_encrypt_block(&encrypt_key, &x); printf("CT\t="); print_w128(&x); for (int i = 0; i < 16; i++) { if (testvec_ct[i] != x.b[i]) { fprintf(stderr, "Encryption self-test failure.\n"); exit(-1); } } kuz_decrypt_block(&decrypt_key, &x); printf("PT\t="); print_w128(&x); for (int i = 0; i < 16; i++) { if (testvec_pt[i] != x.b[i]) { fprintf(stderr, "Decryption self-test failure.\n"); exit(-2); } } printf("Self-test OK!\n"); } int main(int argc, char **argv) { printf("Config: bits: %d, optimize mult: %d, use mul table: %d, use tables: %d\n", get_bits(), use_galois(), use_mul_table(), use_tables()); kuz_key_t key; w128_t x; uint32_t buf[0x100]; clock_t tim; kuz_init(); self_test(); // == Speed Test == for (int i = 0; i < 0x100; i++) buf[i] = i; kuz_set_encrypt_key(&key, testvec_key); for (int n = 4000, tim = 0; tim < 2 * CLOCKS_PER_SEC; n <<= 1) { tim = clock(); for (int j = 0; j < n; j++) { for (int i = 0; i < 0x100; i += 4) kuz_encrypt_block(&key, &buf[i]); } tim = clock() - tim; printf("kuz_encrypt_block(): %.3f kB/s (n=%dkB,t=%.3fs)\r", ((double) CLOCKS_PER_SEC * n) / ((double) tim), n, ((double) tim) / ((double) CLOCKS_PER_SEC)); fflush(stdout); } printf("\n"); for (int i = 0; i < 0x100; i++) buf[i] = i; kuz_set_decrypt_key(&key, testvec_key); for (int n = 4000, tim = 0; tim < 2 * CLOCKS_PER_SEC; n <<= 1) { tim = clock(); for (int j = 0; j < n; j++) { for (int i = 0; i < 0x100; i += 4) kuz_decrypt_block(&key, &buf[i]); } tim = clock() - tim; printf("kuz_decrypt_block(): %.3f kB/s (n=%dkB,t=%.3fs)\r", ((double) CLOCKS_PER_SEC * n) / ((double) tim), n, ((double) tim) / ((double) CLOCKS_PER_SEC)); fflush(stdout); } printf("\n"); printf("Tables: %.1fK (encrypt: %.1fK, decrypt: %.1fK)\n", (float)get_used_memory_count() / 1024, (float)get_encrypt_used_memory_count() / 1024, (float)get_decrypt_used_memory_count() / 1024); return 0; } <|endoftext|>
<commit_before>// This tutorial shows how to optimize a lens shape by using the ROOT Minuite2 // optimization engine. #include "Math/Functor.h" #include "Minuit2/Minuit2Minimizer.h" #include "TCanvas.h" #include "TGeoBBox.h" #include "TGeoMatrix.h" #include "TGeoPhysicalNode.h" #include "TH2D.h" #include "AFocalSurface.h" #include "AGeoAsphericDisk.h" #include "AGlassCatalog.h" #include "ALens.h" #include "AMirror.h" #include "AOpticsManager.h" #include "ARayArray.h" #include "ARayShooter.h" static const Double_t mm = AOpticsManager::mm(); static const Double_t um = AOpticsManager::um(); static const Double_t nm = AOpticsManager::nm(); static AOpticsManager* gOpticsManager = 0; static const int kNtheta = 3; static ARayArray* gArray[kNtheta] = {0, 0, 0}; static double kTheta[kNtheta] = {0., 2.5, 5.0}; static const int kNlambda = 3; static const double kRadius = 5.0 * mm; double GetSpotSize(ARayArray* array) { // Returns standard deviation of a spot TObjArray* focused = array->GetFocused(); TH2D h("", "", 1, 0, 0, 1, 0, 0); for (int i = 0; i < focused->GetLast(); i++) { ARay* ray = (ARay*)(*focused)[i]; double p[4]; ray->GetLastPoint(p); h.Fill(p[0], p[1]); } // i double sx = h.GetStdDev(1); double sy = h.GetStdDev(2); return TMath::Sqrt(sx * sx + sy * sy); } int Nphotons(ARayArray* array) { int total = 0; total += array->GetFocused()->GetLast() + 1; total += array->GetStopped()->GetLast() + 1; total += array->GetSuspended()->GetLast() + 1; total += array->GetAbsorbed()->GetLast() + 1; return total; } double Func(const double* par) { static bool initialized = kFALSE; static TGeoRotation rot[kNtheta]; static TGeoTranslation tr("tr", 0, 0, -3 * mm); if (!initialized) { for (int i = 0; i < kNtheta; i++) { rot[i] = TGeoRotation(); rot[i].SetAngles(0, kTheta[i], 0.); } // i initialized = kTRUE; } // if if (gOpticsManager) { delete gOpticsManager; } // if gOpticsManager = new AOpticsManager("manager", "manager"); gOpticsManager->DisableFresnelReflection(kTRUE); // Make the world TGeoBBox* box = new TGeoBBox("box", 100 * mm, 100 * mm, 100 * mm); AOpticalComponent* top = new AOpticalComponent("top", box); gOpticsManager->SetTopVolume(top); AGeoAsphericDisk* disk = new AGeoAsphericDisk("disk", 0 * mm, 0., par[0], par[1], kRadius, 0. * mm); disk->SetConicConstants(0, par[2]); double f1 = disk->CalcF1(kRadius); double f2 = disk->CalcF2(kRadius); if (f2 - f1 < 0) { // negative edge thickness return 1e100; } // if ALens* lens = new ALens("lens", disk); AGlassCatalog schott("../misc/schottzemax-20180601.agf"); lens->SetRefractiveIndex(schott.GetRefractiveIndex("N-BK7")); gOpticsManager->GetTopVolume()->AddNode(lens, 1); double origin[3] = {0, 0, 50 * mm + 1 * um}; TGeoBBox* box2 = new TGeoBBox("box2", 10 * mm, 10 * mm, 1 * um, origin); AFocalSurface* screen = new AFocalSurface("screen", box2); top->AddNode(screen, 1); AGeoAsphericDisk* disk2 = new AGeoAsphericDisk("disk2", 0 * mm, 0., par[0], 0., kRadius * 1.2, kRadius); AObscuration* obs = new AObscuration("obs", disk2); gOpticsManager->GetTopVolume()->AddNode(obs, 1); gOpticsManager->CloseGeometry(); double total = 0.; for (int i = 0; i < kNtheta; i++) { if (gArray[i]) { delete gArray[i]; gArray[i] = 0; } // if const double kLambda = 587.6 * nm; gArray[i] = ARayShooter::Circle(kLambda, kRadius * 1.1, 20, 10, &rot[i], &tr); gOpticsManager->TraceNonSequential(gArray[i]); total += TMath::Power(GetSpotSize(gArray[i]), 2); } // i if (total == 0) { return 1e100; } // if return total; } void DrawRays() { for (int i = 0; i < kNtheta; i++) { TObjArray* focused = gArray[i]->GetFocused(); for (Int_t j = 0; j <= focused->GetLast(); j++) { ARay* ray = (ARay*)(*focused)[j]; TPolyLine3D* pol = ray->MakePolyLine3D(); pol->SetLineColor(i + 2); pol->Draw(); } // j } // i } void DrawPSF() { TCanvas* can = new TCanvas("can", "can", 1200, 400); can->Divide(3, 1, 1e-10, 1e-10); TGraph* graph[kNtheta]; for (int i = 0; i < kNtheta; i++) { TH2D tmp("", "", 1, 0, 0, 1, 0, 0); TObjArray* focused = gArray[i]->GetFocused(); for (Int_t j = 0; j <= focused->GetLast(); j++) { ARay* ray = (ARay*)(*focused)[j]; Double_t p[4]; ray->GetLastPoint(p); tmp.Fill(p[0], p[1]); } // j double meany = tmp.GetMean(2); graph[i] = new TGraph(); for (Int_t j = 0; j <= focused->GetLast(); j++) { ARay* ray = (ARay*)(*focused)[j]; Double_t p[4]; ray->GetLastPoint(p); graph[i]->SetPoint(j, p[0] / um, (p[1] - meany) / um); } // j can->cd(i + 1); gPad->DrawFrame(-300, -300, 300, 300, Form("%.1f (deg);X (#it{#mu}m);Y (#it{#mu}m)", kTheta[i])); graph[i]->SetMarkerColor(2); graph[i]->SetMarkerStyle(5); graph[i]->SetMarkerSize(0.5); graph[i]->Draw("p same"); } // i } void Optimize() { ROOT::Minuit2::Minuit2Minimizer min2; min2.SetMaxFunctionCalls(1000000); min2.SetMaxIterations(100000); min2.SetTolerance(0.001); ROOT::Math::Functor f(&Func, 3); double step[3] = {0.01, 0.01, 0.01}; double par[3] = {3 * mm, -1 / (50 * mm), 0.}; double pmin[3] = {1 * mm, -1 / (20 * mm), -3}; double pmax[3] = {5 * mm, -1 / (100 * mm), 1}; min2.SetFunction(f); min2.SetLimitedVariable(0, "thickness", par[0], step[0], pmin[0], pmax[0]); min2.SetLimitedVariable(1, "curvature", par[1], step[1], pmin[1], pmax[1]); min2.SetLimitedVariable(2, "conic constant", par[2], step[2], pmin[2], pmax[2]); min2.Minimize(); const double* x = min2.X(); std::cout << "Thickness = " << x[0] / mm << " (mm)\n"; std::cout << "Raduis = " << (1 / x[1]) / mm << " (mm)\n"; std::cout << "Conic = " << x[2] << "\n"; DrawPSF(); gPad = 0; gOpticsManager->GetTopVolume()->Draw("ogl"); DrawRays(); } <commit_msg>Set the extinction coefficients of N-BK7 to zero (NULL) to avoid minimization failure probably due to internal photon absorption.<commit_after>// This tutorial shows how to optimize a lens shape by using the ROOT Minuite2 // optimization engine. #include "Math/Functor.h" #include "Minuit2/Minuit2Minimizer.h" #include "TCanvas.h" #include "TGeoBBox.h" #include "TGeoMatrix.h" #include "TGeoPhysicalNode.h" #include "TH2D.h" #include "AFocalSurface.h" #include "AGeoAsphericDisk.h" #include "AGlassCatalog.h" #include "ALens.h" #include "AMirror.h" #include "AOpticsManager.h" #include "ARayArray.h" #include "ARayShooter.h" static const Double_t mm = AOpticsManager::mm(); static const Double_t um = AOpticsManager::um(); static const Double_t nm = AOpticsManager::nm(); static AOpticsManager* gOpticsManager = 0; static const int kNtheta = 3; static ARayArray* gArray[kNtheta] = {0, 0, 0}; static double kTheta[kNtheta] = {0., 2.5, 5.0}; static const int kNlambda = 3; static const double kRadius = 5.0 * mm; double GetSpotSize(ARayArray* array) { // Returns standard deviation of a spot TObjArray* focused = array->GetFocused(); TH2D h("", "", 1, 0, 0, 1, 0, 0); for (int i = 0; i < focused->GetLast(); i++) { ARay* ray = (ARay*)(*focused)[i]; double p[4]; ray->GetLastPoint(p); h.Fill(p[0], p[1]); } // i double sx = h.GetStdDev(1); double sy = h.GetStdDev(2); return TMath::Sqrt(sx * sx + sy * sy); } int Nphotons(ARayArray* array) { int total = 0; total += array->GetFocused()->GetLast() + 1; total += array->GetStopped()->GetLast() + 1; total += array->GetSuspended()->GetLast() + 1; total += array->GetAbsorbed()->GetLast() + 1; return total; } double Func(const double* par) { static bool initialized = kFALSE; static TGeoRotation rot[kNtheta]; static TGeoTranslation tr("tr", 0, 0, -3 * mm); if (!initialized) { for (int i = 0; i < kNtheta; i++) { rot[i] = TGeoRotation(); rot[i].SetAngles(0, kTheta[i], 0.); } // i initialized = kTRUE; } // if if (gOpticsManager) { delete gOpticsManager; } // if gOpticsManager = new AOpticsManager("manager", "manager"); gOpticsManager->DisableFresnelReflection(kTRUE); // Make the world TGeoBBox* box = new TGeoBBox("box", 100 * mm, 100 * mm, 100 * mm); AOpticalComponent* top = new AOpticalComponent("top", box); gOpticsManager->SetTopVolume(top); AGeoAsphericDisk* disk = new AGeoAsphericDisk("disk", 0 * mm, 0., par[0], par[1], kRadius, 0. * mm); disk->SetConicConstants(0, par[2]); double f1 = disk->CalcF1(kRadius); double f2 = disk->CalcF2(kRadius); if (f2 - f1 < 0) { // negative edge thickness return 1e100; } // if ALens* lens = new ALens("lens", disk); AGlassCatalog schott("../misc/schottzemax-20180601.agf"); auto bk7 = schott.GetRefractiveIndex("N-BK7"); // Temporarily remove the coefficients because the optimization does not // converge well when they are non-zero, resulting in random internal // absorption in the lens. A better workaround is needed. bk7->SetExtinctionCoefficient(0); lens->SetRefractiveIndex(bk7); gOpticsManager->GetTopVolume()->AddNode(lens, 1); double origin[3] = {0, 0, 50 * mm + 1 * um}; TGeoBBox* box2 = new TGeoBBox("box2", 10 * mm, 10 * mm, 1 * um, origin); AFocalSurface* screen = new AFocalSurface("screen", box2); top->AddNode(screen, 1); AGeoAsphericDisk* disk2 = new AGeoAsphericDisk("disk2", 0 * mm, 0., par[0], 0., kRadius * 1.2, kRadius); AObscuration* obs = new AObscuration("obs", disk2); gOpticsManager->GetTopVolume()->AddNode(obs, 1); gOpticsManager->CloseGeometry(); double total = 0.; for (int i = 0; i < kNtheta; i++) { if (gArray[i]) { delete gArray[i]; gArray[i] = 0; } // if const double kLambda = 587.6 * nm; gArray[i] = ARayShooter::Circle(kLambda, kRadius * 1.1, 20, 10, &rot[i], &tr); gOpticsManager->TraceNonSequential(gArray[i]); total += TMath::Power(GetSpotSize(gArray[i]), 2); } // i if (total == 0) { return 1e100; } // if return total; } void DrawRays() { for (int i = 0; i < kNtheta; i++) { TObjArray* focused = gArray[i]->GetFocused(); for (Int_t j = 0; j <= focused->GetLast(); j++) { ARay* ray = (ARay*)(*focused)[j]; TPolyLine3D* pol = ray->MakePolyLine3D(); pol->SetLineColor(i + 2); pol->Draw(); } // j } // i } void DrawPSF() { TCanvas* can = new TCanvas("can", "can", 1200, 400); can->Divide(3, 1, 1e-10, 1e-10); TGraph* graph[kNtheta]; for (int i = 0; i < kNtheta; i++) { TH2D tmp("", "", 1, 0, 0, 1, 0, 0); TObjArray* focused = gArray[i]->GetFocused(); for (Int_t j = 0; j <= focused->GetLast(); j++) { ARay* ray = (ARay*)(*focused)[j]; Double_t p[4]; ray->GetLastPoint(p); tmp.Fill(p[0], p[1]); } // j double meany = tmp.GetMean(2); graph[i] = new TGraph(); for (Int_t j = 0; j <= focused->GetLast(); j++) { ARay* ray = (ARay*)(*focused)[j]; Double_t p[4]; ray->GetLastPoint(p); graph[i]->SetPoint(j, p[0] / um, (p[1] - meany) / um); } // j can->cd(i + 1); gPad->DrawFrame(-300, -300, 300, 300, Form("%.1f (deg);X (#it{#mu}m);Y (#it{#mu}m)", kTheta[i])); graph[i]->SetMarkerColor(2); graph[i]->SetMarkerStyle(5); graph[i]->SetMarkerSize(0.5); graph[i]->Draw("p same"); } // i } void Optimize() { ROOT::Minuit2::Minuit2Minimizer min2; min2.SetMaxFunctionCalls(1000000); min2.SetMaxIterations(100000); min2.SetTolerance(0.001); ROOT::Math::Functor f(&Func, 3); double step[3] = {0.01, 0.01, 0.01}; double par[3] = {3 * mm, -1 / (50 * mm), 0.}; double pmin[3] = {1 * mm, -1 / (20 * mm), -3}; double pmax[3] = {5 * mm, -1 / (100 * mm), 1}; min2.SetFunction(f); min2.SetLimitedVariable(0, "thickness", par[0], step[0], pmin[0], pmax[0]); min2.SetLimitedVariable(1, "curvature", par[1], step[1], pmin[1], pmax[1]); min2.SetLimitedVariable(2, "conic constant", par[2], step[2], pmin[2], pmax[2]); min2.Minimize(); const double* x = min2.X(); std::cout << "Thickness = " << x[0] / mm << " (mm)\n"; std::cout << "Raduis = " << (1 / x[1]) / mm << " (mm)\n"; std::cout << "Conic = " << x[2] << "\n"; DrawPSF(); gPad = 0; gOpticsManager->GetTopVolume()->Draw("ogl"); DrawRays(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestImageDataInterpolation.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME TestImageDataInterpolation.cxx -- Test interpolation from image data // // .SECTION Description // This test applies a function, F(x,y,z), to the image data and tests the // interpolation. #include "vtkDebugLeaks.h" #include "vtkImageData.h" #include "vtkSmartPointer.h" #include "vtkPoints.h" #include "vtkDoubleArray.h" #include "vtkIdList.h" #include "vtkPointData.h" #include "vtkCell.h" #include <cassert> #include <cmath> #include <limits> // Description: // Performs safe division a/b which also checks for underflow & overflow double SafeDiv( const double a, const double b ) { // Catch overflow if( (b < 1) && (a > ( b*std::numeric_limits<double>::max() ) ) ) return std::numeric_limits<double>::max(); // Catch underflow if( (a == static_cast<double>(0.0)) || ( (b > 1) && (a < b*std::numeric_limits<double>::max() ) ) ) return( static_cast<double>( 0.0 ) ); return( a/b ); } // Description: // Checks if two given floating numbers are equivalent. // This algorithm is based on Knuth, The of Computer Programming (vol II). bool eq( double a, double b, double TOL=1e-9 ) { double adiff = std::abs( a-b ); double d1 = SafeDiv( adiff,std::abs(a) ); double d2 = SafeDiv( adiff,std::abs(b) ); if( (d1 <= TOL) || (d2 <= TOL) ) return true; return false; } // Description: // Applies the function to the point with the given coordinates. // The function is defined as F(x,y,z)= x + y + z inline double F( const double x, const double y, const double z ) { return( (x+y+z) ); } // Description: // Returns the grid with the specified extent, origin and spacing. inline vtkImageData* GetGrid( int dims[3], double origin[3], double h[3] ) { vtkImageData *image = vtkImageData::New(); assert( "pre: image data is NULL!" && (image != NULL) ); image->SetDimensions( dims ); image->SetOrigin( origin ); image->SetSpacing( h ); vtkPointData *PD = image->GetPointData(); assert( "pre: point-data is NULL" && (PD != NULL) ); vtkDoubleArray *dataArray = vtkDoubleArray::New(); dataArray->SetName( "Fx" ); dataArray->SetNumberOfTuples( image->GetNumberOfPoints() ); dataArray->SetNumberOfComponents( 1 ); vtkIdType idx = 0; for( ; idx < image->GetNumberOfPoints(); ++idx ) { double pnt[3]; image->GetPoint(idx, pnt); dataArray->SetComponent( idx, 0, F(pnt[0],pnt[1],pnt[2]) ); } // END for all points PD->AddArray( dataArray ); dataArray->Delete(); return( image ); } // Description: // Given the image data this method returns a list of test points for // interpolation at each cell center. inline vtkPoints* GetReceivePoints( vtkImageData *img, vtkIdList* donorCellList) { vtkPoints *rcvPoints = vtkPoints::New(); rcvPoints->SetNumberOfPoints( img->GetNumberOfCells() ); donorCellList->SetNumberOfIds( img->GetNumberOfCells() ); vtkIdType cellIdx = 0; for( ; cellIdx < img->GetNumberOfCells(); ++cellIdx ) { // Get cell vtkCell *myCell = img->GetCell( cellIdx ); assert( "pre: myCell != NULL" && (myCell != NULL) ); // Compute center double c[3]; double pCenter[3]; double *weights = new double[ myCell->GetNumberOfPoints() ]; int subId = myCell->GetParametricCenter( pCenter ); myCell->EvaluateLocation( subId,pCenter,c,weights ); delete [] weights; // Insert center to point list donorCellList->SetId( cellIdx, cellIdx ); rcvPoints->SetPoint( cellIdx, c ); } // END for all cells return( rcvPoints ); } // Description: // Given the mesh data, the donor cell and the interpolation weights, this // method returns the interpolated value at the corresponding point location. inline double InterpolateValue(vtkImageData *img, vtkCell *c, double* w) { assert( "pre: image is NULL!" && (img != NULL) ); assert( "pre: donor cell is NULL" && (c != NULL) ); assert( "pre: weights is NULL" && (w != NULL) ); vtkPointData *PD = img->GetPointData(); assert( "pre: point data is NULL" && (PD != NULL) ); vtkDataArray *dataArray = PD->GetArray( "Fx" ); assert( "pre: data array is NULL" ); std::cout << "W:["; std::cout.flush(); double val = 0.0; vtkIdType numNodes = c->GetNumberOfPoints(); for( vtkIdType nodeIdx=0; nodeIdx < numNodes; ++nodeIdx ) { std::cout << w[ nodeIdx ] << " "; std::cout.flush(); vtkIdType meshNodeIdx = c->GetPointId( nodeIdx ); val += w[nodeIdx]*dataArray->GetComponent( meshNodeIdx, 0 ); } // END for all cells nodes std::cout << "]\n"; std::cout.flush(); return( val ); } // Description: // Main test routine for testing the interpolation inline int TestInterpolation( int dims[3], double origin[3], double h[3] ) { vtkImageData *grid = GetGrid( dims, origin, h ); assert( "pre: grid is NULL" && (grid != NULL) ); std::cout << "NUMBER OF CELLS: " << grid->GetNumberOfCells() << std::endl; std::cout.flush(); vtkIdList *donors = vtkIdList::New(); vtkPoints *pnts = GetReceivePoints( grid, donors ); int subId = 0; double pcoords[3]; double weights[8]; double x[3]; int interpErrors = 0; vtkIdType idx = 0; for( ; idx < pnts->GetNumberOfPoints(); ++idx ) { pnts->GetPoint( idx, x ); vtkIdType cellIdx = grid->FindCell(x,NULL,0,0.0,subId,pcoords,weights); if( cellIdx < 0 ) { std::cerr << "point (" << x[0] << ", " << x[1] << ", " << x[2]; std::cerr << ") is out-of-bounds!\n"; return 1; } vtkCell *donorCell = grid->GetCell( cellIdx ); assert( "pre: donor cell is NULL" && (donorCell != NULL)); std::cout << "N: [" << pcoords[0] << " "; std::cout << pcoords[1] << " " << pcoords[2] << "]\n"; std::cout.flush(); double f = InterpolateValue( grid, donorCell, weights ); double fExpected = F( x[0],x[1],x[2] ); if( !eq( f, fExpected ) ) { std::cout << "INTERPOLATION ERROR: "; std::cout << "f_expeted=" << fExpected << " "; std::cout << "f_interp=" << f << std::endl; std::cout.flush(); ++ interpErrors; } } // END for all points grid->Delete(); donors->Delete(); pnts->Delete(); return interpErrors; } // Description: // Test main function int TestImageDataInterpolation(int, char *[]) { static int dims[4][3]={ {3,3,1}, // XY Plane {3,1,3}, // XZ Plane {1,3,3}, // YZ Plane {3,3,3} // XYZ Volume }; static char* TestName[4]={ "XY-Plane", "XZ-Plane", "YZ-Plane", "XYZ-Grid" }; double origin[3]; origin[0] = origin[1] = origin[2] = 0.0; double h[3]; h[0] = h[1] = h[2] = 0.2; int testStatus = 0; for( int i=0; i < 4; ++i ) { std::cout << "Testing " << TestName[ i ] << "...\n"; std::cout.flush(); int rc = 0; rc = TestInterpolation( dims[i], origin, h ); testStatus += rc; std::cout << "[DONE]\n"; std::cout.flush(); if( rc != 0 ) { std::cout << rc << " failures detected!\n"; std::cout << "TEST FAILED!\n\n"; std::cout.flush(); } else { std::cout << "TEST PASSED!\n"; std::cout << std::endl; } } // END for all tests return( testStatus ); } <commit_msg>COMP: Fix warning in TestImageDataInterpolation.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestImageDataInterpolation.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME TestImageDataInterpolation.cxx -- Test interpolation from image data // // .SECTION Description // This test applies a function, F(x,y,z), to the image data and tests the // interpolation. #include "vtkDebugLeaks.h" #include "vtkImageData.h" #include "vtkSmartPointer.h" #include "vtkPoints.h" #include "vtkDoubleArray.h" #include "vtkIdList.h" #include "vtkPointData.h" #include "vtkCell.h" #include <cassert> #include <cmath> #include <limits> // Description: // Performs safe division a/b which also checks for underflow & overflow double SafeDiv( const double a, const double b ) { // Catch overflow if( (b < 1) && (a > ( b*std::numeric_limits<double>::max() ) ) ) return std::numeric_limits<double>::max(); // Catch underflow if( (a == static_cast<double>(0.0)) || ( (b > 1) && (a < b*std::numeric_limits<double>::max() ) ) ) return( static_cast<double>( 0.0 ) ); return( a/b ); } // Description: // Checks if two given floating numbers are equivalent. // This algorithm is based on Knuth, The of Computer Programming (vol II). bool eq( double a, double b, double TOL=1e-9 ) { double adiff = std::abs( a-b ); double d1 = SafeDiv( adiff,std::abs(a) ); double d2 = SafeDiv( adiff,std::abs(b) ); if( (d1 <= TOL) || (d2 <= TOL) ) return true; return false; } // Description: // Applies the function to the point with the given coordinates. // The function is defined as F(x,y,z)= x + y + z inline double F( const double x, const double y, const double z ) { return( (x+y+z) ); } // Description: // Returns the grid with the specified extent, origin and spacing. inline vtkImageData* GetGrid( int dims[3], double origin[3], double h[3] ) { vtkImageData *image = vtkImageData::New(); assert( "pre: image data is NULL!" && (image != NULL) ); image->SetDimensions( dims ); image->SetOrigin( origin ); image->SetSpacing( h ); vtkPointData *PD = image->GetPointData(); assert( "pre: point-data is NULL" && (PD != NULL) ); vtkDoubleArray *dataArray = vtkDoubleArray::New(); dataArray->SetName( "Fx" ); dataArray->SetNumberOfTuples( image->GetNumberOfPoints() ); dataArray->SetNumberOfComponents( 1 ); vtkIdType idx = 0; for( ; idx < image->GetNumberOfPoints(); ++idx ) { double pnt[3]; image->GetPoint(idx, pnt); dataArray->SetComponent( idx, 0, F(pnt[0],pnt[1],pnt[2]) ); } // END for all points PD->AddArray( dataArray ); dataArray->Delete(); return( image ); } // Description: // Given the image data this method returns a list of test points for // interpolation at each cell center. inline vtkPoints* GetReceivePoints( vtkImageData *img, vtkIdList* donorCellList) { vtkPoints *rcvPoints = vtkPoints::New(); rcvPoints->SetNumberOfPoints( img->GetNumberOfCells() ); donorCellList->SetNumberOfIds( img->GetNumberOfCells() ); vtkIdType cellIdx = 0; for( ; cellIdx < img->GetNumberOfCells(); ++cellIdx ) { // Get cell vtkCell *myCell = img->GetCell( cellIdx ); assert( "pre: myCell != NULL" && (myCell != NULL) ); // Compute center double c[3]; double pCenter[3]; double *weights = new double[ myCell->GetNumberOfPoints() ]; int subId = myCell->GetParametricCenter( pCenter ); myCell->EvaluateLocation( subId,pCenter,c,weights ); delete [] weights; // Insert center to point list donorCellList->SetId( cellIdx, cellIdx ); rcvPoints->SetPoint( cellIdx, c ); } // END for all cells return( rcvPoints ); } // Description: // Given the mesh data, the donor cell and the interpolation weights, this // method returns the interpolated value at the corresponding point location. inline double InterpolateValue(vtkImageData *img, vtkCell *c, double* w) { assert( "pre: image is NULL!" && (img != NULL) ); assert( "pre: donor cell is NULL" && (c != NULL) ); assert( "pre: weights is NULL" && (w != NULL) ); vtkPointData *PD = img->GetPointData(); assert( "pre: point data is NULL" && (PD != NULL) ); vtkDataArray *dataArray = PD->GetArray( "Fx" ); assert( "pre: data array is NULL" ); std::cout << "W:["; std::cout.flush(); double val = 0.0; vtkIdType numNodes = c->GetNumberOfPoints(); for( vtkIdType nodeIdx=0; nodeIdx < numNodes; ++nodeIdx ) { std::cout << w[ nodeIdx ] << " "; std::cout.flush(); vtkIdType meshNodeIdx = c->GetPointId( nodeIdx ); val += w[nodeIdx]*dataArray->GetComponent( meshNodeIdx, 0 ); } // END for all cells nodes std::cout << "]\n"; std::cout.flush(); return( val ); } // Description: // Main test routine for testing the interpolation inline int TestInterpolation( int dims[3], double origin[3], double h[3] ) { vtkImageData *grid = GetGrid( dims, origin, h ); assert( "pre: grid is NULL" && (grid != NULL) ); std::cout << "NUMBER OF CELLS: " << grid->GetNumberOfCells() << std::endl; std::cout.flush(); vtkIdList *donors = vtkIdList::New(); vtkPoints *pnts = GetReceivePoints( grid, donors ); int subId = 0; double pcoords[3]; double weights[8]; double x[3]; int interpErrors = 0; vtkIdType idx = 0; for( ; idx < pnts->GetNumberOfPoints(); ++idx ) { pnts->GetPoint( idx, x ); vtkIdType cellIdx = grid->FindCell(x,NULL,0,0.0,subId,pcoords,weights); if( cellIdx < 0 ) { std::cerr << "point (" << x[0] << ", " << x[1] << ", " << x[2]; std::cerr << ") is out-of-bounds!\n"; return 1; } vtkCell *donorCell = grid->GetCell( cellIdx ); assert( "pre: donor cell is NULL" && (donorCell != NULL)); std::cout << "N: [" << pcoords[0] << " "; std::cout << pcoords[1] << " " << pcoords[2] << "]\n"; std::cout.flush(); double f = InterpolateValue( grid, donorCell, weights ); double fExpected = F( x[0],x[1],x[2] ); if( !eq( f, fExpected ) ) { std::cout << "INTERPOLATION ERROR: "; std::cout << "f_expeted=" << fExpected << " "; std::cout << "f_interp=" << f << std::endl; std::cout.flush(); ++ interpErrors; } } // END for all points grid->Delete(); donors->Delete(); pnts->Delete(); return interpErrors; } // Description: // Test main function int TestImageDataInterpolation(int, char *[]) { static int dims[4][3]={ {3,3,1}, // XY Plane {3,1,3}, // XZ Plane {1,3,3}, // YZ Plane {3,3,3} // XYZ Volume }; static const char* TestName[4]={ "XY-Plane", "XZ-Plane", "YZ-Plane", "XYZ-Grid" }; double origin[3]; origin[0] = origin[1] = origin[2] = 0.0; double h[3]; h[0] = h[1] = h[2] = 0.2; int testStatus = 0; for( int i=0; i < 4; ++i ) { std::cout << "Testing " << TestName[ i ] << "...\n"; std::cout.flush(); int rc = 0; rc = TestInterpolation( dims[i], origin, h ); testStatus += rc; std::cout << "[DONE]\n"; std::cout.flush(); if( rc != 0 ) { std::cout << rc << " failures detected!\n"; std::cout << "TEST FAILED!\n\n"; std::cout.flush(); } else { std::cout << "TEST PASSED!\n"; std::cout << std::endl; } } // END for all tests return( testStatus ); } <|endoftext|>
<commit_before>#include "StdAfx.h" #include "MrwDecoder.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post Copyright (C) 2014-2015 Pedro Côrte-Real This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ namespace RawSpeed { MrwDecoder::MrwDecoder(FileMap* file) : RawDecoder(file) { tiff_meta = NULL; parseHeader(); } MrwDecoder::~MrwDecoder(void) { if (tiff_meta) delete tiff_meta; } int MrwDecoder::isMRW(FileMap* input) { if (input->getSize() < 30) { return false; } const uchar8* data = input->getData(0); return data[0] == 0x00 && data[1] == 0x4D && data[2] == 0x52 && data[3] == 0x4D; } void MrwDecoder::parseHeader() { const unsigned char* data = mFile->getData(0); if (mFile->getSize() < 30) ThrowRDE("Not a valid MRW file (size too small)"); if (!isMRW(mFile)) ThrowRDE("This isn't actually a MRW file, why are you calling me?"); data_offset = get4BE(data,4)+8; if (!mFile->isValid(data_offset)) ThrowRDE("MRW: Data offset is invalid"); // Make sure all values have at least been initialized raw_width = raw_height = packed = 0; wb_coeffs[0] = wb_coeffs[1] = wb_coeffs[2] = wb_coeffs[3] = NAN; uint32 currpos = 8; while (currpos < data_offset) { uint32 tag = get4BE(data,currpos); uint32 len = get4BE(data,currpos+4); switch(tag) { case 0x505244: // PRD raw_height = get2BE(data,currpos+16); raw_width = get2BE(data,currpos+18); packed = (data[currpos+24] == 12); case 0x574247: // WBG for(uint32 i=0; i<4; i++) wb_coeffs[i] = get2BE(data, currpos+12+i*2); break; case 0x545457: // TTW // Base value for offsets needs to be at the beginning of the TIFF block, not the file FileMap *f = new FileMap(mFile->getDataWrt(currpos+8), mFile->getSize()-currpos-8); if (little == getHostEndianness()) tiff_meta = new TiffIFDBE(f, 8); else tiff_meta = new TiffIFD(f, 8); delete f; break; } currpos += MAX(len+8,1); // MAX(,1) to make sure we make progress } } RawImage MrwDecoder::decodeRawInternal() { uint32 imgsize; mRaw->dim = iPoint2D(raw_width, raw_height); mRaw->createData(); if (packed) imgsize = raw_width * raw_height * 3 / 2; else imgsize = raw_width * raw_height * 2; if (!mFile->isValid(data_offset)) ThrowRDE("MRW decoder: Data offset after EOF, file probably truncated"); if (!mFile->isValid(data_offset+imgsize-1)) ThrowRDE("MRW decoder: Image end after EOF, file probably truncated"); ByteStream input(mFile->getData(data_offset), imgsize); try { if (packed) Decode12BitRawBE(input, raw_width, raw_height); else Decode12BitRawBEunpacked(input, raw_width, raw_height); } catch (IOException &e) { mRaw->setError(e.what()); // Let's ignore it, it may have delivered somewhat useful data. } return mRaw; } void MrwDecoder::checkSupportInternal(CameraMetaData *meta) { if (!tiff_meta->hasEntry(MAKE) || !tiff_meta->hasEntry(MODEL)) ThrowRDE("MRW: Couldn't find make and model"); string make = tiff_meta->getEntry(MAKE)->getString(); string model = tiff_meta->getEntry(MODEL)->getString(); this->checkCameraSupported(meta, make, model, ""); } void MrwDecoder::decodeMetaDataInternal(CameraMetaData *meta) { //Default int iso = 0; if (!tiff_meta->hasEntry(MAKE) || !tiff_meta->hasEntry(MODEL)) ThrowRDE("MRW: Couldn't find make and model"); string make = tiff_meta->getEntry(MAKE)->getString(); string model = tiff_meta->getEntry(MODEL)->getString(); setMetaData(meta, make, model, "", iso); if (hints.find("swapped_wb") != hints.end()) { mRaw->metadata.wbCoeffs[0] = (float) wb_coeffs[2]; mRaw->metadata.wbCoeffs[1] = (float) wb_coeffs[0]; mRaw->metadata.wbCoeffs[2] = (float) wb_coeffs[1]; } else { mRaw->metadata.wbCoeffs[0] = (float) wb_coeffs[0]; mRaw->metadata.wbCoeffs[1] = (float) wb_coeffs[1]; mRaw->metadata.wbCoeffs[2] = (float) wb_coeffs[3]; } } } // namespace RawSpeed <commit_msg>Explicitly cast to float.<commit_after>#include "StdAfx.h" #include "MrwDecoder.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post Copyright (C) 2014-2015 Pedro Côrte-Real This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ namespace RawSpeed { MrwDecoder::MrwDecoder(FileMap* file) : RawDecoder(file) { tiff_meta = NULL; parseHeader(); } MrwDecoder::~MrwDecoder(void) { if (tiff_meta) delete tiff_meta; } int MrwDecoder::isMRW(FileMap* input) { if (input->getSize() < 30) { return false; } const uchar8* data = input->getData(0); return data[0] == 0x00 && data[1] == 0x4D && data[2] == 0x52 && data[3] == 0x4D; } void MrwDecoder::parseHeader() { const unsigned char* data = mFile->getData(0); if (mFile->getSize() < 30) ThrowRDE("Not a valid MRW file (size too small)"); if (!isMRW(mFile)) ThrowRDE("This isn't actually a MRW file, why are you calling me?"); data_offset = get4BE(data,4)+8; if (!mFile->isValid(data_offset)) ThrowRDE("MRW: Data offset is invalid"); // Make sure all values have at least been initialized raw_width = raw_height = packed = 0; wb_coeffs[0] = wb_coeffs[1] = wb_coeffs[2] = wb_coeffs[3] = NAN; uint32 currpos = 8; while (currpos < data_offset) { uint32 tag = get4BE(data,currpos); uint32 len = get4BE(data,currpos+4); switch(tag) { case 0x505244: // PRD raw_height = get2BE(data,currpos+16); raw_width = get2BE(data,currpos+18); packed = (data[currpos+24] == 12); case 0x574247: // WBG for(uint32 i=0; i<4; i++) wb_coeffs[i] = (float)get2BE(data, currpos+12+i*2); break; case 0x545457: // TTW // Base value for offsets needs to be at the beginning of the TIFF block, not the file FileMap *f = new FileMap(mFile->getDataWrt(currpos+8), mFile->getSize()-currpos-8); if (little == getHostEndianness()) tiff_meta = new TiffIFDBE(f, 8); else tiff_meta = new TiffIFD(f, 8); delete f; break; } currpos += MAX(len+8,1); // MAX(,1) to make sure we make progress } } RawImage MrwDecoder::decodeRawInternal() { uint32 imgsize; mRaw->dim = iPoint2D(raw_width, raw_height); mRaw->createData(); if (packed) imgsize = raw_width * raw_height * 3 / 2; else imgsize = raw_width * raw_height * 2; if (!mFile->isValid(data_offset)) ThrowRDE("MRW decoder: Data offset after EOF, file probably truncated"); if (!mFile->isValid(data_offset+imgsize-1)) ThrowRDE("MRW decoder: Image end after EOF, file probably truncated"); ByteStream input(mFile->getData(data_offset), imgsize); try { if (packed) Decode12BitRawBE(input, raw_width, raw_height); else Decode12BitRawBEunpacked(input, raw_width, raw_height); } catch (IOException &e) { mRaw->setError(e.what()); // Let's ignore it, it may have delivered somewhat useful data. } return mRaw; } void MrwDecoder::checkSupportInternal(CameraMetaData *meta) { if (!tiff_meta->hasEntry(MAKE) || !tiff_meta->hasEntry(MODEL)) ThrowRDE("MRW: Couldn't find make and model"); string make = tiff_meta->getEntry(MAKE)->getString(); string model = tiff_meta->getEntry(MODEL)->getString(); this->checkCameraSupported(meta, make, model, ""); } void MrwDecoder::decodeMetaDataInternal(CameraMetaData *meta) { //Default int iso = 0; if (!tiff_meta->hasEntry(MAKE) || !tiff_meta->hasEntry(MODEL)) ThrowRDE("MRW: Couldn't find make and model"); string make = tiff_meta->getEntry(MAKE)->getString(); string model = tiff_meta->getEntry(MODEL)->getString(); setMetaData(meta, make, model, "", iso); if (hints.find("swapped_wb") != hints.end()) { mRaw->metadata.wbCoeffs[0] = (float) wb_coeffs[2]; mRaw->metadata.wbCoeffs[1] = (float) wb_coeffs[0]; mRaw->metadata.wbCoeffs[2] = (float) wb_coeffs[1]; } else { mRaw->metadata.wbCoeffs[0] = (float) wb_coeffs[0]; mRaw->metadata.wbCoeffs[1] = (float) wb_coeffs[1]; mRaw->metadata.wbCoeffs[2] = (float) wb_coeffs[3]; } } } // namespace RawSpeed <|endoftext|>
<commit_before><commit_msg>[AArch64] fix an issue with older /proc/cpuinfo layout<commit_after><|endoftext|>
<commit_before>#include "StdAfx.h" #include "RawDecoder.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009 Klaus Post This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ RawDecoder::RawDecoder(FileMap* file) : mFile(file), mRaw(RawImage::create()) { } RawDecoder::~RawDecoder(void) { for (guint i = 0 ; i < errors.size(); i++) { free((void*)errors[i]); } errors.clear(); } void RawDecoder::readUncompressedRaw(ByteStream &input, iPoint2D& size, iPoint2D& offset, int inputPitch, int bitPerPixel, gboolean MSBOrder) { guchar* data = mRaw->getData(); guint outPitch = mRaw->pitch; guint w = size.x; guint h = size.y; guint cpp = mRaw->getCpp(); if (input.getRemainSize()< (inputPitch*h) ) { h = input.getRemainSize() / inputPitch - 1; } if (bitPerPixel>16) ThrowRDE("readUncompressedRaw: Unsupported bit depth"); guint skipBits = inputPitch - w*bitPerPixel/8; // Skip per line if (offset.y>mRaw->dim.y) ThrowRDE("readUncompressedRaw: Invalid y offset"); if (offset.x+size.x>mRaw->dim.x) ThrowRDE("readUncompressedRaw: Invalid x offset"); guint y = offset.y; h = MIN(h+(guint)offset.y,(guint)mRaw->dim.y); if (MSBOrder) { BitPumpMSB bits(&input); w *= cpp; for (; y < h; y++) { gushort* dest = (gushort*)&data[offset.x*sizeof(gushort)*cpp+y*outPitch]; for(guint x =0 ; x < w; x++) { guint b = bits.getBits(bitPerPixel); dest[x] = b; } bits.skipBits(skipBits); } } else { if (bitPerPixel==16) { BitBlt(&data[offset.x*sizeof(gushort)*cpp+y*outPitch],outPitch, input.getData(),inputPitch,w*mRaw->bpp,h-y); return; } BitPumpPlain bits(&input); w *= cpp; for (; y < h; y++) { gushort* dest = (gushort*)&data[offset.x*sizeof(gushort)+y*outPitch]; for(guint x =0 ; x < w; x++) { guint b = bits.getBits(bitPerPixel); dest[x] = b; } bits.skipBits(skipBits); } } } void RawDecoder::Decode12BitRaw(ByteStream &input, guint w, guint h) { guchar* data = mRaw->getData(); guint pitch = mRaw->pitch; const guchar *in = input.getData(); if (input.getRemainSize()< (w*h*3/2) ) { h = input.getRemainSize() / (w*3/2) - 1; } for (guint y=0; y < h; y++) { gushort* dest = (gushort*)&data[y*pitch]; for(guint x =0 ; x < w; x+=2) { guint g1 = *in++; guint g2 = *in++; dest[x] = g1 | ((g2&0xf)<<8); guint g3 = *in++; dest[x+1] = (g2>>4) | (g3<<4); } } } void RawDecoder::checkCameraSupported(CameraMetaData *meta, string make, string model, string mode) { TrimSpaces(make); TrimSpaces(model); Camera* cam = meta->getCamera(make, model, mode); if (!cam) { if (mode.length() == 0) printf("Unable to find camera in database: %s %s %s\n", make.c_str(), model.c_str(), mode.c_str()); return; // Assume true. } if (!cam->supported) ThrowRDE("Camera not supported (explicit). Sorry."); } void RawDecoder::setMetaData( CameraMetaData *meta, string make, string model, string mode ) { TrimSpaces(make); TrimSpaces(model); Camera *cam = meta->getCamera(make, model, mode); if (!cam) { printf("Unable to find camera in database: %s %s %s\n", make.c_str(), model.c_str(), mode.c_str()); return; } mRaw->subFrame(cam->cropPos, cam->cropSize); mRaw->cfa = cam->cfa; if (cam->cropPos.x & 1) mRaw->cfa.shiftLeft(); if (cam->cropPos.y & 1) mRaw->cfa.shiftDown(); mRaw->blackLevel = cam->black; mRaw->whitePoint = cam->white; } void RawDecoder::TrimSpaces( string& str) { // Trim Both leading and trailing spaces size_t startpos = str.find_first_not_of(" \t"); // Find the first character position after excluding leading blank spaces size_t endpos = str.find_last_not_of(" \t"); // Find the first character position from reverse af // if all spaces or empty return an empty string if(( string::npos == startpos ) || ( string::npos == endpos)) { str = ""; } else str = str.substr( startpos, endpos-startpos+1 ); } <commit_msg>Allow negative values in crop size to be used as relative crop values.<commit_after>#include "StdAfx.h" #include "RawDecoder.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009 Klaus Post This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ RawDecoder::RawDecoder(FileMap* file) : mFile(file), mRaw(RawImage::create()) { } RawDecoder::~RawDecoder(void) { for (guint i = 0 ; i < errors.size(); i++) { free((void*)errors[i]); } errors.clear(); } void RawDecoder::readUncompressedRaw(ByteStream &input, iPoint2D& size, iPoint2D& offset, int inputPitch, int bitPerPixel, gboolean MSBOrder) { guchar* data = mRaw->getData(); guint outPitch = mRaw->pitch; guint w = size.x; guint h = size.y; guint cpp = mRaw->getCpp(); if (input.getRemainSize()< (inputPitch*h) ) { h = input.getRemainSize() / inputPitch - 1; } if (bitPerPixel>16) ThrowRDE("readUncompressedRaw: Unsupported bit depth"); guint skipBits = inputPitch - w*bitPerPixel/8; // Skip per line if (offset.y>mRaw->dim.y) ThrowRDE("readUncompressedRaw: Invalid y offset"); if (offset.x+size.x>mRaw->dim.x) ThrowRDE("readUncompressedRaw: Invalid x offset"); guint y = offset.y; h = MIN(h+(guint)offset.y,(guint)mRaw->dim.y); if (MSBOrder) { BitPumpMSB bits(&input); w *= cpp; for (; y < h; y++) { gushort* dest = (gushort*)&data[offset.x*sizeof(gushort)*cpp+y*outPitch]; for(guint x =0 ; x < w; x++) { guint b = bits.getBits(bitPerPixel); dest[x] = b; } bits.skipBits(skipBits); } } else { if (bitPerPixel==16) { BitBlt(&data[offset.x*sizeof(gushort)*cpp+y*outPitch],outPitch, input.getData(),inputPitch,w*mRaw->bpp,h-y); return; } BitPumpPlain bits(&input); w *= cpp; for (; y < h; y++) { gushort* dest = (gushort*)&data[offset.x*sizeof(gushort)+y*outPitch]; for(guint x =0 ; x < w; x++) { guint b = bits.getBits(bitPerPixel); dest[x] = b; } bits.skipBits(skipBits); } } } void RawDecoder::Decode12BitRaw(ByteStream &input, guint w, guint h) { guchar* data = mRaw->getData(); guint pitch = mRaw->pitch; const guchar *in = input.getData(); if (input.getRemainSize()< (w*h*3/2) ) { h = input.getRemainSize() / (w*3/2) - 1; } for (guint y=0; y < h; y++) { gushort* dest = (gushort*)&data[y*pitch]; for(guint x =0 ; x < w; x+=2) { guint g1 = *in++; guint g2 = *in++; dest[x] = g1 | ((g2&0xf)<<8); guint g3 = *in++; dest[x+1] = (g2>>4) | (g3<<4); } } } void RawDecoder::checkCameraSupported(CameraMetaData *meta, string make, string model, string mode) { TrimSpaces(make); TrimSpaces(model); Camera* cam = meta->getCamera(make, model, mode); if (!cam) { if (mode.length() == 0) printf("Unable to find camera in database: %s %s %s\nPlease upload file to ftp.rawstudio.org, thanks!\n", make.c_str(), model.c_str(), mode.c_str()); return; // Assume true. } if (!cam->supported) ThrowRDE("Camera not supported (explicit). Sorry."); } void RawDecoder::setMetaData( CameraMetaData *meta, string make, string model, string mode ) { TrimSpaces(make); TrimSpaces(model); Camera *cam = meta->getCamera(make, model, mode); if (!cam) { printf("Unable to find camera in database: %s %s %s\n", make.c_str(), model.c_str(), mode.c_str()); return; } iPoint2D new_size = cam->cropSize; // If crop size is negative, use relative cropping if (new_size.x <= 0) new_size.x = mRaw->dim.x - cam->cropPos.x + new_size.x; if (new_size.y <= 0) new_size.y = mRaw->dim.y - cam->cropPos.y + new_size.y; mRaw->subFrame(cam->cropPos, new_size); mRaw->cfa = cam->cfa; // Shift CFA to match crop if (cam->cropPos.x & 1) mRaw->cfa.shiftLeft(); if (cam->cropPos.y & 1) mRaw->cfa.shiftDown(); mRaw->blackLevel = cam->black; mRaw->whitePoint = cam->white; } void RawDecoder::TrimSpaces( string& str) { // Trim Both leading and trailing spaces size_t startpos = str.find_first_not_of(" \t"); // Find the first character position after excluding leading blank spaces size_t endpos = str.find_last_not_of(" \t"); // Find the first character position from reverse af // if all spaces or empty return an empty string if(( string::npos == startpos ) || ( string::npos == endpos)) { str = ""; } else str = str.substr( startpos, endpos-startpos+1 ); } <|endoftext|>
<commit_before><commit_msg>Handle incorrect usage of uniform_real_distribution()<commit_after><|endoftext|>
<commit_before>/******************************************************************************\ * File: frame.cpp * Purpose: Implementation of wxExFrameWithHistory class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/config.h> #include <wx/tokenzr.h> #include <wx/extension/report/report.h> // The maximal number of files and projects to be supported. const int NUMBER_RECENT_FILES = 25; const int NUMBER_RECENT_PROJECTS = 25; const int ID_RECENT_PROJECT_LOWEST = wxID_FILE1 + NUMBER_RECENT_FILES + 1; BEGIN_EVENT_TABLE(wxExFrameWithHistory, wxExManagedFrame) EVT_CLOSE(wxExFrameWithHistory::OnClose) EVT_IDLE(wxExFrameWithHistory::OnIdle) EVT_MENU(wxID_OPEN, wxExFrameWithHistory::OnCommand) EVT_MENU(wxID_PREFERENCES, wxExFrameWithHistory::OnCommand) EVT_MENU(ID_TERMINATED_PROCESS, wxExFrameWithHistory::OnCommand) EVT_MENU_RANGE( wxID_FILE1, wxID_FILE1 + NUMBER_RECENT_FILES, wxExFrameWithHistory::OnCommand) EVT_MENU_RANGE( ID_RECENT_PROJECT_LOWEST, ID_RECENT_PROJECT_LOWEST + NUMBER_RECENT_PROJECTS, wxExFrameWithHistory::OnCommand) EVT_MENU_RANGE( ID_EXTENSION_REPORT_LOWEST, ID_EXTENSION_REPORT_HIGHEST, wxExFrameWithHistory::OnCommand) EVT_UPDATE_UI(ID_VIEW_STATUSBAR, wxExFrameWithHistory::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_TOOLBAR, wxExFrameWithHistory::OnUpdateUI) END_EVENT_TABLE() wxExFrameWithHistory::wxExFrameWithHistory(wxWindow* parent, wxWindowID id, const wxString& title, size_t maxFiles, size_t maxProjects, int style) : wxExManagedFrame(parent, id, title, style) , m_FileHistory(maxFiles, wxID_FILE1) , m_FileHistoryList(NULL) , m_ProjectHistory(maxProjects, ID_RECENT_PROJECT_LOWEST) , m_Process(NULL) { // There is only support for one history in the config. // We use file history for this, so update project history ourselves. // The order should be inverted, as the last one added is the most recent used. if (maxProjects > 0) { for (int i = m_ProjectHistory.GetMaxFiles() - 1 ; i >=0 ; i--) { SetRecentProject( wxConfigBase::Get()->Read(wxString::Format("RecentProject%d", i))); } } #ifdef wxExUSE_EMBEDDED_SQL wxExTool::Get()->AddInfo( ID_TOOL_SQL, _("Executed %ld SQL queries in"), wxExEllipsed(_("&SQL Query Run"))); wxExTool::Get()->AddInfo( ID_TOOL_REPORT_SQL, _("Reported %ld SQL queries in"), _("Report SQL &Query")); #endif } void wxExFrameWithHistory::DoRecent( wxFileHistory& history, int index, long flags) { if (history.GetCount() > 0) { const wxString file(history.GetHistoryFile(index)); if (!wxFileExists(file)) { history.RemoveFileFromHistory(index); wxLogMessage(_("Removed not existing file: %s from history"), file.c_str()); } else { OpenFile(file, 0, wxEmptyString, flags); } } } wxExListViewWithFrame* wxExFrameWithHistory::GetProject() { return (wxExListViewWithFrame*)GetFocusedListView(); } void wxExFrameWithHistory::OnClose(wxCloseEvent& event) { if (event.CanVeto()) { if (ProcessIsRunning()) { wxLogMessage(_("Process is running")); event.Veto(); return; } } wxDELETE(m_Process); m_FileHistory.Save(*wxConfigBase::Get()); for (size_t i = 0; i < m_ProjectHistory.GetCount(); i++) { wxConfigBase::Get()->Write( wxString::Format("RecentProject%d", i), m_ProjectHistory.GetHistoryFile(i)); } event.Skip(); } void wxExFrameWithHistory::OnCommand(wxCommandEvent& event) { if (event.GetId() >= wxID_FILE1 && event.GetId() <= wxID_FILE1 + NUMBER_RECENT_FILES) { DoRecent(m_FileHistory, event.GetId() - wxID_FILE1); } else if (event.GetId() >= ID_RECENT_PROJECT_LOWEST && event.GetId() <= ID_RECENT_PROJECT_LOWEST + NUMBER_RECENT_PROJECTS) { DoRecent(m_ProjectHistory, event.GetId() - ID_RECENT_PROJECT_LOWEST, wxExSTCWithFrame::STC_OPEN_IS_PROJECT); } else { switch (event.GetId()) { case wxID_OPEN: if (!event.GetString().empty()) { wxArrayString files; wxStringTokenizer tkz(event.GetString()); wxExSTC* stc = GetSTC(); while (tkz.HasMoreTokens()) { const wxString token = tkz.GetNextToken(); wxFileName file(token); if (file.IsRelative() && stc != NULL) { file.MakeAbsolute(stc->GetFileName().GetPath()); if (!file.FileExists()) { wxLogError(_("Cannot locate file") + ": " + token); } else { files.Add(file.GetFullPath()); } } else { files.Add(file.GetFullPath()); } } wxExOpenFiles(this, files); } else { wxExOpenFilesDialog(this); } break; case wxID_PREFERENCES: wxExSTC::ConfigDialog(this, _("Editor Options"), wxExSTC::STC_CONFIG_MODELESS | wxExSTC::STC_CONFIG_SIMPLE | wxExSTC::STC_CONFIG_WITH_APPLY, event.GetId()); break; case ID_PROJECT_SAVE: { wxExListViewWithFrame* project = GetProject(); if (project != NULL) { project->FileSave(); SetTitle(wxEmptyString, project->GetFileName().GetName()); } } break; case ID_SPECIAL_FIND_IN_FILES: wxExFindInFiles(this); break; case ID_SPECIAL_REPLACE_IN_FILES: wxExFindInFiles(this, true); break; case ID_TERMINATED_PROCESS: wxBell(); wxDELETE(m_Process); break; case ID_VIEW_STATUSBAR: GetStatusBar()->Show(!GetStatusBar()->IsShown()); SendSizeEvent(); break; case ID_VIEW_TOOLBAR: GetToolBar()->Show(!GetToolBar()->IsShown()); SendSizeEvent(); break; default: wxFAIL; } } } void wxExFrameWithHistory::OnIdle(wxIdleEvent& event) { event.Skip(); wxWindow* win = wxWindow::FindFocus(); if (win == NULL) return; wxExSTCWithFrame* editor = wxDynamicCast(win, wxExSTCWithFrame); wxExListViewWithFrame* project = wxDynamicCast(win, wxExListViewWithFrame); const wxString title(GetTitle()); const wxUniChar indicator('*'); if ((project != NULL && project->GetContentsChanged()) || (editor != NULL && editor->GetContentsChanged())) { // Project or editor changed, add indicator if not yet done. if (title.Last() != indicator) { wxFrame::SetTitle(title + " " + indicator); } } else { // Project or editor not changed, remove indicator if not yet done. if (title.Last() == indicator) { wxFrame::SetTitle(title.substr(0, title.length() - 2)); } } } void wxExFrameWithHistory::OnUpdateUI(wxUpdateUIEvent& event) { switch (event.GetId()) { case ID_VIEW_STATUSBAR: wxASSERT(GetStatusBar() != NULL); event.Check(GetStatusBar()->IsShown()); break; case ID_VIEW_TOOLBAR: wxASSERT(GetToolBar() != NULL) ; event.Check(GetToolBar()->IsShown()); break; default: wxFAIL; } } bool wxExFrameWithHistory::OpenFile( const wxExFileName& filename, int line_number, const wxString& match, long flags) { if (wxExManagedFrame::OpenFile(filename, line_number, match, flags)) { SetRecentFile(filename.GetFullPath()); return true; } return false; } bool wxExFrameWithHistory::ProcessIsRunning() const { return m_Process != NULL && wxProcess::Exists(m_Process->GetPid()); } bool wxExFrameWithHistory::ProcessRun(const wxString& command) { wxASSERT(m_Process == NULL); wxExListViewWithFrame* listview = Activate(wxExListViewWithFrame::LIST_PROCESS); if (listview == NULL) { wxFAIL; return false; } if ((m_Process = new wxExProcess(listview, command)) != NULL) { if (m_Process->Execute() <= 0) { wxDELETE(m_Process); return false; } else { return true; } } return false; } bool wxExFrameWithHistory::ProcessStop() { if (ProcessIsRunning()) { if (m_Process->Kill() == wxKILL_ERROR) { // Even if the process could not be killed, set it to NULL, as it is deleted. wxFAIL; m_Process = NULL; return false; } else { m_Process = NULL; return true; } } return true; } void wxExFrameWithHistory::SetRecentFile(const wxString& file) { if (!file.empty()) { m_FileHistory.AddFileToHistory(file); if (m_FileHistoryList != NULL) { wxExListItemWithFileName item(m_FileHistoryList, file); item.Insert((long)0); if (m_FileHistoryList->GetItemCount() > 1) { for (int i = m_FileHistoryList->GetItemCount() - 1; i >= 1 ; i--) { wxExListItemWithFileName item(m_FileHistoryList, i); if (item.GetFileName().GetFullPath() == file) { m_FileHistoryList->DeleteItem(i); } } } } } } void wxExFrameWithHistory::SetTitle( const wxString& file, const wxString& project) { // If one of the strings is empty, try to get a better string. wxString better_file(file); wxString better_project(project); if (better_file.empty()) { wxExSTC* stc = GetSTC(); if (stc != NULL) { better_file = stc->GetFileName().GetFullPath(); } } if (better_project.empty()) { wxExListViewWithFrame* lv = (wxExListViewWithFrame*)GetListView(); if (lv != NULL && lv->GetType() == wxExListViewWithFrame::LIST_PROJECT) { better_project = lv->GetFileName().GetName(); } } // And now update the title. if (better_file.empty() && better_project.empty()) { wxExFrame::SetTitle(wxTheApp->GetAppName()); } else { const wxString sep = (!better_file.empty() && !better_project.empty() ? wxString(" - "): wxString(wxEmptyString)); wxExFrame::SetTitle(better_file + sep + better_project); } } void wxExFrameWithHistory::UseFileHistory(wxWindowID id, wxMenu* menu) { UseHistory(id, menu, m_FileHistory); // We can load file history now. m_FileHistory.Load(*wxConfigBase::Get()); } void wxExFrameWithHistory::UseFileHistoryList(wxExListView* list) { m_FileHistoryList = list; m_FileHistoryList->Hide(); // Add all items from FileHistory. for (size_t i = 0; i < m_FileHistory.GetCount(); i++) { wxExListItemWithFileName item( m_FileHistoryList, m_FileHistory.GetHistoryFile(i)); item.Insert(); } } void wxExFrameWithHistory::UseHistory( wxWindowID id, wxMenu* menu, wxFileHistory& history) { wxMenu* submenu = new wxMenu; menu->Append(id, _("Open &Recent"), submenu); history.UseMenu(submenu); } void wxExFrameWithHistory::UseProjectHistory(wxWindowID id, wxMenu* menu) { UseHistory(id, menu, m_ProjectHistory); // And add the files to the menu. m_ProjectHistory.AddFilesToMenu(); } <commit_msg>simplified code<commit_after>/******************************************************************************\ * File: frame.cpp * Purpose: Implementation of wxExFrameWithHistory class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/config.h> #include <wx/tokenzr.h> #include <wx/extension/report/report.h> // The maximal number of files and projects to be supported. const int NUMBER_RECENT_FILES = 25; const int NUMBER_RECENT_PROJECTS = 25; const int ID_RECENT_PROJECT_LOWEST = wxID_FILE1 + NUMBER_RECENT_FILES + 1; BEGIN_EVENT_TABLE(wxExFrameWithHistory, wxExManagedFrame) EVT_CLOSE(wxExFrameWithHistory::OnClose) EVT_IDLE(wxExFrameWithHistory::OnIdle) EVT_MENU(wxID_OPEN, wxExFrameWithHistory::OnCommand) EVT_MENU(wxID_PREFERENCES, wxExFrameWithHistory::OnCommand) EVT_MENU(ID_TERMINATED_PROCESS, wxExFrameWithHistory::OnCommand) EVT_MENU_RANGE( wxID_FILE1, wxID_FILE1 + NUMBER_RECENT_FILES, wxExFrameWithHistory::OnCommand) EVT_MENU_RANGE( ID_RECENT_PROJECT_LOWEST, ID_RECENT_PROJECT_LOWEST + NUMBER_RECENT_PROJECTS, wxExFrameWithHistory::OnCommand) EVT_MENU_RANGE( ID_EXTENSION_REPORT_LOWEST, ID_EXTENSION_REPORT_HIGHEST, wxExFrameWithHistory::OnCommand) EVT_UPDATE_UI(ID_VIEW_STATUSBAR, wxExFrameWithHistory::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_TOOLBAR, wxExFrameWithHistory::OnUpdateUI) END_EVENT_TABLE() wxExFrameWithHistory::wxExFrameWithHistory(wxWindow* parent, wxWindowID id, const wxString& title, size_t maxFiles, size_t maxProjects, int style) : wxExManagedFrame(parent, id, title, style) , m_FileHistory(maxFiles, wxID_FILE1) , m_FileHistoryList(NULL) , m_ProjectHistory(maxProjects, ID_RECENT_PROJECT_LOWEST) , m_Process(NULL) { // There is only support for one history in the config. // We use file history for this, so update project history ourselves. // The order should be inverted, as the last one added is the most recent used. for (int i = m_ProjectHistory.GetMaxFiles() - 1 ; i >=0 ; i--) { SetRecentProject( wxConfigBase::Get()->Read(wxString::Format("RecentProject%d", i))); } #ifdef wxExUSE_EMBEDDED_SQL wxExTool::Get()->AddInfo( ID_TOOL_SQL, _("Executed %ld SQL queries in"), wxExEllipsed(_("&SQL Query Run"))); wxExTool::Get()->AddInfo( ID_TOOL_REPORT_SQL, _("Reported %ld SQL queries in"), _("Report SQL &Query")); #endif } void wxExFrameWithHistory::DoRecent( wxFileHistory& history, int index, long flags) { if (history.GetCount() > 0) { const wxString file(history.GetHistoryFile(index)); if (!wxFileExists(file)) { history.RemoveFileFromHistory(index); wxLogMessage(_("Removed not existing file: %s from history"), file.c_str()); } else { OpenFile(file, 0, wxEmptyString, flags); } } } wxExListViewWithFrame* wxExFrameWithHistory::GetProject() { return (wxExListViewWithFrame*)GetFocusedListView(); } void wxExFrameWithHistory::OnClose(wxCloseEvent& event) { if (event.CanVeto()) { if (ProcessIsRunning()) { wxLogMessage(_("Process is running")); event.Veto(); return; } } wxDELETE(m_Process); m_FileHistory.Save(*wxConfigBase::Get()); for (size_t i = 0; i < m_ProjectHistory.GetCount(); i++) { wxConfigBase::Get()->Write( wxString::Format("RecentProject%d", i), m_ProjectHistory.GetHistoryFile(i)); } event.Skip(); } void wxExFrameWithHistory::OnCommand(wxCommandEvent& event) { if (event.GetId() >= wxID_FILE1 && event.GetId() <= wxID_FILE1 + NUMBER_RECENT_FILES) { DoRecent(m_FileHistory, event.GetId() - wxID_FILE1); } else if (event.GetId() >= ID_RECENT_PROJECT_LOWEST && event.GetId() <= ID_RECENT_PROJECT_LOWEST + NUMBER_RECENT_PROJECTS) { DoRecent(m_ProjectHistory, event.GetId() - ID_RECENT_PROJECT_LOWEST, wxExSTCWithFrame::STC_OPEN_IS_PROJECT); } else { switch (event.GetId()) { case wxID_OPEN: if (!event.GetString().empty()) { wxArrayString files; wxStringTokenizer tkz(event.GetString()); wxExSTC* stc = GetSTC(); while (tkz.HasMoreTokens()) { const wxString token = tkz.GetNextToken(); wxFileName file(token); if (file.IsRelative() && stc != NULL) { file.MakeAbsolute(stc->GetFileName().GetPath()); if (!file.FileExists()) { wxLogError(_("Cannot locate file") + ": " + token); } else { files.Add(file.GetFullPath()); } } else { files.Add(file.GetFullPath()); } } wxExOpenFiles(this, files); } else { wxExOpenFilesDialog(this); } break; case wxID_PREFERENCES: wxExSTC::ConfigDialog(this, _("Editor Options"), wxExSTC::STC_CONFIG_MODELESS | wxExSTC::STC_CONFIG_SIMPLE | wxExSTC::STC_CONFIG_WITH_APPLY, event.GetId()); break; case ID_PROJECT_SAVE: { wxExListViewWithFrame* project = GetProject(); if (project != NULL) { project->FileSave(); SetTitle(wxEmptyString, project->GetFileName().GetName()); } } break; case ID_SPECIAL_FIND_IN_FILES: wxExFindInFiles(this); break; case ID_SPECIAL_REPLACE_IN_FILES: wxExFindInFiles(this, true); break; case ID_TERMINATED_PROCESS: wxBell(); wxDELETE(m_Process); break; case ID_VIEW_STATUSBAR: GetStatusBar()->Show(!GetStatusBar()->IsShown()); SendSizeEvent(); break; case ID_VIEW_TOOLBAR: GetToolBar()->Show(!GetToolBar()->IsShown()); SendSizeEvent(); break; default: wxFAIL; } } } void wxExFrameWithHistory::OnIdle(wxIdleEvent& event) { event.Skip(); wxWindow* win = wxWindow::FindFocus(); if (win == NULL) return; wxExSTCWithFrame* editor = wxDynamicCast(win, wxExSTCWithFrame); wxExListViewWithFrame* project = wxDynamicCast(win, wxExListViewWithFrame); const wxString title(GetTitle()); const wxUniChar indicator('*'); if ((project != NULL && project->GetContentsChanged()) || (editor != NULL && editor->GetContentsChanged())) { // Project or editor changed, add indicator if not yet done. if (title.Last() != indicator) { wxFrame::SetTitle(title + " " + indicator); } } else { // Project or editor not changed, remove indicator if not yet done. if (title.Last() == indicator) { wxFrame::SetTitle(title.substr(0, title.length() - 2)); } } } void wxExFrameWithHistory::OnUpdateUI(wxUpdateUIEvent& event) { switch (event.GetId()) { case ID_VIEW_STATUSBAR: wxASSERT(GetStatusBar() != NULL); event.Check(GetStatusBar()->IsShown()); break; case ID_VIEW_TOOLBAR: wxASSERT(GetToolBar() != NULL) ; event.Check(GetToolBar()->IsShown()); break; default: wxFAIL; } } bool wxExFrameWithHistory::OpenFile( const wxExFileName& filename, int line_number, const wxString& match, long flags) { if (wxExManagedFrame::OpenFile(filename, line_number, match, flags)) { SetRecentFile(filename.GetFullPath()); return true; } return false; } bool wxExFrameWithHistory::ProcessIsRunning() const { return m_Process != NULL && wxProcess::Exists(m_Process->GetPid()); } bool wxExFrameWithHistory::ProcessRun(const wxString& command) { wxASSERT(m_Process == NULL); wxExListViewWithFrame* listview = Activate(wxExListViewWithFrame::LIST_PROCESS); if (listview == NULL) { wxFAIL; return false; } if ((m_Process = new wxExProcess(listview, command)) != NULL) { if (m_Process->Execute() <= 0) { wxDELETE(m_Process); return false; } else { return true; } } return false; } bool wxExFrameWithHistory::ProcessStop() { if (ProcessIsRunning()) { if (m_Process->Kill() == wxKILL_ERROR) { // Even if the process could not be killed, set it to NULL, as it is deleted. wxFAIL; m_Process = NULL; return false; } else { m_Process = NULL; return true; } } return true; } void wxExFrameWithHistory::SetRecentFile(const wxString& file) { if (!file.empty()) { m_FileHistory.AddFileToHistory(file); if (m_FileHistoryList != NULL) { wxExListItemWithFileName item(m_FileHistoryList, file); item.Insert((long)0); if (m_FileHistoryList->GetItemCount() > 1) { for (int i = m_FileHistoryList->GetItemCount() - 1; i >= 1 ; i--) { wxExListItemWithFileName item(m_FileHistoryList, i); if (item.GetFileName().GetFullPath() == file) { m_FileHistoryList->DeleteItem(i); } } } } } } void wxExFrameWithHistory::SetTitle( const wxString& file, const wxString& project) { // If one of the strings is empty, try to get a better string. wxString better_file(file); wxString better_project(project); if (better_file.empty()) { wxExSTC* stc = GetSTC(); if (stc != NULL) { better_file = stc->GetFileName().GetFullPath(); } } if (better_project.empty()) { wxExListViewWithFrame* lv = (wxExListViewWithFrame*)GetListView(); if (lv != NULL && lv->GetType() == wxExListViewWithFrame::LIST_PROJECT) { better_project = lv->GetFileName().GetName(); } } // And now update the title. if (better_file.empty() && better_project.empty()) { wxExFrame::SetTitle(wxTheApp->GetAppName()); } else { const wxString sep = (!better_file.empty() && !better_project.empty() ? wxString(" - "): wxString(wxEmptyString)); wxExFrame::SetTitle(better_file + sep + better_project); } } void wxExFrameWithHistory::UseFileHistory(wxWindowID id, wxMenu* menu) { UseHistory(id, menu, m_FileHistory); // We can load file history now. m_FileHistory.Load(*wxConfigBase::Get()); } void wxExFrameWithHistory::UseFileHistoryList(wxExListView* list) { m_FileHistoryList = list; m_FileHistoryList->Hide(); // Add all items from FileHistory. for (size_t i = 0; i < m_FileHistory.GetCount(); i++) { wxExListItemWithFileName item( m_FileHistoryList, m_FileHistory.GetHistoryFile(i)); item.Insert(); } } void wxExFrameWithHistory::UseHistory( wxWindowID id, wxMenu* menu, wxFileHistory& history) { wxMenu* submenu = new wxMenu; menu->Append(id, _("Open &Recent"), submenu); history.UseMenu(submenu); } void wxExFrameWithHistory::UseProjectHistory(wxWindowID id, wxMenu* menu) { UseHistory(id, menu, m_ProjectHistory); // And add the files to the menu. m_ProjectHistory.AddFilesToMenu(); } <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2011-2012 Heiko Strathmann * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society */ #include <shogun/evaluation/CrossValidation.h> #include <shogun/machine/Machine.h> #include <shogun/evaluation/Evaluation.h> #include <shogun/evaluation/SplittingStrategy.h> #include <shogun/base/Parameter.h> #include <shogun/mathematics/Statistics.h> #include <shogun/evaluation/CrossValidationOutput.h> #include <shogun/lib/List.h> using namespace shogun; CCrossValidation::CCrossValidation() : CMachineEvaluation() { init(); } CCrossValidation::CCrossValidation(CMachine* machine, CFeatures* features, CLabels* labels, CSplittingStrategy* splitting_strategy, CEvaluation* evaluation_criterion, bool autolock) : CMachineEvaluation(machine, features, labels, splitting_strategy, evaluation_criterion, autolock) { init(); } CCrossValidation::CCrossValidation(CMachine* machine, CLabels* labels, CSplittingStrategy* splitting_strategy, CEvaluation* evaluation_criterion, bool autolock) : CMachineEvaluation(machine, labels, splitting_strategy, evaluation_criterion, autolock) { init(); } CCrossValidation::~CCrossValidation() { SG_UNREF(m_xval_outputs); } void CCrossValidation::init() { m_num_runs=1; /* do reference counting for output objects */ m_xval_outputs=new CList(true); SG_ADD(&m_num_runs, "num_runs", "Number of repetitions", MS_NOT_AVAILABLE); SG_ADD((CSGObject**)&m_xval_outputs, "m_xval_outputs", "List of output " "classes for intermediade cross-validation results", MS_NOT_AVAILABLE); } CEvaluationResult* CCrossValidation::evaluate() { SG_DEBUG("entering %s::evaluate()\n", get_name()) REQUIRE(m_machine, "%s::evaluate() is only possible if a machine is " "attached\n", get_name()); REQUIRE(m_features, "%s::evaluate() is only possible if features are " "attached\n", get_name()); REQUIRE(m_labels, "%s::evaluate() is only possible if labels are " "attached\n", get_name()); /* if for some reason the do_unlock_frag is set, unlock */ if (m_do_unlock) { m_machine->data_unlock(); m_do_unlock=false; } /* set labels in any case (no locking needs this) */ m_machine->set_labels(m_labels); if (m_autolock) { /* if machine supports locking try to do so */ if (m_machine->supports_locking()) { /* only lock if machine is not yet locked */ if (!m_machine->is_data_locked()) { m_machine->data_lock(m_labels, m_features); m_do_unlock=true; } } else { SG_WARNING("%s does not support locking. Autolocking is skipped. " "Set autolock flag to false to get rid of warning.\n", m_machine->get_name()); } } SGVector<float64_t> results(m_num_runs); /* evtl. update xvalidation output class */ CCrossValidationOutput* current=(CCrossValidationOutput*) m_xval_outputs->get_first_element(); while (current) { current->init_num_runs(m_num_runs); current->init_num_folds(m_splitting_strategy->get_num_subsets()); current->init_expose_labels(m_labels); current->post_init(); SG_UNREF(current); current=(CCrossValidationOutput*) m_xval_outputs->get_next_element(); } /* perform all the x-val runs */ SG_DEBUG("starting %d runs of cross-validation\n", m_num_runs) for (index_t i=0; i <m_num_runs; ++i) { /* evtl. update xvalidation output class */ current=(CCrossValidationOutput*)m_xval_outputs->get_first_element(); while (current) { current->update_run_index(i); SG_UNREF(current); current=(CCrossValidationOutput*) m_xval_outputs->get_next_element(); } SG_DEBUG("entering cross-validation run %d \n", i) results[i]=evaluate_one_run(); SG_DEBUG("result of cross-validation run %d is %f\n", i, results[i]) } /* construct evaluation result */ CCrossValidationResult* result = new CCrossValidationResult(); result->mean=CStatistics::mean(results); if (m_num_runs>1) result->std_dev=CStatistics::std_deviation(results); else result->std_dev=0; /* unlock machine if it was locked in this method */ if (m_machine->is_data_locked() && m_do_unlock) { m_machine->data_unlock(); m_do_unlock=false; } SG_DEBUG("leaving %s::evaluate()\n", get_name()) SG_REF(result); return result; } void CCrossValidation::set_num_runs(int32_t num_runs) { if (num_runs <1) SG_ERROR("%d is an illegal number of repetitions\n", num_runs) m_num_runs=num_runs; } float64_t CCrossValidation::evaluate_one_run() { SG_DEBUG("entering %s::evaluate_one_run()\n", get_name()) index_t num_subsets=m_splitting_strategy->get_num_subsets(); SG_DEBUG("building index sets for %d-fold cross-validation\n", num_subsets) /* build index sets */ m_splitting_strategy->build_subsets(); /* results array */ SGVector<float64_t> results(num_subsets); /* different behavior whether data is locked or not */ if (m_machine->is_data_locked()) { SG_DEBUG("starting locked evaluation\n", get_name()) /* do actual cross-validation */ for (index_t i=0; i <num_subsets; ++i) { /* evtl. update xvalidation output class */ CCrossValidationOutput* current=(CCrossValidationOutput*) m_xval_outputs->get_first_element(); while (current) { current->update_fold_index(i); SG_UNREF(current); current=(CCrossValidationOutput*) m_xval_outputs->get_next_element(); } /* index subset for training, will be freed below */ SGVector<index_t> inverse_subset_indices = m_splitting_strategy->generate_subset_inverse(i); /* train machine on training features */ m_machine->train_locked(inverse_subset_indices); /* feature subset for testing */ SGVector<index_t> subset_indices = m_splitting_strategy->generate_subset_indices(i); /* evtl. update xvalidation output class */ current=(CCrossValidationOutput*)m_xval_outputs->get_first_element(); while (current) { current->update_train_indices(inverse_subset_indices, "\t"); current->update_trained_machine(m_machine, "\t"); SG_UNREF(current); current=(CCrossValidationOutput*) m_xval_outputs->get_next_element(); } /* produce output for desired indices */ CLabels* result_labels=m_machine->apply_locked(subset_indices); SG_REF(result_labels); /* set subset for testing labels */ m_labels->add_subset(subset_indices); /* evaluate against own labels */ m_evaluation_criterion->set_indices(subset_indices); results[i]=m_evaluation_criterion->evaluate(result_labels, m_labels); /* evtl. update xvalidation output class */ current=(CCrossValidationOutput*)m_xval_outputs->get_first_element(); while (current) { current->update_test_indices(subset_indices, "\t"); current->update_test_result(result_labels, "\t"); current->update_test_true_result(m_labels, "\t"); current->post_update_results(); current->update_evaluation_result(results[i], "\t"); SG_UNREF(current); current=(CCrossValidationOutput*) m_xval_outputs->get_next_element(); } /* remove subset to prevent side effects */ m_labels->remove_subset(); /* clean up */ SG_UNREF(result_labels); SG_DEBUG("done locked evaluation\n", get_name()) } } else { SG_DEBUG("starting unlocked evaluation\n", get_name()) /* tell machine to store model internally * (otherwise changing subset of features will kaboom the classifier) */ m_machine->set_store_model_features(true); /* do actual cross-validation */ for (index_t i=0; i <num_subsets; ++i) { /* evtl. update xvalidation output class */ CCrossValidationOutput* current=(CCrossValidationOutput*) m_xval_outputs->get_first_element(); while (current) { current->update_fold_index(i); SG_UNREF(current); current=(CCrossValidationOutput*) m_xval_outputs->get_next_element(); } /* set feature subset for training */ SGVector<index_t> inverse_subset_indices= m_splitting_strategy->generate_subset_inverse(i); m_features->add_subset(inverse_subset_indices); for (index_t p=0; p<m_features->get_num_preprocessors(); p++) { CPreprocessor* preprocessor = m_features->get_preprocessor(p); preprocessor->init(m_features); SG_UNREF(preprocessor); } /* set label subset for training */ m_labels->add_subset(inverse_subset_indices); SG_DEBUG("training set %d:\n", i) if (io->get_loglevel()==MSG_DEBUG) { SGVector<index_t>::display_vector(inverse_subset_indices.vector, inverse_subset_indices.vlen, "training indices"); } /* train machine on training features and remove subset */ SG_DEBUG("starting training\n") m_machine->train(m_features); SG_DEBUG("finished training\n") /* evtl. update xvalidation output class */ current=(CCrossValidationOutput*)m_xval_outputs->get_first_element(); while (current) { current->update_train_indices(inverse_subset_indices, "\t"); current->update_trained_machine(m_machine, "\t"); SG_UNREF(current); current=(CCrossValidationOutput*) m_xval_outputs->get_next_element(); } m_features->remove_subset(); m_labels->remove_subset(); /* set feature subset for testing (subset method that stores pointer) */ SGVector<index_t> subset_indices = m_splitting_strategy->generate_subset_indices(i); m_features->add_subset(subset_indices); /* set label subset for testing */ m_labels->add_subset(subset_indices); SG_DEBUG("test set %d:\n", i) if (io->get_loglevel()==MSG_DEBUG) { SGVector<index_t>::display_vector(subset_indices.vector, subset_indices.vlen, "test indices"); } /* apply machine to test features and remove subset */ SG_DEBUG("starting evaluation\n") SG_DEBUG("%p\n", m_features) CLabels* result_labels=m_machine->apply(m_features); SG_DEBUG("finished evaluation\n") m_features->remove_subset(); SG_REF(result_labels); /* evaluate */ results[i]=m_evaluation_criterion->evaluate(result_labels, m_labels); SG_DEBUG("result on fold %d is %f\n", i, results[i]) } /* evtl. update xvalidation output class */ current=(CCrossValidationOutput*)m_xval_outputs->get_first_element(); while (current) { current->update_test_indices(subset_indices, "\t"); current->update_test_result(result_labels, "\t"); current->update_test_true_result(m_labels, "\t"); current->post_update_results(); current->update_evaluation_result(results[i], "\t"); SG_UNREF(current); current=(CCrossValidationOutput*) m_xval_outputs->get_next_element(); } /* clean up, remove subsets */ SG_UNREF(result_labels); m_labels->remove_subset(); } SG_DEBUG("done unlocked evaluation\n", get_name()) } /* build arithmetic mean of results */ float64_t mean=CStatistics::mean(results); SG_DEBUG("leaving %s::evaluate_one_run()\n", get_name()) return mean; } void CCrossValidation::add_cross_validation_output( CCrossValidationOutput* cross_validation_output) { m_xval_outputs->append_element(cross_validation_output); } <commit_msg><commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2011-2012 Heiko Strathmann * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society */ #include <shogun/evaluation/CrossValidation.h> #include <shogun/machine/Machine.h> #include <shogun/evaluation/Evaluation.h> #include <shogun/evaluation/SplittingStrategy.h> #include <shogun/base/Parameter.h> #include <shogun/mathematics/Statistics.h> #include <shogun/evaluation/CrossValidationOutput.h> #include <shogun/lib/List.h> using namespace shogun; CCrossValidation::CCrossValidation() : CMachineEvaluation() { init(); } CCrossValidation::CCrossValidation(CMachine* machine, CFeatures* features, CLabels* labels, CSplittingStrategy* splitting_strategy, CEvaluation* evaluation_criterion, bool autolock) : CMachineEvaluation(machine, features, labels, splitting_strategy, evaluation_criterion, autolock) { init(); } CCrossValidation::CCrossValidation(CMachine* machine, CLabels* labels, CSplittingStrategy* splitting_strategy, CEvaluation* evaluation_criterion, bool autolock) : CMachineEvaluation(machine, labels, splitting_strategy, evaluation_criterion, autolock) { init(); } CCrossValidation::~CCrossValidation() { SG_UNREF(m_xval_outputs); } void CCrossValidation::init() { m_num_runs=1; /* do reference counting for output objects */ m_xval_outputs=new CList(true); SG_ADD(&m_num_runs, "num_runs", "Number of repetitions", MS_NOT_AVAILABLE); SG_ADD((CSGObject**)&m_xval_outputs, "m_xval_outputs", "List of output " "classes for intermediade cross-validation results", MS_NOT_AVAILABLE); } CEvaluationResult* CCrossValidation::evaluate() { SG_DEBUG("entering %s::evaluate()\n", get_name()) REQUIRE(m_machine, "%s::evaluate() is only possible if a machine is " "attached\n", get_name()); REQUIRE(m_features, "%s::evaluate() is only possible if features are " "attached\n", get_name()); REQUIRE(m_labels, "%s::evaluate() is only possible if labels are " "attached\n", get_name()); /* if for some reason the do_unlock_frag is set, unlock */ if (m_do_unlock) { m_machine->data_unlock(); m_do_unlock=false; } /* set labels in any case (no locking needs this) */ m_machine->set_labels(m_labels); if (m_autolock) { /* if machine supports locking try to do so */ if (m_machine->supports_locking()) { /* only lock if machine is not yet locked */ if (!m_machine->is_data_locked()) { m_machine->data_lock(m_labels, m_features); m_do_unlock=true; } } else { SG_WARNING("%s does not support locking. Autolocking is skipped. " "Set autolock flag to false to get rid of warning.\n", m_machine->get_name()); } } SGVector<float64_t> results(m_num_runs); /* evtl. update xvalidation output class */ CCrossValidationOutput* current=(CCrossValidationOutput*) m_xval_outputs->get_first_element(); while (current) { current->init_num_runs(m_num_runs); current->init_num_folds(m_splitting_strategy->get_num_subsets()); current->init_expose_labels(m_labels); current->post_init(); SG_UNREF(current); current=(CCrossValidationOutput*) m_xval_outputs->get_next_element(); } /* perform all the x-val runs */ SG_DEBUG("starting %d runs of cross-validation\n", m_num_runs) for (index_t i=0; i <m_num_runs; ++i) { /* evtl. update xvalidation output class */ current=(CCrossValidationOutput*)m_xval_outputs->get_first_element(); while (current) { current->update_run_index(i); SG_UNREF(current); current=(CCrossValidationOutput*) m_xval_outputs->get_next_element(); } SG_DEBUG("entering cross-validation run %d \n", i) results[i]=evaluate_one_run(); SG_DEBUG("result of cross-validation run %d is %f\n", i, results[i]) } /* construct evaluation result */ CCrossValidationResult* result = new CCrossValidationResult(); result->mean=CStatistics::mean(results); if (m_num_runs>1) result->std_dev=CStatistics::std_deviation(results); else result->std_dev=0; /* unlock machine if it was locked in this method */ if (m_machine->is_data_locked() && m_do_unlock) { m_machine->data_unlock(); m_do_unlock=false; } SG_DEBUG("leaving %s::evaluate()\n", get_name()) SG_REF(result); return result; } void CCrossValidation::set_num_runs(int32_t num_runs) { if (num_runs <1) SG_ERROR("%d is an illegal number of repetitions\n", num_runs) m_num_runs=num_runs; } float64_t CCrossValidation::evaluate_one_run() { SG_DEBUG("entering %s::evaluate_one_run()\n", get_name()) index_t num_subsets=m_splitting_strategy->get_num_subsets(); SG_DEBUG("building index sets for %d-fold cross-validation\n", num_subsets) /* build index sets */ m_splitting_strategy->build_subsets(); /* results array */ SGVector<float64_t> results(num_subsets); /* different behavior whether data is locked or not */ if (m_machine->is_data_locked()) { SG_DEBUG("starting locked evaluation\n", get_name()) /* do actual cross-validation */ for (index_t i=0; i <num_subsets; ++i) { /* evtl. update xvalidation output class */ CCrossValidationOutput* current=(CCrossValidationOutput*) m_xval_outputs->get_first_element(); while (current) { current->update_fold_index(i); SG_UNREF(current); current=(CCrossValidationOutput*) m_xval_outputs->get_next_element(); } /* index subset for training, will be freed below */ SGVector<index_t> inverse_subset_indices = m_splitting_strategy->generate_subset_inverse(i); /* train machine on training features */ m_machine->train_locked(inverse_subset_indices); /* feature subset for testing */ SGVector<index_t> subset_indices = m_splitting_strategy->generate_subset_indices(i); /* evtl. update xvalidation output class */ current=(CCrossValidationOutput*)m_xval_outputs->get_first_element(); while (current) { current->update_train_indices(inverse_subset_indices, "\t"); current->update_trained_machine(m_machine, "\t"); SG_UNREF(current); current=(CCrossValidationOutput*) m_xval_outputs->get_next_element(); } /* produce output for desired indices */ CLabels* result_labels=m_machine->apply_locked(subset_indices); SG_REF(result_labels); /* set subset for testing labels */ m_labels->add_subset(subset_indices); /* evaluate against own labels */ m_evaluation_criterion->set_indices(subset_indices); results[i]=m_evaluation_criterion->evaluate(result_labels, m_labels); /* evtl. update xvalidation output class */ current=(CCrossValidationOutput*)m_xval_outputs->get_first_element(); while (current) { current->update_test_indices(subset_indices, "\t"); current->update_test_result(result_labels, "\t"); current->update_test_true_result(m_labels, "\t"); current->post_update_results(); current->update_evaluation_result(results[i], "\t"); SG_UNREF(current); current=(CCrossValidationOutput*) m_xval_outputs->get_next_element(); } /* remove subset to prevent side effects */ m_labels->remove_subset(); /* clean up */ SG_UNREF(result_labels); SG_DEBUG("done locked evaluation\n", get_name()) } } else { SG_DEBUG("starting unlocked evaluation\n", get_name()) /* tell machine to store model internally * (otherwise changing subset of features will kaboom the classifier) */ m_machine->set_store_model_features(true); /* do actual cross-validation */ for (index_t i=0; i <num_subsets; ++i) { /* evtl. update xvalidation output class */ CCrossValidationOutput* current=(CCrossValidationOutput*) m_xval_outputs->get_first_element(); while (current) { current->update_fold_index(i); SG_UNREF(current); current=(CCrossValidationOutput*) m_xval_outputs->get_next_element(); } /* set feature subset for training */ SGVector<index_t> inverse_subset_indices= m_splitting_strategy->generate_subset_inverse(i); m_features->add_subset(inverse_subset_indices); for (index_t p=0; p<m_features->get_num_preprocessors(); p++) { CPreprocessor* preprocessor = m_features->get_preprocessor(p); preprocessor->init(m_features); SG_UNREF(preprocessor); } /* set label subset for training */ m_labels->add_subset(inverse_subset_indices); SG_DEBUG("training set %d:\n", i) if (io->get_loglevel()==MSG_DEBUG) { SGVector<index_t>::display_vector(inverse_subset_indices.vector, inverse_subset_indices.vlen, "training indices"); } /* train machine on training features and remove subset */ SG_DEBUG("starting training\n") m_machine->train(m_features); SG_DEBUG("finished training\n") /* evtl. update xvalidation output class */ current=(CCrossValidationOutput*)m_xval_outputs->get_first_element(); while (current) { current->update_train_indices(inverse_subset_indices, "\t"); current->update_trained_machine(m_machine, "\t"); SG_UNREF(current); current=(CCrossValidationOutput*) m_xval_outputs->get_next_element(); } m_features->remove_subset(); m_labels->remove_subset(); /* set feature subset for testing (subset method that stores pointer) */ SGVector<index_t> subset_indices = m_splitting_strategy->generate_subset_indices(i); m_features->add_subset(subset_indices); /* set label subset for testing */ m_labels->add_subset(subset_indices); SG_DEBUG("test set %d:\n", i) if (io->get_loglevel()==MSG_DEBUG) { SGVector<index_t>::display_vector(subset_indices.vector, subset_indices.vlen, "test indices"); } /* apply machine to test features and remove subset */ SG_DEBUG("starting evaluation\n") SG_DEBUG("%p\n", m_features) CLabels* result_labels=m_machine->apply(m_features); SG_DEBUG("finished evaluation\n") m_features->remove_subset(); SG_REF(result_labels); /* evaluate */ results[i]=m_evaluation_criterion->evaluate(result_labels, m_labels); SG_DEBUG("result on fold %d is %f\n", i, results[i]) /* evtl. update xvalidation output class */ current=(CCrossValidationOutput*)m_xval_outputs->get_first_element(); while (current) { current->update_test_indices(subset_indices, "\t"); current->update_test_result(result_labels, "\t"); current->update_test_true_result(m_labels, "\t"); current->post_update_results(); current->update_evaluation_result(results[i], "\t"); SG_UNREF(current); current=(CCrossValidationOutput*) m_xval_outputs->get_next_element(); } /* clean up, remove subsets */ SG_UNREF(result_labels); m_labels->remove_subset(); } SG_DEBUG("done unlocked evaluation\n", get_name()) } /* build arithmetic mean of results */ float64_t mean=CStatistics::mean(results); SG_DEBUG("leaving %s::evaluate_one_run()\n", get_name()) return mean; } void CCrossValidation::add_cross_validation_output( CCrossValidationOutput* cross_validation_output) { m_xval_outputs->append_element(cross_validation_output); } <|endoftext|>
<commit_before><commit_msg>Add test for shrinking of range references on row/column deletion.<commit_after><|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2015 Jett * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef HCKT_TREE_H #define HCKT_TREE_H #include <cassert> #include <vector> #include <iostream> #include <bitset> #include "lmemvector.hpp" namespace hckt { template <typename T> class tree { typedef T value_type; protected: std::bitset<64> bitset; std::bitset<64> leaf; hckt::lmemvector<value_type> values; hckt::lmemvector<tree<value_type>*> children; public: tree() : bitset { 0 }, leaf { 0 }, values { }, children { } { } ~tree() { collapse(); } //counts number of set bits static inline unsigned popcount(std::uint64_t x) { #ifdef __SSE4_2__ return _popcnt64(x); #else constexpr std::uint64_t m1 { 0x5555555555555555 }; constexpr std::uint64_t m2 { 0x3333333333333333 }; constexpr std::uint64_t m4 { 0x0f0f0f0f0f0f0f0f }; constexpr std::uint64_t h01 { 0x0101010101010101 }; x -= (x >> 1) & m1; x = (x & m2) + ((x >> 2) & m2); x = (x + (x >> 4)) & m4; return (x * h01) >> 56; #endif } unsigned get_children_position(const unsigned position) const { assert(position < 64); if(position == 0) { return 0; } return popcount((bitset.to_ullong() & ~leaf.to_ullong()) << (64 - position)); } /* * check if we have any children */ bool has_children() const { return bitset.any(); } bool is_set(const unsigned position) const { assert(position < 64); return bitset[position]; } bool is_leaf(const unsigned position) const { assert(position < 64); return leaf[position]; } /* * destroy children */ void collapse() { for(auto child : children) { child->collapse(); } children.clear(); values.clear(); bitset.reset(); } /* * insert a tree into position of tree * position should be result of get_position */ void insert(const unsigned position, const value_type value) { assert(position < 64); assert(! is_set(position)); const unsigned cpos { get_children_position(position) }; children.insert(cpos, new tree<value_type>()); values.insert(cpos, value); bitset.set(position); leaf.reset(position); } /* * insert a leaf into position of tree * position should be result of get_position */ void insert_leaf(const unsigned position, const value_type value) { assert(position < 64); assert(! is_set(position)); const unsigned cpos { get_children_position(position) }; values.insert(cpos, value); bitset.set(position); leaf.set(position); } /* * removes an item from tree * position should be result of get_position */ void remove(const unsigned position) { assert(position < 64); assert(is_set(position)); assert(! is_leaf(position)); const unsigned cpos { get_children_position(position) }; children[cpos]->collapse(); children.erase(cpos); values.erase(cpos); bitset.reset(position); } /* * get child node * position should be result of get_position */ tree<value_type> * child(const unsigned position) const { assert(position < 64); assert(is_set(position)); assert(! is_leaf(position)); const unsigned cpos { get_children_position(position) }; return children[cpos]; } /* * sets node to specific value * note: this does not check whether a value has been inserted here yet * position should be result of get_position */ void set_value(const unsigned position, const value_type value) { assert(position < 64); assert(is_set(position)); const unsigned cpos { get_children_position(position) }; values[cpos] = value; } /* * gets value from specific position * note: this does not check whether a value has been inserted here yet * position should be result of get_position */ value_type get_value(const unsigned position) const { assert(position < 64); const unsigned cpos { get_children_position(position) }; return values[cpos]; } /************************************************ * * BENCHMARKING CODE * ***********************************************/ std::size_t calculate_memory_size() const { std::size_t size { sizeof(bitset) + sizeof(leaf) + sizeof(values) + (values.capacity() * sizeof(value_type)) + sizeof(children) + (children.capacity() * sizeof(tree<value_type>*)) }; for(auto child : children) { size += child->calculate_memory_size(); } return size; } std::size_t calculate_children_amount() const { std::size_t amount { popcount(bitset.to_ullong()) }; for(auto child : children) { amount += child->calculate_children_amount(); } return amount; } std::size_t calculate_leaf_amount() const { std::size_t amount { popcount(leaf.to_ullong()) }; for(auto child : children) { amount += child->calculate_leaf_amount(); } return amount; } void mem_usage_info() { auto memsize = calculate_memory_size(); auto c_amnt = calculate_children_amount(); auto l_amnt = calculate_leaf_amount(); std::cout << "total: " << memsize << std::endl; std::cout << "tree-size: " << sizeof(tree<value_type>) << std::endl; std::cout << "children: " << c_amnt << std::endl; std::cout << "leaves: " << l_amnt << std::endl; std::cout << "per-child: " << (static_cast<float>(memsize) / c_amnt) << std::endl; std::cout << "val-size: " << sizeof(value_type) << std::endl; std::cout << "overhead: " << (static_cast<float>(memsize - (c_amnt * sizeof(value_type))) / c_amnt) << std::endl; } }; }; #endif <commit_msg>minor perf change by inverting leaf to reduce ops when popcnt'ing<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2015 Jett * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef HCKT_TREE_H #define HCKT_TREE_H #include <cassert> #include <vector> #include <iostream> #include <bitset> #include "lmemvector.hpp" namespace hckt { template <typename T> class tree { typedef T value_type; protected: std::bitset<64> bitset; std::bitset<64> inv_leaf; hckt::lmemvector<value_type> values; hckt::lmemvector<tree<value_type>*> children; public: tree() : bitset { 0 }, inv_leaf { 0xFFFFFFFFFFFFFFFF }, values { }, children { } { } ~tree() { collapse(); } //counts number of set bits static inline unsigned popcount(std::uint64_t x) { #ifdef __SSE4_2__ return _popcnt64(x); #else constexpr std::uint64_t m1 { 0x5555555555555555 }; constexpr std::uint64_t m2 { 0x3333333333333333 }; constexpr std::uint64_t m4 { 0x0f0f0f0f0f0f0f0f }; constexpr std::uint64_t h01 { 0x0101010101010101 }; x -= (x >> 1) & m1; x = (x & m2) + ((x >> 2) & m2); x = (x + (x >> 4)) & m4; return (x * h01) >> 56; #endif } unsigned get_children_position(const unsigned position) const { assert(position < 64); if(position == 0) { return 0; } return popcount((bitset.to_ullong() & inv_leaf.to_ullong()) << (64 - position)); } /* * check if we have any children */ bool has_children() const { return bitset.any(); } bool is_set(const unsigned position) const { assert(position < 64); return bitset[position]; } bool is_leaf(const unsigned position) const { assert(position < 64); return !inv_leaf[position]; } /* * destroy children */ void collapse() { for(auto child : children) { child->collapse(); } children.clear(); values.clear(); bitset.reset(); } /* * insert a tree into position of tree * position should be result of get_position */ void insert(const unsigned position, const value_type value) { assert(position < 64); assert(! is_set(position)); const unsigned cpos { get_children_position(position) }; children.insert(cpos, new tree<value_type>()); values.insert(cpos, value); bitset.set(position); inv_leaf.set(position); } /* * insert a leaf into position of tree * position should be result of get_position */ void insert_leaf(const unsigned position, const value_type value) { assert(position < 64); assert(! is_set(position)); const unsigned cpos { get_children_position(position) }; values.insert(cpos, value); bitset.set(position); inv_leaf.reset(position); } /* * removes an item from tree * position should be result of get_position */ void remove(const unsigned position) { assert(position < 64); assert(is_set(position)); assert(! is_leaf(position)); const unsigned cpos { get_children_position(position) }; children[cpos]->collapse(); children.erase(cpos); values.erase(cpos); bitset.reset(position); } /* * get child node * position should be result of get_position */ tree<value_type> * child(const unsigned position) const { assert(position < 64); assert(is_set(position)); assert(! is_leaf(position)); const unsigned cpos { get_children_position(position) }; return children[cpos]; } /* * sets node to specific value * note: this does not check whether a value has been inserted here yet * position should be result of get_position */ void set_value(const unsigned position, const value_type value) { assert(position < 64); assert(is_set(position)); const unsigned cpos { get_children_position(position) }; values[cpos] = value; } /* * gets value from specific position * note: this does not check whether a value has been inserted here yet * position should be result of get_position */ value_type get_value(const unsigned position) const { assert(position < 64); const unsigned cpos { get_children_position(position) }; return values[cpos]; } /************************************************ * * BENCHMARKING CODE * ***********************************************/ std::size_t calculate_memory_size() const { std::size_t size { sizeof(bitset) + sizeof(inv_leaf) + sizeof(values) + (values.capacity() * sizeof(value_type)) + sizeof(children) + (children.capacity() * sizeof(tree<value_type>*)) }; for(auto child : children) { size += child->calculate_memory_size(); } return size; } std::size_t calculate_children_amount() const { std::size_t amount { popcount(bitset.to_ullong()) }; for(auto child : children) { amount += child->calculate_children_amount(); } return amount; } std::size_t calculate_leaf_amount() const { std::size_t amount { popcount(~inv_leaf.to_ullong()) }; for(auto child : children) { amount += child->calculate_leaf_amount(); } return amount; } void mem_usage_info() { auto memsize = calculate_memory_size(); auto c_amnt = calculate_children_amount(); auto l_amnt = calculate_leaf_amount(); std::cout << "total: " << memsize << std::endl; std::cout << "tree-size: " << sizeof(tree<value_type>) << std::endl; std::cout << "children: " << c_amnt << std::endl; std::cout << "leaves: " << l_amnt << std::endl; std::cout << "per-child: " << (static_cast<float>(memsize) / c_amnt) << std::endl; std::cout << "val-size: " << sizeof(value_type) << std::endl; std::cout << "overhead: " << (static_cast<float>(memsize - (c_amnt * sizeof(value_type))) / c_amnt) << std::endl; } }; }; #endif <|endoftext|>
<commit_before>/** * The MIT License (MIT) * * Copyright (c) 2015 Nathan Osman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. **/ #include <QMutableHashIterator> #include "config.h" #include "manager.h" Manager::Manager() { connect(&timer, &QTimer::timeout, this, &Manager::checkTimeouts); connect(&listener, &Listener::pingReceived, this, &Manager::processPing); reload(); } void Manager::start() { listener.start(); timer.start(); } QSharedPointer<Device> Manager::get(const QString &name) const { return devices.value(name); } QList<QSharedPointer<Device>> Manager::list() const { return devices.values(); } void Manager::checkTimeouts() { QMutableHashIterator<QString, QSharedPointer<Device>> i(devices); while(i.hasNext()) { if(i.next().value()->timeoutReached()) { emit deviceRemoved(*(i.value())); i.remove(); } } } void Manager::processPing(const QJsonObject &object, const QHostAddress &address) { if(object.contains("uuid") && object.contains("version")) { QString uuid(object.value("uuid").toString()); QString version(object.value("version").toString()); if(uuid != Settings::get<QString>(Settings::DeviceName) && version == NITROSHARE_VERSION) { if(!devices.contains(uuid)) { QSharedPointer<Device> device(new Device(uuid)); devices.insert(uuid, device); emit deviceAdded(*device); } devices.value(uuid)->update(object, address); } } } void Manager::settingChanged(Settings::Key key) { if(key == Settings::BroadcastTimeout) { timer.stop(); reload(); timer.start(); } } void Manager::reload() { timer.setInterval(Settings::get<int>(Settings::BroadcastTimeout)); } <commit_msg>Ensured that Device::update() was called before deviceAdded() signal was emitted.<commit_after>/** * The MIT License (MIT) * * Copyright (c) 2015 Nathan Osman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. **/ #include <QMutableHashIterator> #include "config.h" #include "manager.h" Manager::Manager() { connect(&timer, &QTimer::timeout, this, &Manager::checkTimeouts); connect(&listener, &Listener::pingReceived, this, &Manager::processPing); reload(); } void Manager::start() { listener.start(); timer.start(); } QSharedPointer<Device> Manager::get(const QString &name) const { return devices.value(name); } QList<QSharedPointer<Device>> Manager::list() const { return devices.values(); } void Manager::checkTimeouts() { QMutableHashIterator<QString, QSharedPointer<Device>> i(devices); while(i.hasNext()) { if(i.next().value()->timeoutReached()) { emit deviceRemoved(*(i.value())); i.remove(); } } } void Manager::processPing(const QJsonObject &object, const QHostAddress &address) { if(object.contains("uuid") && object.contains("version")) { QString uuid(object.value("uuid").toString()); QString version(object.value("version").toString()); if(uuid != Settings::get<QString>(Settings::DeviceName) && version == NITROSHARE_VERSION) { if(!devices.contains(uuid)) { QSharedPointer<Device> device(new Device(uuid)); device->update(object, address); devices.insert(uuid, device); emit deviceAdded(*device); } else { devices.value(uuid)->update(object, address); } } } } void Manager::settingChanged(Settings::Key key) { if(key == Settings::BroadcastTimeout) { timer.stop(); reload(); timer.start(); } } void Manager::reload() { timer.setInterval(Settings::get<int>(Settings::BroadcastTimeout)); } <|endoftext|>
<commit_before><commit_msg>INTEGRATION: CWS fwkbugfix03 (1.31.40); FILE MERGED 2004/10/19 13:20:34 cd 1.31.40.1: #i30041# Added new state to support show/hide controllers with status update<commit_after><|endoftext|>
<commit_before>#include "GUI_ObjectManipulation.hpp" #include "GUI_ObjectList.hpp" #include "OptionsGroup.hpp" #include "wxExtensions.hpp" #include "PresetBundle.hpp" #include "Model.hpp" #include "Geometry.hpp" #include <boost/algorithm/string.hpp> namespace Slic3r { namespace GUI { ObjectManipulation::ObjectManipulation(wxWindow* parent): OG_Settings(parent, true) { m_og->set_name(_(L("Object Manipulation"))); m_og->label_width = 100; m_og->set_grid_vgap(5); m_og->set_process_enter(); // We need to update new values only after press ENTER m_og->m_on_change = [this](t_config_option_key opt_key, boost::any value) { if (opt_key == "scale_unit") { const wxString& selection = boost::any_cast<wxString>(value); std::vector<std::string> axes{ "x", "y", "z" }; for (auto axis : axes) { std::string key = "scale_" + axis; m_og->set_side_text(key, selection); } m_is_percent_scale = selection == _("%"); update_scale_values(); return; } }; ConfigOptionDef def; // Objects(sub-objects) name def.label = L("Name"); // def.type = coString; def.gui_type = "legend"; def.tooltip = L("Object name"); def.full_width = true; def.default_value = new ConfigOptionString{ " " }; m_og->append_single_option_line(Option(def, "object_name")); // Legend for object modification auto line = Line{ "", "" }; def.label = ""; def.type = coString; def.width = 55; std::vector<std::string> axes{ "x", "y", "z" }; for (const auto axis : axes) { const auto label = boost::algorithm::to_upper_copy(axis); def.default_value = new ConfigOptionString{ " " + label }; Option option = Option(def, axis + "_axis_legend"); line.append_option(option); } m_og->append_line(line); auto add_og_to_object_settings = [](const std::string& option_name, const std::string& sidetext) { Line line = { _(option_name), "" }; if (option_name == "Scale") { line.near_label_widget = [](wxWindow* parent) { auto btn = new PrusaLockButton(parent, wxID_ANY); btn->Bind(wxEVT_BUTTON, [btn](wxCommandEvent &event) { event.Skip(); wxTheApp->CallAfter([btn]() { wxGetApp().obj_manipul()->set_uniform_scaling(btn->IsLocked()); }); }); return btn; }; } ConfigOptionDef def; def.type = coFloat; def.default_value = new ConfigOptionFloat(0.0); def.width = 55; if (option_name == "Rotation") def.min = -360; const std::string lower_name = boost::algorithm::to_lower_copy(option_name); std::vector<std::string> axes{ "x", "y", "z" }; for (auto axis : axes) { if (axis == "z" && option_name != "Scale") def.sidetext = sidetext; Option option = Option(def, lower_name + "_" + axis); option.opt.full_width = true; line.append_option(option); } if (option_name == "Scale") { def.width = 45; def.type = coStrings; def.gui_type = "select_open"; def.enum_labels.push_back(L("%")); def.enum_labels.push_back(L("mm")); def.default_value = new ConfigOptionStrings{ "mm" }; const Option option = Option(def, lower_name + "_unit"); line.append_option(option); } return line; }; // Settings table m_og->append_line(add_og_to_object_settings(L("Position"), L("mm"))); m_og->append_line(add_og_to_object_settings(L("Rotation"), "°")); m_og->append_line(add_og_to_object_settings(L("Scale"), "mm")); def.label = L("Place on bed"); def.type = coBool; def.tooltip = L("Automatic placing of models on printing bed in Y axis"); def.gui_type = ""; def.sidetext = ""; def.default_value = new ConfigOptionBool{ false }; m_og->append_single_option_line(Option(def, "place_on_bed")); } void ObjectManipulation::Show(const bool show) { if (show == IsShown()) return; m_og->Show(show); if (show && wxGetApp().get_view_mode() != ConfigMenuModeSimple) { m_og->get_grid_sizer()->Show(size_t(0), false); m_og->get_grid_sizer()->Show(size_t(1), false); } } bool ObjectManipulation::IsShown() { return m_og->get_grid_sizer()->IsShown(2); } void ObjectManipulation::UpdateAndShow(const bool show) { if (show) update_settings_value(_3DScene::get_canvas(wxGetApp().canvas3D())->get_selection()); OG_Settings::UpdateAndShow(show); } int ObjectManipulation::ol_selection() { return wxGetApp().obj_list()->get_selected_obj_idx(); } void ObjectManipulation::update_settings_value(const GLCanvas3D::Selection& selection) { #if ENABLE_MODELVOLUME_TRANSFORM if (selection.is_single_full_instance() || selection.is_single_full_object()) #else if (selection.is_single_full_object()) { auto obj_idx = selection.get_object_idx(); if (obj_idx >=0 && !wxGetApp().model_objects()->empty() && (*wxGetApp().model_objects())[obj_idx]->instances.size() == 1) { // all volumes in the selection belongs to the same instance, any of them contains the needed data, so we take the first const GLVolume* volume = selection.get_volume(*selection.get_volume_idxs().begin()); update_position_value(volume->get_offset()); update_rotation_value(volume->get_rotation()); update_scale_value(volume->get_scaling_factor()); m_og->enable(); } else reset_settings_value(); } else if (selection.is_single_full_instance()) #endif // ENABLE_MODELVOLUME_TRANSFORM { // all volumes in the selection belongs to the same instance, any of them contains the needed data, so we take the first const GLVolume* volume = selection.get_volume(*selection.get_volume_idxs().begin()); #if ENABLE_MODELVOLUME_TRANSFORM update_position_value(volume->get_instance_offset()); update_rotation_value(volume->get_instance_rotation()); update_scale_value(volume->get_instance_scaling_factor()); #else update_position_value(volume->get_offset()); update_rotation_value(volume->get_rotation()); update_scale_value(volume->get_scaling_factor()); #endif // ENABLE_MODELVOLUME_TRANSFORM m_og->enable(); } else if (selection.is_wipe_tower()) { // the selection contains a single volume const GLVolume* volume = selection.get_volume(*selection.get_volume_idxs().begin()); #if ENABLE_MODELVOLUME_TRANSFORM update_position_value(volume->get_volume_offset()); update_rotation_value(volume->get_volume_rotation()); update_scale_value(volume->get_volume_scaling_factor()); #else update_position_value(volume->get_offset()); update_rotation_value(volume->get_rotation()); update_scale_value(volume->get_scaling_factor()); #endif // ENABLE_MODELVOLUME_TRANSFORM m_og->enable(); } else if (selection.is_modifier()) { // the selection contains a single volume const GLVolume* volume = selection.get_volume(*selection.get_volume_idxs().begin()); #if ENABLE_MODELVOLUME_TRANSFORM update_position_value(volume->get_volume_offset()); update_rotation_value(volume->get_volume_rotation()); update_scale_value(volume->get_volume_scaling_factor()); #else update_position_value(volume->get_offset()); update_rotation_value(volume->get_rotation()); update_scale_value(volume->get_scaling_factor()); #endif // ENABLE_MODELVOLUME_TRANSFORM m_og->enable(); } else reset_settings_value(); } void ObjectManipulation::reset_settings_value() { reset_position_value(); reset_rotation_value(); reset_scale_value(); m_og->disable(); } void ObjectManipulation::reset_position_value() { m_og->set_value("position_x", "0"); m_og->set_value("position_y", "0"); m_og->set_value("position_z", "0"); } void ObjectManipulation::reset_rotation_value() { m_og->set_value("rotation_x", "0"); m_og->set_value("rotation_y", "0"); m_og->set_value("rotation_z", "0"); } void ObjectManipulation::reset_scale_value() { m_is_percent_scale = true; m_og->set_value("scale_unit", _("%")); m_og->set_value("scale_x", "100"); m_og->set_value("scale_y", "100"); m_og->set_value("scale_z", "100"); } void ObjectManipulation::update_values() { int selection = ol_selection(); if (selection < 0 || wxGetApp().mainframe->m_plater->model().objects.size() <= selection) { m_og->set_value("position_x", "0"); m_og->set_value("position_y", "0"); m_og->set_value("position_z", "0"); m_og->set_value("scale_x", "0"); m_og->set_value("scale_y", "0"); m_og->set_value("scale_z", "0"); m_og->set_value("rotation_x", "0"); m_og->set_value("rotation_y", "0"); m_og->set_value("rotation_z", "0"); m_og->disable(); return; } m_is_percent_scale = boost::any_cast<wxString>(m_og->get_value("scale_unit")) == _("%"); update_position_values(); update_scale_values(); update_rotation_values(); m_og->enable(); } void ObjectManipulation::update_scale_values() { int selection = ol_selection(); ModelObjectPtrs& objects = wxGetApp().mainframe->m_plater->model().objects; auto instance = objects[selection]->instances.front(); auto size = objects[selection]->instance_bounding_box(0).size(); if (m_is_percent_scale) { m_og->set_value("scale_x", double_to_string(instance->get_scaling_factor(X) * 100, 2)); m_og->set_value("scale_y", double_to_string(instance->get_scaling_factor(Y) * 100, 2)); m_og->set_value("scale_z", double_to_string(instance->get_scaling_factor(Z) * 100, 2)); } else { m_og->set_value("scale_x", double_to_string(instance->get_scaling_factor(X) * size(0) + 0.5, 2)); m_og->set_value("scale_y", double_to_string(instance->get_scaling_factor(Y) * size(1) + 0.5, 2)); m_og->set_value("scale_z", double_to_string(instance->get_scaling_factor(Z) * size(2) + 0.5, 2)); } } void ObjectManipulation::update_position_values() { auto instance = wxGetApp().mainframe->m_plater->model().objects[ol_selection()]->instances.front(); m_og->set_value("position_x", double_to_string(instance->get_offset(X), 2)); m_og->set_value("position_y", double_to_string(instance->get_offset(Y), 2)); m_og->set_value("position_z", double_to_string(instance->get_offset(Z), 2)); } void ObjectManipulation::update_position_value(const Vec3d& position) { m_og->set_value("position_x", double_to_string(position(0), 2)); m_og->set_value("position_y", double_to_string(position(1), 2)); m_og->set_value("position_z", double_to_string(position(2), 2)); } void ObjectManipulation::update_scale_value(const Vec3d& scaling_factor) { // this is temporary // to be able to update the values as size // we need to store somewhere the original size // or have it passed as parameter if (!m_is_percent_scale) m_og->set_value("scale_unit", _("%")); auto scale = scaling_factor * 100.0; m_og->set_value("scale_x", double_to_string(scale(0), 2)); m_og->set_value("scale_y", double_to_string(scale(1), 2)); m_og->set_value("scale_z", double_to_string(scale(2), 2)); } void ObjectManipulation::update_rotation_values() { update_rotation_value(wxGetApp().mainframe->m_plater->model().objects[ol_selection()]->instances.front()->get_rotation()); } void ObjectManipulation::update_rotation_value(double angle, Axis axis) { std::string axis_str; switch (axis) { case X: { axis_str = "rotation_x"; break; } case Y: { axis_str = "rotation_y"; break; } case Z: { axis_str = "rotation_z"; break; } } m_og->set_value(axis_str, round_nearest(int(Geometry::rad2deg(angle)), 0)); } void ObjectManipulation::update_rotation_value(const Vec3d& rotation) { m_og->set_value("rotation_x", double_to_string(round_nearest(Geometry::rad2deg(rotation(0)), 0), 2)); m_og->set_value("rotation_y", double_to_string(round_nearest(Geometry::rad2deg(rotation(1)), 0), 2)); m_og->set_value("rotation_z", double_to_string(round_nearest(Geometry::rad2deg(rotation(2)), 0), 2)); } } //namespace GUI } //namespace Slic3r <commit_msg>Fixed crashing on reset_settings_value()<commit_after>#include "GUI_ObjectManipulation.hpp" #include "GUI_ObjectList.hpp" #include "OptionsGroup.hpp" #include "wxExtensions.hpp" #include "PresetBundle.hpp" #include "Model.hpp" #include "Geometry.hpp" #include <boost/algorithm/string.hpp> namespace Slic3r { namespace GUI { ObjectManipulation::ObjectManipulation(wxWindow* parent): OG_Settings(parent, true) { m_og->set_name(_(L("Object Manipulation"))); m_og->label_width = 100; m_og->set_grid_vgap(5); m_og->set_process_enter(); // We need to update new values only after press ENTER m_og->m_on_change = [this](t_config_option_key opt_key, boost::any value) { if (opt_key == "scale_unit") { const wxString& selection = boost::any_cast<wxString>(value); std::vector<std::string> axes{ "x", "y", "z" }; for (auto axis : axes) { std::string key = "scale_" + axis; m_og->set_side_text(key, selection); } m_is_percent_scale = selection == _("%"); update_scale_values(); return; } }; ConfigOptionDef def; // Objects(sub-objects) name def.label = L("Name"); // def.type = coString; def.gui_type = "legend"; def.tooltip = L("Object name"); def.full_width = true; def.default_value = new ConfigOptionString{ " " }; m_og->append_single_option_line(Option(def, "object_name")); // Legend for object modification auto line = Line{ "", "" }; def.label = ""; def.type = coString; def.width = 50; std::vector<std::string> axes{ "x", "y", "z" }; for (const auto axis : axes) { const auto label = boost::algorithm::to_upper_copy(axis); def.default_value = new ConfigOptionString{ " " + label }; Option option = Option(def, axis + "_axis_legend"); line.append_option(option); } m_og->append_line(line); auto add_og_to_object_settings = [](const std::string& option_name, const std::string& sidetext) { Line line = { _(option_name), "" }; if (option_name == "Scale") { line.near_label_widget = [](wxWindow* parent) { auto btn = new PrusaLockButton(parent, wxID_ANY); btn->Bind(wxEVT_BUTTON, [btn](wxCommandEvent &event) { event.Skip(); wxTheApp->CallAfter([btn]() { wxGetApp().obj_manipul()->set_uniform_scaling(btn->IsLocked()); }); }); return btn; }; } ConfigOptionDef def; def.type = coFloat; def.default_value = new ConfigOptionFloat(0.0); def.width = 50; if (option_name == "Rotation") def.min = -360; const std::string lower_name = boost::algorithm::to_lower_copy(option_name); std::vector<std::string> axes{ "x", "y", "z" }; for (auto axis : axes) { if (axis == "z" && option_name != "Scale") def.sidetext = sidetext; Option option = Option(def, lower_name + "_" + axis); option.opt.full_width = true; line.append_option(option); } if (option_name == "Scale") { def.width = 45; def.type = coStrings; def.gui_type = "select_open"; def.enum_labels.push_back(L("%")); def.enum_labels.push_back(L("mm")); def.default_value = new ConfigOptionStrings{ "mm" }; const Option option = Option(def, lower_name + "_unit"); line.append_option(option); } return line; }; // Settings table m_og->append_line(add_og_to_object_settings(L("Position"), L("mm"))); m_og->append_line(add_og_to_object_settings(L("Rotation"), "°")); m_og->append_line(add_og_to_object_settings(L("Scale"), "mm")); def.label = L("Place on bed"); def.type = coBool; def.tooltip = L("Automatic placing of models on printing bed in Y axis"); def.gui_type = ""; def.sidetext = ""; def.default_value = new ConfigOptionBool{ false }; m_og->append_single_option_line(Option(def, "place_on_bed")); } void ObjectManipulation::Show(const bool show) { if (show == IsShown()) return; m_og->Show(show); if (show && wxGetApp().get_view_mode() != ConfigMenuModeSimple) { m_og->get_grid_sizer()->Show(size_t(0), false); m_og->get_grid_sizer()->Show(size_t(1), false); } } bool ObjectManipulation::IsShown() { return m_og->get_grid_sizer()->IsShown(2); } void ObjectManipulation::UpdateAndShow(const bool show) { if (show) update_settings_value(_3DScene::get_canvas(wxGetApp().canvas3D())->get_selection()); OG_Settings::UpdateAndShow(show); } int ObjectManipulation::ol_selection() { return wxGetApp().obj_list()->get_selected_obj_idx(); } void ObjectManipulation::update_settings_value(const GLCanvas3D::Selection& selection) { #if ENABLE_MODELVOLUME_TRANSFORM if (selection.is_single_full_instance() || selection.is_single_full_object()) #else if (selection.is_single_full_object()) { auto obj_idx = selection.get_object_idx(); if (obj_idx >=0 && !wxGetApp().model_objects()->empty() && (*wxGetApp().model_objects())[obj_idx]->instances.size() == 1) { // all volumes in the selection belongs to the same instance, any of them contains the needed data, so we take the first const GLVolume* volume = selection.get_volume(*selection.get_volume_idxs().begin()); update_position_value(volume->get_offset()); update_rotation_value(volume->get_rotation()); update_scale_value(volume->get_scaling_factor()); m_og->enable(); } else reset_settings_value(); } else if (selection.is_single_full_instance()) #endif // ENABLE_MODELVOLUME_TRANSFORM { // all volumes in the selection belongs to the same instance, any of them contains the needed data, so we take the first const GLVolume* volume = selection.get_volume(*selection.get_volume_idxs().begin()); #if ENABLE_MODELVOLUME_TRANSFORM update_position_value(volume->get_instance_offset()); update_rotation_value(volume->get_instance_rotation()); update_scale_value(volume->get_instance_scaling_factor()); #else update_position_value(volume->get_offset()); update_rotation_value(volume->get_rotation()); update_scale_value(volume->get_scaling_factor()); #endif // ENABLE_MODELVOLUME_TRANSFORM m_og->enable(); } else if (selection.is_wipe_tower()) { // the selection contains a single volume const GLVolume* volume = selection.get_volume(*selection.get_volume_idxs().begin()); #if ENABLE_MODELVOLUME_TRANSFORM update_position_value(volume->get_volume_offset()); update_rotation_value(volume->get_volume_rotation()); update_scale_value(volume->get_volume_scaling_factor()); #else update_position_value(volume->get_offset()); update_rotation_value(volume->get_rotation()); update_scale_value(volume->get_scaling_factor()); #endif // ENABLE_MODELVOLUME_TRANSFORM m_og->enable(); } else if (selection.is_modifier()) { // the selection contains a single volume const GLVolume* volume = selection.get_volume(*selection.get_volume_idxs().begin()); #if ENABLE_MODELVOLUME_TRANSFORM update_position_value(volume->get_volume_offset()); update_rotation_value(volume->get_volume_rotation()); update_scale_value(volume->get_volume_scaling_factor()); #else update_position_value(volume->get_offset()); update_rotation_value(volume->get_rotation()); update_scale_value(volume->get_scaling_factor()); #endif // ENABLE_MODELVOLUME_TRANSFORM m_og->enable(); } else reset_settings_value(); } void ObjectManipulation::reset_settings_value() { reset_position_value(); reset_rotation_value(); reset_scale_value(); m_og->disable(); } wxString def_0 {"0"}; wxString def_100 {"100"}; void ObjectManipulation::reset_position_value() { m_og->set_value("position_x", def_0); m_og->set_value("position_y", def_0); m_og->set_value("position_z", def_0); } void ObjectManipulation::reset_rotation_value() { m_og->set_value("rotation_x", def_0); m_og->set_value("rotation_y", def_0); m_og->set_value("rotation_z", def_0); } void ObjectManipulation::reset_scale_value() { m_is_percent_scale = true; m_og->set_value("scale_unit", _("%")); m_og->set_value("scale_x", def_100); m_og->set_value("scale_y", def_100); m_og->set_value("scale_z", def_100); } void ObjectManipulation::update_values() { int selection = ol_selection(); if (selection < 0 || wxGetApp().mainframe->m_plater->model().objects.size() <= selection) { m_og->set_value("position_x", def_0); m_og->set_value("position_y", def_0); m_og->set_value("position_z", def_0); m_og->set_value("scale_x" , def_0); m_og->set_value("scale_y" , def_0); m_og->set_value("scale_z" , def_0); m_og->set_value("rotation_x", def_0); m_og->set_value("rotation_y", def_0); m_og->set_value("rotation_z", def_0); m_og->disable(); return; } m_is_percent_scale = boost::any_cast<wxString>(m_og->get_value("scale_unit")) == _("%"); update_position_values(); update_scale_values(); update_rotation_values(); m_og->enable(); } void ObjectManipulation::update_scale_values() { int selection = ol_selection(); ModelObjectPtrs& objects = wxGetApp().mainframe->m_plater->model().objects; auto instance = objects[selection]->instances.front(); auto size = objects[selection]->instance_bounding_box(0).size(); if (m_is_percent_scale) { m_og->set_value("scale_x", double_to_string(instance->get_scaling_factor(X) * 100, 2)); m_og->set_value("scale_y", double_to_string(instance->get_scaling_factor(Y) * 100, 2)); m_og->set_value("scale_z", double_to_string(instance->get_scaling_factor(Z) * 100, 2)); } else { m_og->set_value("scale_x", double_to_string(instance->get_scaling_factor(X) * size(0) + 0.5, 2)); m_og->set_value("scale_y", double_to_string(instance->get_scaling_factor(Y) * size(1) + 0.5, 2)); m_og->set_value("scale_z", double_to_string(instance->get_scaling_factor(Z) * size(2) + 0.5, 2)); } } void ObjectManipulation::update_position_values() { auto instance = wxGetApp().mainframe->m_plater->model().objects[ol_selection()]->instances.front(); m_og->set_value("position_x", double_to_string(instance->get_offset(X), 2)); m_og->set_value("position_y", double_to_string(instance->get_offset(Y), 2)); m_og->set_value("position_z", double_to_string(instance->get_offset(Z), 2)); } void ObjectManipulation::update_position_value(const Vec3d& position) { m_og->set_value("position_x", double_to_string(position(0), 2)); m_og->set_value("position_y", double_to_string(position(1), 2)); m_og->set_value("position_z", double_to_string(position(2), 2)); } void ObjectManipulation::update_scale_value(const Vec3d& scaling_factor) { // this is temporary // to be able to update the values as size // we need to store somewhere the original size // or have it passed as parameter if (!m_is_percent_scale) m_og->set_value("scale_unit", _("%")); auto scale = scaling_factor * 100.0; m_og->set_value("scale_x", double_to_string(scale(0), 2)); m_og->set_value("scale_y", double_to_string(scale(1), 2)); m_og->set_value("scale_z", double_to_string(scale(2), 2)); } void ObjectManipulation::update_rotation_values() { update_rotation_value(wxGetApp().mainframe->m_plater->model().objects[ol_selection()]->instances.front()->get_rotation()); } void ObjectManipulation::update_rotation_value(double angle, Axis axis) { std::string axis_str; switch (axis) { case X: { axis_str = "rotation_x"; break; } case Y: { axis_str = "rotation_y"; break; } case Z: { axis_str = "rotation_z"; break; } } m_og->set_value(axis_str, round_nearest(int(Geometry::rad2deg(angle)), 0)); } void ObjectManipulation::update_rotation_value(const Vec3d& rotation) { m_og->set_value("rotation_x", double_to_string(round_nearest(Geometry::rad2deg(rotation(0)), 0), 2)); m_og->set_value("rotation_y", double_to_string(round_nearest(Geometry::rad2deg(rotation(1)), 0), 2)); m_og->set_value("rotation_z", double_to_string(round_nearest(Geometry::rad2deg(rotation(2)), 0), 2)); } } //namespace GUI } //namespace Slic3r <|endoftext|>
<commit_before>/** * @file hmm_util_impl.hpp * @author Ryan Curtin * * Implementation of HMM utilities to load arbitrary HMM types. */ #ifndef __MLPACK_METHODS_HMM_HMM_UTIL_IMPL_HPP #define __MLPACK_METHODS_HMM_HMM_UTIL_IMPL_HPP #include <mlpack/core.hpp> #include <mlpack/methods/hmm/hmm.hpp> #include <mlpack/methods/gmm/gmm.hpp> namespace mlpack { namespace hmm { // Forward declarations of utility functions. // Set up the archive for deserialization. template<typename ActionType, typename ArchiveType, typename ExtraInfoType> void LoadHMMAndPerformActionHelper(const std::string& modelFile, ExtraInfoType* x = NULL); // Actually deserialize into the correct type. template<typename ActionType, typename ArchiveType, typename HMMType, typename ExtraInfoType> void DeserializeHMMAndPerformAction(ArchiveType& ar, ExtraInfoType* x = NULL); template<typename ActionType, typename ExtraInfoType> void LoadHMMAndPerformAction(const std::string& modelFile, ExtraInfoType* x) { using namespace boost::archive; const std::string extension = data::Extension(modelFile); if (extension == "xml") LoadHMMAndPerformActionHelper<ActionType, xml_iarchive>(modelFile, x); else if (extension == "bin") LoadHMMAndPerformActionHelper<ActionType, binary_iarchive>(modelFile, x); else if (extension == "txt") LoadHMMAndPerformActionHelper<ActionType, text_iarchive>(modelFile, x); else Log::Fatal << "Unknown extension '" << extension << "' for HMM model file " << "(known: 'xml', 'txt', 'bin')." << std::endl; } template<typename ActionType, typename ArchiveType, typename ExtraInfoType> void LoadHMMAndPerformActionHelper(const std::string& modelFile, ExtraInfoType* x) { std::ifstream ifs(modelFile); ArchiveType ar(ifs); // Read in the unsigned integer that denotes the type of the model. char type; ar >> data::CreateNVP(type, "hmm_type"); using namespace mlpack::distribution; switch (type) { case HMMType::DiscreteHMM: DeserializeHMMAndPerformAction<ActionType, ArchiveType, HMM<DiscreteDistribution>>(ar, x); break; case HMMType::GaussianHMM: DeserializeHMMAndPerformAction<ActionType, ArchiveType, HMM<GaussianDistribution>>(ar, x); break; case HMMType::GaussianMixtureModelHMM: DeserializeHMMAndPerformAction<ActionType, ArchiveType, HMM<gmm::GMM<>>>(ar, x); break; default: Log::Fatal << "Unknown HMM type '" << (unsigned int) type << "'!" << std::endl; } } template<typename ActionType, typename ArchiveType, typename HMMType, typename ExtraInfoType> void DeserializeHMMAndPerformAction(ArchiveType& ar, ExtraInfoType* x) { // Extract the HMM and perform the action. HMMType hmm; ar >> data::CreateNVP(hmm, "hmm"); ActionType::Apply(hmm, x); } // Helper function. template<typename ArchiveType, typename HMMType> void SaveHMMHelper(HMMType& hmm, const std::string& modelFile); template<typename HMMType> char GetHMMType(); template<typename HMMType> void SaveHMM(HMMType& hmm, const std::string& modelFile) { using namespace boost::archive; const std::string extension = data::Extension(modelFile); if (extension == "xml") SaveHMMHelper<xml_oarchive>(hmm, modelFile); else if (extension == "bin") SaveHMMHelper<binary_oarchive>(hmm, modelFile); else if (extension == "txt") SaveHMMHelper<text_oarchive>(hmm, modelFile); else Log::Fatal << "Unknown extension '" << extension << "' for HMM model file." << std::endl; } template<typename ArchiveType, typename HMMType> void SaveHMMHelper(HMMType& hmm, const std::string& modelFile) { std::ofstream ofs(modelFile); ArchiveType ar(ofs); // Write out the unsigned integer that denotes the type of the model. char type = GetHMMType<HMMType>(); if (type == char(-1)) Log::Fatal << "Unknown HMM type given to SaveHMM()!" << std::endl; ar << data::CreateNVP(type, "hmm_type"); ar << data::CreateNVP(hmm, "hmm"); } // Utility functions to turn a type into something we can store. template<typename HMMType> char GetHMMType() { return char(-1); } template<> char GetHMMType<HMM<distribution::DiscreteDistribution>>() { return HMMType::DiscreteHMM; } template<> char GetHMMType<HMM<distribution::GaussianDistribution>>() { return HMMType::GaussianHMM; } template<> char GetHMMType<HMM<gmm::GMM<>>>() { return HMMType::GaussianMixtureModelHMM; } } // namespace hmm } // namespace mlpack #endif <commit_msg>Add error handling when streams fail to open.<commit_after>/** * @file hmm_util_impl.hpp * @author Ryan Curtin * * Implementation of HMM utilities to load arbitrary HMM types. */ #ifndef __MLPACK_METHODS_HMM_HMM_UTIL_IMPL_HPP #define __MLPACK_METHODS_HMM_HMM_UTIL_IMPL_HPP #include <mlpack/core.hpp> #include <mlpack/methods/hmm/hmm.hpp> #include <mlpack/methods/gmm/gmm.hpp> namespace mlpack { namespace hmm { // Forward declarations of utility functions. // Set up the archive for deserialization. template<typename ActionType, typename ArchiveType, typename ExtraInfoType> void LoadHMMAndPerformActionHelper(const std::string& modelFile, ExtraInfoType* x = NULL); // Actually deserialize into the correct type. template<typename ActionType, typename ArchiveType, typename HMMType, typename ExtraInfoType> void DeserializeHMMAndPerformAction(ArchiveType& ar, ExtraInfoType* x = NULL); template<typename ActionType, typename ExtraInfoType> void LoadHMMAndPerformAction(const std::string& modelFile, ExtraInfoType* x) { using namespace boost::archive; const std::string extension = data::Extension(modelFile); if (extension == "xml") LoadHMMAndPerformActionHelper<ActionType, xml_iarchive>(modelFile, x); else if (extension == "bin") LoadHMMAndPerformActionHelper<ActionType, binary_iarchive>(modelFile, x); else if (extension == "txt") LoadHMMAndPerformActionHelper<ActionType, text_iarchive>(modelFile, x); else Log::Fatal << "Unknown extension '" << extension << "' for HMM model file " << "(known: 'xml', 'txt', 'bin')." << std::endl; } template<typename ActionType, typename ArchiveType, typename ExtraInfoType> void LoadHMMAndPerformActionHelper(const std::string& modelFile, ExtraInfoType* x) { std::ifstream ifs(modelFile); if (ifs.fail()) Log::Fatal << "Cannot open model file '" << modelFile << "' for loading!" << std::endl; ArchiveType ar(ifs); // Read in the unsigned integer that denotes the type of the model. char type; ar >> data::CreateNVP(type, "hmm_type"); using namespace mlpack::distribution; switch (type) { case HMMType::DiscreteHMM: DeserializeHMMAndPerformAction<ActionType, ArchiveType, HMM<DiscreteDistribution>>(ar, x); break; case HMMType::GaussianHMM: DeserializeHMMAndPerformAction<ActionType, ArchiveType, HMM<GaussianDistribution>>(ar, x); break; case HMMType::GaussianMixtureModelHMM: DeserializeHMMAndPerformAction<ActionType, ArchiveType, HMM<gmm::GMM<>>>(ar, x); break; default: Log::Fatal << "Unknown HMM type '" << (unsigned int) type << "'!" << std::endl; } } template<typename ActionType, typename ArchiveType, typename HMMType, typename ExtraInfoType> void DeserializeHMMAndPerformAction(ArchiveType& ar, ExtraInfoType* x) { // Extract the HMM and perform the action. HMMType hmm; ar >> data::CreateNVP(hmm, "hmm"); ActionType::Apply(hmm, x); } // Helper function. template<typename ArchiveType, typename HMMType> void SaveHMMHelper(HMMType& hmm, const std::string& modelFile); template<typename HMMType> char GetHMMType(); template<typename HMMType> void SaveHMM(HMMType& hmm, const std::string& modelFile) { using namespace boost::archive; const std::string extension = data::Extension(modelFile); if (extension == "xml") SaveHMMHelper<xml_oarchive>(hmm, modelFile); else if (extension == "bin") SaveHMMHelper<binary_oarchive>(hmm, modelFile); else if (extension == "txt") SaveHMMHelper<text_oarchive>(hmm, modelFile); else Log::Fatal << "Unknown extension '" << extension << "' for HMM model file." << std::endl; } template<typename ArchiveType, typename HMMType> void SaveHMMHelper(HMMType& hmm, const std::string& modelFile) { std::ofstream ofs(modelFile); if (ofs.fail()) Log::Fatal << "Cannot open model file '" << modelFile << "' for saving!" << std::endl; ArchiveType ar(ofs); // Write out the unsigned integer that denotes the type of the model. char type = GetHMMType<HMMType>(); if (type == char(-1)) Log::Fatal << "Unknown HMM type given to SaveHMM()!" << std::endl; ar << data::CreateNVP(type, "hmm_type"); ar << data::CreateNVP(hmm, "hmm"); } // Utility functions to turn a type into something we can store. template<typename HMMType> char GetHMMType() { return char(-1); } template<> char GetHMMType<HMM<distribution::DiscreteDistribution>>() { return HMMType::DiscreteHMM; } template<> char GetHMMType<HMM<distribution::GaussianDistribution>>() { return HMMType::GaussianHMM; } template<> char GetHMMType<HMM<gmm::GMM<>>>() { return HMMType::GaussianMixtureModelHMM; } } // namespace hmm } // namespace mlpack #endif <|endoftext|>
<commit_before><commit_msg>Changed order in which attributes are set when loading. If the value was set before the maxValue was set, the value got set to maxValue because of the consistency checks.<commit_after><|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief RX24T GPS サンプル @n ・P00(4) ピンに赤色LED(VF:1.9V)を吸い込みで接続する @n ・PB6/RXD5(27) <--- GPS-TX @n ・PB5/TXD5(28) ---> GPS-RX Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 ([email protected]) */ //=====================================================================// #include "common/cmt_io.hpp" #include "common/sci_io.hpp" #include "common/fifo.hpp" #include "common/format.hpp" #include "common/nmea_dec.hpp" namespace { class cmt_task { public: void operator() () { } }; device::cmt_io<device::CMT0, cmt_task> cmt_; typedef utils::fifo<uint8_t, 256> fifo256; typedef utils::fifo<uint16_t, 512> fifo512; device::sci_io<device::SCI1, fifo256, fifo256> sci1_; typedef device::sci_io<device::SCI5, fifo512, fifo256> SCI5; SCI5 sci5_; utils::nmea_dec<SCI5> nmea_(sci5_); } extern "C" { void sci_putch(char ch) { sci1_.putch(ch); } void sci_puts(const char* str) { sci1_.puts(str); } char sci_getch(void) { return sci1_.getch(); } uint16_t sci_length() { return sci1_.recv_length(); } } int main(int argc, char** argv); int main(int argc, char** argv) { device::SYSTEM::PRCR = 0xA50B; // クロック、低消費電力、関係書き込み許可 device::SYSTEM::MEMWAIT = 0b10; // 80MHz 動作 wait 設定 while(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm("nop"); device::SYSTEM::OPCCR = 0; // 高速モード選択 while(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm("nop"); // clock osc 10MHz device::SYSTEM::MOSCWTCR = 9; // 4ms wait // メインクロック・ドライブ能力設定、内部発信 device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV21.b(1); device::SYSTEM::MOSCCR.MOSTP = 0; // メインクロック発振器動作 while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm("nop"); device::SYSTEM::PLLCR.STC = 0b001111; // PLL input: 1, PLL 8 倍(80MHz) device::SYSTEM::PLLCR2.PLLEN = 0; // PLL 動作 while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm("nop"); device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(2) // 1/4 (80/4=20) | device::SYSTEM::SCKCR.ICK.b(0) // 1/1 (80/1=80) | device::SYSTEM::SCKCR.PCKA.b(0) // 1/1 (80/1=80) | device::SYSTEM::SCKCR.PCKB.b(1) // 1/2 (80/2=40) | device::SYSTEM::SCKCR.PCKD.b(1); // 1/2 (120/2=60) device::SYSTEM::SCKCR3.CKSEL = 0b100; ///< PLL 選択 { // タイマー設定(60Hz) uint8_t cmt_level = 4; cmt_.start(60, cmt_level); } { // SCI1 設定 uint8_t sci_level = 2; sci1_.start(115200, sci_level); } { // SCI5 設定 (GPS) uint8_t sci_level = 2; sci5_.start(9600, sci_level); } utils::format("RX24T GPS sample\n"); device::PORT0::PDR.B0 = 1; // output uint32_t cnt = 0; while(1) { cmt_.sync(); auto f = nmea_.service(); if(f) { utils::format("Time: %s, ") % nmea_.get_time(); utils::format("Lat: %s, ") % nmea_.get_lat(); utils::format("Lon: %s\n") % nmea_.get_lon(); }; // while(sci5_.recv_length() > 0) { // auto ch = sci5_.getch(); // sci1_.putch(ch); // } ++cnt; if(cnt >= 30) { cnt = 0; } device::PORT0::PODR.B0 = (cnt < 10) ? 0 : 1; } } <commit_msg>update satelite num<commit_after>//=====================================================================// /*! @file @brief RX24T GPS サンプル @n ・P00(4) ピンに赤色LED(VF:1.9V)を吸い込みで接続する @n ・PB6/RXD5(27) <--- GPS-TX @n ・PB5/TXD5(28) ---> GPS-RX Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 ([email protected]) */ //=====================================================================// #include "common/cmt_io.hpp" #include "common/sci_io.hpp" #include "common/fifo.hpp" #include "common/format.hpp" #include "common/nmea_dec.hpp" namespace { class cmt_task { public: void operator() () { } }; device::cmt_io<device::CMT0, cmt_task> cmt_; typedef utils::fifo<uint8_t, 256> fifo256; typedef utils::fifo<uint16_t, 512> fifo512; device::sci_io<device::SCI1, fifo256, fifo256> sci1_; typedef device::sci_io<device::SCI5, fifo512, fifo256> SCI5; SCI5 sci5_; utils::nmea_dec<SCI5> nmea_(sci5_); } extern "C" { void sci_putch(char ch) { sci1_.putch(ch); } void sci_puts(const char* str) { sci1_.puts(str); } char sci_getch(void) { return sci1_.getch(); } uint16_t sci_length() { return sci1_.recv_length(); } } int main(int argc, char** argv); int main(int argc, char** argv) { device::SYSTEM::PRCR = 0xA50B; // クロック、低消費電力、関係書き込み許可 device::SYSTEM::MEMWAIT = 0b10; // 80MHz 動作 wait 設定 while(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm("nop"); device::SYSTEM::OPCCR = 0; // 高速モード選択 while(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm("nop"); // clock osc 10MHz device::SYSTEM::MOSCWTCR = 9; // 4ms wait // メインクロック・ドライブ能力設定、内部発信 device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV21.b(1); device::SYSTEM::MOSCCR.MOSTP = 0; // メインクロック発振器動作 while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm("nop"); device::SYSTEM::PLLCR.STC = 0b001111; // PLL input: 1, PLL 8 倍(80MHz) device::SYSTEM::PLLCR2.PLLEN = 0; // PLL 動作 while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm("nop"); device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(2) // 1/4 (80/4=20) | device::SYSTEM::SCKCR.ICK.b(0) // 1/1 (80/1=80) | device::SYSTEM::SCKCR.PCKA.b(0) // 1/1 (80/1=80) | device::SYSTEM::SCKCR.PCKB.b(1) // 1/2 (80/2=40) | device::SYSTEM::SCKCR.PCKD.b(1); // 1/2 (120/2=60) device::SYSTEM::SCKCR3.CKSEL = 0b100; ///< PLL 選択 { // タイマー設定(60Hz) uint8_t cmt_level = 4; cmt_.start(60, cmt_level); } { // SCI1 設定 uint8_t sci_level = 2; sci1_.start(115200, sci_level); } { // SCI5 設定 (GPS) uint8_t sci_level = 2; sci5_.start(9600, sci_level); } utils::format("RX24T GPS sample\n"); device::PORT0::PDR.B0 = 1; // output uint32_t cnt = 0; while(1) { cmt_.sync(); auto f = nmea_.service(); if(f) { utils::format("%s: ") % nmea_.get_satellite(); utils::format("Time: %s, ") % nmea_.get_time(); utils::format("Lat: %s, ") % nmea_.get_lat(); utils::format("Lon: %s\n") % nmea_.get_lon(); }; // while(sci5_.recv_length() > 0) { // auto ch = sci5_.getch(); // sci1_.putch(ch); // } ++cnt; if(cnt >= 30) { cnt = 0; } device::PORT0::PODR.B0 = (cnt < 10) ? 0 : 1; } } <|endoftext|>
<commit_before>/* Copyright 2008 Larry Gritz and the other authors and contributors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the software's owners nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (This is the Modified BSD License) */ #include <cstdio> #include <cstdlib> #include <cmath> #include <ctime> #include <iostream> #include <iterator> #include <boost/foreach.hpp> #include "argparse.h" #include "strutil.h" #include "imageio.h" using namespace OpenImageIO; static bool verbose = false; static bool sum = false; static bool help = false; static std::vector<std::string> filenames; static void print_info (const std::string &filename, size_t namefieldlength, ImageInput *input, ImageSpec &spec, bool verbose, bool sum, long long &totalsize) { std::string padding (std::max(0UL, namefieldlength - filename.length()), ' '); printf ("%s%s : %4d x %4d", filename.c_str(), padding.c_str(), spec.width, spec.height); if (spec.depth > 1) printf (" x %4d", spec.depth); printf (", %d channel, %s%s", spec.nchannels, spec.format.c_str(), spec.depth > 1 ? " volume" : ""); printf (" %s", input->format_name()); if (sum) { totalsize += spec.image_bytes(); printf (" (%.2f MB)", (float)spec.image_bytes() / (1024.0*1024.0)); } printf ("\n"); if (verbose) { printf (" channel list: "); for (int i = 0; i < spec.nchannels; ++i) { printf ("%s%s", spec.channelnames[i].c_str(), (i == spec.nchannels-1) ? "" : ", "); } printf ("\n"); if (spec.x || spec.y || spec.z) { printf (" pixel data origin: x=%d, y=%d", spec.x, spec.y); if (spec.depth > 1) printf (", z=%d\n", spec.x, spec.y, spec.z); printf ("\n"); } if (spec.full_x || spec.full_y || spec.full_z || (spec.full_width != spec.width && spec.full_width != 0) || (spec.full_height != spec.height && spec.full_height != 0) || (spec.full_depth != spec.depth && spec.full_depth != 0)) { printf (" full/display size: %d x %d", spec.full_width, spec.full_height); if (spec.depth > 1) printf (" x %d", spec.full_depth); printf ("\n"); printf (" full/display origin: %d, %d", spec.full_x, spec.full_y); if (spec.depth > 1) printf (", %d", spec.full_z); printf ("\n"); } if (spec.tile_width) { printf (" tile size: %d x %d", spec.tile_width, spec.tile_height); if (spec.depth > 1) printf (" x %d", spec.tile_depth); printf ("\n"); } const char *cspacename [] = { "unknown", "linear", "gamma %g", "sRGB" }; printf (" Color space: %s\n", Strutil::format(cspacename[(int)spec.linearity], spec.gamma).c_str()); BOOST_FOREACH (const ImageIOParameter &p, spec.extra_attribs) { printf (" %s: ", p.name().c_str()); if (p.type() == TypeDesc::STRING) printf ("\"%s\"", *(const char **)p.data()); else if (p.type() == TypeDesc::FLOAT) printf ("%g", *(const float *)p.data()); else if (p.type() == TypeDesc::DOUBLE) printf ("%g", *(const float *)p.data()); else if (p.type() == TypeDesc::INT) printf ("%d", *(const int *)p.data()); else if (p.type() == TypeDesc::UINT) printf ("%d", *(const unsigned int *)p.data()); else if (p.type() == TypeDesc::UINT16) printf ("%u", *(const unsigned short *)p.data()); else if (p.type() == TypeDesc::INT16) printf ("%d", *(const short *)p.data()); else if (p.type() == TypeDesc::PT_MATRIX) { const float *m = (const float *)p.data(); printf ("%g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g", m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15]); } else { printf ("<unknown data type> (base %d, agg %d vec %d)", p.type().basetype, p.type().aggregate, p.type().vecsemantics); } printf ("\n"); } } } static int parse_files (int argc, const char *argv[]) { for (int i = 0; i < argc; i++) filenames.push_back (argv[i]); return 0; } int main (int argc, const char *argv[]) { ArgParse ap; ap.options ("Usage: iinfo [options] filename...", "%*", parse_files, "", "--help", &help, "Print help message", "-v", &verbose, "Verbose output", "-s", &sum, "Sum the image sizes", NULL); if (ap.parse(argc, argv) < 0) { std::cerr << ap.error_message() << std::endl; ap.usage (); return EXIT_FAILURE; } if (help) { ap.usage (); exit (EXIT_FAILURE); } // Find the longest filename size_t longestname = 0; BOOST_FOREACH (const std::string &s, filenames) longestname = std::max (longestname, s.length()); long long totalsize = 0; BOOST_FOREACH (const std::string &s, filenames) { ImageInput *in = ImageInput::create (s.c_str(), "" /* searchpath */); if (! in) { std::cerr << OpenImageIO::error_message() << "\n"; continue; } ImageSpec spec; if (in->open (s.c_str(), spec)) { print_info (s, longestname, in, spec, verbose, sum, totalsize); in->close (); } else { fprintf (stderr, "iinfo: Could not open \"%s\" : %s\n", s.c_str(), in->error_message().c_str()); } delete in; } if (sum) { double t = (double)totalsize / (1024.0*1024.0); if (t > 1024.0) printf ("Total size: %.2f GB\n", t/1024.0); else printf ("Total size: %.2f MB\n", t); } return 0; } <commit_msg>Remove compiler error on 32 bit linux.<commit_after>/* Copyright 2008 Larry Gritz and the other authors and contributors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the software's owners nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (This is the Modified BSD License) */ #include <cstdio> #include <cstdlib> #include <cmath> #include <ctime> #include <iostream> #include <iterator> #include <boost/foreach.hpp> #include "argparse.h" #include "strutil.h" #include "imageio.h" using namespace OpenImageIO; static bool verbose = false; static bool sum = false; static bool help = false; static std::vector<std::string> filenames; static void print_info (const std::string &filename, size_t namefieldlength, ImageInput *input, ImageSpec &spec, bool verbose, bool sum, long long &totalsize) { std::string padding (std::max((size_t)0, namefieldlength - filename.length()), ' '); printf ("%s%s : %4d x %4d", filename.c_str(), padding.c_str(), spec.width, spec.height); if (spec.depth > 1) printf (" x %4d", spec.depth); printf (", %d channel, %s%s", spec.nchannels, spec.format.c_str(), spec.depth > 1 ? " volume" : ""); printf (" %s", input->format_name()); if (sum) { totalsize += spec.image_bytes(); printf (" (%.2f MB)", (float)spec.image_bytes() / (1024.0*1024.0)); } printf ("\n"); if (verbose) { printf (" channel list: "); for (int i = 0; i < spec.nchannels; ++i) { printf ("%s%s", spec.channelnames[i].c_str(), (i == spec.nchannels-1) ? "" : ", "); } printf ("\n"); if (spec.x || spec.y || spec.z) { printf (" pixel data origin: x=%d, y=%d", spec.x, spec.y); if (spec.depth > 1) printf (", z=%d\n", spec.x, spec.y, spec.z); printf ("\n"); } if (spec.full_x || spec.full_y || spec.full_z || (spec.full_width != spec.width && spec.full_width != 0) || (spec.full_height != spec.height && spec.full_height != 0) || (spec.full_depth != spec.depth && spec.full_depth != 0)) { printf (" full/display size: %d x %d", spec.full_width, spec.full_height); if (spec.depth > 1) printf (" x %d", spec.full_depth); printf ("\n"); printf (" full/display origin: %d, %d", spec.full_x, spec.full_y); if (spec.depth > 1) printf (", %d", spec.full_z); printf ("\n"); } if (spec.tile_width) { printf (" tile size: %d x %d", spec.tile_width, spec.tile_height); if (spec.depth > 1) printf (" x %d", spec.tile_depth); printf ("\n"); } const char *cspacename [] = { "unknown", "linear", "gamma %g", "sRGB" }; printf (" Color space: %s\n", Strutil::format(cspacename[(int)spec.linearity], spec.gamma).c_str()); BOOST_FOREACH (const ImageIOParameter &p, spec.extra_attribs) { printf (" %s: ", p.name().c_str()); if (p.type() == TypeDesc::STRING) printf ("\"%s\"", *(const char **)p.data()); else if (p.type() == TypeDesc::FLOAT) printf ("%g", *(const float *)p.data()); else if (p.type() == TypeDesc::DOUBLE) printf ("%g", *(const float *)p.data()); else if (p.type() == TypeDesc::INT) printf ("%d", *(const int *)p.data()); else if (p.type() == TypeDesc::UINT) printf ("%d", *(const unsigned int *)p.data()); else if (p.type() == TypeDesc::UINT16) printf ("%u", *(const unsigned short *)p.data()); else if (p.type() == TypeDesc::INT16) printf ("%d", *(const short *)p.data()); else if (p.type() == TypeDesc::PT_MATRIX) { const float *m = (const float *)p.data(); printf ("%g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g", m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15]); } else { printf ("<unknown data type> (base %d, agg %d vec %d)", p.type().basetype, p.type().aggregate, p.type().vecsemantics); } printf ("\n"); } } } static int parse_files (int argc, const char *argv[]) { for (int i = 0; i < argc; i++) filenames.push_back (argv[i]); return 0; } int main (int argc, const char *argv[]) { ArgParse ap; ap.options ("Usage: iinfo [options] filename...", "%*", parse_files, "", "--help", &help, "Print help message", "-v", &verbose, "Verbose output", "-s", &sum, "Sum the image sizes", NULL); if (ap.parse(argc, argv) < 0) { std::cerr << ap.error_message() << std::endl; ap.usage (); return EXIT_FAILURE; } if (help) { ap.usage (); exit (EXIT_FAILURE); } // Find the longest filename size_t longestname = 0; BOOST_FOREACH (const std::string &s, filenames) longestname = std::max (longestname, s.length()); long long totalsize = 0; BOOST_FOREACH (const std::string &s, filenames) { ImageInput *in = ImageInput::create (s.c_str(), "" /* searchpath */); if (! in) { std::cerr << OpenImageIO::error_message() << "\n"; continue; } ImageSpec spec; if (in->open (s.c_str(), spec)) { print_info (s, longestname, in, spec, verbose, sum, totalsize); in->close (); } else { fprintf (stderr, "iinfo: Could not open \"%s\" : %s\n", s.c_str(), in->error_message().c_str()); } delete in; } if (sum) { double t = (double)totalsize / (1024.0*1024.0); if (t > 1024.0) printf ("Total size: %.2f GB\n", t/1024.0); else printf ("Total size: %.2f MB\n", t); } return 0; } <|endoftext|>