id
stringlengths
21
25
content
stringlengths
164
2.33k
codereview_cpp_data_10086
_model->updForceSet() = _originalForceSet; // ExternalLoads were added as miscellaneous ModelComponents - int exfIx = _model->getMiscModelComponentSet().getIndex("externalloads"); - if (exfIx >= 0) { - _model->updMiscModelComponentSet().remove(exfIx); } // CMC was added as a model controller, now remove before printing out Couldn't the user have added their own ExternalLoads called `"externalloads"`? _model->updForceSet() = _originalForceSet; // ExternalLoads were added as miscellaneous ModelComponents + cout << _model->updMiscModelComponentSet() << endl; + if (hasExternalLoads()) { + _model->updMiscModelComponentSet().remove(_externalLoads.release()); } // CMC was added as a model controller, now remove before printing out
codereview_cpp_data_10093
case WIZARDS_ISLE_CAMPAIGN: return getWizardsIsleCampaignAwardData( scenarioID ); // no campaign award for voyage home! } return std::vector<Campaign::CampaignAwardData>(); Could we please still add the case for this campaign but with just break inside? In the future we're goi to add more stricter compilation rules which will require all members of an enumeration be present in the switch-case. case WIZARDS_ISLE_CAMPAIGN: return getWizardsIsleCampaignAwardData( scenarioID ); // no campaign award for voyage home! + case VOYAGE_HOME_CAMPAIGN: + break; } return std::vector<Campaign::CampaignAwardData>();
codereview_cpp_data_10104
else if (setstoragestatus(isPaywall ? STORAGE_PAYWALL : STORAGE_RED)) { LOG_warn << "Storage overquota"; - int end = (isPaywall) ? PUT : GET; // in Paywall state, none DLs/UPs can progress - for (int d = GET; d <= end; d += PUT - GET) { for (transfer_map::iterator it = transfers[d].begin(); it != transfers[d].end(); it++) { the old loop (back in 5e3d86d before the first EPAYWALL commit) was only for PUT, but this one starts at GET (0), but should probably still start at PUT (1) for non-EPAYWALL? else if (setstoragestatus(isPaywall ? STORAGE_PAYWALL : STORAGE_RED)) { LOG_warn << "Storage overquota"; + int start = (isPaywall) ? GET : PUT; // in Paywall state, none DLs/UPs can progress + for (int d = start; d <= PUT; d += PUT - GET) { for (transfer_map::iterator it = transfers[d].begin(); it != transfers[d].end(); it++) {
codereview_cpp_data_10113
_Wcoarse.clear(); - dmsg_error_when( (sizeCoarseSystem==0) ) <<"no constraint" ; _Wcoarse.resize(sizeCoarseSystem,sizeCoarseSystem); for (unsigned int i=0; i<constraintCorrections.size(); i++) What is the warning needing this? Maybe it could be done directly in the macro to preserve a good looking syntax for the user :-) _Wcoarse.clear(); + dmsg_error_when(sizeCoarseSystem==0) <<"no constraint" ; _Wcoarse.resize(sizeCoarseSystem,sizeCoarseSystem); for (unsigned int i=0; i<constraintCorrections.size(); i++)
codereview_cpp_data_10145
auto omp_threads = omp_get_max_threads(); auto processes_on_node = comm->get_procs_per_node(); - auto io_threads_per_process = std::max(1, static_cast<int>((max_threads / processes_on_node) - omp_threads)); return io_threads_per_process; } Note that this excludes any threads our communication libraries (Aluminum, MPI, NCCL, ...) or the like may launch. auto omp_threads = omp_get_max_threads(); auto processes_on_node = comm->get_procs_per_node(); + auto aluminum_threads = 0; +#ifdef LBANN_HAS_ALUMINUM + aluminum_threads = 1; +#endif // LBANN_HAS_ALUMINUM + + auto io_threads_per_process = std::max(1, static_cast<int>((max_threads / processes_on_node) - omp_threads - aluminum_threads)); return io_threads_per_process; }
codereview_cpp_data_10146
void ExportSceneObj(const char*,IOSystem*, const aiScene*, const ExportProperties*); void ExportSceneObjNoMtl(const char*,IOSystem*, const aiScene*, const ExportProperties*); #endif -#ifdef ASSIMP_BUILD_NO_STL_EXPORTER void ExportSceneSTL(const char*,IOSystem*, const aiScene*, const ExportProperties*); void ExportSceneSTLBinary(const char*,IOSystem*, const aiScene*, const ExportProperties*); #endif This one is wrong, you accidentally typed `#ifdef` void ExportSceneObj(const char*,IOSystem*, const aiScene*, const ExportProperties*); void ExportSceneObjNoMtl(const char*,IOSystem*, const aiScene*, const ExportProperties*); #endif +#ifndef ASSIMP_BUILD_NO_STL_EXPORTER void ExportSceneSTL(const char*,IOSystem*, const aiScene*, const ExportProperties*); void ExportSceneSTLBinary(const char*,IOSystem*, const aiScene*, const ExportProperties*); #endif
codereview_cpp_data_10167
auto *card = static_cast<CardItem *>(item); QString pt = card->getPT(); int sep = pt.indexOf('/'); - int pow = pt.left(sep).toInt(); // if not found this will be set to 0 int tou = pt.mid(sep + 1).toInt(); QString newpt = QString::number(pow + deltaP) + "/" + QString::number(tou + deltaT); auto *cmd = new Command_SetCardAttr; If `pt` doesn't contain a `/`, indexOf will return -1. `pt.left(-1)` will return the full content of `pt`; if it's empty or not numeric, `pow` will be set to zero, otherway to the numeric value of `pt`. While the situation where a pt doesn't contain a `/` is already strange, we should probably check if `sep == -1` and force a sane default (0/0 maybe?) auto *card = static_cast<CardItem *>(item); QString pt = card->getPT(); int sep = pt.indexOf('/'); + int pow = pt.left(sep).toInt(); // if not found both are set to full tring int tou = pt.mid(sep + 1).toInt(); QString newpt = QString::number(pow + deltaP) + "/" + QString::number(tou + deltaT); auto *cmd = new Command_SetCardAttr;
codereview_cpp_data_10169
_pathfinder.reEvaluateIfNeeded( *bestHero ); bestHero->GetPath().setPath( _pathfinder.buildPath( bestTargetIndex ), bestTargetIndex ); - const int32_t idxToErase = bestHero->GetPath().GetDestinationIndex(); const size_t heroesBefore = heroes.size(); :warning: **clang\-diagnostic\-unused\-variable** :warning: unused variable `` idxToErase `` _pathfinder.reEvaluateIfNeeded( *bestHero ); bestHero->GetPath().setPath( _pathfinder.buildPath( bestTargetIndex ), bestTargetIndex ); const size_t heroesBefore = heroes.size();
codereview_cpp_data_10171
strategy_(std::move(strategy)), time_provider_(std::move(time_provider)), propagation_subscriber_(strategy_->emitter().subscribe( - [this](auto data) { this->onPropagate(data); }, [] {})) { log_ = logger::log("FairMstProcessor"); } The last lambda looks not obvious. Maybe better to write a doc about it? strategy_(std::move(strategy)), time_provider_(std::move(time_provider)), propagation_subscriber_(strategy_->emitter().subscribe( + [this](auto data) { this->onPropagate(data); })) { log_ = logger::log("FairMstProcessor"); }
codereview_cpp_data_10177
pthread_mutex_lock(&pool->_shared.mutex); destroy_expired(pool); - /* TODO is this needed in this critical section? */ if (is_global_pool(pool)) { target = lookup_target(pool, url); if (target == SIZE_MAX) { No. I think that you should move the call to `lookup_target` outside of the critical section. pthread_mutex_lock(&pool->_shared.mutex); destroy_expired(pool); + /* TODO lookup outside this critical section */ if (is_global_pool(pool)) { target = lookup_target(pool, url); if (target == SIZE_MAX) {
codereview_cpp_data_10183
desktop->server = server; desktop->config = config; - desktop->xcursor_theme = roots_xcursor_theme_create("default"); - if (desktop->xcursor_theme == NULL) { wlr_list_free(desktop->views); free(desktop); return NULL; Does it make sense for this to be fatal? Could there be an embedded application that does not have xcursor themes at all? For instance, compositors without a pointer (like a touch-screen kiosk) will never show a cursor. I think I'm ok with this assumption since it simplifies the code and rootston is assumed to have desktop features, but we should always make sure xcursor is not required to be used in the library. desktop->server = server; desktop->config = config; + desktop->xcursor_manager = wlr_xcursor_manager_create(NULL, + ROOTS_XCURSOR_SIZE); + if (desktop->xcursor_manager == NULL) { + wlr_log(L_ERROR, "Cannot create XCursor manager"); wlr_list_free(desktop->views); free(desktop); return NULL;
codereview_cpp_data_10187
[](iroha::expected::Error<std::string> &error) { FAIL() << "MutableStorage: " << error.error; }); - auto bl = shared_model::proto::from_old(block1); - ms->apply(bl, [](const auto &blk, auto &query, const auto &top_hash) { return true; }); storage->commit(std::move(ms)); I think old block should be renamed to `old_block...` and new one to `block` instead of 'bl' [](iroha::expected::Error<std::string> &error) { FAIL() << "MutableStorage: " << error.error; }); + auto old_block = shared_model::proto::from_old(block1); + ms->apply(old_block, [](const auto &blk, auto &query, const auto &top_hash) { return true; }); storage->commit(std::move(ms));
codereview_cpp_data_10198
auto status = active_segment_->WriteFooterAndClose(footer_builder_); if (status.ok() && metrics_) { - metrics_->wal_size->IncrementBy(active_segment_->written_offset()); } return status; } Lets use the Size() function. auto status = active_segment_->WriteFooterAndClose(footer_builder_); if (status.ok() && metrics_) { + metrics_->wal_size->IncrementBy(active_segment_->Size()); } return status; }
codereview_cpp_data_10208
caf::put(tr_status, "types", keys); // The list of defined concepts auto& concepts_status = put_dictionary(tr_status, "concepts"); - for (auto& concept_ : taxonomies.concepts.data) { - auto& concept_status = put_dictionary(concepts_status, concept_.first); - concept_status["fields"] = concept_.second.fields; - concept_status["concepts"] = concept_.second.concepts; } // The usual per-component status. detail::fill_status_map(tr_status, self); ```suggestion for (auto& [x, y] : taxonomies.concepts.data) { ``` Please do this with appropriate variable names. Kind of hard to figure out what first and second are below. caf::put(tr_status, "types", keys); // The list of defined concepts auto& concepts_status = put_dictionary(tr_status, "concepts"); + for (auto& [name, definition] : taxonomies.concepts.data) { + auto& concept_status = put_dictionary(concepts_status, name); + concept_status["fields"] = definition.fields; + concept_status["concepts"] = definition.concepts; } // The usual per-component status. detail::fill_status_map(tr_status, self);
codereview_cpp_data_10222
return 0; } -std::function<bool (Node*, Node*)> MegaApiImpl::getComparatorFunction(int order, MegaClient* mc) { switch(order) { Can we handle all enum values here so that we get a compiler warning if a new enum value wasn't handled? A `assert(false)` at the end would also be good. return 0; } +std::function<bool (Node*, Node*)> MegaApiImpl::getComparatorFunction(int order, MegaClient& mc) { switch(order) {
codereview_cpp_data_10234
if (IsTileType(tile, MP_STATION) || IsTileType(tile, MP_INDUSTRY)) { const Station *st = nullptr; - if (IsTileType(tile, MP_STATION)){ st = Station::GetByTile(tile); } else { const Industry *in = Industry::GetByTile(tile); missing space ```suggestion if (IsTileType(tile, MP_STATION)) { ``` if (IsTileType(tile, MP_STATION) || IsTileType(tile, MP_INDUSTRY)) { const Station *st = nullptr; + if (IsTileType(tile, MP_STATION)) { st = Station::GetByTile(tile); } else { const Industry *in = Industry::GetByTile(tile);
codereview_cpp_data_10237
namespace { // kernel for initializing GWS -// nwm1 is the total number of wavefronts minus 1 and rid is the GWS resource id __global__ void init_gws(uint nwm1, uint rid) { __ockl_gws_init(nwm1, rid); } This barrier should be initialized with the number of work groups minus 1 since that is what the sync is expecting. namespace { // kernel for initializing GWS +// nwm1 is the total number of workgroups minus 1 and rid is the GWS resource id __global__ void init_gws(uint nwm1, uint rid) { __ockl_gws_init(nwm1, rid); }
codereview_cpp_data_10248
//@HEADER */ -#include <Kokkos_Macros.hpp> -#ifdef KOKKOS_ENABLE_SYCL - #include <cstdint> #include <iostream> #include <iomanip> You shouldn't need that header guard //@HEADER */ #include <cstdint> #include <iostream> #include <iomanip>
codereview_cpp_data_10252
-#include <wlr/util/signal.h> static void handle_noop(struct wl_listener *listener, void *data) { // Do nothing Do you think this should be an internal header? +#include "util/signal.h" static void handle_noop(struct wl_listener *listener, void *data) { // Do nothing
codereview_cpp_data_10266
highQualityURLLabel.setText(tr("Custom Card Download URL:")); highQualityURLLinkLabel.setText(QString("<a href='%1'>%2</a>").arg(LINKING_FAQ_URL).arg(tr("Linking FAQ"))); clearDownloadedPicsButton.setText(tr("Reset/Clear Downloaded Pictures")); - updateNotificationCheckBox.setText(tr("Notify when new client features are available")); } void GeneralSettingsPage::setEnabledStatus(bool status) This is a bit misleading I think. The client won't inform you in general about a new update. He will just inform you if you connect to a server running a newer "version" (or just if there are new features? no important bugfixes included?) brainstorming: `Allow a server you connect to, to inform you that he runs a newer version than your client` `Enable notifications about a server supporting more/new features (new version/update available)` ... highQualityURLLabel.setText(tr("Custom Card Download URL:")); highQualityURLLinkLabel.setText(QString("<a href='%1'>%2</a>").arg(LINKING_FAQ_URL).arg(tr("Linking FAQ"))); clearDownloadedPicsButton.setText(tr("Reset/Clear Downloaded Pictures")); } void GeneralSettingsPage::setEnabledStatus(bool status)
codereview_cpp_data_10269
CHECK_EQUAL(*f, '5'); CHECK_EQUAL(x, 1234); MESSAGE("partial match with non-digits character"); - str = "6789x"sv; f = str.begin(); l = str.end(); CHECK(p.parse(f, l, x)); REQUIRE(f + 1 == l); CHECK_EQUAL(*f, 'x'); - CHECK_EQUAL(x, 6789); } TEST(real) { I think this test should cover the case of an integral with less than `MaxDigits` digits. So `"678x"sv` would make more sense to me. CHECK_EQUAL(*f, '5'); CHECK_EQUAL(x, 1234); MESSAGE("partial match with non-digits character"); + str = "678x"sv; f = str.begin(); l = str.end(); CHECK(p.parse(f, l, x)); REQUIRE(f + 1 == l); CHECK_EQUAL(*f, 'x'); + CHECK_EQUAL(x, 678); } TEST(real) {
codereview_cpp_data_10270
return TRUE; if ( a1 && gbMaxPlayers > 1 ) - MI_Dummy(save_num); // some eliminated function... return FALSE; } This is `mpqapi_update_multi_creation_time` from the debug release. return TRUE; if ( a1 && gbMaxPlayers > 1 ) + mpqapi_update_multi_creation_time(save_num); return FALSE; }
codereview_cpp_data_10272
if (strstr(update->integrate_style,"respa")) nlevels_respa = ((Respa *) update->integrate)->nlevels; - if (strstr(update->integrate_style,"respa") && gjfflag) error->all(FLERR,"Fix langevin gjf and respa are not compatible"); if (gjfflag) gjfa = (1.0-update->dt/2.0/t_period)/(1.0+update->dt/2.0/t_period); using `strstr()` can lead to false positives. it is safer to use `utils::strmatch(modify->fix[i]->style,"^respa")` here (and in similar cases). if (strstr(update->integrate_style,"respa")) nlevels_respa = ((Respa *) update->integrate)->nlevels; + if (utils::strmatch(update->integrate_style,"^respa") && gjfflag) error->all(FLERR,"Fix langevin gjf and respa are not compatible"); if (gjfflag) gjfa = (1.0-update->dt/2.0/t_period)/(1.0+update->dt/2.0/t_period);
codereview_cpp_data_10294
// Catch termination signals only once to allow forced termination by the OS // upon sending the signal a second time. if (sig == SIGINT || sig == SIGTERM) { - std::cerr << "\rInitiating shutdown... (repeat request to terminate)\n"; std::signal(sig, SIG_DFL); } signals[0] = true; I can't remember that we use upper-case for log output. // Catch termination signals only once to allow forced termination by the OS // upon sending the signal a second time. if (sig == SIGINT || sig == SIGTERM) { + std::cerr << "\rinitiating graceful shutdown... (repeat request to " + "terminate immediately)\n"; std::signal(sig, SIG_DFL); } signals[0] = true;
codereview_cpp_data_10299
static inline structs::ItemSlotStruct TitaniumToRoFSlot(uint32 TitaniumSlot) { structs::ItemSlotStruct RoFSlot; - RoFSlot.SlotType = 0xff; RoFSlot.Unknown02 = 0; - RoFSlot.MainSlot = 0xff; - RoFSlot.SubSlot = 0xff; - RoFSlot.AugSlot = 0xff; RoFSlot.Unknown01 = 0; uint32 TempSlot = 0; These changes 0xffff to 0xff likely have side effects relating to the slot conversion. You can use -1 instead if 0xffff is causing a warning. static inline structs::ItemSlotStruct TitaniumToRoFSlot(uint32 TitaniumSlot) { structs::ItemSlotStruct RoFSlot; + RoFSlot.SlotType = (int16)0xFFFF; RoFSlot.Unknown02 = 0; + RoFSlot.MainSlot = (int16)0xFFFF; + RoFSlot.SubSlot = (int16)0xFFFF; + RoFSlot.AugSlot = (int16)0xFFFF; RoFSlot.Unknown01 = 0; uint32 TempSlot = 0;
codereview_cpp_data_10300
if (rootNode && !rootNode->isEmpty()) { ol.startParagraph(); ol.disableAllBut(OutputGenerator::Man); ol.writeString(" - "); - ol.enableAll(); ol.writeDoc(rootNode,this,0); ol.pushGeneratorState(); ol.disable(OutputGenerator::RTF); This is not correct. You need to use ol.pushGeneratorState() and ol.popGeneratorState() to avoid that some output format that was already disabled, gets enabled. if (rootNode && !rootNode->isEmpty()) { ol.startParagraph(); + ol.pushGeneratorState(); ol.disableAllBut(OutputGenerator::Man); ol.writeString(" - "); + ol.popGeneratorState(); ol.writeDoc(rootNode,this,0); ol.pushGeneratorState(); ol.disable(OutputGenerator::RTF);
codereview_cpp_data_10310
break; } - - case WID_CL_CLIENT_NUMBER: { - /* Number of clients */ - int text_y_offset = std::max(0, ((int)this->line_height - (int)FONT_HEIGHT_NORMAL) / 2); - SetDParam(0, NetworkClientInfo::GetNumItems()); - SetDParam(1, Company::GetNumItems()); - DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_LEFT, r.top + text_y_offset, STR_NETWORK_CLIENT_LIST_CLIENT_NUMBER, TC_SILVER, SA_RIGHT); - - break; - } } } `this->line_height` is set to the maximum of some height and `FONT_HEIGHT_NORMAL`, so that value will always be a positive number. So no need for `int` or `std::max` here. Having said that, take a look at `SetDataTip` and how it's used with `NWidget(WWT_TEXTBTN, ...`. I think by adding a `SetDataTip(STR_NETWORK_CLIENT_LIST_CLIENT_NUMBER, <some to be defined string for the tooltip>)` to line 1634, and putting the `SetDParam` lines below in case of `SetStringParameters` around line 2040, you do not need all this custom calculation and drawing. break; } } }
codereview_cpp_data_10318
log_->warn("Could not fetch last block: " + e->error); return; } - block_query_opt = boost::none; last_block = boost::get< Use braces instead (aka `{` & `}`) for dealing with lifetimes, it's easier to understand stuff like that log_->warn("Could not fetch last block: " + e->error); return; } last_block = boost::get<
codereview_cpp_data_10324
} request = requestMap.at(client->restag); if (!request || ((request->getType() != MegaRequest::TYPE_FETCH_NODES) && - (request->getType() != MegaRequest::TYPE_CREATE_ACCOUNT)) ) { return; } when TYPE_FETCH_NODES we are using megaError instead of e (which is a copy). this is rather aesthetically inconsistent } request = requestMap.at(client->restag); if (!request || ((request->getType() != MegaRequest::TYPE_FETCH_NODES) && + (request->getType() != MegaRequest::TYPE_CREATE_ACCOUNT))) { return; }
codereview_cpp_data_10335
{ const BitModes & modes = player; msg << modes << player.id << player.control << player.color << player.race << player.friends << player.name << player.focus << *player._ai; - if ( player._ai ) { - msg << *player._ai; - } - else { - DEBUG_LOG( DBG_GAME, DBG_WARN, "Player object without AI" ); - msg << AI::Normal(); - } return msg; } Is it even possible? If not let's add an assertion here. { const BitModes & modes = player; + assert( player._ai != nullptr ); msg << modes << player.id << player.control << player.color << player.race << player.friends << player.name << player.focus << *player._ai; return msg; }
codereview_cpp_data_10346
return err; } -void default_table_slice::apply_column(size_type col, value_index& idx) const { for (size_type row = 0; row < rows(); ++row) idx.append(make_view(caf::get<vector>(xs_[row])[col]), offset() + row); } This is essentially the same algorithm that is implemented in the base class, so why even override it? return err; } +void default_table_slice::append_column_to_index(size_type col, + value_index& idx) const { for (size_type row = 0; row < rows(); ++row) idx.append(make_view(caf::get<vector>(xs_[row])[col]), offset() + row); }
codereview_cpp_data_10379
cout << cmd << endl; if (!env.empty()) { setenv("HIP_VISIBLE_DEVICES", env.c_str(), 1); cout << "set env HIP_VISIBLE_DEVICES = " << env.c_str() << endl; // verify if the environment variable is set The test needs to run on nvcc path as well. So what you probably need is something like ```c++ #ifdef __HIP_PLATFORM_HCC__ setenv("HIP_VISIBLE_DEVICES", env.c_str(), 1); #else setenv("CUDA_VISIBLE_DEVICES", env.c_str(), 1); #endif ``` cout << cmd << endl; if (!env.empty()) { +#ifdef __HIP_PLATFORM_HCC__ setenv("HIP_VISIBLE_DEVICES", env.c_str(), 1); +#else + setenv("CUDA_VISIBLE_DEVICES", env.c_str(), 1); +#endif cout << "set env HIP_VISIBLE_DEVICES = " << env.c_str() << endl; // verify if the environment variable is set
codereview_cpp_data_10381
, rtps_participant_(p->rtps_participant()) , default_datareader_qos_(DATAREADER_QOS_DEFAULT) { - SubscriberAttributes pub_attr; - XMLProfileManager::getDefaultSubscriberAttributes(pub_attr); - set_qos_from_attributes(default_datareader_qos_, pub_attr); } void SubscriberImpl::disable() ```suggestion SubscriberAttributes sub_attr; XMLProfileManager::getDefaultSubscriberAttributes(sub_attr); set_qos_from_attributes(default_datareader_qos_, sub_attr); ``` , rtps_participant_(p->rtps_participant()) , default_datareader_qos_(DATAREADER_QOS_DEFAULT) { + SubscriberAttributes sub_attr; + XMLProfileManager::getDefaultSubscriberAttributes(sub_attr); + set_qos_from_attributes(default_datareader_qos_, sub_attr); } void SubscriberImpl::disable()
codereview_cpp_data_10384
if (opt_show_metadata) { g_autoptr(GFile) file = NULL; g_autofree char *data = NULL; gsize data_size; file = g_file_get_child (deploy_dir, "metadata"); if (!g_file_load_contents (file, cancellable, &data, &data_size, NULL, error)) Actually, this deploy_dir seems more right than the toplevel one which is: ``` deploy = flatpak_find_deploy_for_ref (ref, NULL, NULL, error); ``` Which means it could come from a system dir even if you said --user. That doesn't seem right. if (opt_show_metadata) { + g_autoptr(GFile) deploy_dir = NULL; g_autoptr(GFile) file = NULL; g_autofree char *data = NULL; gsize data_size; + deploy_dir = flatpak_dir_get_if_deployed (dir, ref, NULL, cancellable); file = g_file_get_child (deploy_dir, "metadata"); if (!g_file_load_contents (file, cancellable, &data, &data_size, NULL, error))
codereview_cpp_data_10397
for (int i = 23; i < 46; ++i){ rms_tols2[i] = 0.75; // velocities } - for (int i = 46; i < rms_tols2.size(); ++i){ rms_tols2[i] = 0.15; // muscle activations and fiber-lengths } `size()` returns an unsigned so I believe some compilers will give a warning when attempting to compare `i` with `rms_tols2.size()`. Not a big deal (we have lots of warnings), but perhaps `i < (int)rms_tols2.size()`? for (int i = 23; i < 46; ++i){ rms_tols2[i] = 0.75; // velocities } + for (size_t i = 46; i < rms_tols2.size(); ++i){ rms_tols2[i] = 0.15; // muscle activations and fiber-lengths }
codereview_cpp_data_10411
* 2. It will not produce the same results on little-endian and big-endian * machines. */ -unsigned int gen_hash(const void *key, int len) { /* 'm' and 'r' are mixing constants generated offline. They're not really 'magic', they just happen to work well. */ public interfaces must be prefixed with flb_, e.g: ```flb_hash_gen_hash``` or ```flb_hash_generate``` * 2. It will not produce the same results on little-endian and big-endian * machines. */ +unsigned int flb_hash_generate(const void *key, int len) { /* 'm' and 'r' are mixing constants generated offline. They're not really 'magic', they just happen to work well. */
codereview_cpp_data_10414
std::unique_ptr<optimizer> build_no_optimizer_from_pbuf( google::protobuf::Message const& msg, lbann_comm* comm) { - return std::unique_ptr<optimizer>(); } using factory_type = lbann::generic_factory< This can just return `nullptr;` All that extra typing... what would @ndryden think?? std::unique_ptr<optimizer> build_no_optimizer_from_pbuf( google::protobuf::Message const& msg, lbann_comm* comm) { + return nullptr; } using factory_type = lbann::generic_factory<
codereview_cpp_data_10422
auto before = maybe_parse(caf::get_if<std::string>(&options, "explore.before")); auto after = maybe_parse(caf::get_if<std::string>(&options, "explore.after")); - std::optional<std::string> by - = to_std(caf::get_if<std::string>(&options, "explore.by")); explorer_state::event_limits limits; limits.total = caf::get_or(options, "explore.max-events", defaults::explore::max_events); - limits.per_result - = caf::get_or(options, "explore.limit2", defaults::explore::limit2); return self->spawn(explorer, self, limits, before, after, by); } ```suggestion auto by ``` auto before = maybe_parse(caf::get_if<std::string>(&options, "explore.before")); auto after = maybe_parse(caf::get_if<std::string>(&options, "explore.after")); + auto by = to_std(caf::get_if<std::string>(&options, "explore.by")); explorer_state::event_limits limits; limits.total = caf::get_or(options, "explore.max-events", defaults::explore::max_events); + limits.per_result = caf::get_or(options, "explore.max-events-context", + defaults::explore::max_events_context); return self->spawn(explorer, self, limits, before, after, by); }
codereview_cpp_data_10423
for (auto &batch : batches) { if (auto answer = batch_validator.validate(batch)) { reason.second.emplace_back(answer.reason()); - break; } } If several batches are invalid, there will be an error only for one of them. Consider removing break. for (auto &batch : batches) { if (auto answer = batch_validator.validate(batch)) { reason.second.emplace_back(answer.reason()); } }
codereview_cpp_data_10430
void TabMessage::processUserMessageEvent(const Event_UserMessage &event) { - const UserLevelFlags userLevel(event.sender_name() == otherUserInfo->name() ? otherUserInfo->user_level() : ownUserInfo->user_level()); - const QString userPriv(event.sender_name() == otherUserInfo->name() ? QString::fromStdString(otherUserInfo->privlevel()) : QString::fromStdString(ownUserInfo->privlevel())); chatView->appendMessage(QString::fromStdString(event.message()), 0,QString::fromStdString(event.sender_name()), userLevel, userPriv, true); if (tabSupervisor->currentIndex() != tabSupervisor->indexOf(this)) soundEngine->playSound("private_message"); Minor tweak for duplication; ```cpp auto userInfo = event.sender_name() == otherUserInfo->name() ? otherUserInfo : ownUserInfo; const UserLevelFlags userLevel(userInfo->user_level()); const QString userPriv = QString::fromStdString(userInfo->privlevel()); ``` void TabMessage::processUserMessageEvent(const Event_UserMessage &event) { + auto userInfo = event.sender_name() == otherUserInfo->name() ? otherUserInfo : ownUserInfo; + const UserLevelFlags userLevel(userInfo->user_level()); + const QString userPriv = QString::fromStdString(userInfo->privlevel()); + chatView->appendMessage(QString::fromStdString(event.message()), 0,QString::fromStdString(event.sender_name()), userLevel, userPriv, true); if (tabSupervisor->currentIndex() != tabSupervisor->indexOf(this)) soundEngine->playSound("private_message");
codereview_cpp_data_10437
} if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == nullptr)) setBlockIndexCandidates.insert(pindex); - if (pindex->nStatus & BLOCK_FAILED_MASK && - (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid.load()->nChainWork)) pindexBestInvalid = pindex; if (pindex->pprev) pindex->BuildSkip(); if (pindex->IsValid(BLOCK_VALID_TREE) && - (pindexBestHeader.load() == nullptr || CBlockIndexWorkComparator()(pindexBestHeader.load(), pindex))) pindexBestHeader = pindex; } store in temporary } if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == nullptr)) setBlockIndexCandidates.insert(pindex); + CBlockIndex *pBestInvalid = pindexBestInvalid.load(); + if (pindex->nStatus & BLOCK_FAILED_MASK && (!pBestInvalid || pindex->nChainWork > pBestInvalid->nChainWork)) pindexBestInvalid = pindex; if (pindex->pprev) pindex->BuildSkip(); + CBlockIndex *pBestHeader = pindexBestHeader.load(); if (pindex->IsValid(BLOCK_VALID_TREE) && + (pBestHeader == nullptr || CBlockIndexWorkComparator()(pBestHeader, pindex))) pindexBestHeader = pindex; }
codereview_cpp_data_10440
* @param arr array to shuffle * @returns new array with elements shuffled from a given array */ -template<typename T, size_t N> -std::array <T, N> shuffle(std::array <T, N> arr) { - for(int i = 0; i < N; i ++) { // Swaps i'th index with random index (less than array size) std::swap(arr[i], arr[std::rand() % N]); } ```suggestion for (int i = 0; i < N; i ++) { ``` Same in other parts of the code. * @param arr array to shuffle * @returns new array with elements shuffled from a given array */ +template <typename T, size_t N> +std::array <T, N> shuffle (std::array <T, N> arr) { + for (int i = 0; i < N; i ++) { // Swaps i'th index with random index (less than array size) std::swap(arr[i], arr[std::rand() % N]); }
codereview_cpp_data_10453
else if (victim->GetOwnerID()) { Message(0, "You cannot steal from pets!"); } - else if (!CombatRange(victim, 3.0)) { //Give benefit of the doubt due to pathing NPCs Message(Chat::Red, "Attempt to pickpocket out of range detected."); database.SetMQDetectionFlag(this->AccountName(), this->GetName(), "OP_PickPocket was sent from outside combat range.", zone->GetShortName()); } Distance is actually just 15. else if (victim->GetOwnerID()) { Message(0, "You cannot steal from pets!"); } + else if (Distance(GetPosition(), victim->GetPosition()) > 15) { Message(Chat::Red, "Attempt to pickpocket out of range detected."); database.SetMQDetectionFlag(this->AccountName(), this->GetName(), "OP_PickPocket was sent from outside combat range.", zone->GetShortName()); }
codereview_cpp_data_10454
} } else { sprintf(msg_buf, - "No data_dir= found in %s. Try reinstalling BOINC.", - LINUX_CONFIG_FILE ); msg = msg_buf; return ERR_FOPEN; Please add another "in %s" and ", LINUX_DEFAULT_DATA_DIR". Otherwise very nice, many thanks! } } else { sprintf(msg_buf, + "No data_dir= found in %s. See %s", + LINUX_CONFIG_FILE, HELP_URL ); msg = msg_buf; return ERR_FOPEN;
codereview_cpp_data_10458
g_hash_table_replace (metadata_hash, g_strdup ("rpmostree.inputhash"), g_variant_ref_sink (g_variant_new_string (new_inputhash))); - const char *gpgkey; if (!_rpmostree_jsonutil_object_get_optional_string_member (treefile, "gpg_key", &gpgkey, error)) goto out; Shouldn't this be initialized? Looking at `_rpmostree_jsonutil_object_get_optional_boolean_member()`, it seems it only assigns a value if it finds the key. g_hash_table_replace (metadata_hash, g_strdup ("rpmostree.inputhash"), g_variant_ref_sink (g_variant_new_string (new_inputhash))); + const char *gpgkey = NULL; if (!_rpmostree_jsonutil_object_get_optional_string_member (treefile, "gpg_key", &gpgkey, error)) goto out;
codereview_cpp_data_10468
clif->clearunit_area(&sd->bl, CLR_DEAD); else { skill->usave_trigger(sd); - if (battle_config.player_warp_keep_direction) clif->changed_dir(&sd->bl, SELF); // Visually updates player facing direction } kindly use == 1 here please clif->clearunit_area(&sd->bl, CLR_DEAD); else { skill->usave_trigger(sd); + if (battle_config.player_warp_keep_direction == 1) clif->changed_dir(&sd->bl, SELF); // Visually updates player facing direction }
codereview_cpp_data_10491
g_autoptr(GOptionContext) context = g_option_context_new (""); glnx_unref_object RPMOSTreeOS *os_proxy = NULL; glnx_unref_object RPMOSTreeSysroot *sysroot_proxy = NULL; - g_autoptr(GVariant) default_deployment = NULL; g_autofree char *transaction_address = NULL; _cleanup_peer_ GPid peer_pid = 0; const char *const *install_pkgs = NULL; Let's still call this `new_default_deployment`? Otherwise it seems confusing, since there clearly *is* a default deployment, we just didn't get a signal. g_autoptr(GOptionContext) context = g_option_context_new (""); glnx_unref_object RPMOSTreeOS *os_proxy = NULL; glnx_unref_object RPMOSTreeSysroot *sysroot_proxy = NULL; + g_autoptr(GVariant) new_default_deployment = NULL; g_autofree char *transaction_address = NULL; _cleanup_peer_ GPid peer_pid = 0; const char *const *install_pkgs = NULL;
codereview_cpp_data_10512
Plugin_128_pixels->Show(); if (mode != lastmode) { - String log; - log = F("NeoPixelBus: Mode Change: "); - log += P128_modeType_toString(mode); - addLog(LOG_LEVEL_INFO, log); NeoPixelSendStatus(event); } return true; Check for logLevelActiveFor missing Plugin_128_pixels->Show(); if (mode != lastmode) { + if (loglevelActiveFor(LOG_LEVEL_INFO)) { + String log; + log = F("NeoPixelBus: Mode Change: "); + log += P128_modeType_toString(mode); + addLog(LOG_LEVEL_INFO, log); + } NeoPixelSendStatus(event); } return true;
codereview_cpp_data_10515
return ok; } -static mrb_state *maybe_init_mrb(struct mruby_configurator_t *self) { if (self->mrb == NULL) { self->mrb = mrb_open(); configurator also should use one shared mrb_state for compile testing, because handlers may cause side-effects to other handlers, and it may cause compile (accurately, evaluating) errors. return ok; } +static mrb_state *get_mrb(struct mruby_configurator_t *self) { if (self->mrb == NULL) { self->mrb = mrb_open();
codereview_cpp_data_10527
return s->lookup(xs_); } -// TODO: return expected<segment_store_ptr> for better error propagation. caf::expected<segment_store_ptr> segment_store::make(std::filesystem::path dir, size_t max_segment_size, size_t in_memory_segments) { The `TODO` can be removed now. return s->lookup(xs_); } caf::expected<segment_store_ptr> segment_store::make(std::filesystem::path dir, size_t max_segment_size, size_t in_memory_segments) {
codereview_cpp_data_10530
// now do the same but connect the elbow from humerus to humerus auto elbowInHumerus = new PhysicalOffsetFrame("elbow_in_humerus", model.getComponent<Body>("r_humerus"), - SimTK::Transform(SimTK::Vec3(0, -0.33, 0.0))); model.addComponent(elbowInHumerus); // update the elbow Joint and connect its socket to the new frame 0 and 0.0? // now do the same but connect the elbow from humerus to humerus auto elbowInHumerus = new PhysicalOffsetFrame("elbow_in_humerus", model.getComponent<Body>("r_humerus"), + SimTK::Transform(SimTK::Vec3(0, -0.33, 0))); model.addComponent(elbowInHumerus); // update the elbow Joint and connect its socket to the new frame
codereview_cpp_data_10542
rubyInterpreter.evalString(embedded_extensions_string); } catch (const std::exception& e) { rubyInterpreter.evalString(R"(STDOUT.flush)"); - std::cout << "Exception in embedded_help: " << e.what() << '\n'; // endl will flush return ruby_cleanup(1); } catch (...) { rubyInterpreter.evalString(R"(STDOUT.flush)"); - std::cout << "Unknown Exception in embedded_help" << '\n'; // endl will flush return ruby_cleanup(1); } Might want some of these to flush, since this would result in ending the program you'd want the output written before exit rubyInterpreter.evalString(embedded_extensions_string); } catch (const std::exception& e) { rubyInterpreter.evalString(R"(STDOUT.flush)"); + std::cout << "Exception in embedded_help: " << e.what() << std::endl; // endl will flush return ruby_cleanup(1); } catch (...) { rubyInterpreter.evalString(R"(STDOUT.flush)"); + std::cout << "Unknown Exception in embedded_help" << std::endl; // endl will flush return ruby_cleanup(1); }
codereview_cpp_data_10545
#include <wlr/types/wlr_tablet_v2.h> #include <wlr/util/log.h> -static const struct wlr_tablet_tool_v2_grab_interface default_tool_interface; static const struct wlr_surface_role tablet_tool_cursor_surface_role = { .name = "wp_tablet_tool-cursor", This variable name should probably contain `grab` #include <wlr/types/wlr_tablet_v2.h> #include <wlr/util/log.h> +static const struct wlr_tablet_tool_v2_grab_interface default_tool_grab_interface; static const struct wlr_surface_role tablet_tool_cursor_surface_role = { .name = "wp_tablet_tool-cursor",
codereview_cpp_data_10557
bool RTPSParticipantImpl::update_attributes( const RTPSParticipantAttributes& patt) { - (void)patt; return false; } More c++ like ```suggestion static_cast<void>(patt); ``` bool RTPSParticipantImpl::update_attributes( const RTPSParticipantAttributes& patt) { + static_cast<void>(patt); return false; }
codereview_cpp_data_10565
stillmore = false; for ( i=0; i<=mm->instance_count; ++i ) if ( ss[i]!=NULL ) stillmore = true; if ( stillmore ) -{ -free(ss); -free(sp); return( false ); -} -free(ss); -free(sp); return( true ); } else { stillmore = true; This can be simplified by moving the free statements before `if ( stillmore )` stillmore = false; for ( i=0; i<=mm->instance_count; ++i ) if ( ss[i]!=NULL ) stillmore = true; + free(ss); + free(sp); if ( stillmore ) return( false ); return( true ); } else { stillmore = true;
codereview_cpp_data_10569
if (iarg+3 > narg) error->all(FLERR,"Illegal pair_style mliap command"); descriptor = new MLIAPDescriptorSNAP(lmp,arg[iarg+2]); iarg += 3; - }else if (strcmp(arg[iarg+1],"so3") == 0) { - if (iarg+3 > narg) error->all(FLERR,"Illegal pair_style mliap command"); - descriptor = new MLIAPDescriptorSO3(lmp,arg[iarg+2]); - iarg += 3; } else error->all(FLERR,"Illegal pair_style mliap command"); descriptorflag = 1; please use `} else` instead of `}else` and a 2 character indentation not 4. if (iarg+3 > narg) error->all(FLERR,"Illegal pair_style mliap command"); descriptor = new MLIAPDescriptorSNAP(lmp,arg[iarg+2]); iarg += 3; + } else if (strcmp(arg[iarg+1],"so3") == 0) { + if (iarg+3 > narg) error->all(FLERR,"Illegal pair_style mliap command"); + descriptor = new MLIAPDescriptorSO3(lmp,arg[iarg+2]); + iarg += 3; } else error->all(FLERR,"Illegal pair_style mliap command"); descriptorflag = 1;
codereview_cpp_data_10575
QStringList ptDbSplit = db->getCard(name)->getPowTough().split("/"); QStringList ptSplit = pt.split("/"); - if ((ptDbSplit.at(0) != ptSplit.at(0) || ptDbSplit.at(1) != ptSplit.at(1)) && !getFaceDown()) painter->setPen(QColor(255, 150, 0)); else painter->setPen(Qt::white); Change to: `if (facedown || ptDbSplit.at(0) != ptSplit.at(0) || ptDbSplit.at(1) != ptSplit.at(1))` If the card is face down it should always be orange. Also performs this checks first so we dont waste cycles on comparisons if not needed. QStringList ptDbSplit = db->getCard(name)->getPowTough().split("/"); QStringList ptSplit = pt.split("/"); + if (getFaceDown() || ptDbSplit.at(0) != ptSplit.at(0) || ptDbSplit.at(1) != ptSplit.at(1)) painter->setPen(QColor(255, 150, 0)); else painter->setPen(Qt::white);
codereview_cpp_data_10577
{ switch (t) { case TypeAnd: - return QString("AND"); case TypeOr: - return QString("OR"); case TypeAndNot: - return QString("AND NOT"); case TypeOrNot: - return QString("OR NOT"); default: return QString(""); } Should these not be translated? { switch (t) { case TypeAnd: + return tr("AND", "Logical conjunction operator used in card filter"); case TypeOr: + return tr("OR", "Logical disjunction operator used in card filter"); case TypeAndNot: + return tr("AND NOT", "Negated logical conjunction operator used in card filter"); case TypeOrNot: + return tr("OR NOT", "Negated logical disjunction operator used in card filter"); default: return QString(""); }
codereview_cpp_data_10578
#include "AirflowNetworkDistributionLinkage.hpp" #include "AirflowNetworkDistributionLinkage_Impl.hpp" // TODO: Check the following class names against object getters and setters. #include "AirflowNetworkNode.hpp" #include "AirflowNetworkNode_Impl.hpp" #include "AirflowNetworkComponent.hpp" #include "AirflowNetworkComponent_Impl.hpp" #include "ThermalZone.hpp" #include "ThermalZone_Impl.hpp" Need to take nodes and component in ctor? #include "AirflowNetworkDistributionLinkage.hpp" #include "AirflowNetworkDistributionLinkage_Impl.hpp" +#include "AirflowNetworkDistributionNode.hpp" +#include "AirflowNetworkDistributionNode_Impl.hpp" // TODO: Check the following class names against object getters and setters. #include "AirflowNetworkNode.hpp" #include "AirflowNetworkNode_Impl.hpp" #include "AirflowNetworkComponent.hpp" #include "AirflowNetworkComponent_Impl.hpp" +#include "AirflowNetworkFan.hpp" +#include "AirflowNetworkFan_Impl.hpp" #include "ThermalZone.hpp" #include "ThermalZone_Impl.hpp"
codereview_cpp_data_10582
return result; } -static void on_context_init(h2o_handler_t *_handler, h2o_context_t *ctx, h2o_pathconf_t *pathconf) { h2o_mruby_handler_t *handler = (void *)_handler; h2o_mruby_context_t *handler_ctx = h2o_mem_alloc(sizeof(*handler_ctx)); handler_ctx->handler = handler; handler_ctx->shared = get_shared_context(ctx); - handler_ctx->pathconf = pathconf; mrb_state *mrb = handler_ctx->shared->mrb; Why does `pathconf` need to be a per loop variable? It is not thread-dependent, and I believe that you can make it a property of `h2o_mruby_handler_t`. The added bonus of making such change will be that you would be able to record the address in `h2o_mruby_register` and you no longer need to change the type of `on_context_init`. return result; } +static void on_context_init(h2o_handler_t *_handler, h2o_context_t *ctx) { h2o_mruby_handler_t *handler = (void *)_handler; h2o_mruby_context_t *handler_ctx = h2o_mem_alloc(sizeof(*handler_ctx)); handler_ctx->handler = handler; handler_ctx->shared = get_shared_context(ctx); mrb_state *mrb = handler_ctx->shared->mrb;
codereview_cpp_data_10583
using namespace iroha; using namespace iroha::ametsuchi; -using namespace iroha::model; -using namespace iroha::model::converters; using namespace iroha::network; BlockLoaderService::BlockLoaderService(std::shared_ptr<BlockQuery> storage) Remove redundant using-namespaces plz (iroha::model and maybe smth else) using namespace iroha; using namespace iroha::ametsuchi; using namespace iroha::network; BlockLoaderService::BlockLoaderService(std::shared_ptr<BlockQuery> storage)
codereview_cpp_data_10590
* This will properly maintain the copyright information. DigitalGlobe * copyrights will be updated automatically. * - * @copyright Copyright (C) 2015 DigitalGlobe (http://www.digitalglobe.com/) */ #include "LongIntegerFieldDefinition.h" Do you know why we are setting _min as -numeric_limits<long long>::max(), instead of ::min()? Strictly speaking, for a signed, n-bit, twos-compliment number, max is going to be 2^(n-1)-1, and min is going to be 2^(n-1), so numeric_limits<>::min() is not the same as -numeric_limits::max() I mean it's probably this way for a reason... I'm just curious if anyone knows what the reason is. * This will properly maintain the copyright information. DigitalGlobe * copyrights will be updated automatically. * + * @copyright Copyright (C) 2017 DigitalGlobe (http://www.digitalglobe.com/) */ #include "LongIntegerFieldDefinition.h"
codereview_cpp_data_10616
{ //allow for calculating the changeset with a slightly larger AOI than the default specified //bounding box; useful in certain situations - Envelope convertBounds = GeometryUtils::envelopeFromConfigString(ConfigOptions().getConvertBoundingBox()); convertBounds.expandBy(changesetBuffer, changesetBuffer); conf().set( So in the initial changeset derived from a freshly conflated dataset, the review relations will be removed. What about the secondary features involved in the reviews? 1. Add potential duplicates on the initial save back to osm? 2. Withold potential duplicates from the changeset until the review has been resolved? { //allow for calculating the changeset with a slightly larger AOI than the default specified //bounding box; useful in certain situations + geos::geom::Envelope convertBounds = GeometryUtils::envelopeFromConfigString(ConfigOptions().getConvertBoundingBox()); convertBounds.expandBy(changesetBuffer, changesetBuffer); conf().set(
codereview_cpp_data_10619
*/ QVariantMap resultMap = array.at(0).toObject().toVariantMap(); - if (resultMap.size() == 0) { qWarning() << "No reply received from the release update server:" << QString(jsonData); emit error(tr("No reply received from the release update server.")); return; `array.at(0)` can fail if we ever deleted the releases or if the github api for some reason returned bad json. Does the app crash in that case? */ QVariantMap resultMap = array.at(0).toObject().toVariantMap(); + if (array.size() == 0 || resultMap.size() == 0) { qWarning() << "No reply received from the release update server:" << QString(jsonData); emit error(tr("No reply received from the release update server.")); return;
codereview_cpp_data_10628
const Scalar val = a((i*32 + j)*32 + k); if(val>lmax) lmax = val; if((k == 11) && (j==17) && (i==2)) lmax = 11.5; -#ifdef GENERIC_REDUCER - },Kokkos::Max<Scalar>(t_max)); -#else },Kokkos::Experimental::Max<Scalar>(t_max)); -#endif if(t_max>thread_max) thread_max = t_max; -#ifdef GENERIC_REDUCER - },Kokkos::Max<Scalar>(team_max)); -#else },Kokkos::Experimental::Max<Scalar>(team_max)); -#endif } if(team_max>lmax) lmax = team_max; },Kokkos::Experimental::Max<Scalar>(max)); GENERIC_REDUCER macro needs to be renamed to conform to our macro convention const Scalar val = a((i*32 + j)*32 + k); if(val>lmax) lmax = val; if((k == 11) && (j==17) && (i==2)) lmax = 11.5; },Kokkos::Experimental::Max<Scalar>(t_max)); if(t_max>thread_max) thread_max = t_max; },Kokkos::Experimental::Max<Scalar>(team_max)); } if(team_max>lmax) lmax = team_max; },Kokkos::Experimental::Max<Scalar>(max));
codereview_cpp_data_10630
int na = _model->getActuators().getSize(); double p = 0.0; for(int i=0;i<na;i++) { - if (ScalarActuator* act = dynamic_cast<ScalarActuator*>(&_model->getActuators().get(i))) p += pow(fabs(parameters[i]),_activationExponent); } performance = p; This seems like the wrong time to be doing the dynamic_cast. The `parameters` should already be correctly sized to (size == na) in which case there is no reason to perform this check. Also performing numerous dynamic_casts in the heart of the optimization is going to degrade performance. int na = _model->getActuators().getSize(); double p = 0.0; for(int i=0;i<na;i++) { p += pow(fabs(parameters[i]),_activationExponent); } performance = p;
codereview_cpp_data_10632
}*/ // calculate the 2 sigma for the distance between the two objects - const double sigma1 = poi->getCircularError() / 2.0; - const double sigma2 = poly->getCircularError() / 2.0; - const double ce = sqrt(sigma1 * sigma1 + sigma2 * sigma2) * 2; - const double reviewDistancePlusCe = _reviewDistanceThreshold + ce; _closeMatch = _distance <= reviewDistancePlusCe; //close match is a requirement for any matching, regardless of the final total evidence count if (!_closeMatch) I'm pretty sure that 2*sqrt( (sigma1/2)*(sigma1/2) + (sigma2/2)*(sigma2/2)) == sqrt(sigma1*sigma1 + sigma2*sigma2) Is there a reason to divide by 2, then multiply by 2 later? }*/ // calculate the 2 sigma for the distance between the two objects + const double poiSigma = poi->getCircularError() / 2.0; + const double polySigma = poly->getCircularError() / 2.0; + const double sigma = sqrt(poiSigma * poiSigma + polySigma * polySigma); + const double combinedCircularError2Sigma = sigma * 2; + const double reviewDistancePlusCe = _reviewDistanceThreshold + combinedCircularError2Sigma; _closeMatch = _distance <= reviewDistancePlusCe; //close match is a requirement for any matching, regardless of the final total evidence count if (!_closeMatch)
codereview_cpp_data_10635
VisualNode->addObject(mapping); } else - std::cout << "Error: mapping visual not possible"; return VisualNode; } Usage of std::cout is allowed only for debugging not for within a PR. Please use msg_error(this) << "Mapping visual not possible" Bonus point if you explain why it is not possible and how the user is supposed to fix his scene to remove the message. VisualNode->addObject(mapping); } else + std::cerr << "Visual Mapping creation not possible. Mapping should be Barycentric or Identity. Found MappingType enum: " << mappingT << std::endl; return VisualNode; }
codereview_cpp_data_10647
} } // namespace util_functions namespace { class Layer { public: // To store activation function and it's derivative ```suggestion assert(machine_learning::argmax(myNN.single_predict({{5,3.4,1.6,0.4}})) == 0); assert(machine_learning::argmax(myNN.single_predict({{6.4,2.9,4.3,1.3}})) == 1); assert(machine_learning::argmax(myNN.single_predict({{6.2,3.4,5.4,2.3}})) == 2); ``` } } // namespace util_functions namespace { + /** + * Layer class is used to store all necessary information about + * the layers (i.e. neurons, activation and kernal). This class + * is used by NeuralNetwork class to store layers. + * + */ class Layer { public: // To store activation function and it's derivative
codereview_cpp_data_10650
!= roles->end()); } - TEST_F(AppendRole, AppendRoleTestInvalidNoAccount) { addAllPerms(); ASSERT_TRUE(val(execute( buildCommand(TestTransactionBuilder().createRole(another_role, {})), You can remove "AppendRoleTest" from test name, since it is contained in the test fixture. Please check all other tests for the same issue != roles->end()); } + /** + * @given command + * @when trying to append role to non-existing account + * @then role is not appended + */ + TEST_F(AppendRole, NoAccount) { addAllPerms(); ASSERT_TRUE(val(execute( buildCommand(TestTransactionBuilder().createRole(another_role, {})),
codereview_cpp_data_10658
* SPDX-License-Identifier: Apache-2.0 */ -#include "flat_file.hpp" #include <boost/filesystem.hpp> #include <boost/range/adaptor/indexed.hpp> Please use file path relative to irohad directory. `ametsuchi/impl/flat_file/flat_file.cpp` * SPDX-License-Identifier: Apache-2.0 */ +#include "ametsuchi/impl/flat_file/flat_file.hpp" #include <boost/filesystem.hpp> #include <boost/range/adaptor/indexed.hpp>
codereview_cpp_data_10670
return i - 2; } -int __fastcall gmenu_presskeys(int a1) { if (!dword_634480) return 0; From it usage and return values I would say that this was probably returning BOOL (long), does it still compile as bin exact if changed to do so? return i - 2; } +BOOL __fastcall gmenu_presskeys(int a1) { if (!dword_634480) return 0;
codereview_cpp_data_10680
* @author [Ghanashyam](https://github.com/g-s-k-zoro) */ -#include <cassert> /// for testing -#include <cctype> /// for case manipulation of alphabets #include <cstring> /// for string operations #include <iostream> /// for IO Operations #include <queue> /// for std::priority_queue `assert` is the name of the function, so we'll use here `for assert`. ```suggestion #include <cassert> /// for assert ``` * @author [Ghanashyam](https://github.com/g-s-k-zoro) */ +#include <cassert> /// for assert +#include <cctype> /// for tolower #include <cstring> /// for string operations #include <iostream> /// for IO Operations #include <queue> /// for std::priority_queue
codereview_cpp_data_10698
* Get transactions from the given batches queue. Does not break batches - * continues getting all the transactions from the ongoing batch until the * required amount is collected. - * @tparam Lambda - type of side effect function for batches * @param requested_tx_amount - amount of transactions to get * @param batch_collection - the collection to get transactions from * @param discarded_txs_amount - the amount of discarded txs - * @param batch_operation - side effect function to be performed on each - * inserted batch. Passed pointer could be modified * @return transactions */ static std::vector<std::shared_ptr<shared_model::interface::Transaction>> Fix function docs as well plz. * Get transactions from the given batches queue. Does not break batches - * continues getting all the transactions from the ongoing batch until the * required amount is collected. * @param requested_tx_amount - amount of transactions to get * @param batch_collection - the collection to get transactions from * @param discarded_txs_amount - the amount of discarded txs * @return transactions */ static std::vector<std::shared_ptr<shared_model::interface::Transaction>>
codereview_cpp_data_10730
shared_ptr<QSqlQuery> changesetItr = _db.getChangesetsCreatedAfterTime(timeStr); - Envelope allChangesetsBounds; while (changesetItr->next()) { shared_ptr<Envelope> changesetBounds( what if: instead of accumulating all of the changeset bounds into one big envelope, you checked each changeset bounds against the arg bounds individually? Then you could bail out early if you found an intersection at any time. shared_ptr<QSqlQuery> changesetItr = _db.getChangesetsCreatedAfterTime(timeStr); while (changesetItr->next()) { shared_ptr<Envelope> changesetBounds(
codereview_cpp_data_10743
const int32_t* row = mat.ptr<int32_t>(y); for (int x = 0; x < qImage->width(); x++) { - int v = log1p(row[x]) / log(maxValue); - int r = std::max(0, std::min<int>(255, v * _colorMultiplier[0] + qRed(_baseColors))); - int g = std::max(0, std::min<int>(255, v * _colorMultiplier[1] + qGreen(_baseColors))); - int b = std::max(0, std::min<int>(255, v * _colorMultiplier[2] + qBlue(_baseColors))); - int a = std::max(0, std::min<int>(255, v * _colorMultiplier[3] + qAlpha(_baseColors))); rgb = qRgba(r, g, b, a); qImage->setPixel(x, qImage->height() - y - 1, rgb); } `v` must remain a `double` so that the calculation of the muliplier is calculated correctly. Once the calculation is complete, only then can it be cast to an integer. ``` int r = std::max(0, std::min<int>(255, std::static_cast<int>(v * _colorMultiplier[0] + qRed(_baseColors)))); ``` const int32_t* row = mat.ptr<int32_t>(y); for (int x = 0; x < qImage->width(); x++) { + double v = log1p(row[x]) / log(maxValue); + int r = std::max(0, std::min<int>(255, std::static_cast<int>(v * _colorMultiplier[0] + qRed(_baseColors)))); + int g = std::max(0, std::min<int>(255, std::static_cast<int>(v * _colorMultiplier[1] + qGreen(_baseColors)))); + int r = std::max(0, std::min<int>(255, std::static_cast<int>(v * _colorMultiplier[2] + qBlue(_baseColors)))); + int a = std::max(0, std::min<int>(255, std::static_cast<int>(v * _colorMultiplier[3] + qAlpha(_baseColors)))); rgb = qRgba(r, g, b, a); qImage->setPixel(x, qImage->height() - y - 1, rgb); }
codereview_cpp_data_10747
void testTutorialOne(); // Test different default activations are respected when activation -// states are not provided. Note if default_activation is 1.0 it -// reproduces the "skyscraper" bug issue #83 in OpenSim32 repo void testTugOfWar(const string& dataFileName, const double& defaultAct); void reportTendonAndFiberForcesAcrossFiberLengths(const Model& model, const SimTK::State& state); - int main() { SimTK::Array_<std::string> failures; Can't this note be deleted now? void testTutorialOne(); // Test different default activations are respected when activation +// states are not provided. void testTugOfWar(const string& dataFileName, const double& defaultAct); void reportTendonAndFiberForcesAcrossFiberLengths(const Model& model, const SimTK::State& state); int main() { SimTK::Array_<std::string> failures;
codereview_cpp_data_10750
* npctalk (sends message to surrounding area) * usage: npctalk "<message>"{,"<npc name>"{,<show_npcname>}}; * <show_npcname>: - * 0: shows npc name like "Npc : message" - * 1: hide npc name *------------------------------------------*/ BUILDIN(npctalk) { struct npc_data* nd; - int show_npcname = 0; const char *str = script_getstr(st,2); if (script_hasdata(st, 3)) { default should be 1 ? By default it should append the npc name right? * npctalk (sends message to surrounding area) * usage: npctalk "<message>"{,"<npc name>"{,<show_npcname>}}; * <show_npcname>: + * 1: shows npc name like "Npc : message" + * 0: hide npc name *------------------------------------------*/ BUILDIN(npctalk) { struct npc_data* nd; + int show_npcname = 1; const char *str = script_getstr(st,2); if (script_hasdata(st, 3)) {
codereview_cpp_data_10753
Object* dependency = Object::newInstanceOfType(dependencyTypeName); - if (dependency == nullptr){ - // Get a concrete instance of a PhysicalFrame, which is a Body - size_t n = dependencyTypeName.length(); - if (n > 4 && dependencyTypeName.substr(n-5) == "Frame") { - dependency = Object::newInstanceOfType("Body"); - } } if (dependency) { It'd be great if we could use `std::is_base_of` or casts instead of this. Object* dependency = Object::newInstanceOfType(dependencyTypeName); + if (dynamic_cast< Connector<Frame>*>(&connector) || + dynamic_cast< Connector<PhysicalFrame>*>(&connector)) { + dependency = Object::newInstanceOfType("Body"); } if (dependency) {
codereview_cpp_data_10756
int main() { BEGIN_TEST(); - EXPECT_SUCCESS(s2n_disable_tls13()); if (!s2n_pq_is_enabled()) { END_TEST(); Since this is a new test, I'd try to write it without disabling TLS1.3. S2N now runs with TLS1.3 enabled by default but turned on/off via security policies. int main() { BEGIN_TEST(); if (!s2n_pq_is_enabled()) { END_TEST();
codereview_cpp_data_10758
PropagationData peers; std::transform( ids.begin(), ids.end(), std::back_inserter(peers), [](auto &s) { - return makePeer(s, empty_pubkey); }); return peers; } Public key can be constructed from string - `shared_model::interface::types::PubkeyType("")` PropagationData peers; std::transform( ids.begin(), ids.end(), std::back_inserter(peers), [](auto &s) { + return makePeer(s, shared_model::interface::types::PubkeyType("")); }); return peers; }
codereview_cpp_data_10772
break; case execution_mode::validation: case execution_mode::testing: - if (get_step() % cb->get_batch_interval() == 0) { - cb->on_batch_evaluate_begin(this); - } break; default: LBANN_ERROR("invalid execution mode"); I agree with making this the default behavior, but I worry it might introduce bugs in our other callbacks. We should make this change in a separate PR. break; case execution_mode::validation: case execution_mode::testing: + cb->on_batch_evaluate_begin(this); break; default: LBANN_ERROR("invalid execution mode");
codereview_cpp_data_10779
select_subset_of_data(); } -bool mesh_reader::fetch_datum(CPUMat& X, int data_id, int mb_idx, thread_pool& io_thread_pool) { - // int tid = io_thread_pool.get_local_thread_id(); if (m_random_flips) { fast_rng_gen& gen = get_fast_generator(); std::uniform_int_distribution<int> dist(0, 1); If this is not used, we should just delete the line. select_subset_of_data(); } +bool mesh_reader::fetch_datum(CPUMat& X, int data_id, int mb_idx) { if (m_random_flips) { fast_rng_gen& gen = get_fast_generator(); std::uniform_int_distribution<int> dist(0, 1);
codereview_cpp_data_10788
IdfObject idfObject(openstudio::IddObjectType::EnergyManagementSystem_Program); m_idfObjects.push_back(idfObject); - m_map.insert(std::make_pair(modelObject.handle(), idfObject)); //Name s = modelObject.name(); if (s) { Again, this shouldn't be here. IdfObject idfObject(openstudio::IddObjectType::EnergyManagementSystem_Program); m_idfObjects.push_back(idfObject); + //m_map.insert(std::make_pair(modelObject.handle(), idfObject)); //Name s = modelObject.name(); if (s) {
codereview_cpp_data_10792
class QueueBehaviorTest : public ::testing::Test { public: - QueueBehaviorTest(): ordering_gate(transport, 1, false) {}; void SetUp() override { - std::shared_ptr<OrderingGateTransport> transport = - std::make_shared<MockOrderingGateTransport>(); - std::shared_ptr<MockPeerCommunicationService> pcs = - std::make_shared<MockPeerCommunicationService>(); EXPECT_CALL(*pcs, on_commit()) .WillOnce(Return(commit_subject.get_observable())); It will not be possible to set any expects on this `transport` pointer because gmock type is erased, so OrderingGateTransport -> MockOrderingGateTransport class QueueBehaviorTest : public ::testing::Test { public: + QueueBehaviorTest() : ordering_gate(transport, 1, false){}; void SetUp() override { + transport = std::make_shared<MockOrderingGateTransport>(); + pcs = std::make_shared<MockPeerCommunicationService>(); EXPECT_CALL(*pcs, on_commit()) .WillOnce(Return(commit_subject.get_observable()));
codereview_cpp_data_10793
// setup cursor const CursorRestorer cursorRestorer( true, Cursor::POINTER ); - const u32 min = std::min( 1u, redistributeMax ); const int spacer = 10; const int defaultYPosition = 160; :warning: **readability\-uppercase\-literal\-suffix** :warning: integer literal has suffix `` u ``, which is not uppercase ```suggestion const u32 min = std::min( 1U, redistributeMax ); ``` // setup cursor const CursorRestorer cursorRestorer( true, Cursor::POINTER ); + const u32 min = std::min( 1U, redistributeMax ); const int spacer = 10; const int defaultYPosition = 160;
codereview_cpp_data_10797
// We don't have to look into the synopses for type queries, just // at the layout names. result_type result; - for (auto& [part_id, part_syn] : synopses_) for (auto& pair : part_syn) { // TODO: provide an overload for view of evaluate() so that // we can use string_view here. Fortunately type names are Let's be consistent with curly braces surrounding loop bodys. The inner loop has them, so the outer loop should too. I would also prefer to not remove them despite that being an option, because they generally help with readability. // We don't have to look into the synopses for type queries, just // at the layout names. result_type result; + for (auto& [part_id, part_syn] : synopses_) { for (auto& pair : part_syn) { // TODO: provide an overload for view of evaluate() so that // we can use string_view here. Fortunately type names are
codereview_cpp_data_10801
// List the device outputs we wish to display during the simulation. std::vector<std::string> deviceOutputs{ "length", "tension", "power" }; - std::vector<std::string> controllerOutputs{ "myo_control" }; // Add a ConsoleReporter to report deviceOutputs. //addDeviceConsoleReporterToModel(testbed, *device, deviceOutputs, - // controllerOutputs); // Create the system, initialize the state, and simulate. SimTK::State& sDev = testbed.initSystem(); I think this should be `deviceControllerOutputs` to reinforce the ownership tree (i.e., that the controller is owned by the device). // List the device outputs we wish to display during the simulation. std::vector<std::string> deviceOutputs{ "length", "tension", "power" }; + std::vector<std::string> deviceControllerOutputs{ "myo_control" }; // Add a ConsoleReporter to report deviceOutputs. //addDeviceConsoleReporterToModel(testbed, *device, deviceOutputs, + // deviceControllerOutputs); // Create the system, initialize the state, and simulate. SimTK::State& sDev = testbed.initSystem();
codereview_cpp_data_10809
ch->writerGUID = c_Guid_Unknown; ch->serializedPayload.length = 0; ch->serializedPayload.pos = 0; - for(uint8_t i=0;i<16;++i) - ch->instanceHandle.value[i] = 0; ch->isRead = 0; ch->sourceTimestamp.seconds(0); ch->sourceTimestamp.fraction(0); Use memset here (needs `#include <cstring># ch->writerGUID = c_Guid_Unknown; ch->serializedPayload.length = 0; ch->serializedPayload.pos = 0; + memset(ch->instanceHandle.value, 0, 16); ch->isRead = 0; ch->sourceTimestamp.seconds(0); ch->sourceTimestamp.fraction(0);
codereview_cpp_data_10811
*/ /* HIT_START - * BUILD: %t %s ../../test_common.cpp EXCLUDE_HIP_PLATFORM nvcc * TEST: %t * HIT_END */ Why is this disabled on cuda path? Looking at your previous changes in this ticket, I think the issue is that you are trying to use the same context on all the threads. Creating a new context for the same device on all the threads should fix the cuda path. */ /* HIT_START + * BUILD: %t %s ../../test_common.cpp NVCC_OPTIONS -std=c++11 * TEST: %t * HIT_END */
codereview_cpp_data_10815
FontSize size = this->DefaultSize(); if (str != NULL) *str = text; for (WChar c = Utf8Consume(&text); c != '\0'; c = Utf8Consume(&text)) { - - if (c >= SCC_NORMALFONT && c <= SCC_MONOFONT) { - size = (FontSize)(c - SCC_NORMALFONT); } else if (!IsInsideMM(c, SCC_SPRITE_START, SCC_SPRITE_END) && IsPrintable(c) && !IsTextDirectionChar(c) && c != '?' && GetGlyph(size, c) == question_mark[size]) { /* The character is printable, but not in the normal font. This is the case we were testing for. */ return true; The blank line is out of place. FontSize size = this->DefaultSize(); if (str != NULL) *str = text; for (WChar c = Utf8Consume(&text); c != '\0'; c = Utf8Consume(&text)) { + if (c >= SCC_FIRST_FONT && c <= SCC_LAST_FONT) { + size = (FontSize)(c - SCC_FIRST_FONT); } else if (!IsInsideMM(c, SCC_SPRITE_START, SCC_SPRITE_END) && IsPrintable(c) && !IsTextDirectionChar(c) && c != '?' && GetGlyph(size, c) == question_mark[size]) { /* The character is printable, but not in the normal font. This is the case we were testing for. */ return true;
codereview_cpp_data_10817
namespace { shared_model::interface::types::TimestampType oldestTimestamp( const iroha::BatchPtr &batch) { auto timestamps = batch->transactions() | boost::adaptors::transformed( It looks like assertion will check only case when batch is empty so maybe better check this explicitly? Also if empty batches are invalid here may be `optional<TimestampType>` will be a better choice? Technically 0 is a valid value (even though pretty unlikely). namespace { shared_model::interface::types::TimestampType oldestTimestamp( const iroha::BatchPtr &batch) { + const bool batch_is_empty = boost::empty(batch->transactions()); + assert(not batch_is_empty); + if (batch_is_empty) { + return 0; + } auto timestamps = batch->transactions() | boost::adaptors::transformed(
codereview_cpp_data_10829
#define IfFailRet(EXPR) do { Status = (EXPR); if(FAILED(Status)) { return (Status); } } while (0) #endif -bool IsWindowsTarget() -{ - return (g_pRuntime->GetRuntimeConfiguration() == IRuntime::WindowsCore) || - (g_pRuntime->GetRuntimeConfiguration() == IRuntime::WindowsDesktop); -} - #ifdef FEATURE_PAL #define MINIDUMP_NOT_SUPPORTED() This seems like it should be in runtime.cpp with an extern in runtime.h. It may be useful in files other than strike.cpp. #define IfFailRet(EXPR) do { Status = (EXPR); if(FAILED(Status)) { return (Status); } } while (0) #endif #ifdef FEATURE_PAL #define MINIDUMP_NOT_SUPPORTED()
codereview_cpp_data_10832
CoinAccessor::CoinAccessor(const CCoinsViewCache &view, const uint256 &txid) : cache(&view), lock(cache->csCacheInsert) { - cache->cs_utxo.lock_shared(); EnterCritical("CCoinsViewCache.cs_utxo", __FILE__, __LINE__, (void *)(&cache->cs_utxo)); COutPoint iter(txid, 0); coin = &emptyCoin; while (iter.n < nMaxOutputsPerBlock) is the lock stack getting updated properly when doing EnterCritical() and when in DEBUG_LOCKORDER, in the same way it does when we used ENTER_CRITICAL_SECTION()? CoinAccessor::CoinAccessor(const CCoinsViewCache &view, const uint256 &txid) : cache(&view), lock(cache->csCacheInsert) { EnterCritical("CCoinsViewCache.cs_utxo", __FILE__, __LINE__, (void *)(&cache->cs_utxo)); + cache->cs_utxo.lock_shared(); COutPoint iter(txid, 0); coin = &emptyCoin; while (iter.n < nMaxOutputsPerBlock)
codereview_cpp_data_10834
} else { - const char *const* p = { NULL }; g_variant_builder_add (&metadata_builder, "{sv}", "rpmostree.packages", g_variant_new_strv (p, -1)); Kind of wonder if we need both the flag and the version...we could just combine them so `rpmostree.serverbase` is of type `u`. Admittedly not symmetric with clientlayer then. } else { + const char *const p[] = { NULL }; g_variant_builder_add (&metadata_builder, "{sv}", "rpmostree.packages", g_variant_new_strv (p, -1));
codereview_cpp_data_10838
namespace parse { namespace detail { condition_parser_rules_3::condition_parser_rules_3( const parse::lexer& tok, - parse::detail::Labeller& labeller, const condition_parser_grammar& condition_parser, const parse::value_ref_grammar<std::string>& string_grammar ) : Is the `parse::detail::` necessary? This is already in that namespace. namespace parse { namespace detail { condition_parser_rules_3::condition_parser_rules_3( const parse::lexer& tok, + Labeller& labeller, const condition_parser_grammar& condition_parser, const parse::value_ref_grammar<std::string>& string_grammar ) :
codereview_cpp_data_10842
const consensus::RejectRoundType kNextCommitRoundConsumer = kFirstRejectRound; - consensus::Round nextCommitRound(consensus::Round round) { return {round.block_round + 1, kFirstRejectRound}; } - consensus::Round nextRejectRound(consensus::Round round) { return {round.block_round, round.reject_round + 1}; } Maybe rework it with const ref? const consensus::RejectRoundType kNextCommitRoundConsumer = kFirstRejectRound; + consensus::Round nextCommitRound(const consensus::Round &round) { return {round.block_round + 1, kFirstRejectRound}; } + consensus::Round nextRejectRound(const consensus::Round &round) { return {round.block_round, round.reject_round + 1}; }
codereview_cpp_data_10844
* overloaded to accommodate (mathematical) field operations. */ #include <cmath> #include <iostream> #include <stdexcept> -#include <cassert> /** * Class Complex to represent complex numbers as a field. maybe put the complex number within parentheses? * overloaded to accommodate (mathematical) field operations. */ +#include <cassert> #include <cmath> +#include <complex> #include <iostream> #include <stdexcept> /** * Class Complex to represent complex numbers as a field.
codereview_cpp_data_10868
return sounds.rangeAttack; } return sounds.meleeAttack; } Why meleeAttack sound can be M82::UNKNOWN, but rangeAttack isn't? return sounds.rangeAttack; } + assert( sounds.meleeAttack != M82::UNKNOWN ); return sounds.meleeAttack; }
codereview_cpp_data_10870
} break; case LONG_OPT_DISABLE_BATCH_CACHE: - cache_mode = 1; break; case LONG_OPT_WQ_WAIT_FOR_WORKERS: wq_wait_queue_size = optarg; cache_mode = 1 should be with cache on, otherwise it gets confusing with the double negatives. } break; case LONG_OPT_DISABLE_BATCH_CACHE: + cache_mode = 0; break; case LONG_OPT_WQ_WAIT_FOR_WORKERS: wq_wait_queue_size = optarg;