id
stringlengths
21
25
content
stringlengths
164
2.33k
codereview_cpp_data_2
exit(EXIT_FAILURE); } } - if(runos_os) { cmd = string_format("cp \"$(which vc3-builder)\" '%s'", scratch_dir); int k = system(cmd); free(cmd), since it was allocated in the if-else block above. exit(EXIT_FAILURE); } } + + free(cmd); + if(runos_os) { cmd = string_format("cp \"$(which vc3-builder)\" '%s'", scratch_dir); int k = system(cmd);
codereview_cpp_data_8
g_autoptr(GString) txn_title = g_string_new (""); if (is_install) g_string_append (txn_title, "install"); else if (self->revision) g_string_append (txn_title, "deploy"); else Another `else if (self->refspec` for rebases? g_autoptr(GString) txn_title = g_string_new (""); if (is_install) g_string_append (txn_title, "install"); + else if (self->refspec) + g_string_append (txn_title, "rebase"); else if (self->revision) g_string_append (txn_title, "deploy"); else
codereview_cpp_data_19
} if( - cxxTokenTypeIs(t->pPrev,CXXTokenTypeKeyword) && - (t->pPrev->eKeyword == CXXKeywordDECLTYPE) && t->pNext ) { Cannot we unify the two lines into ``` cxxTokenIsKeyword(t->pPrev, CXXKeywordDECLTYPE) && ``` ? } if( + cxxTokenIsKeyword(t->pPrev,CXXKeywordDECLTYPE) && t->pNext ) {
codereview_cpp_data_29
bool Battle::Arena::CanRetreatOpponent( int color ) const { - const Force * const force = ( army1->GetColor() == color ) ? army1 : army2; - const HeroBase * const commander = force->GetCommander(); - if ( !commander ) { - return false; - } - const Castle * const castle = commander->inCastle(); - return commander->isHeroes() && !castle; } bool Battle::Arena::isSpellcastDisabled() const Could we please just remove `&& world.GetKingdom( hero->GetColor() ).GetCastles().size()` for the whole pull request changes? bool Battle::Arena::CanRetreatOpponent( int color ) const { + const HeroBase * hero = army1->GetColor() == color ? army1->GetCommander() : army2->GetCommander(); + return hero && hero->isHeroes() && NULL == hero->inCastle(); } bool Battle::Arena::isSpellcastDisabled() const
codereview_cpp_data_38
plink = NULL; memset(&changed, 0, sizeof changed); - changed.newnode = true; Node* p; It might be clearer to keep it false in constructor and set the flag at `MegaClient::readnodes` call to new Node. plink = NULL; memset(&changed, 0, sizeof changed); Node* p;
codereview_cpp_data_43
movePointsLeft = _remainingMovePoints - consumedMovePoints; } else { - movePointsLeft = _maxMovePoints - ( consumedMovePoints - _remainingMovePoints ) % _maxMovePoints; } lastMove = movePointsLeft >= srcTilePenalty && movePointsLeft <= dstTilePenalty; Please add parentheses for `( consumedMovePoints - _remainingMovePoints ) % _maxMovePoints` for better code readability. movePointsLeft = _remainingMovePoints - consumedMovePoints; } else { + movePointsLeft = _maxMovePoints - ( ( consumedMovePoints - _remainingMovePoints ) % _maxMovePoints ); } lastMove = movePointsLeft >= srcTilePenalty && movePointsLeft <= dstTilePenalty;
codereview_cpp_data_50
#ifdef HAVE_ERRNO_H #include <errno.h> -#elif defined(__APPLE__) -#include <errno.h> #endif - /********************************************* * UID, GID access methods * *********************************************/ I think we should fix HAVE_ERRNO_H for APPLE #ifdef HAVE_ERRNO_H #include <errno.h> #endif /********************************************* * UID, GID access methods * *********************************************/
codereview_cpp_data_51
megaApi[0] = new MegaApi(APP_KEY.c_str(), megaApiCacheFolder(0).c_str(), USER_AGENT.c_str()); - MegaApiImpl* impl = *((MegaApiImpl**)(((char*)megaApi[0]) + sizeof(*megaApi[0])) - 1); //megaApi[0]->pImpl; - MegaClient* client = impl->getMegaClient(); - client->clientname = "0 "; - megaApi[0]->setLogLevel(MegaApi::LOG_LEVEL_DEBUG); megaApi[0]->addListener(this); This approach breaks encapsulation in an ugly way. I know this is a test, but... let's be elegant here too. I think you should find another way to differentiate between MegaApi instances in the log (which is very useful, indeed). It could be based on the thread-id (each instance runs in a different one), or prepare a public interface `MegaApi::setClientName(const char *clientname)` that properly allows to set it. megaApi[0] = new MegaApi(APP_KEY.c_str(), megaApiCacheFolder(0).c_str(), USER_AGENT.c_str()); + megaApi[0]->setLoggingName("0"); megaApi[0]->setLogLevel(MegaApi::LOG_LEVEL_DEBUG); megaApi[0]->addListener(this);
codereview_cpp_data_70
const { if (not transactions_) { types::SharedTxsCollectionType result; - auto transactions_amount = 0u; - for (const auto &batch : batches_) { - transactions_amount += batch->transactions().size(); - } result.reserve(transactions_amount); for (const auto &batch : batches_) { auto &transactions = batch->transactions(); I think, we counting size can be done more elegantly by ``` auto transactions_amount = std::accumulate( std::next(std::begin(batches_)), std::end(batches_), batches_->front().transactions().size(), [](size_t acc_size, decltype(batches_->front()) batch) { return acc_size + batch.transactions().size(); }); ``` Sorry for styling, for some reason new lines did not appear const { if (not transactions_) { types::SharedTxsCollectionType result; + auto transactions_amount = + std::accumulate(std::begin(batches_), + std::end(batches_), + 0ul, + [](size_t acc_size, auto batch) { + return acc_size + batch->transactions().size(); + }); result.reserve(transactions_amount); for (const auto &batch : batches_) { auto &transactions = batch->transactions();
codereview_cpp_data_73
Tnode &operator=(Tnode &&) = default; /** - * numberOfChildren : To count the number of children a node in the trie has - * @param node : A trie node whose children need to be counted * @return count of the number of children of the given node (max 26) */ inline int numberOfChildren(Tnode *node) { Please check out other parts of the code for minor issues like this. ```suggestion * @brief Function to insert a word in the trie * @param entry the string entry to be inserted in the trie ``` Tnode &operator=(Tnode &&) = default; /** + * @brief Function to count the number of children a node in the trie has + * @param node a trie node whose children need to be counted * @return count of the number of children of the given node (max 26) */ inline int numberOfChildren(Tnode *node) {
codereview_cpp_data_75
template <typename TensorDataType> bool hypergradient_adam<TensorDataType>::save_to_checkpoint_distributed(persist& p, std::string name_prefix) { - write_cereal_archive<hypergradient_adam<TensorDataType>>(*this, p, "hypergradient_adam.xml"); char l_name[512]; sprintf(l_name, "%s_optimizer_adam_moment1_%lldx%lld", name_prefix.c_str(), m_moment1->Height(), m_moment2->Width()); ```suggestion write_cereal_archive(*this, p, "hypergradient_adam.xml"); ``` template <typename TensorDataType> bool hypergradient_adam<TensorDataType>::save_to_checkpoint_distributed(persist& p, std::string name_prefix) { + write_cereal_archive(*this, p, "hypergradient_adam.xml"); char l_name[512]; sprintf(l_name, "%s_optimizer_adam_moment1_%lldx%lld", name_prefix.c_str(), m_moment1->Height(), m_moment2->Width());
codereview_cpp_data_78
return f(x.a, x.b); } -template <class T, size_t N> -std::string hexify(const std::array<T, N>& xs) { - std::stringstream ss; - ss << std::setfill('0') << std::hex; - auto ptr = reinterpret_cast<const uint8_t*>(xs.data()); - for (auto i = 0u; i < N * sizeof(T); ++i) - ss << std::setw(2) << static_cast<int>(ptr[i]); - return ss.str(); -} - } // namespace TEST(hashing an inspectable type) { A stream seems a bit heavyweight for this task and the code. Did you consider using `byte_to_hex` instead? ```c++ std::string result; for (auto x : xs) { auto [first, second] = byte_to_hex<policy::lowercase>(x); result += first; result += second; } return result; ``` I think a version like this is also easier to follow. return f(x.a, x.b); } } // namespace TEST(hashing an inspectable type) {
codereview_cpp_data_94
struct st_h2o_hpack_header_table_entry_t { h2o_iovec_t *name; h2o_iovec_t *value; - int decode_return_value; /* record the soft error for bad chars in headers */ const char *err_desc; /* the recorded soft error description */ }; I think we do not need to retain the value, since if a soft error has occurred can be found by checking the value of `err_desc`, and in such case the error code would always be `H2O_HTTP2_ERROR_INVALID_HEADER_CHAR`. struct st_h2o_hpack_header_table_entry_t { h2o_iovec_t *name; h2o_iovec_t *value; const char *err_desc; /* the recorded soft error description */ };
codereview_cpp_data_107
auto &db = dbname.value(); log_->info("Drop database {}", db); freeConnections(); std::unique_lock<std::shared_timed_mutex> lock(drop_mutex); soci::session sql(*soci::factory_postgresql(), postgres_options_.optionsStringWithoutDbName()); Pls, add a task(todo) with a fair-enough fix. auto &db = dbname.value(); log_->info("Drop database {}", db); freeConnections(); + // TODO mboldyrev 04.02.2019 IR-284 rework synchronization std::unique_lock<std::shared_timed_mutex> lock(drop_mutex); soci::session sql(*soci::factory_postgresql(), postgres_options_.optionsStringWithoutDbName());
codereview_cpp_data_108
q->long_timeout = 3600; q->stats->time_when_started = timestamp_get(); - q->stats->time_when_compatibility_checked = timestamp_get(); q->task_reports = list_create(); q->time_last_wait = 0; @Cpreciad I think this one is better as a field of q (e.g. `q->last_time_tasks_fit_check`), as this is not really a stat. q->long_timeout = 3600; q->stats->time_when_started = timestamp_get(); + q->last_time_tasks_fit_check = timestamp_get(); q->task_reports = list_create(); q->time_last_wait = 0;
codereview_cpp_data_111
* @param informationKey contains the statistics in its meta information * @param metaName which statistic to set * @param value which value to set it to, must be a number - * @retval 0 on success, -1 otherwise. * * This enforces that a number is set. */ for every different retval you can make its own line. * @param informationKey contains the statistics in its meta information * @param metaName which statistic to set * @param value which value to set it to, must be a number + * @retval 0 on success + * @retval -1 on error * * This enforces that a number is set. */
codereview_cpp_data_116
#ifdef UA_DEBUG_DUMP_PKGS UA_dump_hex_pkg(buffer->data, buffer->length); #endif - break; } } } // TODO check if warning is correct here and error code carries correct info UA_CHECK_WARN(processed, return UA_STATUSCODE_BADNOTFOUND, logger, UA_LOGCATEGORY_SERVER, Break out of both for-loops. Goto? #ifdef UA_DEBUG_DUMP_PKGS UA_dump_hex_pkg(buffer->data, buffer->length); #endif + /* break out of all loops when first verify & decrypt was successful */ + goto loops_exit; } } } +loops_exit: // TODO check if warning is correct here and error code carries correct info UA_CHECK_WARN(processed, return UA_STATUSCODE_BADNOTFOUND, logger, UA_LOGCATEGORY_SERVER,
codereview_cpp_data_122
std::shared_ptr<lbann_summary> const&>, default_key_error_policy>; -namespace -{ template <typename... Ts> std::string BuildErrorMessage(Ts... args) { This doesn't need to be nested in yet another anonymous namespace (it's already in one). std::shared_ptr<lbann_summary> const&>, default_key_error_policy>; template <typename... Ts> std::string BuildErrorMessage(Ts... args) {
codereview_cpp_data_123
//Handle layout statusLabel = new QLabel(this); descriptionLabel = new QLabel(tr("Current release channel:") + " " + tr(settingsCache->getUpdateReleaseChannel()->getName().toUtf8()), this); progress = new QProgressBar(this); QDialogButtonBox *buttonBox = new QDialogButtonBox(this); ok = new QPushButton("Close", this); - manualDownload = new QPushButton(tr("Download Anyway"), this); enableUpdateButton(false); //Unless we know there's an update available, you can't install gotoDownload = new QPushButton(tr("Open Download Page"), this); buttonBox->addButton(manualDownload, QDialogButtonBox::ActionRole); I liked the original `Update` wording, because it triggers a download+install = update. It's not just a simple download. Regarding Dae's issue: >"Update anyway" - What does "anyway" refer to? What do you think about `Force recent update` or something?? //Handle layout statusLabel = new QLabel(this); + statusLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed); + statusLabel->setWordWrap(true); descriptionLabel = new QLabel(tr("Current release channel:") + " " + tr(settingsCache->getUpdateReleaseChannel()->getName().toUtf8()), this); progress = new QProgressBar(this); QDialogButtonBox *buttonBox = new QDialogButtonBox(this); ok = new QPushButton("Close", this); + manualDownload = new QPushButton(tr("Reinstall"), this); enableUpdateButton(false); //Unless we know there's an update available, you can't install gotoDownload = new QPushButton(tr("Open Download Page"), this); buttonBox->addButton(manualDownload, QDialogButtonBox::ActionRole);
codereview_cpp_data_128
return true; } -std::string TaskManager::SaveClientStateQuery(Client *c, ClientTaskState *state) { // I am saving the slot in the ActiveTasks table, because unless a Task is cancelled/completed, the client // doesn't seem to like tasks moving slots between zoning and you can end up with 'bogus' activities if the task // previously in that slot had more activities than the one now occupying it. Hopefully retaining the slot // number for the duration of a session will overcome this. if (!c || !state) - return false; const char *ERR_MYSQLERROR = "[TASKS]Error in TaskManager::SaveClientState %s"; Ignoring the fact VS lets this compile for some reason. This is also written in a way that may possibly fail NRVO and since this is a performance focused commit, that is a very relevant point :P return true; } +void TaskManager::SaveClientStateQuery(Client *c, ClientTaskState *state, std::string& query) { // I am saving the slot in the ActiveTasks table, because unless a Task is cancelled/completed, the client // doesn't seem to like tasks moving slots between zoning and you can end up with 'bogus' activities if the task // previously in that slot had more activities than the one now occupying it. Hopefully retaining the slot // number for the duration of a session will overcome this. if (!c || !state) + return; const char *ERR_MYSQLERROR = "[TASKS]Error in TaskManager::SaveClientState %s";
codereview_cpp_data_135
} void printCommandParameters(std::string &command, - ParamsDescription parameters) { std::cout << "Run " << command << " with following parameters: " << std::endl; std::for_each(parameters.begin(), parameters.end(), [](auto el) { - std::cout << " " << std::get<0>(*el) << std::endl; }); } should be `const ParamsDescription&` } void printCommandParameters(std::string &command, + const ParamsDescription &parameters) { std::cout << "Run " << command << " with following parameters: " << std::endl; std::for_each(parameters.begin(), parameters.end(), [](auto el) { + std::cout << " " << el->message << std::endl; }); }
codereview_cpp_data_140
static PyObject* __Pyx_Globals(void) { Py_ssize_t i; - PyObject *names; #if CYTHON_COMPILING_IN_LIMITED_API PyObject *globals = PyDict_New(); if (unlikely(!globals)) goto bad; This would prevent modifying `globals()`. Can't we read and use `(this_module).__dict__` instead? static PyObject* __Pyx_Globals(void) { Py_ssize_t i; + PyObject *names = NULL; #if CYTHON_COMPILING_IN_LIMITED_API PyObject *globals = PyDict_New(); if (unlikely(!globals)) goto bad;
codereview_cpp_data_141
//Get the number of state variables added (or exposed) by this Component int ns = getNumStateVariablesAddedByComponent(); // And then include the states of its subcomponents for(unsigned int i=0; i<_propertySubcomponents.size(); i++) ns += _propertySubcomponents[i]->getNumStateVariables(); return ns; } How come this doesn't include adopted or member subcomponents? //Get the number of state variables added (or exposed) by this Component int ns = getNumStateVariablesAddedByComponent(); // And then include the states of its subcomponents + for (unsigned int i = 0; i<_memberSubcomponents.size(); i++) + ns += _memberSubcomponents[i]->getNumStateVariables(); + for(unsigned int i=0; i<_propertySubcomponents.size(); i++) ns += _propertySubcomponents[i]->getNumStateVariables(); + for (unsigned int i = 0; i<_adoptedSubcomponents.size(); i++) + ns += _adoptedSubcomponents[i]->getNumStateVariables(); + return ns; }
codereview_cpp_data_150
* @then there is an empty proposal */ TEST_F(TransferAsset, NonexistentAsset) { - const std::string &nonexistent = "inexist#test"s; IntegrationTestFramework(1) .setInitialState(kAdminKeypair) .sendTx(makeUserWithPerms(kUser1, kUser1Keypair, kPerms, kRole1)) Same as about omitting skip proposal and block. * @then there is an empty proposal */ TEST_F(TransferAsset, NonexistentAsset) { + std::string nonexistent = "inexist#test"; IntegrationTestFramework(1) .setInitialState(kAdminKeypair) .sendTx(makeUserWithPerms(kUser1, kUser1Keypair, kPerms, kRole1))
codereview_cpp_data_157
"block until the IMPORTER forwarded all data") .add<bool>("node,N", "spawn a node instead of connecting to one") - .add<size_t>("num,n", "the maximum number of events to import")); import_->add(reader_command<format::zeek::reader>, "zeek", "imports Zeek logs from STDIN or file", src_opts()); I find `num` too short for a long option. How about using `max-events` instead? That also works for import and export, describes the intent better as well. Only downside, it doesn't begin with the same letter as the short option. I think that's fine because most people still find `-n` very idiomatic for a number of events. "block until the IMPORTER forwarded all data") .add<bool>("node,N", "spawn a node instead of connecting to one") + .add<size_t>("max-events,n", "the maximum number of events to import")); import_->add(reader_command<format::zeek::reader>, "zeek", "imports Zeek logs from STDIN or file", src_opts());
codereview_cpp_data_158
*/ #include <gmock/gmock.h> -#include <validators/transactions_collection/batch_order_validator.hpp> #include "framework/batch_helper.hpp" #include "framework/result_fixture.hpp" #include "interfaces/iroha_internal/transaction_batch.hpp" #include "validators/field_validator.hpp" #include "validators/transaction_validator.hpp" #include "validators/transactions_collection/unsigned_transactions_collection_validator.hpp" using namespace shared_model; Use quotes instead of <> for this include. */ #include <gmock/gmock.h> #include "framework/batch_helper.hpp" #include "framework/result_fixture.hpp" #include "interfaces/iroha_internal/transaction_batch.hpp" #include "validators/field_validator.hpp" #include "validators/transaction_validator.hpp" +#include "validators/transactions_collection/batch_order_validator.hpp" #include "validators/transactions_collection/unsigned_transactions_collection_validator.hpp" using namespace shared_model;
codereview_cpp_data_166
using namespace iroha::consensus::yac; -// TODO mboldyrev 13.12.2018 IR- Parametrize the tests with consistency models static const iroha::consensus::yac::ConsistencyModel kConsistencyModel = iroha::consensus::yac::ConsistencyModel::kBft; Same issue as for yac tests using namespace iroha::consensus::yac; +// TODO mboldyrev 14.02.2019 IR-324 Use supermajority checker mock static const iroha::consensus::yac::ConsistencyModel kConsistencyModel = iroha::consensus::yac::ConsistencyModel::kBft;
codereview_cpp_data_190
switch (index.row()) { case MaxGeneratedBlock: - return QVariant((unsigned int)maxGeneratedBlock); case ExcessiveBlockSize: - return QVariant((unsigned int)excessiveBlockSize); case ExcessiveAcceptDepth: return QVariant(excessiveAcceptDepth); case UseReceiveShaping: shouldn't this be a uint64_t? switch (index.row()) { case MaxGeneratedBlock: + return QVariant((uint64_t)maxGeneratedBlock); case ExcessiveBlockSize: + return QVariant((uint64_t)excessiveBlockSize); case ExcessiveAcceptDepth: return QVariant(excessiveAcceptDepth); case UseReceiveShaping:
codereview_cpp_data_195
static LogPatterns default_patterns; if (not is_initialized.test_and_set()) { default_patterns.setPattern( - LogLevel::kTrace, R"([%Y-%m-%d %H:%M:%S.%F][th:%t][%=7l][%n]: %v)"); default_patterns.setPattern(LogLevel::kInfo, R"([%Y-%m-%d %H:%M:%S.%F][%L][%n]: %v)"); } ```suggestion LogLevel::kTrace, R"([%Y-%m-%d %H:%M:%S.%F][th:%t][%=8l][%n]: %v)"); ``` Because `critical` is 8 characters. static LogPatterns default_patterns; if (not is_initialized.test_and_set()) { default_patterns.setPattern( + LogLevel::kTrace, R"([%Y-%m-%d %H:%M:%S.%F][th:%t][%=8l][%n]: %v)"); default_patterns.setPattern(LogLevel::kInfo, R"([%Y-%m-%d %H:%M:%S.%F][%L][%n]: %v)"); }
codereview_cpp_data_212
amount_{ [this] { return proto::Amount(add_asset_quantity_.amount()); }} {} template AddAssetQuantity::AddAssetQuantity( AddAssetQuantity::TransportType &); template AddAssetQuantity::AddAssetQuantity( Add todo about boilerplate here. amount_{ [this] { return proto::Amount(add_asset_quantity_.amount()); }} {} + // TODO 30/05/2018 andrei Reduce boilerplate code in variant classes template AddAssetQuantity::AddAssetQuantity( AddAssetQuantity::TransportType &); template AddAssetQuantity::AddAssetQuantity(
codereview_cpp_data_215
return pt; } - virtual void OnGameTick() - { - // hello! hunt for trees here - // ...maybe - } - virtual void OnPlaceMouseUp(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt, TileIndex start_tile, TileIndex end_tile) { if (pt.x != -1) { Ok? I guess you didn't mean to leave this in. return pt; } virtual void OnPlaceMouseUp(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt, TileIndex start_tile, TileIndex end_tile) { if (pt.x != -1) {
codereview_cpp_data_230
// A non-empty queue means that the server has received a change while it is running the processing routine. while (!discovery_db_.data_queue_empty()); - // must restart the routin after the period time return pending_work; } ```suggestion // Must restart the routine after the period time ``` // A non-empty queue means that the server has received a change while it is running the processing routine. while (!discovery_db_.data_queue_empty()); + // Must restart the routin after the period time return pending_work; }
codereview_cpp_data_253
using namespace vast; using namespace std::string_literals; -using namespace std::string_view_literals; TEST(functionality) { std::string str = "1"; I don't spot any `""sv`, is this really used? using namespace vast; using namespace std::string_literals; TEST(functionality) { std::string str = "1";
codereview_cpp_data_257
{} void StartUsing() { - if (m_failed_init || (!GetOptionsDB().Get<bool>("UI.system-fog-of-war"))) return; if (!m_scanline_shader) { - if (m_failed_init) - return; - boost::filesystem::path shader_path = GetRootDataDir() / "default" / "shaders" / "scanlines.frag"; std::string shader_text; ReadFile(shader_path, shader_text); wondering whether this should be in here, or in calling / wrapping code... {} void StartUsing() { + if (m_failed_init) return; if (!m_scanline_shader) { boost::filesystem::path shader_path = GetRootDataDir() / "default" / "shaders" / "scanlines.frag"; std::string shader_text; ReadFile(shader_path, shader_text);
codereview_cpp_data_266
total_size += (sizeof(s2n_preferred_hashes) * num_signature_algs * 2) + 6; } - struct s2n_blob *app_protocols; - GUARD(s2n_connection_get_protocol_preferences(conn, &app_protocols)); - uint16_t application_protocols_len = app_protocols->size; uint16_t server_name_len = strlen(conn->server_name); uint16_t mfl_code_len = sizeof(conn->config->mfl_code); Readability nit: Can we rename `app_protocols` to `client_app_protocols`? total_size += (sizeof(s2n_preferred_hashes) * num_signature_algs * 2) + 6; } + struct s2n_blob *client_app_protocols; + GUARD(s2n_connection_get_protocol_preferences(conn, &client_app_protocols)); + uint16_t application_protocols_len = client_app_protocols->size; uint16_t server_name_len = strlen(conn->server_name); uint16_t mfl_code_len = sizeof(conn->config->mfl_code);
codereview_cpp_data_286
// the MissionGroup if not specified. SimGroup* missionGroup = dynamic_cast<SimGroup*>(Sim::findObject("MissionGroup")); SimGroup* group = 0; - if ( parentGroup != "" ) { if (!Sim::findObject(parentGroup, group)) { // Create the group if it could not be found group = new SimGroup; Should be `if (dStrcmp(parentGroup, "") != 0)` // the MissionGroup if not specified. SimGroup* missionGroup = dynamic_cast<SimGroup*>(Sim::findObject("MissionGroup")); SimGroup* group = 0; + if (dStrcmp(parentGroup, "") == 0){ if (!Sim::findObject(parentGroup, group)) { // Create the group if it could not be found group = new SimGroup;
codereview_cpp_data_306
fprintf(stderr, " Turn on experimental TLS1.3 support.\n"); fprintf(stderr, " -w --https-server\n"); fprintf(stderr, " Run s2nd in a simple https server mode.\n"); fprintf(stderr, " -h,--help\n"); fprintf(stderr, " Display this message and quit.\n"); no help for the `--https-bench` option? fprintf(stderr, " Turn on experimental TLS1.3 support.\n"); fprintf(stderr, " -w --https-server\n"); fprintf(stderr, " Run s2nd in a simple https server mode.\n"); + fprintf(stderr, " -b --https-bench <bytes>\n"); + fprintf(stderr, " Send number of bytes in https server mode to test throughput.\n"); fprintf(stderr, " -h,--help\n"); fprintf(stderr, " Display this message and quit.\n");
codereview_cpp_data_310
bool success = false; if (!isInitialized()) { - if (_stripType == P038_STRIP_TYPE_RGBW) { - Plugin_038_pixels = new (std::nothrow) Adafruit_NeoPixel(_maxPixels, _gpioPin, NEO_GRBW + NEO_KHZ800); - } - else { - Plugin_038_pixels = new (std::nothrow) Adafruit_NeoPixel(_maxPixels, _gpioPin, NEO_GRB + NEO_KHZ800); - } if (Plugin_038_pixels != nullptr) { Plugin_038_pixels->begin(); // This initializes the NeoPixel library. This piece of code is copy/pasted quite a lot. bool success = false; if (!isInitialized()) { + Plugin_038_pixels = new (std::nothrow) Adafruit_NeoPixel(_maxPixels, + _gpioPin, + (_stripType == P038_STRIP_TYPE_RGBW ? NEO_GRBW : NEO_GRB) + NEO_KHZ800); if (Plugin_038_pixels != nullptr) { Plugin_038_pixels->begin(); // This initializes the NeoPixel library.
codereview_cpp_data_320
* (1,0) - current round. The diagram is similar to the initial case. */ - size_t discarded_txs_amount; - auto get_transactions = [this, &discarded_txs_amount](auto &queue) { - return getTransactions(transaction_limit_, queue, discarded_txs_amount); - }; - auto now = iroha::time::now(); - auto generate_proposal = [this, now, &discarded_txs_amount]( consensus::Round round, const auto &txs) { auto proposal = proposal_factory_->unsafeCreateProposal( round.block_round, now, txs | boost::adaptors::indirected); since it is only used once now, the internal `getTransactions` could be used directly instead. * (1,0) - current round. The diagram is similar to the initial case. */ + size_t discarded_txs_quantity; auto now = iroha::time::now(); + auto generate_proposal = [this, now, &discarded_txs_quantity]( consensus::Round round, const auto &txs) { auto proposal = proposal_factory_->unsafeCreateProposal( round.block_round, now, txs | boost::adaptors::indirected);
codereview_cpp_data_327
bool Way::isSimpleLoop() const { - if (getNodeId(0) == getNodeId(getNodeCount()-1)) - { - return true; - } - return false; } bool Way::isValidPolygon() const This looks good. I'm a simple kind of man: ``` return (getNodeId(0) == getNodeId(getNodeCount()-1); ``` But like Seth says "it'll probably be optimized out" so it is up to you. bool Way::isSimpleLoop() const { + return (getFirstNodeId() == getLastNodeId()); } bool Way::isValidPolygon() const
codereview_cpp_data_332
uint all_sum = 0; for (int i = 0; i < numDevices; ++i) { - mg_info *mg_info_temp; result = hip_internal::ihipHostMalloc(tls, (void **)&mg_info_temp, sizeof(mg_info), hipHostMallocDefault); if (result != hipSuccess) { hip_internal::ihipHostFree(tls, mg_sync_ptr); Uninitialized to nullptr. uint all_sum = 0; for (int i = 0; i < numDevices; ++i) { + mg_info *mg_info_temp = nullptr; result = hip_internal::ihipHostMalloc(tls, (void **)&mg_info_temp, sizeof(mg_info), hipHostMallocDefault); if (result != hipSuccess) { hip_internal::ihipHostFree(tls, mg_sync_ptr);
codereview_cpp_data_344
size_t maxIndexRequested = currentPrimitive * numOffsets * numPoints + (currentVertex + 1) * numOffsets - 1; ai_assert(maxIndexRequested < indices.size()); - // read all indices for this vertex. Yes, in a hacky local array - ai_assert(numOffsets < 20 && perVertexOffset < 20); - size_t vindex[20]; for (size_t offsets = 0; offsets < numOffsets; ++offsets) vindex[offsets] = indices[currentPrimitive * numOffsets * numPoints + currentVertex * numOffsets + offsets]; I know this was there before, but where does 20 come from? size_t maxIndexRequested = currentPrimitive * numOffsets * numPoints + (currentVertex + 1) * numOffsets - 1; ai_assert(maxIndexRequested < indices.size()); + // copy the indices pertaining to this vertex + std::vector<size_t> vindex; + vindex.reserve(numOffsets); for (size_t offsets = 0; offsets < numOffsets; ++offsets) vindex[offsets] = indices[currentPrimitive * numOffsets * numPoints + currentVertex * numOffsets + offsets];
codereview_cpp_data_351
bool do_mscgen_generate(const QCString& inFile,const QCString& outFile,mscgen_format_t msc_format, const QCString &srcFile,int srcLine) { - QCString const& external_mscgen = Config_getString(MSCGEN); if (!external_mscgen.isEmpty()) { QCString type; switch (msc_format) This indicate that when `MSCGEN` is set and the generation of the image fails it attempts to create it with the build in generator? I think that this is unwanted behavior, I think it should be either the external generator or the internal generator but not both. bool do_mscgen_generate(const QCString& inFile,const QCString& outFile,mscgen_format_t msc_format, const QCString &srcFile,int srcLine) { + QCString const& external_mscgen = Config_getString(MSCGEN).stripWhiteSpace(); if (!external_mscgen.isEmpty()) { QCString type; switch (msc_format)
codereview_cpp_data_355
XMLDocument::renameChildNode(aNode,"ZAttachment", "z_location"); } if (documentVersion < 30505) { - // replace old properties with latest use of Sockets SimTK::Xml::element_iterator xCoord = aNode.element_begin("x_coordinate"); SimTK::Xml::element_iterator yCoord = aNode.element_begin("y_coordinate"); SimTK::Xml::element_iterator zCoord = aNode.element_begin("z_coordinate"); This should remain as `Connectors` for this model version to first be updated to connectors and then to proceed to the latest update. XMLDocument::renameChildNode(aNode,"ZAttachment", "z_location"); } if (documentVersion < 30505) { + // replace old properties with latest use of Connectors SimTK::Xml::element_iterator xCoord = aNode.element_begin("x_coordinate"); SimTK::Xml::element_iterator yCoord = aNode.element_begin("y_coordinate"); SimTK::Xml::element_iterator zCoord = aNode.element_begin("z_coordinate");
codereview_cpp_data_363
for (const auto &tx : proposal.transactions()) { if (auto tx_answer = transaction_validator_->validate(tx)) { reason.second.emplace_back(tx_answer.reason()); - break; } } Why not validate all transactions in proposal here? Right now there can ve several invalid transactions, but only one error. for (const auto &tx : proposal.transactions()) { if (auto tx_answer = transaction_validator_->validate(tx)) { reason.second.emplace_back(tx_answer.reason()); } }
codereview_cpp_data_368
// (*adj)[v - 1].push_back(std::make_pair(u - 1, w)); } /** - *@brief This function returns the shortest distance from the source * to the target if there is path between vertices 's' and 't'. * * @param workset_ vertices visited in the search ```suggestion * @brief This function returns the shortest distance from the source ``` // (*adj)[v - 1].push_back(std::make_pair(u - 1, w)); } /** + * @brief This function returns the shortest distance from the source * to the target if there is path between vertices 's' and 't'. * * @param workset_ vertices visited in the search
codereview_cpp_data_373
} #endif -double GetShootingAngle( const Point & start, const Point & target ) { const int dx = target.x - start.x; const int dy = target.y - start.y; It is good to rename it to `GetAngle` as this function does not have any code related to shooting. } #endif +double GetAngle( const Point & start, const Point & target ) { const int dx = target.x - start.x; const int dy = target.y - start.y;
codereview_cpp_data_374
nullpo_retv(sd); fd = sd->fd; - - WFIFOHEAD(fd, 4+37*MAX_HOMUNSKILL); - hd = sd->hd; - if ( !hd ) // FIXME: If nothing is going to be sent should WFIFOHEAD be above this check? [panikon] return; WFIFOW(fd,0)=0x235; for ( i = 0; i < MAX_HOMUNSKILL; i++){ if( (id = hd->homunculus.hskill[i].id) != 0 ){ Good point o.o I believe it's better to reorder it nullpo_retv(sd); fd = sd->fd; hd = sd->hd; + + if ( !hd ) return; + WFIFOHEAD(fd, 4+37*MAX_HOMUNSKILL); + WFIFOW(fd,0)=0x235; for ( i = 0; i < MAX_HOMUNSKILL; i++){ if( (id = hd->homunculus.hskill[i].id) != 0 ){
codereview_cpp_data_379
case 'x': req.connect_to = h2o_mem_alloc(sizeof(*req.connect_to)); if (h2o_url_init(req.connect_to, NULL, h2o_iovec_init(optarg, strlen(optarg)), h2o_iovec_init(NULL, 0)) != 0 || - req.connect_to->_port == 0 || req.connect_to->_port == 65535) { - fprintf(stderr, "invalid server address specified for -X\n"); exit(EXIT_FAILURE); } break; sorry for a side-tracked request, but can you add a patch to fix this message as well? I think this must be -x instead of -X. case 'x': req.connect_to = h2o_mem_alloc(sizeof(*req.connect_to)); if (h2o_url_init(req.connect_to, NULL, h2o_iovec_init(optarg, strlen(optarg)), h2o_iovec_init(NULL, 0)) != 0 || + req.connect_to->_port == 0 || req.connect_to->_port == 65535) { + fprintf(stderr, "invalid server address specified for -x\n"); exit(EXIT_FAILURE); } break;
codereview_cpp_data_386
} numUploads = uploadTags.size(); - notificationNumber = notificationNumber; } MegaTransferDataPrivate::MegaTransferDataPrivate(const MegaTransferDataPrivate *transferData) Add `this` to the first variable } numUploads = uploadTags.size(); + this->notificationNumber = notificationNumber; } MegaTransferDataPrivate::MegaTransferDataPrivate(const MegaTransferDataPrivate *transferData)
codereview_cpp_data_394
namespace caffe { bool ReadProtoFromTextFile(const char* filename, Message* proto) { -#ifdef _MSC_VER - int fd = open(filename, O_RDONLY | O_BINARY); -#else int fd = open(filename, O_RDONLY); -#endif CHECK_NE(fd, -1) << "File not found: " << filename; FileInputStream* input = new FileInputStream(fd); bool success = google::protobuf::TextFormat::Parse(input, proto); We should not use the flag of `O_BINARY` here. Because it reads from text file not binary file. namespace caffe { bool ReadProtoFromTextFile(const char* filename, Message* proto) { int fd = open(filename, O_RDONLY); CHECK_NE(fd, -1) << "File not found: " << filename; FileInputStream* input = new FileInputStream(fd); bool success = google::protobuf::TextFormat::Parse(input, proto);
codereview_cpp_data_409
#define LONGEST_STR \ ELEMENT_LONGEST_STR("connect") \ - DELIMITER ELEMENT_LONGEST_STR("header") DELIMITER ELEMENT_LONGEST_STR("body") DELIMITER ELEMENT_LONGEST_STR("request_total") \ - DELIMITER ELEMENT_LONGEST_STR("process") DELIMITER ELEMENT_LONGEST_STR("proxy-idle") \ - DELIMITER ELEMENT_LONGEST_STR("proxy-connect") DELIMITER ELEMENT_LONGEST_STR("proxy-request-header") \ - DELIMITER ELEMENT_LONGEST_STR("proxy-request-body") DELIMITER ELEMENT_LONGEST_STR("proxy-request-total") \ - DELIMITER ELEMENT_LONGEST_STR("proxy-first-byte") size_t max_len = sizeof(LONGEST_STR); emit_server_timing_element(req, &dst, "connect", h2o_time_compute_connect_time, max_len); Do these field names match those that are actually being emitted? #define LONGEST_STR \ ELEMENT_LONGEST_STR("connect") \ + DELIMITER ELEMENT_LONGEST_STR("request-header") DELIMITER ELEMENT_LONGEST_STR("request-body") \ + DELIMITER ELEMENT_LONGEST_STR("request-total") DELIMITER ELEMENT_LONGEST_STR("process") \ + DELIMITER ELEMENT_LONGEST_STR("proxy-idle") DELIMITER ELEMENT_LONGEST_STR("proxy-connect") \ + DELIMITER ELEMENT_LONGEST_STR("proxy-request") DELIMITER ELEMENT_LONGEST_STR("proxy-process") size_t max_len = sizeof(LONGEST_STR); emit_server_timing_element(req, &dst, "connect", h2o_time_compute_connect_time, max_len);
codereview_cpp_data_418
fireOnRequestFinish(request, megaError); } -void MegaApiImpl::querybandwidthquota_result(int code) { if(requestMap.find(client->restag) == requestMap.end()) return; MegaRequestPrivate* request = requestMap.at(client->restag); - if(!request || (request->getType() != MegaRequest::TYPE_QUERY_BANDWIDTH_QUOTA)) return; request->setFlag(code); fireOnRequestFinish(request, MegaError(API_OK)); If we return in the `Command::procresult()` an `API_EINTERNAL` (or any other error code), I think we should not set the flag in the request unless the code is `API_OK` fireOnRequestFinish(request, megaError); } +void MegaApiImpl::querytransferquota_result(int code) { if(requestMap.find(client->restag) == requestMap.end()) return; MegaRequestPrivate* request = requestMap.at(client->restag); + if(!request || (request->getType() != MegaRequest::TYPE_QUERY_TRANSFER_QUOTA)) return; request->setFlag(code); fireOnRequestFinish(request, MegaError(API_OK));
codereview_cpp_data_423
QMessageBox::warning(this, tr("Load sets/cards"), tr("Selected file cannot be found.")); return; } - else if (QFileInfo(fileName).suffix() != "xml") { // fileName = *.xml QMessageBox::warning(this, tr("Load sets/cards"), tr("You can only import XML databases at this time.")); return; } Just a minor remark: no need to `else`, since the previous `if` block contains a `return`. QMessageBox::warning(this, tr("Load sets/cards"), tr("Selected file cannot be found.")); return; } + + if (QFileInfo(fileName).suffix() != "xml") { // fileName = *.xml QMessageBox::warning(this, tr("Load sets/cards"), tr("You can only import XML databases at this time.")); return; }
codereview_cpp_data_424
#include <thrift/transport/TSocket.h> #include <thrift/transport/TServerSocket.h> #include "TestPortFixture.h" -#include "TestTServerSocket.h" using apache::thrift::transport::TServerSocket; using apache::thrift::transport::TSocket; This should really be 'accept()' and not 'acceptImpl()'. #include <thrift/transport/TSocket.h> #include <thrift/transport/TServerSocket.h> #include "TestPortFixture.h" using apache::thrift::transport::TServerSocket; using apache::thrift::transport::TSocket;
codereview_cpp_data_428
for(const auto key: m_scalar_keys) { std::string conduit_field = m_output_scalar_prefix + key; - std::string conduit_obj = '/' + pad(std::to_string(sample_id), LBANN_SAMPLE_ID_PAD, '0') + '/' + conduit_field; if(sample[conduit_obj].schema().dtype().is_empty()) { if (data_store_active()) { LBANN_ERROR("Unable to find field " + conduit_obj Can `LBANN_DATA_ID_STR` be used as the others? for(const auto key: m_scalar_keys) { std::string conduit_field = m_output_scalar_prefix + key; + std::string conduit_obj = '/' + LBANN_DATA_ID_STR(sample_id) + '/' + conduit_field; if(sample[conduit_obj].schema().dtype().is_empty()) { if (data_store_active()) { LBANN_ERROR("Unable to find field " + conduit_obj
codereview_cpp_data_437
const DataType norm_img_val = (img_buf[img_offset + row + col*dims[1]] - min) / norm_denom; cv_buf[dims[0]*(col + row*dims[2]) + channel] = - static_cast<uint8_t>(std::round(norm_img_val) * 255); } } } Microoptimization: It looks like we're biasing away from 0 and 255. A pixel in a white noise image has 50% less probability of converting to 0 or 255 than to other numbers. Perhaps: ```suggestion static_cast<uint8_t>(std::min(std::floor(norm_img_val) * 256, DataType(255))); ``` const DataType norm_img_val = (img_buf[img_offset + row + col*dims[1]] - min) / norm_denom; cv_buf[dims[0]*(col + row*dims[2]) + channel] = + static_cast<uint8_t>(std::min(std::floor(norm_img_val) * 256, DataType(255))); } } }
codereview_cpp_data_440
// bugs. auto schedule_teardown = [&](const std::string& type_or_label) { if (is_singleton(type_or_label)) { - auto component = self->state.registry.remove(type_or_label); - if (component) { VAST_VERBOSE("{} schedules {} for shutdown", self, type_or_label); self->demonitor(component->actor); scheduled_for_teardown.push_back(std::move(component->actor)); Nit: Exactly the same code is written as ``` auto component = self->state.registry.remove(type_or_label); if (component) { ``` here but ``` if (auto removed = self->state.registry.remove(component)) { ``` below // bugs. auto schedule_teardown = [&](const std::string& type_or_label) { if (is_singleton(type_or_label)) { + if (auto component = self->state.registry.remove(type_or_label)) { VAST_VERBOSE("{} schedules {} for shutdown", self, type_or_label); self->demonitor(component->actor); scheduled_for_teardown.push_back(std::move(component->actor));
codereview_cpp_data_442
{1," Quit when the option is processed. Useful to debug the chain"}, {1," of loading option files."}, #ifdef HAVE_JANSSON - {0," --_interactive" -#ifdef HAVE_SECCOMP - "=[default|sandbox]" -#endif - }, {0," Enter interactive mode (json over stdio)."}, -#ifdef HAVE_SECCOMP - {0," Enter file I/O limited interactive mode if sandbox is specified. [default]"}, -#endif #endif {1," --_list-roles=[[language|all]:[kindletters|*]]"}, {1," Output list of all roles of tag kind(s) specified for language(s)."}, s/fileio limited/sandboxed/ ? {1," Quit when the option is processed. Useful to debug the chain"}, {1," of loading option files."}, #ifdef HAVE_JANSSON + {0," --_interactive"}, {0," Enter interactive mode (json over stdio)."}, #endif {1," --_list-roles=[[language|all]:[kindletters|*]]"}, {1," Output list of all roles of tag kind(s) specified for language(s)."},
codereview_cpp_data_458
// assemble a multibody tree according to the PhysicalFrames in the // OpenSim model, which include Ground and Bodies - _multibodyTree.addBody("/" + getName() + "/" + ground.getName(), 0, false, &ground); auto bodies = getComponentList<Body>(); Does this mean that `ground.getAbsolutePathName()` didn't work? // assemble a multibody tree according to the PhysicalFrames in the // OpenSim model, which include Ground and Bodies + _multibodyTree.addBody(ground.getAbsolutePathName(), 0, false, &ground); auto bodies = getComponentList<Body>();
codereview_cpp_data_464
else if (refspec) { const char *refspec_value; - if (!rpmostree_refspec_classify (refspec, &ret->refspec_type, &refspec_value, error)) return FALSE; /* Note the lack of a prefix here so that code that just calls * rpmostree_origin_get_refspec() in the ostree:// case * sees it without the prefix for compatibility. */ - ret->cached_refspec = g_strdup (refspec); ret->cached_override_commit = g_key_file_get_string (ret->kf, "origin", "override-commit", NULL); } Why not keep doing `g_steal_pointer` here? else if (refspec) { const char *refspec_value; + if (!rpmostree_refspec_classify (refspec, &ret->refspec_type, NULL, error)) return FALSE; /* Note the lack of a prefix here so that code that just calls * rpmostree_origin_get_refspec() in the ostree:// case * sees it without the prefix for compatibility. */ + ret->cached_refspec = g_steal_pointer (&refspec); ret->cached_override_commit = g_key_file_get_string (ret->kf, "origin", "override-commit", NULL); }
codereview_cpp_data_472
} ARR_FIND(0, MAX_PARTY, j, p->party.member[j].leader == 1); - if( j == MAX_PARTY ) { // Leader has changed - int i; - ARR_FIND(0, MAX_PARTY, i, sp->member[i].leader == 1); - if( i < MAX_PARTY ) { - clif->PartyLeaderChanged(map->id2sd(sp->member[i].account_id), 0, sp->member[i].account_id); } else { party->broken(p->party.party_id); // Should not happen, Party is leaderless, disband } i is already defined before, please use another name like j k v } ARR_FIND(0, MAX_PARTY, j, p->party.member[j].leader == 1); + if (j == MAX_PARTY) { // Leader has changed + int k; + ARR_FIND(0, MAX_PARTY, k, sp->member[k].leader == 1); + if (i < MAX_PARTY) { + clif->PartyLeaderChanged(map->id2sd(sp->member[k].account_id), 0, sp->member[k].account_id); } else { party->broken(p->party.party_id); // Should not happen, Party is leaderless, disband }
codereview_cpp_data_479
Time_t ts(data.ts.seconds, data.ts.fraction); Time_t current_ts; Time_t::now(current_ts); - auto latency = static_cast<double>((current_ts - ts).to_ns()); Locator2LocatorData notification; notification.src_locator(to_statistics_type(source_locator)); use `float` to match the `Locator2LocatorData` setter. Time_t ts(data.ts.seconds, data.ts.fraction); Time_t current_ts; Time_t::now(current_ts); + auto latency = static_cast<float>((current_ts - ts).to_ns()); Locator2LocatorData notification; notification.src_locator(to_statistics_type(source_locator));
codereview_cpp_data_486
PMIX_DESTRUCT(&pbkt); cbfunc(rc, NULL, 0, cbdata, NULL, NULL); return rc; - } - if (rank == PMIX_RANK_WILDCARD) found++; } while (NULL != *htptr) { Minor nit: coding standards require use of braces around every if clause as it helps when running a debugger PMIX_DESTRUCT(&pbkt); cbfunc(rc, NULL, 0, cbdata, NULL, NULL); return rc; + } } while (NULL != *htptr) {
codereview_cpp_data_496
} // 2.6- Need to wait several ms for the scheduler to be well launched and retrieving correct device information before updating information on the SOFA side. -#ifndef WIN32 - usleep(42); -#else - Sleep(42); -#endif updatePosition(); } Please use ` std::this_thread::sleep_for(std::chrono::milliseconds(x)); ` instead of sleep/Sleep and the ifdefs } // 2.6- Need to wait several ms for the scheduler to be well launched and retrieving correct device information before updating information on the SOFA side. + std::this_thread::sleep_for(42); updatePosition(); }
codereview_cpp_data_507
msg_deprecated("SofaComponentAllCommonComponents") << "This plugin was renamed into SofaComponentAll. Backward compatiblity will be stopped at SOFA v20.06"; #endif - sofa::component::initBase(); - sofa::component::initCommon(); - sofa::component::initGeneral(); - sofa::component::initAdvanced(); - sofa::component::initMisc(); } const char* getModuleName() Should not change. msg_deprecated("SofaComponentAllCommonComponents") << "This plugin was renamed into SofaComponentAll. Backward compatiblity will be stopped at SOFA v20.06"; #endif + sofa::component::initSofaBase(); + sofa::component::initSofaCommon(); + sofa::component::initSofaGeneral(); + sofa::component::initSofaAdvanced(); + sofa::component::initSofaMisc(); } const char* getModuleName()
codereview_cpp_data_519
{ int rank = 0; #ifdef ADIOS2_HAVE_MPI - int size = 1; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); #endif adios2::ADIOS ad; try size isn't actually being used here and can be removed { int rank = 0; #ifdef ADIOS2_HAVE_MPI MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); #endif adios2::ADIOS ad; try
codereview_cpp_data_524
void ContactListener::init(void) { -// helper::vector<ContactManager*> contactManagers; m_NarrowPhase = getContext()->get<core::collision::NarrowPhaseDetection>(); if ( m_NarrowPhase != nullptr ) { To be removed if not needed ;) void ContactListener::init(void) { m_NarrowPhase = getContext()->get<core::collision::NarrowPhaseDetection>(); if ( m_NarrowPhase != nullptr ) {
codereview_cpp_data_532
chrif->buildfamelist = chrif_buildfamelist; chrif->save_scdata = chrif_save_scdata; chrif->ragsrvinfo = chrif_ragsrvinfo; - //chrif->char_offline = chrif_char_offline; chrif->char_offline_nsd = chrif_char_offline_nsd; chrif->char_reset_offline = chrif_char_reset_offline; chrif->send_users_tochar = send_users_tochar; No need to keep it here, let's remove it :3 chrif->buildfamelist = chrif_buildfamelist; chrif->save_scdata = chrif_save_scdata; chrif->ragsrvinfo = chrif_ragsrvinfo; chrif->char_offline_nsd = chrif_char_offline_nsd; chrif->char_reset_offline = chrif_char_reset_offline; chrif->send_users_tochar = send_users_tochar;
codereview_cpp_data_534
Player *newPlayer = addPlayer(playerId, playerInfo.user_info()); messageLog->logJoin(newPlayer); if (trayIcon) { - trayIcon->showMessage(tr("A player has joined your game"), - tr("%1 has joined your game").arg(newPlayer->getName())); } } playerListWidget->addPlayer(playerInfo); I like the idea! Maybe say "A player joined game #12345" and then the body as "PLAYER has joined the game" because it might not be "your" game per say. Overall, awesome idea :) Player *newPlayer = addPlayer(playerId, playerInfo.user_info()); messageLog->logJoin(newPlayer); if (trayIcon) { + QString gameId(QString::number(gameInfo.game_id())); + trayIcon->showMessage(tr("A player has joined game #%1").arg(gameId), + tr("%1 has joined the game").arg(newPlayer->getName())); } } playerListWidget->addPlayer(playerInfo);
codereview_cpp_data_536
ASSERT_EQ(boost::size(resp_assets), account_assets_.size()); // check that every initially created asset is present in the result for (const auto &asset : account_assets_) { - bool presented = false; - std::for_each(resp_assets.begin(), resp_assets.end(), [&asset, &presented](const auto &a) { - presented |= asset.first == a.assetId(); - }); - ASSERT_TRUE(presented); } }) << "Actual response: " << response.toString(); `std::find` was more descriptive, so plz use it instead ```cpp ASSERT_NE(std::find_if(resp_assets.begin(), resp_assets.end(), [&asset, &presented](const auto &a) { return asset.first == a.assetId(); ), resp_assets.end()); ``` ASSERT_EQ(boost::size(resp_assets), account_assets_.size()); // check that every initially created asset is present in the result for (const auto &asset : account_assets_) { + ASSERT_NE(std::find_if(resp_assets.begin(), + resp_assets.end(), + [&asset](const auto &a) { + return asset.first == a.assetId(); + }), + resp_assets.end()); } }) << "Actual response: " << response.toString();
codereview_cpp_data_551
ObjectColor & objcol = ( *it ).second.objcol; if ( objcol.isColor( color ) ) { - MP2::MapObjectType objectType = static_cast<MP2::MapObjectType>( objcol.first ); objcol.second = objectType == MP2::OBJ_CASTLE ? Color::UNUSED : Color::NONE; world.GetTiles( ( *it ).first ).CaptureFlags32( objectType, objcol.second ); I suppose, `objectType` can be declared as `const` here. ObjectColor & objcol = ( *it ).second.objcol; if ( objcol.isColor( color ) ) { + const MP2::MapObjectType objectType = static_cast<MP2::MapObjectType>( objcol.first ); objcol.second = objectType == MP2::OBJ_CASTLE ? Color::UNUSED : Color::NONE; world.GetTiles( ( *it ).first ).CaptureFlags32( objectType, objcol.second );
codereview_cpp_data_566
LogPrint("thin", "Received block %s in %.2f seconds\n", hash.ToString(), nResponseTime); LogPrint("thin", "Average block response time is %.2f seconds\n", avgResponseTime); - if (maxBlocksInTransitPerPeer.value != 0) - { - MAX_BLOCKS_IN_TRANSIT_PER_PEER = maxBlocksInTransitPerPeer.value; - } - if (blockDownloadWindow.value != 0) - { - BLOCK_DOWNLOAD_WINDOW = blockDownloadWindow.value; - } LogPrintf("BLOCK_DOWNLOAD_WINDOW is %d MAX_BLOCKS_IN_TRANSIT_PER_PEER is %d\n", BLOCK_DOWNLOAD_WINDOW, MAX_BLOCKS_IN_TRANSIT_PER_PEER); { Identitation is screwed up. LogPrint("thin", "Received block %s in %.2f seconds\n", hash.ToString(), nResponseTime); LogPrint("thin", "Average block response time is %.2f seconds\n", avgResponseTime); LogPrintf("BLOCK_DOWNLOAD_WINDOW is %d MAX_BLOCKS_IN_TRANSIT_PER_PEER is %d\n", BLOCK_DOWNLOAD_WINDOW, MAX_BLOCKS_IN_TRANSIT_PER_PEER); {
codereview_cpp_data_590
#endif #include <iostream> #include <chrono> #define NUM_GROUPS 1 #define GROUP_SIZE 1 are you planning to verify status of all HIP APIs? If not, remove it. #endif #include <iostream> #include <chrono> +#include <algorithm> #define NUM_GROUPS 1 #define GROUP_SIZE 1
codereview_cpp_data_607
void StatusBar::SetCenter( s32 cx, s32 cy ) { center.x = cx; - center.y = cy + 1; } void StatusBar::ShowMessage( const std::string & msg ) This is an incorrect way to do. We should modify values of callers of this function. void StatusBar::SetCenter( s32 cx, s32 cy ) { center.x = cx; + center.y = cy; } void StatusBar::ShowMessage( const std::string & msg )
codereview_cpp_data_609
// Insert the new char entry to the database if (SQL_ERROR == SQL->Query(inter->sql_handle, "INSERT INTO `%s` (`account_id`, `char_num`, `name`, `class`, `zeny`, `status_point`,`str`, `agi`, `vit`, `int`, `dex`, `luk`, `max_hp`, `hp`," "`max_sp`, `sp`, `hair`, `hair_color`, `last_map`, `last_x`, `last_y`, `save_map`, `save_x`, `save_y`) VALUES (" - "'%d', '%d', '%s', '%d', '%d','%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d','%d', '%d','%d', '%d', '%s', '%d', '%d', '%s', '%d', '%d')", char_db, sd->account_id , slot, esc_name, starting_job, start_zeny, 48, str, agi, vit, int_, dex, luk, (40 * (100 + vit)/100) , (40 * (100 + vit)/100 ), (11 * (100 + int_)/100), (11 * (100 + int_)/100), hair_style, hair_color, mapindex_id2name(start_point.map), start_point.x, start_point.y, mapindex_id2name(start_point.map), start_point.x, start_point.y) ) Isn't this missing a '%d' in the format string? (it adds an argument, doesn't add the matching format string placeholder) // Insert the new char entry to the database if (SQL_ERROR == SQL->Query(inter->sql_handle, "INSERT INTO `%s` (`account_id`, `char_num`, `name`, `class`, `zeny`, `status_point`,`str`, `agi`, `vit`, `int`, `dex`, `luk`, `max_hp`, `hp`," "`max_sp`, `sp`, `hair`, `hair_color`, `last_map`, `last_x`, `last_y`, `save_map`, `save_x`, `save_y`) VALUES (" + "'%d', '%d', '%s', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d','%d', '%d','%d', '%d', '%s', '%d', '%d', '%s', '%d', '%d')", char_db, sd->account_id , slot, esc_name, starting_job, start_zeny, 48, str, agi, vit, int_, dex, luk, (40 * (100 + vit)/100) , (40 * (100 + vit)/100 ), (11 * (100 + int_)/100), (11 * (100 + int_)/100), hair_style, hair_color, mapindex_id2name(start_point.map), start_point.x, start_point.y, mapindex_id2name(start_point.map), start_point.x, start_point.y) )
codereview_cpp_data_617
* This will properly maintain the copyright information. DigitalGlobe * copyrights will be updated automatically. * - * @copyright Copyright (C) 2017 DigitalGlobe (http://www.digitalglobe.com/) */ // Hoot #include "../TestUtils.h" Looks like the copyright stuff needs to be run on the new files. * This will properly maintain the copyright information. DigitalGlobe * copyrights will be updated automatically. * + * @copyright Copyright (C) 2017, 2018 DigitalGlobe (http://www.digitalglobe.com/) */ // Hoot #include "../TestUtils.h"
codereview_cpp_data_634
pal[i].unused = 0; } - if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 8) { - SDL_SetColors(_sdl_screen, pal, _local_palette.first_dirty, _local_palette.count_dirty); - } if (_sdl_screen != _sdl_realscreen && init) { /* When using a shadow surface, also set our palette on the real screen. This lets SDL codestyle - if statements with a single statement as a body need to be on the same line, or enclosed by braces. Probably want to add the braces & other places pal[i].unused = 0; } + SDL_SetColors(_sdl_screen, pal, _local_palette.first_dirty, _local_palette.count_dirty); if (_sdl_screen != _sdl_realscreen && init) { /* When using a shadow surface, also set our palette on the real screen. This lets SDL
codereview_cpp_data_637
commitBlocks(); - std::vector<decltype(hash3)> hashes; hashes.push_back(hash1); hashes.emplace_back("AbsolutelyInvalidHash"); hashes.push_back(hash2); Why to change that? commitBlocks(); + std::vector<decltype(hash1)> hashes; hashes.push_back(hash1); hashes.emplace_back("AbsolutelyInvalidHash"); hashes.push_back(hash2);
codereview_cpp_data_652
if (--(sce->val4) >= 0) { // Needed to check the caster's location for the range check. struct block_list *src = map->id2bl(sce->val2); - if (!src || status->isdead(src) || src->m != bl->m || !check_distance_bl(bl, src, 11)) break; status->heal(bl, 150 * sce->val1, 0, 2); should be used ``status->isdead`` if (--(sce->val4) >= 0) { // Needed to check the caster's location for the range check. struct block_list *src = map->id2bl(sce->val2); + if (!src || status_isdead(src) || src->m != bl->m || !check_distance_bl(bl, src, 11)) break; status->heal(bl, 150 * sce->val1, 0, 2);
codereview_cpp_data_654
os << std::endl << "# auto combat spell casting: on/off" << std::endl; os << "auto spell casting = " << ( opt_global.Modes( GLOBAL_BATTLE_AUTO_SPELLCAST ) ? "on" : "off" ) << std::endl; - os << std::endl << "# game language (empty field is for English)" << std::endl; os << "lang = " << force_lang << std::endl; os << std::endl << "# controller pointer speed: 0 - 100" << std::endl; I'd rephrase this as "an empty value means English" :) os << std::endl << "# auto combat spell casting: on/off" << std::endl; os << "auto spell casting = " << ( opt_global.Modes( GLOBAL_BATTLE_AUTO_SPELLCAST ) ? "on" : "off" ) << std::endl; + os << std::endl << "# game language (an empty value means English)" << std::endl; os << "lang = " << force_lang << std::endl; os << std::endl << "# controller pointer speed: 0 - 100" << std::endl;
codereview_cpp_data_655
return true; } -bool ArtifactsBar::ActionBarLeftMouseDoubleClick( const fheroes2::Point &, Artifact & art, const fheroes2::Rect & ) { if ( art.GetID() == Artifact::SPELL_SCROLL && Settings::Get().ExtHeroAllowTranscribingScroll() && !read_only && _hero->CanTranscribeScroll( art ) ) { Spell spell = art.GetSpell(); :warning: **readability\-named\-parameter** :warning: all parameters should be named in a function ```suggestion bool ArtifactsBar::ActionBarLeftMouseDoubleClick( const fheroes2::Point & /*cursor*/, Artifact & art, const fheroes2::Rect & /*pos*/) ``` return true; } +bool ArtifactsBar::ActionBarLeftMouseDoubleClick( const fheroes2::Point & /*cursor*/, Artifact & art, const fheroes2::Rect & /*pos*/) { if ( art.GetID() == Artifact::SPELL_SCROLL && Settings::Get().ExtHeroAllowTranscribingScroll() && !read_only && _hero->CanTranscribeScroll( art ) ) { Spell spell = art.GetSpell();
codereview_cpp_data_657
#if !defined(_WIN32) || defined(__CYGWIN__) #include <signal.h> #define HAS_SIGNALS -extern "C" -{ - int killpg(pid_t pgrp, int sig); -} #endif // globally accessible variables I don't really like forward declaring of standard functions. Can you check if putting `#define _DEFAULT_SOURCE` before the `#include <signal.h>` also works? Looking at the header, this seems to trigger that the killpg prototype becomes declared. #if !defined(_WIN32) || defined(__CYGWIN__) #include <signal.h> #define HAS_SIGNALS #endif // globally accessible variables
codereview_cpp_data_661
assert_fatal(src.IsObject(), path + " Irohad config top element must be an object."); const auto obj = src.GetObject(); - getValByKey(path, dest.blok_store_path, obj, config_members::BlockStorePath); getValByKey(path, dest.torii_port, obj, config_members::ToriiPort); getValByKey(path, dest.internal_port, obj, config_members::InternalPort); getValByKey(path, dest.pg_opt, obj, config_members::PgOpt); ```suggestion getValByKey(path, dest.block_store_path, obj, config_members::BlockStorePath); ``` assert_fatal(src.IsObject(), path + " Irohad config top element must be an object."); const auto obj = src.GetObject(); + getValByKey(path, dest.block_store_path, obj, config_members::BlockStorePath); getValByKey(path, dest.torii_port, obj, config_members::ToriiPort); getValByKey(path, dest.internal_port, obj, config_members::InternalPort); getValByKey(path, dest.pg_opt, obj, config_members::PgOpt);
codereview_cpp_data_663
* pulled a flatpak ref using flatpak_installation_install_full() and * specified %FLATPAK_INSTALL_FLAGS_NO_DEPLOY but then decided not to * deploy the ref later on and want to remove the local ref to prevent it - * from taking up disk space. Note that this will not remove the objects - * referred to by @ref from the underlying OSTree repo, you should use - * flatpak_installation_prune_local_repo() to do that. * * Returns: %TRUE on success */ Maybe we also need a prune operation? * pulled a flatpak ref using flatpak_installation_install_full() and * specified %FLATPAK_INSTALL_FLAGS_NO_DEPLOY but then decided not to * deploy the ref later on and want to remove the local ref to prevent it + * from taking up disk space. * * Returns: %TRUE on success */
codereview_cpp_data_669
{ if (m_RankMPI == 0) { - std::cout << "Warning substreams is less than zero, using " "substreams=1, in call to Open\n"; } subStreams = 1; Warning substreams is less than ONE { if (m_RankMPI == 0) { + std::cout << "Warning substreams is less than 1, using " "substreams=1, in call to Open\n"; } subStreams = 1;
codereview_cpp_data_672
return true; } - check_acked_status(); logInfo(RTPS_HISTORY, "Reader Proxy doesn't exist in this writer"); return false; } As we have not modified the list of matched readers, I don't think this is necessary return true; } logInfo(RTPS_HISTORY, "Reader Proxy doesn't exist in this writer"); return false; }
codereview_cpp_data_689
auto sig = proto_->mutable_signature(); sig->set_signature(crypto::toBinaryString(signed_blob)); sig->set_public_key(crypto::toBinaryString(public_key)); signatures_.emplace(proto_->signature()); return true; } I wonder how did it work before. Please add a task and a TODO to cover such methods of other shared model classes. auto sig = proto_->mutable_signature(); sig->set_signature(crypto::toBinaryString(signed_blob)); sig->set_public_key(crypto::toBinaryString(public_key)); + // TODO: nickaleks IR-120 12.12.2018 remove set signatures_.emplace(proto_->signature()); return true; }
codereview_cpp_data_691
return ihipLogStatus(hipErrorInvalidSymbol); } - return ihipLogStatus(hip_internal::memcpySync(dst, (char*)src+offset, count, kind, hipStreamNull)); } Since you are adding error checks don't you think symbol_name and hipMemcpyKind should also be validated? return ihipLogStatus(hipErrorInvalidSymbol); } + if (kind == hipMemcpyHostToDevice || kind == hipMemcpyHostToHost) { + return ihipLogStatus(hipErrorInvalidMemcpyDirection); + } else if (kind == hipMemcpyDeviceToDevice) { + return ihipLogStatus(hipErrorInvalidValue); + } + + return ihipLogStatus(hip_internal::memcpySync(dst, static_cast<const char*>(src)+offset, count, kind, hipStreamNull)); }
codereview_cpp_data_695
// from disk, but an active partition does not have any files // on disk, so it should never get selected for deletion. VAST_WARN("{} got erase atom as an active partition", self); - return atom::done_v; }, [self](caf::stream<table_slice> in) { self->state.streaming_initiated = true; Should this return an error to the disk monitor instead? // from disk, but an active partition does not have any files // on disk, so it should never get selected for deletion. VAST_WARN("{} got erase atom as an active partition", self); + return caf::make_error(ec::logic_error, "can not erase the active " + "partition"); }, [self](caf::stream<table_slice> in) { self->state.streaming_initiated = true;
codereview_cpp_data_706
{ slocalname = new string(); } - if (sync->client->fsaccess->getsname(newlocalpath, slocalname) && slocalname->size() && *slocalname != localname) { parent->schildren[slocalname] = this; } It seems that `slocalname->size()` is always true if `getsname()` returned true. Maybe the check is not needed. { slocalname = new string(); } + if (sync->client->fsaccess->getsname(newlocalpath, slocalname) && *slocalname != localname) { parent->schildren[slocalname] = this; }
codereview_cpp_data_707
MEventType MEvent::getType() { - return (MEventType) (megaEvent ? megaEvent->getType() : 0); } String^ MEvent::getText() I'd use -1 by default, since 0 is a valid type of event. Anyway, the callback `onEvent(e)` always provide a valid object `e` (not like `onUserUpdate()` and similar, which are called with `NULL` upon fetchnodes completion) MEventType MEvent::getType() { + return (MEventType) (megaEvent ? megaEvent->getType() : -1); } String^ MEvent::getText()
codereview_cpp_data_716
k2ch = k2c/hbar; K6h = K6/hbar; - if (strstr(update->integrate_style,"respa")) { ilevel_respa = ((Respa *) update->integrate)->nlevels-1; if (respa_level >= 0) ilevel_respa = MIN(respa_level,ilevel_respa); } this change should be reverted. k2ch = k2c/hbar; K6h = K6/hbar; + if (utils::strmatch(update->integrate_style,"^respa")) { ilevel_respa = ((Respa *) update->integrate)->nlevels-1; if (respa_level >= 0) ilevel_respa = MIN(respa_level,ilevel_respa); }
codereview_cpp_data_718
&& (msg.source == self->state.archive || msg.source == self->state.index)) report_statistics(self); - // Without sinks and resumable sessions, there's not reason to proceed. self->quit(msg.reason); } ); ```suggestion // Without sinks and resumable sessions, there's no reason to proceed. ``` && (msg.source == self->state.archive || msg.source == self->state.index)) report_statistics(self); + // Without sinks and resumable sessions, there's no reason to proceed. self->quit(msg.reason); } );
codereview_cpp_data_724
#include "framework/integration_framework/fake_peer/proposal_storage.hpp" namespace integration_framework { namespace fake_peer { might be a bit clearer: `return it->second ? OrderingProposalRequestResult{*it->second}: boost::none;` #include "framework/integration_framework/fake_peer/proposal_storage.hpp" +#include <mutex> + namespace integration_framework { namespace fake_peer {
codereview_cpp_data_725
proposed_kems.data = s2n_stuffer_raw_read(extension, proposed_kems.size); notnull_check(proposed_kems.data); - if (s2n_kem_find_supported_kem(&proposed_kems, s2n_sike_supported_params, 1, &conn->secure.s2n_kem_keys.negotiated_kem) != 0) { - /* Can't agree on a kem. Return success to proceed with the handshake. */ - conn->secure.s2n_kem_keys.negotiated_kem = NULL; - } return 0; } This one line is doing a few different things at once, I think we should break it up: ``` struct s2n_kem *match = NULL; int num_params = sizeof(s2n_sike_supported_params) / sizeof(s2n_sike_supported_params[0]); s2n_kem_find_supported_kem(&proposed_kems, s2n_sike_supported_params, num_params, match); conn->secure.s2n_kem_keys.negotiated_kem = match; /* If no supported kem is found, match stays NULL */ return 0; ``` proposed_kems.data = s2n_stuffer_raw_read(extension, proposed_kems.size); notnull_check(proposed_kems.data); + const struct s2n_kem *match = NULL; + int num_params = sizeof(s2n_sike_supported_params) / sizeof(s2n_sike_supported_params[0]); + s2n_kem_find_supported_kem(&proposed_kems, s2n_sike_supported_params, num_params, &match); + conn->secure.s2n_kem_keys.negotiated_kem = match; + return 0; }
codereview_cpp_data_749
//{ Close(it->second); //} - m_OutputFileMap.erase(it); } for (auto it = m_InputFileMap.begin(); it != m_InputFileMap.end(); ++it) { @pnorbert the test failures on Windows are due to invalidating the loop iterator here (and in the input loop below). The `.erase()` removes the current iterator so the `++it` in end of the `for()` tries to increment an invalid iterator. In a Debug build the MSVC iterator debugging catches it. Otherwise this likely strays off and doesn't actually close or flush all of the files, hence the test failure. I fixed it locally with ```patch diff --git a/source/adios2/toolkit/burstbuffer/FileDrainer.cpp b/source/adios2/toolkit/burstbuffer/FileDrainer.cpp index 72b0b85e..97eb793a 100644 --- a/source/adios2/toolkit/burstbuffer/FileDrainer.cpp +++ b/source/adios2/toolkit/burstbuffer/FileDrainer.cpp @@ -181,16 +181,16 @@ void FileDrainer::CloseAll() //{ Close(it->second); //} - m_OutputFileMap.erase(it); } + m_OutputFileMap.clear(); for (auto it = m_InputFileMap.begin(); it != m_InputFileMap.end(); ++it) { // if (it->second->good()) //{ Close(it->second); //} - m_InputFileMap.erase(it); } + m_InputFileMap.clear(); } void FileDrainer::Seek(InputFile &f, size_t offset, const std::string &path) ``` With that the `Utils.IOTest.BurstBuffer.1to1.BP4.Write` test passes. //{ Close(it->second); //} } for (auto it = m_InputFileMap.begin(); it != m_InputFileMap.end(); ++it) {
codereview_cpp_data_752
if(connection->state == UA_CONNECTION_CLOSED) return; connection->state = UA_CONNECTION_CLOSED; #endif /* only "shutdown" here. this triggers the select, where the socket is "closed" in the mainloop */ i still do not get why you deleted this? the "normal" network layer has the pointer to itself if(connection->state == UA_CONNECTION_CLOSED) return; connection->state = UA_CONNECTION_CLOSED; +#endif +#if UA_LOGLEVEL <= 300 + //cppcheck-suppress unreadVariable + ServerNetworkLayerTCP *layer = connection->handle; + UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK, "Connection %i | Force closing the connection", + connection->sockfd); #endif /* only "shutdown" here. this triggers the select, where the socket is "closed" in the mainloop */
codereview_cpp_data_759
void ScalarActuator::constructOutputs() { - constructOutput<double>("Actuation", &ScalarActuator::getActuation, SimTK::Stage::Velocity); constructOutput<double>("speed", &ScalarActuator::getSpeed, SimTK::Stage::Velocity); } lower case `A` void ScalarActuator::constructOutputs() { + constructOutput<double>("actuation", &ScalarActuator::getActuation, SimTK::Stage::Velocity); constructOutput<double>("speed", &ScalarActuator::getSpeed, SimTK::Stage::Velocity); }
codereview_cpp_data_763
pScene->mNumMaterials = sib.mtls.size(); pScene->mNumMeshes = sib.meshes.size(); pScene->mNumLights = sib.lights.size(); - pScene->mMaterials = pScene->mNumMaterials ? new aiMaterial*[pScene->mNumMaterials] : 0; - pScene->mMeshes = pScene->mNumMeshes ? new aiMesh*[pScene->mNumMeshes] : 0; - pScene->mLights = pScene->mNumLights ? new aiLight*[pScene->mNumLights] : 0; if (pScene->mNumMaterials) memcpy(pScene->mMaterials, &sib.mtls[0], sizeof(aiMaterial*) * pScene->mNumMaterials); if (pScene->mNumMeshes) Coud you please use NULL istead of 0? pScene->mNumMaterials = sib.mtls.size(); pScene->mNumMeshes = sib.meshes.size(); pScene->mNumLights = sib.lights.size(); + pScene->mMaterials = pScene->mNumMaterials ? new aiMaterial*[pScene->mNumMaterials] : NULL; + pScene->mMeshes = pScene->mNumMeshes ? new aiMesh*[pScene->mNumMeshes] : NULL; + pScene->mLights = pScene->mNumLights ? new aiLight*[pScene->mNumLights] : NULL; if (pScene->mNumMaterials) memcpy(pScene->mMaterials, &sib.mtls[0], sizeof(aiMaterial*) * pScene->mNumMaterials); if (pScene->mNumMeshes)