id
stringlengths
21
25
content
stringlengths
164
2.33k
codereview_cpp_data_8626
repl_module = swift_ast->GetModule(g_repl_module_name, error); if (repl_module == nullptr) { - swift::ModuleDecl *repl_module = nullptr; repl_module = swift_ast->CreateModule(g_repl_module_name, error); const swift::SourceFile::ImplicitModuleImportKind implicit_import_kind = swift::SourceFile::ImplicitModuleImportKind::Stdlib; Isn't that redundant? repl_module = swift_ast->GetModule(g_repl_module_name, error); if (repl_module == nullptr) { repl_module = swift_ast->CreateModule(g_repl_module_name, error); const swift::SourceFile::ImplicitModuleImportKind implicit_import_kind = swift::SourceFile::ImplicitModuleImportKind::Stdlib;
codereview_cpp_data_8636
*/ #include "mega/utils.h" -#include "mega/base64.h" namespace mega { Cachable::Cachable() We don't need bases64 here if the `pubk` parameter is in a binary format already. */ #include "mega/utils.h" namespace mega { Cachable::Cachable()
codereview_cpp_data_8640
client->isNewSession = false; } - fireOnRequestFinish(new MegaRequestPrivate(request), megaError); - #ifdef ENABLE_SYNC - if (e == API_OK && resumeSyncs) { resumeActiveSyncs(request->getListener()); } #endif } else // TYPE_CREATE_ACCOUNT { Same than above: no new request, no `onRequestFinish()` yet client->isNewSession = false; } #ifdef ENABLE_SYNC + if (e == API_OK) { resumeActiveSyncs(request->getListener()); } #endif + + fireOnRequestFinish(request, megaError); } else // TYPE_CREATE_ACCOUNT {
codereview_cpp_data_8653
plr[rid]._pInvincible = FALSE; #ifndef HELLFIRE PlacePlayer(rid); hp = 640; if (plr[rid]._pMaxHPBase < 640) { hp = plr[rid]._pMaxHPBase; } -#else - hp = 640; #endif SetPlayerHitPoints(rid, hp); I would prefer two hellfire `ifdef`s to an `else`. plr[rid]._pInvincible = FALSE; #ifndef HELLFIRE PlacePlayer(rid); +#endif hp = 640; +#ifndef HELLFIRE if (plr[rid]._pMaxHPBase < 640) { hp = plr[rid]._pMaxHPBase; } #endif SetPlayerHitPoints(rid, hp);
codereview_cpp_data_8658
*/ const int linkStart = 0; -int lineCount = 0; static inline int linkPossible (int old, int new) { return (old == 0 || old == 5) && new == 2; If possible this should be avoided. For this kind of tools its ok, but it is definitely a code smell. */ const int linkStart = 0; static inline int linkPossible (int old, int new) { return (old == 0 || old == 5) && new == 2;
codereview_cpp_data_8669
void ServerRunner::shutdown() { serverInstance_->Shutdown(); - while (!commandServiceHandler_->isShutdownCompletionQueue()) usleep(1); // wait for shutting down completion queue commandServiceHandler_->shutdown(); } Is it need? void ServerRunner::shutdown() { serverInstance_->Shutdown(); + while (!commandServiceHandler_->isShutdownCompletionQueue()) { usleep(1); // wait for shutting down completion queue + } commandServiceHandler_->shutdown(); }
codereview_cpp_data_8672
comm->intermodel_gather(score, score_list); comm->intermodel_gather(score_samples, num_samples_list); for (int i = 0; i < num_models; ++i) { - std::cout << "Model " << i << " " << m->get_name() << " " << mode_string << " " << met->name() << " : " << score_list[i] << met->get_unit() << std::endl; I think this is going to be misleading. A better output string would be: ``` Model "gen" (instance 2) training mean squared error: 12.345 ``` comm->intermodel_gather(score, score_list); comm->intermodel_gather(score_samples, num_samples_list); for (int i = 0; i < num_models; ++i) { + std::cout << "Model " << m->get_name() << " (instance " << i << ") " << mode_string << " " << met->name() << " : " << score_list[i] << met->get_unit() << std::endl;
codereview_cpp_data_8673
fz >> World::Get() >> conf >> GameOver::Result::Get() >> GameStatic::Data::Get(); // Settings should contain the full path to the current map file, if this map is available conf.SetMapsFile( Settings::GetLastFile( "maps", System::GetUniversalBasename( conf.MapsFile() ) ) ); // TODO: starting from 0.9.5 we do not write any data related to monsters. Remove reading the information for Monsters once minimum supported version is 0.9.5. If is correct that this call is needed only for saves which were made before these changes? fz >> World::Get() >> conf >> GameOver::Result::Get() >> GameStatic::Data::Get(); // Settings should contain the full path to the current map file, if this map is available + static_assert( LAST_SUPPORTED_FORMAT_VERSION < FORMAT_VERSION_095_RELEASE, "Remove the System::GetUniversalBasename()" ); conf.SetMapsFile( Settings::GetLastFile( "maps", System::GetUniversalBasename( conf.MapsFile() ) ) ); // TODO: starting from 0.9.5 we do not write any data related to monsters. Remove reading the information for Monsters once minimum supported version is 0.9.5.
codereview_cpp_data_8691
QString JobQueue::pop() { _mutex.lock(); - QString job = *_jobs.begin(); - _jobs.erase(_jobs.begin()); _mutex.unlock(); return job; } I think you have a race condition here. It is possible that queue->empty() could return false, then another thread pops the last job which would cause you to enter this method with a bad job name. Possibly have pop return an empty string if there are no more names, then you could pop and check for empty in a single call which would be atomic. QString JobQueue::pop() { _mutex.lock(); + QString job; + // Don't try to erase a job from an empty queue + if (!_jobs.empty()) + { + job = *_jobs.begin(); + _jobs.erase(_jobs.begin()); + } _mutex.unlock(); return job; }
codereview_cpp_data_8710
/* Should throw an error if rewriting would require an invalid stuffer state. * ( A write cursor being greater than the high water mark is an invalid stuffer state.) */ reservation.write_cursor = stuffer.high_water_mark + 1; - EXPECT_FAILURE_WITH_ERRNO(s2n_stuffer_write_reservation(reservation, 0), S2N_ERR_SAFETY); EXPECT_EQUAL(stuffer.write_cursor, expected_write_cursor); /* Happy case: successfully rewrites a uint16_t */ how long does this take? /* Should throw an error if rewriting would require an invalid stuffer state. * ( A write cursor being greater than the high water mark is an invalid stuffer state.) */ reservation.write_cursor = stuffer.high_water_mark + 1; + EXPECT_FAILURE_WITH_ERRNO(s2n_stuffer_write_reservation(reservation, 0), S2N_ERR_PRECONDITION_VIOLATION); EXPECT_EQUAL(stuffer.write_cursor, expected_write_cursor); /* Happy case: successfully rewrites a uint16_t */
codereview_cpp_data_8715
LOG(NET, "more getheaders (%d) to end to peer=%s (startheight:%d)\n", pindexLast->nHeight, pfrom->GetLogName(), pfrom->nStartingHeight); pfrom->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256()); - CNodeState* state = State(pfrom->GetId()); - if (state) state->nSyncStartTime = GetTime(); // reset the time because more headers needed // During the process of IBD we need to update block availability for every connected peer. To do that we // request, from each NODE_NETWORK peer, a header that matches the last blockhash found in this recent set // of headers. Once the reqeusted header is received then the block availability for this peer will get nit -> leave a newline after this ... Also need a dbgassert here LOG(NET, "more getheaders (%d) to end to peer=%s (startheight:%d)\n", pindexLast->nHeight, pfrom->GetLogName(), pfrom->nStartingHeight); pfrom->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256()); + + CNodeState *state = State(pfrom->GetId()); + DbgAssert(state != nullptr, ); + if (state) + state->nSyncStartTime = GetTime(); // reset the time because more headers needed + // During the process of IBD we need to update block availability for every connected peer. To do that we // request, from each NODE_NETWORK peer, a header that matches the last blockhash found in this recent set // of headers. Once the reqeusted header is received then the block availability for this peer will get
codereview_cpp_data_8719
El::Matrix<TensorDataType, Device>& mat) { El::EntrywiseMap( mat, - {[](TensorDataType const& a) -> TensorDataType { return El::Sqrt(a); }}); } template <typename TensorDataType, data_layout Layout, El::Device Device> ```suggestion {[](TensorDataType const& a) { return El::Sqrt(a); }}); ``` El::Matrix<TensorDataType, Device>& mat) { El::EntrywiseMap( mat, + {[](TensorDataType const& a) { return El::Sqrt(a); }}); } template <typename TensorDataType, data_layout Layout, El::Device Device>
codereview_cpp_data_8722
GUARD(s2n_stuffer_write_uint16(out, total_size)); /* Write server name extension */ - if (s2n_server_should_send_server_name(conn)) { GUARD(s2n_stuffer_write_uint16(out, TLS_EXTENSION_SERVER_NAME)); GUARD(s2n_stuffer_write_uint16(out, 0)); } Same thing above (L49)? GUARD(s2n_stuffer_write_uint16(out, total_size)); /* Write server name extension */ + if (s2n_server_can_send_server_name(conn)) { GUARD(s2n_stuffer_write_uint16(out, TLS_EXTENSION_SERVER_NAME)); GUARD(s2n_stuffer_write_uint16(out, 0)); }
codereview_cpp_data_8727
{ S2N_ERR_ECDHE_GEN_KEY, "Failed to generate an ECDHE key" }, { S2N_ERR_ECDHE_SHARED_SECRET, "Error computing ECDHE shared secret" }, { S2N_ERR_ECDHE_UNSUPPORTED_CURVE, "Unsupported EC curve was presented during an ECDHE handshake" }, - { S2N_ERR_ECDHE_SERIALIZING, "Error serializing ECDHE public" } }; const char *s2n_strerror(int error, const char *lang) why not leave the ',' on the end? makes for less changes when adding new items here { S2N_ERR_ECDHE_GEN_KEY, "Failed to generate an ECDHE key" }, { S2N_ERR_ECDHE_SHARED_SECRET, "Error computing ECDHE shared secret" }, { S2N_ERR_ECDHE_UNSUPPORTED_CURVE, "Unsupported EC curve was presented during an ECDHE handshake" }, + { S2N_ERR_ECDHE_SERIALIZING, "Error serializing ECDHE public" }, }; const char *s2n_strerror(int error, const char *lang)
codereview_cpp_data_8731
connect(priceTagSource0, SIGNAL(toggled(bool)), this, SLOT(radioPriceTagSourceClicked(bool))); connect(priceTagSource1, SIGNAL(toggled(bool)), this, SLOT(radioPriceTagSourceClicked(bool))); QGridLayout *generalGrid = new QGridLayout; generalGrid->addWidget(priceTagsCheckBox, 0, 0); generalGrid->addWidget(priceTagSource0, 1, 0); Can you make this an enum? Also add a default case so that someone can't break it by messing with their settings file connect(priceTagSource0, SIGNAL(toggled(bool)), this, SLOT(radioPriceTagSourceClicked(bool))); connect(priceTagSource1, SIGNAL(toggled(bool)), this, SLOT(radioPriceTagSourceClicked(bool))); + connect(this, SIGNAL(priceTagSourceChanged(int)), settingsCache, SLOT(setPriceTagSource(int))); + QGridLayout *generalGrid = new QGridLayout; generalGrid->addWidget(priceTagsCheckBox, 0, 0); generalGrid->addWidget(priceTagSource0, 1, 0);
codereview_cpp_data_8734
auto src = unbox(caf::get_if<view<address>>(&src_field)); CHECK_EQUAL(src, unbox(to<address>("192.168.1.1"))); auto community_id_at = [&](size_t row) { - auto id_field = slice->at(row, 6); return unbox(caf::get_if<view<std::string>>(&id_field)); }; for (size_t row = 0; row < 44; ++row) Can we lookup by field for extra robustness? auto src = unbox(caf::get_if<view<address>>(&src_field)); CHECK_EQUAL(src, unbox(to<address>("192.168.1.1"))); auto community_id_at = [&](size_t row) { + auto id_field = slice->at(row, 5); return unbox(caf::get_if<view<std::string>>(&id_field)); }; for (size_t row = 0; row < 44; ++row)
codereview_cpp_data_8744
return 0; } - h2o_probe_log_request(&stream->req, stream->quic->stream_id); - /* change state */ set_state(stream, H2O_HTTP3_SERVER_STREAM_STATE_RECV_BODY_BEFORE_BLOCK); Should we better log the request headers at an earlier point? I'd assume that we'd want to log the request headers whenever we log the response headers. However, this line would never be executed when `h2o_send_error_4xx` functions are called in the lines above. return 0; } /* change state */ set_state(stream, H2O_HTTP3_SERVER_STREAM_STATE_RECV_BODY_BEFORE_BLOCK);
codereview_cpp_data_8756
/* Determines if query_iana_id corresponds to a curve for these ECC preferences. */ bool s2n_ecc_preferences_includes(const struct s2n_ecc_preferences *ecc_preferences, uint16_t query_iana_id) { - notnull_check(ecc_preferences); for (size_t i = 0; i < ecc_preferences->count; i++) { if (query_iana_id == ecc_preferences->ecc_curves[i]->iana_id) { Do we want to error for cases when `query_iana_id` is not present in the list or is zero? /* Determines if query_iana_id corresponds to a curve for these ECC preferences. */ bool s2n_ecc_preferences_includes(const struct s2n_ecc_preferences *ecc_preferences, uint16_t query_iana_id) { + if (ecc_preferences == NULL) { + return false; + } for (size_t i = 0; i < ecc_preferences->count; i++) { if (query_iana_id == ecc_preferences->ecc_curves[i]->iana_id) {
codereview_cpp_data_8757
{ if (write (fd, buffer, sizeof (buffer)) != sizeof (buffer)) { - // save the error state but keep on writing in the hope that further writes wont't fail - error = 1; } } - if (error) - { - goto error; - } - return 1; error: Wouldn't that write a corrupted file? { if (write (fd, buffer, sizeof (buffer)) != sizeof (buffer)) { + goto error; } } return 1; error:
codereview_cpp_data_8761
void s2n_mem_init_harness() { /* Operation under verification. */ - if(s2n_mem_init( ) == S2N_SUCCESS) { assert(s2n_mem_is_init()); assert(s2n_mem_get_page_size() > 0); assert(s2n_mem_get_page_size() <= UINT32_MAX); We typically space between if and parenthesis. void s2n_mem_init_harness() { /* Operation under verification. */ + if( s2n_mem_init( ) == S2N_SUCCESS ) { assert(s2n_mem_is_init()); assert(s2n_mem_get_page_size() > 0); assert(s2n_mem_get_page_size() <= UINT32_MAX);
codereview_cpp_data_8762
#include <assert.h> struct wlr_output_layout_state { - struct wlr_box box; }; struct wlr_output_layout_output_state { struct wlr_output_layout *layout; struct wlr_output_layout_output *l_output; - struct wlr_box box; bool auto_configured; struct wl_listener resolution; I put an underscore here to emphasize that you should never read this, but only use the getter. #include <assert.h> struct wlr_output_layout_state { + struct wlr_box _box; // should never be read directly, use the getter }; struct wlr_output_layout_output_state { struct wlr_output_layout *layout; struct wlr_output_layout_output *l_output; + struct wlr_box _box; // should never be read directly, use the getter bool auto_configured; struct wl_listener resolution;
codereview_cpp_data_8768
if ( spell.MovePoint() ) { text += '\n'; - text.append( _( "Move points: " ) ); - text += std::to_string( spell.MovePoint() ); } const uint32_t answer = Dialog::Message( _( "Transcribe Spell Scroll" ), text, Font::BIG, Dialog::YES | Dialog::NO ); In general, formatted strings (in form of "Move points: %{mp}") may be preferable in comparison with basic string concatenation in case we ever add support for right-to-left writing languages. Although of course such formatting requires a certain accuracy from translators. if ( spell.MovePoint() ) { text += '\n'; + text.append( _( "Move points: %{mp}" ) ); + StringReplace( text, "%{mp}", spell.MovePoint() ); } const uint32_t answer = Dialog::Message( _( "Transcribe Spell Scroll" ), text, Font::BIG, Dialog::YES | Dialog::NO );
codereview_cpp_data_8769
* be found * warnings will be reported to warningsKey */ -int ELEKTRA_PLUGIN_FUNCTION (resolver, filename)(Key * forKey, resolverHandle * p, Key * warningsKey) { if (!p) { there seem to be plenty of whitespace changes, please rerun scripts/reformat-source * be found * warnings will be reported to warningsKey */ +int ELEKTRA_PLUGIN_FUNCTION (resolver, filename) (Key * forKey, resolverHandle * p, Key * warningsKey) { if (!p) {
codereview_cpp_data_8793
} #define PROTO(T) \ - template class data_type_layer<T>; #define LBANN_INSTANTIATE_CPU_HALF #include "lbann/macros/instantiate.hpp" ```suggestion template class data_type_layer<T> ``` } #define PROTO(T) \ + template class data_type_layer<T> #define LBANN_INSTANTIATE_CPU_HALF #include "lbann/macros/instantiate.hpp"
codereview_cpp_data_8794
m_Port(port) { m_Context = zmq_ctx_new(); if (m_DebugMode) { // TODO verify port is unsigned int Does this need to be checked for validity in case it fails or will it always be guaranteed to succeed? m_Port(port) { m_Context = zmq_ctx_new(); + if (m_Context == nullptr || m_Context == NULL) + { + throw std::runtime_error("ERROR: Creating ZeroMQ context failed"); + } if (m_DebugMode) { // TODO verify port is unsigned int
codereview_cpp_data_8795
KeySet * contract = ksNew (4, keyNew ("system:/elektra/contract/highlevel/check/specproperlymounted", KEY_VALUE, "1", KEY_END), - keyNew ("system:/elektra/contract/highlevel/check/spectoken/token", KEY_VALUE, "d1987403dc0042f18511dba2b212e33303ae715b69593d924f82710986cc75c0", KEY_END), keyNew ("system:/elektra/contract/highlevel/helpmode/ignore/require", KEY_VALUE, "1", KEY_END), keyNew ("system:/elektra/contract/mountglobal/gopts", KEY_END), KS_END); Is properly needed? (Are there different checks?) ```suggestion keyNew ("system:/elektra/contract/highlevel/check/spec/mounted", KEY_VALUE, "1", KEY_END), ``` KeySet * contract = ksNew (4, keyNew ("system:/elektra/contract/highlevel/check/specproperlymounted", KEY_VALUE, "1", KEY_END), + keyNew ("system:/elektra/contract/highlevel/check/spectoken/token", KEY_VALUE, "446dd2d26ec422a78c5cf54da3dbce9d77d6625a593ff3f45ed6b941bf2e3606", KEY_END), keyNew ("system:/elektra/contract/highlevel/helpmode/ignore/require", KEY_VALUE, "1", KEY_END), keyNew ("system:/elektra/contract/mountglobal/gopts", KEY_END), KS_END);
codereview_cpp_data_8804
// bool cxxParserParseBlock(bool bExpectClosingBracket) { - cppSetExternalParserState(cppGetExternalParserState() + 1); bool bRet = cxxParserParseBlockInternal(bExpectClosingBracket); - cppSetExternalParserState(cppGetExternalParserState() - 1); return bRet; } Does Cxx parser uses the value returned from cppGetExternalParserState()? If not, how about introducing cppPushExternalParserState/cppPopExternalParserState(or inc/dec) instead of Get/Set? So you don't have to write +/- 1 for each invocation. // bool cxxParserParseBlock(bool bExpectClosingBracket) { + cppPushExternalParserBlock(); bool bRet = cxxParserParseBlockInternal(bExpectClosingBracket); + cppPopExternalParserBlock(); return bRet; }
codereview_cpp_data_8817
} bool open(const char* filename) { - char buf[256]; - sprintf(buf, "%s.gz", filename); gz = gzopen(buf, "wb"); return gz != 0; } `gzvprintf()` is relatively new addition. RHEL 6 users are not going to like you using it and I don't think RHEL 7 users either. Another problem is that it uses 8 kB buffer and at least team descriptions can be larger than that. } bool open(const char* filename) { + char buf[MAXPATHLEN]; + snprintf(buf, sizeof(buf), "%s.gz", filename); gz = gzopen(buf, "wb"); return gz != 0; }
codereview_cpp_data_8819
s2n_blocked_status blocked; EXPECT_NOT_NULL(conn); - return s2n_negotiate(conn, &blocked); /* verify client hello cb has been invoked */ EXPECT_EQUAL(ch_ctx->invoked, 1); - return S2N_SUCCESS; } int server_recv(struct s2n_connection *conn) Just wanted to verify this line, should the rest be removed? Or the `return` be removed? s2n_blocked_status blocked; EXPECT_NOT_NULL(conn); + int rc = s2n_negotiate(conn, &blocked); /* verify client hello cb has been invoked */ EXPECT_EQUAL(ch_ctx->invoked, 1); + return rc; } int server_recv(struct s2n_connection *conn)
codereview_cpp_data_8822
* extra file descriptor, the poll(2) call is straightforward * for this use case. */ - FD_ZERO(&wait_set); - FD_SET(fd, &wait_set); pfd_read.fd = fd + 1; pfd_read.events = POLLIN; Now variable `fd_set wait_set`, FD_ZERO and FD_SET are useless. * extra file descriptor, the poll(2) call is straightforward * for this use case. */ pfd_read.fd = fd + 1; pfd_read.events = POLLIN;
codereview_cpp_data_8823
void MegaApiImpl::startUploadForSupport(const char *localPath, MegaTransferListener *listener) { - return startUpload(false, localPath, nullptr, nullptr, "supportdrop@mega.nz", -1, 0, false, nullptr, false, false, listener); } void MegaApiImpl::startDownload(bool startFirst, MegaNode *node, const char* localPath, int folderTransferTag, const char *appData, MegaTransferListener *listener) Considering the relevance of this upload, perhaps we want to use the `startFirst = true`, indeed. Also, it could be useful to give the ownership of the file to the SDK, so it deletes it after the upload, by setting the `isSourceFileTemporary = true`. ```suggestion return startUpload(true, localPath, nullptr, nullptr, "supportdrop@mega.nz", -1, 0, false, nullptr, false, false, listener); ``` void MegaApiImpl::startUploadForSupport(const char *localPath, MegaTransferListener *listener) { + return startUpload(true, localPath, nullptr, nullptr, "supportdrop@mega.nz", -1, 0, false, nullptr, false, false, listener); } void MegaApiImpl::startDownload(bool startFirst, MegaNode *node, const char* localPath, int folderTransferTag, const char *appData, MegaTransferListener *listener)
codereview_cpp_data_8835
{ for (int n=0; n<ncomp; ++n) { - face_linear_face_interp(i,j,k,n,0,fine_arr[0],crse_arr[0],mask_arr[0],ratio); } }); }, No, we do not need a sync here, because they are on the same stream. Box sizes are irrelevant here. ```suggestion ``` { for (int n=0; n<ncomp; ++n) { + face_linear_face_interp_x(i,j,k,n,fine_arr[0],crse_arr[0],mask_arr[0],ratio); } }); },
codereview_cpp_data_8838
// The maximum length of a glyph's name is 31 chars. #define MAXGLYPHNAME_LEN 31 unsigned int selectmax = fvmv_selectmax < 0 ? fv->b.sf->glyphcnt : fvmv_selectmax; - char buf[selectmax * MAXGLYPHNAME_LEN], *pt; char titlebuf[50+strlen(fv->b.sf->fontname)+1]; GTextInfo label; int i,j,cnt; Let's avoid VLAs like this, just malloc it. This can easily lead to a stack overflow depending on how large this is. // The maximum length of a glyph's name is 31 chars. #define MAXGLYPHNAME_LEN 31 unsigned int selectmax = fvmv_selectmax < 0 ? fv->b.sf->glyphcnt : fvmv_selectmax; + char *buf = malloc(selectmax * MAXGLYPHNAME_LEN); + char *pt; char titlebuf[50+strlen(fv->b.sf->fontname)+1]; GTextInfo label; int i,j,cnt;
codereview_cpp_data_8841
bool Battle::Interface::IdleTroopsAnimation( void ) { - bool redrawNeeded = false; - if ( Battle::AnimateInfrequentDelay( Game::BATTLE_IDLE_DELAY ) ) { - redrawNeeded = arena.GetForce1().animateIdleUnits() || arena.GetForce2().animateIdleUnits(); } - return redrawNeeded; } void Battle::Interface::CheckGlobalEvents( LocalEvent & le ) It would be better if we return here immediately. Then we do not need **redrawNeeded** variable and at the end of this function's body we return `false`. bool Battle::Interface::IdleTroopsAnimation( void ) { if ( Battle::AnimateInfrequentDelay( Game::BATTLE_IDLE_DELAY ) ) { + return arena.GetForce1().animateIdleUnits() || arena.GetForce2().animateIdleUnits(); } + return false; } void Battle::Interface::CheckGlobalEvents( LocalEvent & le )
codereview_cpp_data_8858
Ef[2][2] = h_rate[2]/domain->zprd; Ef[0][1] = Ef[1][0] = 0.5 * h_rate[5]/domain->yprd; Ef[0][2] = Ef[2][0] = 0.5 * h_rate[4]/domain->zprd; - Ef[1][2] = Ef[2][1] = 0.5 * h_rate[3]/domain->xprd; // copy updated velocity/omega/angmom to the ghost particles // no need to do this if not shearing since comm->ghost_velocity is set Not clear on why this change is correct. Ef[2][2] = h_rate[2]/domain->zprd; Ef[0][1] = Ef[1][0] = 0.5 * h_rate[5]/domain->yprd; Ef[0][2] = Ef[2][0] = 0.5 * h_rate[4]/domain->zprd; + Ef[1][2] = Ef[2][1] = 0.5 * h_rate[3]/domain->zprd; // copy updated velocity/omega/angmom to the ghost particles // no need to do this if not shearing since comm->ghost_velocity is set
codereview_cpp_data_8874
mp_edpXML->loadXMLParticipantEndpoint(titleElement, pdata); EXPECT_EQ(pdata->m_RTPSParticipantName, "HelloWorldSubscriber"); EXPECT_EQ(pdata->m_readers.size(), (size_t)1); delete pdata; } pdata is created inside XMLEndpointParser, it does not need to be created in the Test, just to delete it. mp_edpXML->loadXMLParticipantEndpoint(titleElement, pdata); EXPECT_EQ(pdata->m_RTPSParticipantName, "HelloWorldSubscriber"); EXPECT_EQ(pdata->m_readers.size(), (size_t)1); + + // Delete the ReaderProxyData created inside loadXMLParticipantEndpoint + delete pdata->m_readers[0]; + + // Then delete StaticRTPSParticipantInfo delete pdata; }
codereview_cpp_data_8883
memset(ctx->_module_configs, 0, sizeof(*ctx->_module_configs) * config->_num_config_slots); static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; - static int once = 0; pthread_mutex_lock(&mutex); - if (once == 0) { - once++; - h2o_socketpool_register_loop(&ctx->globalconf->proxy.global_socketpool, loop); - } for (i = 0; config->hosts[i] != NULL; ++i) { h2o_hostconf_t *hostconf = config->hosts[i]; I think we do not need this change, as `h2o_socketpool_register_pool` has that check? memset(ctx->_module_configs, 0, sizeof(*ctx->_module_configs) * config->_num_config_slots); static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&mutex); + h2o_socketpool_register_loop(&ctx->globalconf->proxy.global_socketpool, loop); for (i = 0; config->hosts[i] != NULL; ++i) { h2o_hostconf_t *hostconf = config->hosts[i];
codereview_cpp_data_8886
} double tm2 = get_time(); do_preload_data_store(); - m_data_store->set_is_preloaded(); if(is_master()) { std::cout << "Preload complete; time: " << get_time() - tm2 << std::endl; } `preload_data_store()` calls `set_is_preloaded` internally, so it should be sufficient to replace ```c++ do_preload_data_store(); m_data_store->set_is_preloaded(); ``` with ```c++ preload_data_store(); ``` } double tm2 = get_time(); do_preload_data_store(); if(is_master()) { std::cout << "Preload complete; time: " << get_time() - tm2 << std::endl; }
codereview_cpp_data_8915
hypre_bndry.reset(new MLMGBndry(ba, dm, ncomp, geom)); hypre_bndry->setHomogValues(); - const Real* dx = linop.m_geom[amrlev][mglev].CellSize(); int crse_ratio = linop.m_coarse_data_crse_ratio > 0 ? linop.m_coarse_data_crse_ratio : 1; RealVect bclocation(AMREX_D_DECL(0.5*dx[0]*crse_ratio, 0.5*dx[1]*crse_ratio, I don't think this change is correct. hypre_bndry.reset(new MLMGBndry(ba, dm, ncomp, geom)); hypre_bndry->setHomogValues(); + const Real* dx = linop.m_geom[0][0].CellSize(); int crse_ratio = linop.m_coarse_data_crse_ratio > 0 ? linop.m_coarse_data_crse_ratio : 1; RealVect bclocation(AMREX_D_DECL(0.5*dx[0]*crse_ratio, 0.5*dx[1]*crse_ratio,
codereview_cpp_data_8920
return; } - static_args += 2 * cgroup_num_hierarchies(); if (opts->user->verbose) static_args++; Stupid question, but why `2 *`? :) return; } + if (cgroup_num_hierarchies() > 0) + static_args += 2 * cgroup_num_hierarchies(); if (opts->user->verbose) static_args++;
codereview_cpp_data_8925
double max_applied_impulse = m_use_multi_dof_params ? m_maxAppliedImpulseMultiDof[row % 3] : m_maxAppliedImpulse; fillMultiBodyConstraint(constraintRow, data, 0, 0, constraintNormalAng, btVector3(0,0,0), dummy, dummy, - posError + velocityError, infoGlobal, -max_applied_impulse, max_applied_impulse, true, 1.0, false, 0, 0, adding a velocityError here is a change in behavior. Also, there is a separate argument to add a desired relative velocity. If this change is required, it is best to create a separate PR/CL for that, so we can easily undo it (if it causes issues anywhere). double max_applied_impulse = m_use_multi_dof_params ? m_maxAppliedImpulseMultiDof[row % 3] : m_maxAppliedImpulse; fillMultiBodyConstraint(constraintRow, data, 0, 0, constraintNormalAng, btVector3(0,0,0), dummy, dummy, + posError, infoGlobal, -max_applied_impulse, max_applied_impulse, true, 1.0, false, 0, 0,
codereview_cpp_data_8928
{ bool has_child_methods = false; - if (is_dynamic_prop) - { - injectDynamicName (name, dprop); - dprop = NULL; - } - /* skip whatever is the value */ while (! isType (token, TOKEN_COMMA) && ! isType (token, TOKEN_CLOSE_CURLY) && couldn't that be done in the parent scope for both branches at once? e.g. move it anywhere between lines 1668 (in the `if (is_computed_name)` block) and 1678 (right before the branching that leads to these duplicated handling). { bool has_child_methods = false; /* skip whatever is the value */ while (! isType (token, TOKEN_COMMA) && ! isType (token, TOKEN_CLOSE_CURLY) &&
codereview_cpp_data_8944
conn->client = &conn->secure; /* The client session key might have been set to the early traffic key. - * This is not an problem for most libcrypto implementations, but in older - * versions of OpenSSL will cause a memory leak when we call init again. */ POSIX_GUARD(conn->secure.cipher_suite->record_alg->cipher->destroy_key(session_key)); } else { finished_data = conn->handshake.server_finished; Can we specifically call out the older versions of OpenSSL and remove the ambiguity, maybe say `in OpenSSL versions <= 1.0.2` instead of `in older versions of OpenSSL`? conn->client = &conn->secure; /* The client session key might have been set to the early traffic key. + * This is not an problem for most libcrypto implementations, but in + * OpenSSL < 1.1.0 will cause a memory leak when we call init again. */ POSIX_GUARD(conn->secure.cipher_suite->record_alg->cipher->destroy_key(session_key)); } else { finished_data = conn->handshake.server_finished;
codereview_cpp_data_8945
CHECK(test_hipDeviceGetAttribute(deviceId, hipDeviceAttributeMaxTexture3DWidth, props.maxTexture3D[0])); CHECK(test_hipDeviceGetAttribute(deviceId, hipDeviceAttributeMaxTexture3DHeight, props.maxTexture3D[1])); CHECK(test_hipDeviceGetAttribute(deviceId, hipDeviceAttributeMaxTexture3DDepth, props.maxTexture3D[2])); CHECK(test_hipDeviceGetHdpAddress(deviceId, hipDeviceAttributeHdpMemFlushCntl, props.hdpMemFlushCntl)); CHECK(test_hipDeviceGetHdpAddress(deviceId, hipDeviceAttributeHdpRegFlushCntl, props.hdpRegFlushCntl)); passed(); }; These two lines should not be executed on nvidia devices. So you probably need something like ```#ifndef __HIP_PLATFORM_NVCC__```. CHECK(test_hipDeviceGetAttribute(deviceId, hipDeviceAttributeMaxTexture3DWidth, props.maxTexture3D[0])); CHECK(test_hipDeviceGetAttribute(deviceId, hipDeviceAttributeMaxTexture3DHeight, props.maxTexture3D[1])); CHECK(test_hipDeviceGetAttribute(deviceId, hipDeviceAttributeMaxTexture3DDepth, props.maxTexture3D[2])); +#ifndef __HIP_PLATFORM_NVCC__ CHECK(test_hipDeviceGetHdpAddress(deviceId, hipDeviceAttributeHdpMemFlushCntl, props.hdpMemFlushCntl)); CHECK(test_hipDeviceGetHdpAddress(deviceId, hipDeviceAttributeHdpRegFlushCntl, props.hdpRegFlushCntl)); +#endif passed(); };
codereview_cpp_data_8958
file->name); flb_tail_file_remove(file); } - if (file->config->exit_on_eof) { - flb_info("[in_tail] file=%s ended, stop", file->name); - flb_engine_shutdown(config); - exit(0); - } break; } } would you please move this routine before the file gets promoted (few lines back) file->name); flb_tail_file_remove(file); } break; } }
codereview_cpp_data_8964
return 0; const uint32_t unitsLeft = ( hp - damageTaken ) / Monster::GetHitPoints(); - return unitsLeft * ( Monster::GetDamageMin() + Monster::GetDamageMax() ) / 2; } u32 Battle::Unit::CalculateMinDamage( const Unit & enemy ) const This is incorrect. We don't use Bless and Curse modificators here. return 0; const uint32_t unitsLeft = ( hp - damageTaken ) / Monster::GetHitPoints(); + + uint32_t damagePerUnit = 0; + if ( Modes( SP_CURSE ) ) + damagePerUnit = Monster::GetDamageMin(); + else if ( Modes( SP_BLESS ) ) + damagePerUnit = Monster::GetDamageMax(); + else + damagePerUnit = ( Monster::GetDamageMin() + Monster::GetDamageMax() ) / 2; + + return unitsLeft * damagePerUnit; } u32 Battle::Unit::CalculateMinDamage( const Unit & enemy ) const
codereview_cpp_data_8973
} const AccountResponse::AccountRolesIdType &AccountResponse::roles() const { - return accountRoles_; } } // namespace proto Please fix the naming of all the fields like that. Please use snake_case_ for them } const AccountResponse::AccountRolesIdType &AccountResponse::roles() const { + return account_roles_; } } // namespace proto
codereview_cpp_data_8974
try { LoadOpenSimLibrary("osimActuators"); testStates("arm26.osim"); - if (isGetRSSValid()) { - testMemoryUsage("arm26.osim"); - testMemoryUsage("PushUpToesOnGroundWithMuscles.osim"); - } } catch (const Exception& e) { cout << "testInitState failed: "; I don't think this is a good idea, as it will just silently skip the tests if `!isGetRSSValid()`. My understanding is that part of the motivation behind his PR was to be more strict about testing memory usage (e.g., not just allowing the test to pass if `mem1 < mem0`). If you want to check whether `getCurrentRSS()` is operating as expected, I suggest moving this part of the test to a new test case and throwing an exception if `!isGetRSSValid()`. We could then decide to merge a PR even if `getCurrentRSS()` malfunctions, but at least we would have that information. try { LoadOpenSimLibrary("osimActuators"); testStates("arm26.osim"); + testMemoryUsage("arm26.osim"); + testMemoryUsage("PushUpToesOnGroundWithMuscles.osim"); } catch (const Exception& e) { cout << "testInitState failed: ";
codereview_cpp_data_8977
void SynchronizerImpl::process_commit(network::Commit commit_message) { log_->info("processing commit"); - auto top_block_height = block_query_factory_->createBlockQuery() | - [](const auto &block_query) { - return block_query->getTopBlockHeight(); - }; const auto &block = commit_message.block; This will result in `uint32_t()` (which is 0) being assigned to `top_block_height` if `createBlockQuery` returns `boost::none`. This should be either refactored with two different statements (one for creating block query and checking it, and another for getting top block height) or returning optional from lambda with `getTopBlockHeight()`. void SynchronizerImpl::process_commit(network::Commit commit_message) { log_->info("processing commit"); + shared_model::interface::types::HeightType top_block_height{0}; + if (auto block_query = block_query_factory_->createBlockQuery()) { + top_block_height = (*block_query)->getTopBlockHeight(); + } else { + log_->error("Unable to retrieve top block height"); + return; + } const auto &block = commit_message.block;
codereview_cpp_data_9000
common_objects_factory_ = std::make_shared<shared_model::proto::ProtoCommonObjectsFactory< shared_model::validation::FieldValidator>>(); - perm_converter_ = std::make_shared<shared_model::proto::ProtoPermissionToString>(); auto block_converter = std::make_shared<shared_model::proto::ProtoBlockJsonConverter>(); For now, it isn't needed anywhere in `application` except this initialization. Maybe make it not a class variable, but a local one, and move? common_objects_factory_ = std::make_shared<shared_model::proto::ProtoCommonObjectsFactory< shared_model::validation::FieldValidator>>(); + auto perm_converter_ = std::make_shared<shared_model::proto::ProtoPermissionToString>(); auto block_converter = std::make_shared<shared_model::proto::ProtoBlockJsonConverter>();
codereview_cpp_data_9001
l.request_output_values == r.request_output_values && l.declare_optimization_goal == r.declare_optimization_goal; } -template <typename Callback, typename... Args> -void call_kokkos_callback(const Callback callback, bool ever_needs_fence, Args... args) { if (callback != nullptr) { - if ((ever_needs_fence) && (Kokkos::Tools::Experimental::tool_requirements - .requires_global_fencing)) { Kokkos::fence(); } (*callback)(args...); I think this would help optimize the call: ```suggestion #if __cplusplus >= 201703L # define KOKKOS_IF_CONSTEXPR if constexpr #else # define KOKKOS_IF_CONSTEXPR if #endif template <typename Callback, typename EverNeedsFence, typename... Args> void call_kokkos_callback(const Callback callback, EverNeedsFence, Args... args) { if (callback != nullptr) { // a macro for if constexpr is needed KOKKOS_IF_CONSTEXPR (EverNeedsFence::value) { if (Kokkos::Tools::Experimental::tool_requirements.requires_global_fencing) { Kokkos::fence(); } } (*callback)(args...); } } ``` Usage: ```cpp Kokkos::Tools::Experimental::call_kokkos_callback( Kokkos::Tools::Experimental::current_callbacks.begin_parallel_for, std::true_type{}, kernelPrefix.c_str(), devID, kernelID); ``` l.request_output_values == r.request_output_values && l.declare_optimization_goal == r.declare_optimization_goal; } +template <typename Callback, typename BooleanConstant, typename... Args> +void call_kokkos_callback(const Callback callback, BooleanConstant, Args... args) { if (callback != nullptr) { + if ((BooleanConstant::value) && + (Kokkos::Tools::Experimental::tool_requirements + .requires_global_fencing)) { Kokkos::fence(); } (*callback)(args...);
codereview_cpp_data_9006
(((client->handshake.handshake_type) & HELLO_RETRY_REQUEST) \ && ((server->handshake.handshake_type) & HELLO_RETRY_REQUEST)) -#define EXPECT_TICKETS_SENT(conn, count) do { \ - uint16_t _tickets_sent = 0; \ - EXPECT_SUCCESS(s2n_connection_get_tickets_sent(conn, &_tickets_sent)); \ - EXPECT_EQUAL(_tickets_sent, count); \ -} while(0); struct s2n_early_data_test_case { bool ticket_supported; Does this need to be a macro? (((client->handshake.handshake_type) & HELLO_RETRY_REQUEST) \ && ((server->handshake.handshake_type) & HELLO_RETRY_REQUEST)) +#define EXPECT_TICKETS_SENT(conn, count) EXPECT_OK(s2n_assert_tickets_sent(conn, count)) struct s2n_early_data_test_case { bool ticket_supported;
codereview_cpp_data_9007
wl_signal_emit(&layout->events.destroy, layout); - struct wlr_output_layout_output *output, *temp = NULL; - wl_list_for_each_safe(output, temp, &layout->outputs, link) { - wlr_output_layout_output_destroy(output); } free(layout->state); should be `l_output` for consistency with the rest of the code. wl_signal_emit(&layout->events.destroy, layout); + struct wlr_output_layout_output *l_output, *temp = NULL; + wl_list_for_each_safe(l_output, temp, &layout->outputs, link) { + wlr_output_layout_output_destroy(l_output); } free(layout->state);
codereview_cpp_data_9012
ipv6deactivationtime = Waiter::ds; // for IPv6 errors, try IPv4 before sending an error to the engine - if ((dnsEntry.ipv4.size() - && (!DNS_CACHE_EXPIRES || (Waiter::ds - dnsEntry.ipv4timestamp) < DNS_CACHE_TIMEOUT_DS)) - || httpctx->ares_pending) { numconnections[httpctx->d]--; pausedrequests[httpctx->d].erase(msg->easy_handle); What if `ares_pending` is greater than 0 because a IPv6 lookup is in-flight? Not sure if it's possible in this code-path ipv6deactivationtime = Waiter::ds; // for IPv6 errors, try IPv4 before sending an error to the engine + if ((dnsEntry.ipv4.size() && !dnsEntry.isIPv4Expired()) + || (!httpctx->isCachedIp && httpctx->ares_pending)) { numconnections[httpctx->d]--; pausedrequests[httpctx->d].erase(msg->easy_handle);
codereview_cpp_data_9019
return; } { struct phr_header src_headers[MAX_HEADERS]; /* parse response */ How about creating a memory pool as a local variable of the function (i.e. `h2o_mem_pool_t pool; h2o_mem_init_pool(&pool)` at the top scope of the function), and allocate memory from that pool instead of calling `h2o_strdup` (and `free`) for every header name? I believe that that would be a good optimization considering the fact that `h2o_mem_alloc_pool` is super-fast for small objects. We could also allocate `headers` of type `h2o_headers_t` using the pool (instead of `h2o_headers_t *headers[100]`). return; } + h2o_mem_init_pool(&pool); + + headers = h2o_mem_alloc_pool(&pool, sizeof(*headers) * MAX_HEADERS); + header_names = h2o_mem_alloc_pool(&pool, sizeof(*header_names) * MAX_HEADERS); + { struct phr_header src_headers[MAX_HEADERS]; /* parse response */
codereview_cpp_data_9025
if( !strmatch(tok,"ImageX:")) { #ifndef _NO_LIBPNG ImageList *img = SFDGetImagePNG(sfd); if ( !u->u.state.images ) A new ImageX label is fine (with me), but there shouldn't be new tags for every format that might be supported in the future. Move the reading of the mime type up to this level and for now print an error if it's not PNG. Then you can leave the file descriptor queued up to start reading the parameters (`width` etc.). That way other formats can also use `ImageX` as long as they specify the mime type immediately afterward. if( !strmatch(tok,"ImageX:")) { + enum MIME mime = SFDGetImageMIME(sfd); + if (mime == false) exit(1); #ifndef _NO_LIBPNG ImageList *img = SFDGetImagePNG(sfd); if ( !u->u.state.images )
codereview_cpp_data_9033
QMenu *Player::getCardMenu() const { - return aCardMenu->menu(); // can return nullptr } QString Player::getName() const I don't like the removal of a NP check QMenu *Player::getCardMenu() const { + if (aCardMenu != nullptr) { + return aCardMenu->menu(); + } else { + return nullptr; + } } QString Player::getName() const
codereview_cpp_data_9036
creatorNameFilter = QString(); gameTypeFilter.clear(); maxPlayersFilterMin = 1; - maxPlayersFilterMax = 99; invalidateFilter(); } I'd like to see the number here reused from a constant creatorNameFilter = QString(); gameTypeFilter.clear(); maxPlayersFilterMin = 1; + maxPlayersFilterMax = DEFAULT_MAX_PLAYERS_MAX; invalidateFilter(); }
codereview_cpp_data_9042
void USM_memcpy(void* dst, const void* src, size_t n) { Experimental::SYCL().fence(); - auto event = - USM_memcpy(*Kokkos::Experimental::Impl::SYCLInternal::singleton().m_queue, - dst, src, n); Experimental::Impl::SYCLInternal::fence(event); } } // namespace Be consistent within the body of that function ```suggestion USM_memcpy(*Experimental::Impl::SYCLInternal::singleton().m_queue, ``` void USM_memcpy(void* dst, const void* src, size_t n) { Experimental::SYCL().fence(); + auto event = USM_memcpy( + *Experimental::Impl::SYCLInternal::singleton().m_queue, dst, src, n); Experimental::Impl::SYCLInternal::fence(event); } } // namespace
codereview_cpp_data_9045
EdgeDistanceExtractor::EdgeDistanceExtractor(ValueAggregatorPtr a, Meters spacing): _aggregator(a) { setSpacing(spacing); } Again, should an "empty" shared pointer be replaced by the default aggregator? EdgeDistanceExtractor::EdgeDistanceExtractor(ValueAggregatorPtr a, Meters spacing): _aggregator(a) { + if (!_aggregator) + _aggregator.reset(new MeanAggregator()); + setSpacing(spacing); }
codereview_cpp_data_9049
* supplied as quaternions and registered onto a subject via labeled markers * * OR, by registering IMU rotations on to a model in the calibration pose. * * * -* Developed by AMJR Consulting for NSRDEC under subcontract No. XXXXXXXXX, * -* The Johns Hopkins University Applied Physics Laboratory (APL) * * * * Copyright (c) 2017-2019 AMJR Consulting and the Authors * * Author(s): Ajay Seth & Ayman Habib * Should be added to `OpenSenseUtilities` and the writing of the quaternions to file should NOT be baked into the method. Instead the writing to file is a convenience we can add here. * supplied as quaternions and registered onto a subject via labeled markers * * OR, by registering IMU rotations on to a model in the calibration pose. * * * +* Developed by AMJR Consulting under a contract and in a * +* collaborative effort with The Johns Hopkins University Applied Physics * +* Laboratory for a project sponsored by the United States Army Natick Soldier* +* Research Development and Engineering Center and supported by a the NAVAL * +* SEA SYSTEMS COMMAND (NAVSEA) under Contract No. N00024-13-D-6400, * +* Task Order #VKW02. Any opinions, findings, conclusions or recommendations * +* expressed in this material are those of the author(s) and do not * +* necessarily reflect the views of NAVSEA. * * * * Copyright (c) 2017-2019 AMJR Consulting and the Authors * * Author(s): Ajay Seth & Ayman Habib *
codereview_cpp_data_9058
} msg_info() << "Found " << m_linearSolvers.size() << " m_linearSolvers"; - for (auto & m_linearSolver : m_linearSolvers) - msg_info() << m_linearSolver->getName(); } void GenericConstraintCorrection::cleanup() ```suggestion for (auto & linearSolver : m_linearSolvers) msg_info() << linearSolver->getName(); ``` } msg_info() << "Found " << m_linearSolvers.size() << " m_linearSolvers"; + for (auto & linearSolver : m_linearSolvers) + msg_info() << linearSolver->getName(); } void GenericConstraintCorrection::cleanup()
codereview_cpp_data_9067
whitelist ${HOME}/.local/share/icons whitelist ${HOME}/.local/share/mime whitelist ${HOME}/.mime.types -whitelist ${HOME}/.uim.d whitelist ${HOME}/.sndio/cookie # dconf mkdir ${HOME}/.config/dconf ```suggestion whitelist ${HOME}/.sndio/cookie whitelist ${HOME}/.uim.d ``` whitelist ${HOME}/.local/share/icons whitelist ${HOME}/.local/share/mime whitelist ${HOME}/.mime.types whitelist ${HOME}/.sndio/cookie +whitelist ${HOME}/.uim.d # dconf mkdir ${HOME}/.config/dconf
codereview_cpp_data_9074
namespace { bool CompareByHost(const TabletReplica& a, const TabletReplica& b) { - TSRegistrationPB reg_a = a.ts_desc->GetRegistration(); - TSRegistrationPB reg_b = b.ts_desc->GetRegistration(); - if (!reg_a.common().http_addresses().empty() && !reg_b.common().http_addresses().empty()) { - return reg_a.common().http_addresses(0).host() < reg_b.common().http_addresses(0).host(); - } else { - return a.ts_desc->permanent_uuid() < b.ts_desc->permanent_uuid(); - } } } // anonymous namespace since permanent_uuid is generally expected to not be empty, and since our goal is only to have /some/ stable sorting of hosts, why dont we simplify this logic by always sorting by permanent_uuid? namespace { bool CompareByHost(const TabletReplica& a, const TabletReplica& b) { + return a.ts_desc->permanent_uuid() < b.ts_desc->permanent_uuid(); } } // anonymous namespace
codereview_cpp_data_9076
d->should_read_archive = should_read_archive; d->should_write_to_archive = should_write_to_archive; - /* Makeflow fails by default if we goto FAILURE_LABEL. This indicates we have correctly initialized. */ makeflow_failed_flag = 0; while not needed, I would suggest a goto EXIT_WITH_FAILURE here. d->should_read_archive = should_read_archive; d->should_write_to_archive = should_write_to_archive; + /* Makeflow fails by default if we goto EXIT_WITH_FAILURE. This indicates we have correctly initialized. */ makeflow_failed_flag = 0;
codereview_cpp_data_9085
model::RolesResponse res{}; std::copy(response.roles().begin(), response.roles().end(), - res.roles.begin()); return res; } Can't find `res.roles` allocation, missed `std::back_inserter`? model::RolesResponse res{}; std::copy(response.roles().begin(), response.roles().end(), + std::back_inserter(res.roles)); return res; }
codereview_cpp_data_9089
tz.setZoneControlContaminantController(controllerClone); } - if( auto t_color = renderingColor() ) { - auto colorClone = t_color->clone(model).cast<RenderingColor>(); - tz.setRenderingColor(colorClone); - } // DLM: do not clone zone mixing objects @jmarrec all objects need to do this in clone right? tz.setZoneControlContaminantController(controllerClone); } + // Note: rendering color is already handled via the fact that it's a children // DLM: do not clone zone mixing objects
codereview_cpp_data_9096
EnterCriticalSection(&sgMemCrit); if (nNumberOfBytesToWrite) { - if (log_file == (HANDLE)-1) { log_file = log_create(); - if (log_file == (HANDLE)-1) { nNumberOfBytesToWrite = 0; return; } `winbase.h` defines `#define INVALID_HANDLE_VALUE (HANDLE)-1`, could be used here :) EnterCriticalSection(&sgMemCrit); if (nNumberOfBytesToWrite) { + if (log_file == INVALID_HANDLE_VALUE) { log_file = log_create(); + if (log_file == INVALID_HANDLE_VALUE) { nNumberOfBytesToWrite = 0; return; }
codereview_cpp_data_9100
AttachChild(m_icon); m_link_text = new LinkText(GG::X0, GG::Y0, GG::X1, m_sitrep_entry.GetText() + " ", - ClientUI::GetFont(ClientUI::Pts()), GG::FORMAT_LEFT | GG::FORMAT_VCENTER | GG::FORMAT_WORDBREAK, ClientUI::TextColor()); m_link_text->SetDecorator(VarText::EMPIRE_ID_TAG, new ColorEmpire()); AttachChild(m_link_text); not sure what changed, but it wasn't this being fixed AttachChild(m_icon); m_link_text = new LinkText(GG::X0, GG::Y0, GG::X1, m_sitrep_entry.GetText() + " ", + ClientUI::GetFont(), GG::FORMAT_LEFT | GG::FORMAT_VCENTER | GG::FORMAT_WORDBREAK, ClientUI::TextColor()); m_link_text->SetDecorator(VarText::EMPIRE_ID_TAG, new ColorEmpire()); AttachChild(m_link_text);
codereview_cpp_data_9108
namespace { - auto getPressedBuildingHotkey() -> building_t { if ( HotKeyPressEvent( Game::EVENT_TOWN_CREATURE_1 ) ) { return DWELLING_MONSTER1; Why can't we just do `building_t getPressedBuildingHotkey()` ? namespace { + building_t getPressedBuildingHotkey() { if ( HotKeyPressEvent( Game::EVENT_TOWN_CREATURE_1 ) ) { return DWELLING_MONSTER1;
codereview_cpp_data_9125
if (!rel->auto_prune && !g_hash_table_contains (used_refs, rel->ref)) { g_autofree char *related_origin = NULL; related_origin = flatpak_dir_get_origin (dir, rel->ref, NULL, NULL); if (related_origin != NULL) find_used_refs (dir, used_refs, rel->ref, related_origin); - - g_hash_table_add (used_refs, g_strdup (rel->ref)); } } } I think you need to add to used_ref before recursing, because otherwise you could accidentally get stuck in a loop in case some related ref is related to the original ref. if (!rel->auto_prune && !g_hash_table_contains (used_refs, rel->ref)) { g_autofree char *related_origin = NULL; + + g_hash_table_add (used_refs, g_strdup (rel->ref)); + related_origin = flatpak_dir_get_origin (dir, rel->ref, NULL, NULL); if (related_origin != NULL) find_used_refs (dir, used_refs, rel->ref, related_origin); } } }
codereview_cpp_data_9132
// This shouldn't happen, as the SELECT is bounded by MAXTASKS LogTasks( - "Error: Task or activity_information ID ([{}], [{}]) out of range while loading activities from database", task_id, activity_id ); Missing fmt string braces for `activity_id` // This shouldn't happen, as the SELECT is bounded by MAXTASKS LogTasks( + "[LoadTasks] Error: Task or activity_information ID ([{}], [{}]) out of range while loading activities from database", task_id, activity_id );
codereview_cpp_data_9155
request->setSessionKey(sid.c_str()); // chain a fetchnodes to get waitlink for ephemeral account - requestMap.erase(request->getTag()); - int nextTag = client->nextreqtag(); - request->setTag(nextTag); - requestMap[nextTag] = request; - client->fetchnodes(); } void MegaApiImpl::sendsignuplink_result(error e) don't we need ``` resetTotalDownloads(); resetTotalUploads(); ``` here? request->setSessionKey(sid.c_str()); // chain a fetchnodes to get waitlink for ephemeral account + int creqtag = client->reqtag; + client->reqtag = client->restag; client->fetchnodes(); + client->reqtag = creqtag; } void MegaApiImpl::sendsignuplink_result(error e)
codereview_cpp_data_9160
if(p) { *p = 0; if(!work_queue_task_specify_file(t, f, p + 1, WORK_QUEUE_INPUT, caching_flag)){ - fatal("Failed to specify file %s->%s in Work Queue", f, p+1); } *p = '='; } else { if(!work_queue_task_specify_file(t, f, f, WORK_QUEUE_INPUT, caching_flag)){ - fatal("Failed to specify file %s in Work Queue", f); } } f = strtok(0, " \t,"); Message is confusing, as the file was specified. You want something like: Error while specifying file. if(p) { *p = 0; if(!work_queue_task_specify_file(t, f, p + 1, WORK_QUEUE_INPUT, caching_flag)){ + fatal("Error while specifying file: %s->%s.", f, p+1); } *p = '='; } else { if(!work_queue_task_specify_file(t, f, f, WORK_QUEUE_INPUT, caching_flag)){ + fatal("Error while specifying file: %s.", f); } } f = strtok(0, " \t,");
codereview_cpp_data_9161
auto current_time = time_provider_->getCurrentTime(); auto size = data.size(); std::for_each( - data.begin(), data.end(), [this, &current_time, &size](const auto &peer) { auto diff = storage_->getDiffState(peer, current_time); if (not diff.isEmpty()) { log_->info("Propagate new data[{}]", size); it's better capture by value auto current_time = time_provider_->getCurrentTime(); auto size = data.size(); std::for_each( + data.begin(), data.end(), [this, &current_time, size](const auto &peer) { auto diff = storage_->getDiffState(peer, current_time); if (not diff.isEmpty()) { log_->info("Propagate new data[{}]", size);
codereview_cpp_data_9170
return false; } -bool ArtifactsBar::ActionBarCursor( const fheroes2::Point &, Artifact & art, const fheroes2::Rect & ) { if ( isSelected() ) { const Artifact * art2 = GetSelectedItem(); :warning: **readability\-named\-parameter** :warning: all parameters should be named in a function ```suggestion bool ArtifactsBar::ActionBarCursor( const fheroes2::Point & /*unused*/, Artifact & art, const fheroes2::Rect & /*unused*/) ``` return false; } +bool ArtifactsBar::ActionBarCursor( const fheroes2::Point & /*unused*/, Artifact & art, const fheroes2::Rect & /*unused*/) { if ( isSelected() ) { const Artifact * art2 = GetSelectedItem();
codereview_cpp_data_9175
rpmostree_origin_set_regenerate_initramfs (origin, self->regenerate, self->args); rpmostree_sysroot_upgrader_set_origin (upgrader, origin); - RpmOstreeSysrootUpgraderLayeringType layering_type; - gboolean layering_changed = FALSE; - if (!rpmostree_sysroot_upgrader_prep_layering (upgrader, &layering_type, &layering_changed, - cancellable, error)) - return FALSE; - if (!rpmostree_sysroot_upgrader_deploy (upgrader, cancellable, error)) return FALSE; Maybe let's simplify this flow by just automatically calling `prep_layering` in `deploy` if `self->layering_initialized == FALSE` and drop the related `g_assert`? rpmostree_origin_set_regenerate_initramfs (origin, self->regenerate, self->args); rpmostree_sysroot_upgrader_set_origin (upgrader, origin); if (!rpmostree_sysroot_upgrader_deploy (upgrader, cancellable, error)) return FALSE;
codereview_cpp_data_9179
TEST_P(PubSubBasic, BestEffortTwoWritersConsecutives) { - // Best effort incompatible with best effort if (use_pull_mode) { return; ```suggestion // Pull mode incompatible with best effort ``` TEST_P(PubSubBasic, BestEffortTwoWritersConsecutives) { + // Pull mode incompatible with best effort if (use_pull_mode) { return;
codereview_cpp_data_9206
LOG_VARD(poisMergedIntoPolys); const QString description = MatchCreator::BaseFeatureTypeToString(featureType); LOG_VARD(description); - boost::shared_ptr<ElementCriterion> e_criterion(criterion); double totalFeatures = 0.0; totalFeatures = _applyVisitor( - map, FilteredVisitor(*(e_criterion->clone()), *(_getElementVisitorForFeatureType(featureType)))); LOG_VARD(totalFeatures); _stats.append(SingleStat(QString("%1 Count").arg(description), totalFeatures)); _stats.append(SingleStat(QString("Conflatable %1s").arg(description), conflatableCount)); I think that these additions shouldn't be necessary. Filtered visitor has a constructor like so: ``` FilteredVisitor(ElementCriterionPtr criterion, ConstElementVisitorPtr visitor) ``` And `ElementCriterion::clone` returns an `ElementCriterionPtr` while `_getElementVisitorForFeatureType` returns a `ConstElementVisitorPtr`. So the code might look like this: ``` map, FilteredVisitor(criterion->clone(), _getElementVisitorForFeatureType(featureType))); ``` Also for the sake of cleanliness, `e_criterion` is actually no longer needed because `criterion` is actually of the same type. LOG_VARD(poisMergedIntoPolys); const QString description = MatchCreator::BaseFeatureTypeToString(featureType); LOG_VARD(description); double totalFeatures = 0.0; totalFeatures = _applyVisitor( + map, FilteredVisitor(criterion->clone(), _getElementVisitorForFeatureType(featureType))); LOG_VARD(totalFeatures); _stats.append(SingleStat(QString("%1 Count").arg(description), totalFeatures)); _stats.append(SingleStat(QString("Conflatable %1s").arg(description), conflatableCount));
codereview_cpp_data_9209
auto mst_transport = std::make_shared<MstTransportGrpc>(); auto mst_completer = std::make_shared<DefaultCompleter>(); auto mst_storage = std::make_shared<MstStorageStateImpl>(mst_completer); - // TODO: @l4l magics should be fixed with options in cli branch - // check #661 for details auto mst_propagation = std::make_shared<GossipPropagationStrategy>( wsv, std::chrono::seconds(5) /*emitting period*/, PR 661 is really old, please create a JIRA task. auto mst_transport = std::make_shared<MstTransportGrpc>(); auto mst_completer = std::make_shared<DefaultCompleter>(); auto mst_storage = std::make_shared<MstStorageStateImpl>(mst_completer); + // TODO: IR-1317 @l4l (02/05/18) magics should be replaced with options via + // cli parameters auto mst_propagation = std::make_shared<GossipPropagationStrategy>( wsv, std::chrono::seconds(5) /*emitting period*/,
codereview_cpp_data_9214
/** * Set the integrator. */ -void Manager::setIntegrator(Integrator integMethod) { if (_timeStepper) { std::string msg = "Cannot set a new integrator on this Manager"; Consider changing "method" to "type". /** * Set the integrator. */ +void Manager::setIntegrator(IntegratorType integType) { if (_timeStepper) { std::string msg = "Cannot set a new integrator on this Manager";
codereview_cpp_data_9215
int result = s2n_hmac_free(state); /* Post-conditions. */ - assert (result == S2N_SUCCESS); if (state != NULL) { assert(state->inner.hash_impl->free != NULL); assert(state->inner_just_key.hash_impl->free != NULL); Nit: you put an extra space on this one, but not on the others. ```suggestion /* Post-conditions. */ assert(result == S2N_SUCCESS); ``` int result = s2n_hmac_free(state); /* Post-conditions. */ + assert(result == S2N_SUCCESS); if (state != NULL) { assert(state->inner.hash_impl->free != NULL); assert(state->inner_just_key.hash_impl->free != NULL);
codereview_cpp_data_9218
* code related to the symbol table. */ typedef enum { /* parser private items */ - K_IGNORE = -16, K_DEFINE, K_UNDEFINED = KEYWORD_NONE, /* the followings items are also used as indices for VerilogKinds[] and SystemVerilogKinds[] */ s it the best way to tag "foo" of "`define foo ..." with constant kind? Introducing "d/definition" kind and tagging the "foo" with the definition kind is an alternative way. Using the unified kind "constant" in many areas reduces the information that client tools get from a tags file. In my experience, it is better to tag different things with different kinds. If ctags hides the differences, and just reports various language objects as "constant," in some cases, a client tool must parse the raw .sv source file for distinguishing whether a given tag is "`define"'ed or not. IMHO, ctags should not be too smart. Instead, ctags should be stupid; it should report what it sees in source input files as-is to client tools that will do something smart. * code related to the symbol table. */ typedef enum { /* parser private items */ + K_IGNORE = -16, /* Verilog/SystemVerilog keywords to be ignored */ K_DEFINE, + K_IFDEF, + K_BEGIN, + K_END, + K_END_DE, /* End of Design Elements */ K_UNDEFINED = KEYWORD_NONE, /* the followings items are also used as indices for VerilogKinds[] and SystemVerilogKinds[] */
codereview_cpp_data_9220
caf::actor_system sys{cfg}; fixup_logger(cfg); // Print the configuration file(s) that were loaded. - if (cfg.config_paths.size() == 1) - VAST_INFO_ANON("loaded configuration file:", cfg.config_paths[0]); - else if (!cfg.config_paths.empty()) - VAST_INFO_ANON("loaded configuration files:", cfg.config_paths); using string_list = std::vector<std::string>; auto schema_dirs = std::vector<vast::path>{}; if (!caf::get_or(cfg, "system.no-default-schema", false)) { ```suggestion for (auto& path : cfg.config_paths) VAST_INFO_ANON("loaded configuration file:", path); ``` caf::actor_system sys{cfg}; fixup_logger(cfg); // Print the configuration file(s) that were loaded. + if (!cfg.config_file_path.empty()) + cfg.config_paths.emplace_back(std::move(cfg.config_file_path)); + for (auto& path : cfg.config_paths) + VAST_INFO_ANON("loaded configuration file:", path); using string_list = std::vector<std::string>; auto schema_dirs = std::vector<vast::path>{}; if (!caf::get_or(cfg, "system.no-default-schema", false)) {
codereview_cpp_data_9225
uint16_t status; Maps::FileInfo info; int gameType; - const uint16_t _saveFileVersion; }; StreamBase & operator<<( StreamBase & msg, const HeaderSAV & hdr ) Strange but this member is not used anywhere. uint16_t status; Maps::FileInfo info; int gameType; }; StreamBase & operator<<( StreamBase & msg, const HeaderSAV & hdr )
codereview_cpp_data_9227
{commit_round.block_round + 1, commit_round.reject_round})); for (auto i = commit_round.reject_round + 1; - i < commit_round.reject_round + 1 + proposal_limit + 2; ++i) { generateTransactionsAndInsert({1, 2}); os->onCollaborationOutcome({commit_round.block_round, i}); Maybe better to add an explanation for the `commit_round.reject_round + 1 + proposal_limit + 2` expression? {commit_round.block_round + 1, commit_round.reject_round})); for (auto i = commit_round.reject_round + 1; + i < (commit_round.reject_round + 1) + (proposal_limit + 2); ++i) { generateTransactionsAndInsert({1, 2}); os->onCollaborationOutcome({commit_round.block_round, i});
codereview_cpp_data_9234
/** * @given initialized storage, all permissions * @when get account transactions of non existing account - * @then Return empty account transactions */ TEST_F(GetAccountTransactionsExecutorTest, InvalidNoAccount) { addAllPerms(); ```suggestion * @then Return error ``` /** * @given initialized storage, all permissions * @when get account transactions of non existing account + * @then return error */ TEST_F(GetAccountTransactionsExecutorTest, InvalidNoAccount) { addAllPerms();
codereview_cpp_data_9266
auto r_statistics_participant = statistics::dds::DomainParticipant::narrow(r_participant); ASSERT_NE(nullptr, r_statistics_participant); - // TODO: some topics get stuck in infinite loop in an error: // [SUBSCRIBER Error] Change not found on this key, something is wrong -> Function remove_change_sub // These topics are commented in test params // TODO: some topics could be used in both participants, but they lead to the same error These lines were already included several lines above and can be removed auto r_statistics_participant = statistics::dds::DomainParticipant::narrow(r_participant); ASSERT_NE(nullptr, r_statistics_participant); + // TODO: some topics get stuck in infinite loop in an error (generally if they are included twice): // [SUBSCRIBER Error] Change not found on this key, something is wrong -> Function remove_change_sub // These topics are commented in test params // TODO: some topics could be used in both participants, but they lead to the same error
codereview_cpp_data_9267
const Indexes around = Board::GetAroundIndexes( enemy->GetHeadIndex() ); std::set<const Unit *> targetedUnits; - for ( Indexes::const_iterator it = around.begin(); it != around.end(); ++it ) { - const Unit * monsterOnCell = Board::GetCell( *it )->GetUnit(); if ( monsterOnCell != nullptr ) { targetedUnits.emplace( monsterOnCell ); } warning: use range-based for loop instead [modernize-loop-convert] ```cpp for ( Indexes::const_iterator it = around.begin(); it != around.end(); ++it ) { ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (int it : around) ``` const Indexes around = Board::GetAroundIndexes( enemy->GetHeadIndex() ); std::set<const Unit *> targetedUnits; + for ( const int32_t cellId : around ) { + const Unit * monsterOnCell = Board::GetCell( cellId )->GetUnit(); if ( monsterOnCell != nullptr ) { targetedUnits.emplace( monsterOnCell ); }
codereview_cpp_data_9281
namespace vast { namespace { -// Translates a key to directory. auto key_to_dir(std::string key, const path& prefix) { return prefix / detail::replace_all(std::move(key), ".", path::separator); } ... `a key to a directory` or `keys to directories`. namespace vast { namespace { +// Translates a key to a directory. auto key_to_dir(std::string key, const path& prefix) { return prefix / detail::replace_all(std::move(key), ".", path::separator); }
codereview_cpp_data_9297
{ #ifdef __linux__ if((fd = open(filename.getFullPath().c_str(), O_RDONLY)) < 0) - msg_info() << "ERROR: impossible to open the file: " << filename.getValue(); #endif if(p_outputFilename.isSet()) remove the "ERROR:" message { #ifdef __linux__ if((fd = open(filename.getFullPath().c_str(), O_RDONLY)) < 0) + msg_error() << "Impossible to open the file: " << filename.getValue(); #endif if(p_outputFilename.isSet())
codereview_cpp_data_9304
return 0; } -int link_ssl_wrap_server(struct link *link, const char *key, const char *cert) { #ifdef HAS_OPENSSL if(key && cert) { - debug(D_TCP, "setting up ssl state for %s port %d", link->raddr, link->rport); link->ctx = _create_ssl_context(/* is client */ 0); _set_ssl_keys(link->ctx, key, cert); Drop the argument from `_create_ssl_context`, and use `TLS_method()` or `SSLv23_method()` as appropriate. return 0; } +int link_ssl_wrap_accept(struct link *link, const char *key, const char *cert) { #ifdef HAS_OPENSSL if(key && cert) { + debug(D_TCP, "accepting ssl state for %s port %d", link->raddr, link->rport); link->ctx = _create_ssl_context(/* is client */ 0); _set_ssl_keys(link->ctx, key, cert);
codereview_cpp_data_9307
extern const struct batch_queue_module batch_queue_mesos; extern const struct batch_queue_module batch_queue_k8s; extern const struct batch_queue_module batch_queue_dryrun; -#ifdef MPI extern const struct batch_queue_module batch_queue_mpi; #endif Please change MPI to CCTOOLS_WITH_MPI extern const struct batch_queue_module batch_queue_mesos; extern const struct batch_queue_module batch_queue_k8s; extern const struct batch_queue_module batch_queue_dryrun; +#ifdef CCTOOLS_WITH_MPI extern const struct batch_queue_module batch_queue_mpi; #endif
codereview_cpp_data_9308
{ /* Somehow, we have a deployment which has gpg-verify=true, but *doesn't* have a valid * signature. Let's not just bomb out here. We need to return this in the variant so - * that `status` can show "(unsigned)". */ *out_enabled = TRUE; *out_results = NULL; return TRUE; Well it's not necessarily unsigned, the signature could be invalid right? Not something to fix in this patch...handling things correctly here feels ugly, since the deployment data is a property and returning an error from reading that doesn't feel right. Maybe the best thing to do is to log to the journal once? Anyways not something to do in this patch. { /* Somehow, we have a deployment which has gpg-verify=true, but *doesn't* have a valid * signature. Let's not just bomb out here. We need to return this in the variant so + * that `status` can show the appropriate msg. */ *out_enabled = TRUE; *out_results = NULL; return TRUE;
codereview_cpp_data_9320
EXPECT_SUCCESS(s2n_connection_free(conn)); } - /* No non-post handshake messages can be received, except HelloRetry during TLS1.2. * This means that no handshake message that appears in the handshake state machine * should be allowed, except TLS_HELLO_REQUEST. */ Wouldn't this be Hello Request? EXPECT_SUCCESS(s2n_connection_free(conn)); } + /* No non-post handshake messages can be received, except HelloRequest during TLS1.2. * This means that no handshake message that appears in the handshake state machine * should be allowed, except TLS_HELLO_REQUEST. */
codereview_cpp_data_9335
void PoliciesListBox::SizeMove(const GG::Pt& ul, const GG::Pt& lr) { GG::Pt old_size = GG::Wnd::Size(); - double zoom_factor = 1; auto policy_palette = Parent(); auto gov_wnd = std::dynamic_pointer_cast<GovernmentWnd>(policy_palette->Parent()); if (gov_wnd) - zoom_factor = gov_wnd->GetPolicyZoomFactor(); - GG::X slot_width = static_cast<GG::X>(SLOT_CONTROL_WIDTH * zoom_factor); // maybe later do something interesting with docking CUIListBox::SizeMove(ul, lr); could probably make a separate function for getting the policy width and height as a pair, rather than repeating this and similar code in a few places void PoliciesListBox::SizeMove(const GG::Pt& ul, const GG::Pt& lr) { GG::Pt old_size = GG::Wnd::Size(); auto policy_palette = Parent(); auto gov_wnd = std::dynamic_pointer_cast<GovernmentWnd>(policy_palette->Parent()); + + GG::Pt slot_size = GG::Pt(SLOT_CONTROL_WIDTH, SLOT_CONTROL_HEIGHT); if (gov_wnd) + slot_size = gov_wnd->GetPolicySlotSize(); // maybe later do something interesting with docking CUIListBox::SizeMove(ul, lr);
codereview_cpp_data_9345
// it contains all of the useful sizing information in the first place, // even though it does not derive from GG::Wnd and have a virtual // MinUsableSize function. - if(m_sizer) { min_size += m_sizer->GetMinSize(); } - if(m_options_bar) { GG::Pt options_bar_min_size(m_options_bar->MinUsableSize()); min_size.x = std::max(min_size.x, options_bar_min_size.x); min_size.y += options_bar_min_size.y; don't need to break this string across lines... // it contains all of the useful sizing information in the first place, // even though it does not derive from GG::Wnd and have a virtual // MinUsableSize function. + if (m_sizer) { min_size += m_sizer->GetMinSize(); } + if (m_options_bar) { GG::Pt options_bar_min_size(m_options_bar->MinUsableSize()); min_size.x = std::max(min_size.x, options_bar_min_size.x); min_size.y += options_bar_min_size.y;
codereview_cpp_data_9346
namespace lbann { namespace callback { -void print_statistics::setup(model *m, const std::string& trainer_name) { #ifdef LBANN_VERSION lbann_comm *comm = m->get_comm(); if (comm->am_world_master()) { ```suggestion void print_statistics::setup(model *m, const std::string&) { ``` namespace lbann { namespace callback { +void print_statistics::setup(model *m, const std::string&) { #ifdef LBANN_VERSION lbann_comm *comm = m->get_comm(); if (comm->am_world_master()) {
codereview_cpp_data_9351
* * @author [Rakshit Raj](https://github.com/rakshitraj) */ -#include <cassert> -#include <cstdint> -#include <iostream> -#include <vector> /** * @namespace sorting Add a brief description of what each library does/adds (see the example below). ```c++ #include <iostream> /// for io operations #include <vector> /// for std::vector ``` * * @author [Rakshit Raj](https://github.com/rakshitraj) */ +#include <cassert> // for tests +#include <cstdint> // for typedef datatype uint64_t +#include <iostream> // for IO +#include <vector> // for std::vector<> /** * @namespace sorting
codereview_cpp_data_9352
if (!ISUNDEF(uh)) { client->mapuser(uh, u->email.c_str()); - if (u->isTemporary && u->uid == u->email) { - char uid[12]; - Base64::btoa((byte*)&uh, MegaClient::USERHANDLE, uid); - uid[11] = '\0'; - u->uid = uid; } } We have a much nicer interface to convert from Binary to B64: ``` u->uid = Base64Str<MegaClient::USERHANDLE>(uh); ``` :) if (!ISUNDEF(uh)) { client->mapuser(uh, u->email.c_str()); + if (u->isTemporary && u->uid == u->email) //update uid with the received USERHANDLE (will be used as target for putnodes) { + u->uid = Base64Str<MegaClient::USERHANDLE>(uh); } }