id
stringlengths
21
25
content
stringlengths
164
2.33k
codereview_cpp_data_4329
hwloc_topology_destroy(topo); #endif - // Initialize local random number generators. - init_random(seed); - init_data_seq_random(seed); - #ifdef LBANN_HAS_SHMEM // Initialize SHMEM { Should this be restored in some way? Also, it makes sense that (NV)SHMEM would require `MPI_COMM_WORLD` because the SHEAP is global (in the specific case of OpenMPI, global to a PMI universe). hwloc_topology_destroy(topo); #endif #ifdef LBANN_HAS_SHMEM // Initialize SHMEM {
codereview_cpp_data_4332
// Return true when all valid troops have the same ID, or when there are no troops bool Troops::AllTroopsAreTheSame( void ) const { - const Troop * first_troop = nullptr; for ( const Troop * troop : *this ) { if ( troop->isValid() ) { - if ( first_troop == nullptr ) { - first_troop = troop; } - else if ( troop->GetID() != first_troop->GetID() ) { return false; } } We could avoid pointer usage by having `int firstMonsterId = UNKNOWN;` What do you think? // Return true when all valid troops have the same ID, or when there are no troops bool Troops::AllTroopsAreTheSame( void ) const { + int firstMonsterId = Monster::UNKNOWN; for ( const Troop * troop : *this ) { if ( troop->isValid() ) { + if ( firstMonsterId == Monster::UNKNOWN ) { + firstMonsterId = troop->GetID(); } + else if ( troop->GetID() != firstMonsterId ) { return false; } }
codereview_cpp_data_4347
} if (GetTarget() == this) { - this->MessageString(Chat::TooFarAway, TRY_ATTACKING_SOMEONE); auto_fire = false; return; } Don't need this-> here. } if (GetTarget() == this) { + MessageString(Chat::TooFarAway, TRY_ATTACKING_SOMEONE); auto_fire = false; return; }
codereview_cpp_data_4353
if (rdevices > 0) { if (skip_device > 0 && rdevices == 1) Impl::throw_runtime_exception( - "Error: cannot KOKKOS_SKIP_DEVICE the only " - "KOKKOS_RAND_DEVICE.Raised by Kokkos::initialize(int narg, char* " - "argc[])."); std::srand(getpid()); while (device < 0) { Formatting looks weird. Missing a space after the dot at the end go the 1st sentence. if (rdevices > 0) { if (skip_device > 0 && rdevices == 1) Impl::throw_runtime_exception( + "Error: cannot KOKKOS_SKIP_DEVICE the only KOKKOS_RAND_DEVICE. " + "Raised by Kokkos::initialize(int narg, char* argc[])."); std::srand(getpid()); while (device < 0) {
codereview_cpp_data_4362
} } - printf("kc:%p\n", kc ); // refresh other kerning input boxes if they are the same characters static int MV_ChangeKerning_Nested = 0; int refreshOtherPairEntries = true; There is a lot of added printfs in this file, I'd probably convert them to debug printfs. } } // refresh other kerning input boxes if they are the same characters static int MV_ChangeKerning_Nested = 0; int refreshOtherPairEntries = true;
codereview_cpp_data_4366
} } - this->max_hp = std::min(max_hp, 2147483647LL); return this->max_hp; } Shouldn't we do something like `std::numeric_limits<decltype(Mob::max_hp)>::max()` } } + this->max_hp = std::min(max_hp, (int64)2147483647); return this->max_hp; }
codereview_cpp_data_4373
} const size_t expected{ column_labels.size() * 3 + 2 }; - // Will read into in memory matrix, then create table from matrix int rowNumber = 0; int last_size = 1024; SimTK::Matrix_<SimTK::Vec3> markerData{last_size, static_cast<int>(num_markers_expected)}; "Will read into in memory matrix" was a little confusing to me. Consider "Will first store data in a SimTK::Matrix to avoid expensive calls to the table's appendRow()." } const size_t expected{ column_labels.size() * 3 + 2 }; + // Will first store data in a SimTK::Matrix to avoid expensive calls + // to the table's appendRow() which reallocates and copies the whole table. int rowNumber = 0; int last_size = 1024; SimTK::Matrix_<SimTK::Vec3> markerData{last_size, static_cast<int>(num_markers_expected)};
codereview_cpp_data_4378
if (nullptr == new_params) return proj_errno_set (P, ENOMEM); new_params->next = pj_mkparam (ellps->ell); - if (nullptr == new_params) { pj_dealloc(new_params); return proj_errno_set (P, ENOMEM); cppcheck complains: ``` /home/travis/build/OSGeo/PROJ/src/ell_set.cpp:163,warning,nullPointer,Possible null pointer dereference: new_params - otherwise it is redundant to check it against null. ``` Indeed the check should be against new_params->next if (nullptr == new_params) return proj_errno_set (P, ENOMEM); new_params->next = pj_mkparam (ellps->ell); + if (nullptr == new_params->next) { pj_dealloc(new_params); return proj_errno_set (P, ENOMEM);
codereview_cpp_data_4379
} TEST_F(AmetsuchiTest, SampleTest) { - auto storage = StorageImpl::create(block_store_path, pgopt_); ASSERT_TRUE(storage); auto wsv = storage->getWsvQuery(); auto blocks = storage->getBlockQuery(); Are these two builders used? } TEST_F(AmetsuchiTest, SampleTest) { + std::shared_ptr<StorageImpl> storage; + auto storageResult = StorageImpl::create(block_store_path, pgopt_); + storageResult.match( + [&](iroha::expected::Value<std::shared_ptr<StorageImpl>> &_storage) { + storage = _storage.value; + }, + [](iroha::expected::Error<std::string> &error) { + FAIL() << "StorageImpl: " << error.error; + }); ASSERT_TRUE(storage); auto wsv = storage->getWsvQuery(); auto blocks = storage->getBlockQuery();
codereview_cpp_data_4385
} int main(int argc, char const *argv[]) { // Compute the result of (b^p) % m - long long int b, p, m; - while (cin >> b >> p >> m) - cout << solve(b%m, p, m) << endl; return 0; } don't you think the function name should be more descriptive, something which relates to binary exponentiation? } int main(int argc, char const *argv[]) { // Compute the result of (b^p) % m + // b and p are the maximum value of long long int + // m is sqrt(2^63 - 1) + long long int b = (1ll<<63) - 1, p = b, m = 3037000499; + cout << solve(b, p, m) << endl; return 0; }
codereview_cpp_data_4397
#include <climits> #include <iostream> -/** - * @brief description - * @param n description - * @returns description - */ /** * @brief description * @param n description Provide a brief description about the parameters, return statement and description of the function. See #962 as a reference. ```suggestion /** * @brief description * @param n description * @returns description */ ``` #include <climits> #include <iostream> /** * @brief description * @param n description
codereview_cpp_data_4409
See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include <cmath> -#include <cstdlib> #include <cstring> -#include "fix_deposit.h" #include "atom.h" #include "atom_vec.h" #include "molecule.h" this is undoing recent changes for increased consistency of include file statements. please restore to the original. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ +#include "fix_deposit.h" +#include <mpi.h> #include <cmath> #include <cstring> #include "atom.h" #include "atom_vec.h" #include "molecule.h"
codereview_cpp_data_4430
// If XVal is not on then check all inputs, otherwise only check // transactions that were not previously verified in the mempool. bool fUnVerified = block.setUnVerifiedTxns.count(hash); - if ((block.fXVal && fUnVerified) || !block.fXVal) { if (fUnVerified) nUnVerifiedChecked++; Isn't this equivalent to: ```c++ if (!block.fXVal || fUnVerified) ``` // If XVal is not on then check all inputs, otherwise only check // transactions that were not previously verified in the mempool. bool fUnVerified = block.setUnVerifiedTxns.count(hash); + if (fUnVerified || !block.fXVal) { if (fUnVerified) nUnVerifiedChecked++;
codereview_cpp_data_4433
if (not res and not *res) { // Continue parsing - std::cout << "Enter the value again" << std::endl ; return true; } redundant space before `;` if (not res and not *res) { // Continue parsing + std::cout << "Unable to parse the result." << std::endl; return true; }
codereview_cpp_data_4435
const int defaultYPosition = 160; const int boxHeight = free_slots > 2 ? 90 + spacer : 45; - const int boxYPosition = defaultYPosition + ( ( display.height() - display.DEFAULT_HEIGHT ) * 0.5f ) - boxHeight; NonFixedFrameBox box( boxHeight, boxYPosition, true ); SelectValue sel( min, max, cur, 1 ); Please just divide by 2. In this case we don't introduce implicit type conversion. const int defaultYPosition = 160; const int boxHeight = free_slots > 2 ? 90 + spacer : 45; + const int boxYPosition = defaultYPosition + ( ( display.height() - display.DEFAULT_HEIGHT ) / 2 ) - boxHeight; NonFixedFrameBox box( boxHeight, boxYPosition, true ); SelectValue sel( min, max, cur, 1 );
codereview_cpp_data_4439
} if (strProjectPlanClass.Find(_T("nvidia")) != wxNOT_FOUND) { - pProjectInfo->m_bProjectSupportsIntelGPU = true; if (!pDoc->state.host_info.coprocs.have_nvidia()) continue; } Bug, though checking for `nvidia` makes sense to catch NVIDIA+OpenCL. } if (strProjectPlanClass.Find(_T("nvidia")) != wxNOT_FOUND) { + pProjectInfo->m_bProjectSupportsCUDA = true; if (!pDoc->state.host_info.coprocs.have_nvidia()) continue; }
codereview_cpp_data_4443
#include <sstream> #include <string> -// FIXME: workaround for actor-framework/actor-framework#940 namespace caf { std::string to_string(pec x); -} namespace vast { namespace { ```suggestion } // namespace caf ``` Would you mind adding concrete guidance on how to fix this in the future? e.g., "remove this forward declaration after upgrading to 17.3" #include <sstream> #include <string> +// FIXME: Workaround for actor-framework/actor-framework#940 +// Remove this declaration when updating to CAF >0.17.2 namespace caf { std::string to_string(pec x); +} // namespace caf namespace vast { namespace {
codereview_cpp_data_4445
__CPROVER_assume(s2n_stuffer_is_valid(stuffer)); __CPROVER_assume(s2n_blob_is_bounded(&stuffer->blob, BLOB_SIZE)); const char expected; - int min; - int max; uint32_t index; /* Save previous state from stuffer. */ You can also check that you skipped between `min` and `max` __CPROVER_assume(s2n_stuffer_is_valid(stuffer)); __CPROVER_assume(s2n_blob_is_bounded(&stuffer->blob, BLOB_SIZE)); const char expected; + unsigned int min; + unsigned int max; + unsigned int skipped; uint32_t index; /* Save previous state from stuffer. */
codereview_cpp_data_4450
GUARD_AS_POSIX(s2n_array_get(psk_list, i, (void**) &psk)); notnull_check(psk); - /* From https://tools.ietf.org/html/rfc8446#section-4.1.4: - * In its updated ClientHello, the client SHOULD NOT offer - * any pre-shared keys associated with a hash other than that of the - * selected cipher suite. */ if (s2n_is_hello_retry_handshake(conn) && conn->secure.cipher_suite->prf_alg != psk->hmac_alg) { continue; Nit: Indenting is a bit off here. GUARD_AS_POSIX(s2n_array_get(psk_list, i, (void**) &psk)); notnull_check(psk); + /*= https://tools.ietf.org/html/rfc8446#section-4.1.4 + *# In its updated ClientHello, the client SHOULD NOT offer + *# any pre-shared keys associated with a hash other than that of the + *# selected cipher suite. */ if (s2n_is_hello_retry_handshake(conn) && conn->secure.cipher_suite->prf_alg != psk->hmac_alg) { continue;
codereview_cpp_data_4451
{ if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { - auto *keyEvent = (QKeyEvent *) event; if (event->type() == QEvent::KeyPress && !keyEvent->isAutoRepeat()) { Replace with cpp-style cast? I think this is a `reinterpret_cast` ? { if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { + auto *keyEvent = reinterpret_cast<QKeyEvent *>(event); if (event->type() == QEvent::KeyPress && !keyEvent->isAutoRepeat()) {
codereview_cpp_data_4461
I.RedrawFocus(); I.Redraw(); - if ( castle && castle->GetHeroes().Guest() && castle->GetHeroes().Guest() != &hero ) { - Dialog::Message( "", _( "Nearest town occupied.\nSpell Failed!!!" ), Font::BIG, Dialog::OK ); return false; } - else if ( !castle ) { - Dialog::Message( "", _( "No available towns.\nSpell Failed!!!" ), Font::BIG, Dialog::OK ); return false; } Let's do reverse logic: ``` if ( !castle ) { } else if ( castle->GetHeroes().Guest() && castle->GetHeroes().Guest() != &hero ) { } ``` so that we can save one check :) I.RedrawFocus(); I.Redraw(); + if ( !castle ) { + Dialog::Message( "", _( "No available towns.\nSpell Failed!!!" ), Font::BIG, Dialog::OK ); return false; } + else if ( castle->GetHeroes().Guest() && castle->GetHeroes().Guest() != &hero ) { + Dialog::Message( "", _( "Nearest town occupied.\nSpell Failed!!!" ), Font::BIG, Dialog::OK ); return false; }
codereview_cpp_data_4471
MapsIndexes vec_eyes = Maps::GetObjectPositions( MP2::OBJ_EYEMAGI, false ); if ( vec_eyes.size() ) { for ( MapsIndexes::const_iterator it = vec_eyes.begin(); it != vec_eyes.end(); ++it ) { Maps::ClearFog( *it, Game::GetViewDistance( Game::VIEW_MAGI_EYES ), hero.GetColor() ); - Interface::Basic & I = Interface::Basic::Get(); I.GetGameArea().SetCenter( Maps::GetPoint( *it ) ); I.RedrawFocus(); I.Redraw(); At the end of this code we should return to the original place. Right now it stops at the last eye. Please add such logic after. MapsIndexes vec_eyes = Maps::GetObjectPositions( MP2::OBJ_EYEMAGI, false ); if ( vec_eyes.size() ) { + Interface::Basic & I = Interface::Basic::Get(); for ( MapsIndexes::const_iterator it = vec_eyes.begin(); it != vec_eyes.end(); ++it ) { Maps::ClearFog( *it, Game::GetViewDistance( Game::VIEW_MAGI_EYES ), hero.GetColor() ); I.GetGameArea().SetCenter( Maps::GetPoint( *it ) ); I.RedrawFocus(); I.Redraw();
codereview_cpp_data_4473
} } static void SplitMonotonicAtFake(Monotonic *m,int which,bigreal coord, struct inter_data *id) { SplitMonotonicAtFlex(m, which, coord, id, 0); We can note that the function is unused, but there are likely future cases in which this function would be used, and I want to make sure that we call this function in those cases rather than calling SplitMonotonicAtFlex with the extra argument. } } +static void SplitMonotonicAt(Monotonic *m,int which,bigreal coord, + struct inter_data *id) { + SplitMonotonicAtFlex(m, which, coord, id, 1); +} + static void SplitMonotonicAtFake(Monotonic *m,int which,bigreal coord, struct inter_data *id) { SplitMonotonicAtFlex(m, which, coord, id, 0);
codereview_cpp_data_4482
NULL, "SFXSound sfxCreateSource( SFXDescription description, string filename, float x, float y, float z );" ); -DefineConsoleFunction( sfxCreateSource, S32, ( const char * SFXType, const char * filename, const char * x, const char * y, const char * z ), ("", "", "", ""), "( SFXTrack track | ( SFXDescription description, string filename ) [, float x, float y, float z ] ) " "Creates a new paused sound source using a profile or a description " "and filename. The return value is the source which must be " I think this functions is dificult to convert to `DefineConsoleFunction`, becouse `SFXTrack track | ( SFXDescription description, string filename )` NULL, "SFXSound sfxCreateSource( SFXDescription description, string filename, float x, float y, float z );" ); +DefineConsoleFunction( sfxCreateSource, S32, ( const char * sfxType, const char * arg0, const char * arg1, const char * arg2, const char * arg3 ), ("", "", "", ""), "( SFXTrack track | ( SFXDescription description, string filename ) [, float x, float y, float z ] ) " "Creates a new paused sound source using a profile or a description " "and filename. The return value is the source which must be "
codereview_cpp_data_4484
bool optionOrArgBelongsToCommand (const Key * command, const Key * optionOrArg) { const Key * commandKey = keyGetMeta (optionOrArg, META_COMMAND_KEY); - if (commandKey != NULL) - { - const char * commandKeyString = keyString (commandKey); - if (commandKeyString != NULL) - { - return strcmp (keyName (command), commandKeyString) == 0; - } - } - return false; } ```suggestion ```suggestion const Key * commandKey = keyGetMeta (optionOrArg, META_COMMAND_KEY); const char * commandKeyString = commandKey != NULL ? keyString (commandKey) : NULL; return commandKeyString != NULL && strcmp (keyName (command), commandKeyString) == 0; ``` By using a ternary you can reduce the nesting of this code a bit. bool optionOrArgBelongsToCommand (const Key * command, const Key * optionOrArg) { const Key * commandKey = keyGetMeta (optionOrArg, META_COMMAND_KEY); + const char * commandKeyString = commandKey != NULL ? keyString (commandKey) : NULL; + return commandKeyString != NULL && strcmp (keyName (command), commandKeyString) == 0; }
codereview_cpp_data_4495
#include "lbann/callbacks/callback_learning_rate.hpp" #include <limits> #include <utility> -#include <cmath> // pow namespace lbann { Could we use `std::pow` instead? #include "lbann/callbacks/callback_learning_rate.hpp" #include <limits> #include <utility> +#include <cmath> // std::pow namespace lbann {
codereview_cpp_data_4506
// If prev is coinbase, check that it's matured if (coin.IsCoinBase()) { CAmount nCoinOutValue = coin.out.nValue; int nCoinHeight = coin.nHeight; Leave and re-enter is a bit of a lie because the protected variables cannot be used after inputs.cs_utxo is given, even if it is relocked. So I would like to discourage its use, since it will be prone to bugs. In this case, the code correctly does not use "coin" after the lock is given. However, this code would be a lot more clear if the lock just protected pulling the relevant data out of "coin" and into local variables, at the top of the for loop body. This is already basically happening in lines 229 and 230, so a bit of reorg (pull these locals out of the if, assign them, and use in the else as well) could make this code both cleaner and lock cs_utxo for less time. // If prev is coinbase, check that it's matured if (coin.IsCoinBase()) { + // Copy these values here because once we unlock and re-lock cs_utxo we can't count on "coin" + // still being valid. CAmount nCoinOutValue = coin.out.nValue; int nCoinHeight = coin.nHeight;
codereview_cpp_data_4517
void RPCTypeCheck(const UniValue &params, const list<UniValue::VType> &typesExpected, bool fAllowNull) { unsigned int i = 0; - for (UniValue::VType t : typesExpected) { if (params.size() <= i) break; can can we add a reference here? +for(UniValue::VType &t : .... void RPCTypeCheck(const UniValue &params, const list<UniValue::VType> &typesExpected, bool fAllowNull) { unsigned int i = 0; + for (const UniValue::VType &t : typesExpected) { if (params.size() <= i) break;
codereview_cpp_data_4521
g_string_append_printf (txn_title, "; localinstall: %u", pkgs->len); g_ptr_array_add (pkgs, NULL); if (!rpmostree_origin_add_packages (origin, (char**)pkgs->pdata, TRUE, - idempotent_layering, &changed, error)) return FALSE; } } We need to do something like: ``` add_packages (..., &add_changed); if (add_changed) changed = TRUE; ``` otherwise if we changed an install but not an uninstall, the latter will override right? g_string_append_printf (txn_title, "; localinstall: %u", pkgs->len); g_ptr_array_add (pkgs, NULL); + + gboolean add_changed = FALSE; if (!rpmostree_origin_add_packages (origin, (char**)pkgs->pdata, TRUE, + idempotent_layering, &add_changed, error)) return FALSE; + + changed = changed || add_changed; } }
codereview_cpp_data_4527
self->state.self = self; self->state.path = path; self->state.archive = legacy_archive; - self->state.id = id; self->state.name = "partition-" + id_string; VAST_TRACEPOINT(passive_partition_spawned, id_string.c_str()); self->set_exit_handler([=](const caf::exit_msg& msg) { How about just this and ditch the extra local variable? ```cpp self->state.id = to_string(id); self->state.name = "partition-" + self->state.name; ``` self->state.self = self; self->state.path = path; self->state.archive = legacy_archive; self->state.name = "partition-" + id_string; VAST_TRACEPOINT(passive_partition_spawned, id_string.c_str()); self->set_exit_handler([=](const caf::exit_msg& msg) {
codereview_cpp_data_4533
}, [=](telemetry_atom) { self->state.send_report(); - self->delayed_send( - self, - std::chrono::milliseconds(defs::telemetry_rate_ms), - telemetry_atom::value); } }; } Some vertical whitespace could be shaved off here as well. }, [=](telemetry_atom) { self->state.send_report(); + self->delayed_send(self, + std::chrono::milliseconds(defs::telemetry_rate_ms), + telemetry_atom::value); } }; }
codereview_cpp_data_4535
} std::string role = "role", permission = "permission"; - std::shared_ptr<shared_model::interface::Account> account; - std::shared_ptr<shared_model::interface::Domain> domain; std::unique_ptr<pqxx::lazyconnection> postgres_connection; std::unique_ptr<pqxx::nontransaction> wsv_transaction; I think unique_ptr would be enough } std::string role = "role", permission = "permission"; + std::unique_ptr<shared_model::interface::Account> account; + std::unique_ptr<shared_model::interface::Domain> domain; std::unique_ptr<pqxx::lazyconnection> postgres_connection; std::unique_ptr<pqxx::nontransaction> wsv_transaction;
codereview_cpp_data_4538
uint64_t>; using PermissionTuple = boost::tuple<int>; - auto &pagination_info = q.paginationMeta(); auto first_hash = pagination_info.firstTxHash(); // retrieve one extra transaction to populate next_hash auto query_size = pagination_info.pageSize() + 1u; If `paginationMeta()` returns constref, it should be `const auto &pagination_info` uint64_t>; using PermissionTuple = boost::tuple<int>; + const auto &pagination_info = q.paginationMeta(); auto first_hash = pagination_info.firstTxHash(); // retrieve one extra transaction to populate next_hash auto query_size = pagination_info.pageSize() + 1u;
codereview_cpp_data_4542
return UA_STATUSCODE_GOOD; } -static UA_Client_Subscription *findSubscription(UA_Client *client, UA_UInt32 subscriptionId) { UA_Client_Subscription *sub = NULL; LIST_FOREACH(sub, &client->subscriptions, listEntry) { Nice one! One small change request: Can you use const wherever possible, i.e., change this (if the compiler agrees) to `static UA_Client_Subscription *findSubscription(const UA_Client *client, const UA_UInt32 subscriptionId)` Thanks! return UA_STATUSCODE_GOOD; } +static UA_Client_Subscription *findSubscription(const UA_Client *client, UA_UInt32 subscriptionId) { UA_Client_Subscription *sub = NULL; LIST_FOREACH(sub, &client->subscriptions, listEntry) {
codereview_cpp_data_4560
// IN THE SOFTWARE. //----------------------------------------------------------------------------- - -#include "torqueConfig.h" - -#ifdef TORQUE_ENABLE_ASSET_FILE_CLIENT_REPLICATION - #include "netFileServer.h" #include "netFileUtils.h" #include "console/fileSystemFunctions.h" Curly braces are off by one intention, indention.., throughout this source file. // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "netFileServer.h" #include "netFileUtils.h" #include "console/fileSystemFunctions.h"
codereview_cpp_data_4569
void Player::actCreateRelatedCard() { - // get he target card name QAction *action = static_cast<QAction *>(sender()); CardInfo *cardInfo = db->getCard(action->text()); Instead of setting x and y by default, why not acquire where the card the transformation was called from (i.e. Get Delver of Secret's location) and place this new card right on top of it (giving it the same X/Y of Delver) void Player::actCreateRelatedCard() { + // get the clicked card + CardItem * sourceCard = game->getActiveCard(); + if(!sourceCard) + return; + + // get the target card name QAction *action = static_cast<QAction *>(sender()); CardInfo *cardInfo = db->getCard(action->text());
codereview_cpp_data_4583
namespace sofa::component::collision { -using namespace sofa::defaulttype; -using namespace sofa::core::collision; -using namespace helper; - int PointCollisionModelClass = core::RegisterObject("Collision model which represents a set of points") .add< PointCollisionModel<defaulttype::Vec3Types> >() Not sure those using namespace are necessary here namespace sofa::component::collision { int PointCollisionModelClass = core::RegisterObject("Collision model which represents a set of points") .add< PointCollisionModel<defaulttype::Vec3Types> >()
codereview_cpp_data_4590
repo_dir_config = g_file_get_child (repo_dir, "config"); if (!g_file_query_exists (repo_dir_config, NULL)) { -#if OSTREE_CHECK_VERSION(2017, 3) - OstreeRepoMode mode = OSTREE_REPO_MODE_BARE_USER_ONLY; -#else - OstreeRepoMode mode = OSTREE_REPO_MODE_BARE_USER; -#endif - if (!ostree_repo_create (new_repo, mode, NULL, error)) return NULL; } else I think this should use the same mode as the system one, because otherwise we can run into issue if the system repo is an (old) bare-user and we have a new libostree, then the child repo could lose some information making the pull into the system repo break. repo_dir_config = g_file_get_child (repo_dir, "config"); if (!g_file_query_exists (repo_dir_config, NULL)) { + OstreeRepoMode parent_mode = ostree_repo_get_mode (self->repo); + if (!ostree_repo_create (new_repo, parent_mode, NULL, error)) return NULL; } else
codereview_cpp_data_4595
const static iroha::protocol::GrantablePermission invalid_grantable_permission = static_cast<iroha::protocol::GrantablePermission>(-1); -iroha::protocol::Transaction generateEmptyTransaction() { - return iroha::protocol::Transaction(); -} - iroha::protocol::Transaction generateCreateRoleTransaction( iroha::protocol::RolePermission permission) { - auto tx = generateEmptyTransaction(); auto cr = tx.mutable_payload() ->mutable_reduced_payload() Why not just a constructor? ```suggestion auto tx = iroha::protocol::Transaction(); ``` or ```suggestion iroha::protocol::Transaction tx; ``` const static iroha::protocol::GrantablePermission invalid_grantable_permission = static_cast<iroha::protocol::GrantablePermission>(-1); iroha::protocol::Transaction generateCreateRoleTransaction( iroha::protocol::RolePermission permission) { + auto tx = iroha::protocol::Transaction(); auto cr = tx.mutable_payload() ->mutable_reduced_payload()
codereview_cpp_data_4596
const shared_model::interface::Block &block) const { YacHash result; auto hex_hash = block.hash().hex(); - result.vote_hashes_.proposal_hash = hex_hash; - result.vote_hashes_.block_hash = hex_hash; - result.vote_round_ = Round{block.height(), 1}; result.block_signature = clone(block.signatures().front()); return result; } Maybe fill vote round before hashes, since it is a key? It is also not required to specify `Round` type here, brackets should suffice. const shared_model::interface::Block &block) const { YacHash result; auto hex_hash = block.hash().hex(); + result.vote_round = {block.height(), 1}; + result.vote_hashes.proposal_hash = hex_hash; + result.vote_hashes.block_hash = hex_hash; result.block_signature = clone(block.signatures().front()); return result; }
codereview_cpp_data_4602
return success; } -std::vector<std::string> UDPv4Transport::GetBindingInterfacesList(const Locator_t& locator) { std::vector<std::string> vOutputInterfaces; - if (IsInterfaceWhiteListEmpty() || (!IPLocator::isAny(locator) && !IPLocator::isMulticast(locator))) { vOutputInterfaces.push_back("0.0.0.0"); } Remove ` || (!IPLocator::isAny(locator) && !IPLocator::isMulticast(locator))` return success; } +std::vector<std::string> UDPv4Transport::GetBindingInterfacesList(const Locator_t& /*locator*/) { std::vector<std::string> vOutputInterfaces; + if (IsInterfaceWhiteListEmpty()) { vOutputInterfaces.push_back("0.0.0.0"); }
codereview_cpp_data_4605
mi[i].mid = MID_SpiroCorner; mi[i].invoke = CVMenuPointType; i++; - mi[i].ti.text = (unichar_t *) _("Left Constraint ([)"); mi[i].ti.text_is_1byte = true; mi[i].ti.fg = COLOR_DEFAULT; mi[i].ti.bg = COLOR_DEFAULT; mi[i].mid = MID_SpiroLeft; mi[i].invoke = CVMenuPointType; i++; - mi[i].ti.text = (unichar_t *) _("Right Constraint (])"); mi[i].ti.text_is_1byte = true; mi[i].ti.fg = COLOR_DEFAULT; mi[i].ti.bg = COLOR_DEFAULT; What's the bracket about? (Not implying it's wrong.) mi[i].mid = MID_SpiroCorner; mi[i].invoke = CVMenuPointType; i++; + mi[i].ti.text = (unichar_t *) _("Left Constraint"); mi[i].ti.text_is_1byte = true; mi[i].ti.fg = COLOR_DEFAULT; mi[i].ti.bg = COLOR_DEFAULT; mi[i].mid = MID_SpiroLeft; mi[i].invoke = CVMenuPointType; i++; + mi[i].ti.text = (unichar_t *) _("Right Constraint"); mi[i].ti.text_is_1byte = true; mi[i].ti.fg = COLOR_DEFAULT; mi[i].ti.bg = COLOR_DEFAULT;
codereview_cpp_data_4606
caffe_set(top_count, Dtype(-1), top_mask); } else { mask = max_idx_->mutable_cpu_data(); - for (int i = 0; i < top_count; ++i) { - mask[i] = -1; - } } caffe_set(top_count, Dtype(-FLT_MAX), top_data); // The main loop @jeffdonahue why don't you use `caffe_set` again? Also I don't think you need to initialize `top_mask` since later you are going to copy `max_idx_` over it. caffe_set(top_count, Dtype(-1), top_mask); } else { mask = max_idx_->mutable_cpu_data(); + caffe_set(top_count, -1, mask); } caffe_set(top_count, Dtype(-FLT_MAX), top_data); // The main loop
codereview_cpp_data_4617
in_file.open(file_name.c_str(), std::ios::in); // Open file // If there is any problem in opening file if(!in_file.is_open()) { - std::cerr << "ERROR: Unable to open file: "<< file_name << std::endl; std::exit(EXIT_FAILURE); } std::vector <std::vector<std::valarray<double>>> X, Y; // To store X and Y ```suggestion std::cerr << __func__ << ": ERROR: Unable to open file: "<< file_name << std::endl; ``` this will also print which function printed that error message in_file.open(file_name.c_str(), std::ios::in); // Open file // If there is any problem in opening file if(!in_file.is_open()) { + std::cerr << "ERROR (" << __func__ << ") : "; + std::cerr << "Unable to open file: "<< file_name << std::endl; std::exit(EXIT_FAILURE); } std::vector <std::vector<std::valarray<double>>> X, Y; // To store X and Y
codereview_cpp_data_4632
++freeSlots; const uint32_t maxCount = saveLastTroop ? troopFrom.GetCount() - 1 : troopFrom.GetCount(); - uint32_t redistributeCount = isSameTroopType - 1 ? 1 : troopFrom.GetCount() / 2; // if splitting to the same troop type, use this bool to turn off fast split option at the beginning of the dialog bool useFastSplit = !isSameTroopType; The `isSameTroopType - 1` operation is done on boolean type which we should not allow. Could you please explain what was the original intention? ++freeSlots; const uint32_t maxCount = saveLastTroop ? troopFrom.GetCount() - 1 : troopFrom.GetCount(); + uint32_t redistributeCount = isSameTroopType ? 1 : troopFrom.GetCount() / 2; // if splitting to the same troop type, use this bool to turn off fast split option at the beginning of the dialog bool useFastSplit = !isSameTroopType;
codereview_cpp_data_4637
mst_processor_->onPreparedBatches().subscribe([this](auto &&batch) { log_->info("MST batch prepared"); this->publishEnoughSignaturesStatus(batch->transactions()); - log_->critical("BATCH {}", batch); if (not this->pcs_->propagate_batch(batch)) { log_->error("PCS was unable to serve the batch received from MST {}", batch->toString()); Same for removal here. mst_processor_->onPreparedBatches().subscribe([this](auto &&batch) { log_->info("MST batch prepared"); this->publishEnoughSignaturesStatus(batch->transactions()); if (not this->pcs_->propagate_batch(batch)) { log_->error("PCS was unable to serve the batch received from MST {}", batch->toString());
codereview_cpp_data_4651
#include <QDialogButtonBox> #include <QRadioButton> #include <QDebug> -#include <QFont> #include "carddatabase.h" #include "dlg_settings.h" #include "main.h" Is `QFont` necessary in this situation? #include <QDialogButtonBox> #include <QRadioButton> #include <QDebug> #include "carddatabase.h" #include "dlg_settings.h" #include "main.h"
codereview_cpp_data_4656
if ((initial_announcements_.count > 0) && (initial_announcements_.period <= c_TimeZero)) { // Force a small interval (1ms) between initial announcements initial_announcements_.period = { 0, 1000000 }; } If the user passes 0 or negative we setup 1ms, maybe we should warn about this. Note that as tinyxml2 works passing a negative count is actually passing a large positive one. if ((initial_announcements_.count > 0) && (initial_announcements_.period <= c_TimeZero)) { // Force a small interval (1ms) between initial announcements + logWarning(RTPS_PDP, "Initial announcement period is not strictly positive. Changing to 1ms."); initial_announcements_.period = { 0, 1000000 }; }
codereview_cpp_data_4667
SplineChar *sc; CharViewBase *cvs; FontViewBase *fvs; - int layers, any_quads = false; if ( sf->subfontcnt!=0 || l<=ly_fore || sf->multilayer ) return; - for ( layers=ly_fore, any_quads=0; layers<sf->layer_cnt; ++layers ) { if ( layers!=l && sf->layers[layers].order2 ) any_quads = true; // Check whether remaining layers have quadratics. } It seems like the for loop below already initializes that variable. It would probably good to clean up that redundant assignment then, also this could be changed to boolean. SplineChar *sc; CharViewBase *cvs; FontViewBase *fvs; + int layers, any_quads; if ( sf->subfontcnt!=0 || l<=ly_fore || sf->multilayer ) return; + for ( layers = ly_fore, any_quads = false; layers<sf->layer_cnt; ++layers ) { if ( layers!=l && sf->layers[layers].order2 ) any_quads = true; // Check whether remaining layers have quadratics. }
codereview_cpp_data_4686
*polymorphic_tx.operator->()); }); auto block = std::make_shared<shared_model::proto::Block>( - shared_model::proto::TemplateBlockBuilder< - (1 << shared_model::proto::TemplateBlockBuilder<>::total) - 1, - shared_model::validation::DefaultBlockValidator, - shared_model::proto::Block>() .height(proposal.height()) .prevHash(last_block.value()->hash()) .transactions(proto_txs) Why we set this parameter to total? Should be `0` instead *polymorphic_tx.operator->()); }); auto block = std::make_shared<shared_model::proto::Block>( + shared_model::proto::UnsignedBlockBuilder() .height(proposal.height()) .prevHash(last_block.value()->hash()) .transactions(proto_txs)
codereview_cpp_data_4694
for ( refs = cvtemp->b.sc->layers[ly_fore].refs; refs!=NULL; refs = refs->next ) CVDrawSplineSet(cvtemp,pixmap,refs->layers[0].splines,col,false,&clip); } if ( bv->active_tool==bvt_pointer ) { if ( bv->bc->selection==NULL ) { int xmin, xmax, ymin, ymax; Why is this now needed? Because cvtabs isn't initialised? Also if we do this, we're now missing a free somewhere for ( refs = cvtemp->b.sc->layers[ly_fore].refs; refs!=NULL; refs = refs->next ) CVDrawSplineSet(cvtemp,pixmap,refs->layers[0].splines,col,false,&clip); } + CharViewFree(cvtemp); if ( bv->active_tool==bvt_pointer ) { if ( bv->bc->selection==NULL ) { int xmin, xmax, ymin, ymax;
codereview_cpp_data_4700
void MainWindow::notifyUserAboutUpdate() { - QMessageBox::information(this, tr("Information"), tr("This server supports additional features that your client doesn't have.\nThis is most likely not a problem, but this message might mean there is a new version of Cockatrice available.\n\nTo update your client, go to Help -> Update Cockatrice.")); } void MainWindow::actOpenCustomFolder() Add in `This can also happen if the server is running a custom or pre-release version` void MainWindow::notifyUserAboutUpdate() { + QMessageBox::information(this, tr("Information"), tr("This server supports additional features that your client doesn't have.\nThis is most likely not a problem, but this message might mean there is a new version of Cockatrice available or this server is running a custom or pre-release version.\n\nTo update your client, go to Help -> Update Cockatrice.")); } void MainWindow::actOpenCustomFolder()
codereview_cpp_data_4703
{ QCString replBuf = replaceRef(buf,relPath,urlOnly,context); int indexS = replBuf.find("id=\""), indexE; - indexE=replBuf.find('"',indexS+4); - if (indexS>=0 && (indexE=buf.find('"',indexS))!=-1) { t << replBuf.left(indexS-1) << replBuf.right(replBuf.length() - indexE - 1); } This doesn't look right. `indexE` is already assigned, you probably meant `indexE>indexS`? { QCString replBuf = replaceRef(buf,relPath,urlOnly,context); int indexS = replBuf.find("id=\""), indexE; + if (indexS>=0 && (indexE=replBuf.find('"',indexS+4))!=-1) { t << replBuf.left(indexS-1) << replBuf.right(replBuf.length() - indexE - 1); }
codereview_cpp_data_4708
tmp.replace(F("{{title}}"), title); #if BUILD_IN_WEBHEADER - tmp.replace(F("{{build}}"), parseString(get_binary_filename(), 4, '_')); // Assuming binary filename is ESP_Easy_mega_<date>_... #endif // #if BUILD_IN_WEBHEADER tmpl += tmp; } I think this is tricky as it assumes the filename to be set. But someone building with ArduinoIDE will not have this set. Since you're relying on the date only, you can also output the build date, which is always set. `__BUILD_DATE__` or something like that. tmp.replace(F("{{title}}"), title); #if BUILD_IN_WEBHEADER + tmp.replace(F("{{build}}"), get_build_date()); #endif // #if BUILD_IN_WEBHEADER tmpl += tmp; }
codereview_cpp_data_4711
runMainLoop (args); - if (Option.verbose || Option.mtablePrintTotals) { for (unsigned int i = 0; i < countParsers(); i++) - printLanguageMultitableStatistics (i, stderr); } /* Clean up. */ I would like not to expose "stderr". Could you add following code to option.h: ``` #define BEGIN_VERBOSE_XCOND(COND,VFP) do { if (Option.verbose || (COND)) { \ FILE* VFP = stderr ``` So you can write as follows: `BEGIN_VERBOSE_XCOND(Option.mtablePrintTotals, vfp);` runMainLoop (args); + BEGIN_VERBOSE_IF(Option.mtablePrintTotals, vfp); { for (unsigned int i = 0; i < countParsers(); i++) + printLanguageMultitableStatistics (i, vfp); } + END_VERBOSE(); /* Clean up. */
codereview_cpp_data_4721
void SimManagerNameDictionary::remove(SimObject* obj) { - if(!obj->objectName) return; #ifndef USE_NEW_SIMDICTIONARY Better if we check obj ptr before use.. void SimManagerNameDictionary::remove(SimObject* obj) { + if(!obj || !obj->objectName) return; #ifndef USE_NEW_SIMDICTIONARY
codereview_cpp_data_4740
new->command_line = xxstrdup(task->command_line); } - if(task->user_resources) { - new->user_resources = list_create(0); char *req; - list_first_item(task->user_resources); - while((req = list_next_item(task->user_resources))) { - list_push_tail(new->user_resources, xxstrdup(req)); } } Using features, requirements and user_resources for the same thing. Choose one. new->command_line = xxstrdup(task->command_line); } + if(task->features) { + new->features = list_create(); char *req; + list_first_item(task->features); + while((req = list_next_item(task->features))) { + list_push_tail(new->features, xxstrdup(req)); } }
codereview_cpp_data_4743
const Bridge * bridge = Arena::GetBridge(); const bool isPassableBridge = bridge == nullptr || bridge->isPassable( unit ); - for ( iterator it = begin(); it != end(); ++it ) { - if ( ( *it ).isPassable3( unit, false ) && ( isPassableBridge || !Board::isBridgeIndex( it - begin(), unit ) ) ) { - ( *it ).SetDirection( CENTER ); } } } Please use here normal `size_t` based loop. The compiler will optimize this and `it - begin()` will be just `size_t` value. It also would be a bit more readable. However, I'm leaving it up to you to decide. const Bridge * bridge = Arena::GetBridge(); const bool isPassableBridge = bridge == nullptr || bridge->isPassable( unit ); + for ( std::size_t i = 0; i < size(); i++ ) { + if ( at( i ).isPassable3( unit, false ) && ( isPassableBridge || !Board::isBridgeIndex( i, unit ) ) ) { + at( i ).SetDirection( CENTER ); } } }
codereview_cpp_data_4752
if ( event->type==et_close ) { SD_DoCancel( sd ); } else if ( event->type==et_charup ) { - char* contents = GGadgetGetTitle8(GWidgetGetControl(sd->gw,CID_Script)); - sd->fv->script_unsaved = (bool)strlen(contents); - free(contents); } else if ( event->type==et_save ) { sd->fv->script_unsaved = false; } else if ( event->type==et_char ) { I can't take a closer look at the moment, but at a cursory glance this seems mighty inefficient. On every key press, you're reading the *full* contents of the script and performing at least one copy. You're then running over that again to find it's string length, *just* to see if it's unsaved or not. Why can't you just always set `script_unsaved` to true? Also are you sure this is the right event to listen off? if ( event->type==et_close ) { SD_DoCancel( sd ); } else if ( event->type==et_charup ) { + sd->fv->script_unsaved = !GTextFieldIsEmpty(GWidgetGetControl(sd->gw,CID_Script)); } else if ( event->type==et_save ) { sd->fv->script_unsaved = false; } else if ( event->type==et_char ) {
codereview_cpp_data_4775
char tmp[PFS_PATH_MAX]; path_split(pname->path,pname->service_name,tmp); pname->service = pfs_service_lookup(pname->service_name); - if (result == PFS_RESOLVE_LOCAL) pname->service = NULL; if(!pname->service) { pname->service = pfs_service_lookup_default(); strcpy(pname->service_name,"local"); Tim, please add { } to this 'if'. char tmp[PFS_PATH_MAX]; path_split(pname->path,pname->service_name,tmp); pname->service = pfs_service_lookup(pname->service_name); + if (result == PFS_RESOLVE_LOCAL) { + pname->service = NULL; + } if(!pname->service) { pname->service = pfs_service_lookup_default(); strcpy(pname->service_name,"local");
codereview_cpp_data_4783
total_resources->disk.largest = MAX(0, local_resources->disk.largest); total_resources->disk.smallest = MAX(0, local_resources->disk.smallest); - //if workers are set to expire at some time, send the amount of time left to manager - if(manual_wall_time_option != 0) { - total_resources->time_left = worker_start_time + manual_wall_time_option - time(0); } else { - total_resources->time_left = -1; } } If following above, this would be: end_time = time(0) + manual_wall_time_option, which is simpler. Also, make the check manual_wall_time_option > 0, otherwise negative times would terminate the worker right away. total_resources->disk.largest = MAX(0, local_resources->disk.largest); total_resources->disk.smallest = MAX(0, local_resources->disk.smallest); + //if workers are set to expire in some time, send the expiration time to manager + if(manual_wall_time_option > 0) { + end_time = worker_start_time + manual_wall_time_option; } else { + end_time = 0; } }
codereview_cpp_data_4795
campaignRoi.emplace_back( 30 + roiOffset.x, 59 + roiOffset.y, 224, 297 ); Video::ShowVideo( Settings::GetLastFile( System::ConcatePath( "heroes2", "anim" ), "INTRO.SMK" ), false ); - const size_t chosenCampaign = Video::ShowVideo( Settings::GetLastFile( System::ConcatePath( "heroes2", "anim" ), "CHOOSE.SMK" ), true, campaignRoi ); Video::ShowVideo( Settings::GetLastFile( System::ConcatePath( "heroes2", "anim" ), "CHOOSEW.SMK" ), false ); const bool goodCampaign = chosenCampaign == 0; AGG::PlayMusic( MUS::VICTORY ); Logically we output the video / audio after choosing the campaign. campaignRoi.emplace_back( 30 + roiOffset.x, 59 + roiOffset.y, 224, 297 ); Video::ShowVideo( Settings::GetLastFile( System::ConcatePath( "heroes2", "anim" ), "INTRO.SMK" ), false ); Video::ShowVideo( Settings::GetLastFile( System::ConcatePath( "heroes2", "anim" ), "CHOOSEW.SMK" ), false ); + const size_t chosenCampaign = Video::ShowVideo( Settings::GetLastFile( System::ConcatePath( "heroes2", "anim" ), "CHOOSE.SMK" ), true, campaignRoi ); const bool goodCampaign = chosenCampaign == 0; AGG::PlayMusic( MUS::VICTORY );
codereview_cpp_data_4798
pendingcs = NULL; csretrying = false; - reqs.servererror("-23", this); break; } } we can use std::to_string(API_ESSL) here, to avoid hard-coding magic constants and make it clear which error we are producing. Performance is not important for this case, if that was the concern. thanks pendingcs = NULL; csretrying = false; + reqs.servererror(std::to_string(API_ESSL), this); break; } }
codereview_cpp_data_4801
static struct work_queue_file *work_queue_file_clone(const struct work_queue_file *file) { const int file_t_size = sizeof(struct work_queue_file); - struct work_queue_file *new = calloc(1, file_t_size); memcpy(new, file, file_t_size); //allocate new memory for strings so we don't segfault when the original //memory is freed. - new->payload = strdup(file->payload); - new->remote_name = strdup(file->remote_name); return new; } xxmalloc is better. static struct work_queue_file *work_queue_file_clone(const struct work_queue_file *file) { const int file_t_size = sizeof(struct work_queue_file); + struct work_queue_file *new = xxmalloc(1, file_t_size); memcpy(new, file, file_t_size); //allocate new memory for strings so we don't segfault when the original //memory is freed. + new->payload = xxstrdup(file->payload); + new->remote_name = xxstrdup(file->remote_name); return new; }
codereview_cpp_data_4806
auto request = tpm.ReceiveRequest(); if (request && request->size() > 0) { - std::lock_guard lck(m_AggregatedMetadataMutex); tpm.SendReply(m_AggregatedMetadata); } } Looks like the template argument doesn't resolve by default so you need `std::lock_guard<std::mutex> lck` auto request = tpm.ReceiveRequest(); if (request && request->size() > 0) { + std::lock_guard<std::mutex> lck(m_AggregatedMetadataMutex); tpm.SendReply(m_AggregatedMetadata); } }
codereview_cpp_data_4809
handle = guid_; handle.value[15] = 0x01; // Vendor specific; handle.value[14] = static_cast<octet>(next_instance_id_ & 0xFF); - handle.value[13] = static_cast<octet>( (next_instance_id_ >> 8) & 0xFF); - handle.value[12] = static_cast<octet>((next_instance_id_ >> 8) & 0xFF);; } } // namespace dds ```suggestion handle.value[13] = static_cast<octet>((next_instance_id_ >> 8) & 0xFF); ``` handle = guid_; handle.value[15] = 0x01; // Vendor specific; handle.value[14] = static_cast<octet>(next_instance_id_ & 0xFF); + handle.value[13] = static_cast<octet>((next_instance_id_ >> 8) & 0xFF); + handle.value[12] = static_cast<octet>((next_instance_id_ >> 16) & 0xFF);; } } // namespace dds
codereview_cpp_data_4811
Key *sectionKey = ksLookup(handle->result, appendKey, KDB_O_NONE); if(sectionKey) { - if(!(keyGetMeta(sectionKey, "ini/index"))) { char buf[16]; snprintf(buf, sizeof(buf), "%ld", lastIndex); ++lastIndex; - keySetMeta(sectionKey, "ini/index", buf); } } } Please use `order` metadata and not `ini/index` or are there any differences? Key *sectionKey = ksLookup(handle->result, appendKey, KDB_O_NONE); if(sectionKey) { + if(!(keyGetMeta(sectionKey, "order"))) { char buf[16]; snprintf(buf, sizeof(buf), "%ld", lastIndex); ++lastIndex; + keySetMeta(sectionKey, "order", buf); } } }
codereview_cpp_data_4818
* and multiply it by -1. */ Vec3 massCenter = osimModel.getBodySet().get("r_ulna_radius_hand").getMassCenter(); - Vec3 velocity; osimModel.getMultibodySystem().realize(s, Stage::Velocity); const auto& hand = osimModel.getComponent<OpenSim::Body>("r_ulna_radius_hand"); - velocity = hand.findVelocityInGround(s, massCenter); f = -velocity[0]; stepCount++; Simply `Vec3 velocity = ...`? * and multiply it by -1. */ Vec3 massCenter = osimModel.getBodySet().get("r_ulna_radius_hand").getMassCenter(); osimModel.getMultibodySystem().realize(s, Stage::Velocity); const auto& hand = osimModel.getComponent<OpenSim::Body>("r_ulna_radius_hand"); + Vec3 velocity = hand.findVelocityInGround(s, massCenter); f = -velocity[0]; stepCount++;
codereview_cpp_data_4819
{ double spellValue = 0; std::vector<Spell> guildSpells = mageguild.GetSpells( GetLevelMageGuild(), isLibraryBuild() ); - for ( auto spell : guildSpells ) { if ( spell.isAdventure() ) { // AI is stupid to use Adventure spells. continue; Could you please use `const Spell & spell` as **auto** is harder to read and to avoid extra copy of data? { double spellValue = 0; std::vector<Spell> guildSpells = mageguild.GetSpells( GetLevelMageGuild(), isLibraryBuild() ); + for ( const Spell & spell : guildSpells ) { if ( spell.isAdventure() ) { // AI is stupid to use Adventure spells. continue;
codereview_cpp_data_4824
// this call can be recursive and remove multiple, eg with MegaFolderUploadController fireOnTransferFinish(transfer, preverror); } requestMap.clear(); transferMap.clear(); Instead of `transferMap.clear();` I'd do: `assert(transferMap.empty());` // this call can be recursive and remove multiple, eg with MegaFolderUploadController fireOnTransferFinish(transfer, preverror); } + assert(transferMap.empty()); requestMap.clear(); transferMap.clear();
codereview_cpp_data_4832
const SimTK::Real& muscleTendonVelocity, const SimTK::Real& activation, const bool& ignoreTendonCompliance, const bool& isTendonDynamicsExplicit, const MuscleLengthInfo& mli, - FiberVelocityInfo& fvi, const SimTK::Real& normTendonForce = SimTK::NaN, - const SimTK::Real& normTendonForceDerivative = SimTK::NaN) const { if (isTendonDynamicsExplicit && !ignoreTendonCompliance) { const auto& normFiberForce = normTendonForce / mli.cosPennationAngle; Neither a review, nor blocking, nor do you have to answer, but why is it that devs default to using `const T&` for primitive value types like `bool` or `SimTK::Real`? const SimTK::Real& muscleTendonVelocity, const SimTK::Real& activation, const bool& ignoreTendonCompliance, const bool& isTendonDynamicsExplicit, const MuscleLengthInfo& mli, + FiberVelocityInfo& fvi, const SimTK::Real& normTendonForce, + const SimTK::Real& normTendonForceDerivative) const { if (isTendonDynamicsExplicit && !ignoreTendonCompliance) { const auto& normFiberForce = normTendonForce / mli.cosPennationAngle;
codereview_cpp_data_4835
if (strcmp(my_style,"reax") == 0) { writemsg(lmp,"\nPair style 'reax' has been removed from LAMMPS " "after the 12 December 2018 version\n\n",1); if (strcmp(my_style,"DEPRECATED") == 0) { writemsg(lmp,"\nPair style 'DEPRECATED' is a dummy style\n\n",0); Missing closing curly bracket `}` if (strcmp(my_style,"reax") == 0) { writemsg(lmp,"\nPair style 'reax' has been removed from LAMMPS " "after the 12 December 2018 version\n\n",1); + } if (strcmp(my_style,"DEPRECATED") == 0) { writemsg(lmp,"\nPair style 'DEPRECATED' is a dummy style\n\n",0);
codereview_cpp_data_4840
delete [] pack_choice; delete [] vtype; - delete [] field2index; - delete [] argindex; delete [] idregion; memory->destroy(thresh_array); Needs to switch back to use memory class. delete [] pack_choice; delete [] vtype; + memory->destroy(field2index); + memory->destroy(argindex); delete [] idregion; memory->destroy(thresh_array);
codereview_cpp_data_4841
nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST) ? nMedianTimePast : pblock->GetBlockTime(); - std::vector<const CTxMemPoolEntry*> txs; - addPriorityTxs(&txs); - addScoreTxs(&txs); nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; need to be run though formatting... Also, txs could be changed maybe to vtxe...i think we've used txe to described CTxMempool entries before and which also differentiates them from simple transactions. Other than that it looks good to me... nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST) ? nMedianTimePast : pblock->GetBlockTime(); + std::vector<const CTxMemPoolEntry *> vtxe; + addPriorityTxs(&vtxe); + addScoreTxs(&vtxe); nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize;
codereview_cpp_data_4843
break; } - // consider the protected tile is an obstacle because the hero will not be able to step on it without a battle if ( Maps::TileIsUnderProtection( index ) ) { return true; } :warning: **readability\-simplify\-boolean\-expr** :warning: redundant boolean literal in conditional return statement ```suggestion return Maps::TileIsUnderProtection( index ) ``` break; } + // consider the protected tile as an obstacle because the hero will not be able to step on it without a battle if ( Maps::TileIsUnderProtection( index ) ) { return true; }
codereview_cpp_data_4850
if(itable_size(n->remote_names) > 0 || (wrapper && wrapper->uses_remote_rename)){ if(n->local_job) { - debug(D_ERROR, "remote renaming is not supported locally. Rule %d.\n", n->nodeid); error = 1; break; } else if (!batch_queue_supports_feature(remote_queue, "remote_rename")) { "not supported with -Tlocal or LOCAL execution." if(itable_size(n->remote_names) > 0 || (wrapper && wrapper->uses_remote_rename)){ if(n->local_job) { + debug(D_ERROR, "remote renaming is not supported with -Tlocal or LOCAL execution. Rule %d.\n", n->nodeid); error = 1; break; } else if (!batch_queue_supports_feature(remote_queue, "remote_rename")) {
codereview_cpp_data_4853
= { GameOver::WINS_ALL, GameOver::WINS_TOWN, GameOver::WINS_HERO, GameOver::WINS_ARTIFACT, GameOver::WINS_SIDE, GameOver::WINS_GOLD }; for ( const uint32_t cond : wins ) { - if ( ( conf.ConditionWins() & cond ) && KingdomIsWins( kingdom, cond ) ) { return cond; } } To avoid the future changes with issues I would suggest to use `( conf.ConditionWins() & cond ) == cond` because **conditions_t** contains combinations of other entries. = { GameOver::WINS_ALL, GameOver::WINS_TOWN, GameOver::WINS_HERO, GameOver::WINS_ARTIFACT, GameOver::WINS_SIDE, GameOver::WINS_GOLD }; for ( const uint32_t cond : wins ) { + if ( ( ( conf.ConditionWins() & cond ) == cond ) && KingdomIsWins( kingdom, cond ) ) { return cond; } }
codereview_cpp_data_4861
#define MAX_NEW_WORKERS 10 -// Seconds for how often the user can be notified about when a task cannot fit to any workers -// Used in check_task_fit_in_connected_workers() -#define THRESHOLD 60000000 - // Result codes for signaling the completion of operations in WQ typedef enum { WQ_SUCCESS = 0, let's make this one: ``` static timestamp_t interval_tasks_fit_check 180000000; //3 minutes in usecs ``` #define MAX_NEW_WORKERS 10 // Result codes for signaling the completion of operations in WQ typedef enum { WQ_SUCCESS = 0,
codereview_cpp_data_4879
auto& st = self->state; timespan runtime = steady_clock::now() - st.start; st.query.runtime = runtime; - VAST_INFO(self, "relayed", rank(hits), "hits in", vast::to_string(runtime)); self->send(st.sink, st.id, st.query); if (st.accountant) { auto hits = rank(st.hits); This may not be true, since the hits are a superset of the results. It is only true if the candidate check returns all hits as valid results. Both information might be helpful: the number of hits as well as the (subset of) relayed results. auto& st = self->state; timespan runtime = steady_clock::now() - st.start; st.query.runtime = runtime; + VAST_INFO(self, "shipped", st.query.shipped, "results out of", + st.query.processed, "candidates in", vast::to_string(runtime)); self->send(st.sink, st.id, st.query); if (st.accountant) { auto hits = rank(st.hits);
codereview_cpp_data_4893
.add<std::string>("directory,d", "directory for persistent state") .add<std::string>("endpoint,e", "node endpoint") .add<std::string>("node-id,i", "the unique ID of this node") .add<bool>("disable-accounting", "don't run the accountant") .add<bool>("no-default-schema", "don't load the default schema " "definitions")); The whole `-N` thing seems to be an orthogonal concern. I wonder if it can somehow be factored. @tobim, any ideas? .add<std::string>("directory,d", "directory for persistent state") .add<std::string>("endpoint,e", "node endpoint") .add<std::string>("node-id,i", "the unique ID of this node") + .add<bool>("node,N", "spawn a node instead of connecting to one") .add<bool>("disable-accounting", "don't run the accountant") .add<bool>("no-default-schema", "don't load the default schema " "definitions"));
codereview_cpp_data_4895
uint8_t session_id_from_client[MAX_KEY_LEN]; /* aes keys. Used for session ticket/session data encryption. Taken from test vectors in https://tools.ietf.org/html/rfc5869 */ - uint8_t ticket_key_name[16] = "2018.07.26.15\0"; uint8_t ticket_key[32] = {0x19, 0xef, 0x24, 0xa3, 0x2c, 0x71, 0x7b, 0x16, 0x7f, 0x33, 0xa9, 0x1d, 0x6f, 0x64, 0x8b, 0xdf, 0x96, 0x59, 0x67, 0x76, 0xaf, 0xdb, 0x63, 0x77, 0xac, 0x43, 0x4c, 0x1c, 0x29, 0x3c, you are only using this as a `char *` below, so retype it? also: ``` char ticket_key_name[] = "2018.07.26.10"; ``` uint8_t session_id_from_client[MAX_KEY_LEN]; /* aes keys. Used for session ticket/session data encryption. Taken from test vectors in https://tools.ietf.org/html/rfc5869 */ + char ticket_key_name[] = "2018.07.26.15\0"; uint8_t ticket_key[32] = {0x19, 0xef, 0x24, 0xa3, 0x2c, 0x71, 0x7b, 0x16, 0x7f, 0x33, 0xa9, 0x1d, 0x6f, 0x64, 0x8b, 0xdf, 0x96, 0x59, 0x67, 0x76, 0xaf, 0xdb, 0x63, 0x77, 0xac, 0x43, 0x4c, 0x1c, 0x29, 0x3c,
codereview_cpp_data_4912
template <typename TensorDataType> bool adam<TensorDataType>::save_to_checkpoint_shared(persist& p, std::string name_prefix) { if (this->get_comm().am_trainer_master()) { - write_cereal_archive<adam<TensorDataType>>(*this, p, "adam.xml"); } char l_name[512]; ```suggestion write_cereal_archive(*this, p, "adam.xml"); ``` template <typename TensorDataType> bool adam<TensorDataType>::save_to_checkpoint_shared(persist& p, std::string name_prefix) { if (this->get_comm().am_trainer_master()) { + write_cereal_archive(*this, p, "adam.xml"); } char l_name[512];
codereview_cpp_data_4929
} else if (error == ENOSYS) { - ELEKTRA_SET_ERRORF (145, parentKey, "Open semaphore: %s\n", "ENOSYS"); } } please also add here info that /dev/shm should be mounted } else if (error == ENOSYS) { + ELEKTRA_SET_ERRORF (145, parentKey, "Open semaphore: %s\n", "ENOSYS. /dev/shm should be mounted as tempfs. Look in the README!"); } }
codereview_cpp_data_4931
{ /** * Only uncompressed points are supported by the server and the client must include it in - * th e extension. Just skip the extension. */ return 0; } Slight typo here "th e" { /** * Only uncompressed points are supported by the server and the client must include it in + * the extension. Just skip the extension. */ return 0; }
codereview_cpp_data_4955
error =0; //constraints are treated 3x3 (friction contact) - for (it_c = contact_sequence.begin(); it_c != contact_sequence.end() ; ++(++(++it_c)) ) { int constraint = *it_c; c1 = constraint/3; wtf? ++(++(++ ? it_c += 3 ? error =0; //constraints are treated 3x3 (friction contact) + for (it_c = contact_sequence.begin(); it_c != contact_sequence.end() ; it_c += 3 ) { int constraint = *it_c; c1 = constraint/3;
codereview_cpp_data_4979
P->opaque = Q; P->destructor = destructor; - Q->rot = pj_param(P->ctx, P->params,"drot").f * M_PI / 180.0; if (P->es != 0.0) { Q->apa = pj_authset(P->es); /* For auth_lat(). */ Improve readability a bit: ```suggestion double angle = pj_param(P->ctx, P->params,"drot").f; Q->rot = PJ_TORAD(angle); ``` P->opaque = Q; P->destructor = destructor; + double angle = pj_param(P->ctx, P->params,"drot").f; + Q->rot = PJ_TORAD(angle); if (P->es != 0.0) { Q->apa = pj_authset(P->es); /* For auth_lat(). */
codereview_cpp_data_4985
std::shared_ptr<CountManualMatchesVisitor> manualMatchVisitor( new CountManualMatchesVisitor()); map1->visitRo(*manualMatchVisitor); - double numManualMatches1 = manualMatchVisitor->getStat(); manualMatchVisitor.reset(new CountManualMatchesVisitor()); map2->visitRo(*manualMatchVisitor); - double numManualMatches2 = manualMatchVisitor->getStat(); - LOG_VARD(numManualMatches1); LOG_VARD(numManualMatches2); Since matches are whole numbers and the `getStat()` function returns a `double` it needs to be cast to an integer. ``` const int numManualMatches1 = std::static_cast<int>(manualMatchVisitor->getStat()); ``` std::shared_ptr<CountManualMatchesVisitor> manualMatchVisitor( new CountManualMatchesVisitor()); map1->visitRo(*manualMatchVisitor); + const int numManualMatches1 = std::static_cast<int>(manualMatchVisitor->getStat()); manualMatchVisitor.reset(new CountManualMatchesVisitor()); map2->visitRo(*manualMatchVisitor); + const int numManualMatches2 = std::static_cast<int>(manualMatchVisitor->getStat()); LOG_VARD(numManualMatches1); LOG_VARD(numManualMatches2);
codereview_cpp_data_4990
break; } - if( k != instance->list[i].num_map ) /* any (or all) of them were disabled, we destroy */ { instance->destroy(i); } else { /* populate the instance again */ should be ``if (k != instance->list[i].num_map) /* any (or all) of them were disabled, we destroy */ {`` break; } + if (k != instance->list[i].num_map) /* any (or all) of them were disabled, we destroy */ { instance->destroy(i); } else { /* populate the instance again */
codereview_cpp_data_4992
" Disable automatic spelling correction of initialisms (e.g. \"URL\")\n" \ " read_write_private\n" " Make read/write methods private, default is public Read/Write\n" \ - " use_context\n" - " Make service method receive a context as first argument, only go1.7+ is supported.\n") Can we support `x/net/context` for go<1.7? " Disable automatic spelling correction of initialisms (e.g. \"URL\")\n" \ " read_write_private\n" " Make read/write methods private, default is public Read/Write\n" \ + " legacy_context\n" + " Use lagacy x/net/context instead of context in go<1.7.\n")
codereview_cpp_data_5004
void ScalarActuator::constructOutputs() { - constructOutput<double>("Actuation", &ScalarActuator::getActuation, SimTK::Stage::Velocity); constructOutput<double>("speed", &ScalarActuator::getSpeed, SimTK::Stage::Velocity); } // Create the underlying computational system component(s) that support the -// Actuator model component void ScalarActuator::addToSystem(SimTK::MultibodySystem& system) const { Super::addToSystem(system); @sohapouya Did you change the code wherever these 3 (option, cache, discrete) were used elsewhere in the code? void ScalarActuator::constructOutputs() { + constructOutput<double>("actuation", &ScalarActuator::getActuation, SimTK::Stage::Velocity); constructOutput<double>("speed", &ScalarActuator::getSpeed, SimTK::Stage::Velocity); } // Create the underlying computational system component(s) that support the +// ScalarActuator model component void ScalarActuator::addToSystem(SimTK::MultibodySystem& system) const { Super::addToSystem(system);
codereview_cpp_data_5019
} if ( !_recognizePUA && i>=0xe000 && i<=0xf8ff ) i = -1; -g_assert( i >= -1 ); return( i ); } don't do this, `#import <assert.h>` instead } if ( !_recognizePUA && i>=0xe000 && i<=0xf8ff ) i = -1; + assert( i >= -1 ); return( i ); }
codereview_cpp_data_5022
} } while (handled); - if (conn->_write_buf.cnt > 0) { /* write */ h2o_socket_write(conn->sock, conn->_write_buf.bufs, conn->_write_buf.cnt, on_write_complete); - conn->_write_buf.cnt = 0; } if (wslay_event_want_read(conn->ws_ctx)) { You cannot write to a socket that has a pending-write. In the loop above, there is a check for that, but nothing here. I would suggest instead to move the code that writes the pending write to the beginning of `on_write_complete`. Please also make sure that the buffers are not freed until `on_write_complete` is called. } } while (handled); + if (!h2o_socket_is_writing(conn->sock) && conn->_write_buf.cnt > 0) { /* write */ h2o_socket_write(conn->sock, conn->_write_buf.bufs, conn->_write_buf.cnt, on_write_complete); } if (wslay_event_want_read(conn->ws_ctx)) {
codereview_cpp_data_5026
// Optional object to provide the base transform MatrixF offset(true); - if (baseObject != "") { SceneObject *obj; if (Sim::findObject(baseObject, obj)) offset = obj->getTransform(); Ditto `if (dStrcmp(baseObject, "") != 0)` // Optional object to provide the base transform MatrixF offset(true); + if (dStrcmp(baseObject, "") != 0){ SceneObject *obj; if (Sim::findObject(baseObject, obj)) offset = obj->getTransform();
codereview_cpp_data_5027
// FIX: "type" is already used to define the type of object to instanciate, any Data with // the same name cannot be extracted from BaseObjectDescription - if (attrName == std::string("type")) continue; - - if (attrName == std::string("name") && std::string(it.second.c_str()).empty()) - { - msg_warning(getName()) << "Empty name given: Renaming to \"unnamed\"" - " as this can lead to unexpected behaviors."; - parseField(attrName, "unnamed"); continue; - } if (!hasField(attrName)) continue; parseField(attrName, it.second); I thought there was already a mechanism for that with an increment? For example if I take a scene like ChainAll, every component has a value for name. // FIX: "type" is already used to define the type of object to instanciate, any Data with // the same name cannot be extracted from BaseObjectDescription + if (attrName == std::string("type")) continue; if (!hasField(attrName)) continue; parseField(attrName, it.second);
codereview_cpp_data_5033
# common profile for archiver/compression tools blacklist ${RUNUSER}/wayland-* include disable-common.inc include disable-devel.inc I think we can `blacklist ${RUNUSER}`. # common profile for archiver/compression tools blacklist ${RUNUSER}/wayland-* +blacklist ${RUNUSER} include disable-common.inc include disable-devel.inc
codereview_cpp_data_5036
} int main() { - unsetenv("HIP_VISIBLE_DEVICES"); - std::vector<std::string> devPCINum; char pciBusID[100]; // collect the device pci bus ID for all devices same changes as in hipEnvVar.cpp } int main() { + unsetenv(HIP_VISIBLE_DEVICES_STR); + unsetenv(CUDA_VISIBLE_DEVICES_STR); std::vector<std::string> devPCINum; char pciBusID[100]; // collect the device pci bus ID for all devices
codereview_cpp_data_5052
#if !defined(LIBRESSL_VERSION_NUMBER) /* assert that openssl library and header versions are the same */ - assert(OpenSSL_version_num() == OPENSSL_VERSION_NUMBER); #endif const char *cmd = argv[0], *opt_config_file = H2O_TO_STR(H2O_CONFIG_PATH); ```suggestion assert(SSLeay() == OPENSSL_VERSION_NUMBER); ``` Looks like OpenSSL 1.0.2g does not provide `OpenSSL_version_num()`. It was called `SSLeay()` and is still available as a macro. #if !defined(LIBRESSL_VERSION_NUMBER) /* assert that openssl library and header versions are the same */ + assert(SSLeay() == OPENSSL_VERSION_NUMBER); #endif const char *cmd = argv[0], *opt_config_file = H2O_TO_STR(H2O_CONFIG_PATH);
codereview_cpp_data_5053
#include "hip_hcc_internal.h" #include "trace_helper.h" -//TODO Add support for multiple modules -static std::unordered_map<std::string, uintptr_t> coGlobals; //TODO Use Pool APIs from HCC to get memory regions. #include <cassert> I know this is not new here but we need to remove this global or protect access from multiple threads. #include "hip_hcc_internal.h" #include "trace_helper.h" //TODO Use Pool APIs from HCC to get memory regions. #include <cassert>
codereview_cpp_data_5056
* This will properly maintain the copyright information. DigitalGlobe * copyrights will be updated automatically. * - * @copyright Copyright (C) 2015, 2016, 2017, 2018, 2019 DigitalGlobe (http://www.digitalglobe.com/) */ #include "HighwayTagOnlyMerger.h" Again, new file, 2019 copyright only. * This will properly maintain the copyright information. DigitalGlobe * copyrights will be updated automatically. * + * @copyright Copyright (C) 2019 DigitalGlobe (http://www.digitalglobe.com/) */ #include "HighwayTagOnlyMerger.h"
codereview_cpp_data_5075
if (!dev::stringCmpIgnoreCase(m_param->mutableStorageParam().type, "External")) { - initAMOPStorage(); } else if (!dev::stringCmpIgnoreCase(m_param->mutableStorageParam().type, "LevelDB")) { AMOP or AMDB ? if (!dev::stringCmpIgnoreCase(m_param->mutableStorageParam().type, "External")) { + initSQLStorage(); } else if (!dev::stringCmpIgnoreCase(m_param->mutableStorageParam().type, "LevelDB")) {