id
stringlengths
21
25
content
stringlengths
164
2.33k
codereview_cpp_data_2176
if (e.attr == system::type_atom::value) return evaluate(slice_.layout().name(), op_, d); // Find the column with attribute 'time'. auto pred = [](auto& x) { return caf::holds_alternative<timestamp_type>(x.type) && has_attribute(x.type, "time"); You are missing a check for `if (e.attr == system::time_atom::value) { /* diff here */}`. Then `return false` at the very end of the function. This way, new attributes can be added easily. if (e.attr == system::type_atom::value) return evaluate(slice_.layout().name(), op_, d); // Find the column with attribute 'time'. + if (e.attr != system::time_atom::value) + return false; auto pred = [](auto& x) { return caf::holds_alternative<timestamp_type>(x.type) && has_attribute(x.type, "time");
codereview_cpp_data_2179
picsPathEdit->setReadOnly(true); QPushButton *picsPathButton = new QPushButton("..."); connect(picsPathButton, SIGNAL(clicked()), this, SLOT(picsPathButtonClicked())); - QPushButton *clearDownloadedPicsButton = new QPushButton(tr("Clear Downloaded Pics")); - connect(clearDownloadedPicsButton, SIGNAL(clicked()), this, SLOT(clearDownloadedPicsButtonClicked())); cardDatabasePathLabel = new QLabel; cardDatabasePathEdit = new QLineEdit(settingsCache->getCardDatabasePath()); This should be `Delete downloaded pictures.` to be explicit picsPathEdit->setReadOnly(true); QPushButton *picsPathButton = new QPushButton("..."); connect(picsPathButton, SIGNAL(clicked()), this, SLOT(picsPathButtonClicked())); cardDatabasePathLabel = new QLabel; cardDatabasePathEdit = new QLineEdit(settingsCache->getCardDatabasePath());
codereview_cpp_data_2181
return; } free(tmp); - PMIX_INFO_LOAD(&info[4], PMIX_NODE_MAP, regex, PMIX_STRING); } /* generate the global proc map - if we have two Ditto here - needs to be a ```PMIX_REGEX``` return; } free(tmp); + PMIX_INFO_LOAD(&info[4], PMIX_NODE_MAP, regex, PMIX_REGEX); } /* generate the global proc map - if we have two
codereview_cpp_data_2182
#include <stdlib.h> #include <kdberrors.h> #include <kdbextension.h> -#include "inih-r29/ini.h" #include "ini.h" #include "contract.h" isn't adding inih-r29 to the include path better? #include <stdlib.h> #include <kdberrors.h> #include <kdbextension.h> +#include <inih.h> #include "ini.h" #include "contract.h"
codereview_cpp_data_2185
notnull_check(config->ticket_key_hashes = s2n_array_new(SHA_DIGEST_LENGTH)); } - if (s2n_verify_unique_ticket_key(config, hash_output, &insert_index) < 0) { - return 1; - } /* Insert hash key into a sorted array at known index */ struct uint8_t *hash_element = s2n_array_insert(config->ticket_key_hashes, insert_index); Why 1 instead of GUARD? notnull_check(config->ticket_key_hashes = s2n_array_new(SHA_DIGEST_LENGTH)); } + S2N_ERROR_IF(s2n_verify_unique_ticket_key(config, hash_output, &insert_index) < 0, S2N_ERR_TICKET_KEY_NOT_UNIQUE); /* Insert hash key into a sorted array at known index */ struct uint8_t *hash_element = s2n_array_insert(config->ticket_key_hashes, insert_index);
codereview_cpp_data_2196
} break; case NECROMANCY: { - const uint32_t necroCount = std::max( Skill::GetNecromancyPercent( hero ), count ); const std::string tmpDescription( std::string( GetNameWithBonus( hero ) ) + std::string( " allows %{necrocount} percent of the creatures killed in combat to be brought back from the dead as Skeletons." ) ); Could you please verify this check with Spade of Necromancy artifact as well as built Shrines? I think this will not work. The correct solution should be ``` Skill::GetNecromancyPercent( hero ) - hero.GetSecondaryValues( Skill::Secondary::NECROMANCY ) + count; ``` } break; case NECROMANCY: { + const uint32_t necroCount = Skill::GetNecromancyPercent( hero ) - hero.GetSecondaryValues( Skill::Secondary::NECROMANCY ) + count; const std::string tmpDescription( std::string( GetNameWithBonus( hero ) ) + std::string( " allows %{necrocount} percent of the creatures killed in combat to be brought back from the dead as Skeletons." ) );
codereview_cpp_data_2197
else { std::string error_message; -#pragma omp parallel for - for (int s = 0; s < mb_size; s++) { int n = m_current_pos + (s * m_sample_stride); int index = m_shuffled_indices[n]; - bool valid = fetch_datum(X, index, s, omp_get_thread_num()); if (!valid) { -#pragma omp critical error_message = "invalid datum (index " + std::to_string(index) + ")"; } } This is probably not good here...empty lines. else { std::string error_message; + LBANN_DATA_FETCH_OMP_FOR (int s = 0; s < mb_size; s++) { int n = m_current_pos + (s * m_sample_stride); int index = m_shuffled_indices[n]; + bool valid = fetch_datum(X, index, s, LBANN_OMP_THREAD_NUM); if (!valid) { + LBANN_DATA_FETCH_OMP_CRITICAL error_message = "invalid datum (index " + std::to_string(index) + ")"; } }
codereview_cpp_data_2198
bool Battle::Unit::checkIdleDelay() { - bool res = false; - if ( !idleTimerSet ) { const uint32_t halfDelay = animation.getIdleDelay() / 2; idleTimer.second = Rand::Get( 0, halfDelay / 2 ) + halfDelay * 3 / 2; idleTimerSet = true; } - res = idleTimer.Trigger(); if ( res ) idleTimerSet = false; return res; Please put declaration of the variable here: `bool res = idleTimer.Trigger();`. bool Battle::Unit::checkIdleDelay() { if ( !idleTimerSet ) { const uint32_t halfDelay = animation.getIdleDelay() / 2; idleTimer.second = Rand::Get( 0, halfDelay / 2 ) + halfDelay * 3 / 2; idleTimerSet = true; } + const bool res = idleTimer.Trigger(); if ( res ) idleTimerSet = false; return res;
codereview_cpp_data_2204
return false; } - const struct wlr_gles2_pixel_format *fmt = get_gles2_format_from_wl( - texture->wl_format); assert(fmt); // TODO: what if the unpack subimage extension isn't supported? nit: this would be better balanced as ```c const struct wlr_gles2_pixel_format *fmt = get_gles2_format_from_wl(texture->wl_format); ``` return false; } + const struct wlr_gles2_pixel_format *fmt = + get_gles2_format_from_wl(texture->wl_format); assert(fmt); // TODO: what if the unpack subimage extension isn't supported?
codereview_cpp_data_2206
char hasLinkCreationTs = plink ? 1 : 0; d->append((char*)&hasLinkCreationTs, 1); - d->append((char*)&mSyncable, sizeof(mSyncable)); d->append("\0\0\0\0", 5); // Use these bytes for extensions Can we switch Node's serialize and unserialize to use CacheableReader/CacheableWriter which is much easier to maintain, since we are making changes in these functions? thanks char hasLinkCreationTs = plink ? 1 : 0; d->append((char*)&hasLinkCreationTs, 1); + const auto syncableInt = static_cast<int8_t>(mSyncable); + d->append((char*)&syncableInt, 1); d->append("\0\0\0\0", 5); // Use these bytes for extensions
codereview_cpp_data_2209
// auto inject saylinks (say) if (RuleB(Chat, AutoInjectSaylinksToSay)) { std::string new_message = EQ::SayLinkEngine::InjectSaylinksIfNotExist(message); - buf.WriteString(new_message.c_str()); } else { buf.WriteString(message); `c_str()` is not needed. // auto inject saylinks (say) if (RuleB(Chat, AutoInjectSaylinksToSay)) { std::string new_message = EQ::SayLinkEngine::InjectSaylinksIfNotExist(message); + buf.WriteString(new_message); } else { buf.WriteString(message);
codereview_cpp_data_2234
nnodes = 10; break; default: - msg_warning() << "Error: MeshGmshLoader: Elements of type 1, 2, 3, 4, 5, or 6 expected. Element of type " << etype << " found."; nnodes = 0; } } You can remove the Error:MesgGMeshLoader: prefix the is duplicated with msg_warning nnodes = 10; break; default: + msg_warning() << "Elements of type 1, 2, 3, 4, 5, or 6 expected. Element of type " << etype << " found."; nnodes = 0; } }
codereview_cpp_data_2251
*/ #include <utils/s2n_socket.h> void s2n_socket_quickack_harness() { - struct s2n_socket_read_io_context *cbmc_allocate_s2n_socket_read_io_context(); - /* Non-deterministic inputs. */ struct s2n_connection *s2n_connection = malloc(sizeof(*s2n_connection)); if (s2n_connection != NULL) { s2n_connection->recv_io_context = cbmc_allocate_s2n_socket_read_io_context(); It looks like `result` is always going to be `0` i.e. `S2N_SUCCESS`. Why not just have `assert(result == S2N_SUCCESS)`? */ #include <utils/s2n_socket.h> +#include <cbmc_proof/make_common_datastructures.h> void s2n_socket_quickack_harness() { + /* Non-deterministic inputs. */ struct s2n_connection *s2n_connection = malloc(sizeof(*s2n_connection)); if (s2n_connection != NULL) { s2n_connection->recv_io_context = cbmc_allocate_s2n_socket_read_io_context();
codereview_cpp_data_2278
#else uc_strcat(pt,"-X11"); #endif - uc_strcat(pt,")"); pt += u_strlen(pt); lines[linecnt++] = pt; lines[linecnt] = NULL; This is spurious now. #else uc_strcat(pt,"-X11"); #endif pt += u_strlen(pt); lines[linecnt++] = pt; lines[linecnt] = NULL;
codereview_cpp_data_2280
LOCK(cs_main); - // BU remove, unused std::vector<CInv> vToFetch; - for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { const CInv &inv = vInv[nInv]; If it is unused and need to be removed, remove it. LOCK(cs_main); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { const CInv &inv = vInv[nInv];
codereview_cpp_data_2293
config->mfl_code = S2N_TLS_MAX_FRAG_LEN_EXT_NONE; config->accept_mfl = 0; config->session_state_lifetime_in_nanos = S2N_STATE_LIFETIME_IN_NANOS; - config->use_tickets = 1; - config->num_prepped_ticket_keys = 0; - config->total_used_ticket_keys = 0; config->valid_key_lifetime_in_nanos = S2N_TICKET_VALID_KEY_LIFETIME_IN_NANOS; config->semi_valid_key_lifetime_in_nanos = S2N_TICKET_SEMI_VALID_KEY_LIFETIME_IN_NANOS; why is this the default? config->mfl_code = S2N_TLS_MAX_FRAG_LEN_EXT_NONE; config->accept_mfl = 0; config->session_state_lifetime_in_nanos = S2N_STATE_LIFETIME_IN_NANOS; + config->use_tickets = 0; + config->ticket_keys = NULL; + config->ticket_key_hashes = NULL; config->valid_key_lifetime_in_nanos = S2N_TICKET_VALID_KEY_LIFETIME_IN_NANOS; config->semi_valid_key_lifetime_in_nanos = S2N_TICKET_SEMI_VALID_KEY_LIFETIME_IN_NANOS;
codereview_cpp_data_2296
proto::State request; grpc::ServerContext context; - for (const auto &vote : {message}) { - auto pb_vote = request.add_votes(); - *pb_vote = PbConverters::serializeVote(vote); - } auto response = network->SendState(&context, &request, nullptr); ASSERT_EQ(response.error_code(), grpc::StatusCode::OK); Meaningless loop. Why not just add message to request without loop? proto::State request; grpc::ServerContext context; + auto pb_vote = request.add_votes(); + *pb_vote = PbConverters::serializeVote(message); auto response = network->SendState(&context, &request, nullptr); ASSERT_EQ(response.error_code(), grpc::StatusCode::OK);
codereview_cpp_data_2308
fastrtps::rtps::RTPSParticipantAttributes patt; set_attributes_from_qos(patt, qos_); rtps_participant_->update_attributes(patt); } return ReturnCode_t::RETCODE_OK; I think this was to be done inside, which is the call right above this one ``` DomainParticipantImpl::set_qos( DomainParticipantQos& /*to*/, const DomainParticipantQos& /*from*/, bool /*first_time*/) ``` fastrtps::rtps::RTPSParticipantAttributes patt; set_attributes_from_qos(patt, qos_); rtps_participant_->update_attributes(patt); + + // Reset flag + qos_.user_data().hasChanged = false; } return ReturnCode_t::RETCODE_OK;
codereview_cpp_data_2315
/** * Iterative function/method to print graph: - * @param a[] : array of vectors (2D) - * @param V : vertices * @return void **/ void print(const std::vector< std::vector<int> > &a, int V) { ```suggestion * @param vis array to keep track of visited nodes (boolean type) ``` the colons in the param descriptions can be removed /** * Iterative function/method to print graph: + * @param a adjacency list representation of the graph + * @param V number of vertices * @return void **/ void print(const std::vector< std::vector<int> > &a, int V) {
codereview_cpp_data_2324
void ModelComponent::extendFinalizeFromProperties() { Super::extendFinalizeFromProperties(); - int geomSize = getProperty_GeometrySet().size(); if (geomSize > 0){ for (int i = 0; i < geomSize; ++i){ - addComponent(&upd_GeometrySet(i)); } } } @aseth1 is this an OK use of `addComponent()`? It is in `finalizeFromProperties()` so gets called from the constructor. void ModelComponent::extendFinalizeFromProperties() { Super::extendFinalizeFromProperties(); + int geomSize = getProperty_geometry().size(); if (geomSize > 0){ for (int i = 0; i < geomSize; ++i){ + addComponent(&upd_geometry(i)); } } }
codereview_cpp_data_2334
[this] { return CommandVariantType(variant_); }()}; }; - Command::Command(const Command &o) { - this->impl_ = std::make_unique<Impl>(*o.impl_->proto_); - } Command::Command(Command &&o) noexcept = default; Command::Command(const TransportType &ref) { It should be possible to use delegating constructor: `: Command(*o.impl_->proto_)` [this] { return CommandVariantType(variant_); }()}; }; + Command::Command(const Command &o) : Command(*o.impl_->proto_) {} Command::Command(Command &&o) noexcept = default; Command::Command(const TransportType &ref) {
codereview_cpp_data_2335
std::unique_lock<RecursiveTimedMutex> lock(reader_->getMutex()); CacheChange_t* earliest_change; - while (!history_.get_earliest_change(&earliest_change)) { auto source_timestamp = system_clock::time_point() + nanoseconds(earliest_change->sourceTimestamp.to_ns()); auto now = system_clock::now(); ```suggestion while (history_.get_earliest_change(&earliest_change)) ``` std::unique_lock<RecursiveTimedMutex> lock(reader_->getMutex()); CacheChange_t* earliest_change; + while (history_.get_earliest_change(&earliest_change)) { auto source_timestamp = system_clock::time_point() + nanoseconds(earliest_change->sourceTimestamp.to_ns()); auto now = system_clock::now();
codereview_cpp_data_2338
static void dumpcffcharset(SplineFont *sf,struct alltabs *at) { int i; - at->gn_sid = calloc(at->gi.gcnt,sizeof(short)); putc(0,at->charset); /* I always use a format 0 charset. ie. an array of SIDs in random order */ This one is also not safe. static void dumpcffcharset(SplineFont *sf,struct alltabs *at) { int i; + at->gn_sid = calloc(at->gi.gcnt,2*sizeof(short)); putc(0,at->charset); /* I always use a format 0 charset. ie. an array of SIDs in random order */
codereview_cpp_data_2339
if (outpath) { #ifdef WIN32 - // todo: thia whole function should be adjusted to use LocalPath member functions instead of manipulating its internal strings, so we don't need any ifdefs std::wstring s(ptr, localpath.getLocalpath().data() - ptr + localpath.getLocalpath().size()); #else std::string s(ptr, localpath.getLocalpath().data() - ptr + localpath.getLocalpath().size()); ```suggestion // todo: this whole function should be adjusted to use LocalPath member functions instead of manipulating its internal strings, so we don't need any ifdefs ``` if (outpath) { #ifdef WIN32 + // todo: this whole function should be adjusted to use LocalPath member functions instead of manipulating its internal strings, so we don't need any ifdefs std::wstring s(ptr, localpath.getLocalpath().data() - ptr + localpath.getLocalpath().size()); #else std::string s(ptr, localpath.getLocalpath().data() - ptr + localpath.getLocalpath().size());
codereview_cpp_data_2347
if (!self->have_rofiles) { - g_debug ("rofiles-fuse not available, doing without"); return TRUE; } I think this should be g_warning, because even if this *works* it is not the experience we want by default. if (!self->have_rofiles) { + g_warning ("rofiles-fuse not available, doing without"); return TRUE; }
codereview_cpp_data_2351
} } -bool PrimarySkillsBar::ActionBarLeftMouseSingleClick( const fheroes2::Point &, int & skill, const fheroes2::Rect & ) { if ( Skill::Primary::UNKNOWN != skill ) { Dialog::Message( Skill::Primary::String( skill ), Skill::Primary::StringDescription( skill, _hero ), Font::BIG, Dialog::OK ); :warning: **readability\-named\-parameter** :warning: all parameters should be named in a function ```suggestion bool PrimarySkillsBar::ActionBarLeftMouseSingleClick( const fheroes2::Point & /*unused*/, int & skill, const fheroes2::Rect & /*unused*/) ``` } } +bool PrimarySkillsBar::ActionBarLeftMouseSingleClick( const fheroes2::Point & /*unused*/, int & skill, const fheroes2::Rect & /*unused*/) { if ( Skill::Primary::UNKNOWN != skill ) { Dialog::Message( Skill::Primary::String( skill ), Skill::Primary::StringDescription( skill, _hero ), Font::BIG, Dialog::OK );
codereview_cpp_data_2361
} bool Mob::IsValidXTarget() const { - return (!GetID() == 0 || !IsCorpse()); } The bool check on `GetID` is a bit confusing. Why don't we just `GetID()` > 0 in this case? } bool Mob::IsValidXTarget() const { + return (GetID() > 0 || !IsCorpse()); }
codereview_cpp_data_2371
bool is_flat(const type& t) { auto r = get_if<record_type>(&t); - return r ? is_flat(*r) : true; } size_t flat_size(const record_type& rec) { Simpler: `return r && is_flat(*r)`. bool is_flat(const type& t) { auto r = get_if<record_type>(&t); + return !r || is_flat(*r); } size_t flat_size(const record_type& rec) {
codereview_cpp_data_2372
printf("Application protocol: %s\n", s2n_get_application_protocol(conn)); } - if (s2n_connection_get_curve(conn)) { - printf("Curve: %s\n", s2n_connection_get_curve(conn)); - } uint32_t length; const uint8_t *status = s2n_connection_get_ocsp_response(conn, &length); This function never returns NULL, do you need the guard? printf("Application protocol: %s\n", s2n_get_application_protocol(conn)); } + printf("Curve: %s\n", s2n_connection_get_curve(conn)); uint32_t length; const uint8_t *status = s2n_connection_get_ocsp_response(conn, &length);
codereview_cpp_data_2382
void DataSpacesReader::DoClose(const int transportIndex) { - if (globals_adios_is_dataspaces_connected_from_reader() && - !globals_adios_is_dataspaces_connected_from_both()) - { - // fprintf(stderr, "Disconnecting reader via finalize \n"); - // MPI_Barrier(m_data.mpi_comm); - // dspaces_finalize(); - } - globals_adios_set_dataspaces_disconnected_from_writer(); } void DataSpacesReader::Flush(const int transportIndex) {} Could you remove this empty block void DataSpacesReader::DoClose(const int transportIndex) { + globals_adios_set_dataspaces_disconnected_from_reader(); } void DataSpacesReader::Flush(const int transportIndex) {}
codereview_cpp_data_2388
} if (flags & DC_EXEC) { - /* _viewport_sign_kdtree does not need to be updated, only in-use depots can be renamed */ - if (reset) { d->name.clear(); MakeDefaultName(d); ```suggestion if (!adjacent) return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING_DEPOT); ``` } if (flags & DC_EXEC) { if (reset) { d->name.clear(); MakeDefaultName(d);
codereview_cpp_data_2392
return size; } - /** * Return the owner of the key. * - Given @p user:someuser:/..... return @p someuser Did you also consider to remove everything related to owner? return size; } +// TODO (kodebach): update docu /** * Return the owner of the key. * - Given @p user:someuser:/..... return @p someuser
codereview_cpp_data_2422
StatisticsSubmessageData data; read_statistics_submessage(msg, data); participant_->on_network_statistics( - source_guid_prefix_, source_locator, reception_locator, data, msg->length); - msg->length -= statistics_submessage_length; - msg->pos = msg->length; break; } In order to prevent side effects is better practice to stash the msg state before the `read_statistics_submessage` call using local variables. Note that `read_statistics_submessage` original implementation avoided side effects and stashing would have prevented applying the correction twice. StatisticsSubmessageData data; read_statistics_submessage(msg, data); participant_->on_network_statistics( + source_guid_prefix_, source_locator, reception_locator, data, msg_length); break; }
codereview_cpp_data_2426
sofa::core::topology::BaseMeshTopology* topoCon; firstBody.body->getContext()->get(topoCon); - if (!topoCon || topoCon->getTriangles().empty()) return; // Output declarations ```suggestion if (!topoCon || topoCon->getTopologyType() != sofa::core::topology::TopologyElementType::TRIANGLE) ``` sofa::core::topology::BaseMeshTopology* topoCon; firstBody.body->getContext()->get(topoCon); + if (!topoCon || topoCon->getTopologyType() != sofa::core::topology::TopologyElementType::TRIANGLE) return; // Output declarations
codereview_cpp_data_2434
StreamBase & operator<<( StreamBase & msg, const UltimateArtifact & ultimate ) { - return msg << static_cast<Artifact>( ultimate ) << ultimate._index << ultimate._isFound << ultimate._offset; } StreamBase & operator>>( StreamBase & msg, UltimateArtifact & ultimate ) :warning: **cppcoreguidelines\-slicing** :warning: slicing object from type `` UltimateArtifact `` to `` Artifact `` discards 13 bytes of state StreamBase & operator<<( StreamBase & msg, const UltimateArtifact & ultimate ) { + return msg << static_cast<const Artifact &>( ultimate ) << ultimate._index << ultimate._isFound << ultimate._offset; } StreamBase & operator>>( StreamBase & msg, UltimateArtifact & ultimate )
codereview_cpp_data_2438
mStackDepth = 0; stack.reserve( 64 ); mShouldReset = false; } ExprEvalState::~ExprEvalState() Should mResetLocked be initialized here as well? mStackDepth = 0; stack.reserve( 64 ); mShouldReset = false; + mResetLocked = false; } ExprEvalState::~ExprEvalState()
codereview_cpp_data_2441
break; case CR_ACIDDEMONSTRATION: #ifdef RENEWAL - {// [violetharmony] int64 matk=0, atk; short tdef = status->get_total_def(target); short tmdef = status->get_total_mdef(target); Please do not remove the name of the previous contributor, please add your name instead. break; case CR_ACIDDEMONSTRATION: #ifdef RENEWAL + {// [malufett] + // [violetharmony] ratio change int64 matk=0, atk; short tdef = status->get_total_def(target); short tmdef = status->get_total_mdef(target);
codereview_cpp_data_2461
* participating - note that the proc would not * have been added to any collective tracker until * after it successfully connected */ - PMIX_LIST_FOREACH(trk, &pmix_server_globals.collectives, pmix_server_trkr_t) { /* see if this proc is participating in this tracker */ PMIX_LIST_FOREACH_SAFE(rinfo, rnext, &trk->local_cbs, pmix_server_caddy_t) { if (!PMIX_CHECK_PROCID(&rinfo->peer->info->pname, &peer->info->pname)) { it should be a `break` or something else. `continue` will move to the next `rinfo` of the `trk->local_cbs` but `trk` could be `NULL` since it was just `PMIX_RELEASE()` earlier. * participating - note that the proc would not * have been added to any collective tracker until * after it successfully connected */ + PMIX_LIST_FOREACH_SAFE(trk, tnxt, &pmix_server_globals.collectives, pmix_server_trkr_t) { /* see if this proc is participating in this tracker */ PMIX_LIST_FOREACH_SAFE(rinfo, rnext, &trk->local_cbs, pmix_server_caddy_t) { if (!PMIX_CHECK_PROCID(&rinfo->peer->info->pname, &peer->info->pname)) {
codereview_cpp_data_2463
return false; }); }) - | boost::adaptors::transformed([&](auto result) { return std::move( boost::get<iroha::expected::ValueOf<decltype(result)>>( result)) Do we need a lambda capture here? return false; }); }) + | boost::adaptors::transformed([](auto result) { return std::move( boost::get<iroha::expected::ValueOf<decltype(result)>>( result))
codereview_cpp_data_2466
/* Do handshake */ EXPECT_OK(s2n_negotiate_test_server_and_client_until_message(server_conn, client_conn, SERVER_CERT)); - EXPECT_EQUAL(client_conn->actual_protocol_version, s2n_get_highest_fully_supported_tls_version()); - EXPECT_EQUAL(server_conn->actual_protocol_version, s2n_get_highest_fully_supported_tls_version()); /* Output memory allocated according to max fragment length. */ EXPECT_EQUAL(client_conn->max_outgoing_fragment_length, S2N_DEFAULT_FRAGMENT_LENGTH); This test was already pretty difficult to reason about. It might be worth keeping it simple and only running it when TLS1.3 is fully supported. /* Do handshake */ EXPECT_OK(s2n_negotiate_test_server_and_client_until_message(server_conn, client_conn, SERVER_CERT)); + EXPECT_EQUAL(client_conn->actual_protocol_version, S2N_TLS13); + EXPECT_EQUAL(server_conn->actual_protocol_version, S2N_TLS13); /* Output memory allocated according to max fragment length. */ EXPECT_EQUAL(client_conn->max_outgoing_fragment_length, S2N_DEFAULT_FRAGMENT_LENGTH);
codereview_cpp_data_2478
caf::binary_serializer sink2{nullptr, data_buffer}; if (auto error = sink2(x)) return error; - auto encoding = create_encoding(x->implementation_id()); if (!encoding) return encoding.error(); auto layout_ptr = reinterpret_cast<const uint8_t*>(layout_buffer.data()); ~A call to `__builtin_unreachable()` below that line would silence a GCC warning about a missing return here.~ This function should just return an `expected`. caf::binary_serializer sink2{nullptr, data_buffer}; if (auto error = sink2(x)) return error; + auto encoding = transform(x->implementation_id()); if (!encoding) return encoding.error(); auto layout_ptr = reinterpret_cast<const uint8_t*>(layout_buffer.data());
codereview_cpp_data_2479
void ZoneReload::HotReloadQuests() { BenchTimer timer; - timer.reset(); entity_list.ClearAreas(); It's not required to call BenchTimer::reset() here. void ZoneReload::HotReloadQuests() { BenchTimer timer; entity_list.ClearAreas();
codereview_cpp_data_2500
std::unique_lock<RecursiveTimedMutex> lock(writer_->getMutex()); CacheChange_t* earliest_change; - while (!history_.get_earliest_change(&earliest_change)) { auto source_timestamp = system_clock::time_point() + nanoseconds(earliest_change->sourceTimestamp.to_ns()); auto now = system_clock::now(); why is entering if there aren't CacheChange_t in History? std::unique_lock<RecursiveTimedMutex> lock(writer_->getMutex()); CacheChange_t* earliest_change; + while (history_.get_earliest_change(&earliest_change)) { auto source_timestamp = system_clock::time_point() + nanoseconds(earliest_change->sourceTimestamp.to_ns()); auto now = system_clock::now();
codereview_cpp_data_2502
if (line == "$continue" || line == "$quit" || line == "$exit") break; else if (line == "$help") - std::cout << "Welcome to the Icinga 2 console/script debugger.\n" "Usable commands:\n" - " $continue, $quit, $exit Quit the console\n" - " $help Print this help\n\n" "For more information on how to use this console, please consult the documentation at https://icinga.com/docs\n"; else std::cout << "Unknown debugger command: " << line << "\n"; While that's technically correct (the best kind of correct...) this might be confusing for users: "Why do we have $continue for closing the console?" if (line == "$continue" || line == "$quit" || line == "$exit") break; else if (line == "$help") + std::cout << "Welcome to the Icinga 2 debug console.\n" "Usable commands:\n" + " $continue Continue running Icinga 2 (script debugger).\n" + " $quit, $exit Stop debugging and quit the console.\n" + " $help Print this help.\n\n" "For more information on how to use this console, please consult the documentation at https://icinga.com/docs\n"; else std::cout << "Unknown debugger command: " << line << "\n";
codereview_cpp_data_2506
{ struct session_cache_entry *cache = ctx; - POSIX_ENSURE(key_size > 0, S2N_ERR_INVALID_ARGUMENT); - POSIX_ENSURE(key_size <= MAX_KEY_LEN, S2N_ERR_INVALID_ARGUMENT); - POSIX_ENSURE(value_size > 0, S2N_ERR_INVALID_ARGUMENT); - POSIX_ENSURE(value_size <= MAX_VAL_LEN, S2N_ERR_INVALID_ARGUMENT); uint8_t idx = ((const uint8_t *)key)[0]; Why not? ```suggestion POSIX_ENSURE_INCLUSIVE_RANGE(1, key_size, MAX_KEY_LEN); POSIX_ENSURE_INCLUSIVE_RANGE(1, value_size, MAX_VAL_LEN); ``` If this doesn't work, does this indicate missing macros which should exist? (I'm guessing that the error code is incorrect. So, should POSIX_ENSURE_INCLUSIVE_RANGE accept an error code?) { struct session_cache_entry *cache = ctx; + POSIX_ENSURE_INCLUSIVE_RANGE(1, key_size, MAX_KEY_LEN); + POSIX_ENSURE_INCLUSIVE_RANGE(1, value_size, MAX_VAL_LEN); uint8_t idx = ((const uint8_t *)key)[0];
codereview_cpp_data_2507
else if (m->s->from->nonextcp && m->s->to->noprevcp && Within4RoundingErrors(m->s->from->me.x,m->s->to->me.x) && Within4RoundingErrors(m->s->from->me.y,m->s->to->me.y)) - SOError( "The curve is too short.\n"); else if (Within4RoundingErrors(evalCubicSpline(m->s->splines[0], m->tstart), evalCubicSpline(m->s->splines[0], m->tend)) && Within4RoundingErrors(evalCubicSpline(m->s->splines[1], m->tstart), evalCubicSpline(m->s->splines[1], m->tend))) - SOError( "The subcurve is too short.\n"); else { /* It is monotonic, so a subset of it must also be */ Monotonic *m2 = chunkalloc(sizeof(Monotonic)); About a month ago I read enough about actual spline math that I have started to understand this stuff a little, including the macro above (relative to FontForge's representation, which I understand bits of). I take it here you're replacing a dodgy heuristic of just looking at the end point locations with an evaluation of the endpoints in the line case (because nothing interesting can happen between the very-close-together endpoints of a line) and the spline case (where far-away control points might stretch the spline enough away from the endpoints to make the t-interval "subcurve" interesting). If that's right, might "The line is too short." be a more informative message in the former case? else if (m->s->from->nonextcp && m->s->to->noprevcp && Within4RoundingErrors(m->s->from->me.x,m->s->to->me.x) && Within4RoundingErrors(m->s->from->me.y,m->s->to->me.y)) + SOError( "The spline is straight and is too short to be meaningful.\n"); else if (Within4RoundingErrors(evalCubicSpline(m->s->splines[0], m->tstart), evalCubicSpline(m->s->splines[0], m->tend)) && Within4RoundingErrors(evalCubicSpline(m->s->splines[1], m->tstart), evalCubicSpline(m->s->splines[1], m->tend))) + SOError( "The monotonic curve is too short.\n"); else { /* It is monotonic, so a subset of it must also be */ Monotonic *m2 = chunkalloc(sizeof(Monotonic));
codereview_cpp_data_2521
#include "caffe/caffe.hpp" int main(int argc, char** argv) { - LOG(ERROR) << "Deprecated. Use caffe.bin train --solver_proto_file=... " "[--resume_point_file=...] instead."; return 0; } maybe these should be `LOG(FATAL)`s? #include "caffe/caffe.hpp" int main(int argc, char** argv) { + LOG(FATAL) << "Deprecated. Use caffe.bin train --solver_proto_file=... " "[--resume_point_file=...] instead."; return 0; }
codereview_cpp_data_2531
size_t start; size_t end; uint32_t recovery; bool more = true; while (std::getline(fi, line)) { Doesn't seem the correct way to do this, as we are checking for negative values below (which now give additional warnings). I would suggest adding an `int32_t input_recovery;` after the declaration of `iss` below, use it to read and validate the input, and then do a `recovery = static_cast<uint32_t>(input_recovery);` before finding and pushing to the vector. size_t start; size_t end; uint32_t recovery; + int32_t input_recovery; bool more = true; while (std::getline(fi, line)) {
codereview_cpp_data_2534
loaded = load_config(&parse_args); if (loaded != NULL) { - /* cache included node */ h2o_vector_reserve(NULL, &arg->node_cache, arg->node_cache.size + 1); resolve_tag_node_cache_entry_t entry = {h2o_strdup(NULL, filename, SIZE_MAX), loaded}; arg->node_cache.entries[arg->node_cache.size++] = entry; } return loaded; Please retain (i.g. increment `_refcnt`) when storing the node to the cache (and also release it when the cache is disposed of), to guarantee that all nodes stored in the cache are valid. loaded = load_config(&parse_args); if (loaded != NULL) { + /* cache newly loaded node */ h2o_vector_reserve(NULL, &arg->node_cache, arg->node_cache.size + 1); resolve_tag_node_cache_entry_t entry = {h2o_strdup(NULL, filename, SIZE_MAX), loaded}; arg->node_cache.entries[arg->node_cache.size++] = entry; + ++loaded->_refcnt; } return loaded;
codereview_cpp_data_2567
apply(t, [&account_ids, &asset_ids, &balances]( auto &account_id, auto &asset_id, auto &amount) { - account_ids.push_back(account_id); - asset_ids.push_back(asset_id); balances.push_back( shared_model::interface::Amount(amount)); }); Moving account_id and other parameters? apply(t, [&account_ids, &asset_ids, &balances]( auto &account_id, auto &asset_id, auto &amount) { + account_ids.push_back(std::move(account_id)); + asset_ids.push_back(std::move(asset_id)); balances.push_back( shared_model::interface::Amount(amount)); });
codereview_cpp_data_2582
if ( interface ) interface->RedrawActionMove( *b, path ); else if ( bridge ) { - Indexes::const_iterator dst = path.begin(); - while ( dst != path.end() ) { bool doMovement = false; if ( bridge && bridge->NeedDown( *b, *dst ) ) Please use `for()` loop to reduce **dst** variable lifetime. if ( interface ) interface->RedrawActionMove( *b, path ); else if ( bridge ) { + for ( Indexes::const_iterator dst = path.begin(); dst != path.end() ; ++dst ) { bool doMovement = false; if ( bridge && bridge->NeedDown( *b, *dst ) )
codereview_cpp_data_2600
std::shared_ptr<ametsuchi::TemporaryFactory> factory, std::shared_ptr<ametsuchi::BlockQuery> blockQuery, std::shared_ptr<model::ModelCryptoProvider> crypto_provider) - : proposal_subscription_(rxcpp::composite_subscription()), - verified_proposal_subscription_(rxcpp::composite_subscription()), - validator_(std::move(statefulValidator)), ametsuchi_factory_(std::move(factory)), block_queries_(std::move(blockQuery)), crypto_provider_(std::move(crypto_provider)) { No need to call empty constructor, it will be called before constructor body. Same for `verified_proposal_subscription_` std::shared_ptr<ametsuchi::TemporaryFactory> factory, std::shared_ptr<ametsuchi::BlockQuery> blockQuery, std::shared_ptr<model::ModelCryptoProvider> crypto_provider) + : validator_(std::move(statefulValidator)), ametsuchi_factory_(std::move(factory)), block_queries_(std::move(blockQuery)), crypto_provider_(std::move(crypto_provider)) {
codereview_cpp_data_2604
r.unserializeu32(width); r.unserializeu32(height); r.unserializeu32(fps); r.unserializeu32(containerid); r.unserializeu32(videocodecid); r.unserializeu32(audiocodecid); I'm not sure if there will be a case where we wan this to receive `string *deserialize` ? and then do `r.eraseused(deserialize);` by the end r.unserializeu32(width); r.unserializeu32(height); r.unserializeu32(fps); + r.unserializeu32(playtime); r.unserializeu32(containerid); r.unserializeu32(videocodecid); r.unserializeu32(audiocodecid);
codereview_cpp_data_2611
/* Call exit() directly on this function because it retuns an exit code. */ exit(EXIT_SUCCESS); -} \ No newline at end of file Ah, there needs to be a newline at the end of the file. Otherwise it's (by POSIX standards) not a file. :) /* Call exit() directly on this function because it retuns an exit code. */ exit(EXIT_SUCCESS); \ No newline at end of file +}
codereview_cpp_data_2621
dir.setFilter(QDir::Files); foreach(QString dirFile, dir.entryList()) { - LOG_warn << "Removing unexpected temporary file found from previous executions: " << dirFile.toStdString(); dir.remove(dirFile); } #endif I think we'd rather use `.toUtf8().constData()` : toStdString return encodes in UTF-8 in qt 5, but as utf8 in qt4 dir.setFilter(QDir::Files); foreach(QString dirFile, dir.entryList()) { + LOG_warn << "Removing unexpected temporary file found from previous executions: " << dirFile.toUtf8().constData(); dir.remove(dirFile); } #endif
codereview_cpp_data_2627
EXPECT_FAILURE_WITH_ERRNO(s2n_extensions_server_key_share_select(server_conn), S2N_ERR_ECDHE_UNSUPPORTED_CURVE); EXPECT_NULL(server_conn->secure.server_ecc_evp_params.negotiated_curve); - /* Commented out until hello retry is implemented. EXPECT_FALSE(s2n_server_requires_retry(server_conn)); */ EXPECT_SUCCESS(s2n_connection_free(server_conn)); } Could you mention #1607 in this code, and update the issue to include enabling these tests? EXPECT_FAILURE_WITH_ERRNO(s2n_extensions_server_key_share_select(server_conn), S2N_ERR_ECDHE_UNSUPPORTED_CURVE); EXPECT_NULL(server_conn->secure.server_ecc_evp_params.negotiated_curve); + /* Commented out until hello retry is implemented in issue #1607. EXPECT_FALSE(s2n_server_requires_retry(server_conn)); */ EXPECT_SUCCESS(s2n_connection_free(server_conn)); }
codereview_cpp_data_2637
logger::LoggerPtr pb_qry_factory_log) : command_client_(target_ip, port, pb_qry_factory_log), query_client_(target_ip, port), - pb_qry_factory_log_(pb_qry_factory_log) {} CliClient::Response<CliClient::TxStatus> CliClient::sendTx( const shared_model::interface::Transaction &tx) { Can we use & references or moves here? logger::LoggerPtr pb_qry_factory_log) : command_client_(target_ip, port, pb_qry_factory_log), query_client_(target_ip, port), + pb_qry_factory_log_(std::move(pb_qry_factory_log)) {} CliClient::Response<CliClient::TxStatus> CliClient::sendTx( const shared_model::interface::Transaction &tx) {
codereview_cpp_data_2638
} } -bool ArtifactsBar::ActionBarLeftMouseSingleClick( const fheroes2::Point &, Artifact & art, const fheroes2::Rect & ) { if ( isMagicBook( art ) ) { const bool isMbSelected = ( !isSelected() || isMagicBook( *GetSelectedItem() ) ); :warning: **readability\-named\-parameter** :warning: all parameters should be named in a function ```suggestion bool ArtifactsBar::ActionBarLeftMouseSingleClick( const fheroes2::Point & /*unused*/, Artifact & art, const fheroes2::Rect & /*unused*/) ``` } } +bool ArtifactsBar::ActionBarLeftMouseSingleClick( const fheroes2::Point & /*unused*/, Artifact & art, const fheroes2::Rect & /*unused*/) { if ( isMagicBook( art ) ) { const bool isMbSelected = ( !isSelected() || isMagicBook( *GetSelectedItem() ) );
codereview_cpp_data_2644
size_t segments = 10; size_t max_segment_size = 128; size_t initially_requested_ids = 128; -size_t telemetry_rate_ms = 1000; } // namespace system Does anything speak against making this type `std::chrono::milliseconds` and ditch the `_ms` suffix? size_t segments = 10; size_t max_segment_size = 128; size_t initially_requested_ids = 128; +std::chrono::milliseconds telemetry_rate = std::chrono::milliseconds{1000}; } // namespace system
codereview_cpp_data_2650
wl_keyboard_send_keymap(handle->keyboard, WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1, state->keymap_fd, state->keymap_size); - if (wl_resource_get_version(handle->keyboard) >= 2) - wl_keyboard_send_repeat_info(handle->keyboard, 660, 25); } int main() { I shouldn't have to tell you about style at this point wl_keyboard_send_keymap(handle->keyboard, WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1, state->keymap_fd, state->keymap_size); + if (wl_resource_get_version(handle->keyboard) >= 2) { + wl_keyboard_send_repeat_info(handle->keyboard, 25, 600); + } } int main() {
codereview_cpp_data_2655
} } -#if QT_VERSION < 0x050000 - reset(); -#else endResetModel(); -#endif } int DeckListModel::rowCount(const QModelIndex &parent) const Can this block get moved to its own function? I'd like to keep `#IF` branching out of as much of the main code as possible. } } endResetModel(); } int DeckListModel::rowCount(const QModelIndex &parent) const
codereview_cpp_data_2665
*/ /* HIT_START - * BUILD: %t %s ../../test_common.cpp * RUN: %t * HIT_END */ #include <stdio.h> -#include <unistd.h> #include "hip/hip_runtime.h" #include "test_common.h" unistd.h is a POSIX header. With supporting Windows in the future it should be replaced with one or multiple C/C++ headers and also supplemented with platform ifdefs, for instance: ```c++ +#ifdef _WIN32 +#include <windows.h> +#define sleep(x) Sleep(x) +#else +#include <unistd.h> +#endif ``` */ /* HIT_START + * BUILD: %t %s ../../test_common.cpp NVCC_OPTIONS -std=c++11 * RUN: %t * HIT_END */ #include <stdio.h> +#include <thread> +#include <chrono> #include "hip/hip_runtime.h" #include "test_common.h"
codereview_cpp_data_2667
rpmostree_sysroot_upgrader_set_origin (upgrader, origin); - RpmOstreeSysrootUpgraderLayeringType layering_type; - gboolean layering_changed = FALSE; /* Mainly for the `install` and `override` commands */ if (!(self->flags & RPMOSTREE_TRANSACTION_DEPLOY_FLAG_NO_PULL_BASE)) { Nit: should these be declared lower down near the related call site? rpmostree_sysroot_upgrader_set_origin (upgrader, origin); /* Mainly for the `install` and `override` commands */ if (!(self->flags & RPMOSTREE_TRANSACTION_DEPLOY_FLAG_NO_PULL_BASE)) {
codereview_cpp_data_2687
/* Subtract the padding length */ gt_check(en.size, 0); - gte_check(payload_length, en.data[en.size - 1] + 1); - payload_length -= (en.data[en.size - 1] + 1); - /* Update the MAC */ header[3] = (payload_length >> 8); header[4] = payload_length & 0xff; minor nit - you might want to calculate the length to subtract once and use it in the following two lines - you could even make a macro to do it for you: ``` #define s2n_subtract_underflow(n, diff) do { \ gte_check((n), (diff)); \ (n) -= (diff); \ } while (0) ``` then we can just invoke: ``` s2n_subtract_underflow(payload_length, en.data[en.size - 1] + 1); ``` /* Subtract the padding length */ gt_check(en.size, 0); + uint32_t out; + GUARD(s2n_sub_overflow(payload_length, en.data[en.size - 1] + 1, &out)); + payload_length = out; /* Update the MAC */ header[3] = (payload_length >> 8); header[4] = payload_length & 0xff;
codereview_cpp_data_2695
const char *pattern) { size_t added = 0; - for (auto usdt : available_usdts) { if (fnmatch(pattern, usdt.fully_qualified_name().c_str(), 0) == 0) { selected_usdts.push_back(usdt); added++; ```suggestion for (const auto& usdt : available_usdts) { ``` You can avoid copying loop variable by using reference. const char *pattern) { size_t added = 0; + for (const auto& usdt : available_usdts) { if (fnmatch(pattern, usdt.fully_qualified_name().c_str(), 0) == 0) { selected_usdts.push_back(usdt); added++;
codereview_cpp_data_2696
* are part of a newgrf vehicle set which changes bounding boxes within a * single vehicle direction. * - * TODO: is there a cleaner solution than casting to a mutable type? */ - Vehicle* v_mutable = const_cast<Vehicle*>(v); - v_mutable->rstate.is_viewport_candidate = true; } v = v->hash_viewport_next; If you change `sprite_seq` and `rstate` to be declared with the keyword `mutable`, you don't need to cast. It's a tiny cheat, though. Maybe `sprite_seq` should be inside `rstate` then, which then becomes a kind of mutable `sprite_cache`. * are part of a newgrf vehicle set which changes bounding boxes within a * single vehicle direction. * + * TODO: this will consider too many false positives, use the bounding box + * information or something which better narrows down the candidates. */ + v->sprite_cache.is_viewport_candidate = true; } v = v->hash_viewport_next;
codereview_cpp_data_2705
ostree_progress, NULL, &error)) { - if (error->domain == FLATPAK_ERROR) - g_dbus_method_invocation_return_gerror (invocation, error); - else - g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED, - "Error pulling from repo: %s", error->message); - return TRUE; } Why can't we just return the error as is from flatpak_dir_pull_untrusted_local()? At least for the FLATPAK_ERROR domain. Listing everything separately like this does't seem super useful. ostree_progress, NULL, &error)) { + g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED, + "Error pulling from repo: %s", error->message); return TRUE; }
codereview_cpp_data_2708
static int s2n_connection_new_hashes(struct s2n_connection *conn) { /* Allocate long-term memory for the Connection's hash states */ - POSIX_GUARD(s2n_hash_new(&conn->hash_workspace)); POSIX_GUARD(s2n_hash_new(&conn->prf_space.ssl3.md5)); POSIX_GUARD(s2n_hash_new(&conn->prf_space.ssl3.sha1)); So, why are hash_workspace, ssl3.md5, and ssl3.sha1 being left behind? static int s2n_connection_new_hashes(struct s2n_connection *conn) { /* Allocate long-term memory for the Connection's hash states */ POSIX_GUARD(s2n_hash_new(&conn->prf_space.ssl3.md5)); POSIX_GUARD(s2n_hash_new(&conn->prf_space.ssl3.sha1));
codereview_cpp_data_2709
ns_sol.reset(new MultiFab(ba, dm, ncomp, ng, MFInfo(), *(ns_linop->Factory(0,0)))); ng = 0; if (cf_strategy == CFStrategy::ghostnodes) ng = nghost; - std::cout << __LINE__ << " " << (int)cf_strategy << " " << (int)CFStrategy::ghostnodes << std::endl; ns_rhs.reset(new MultiFab(ba, dm, ncomp, ng, MFInfo(), *(ns_linop->Factory(0,0)))); ns_sol->setVal(0.0); ns_rhs->setVal(0.0); This line should be removed. ns_sol.reset(new MultiFab(ba, dm, ncomp, ng, MFInfo(), *(ns_linop->Factory(0,0)))); ng = 0; if (cf_strategy == CFStrategy::ghostnodes) ng = nghost; ns_rhs.reset(new MultiFab(ba, dm, ncomp, ng, MFInfo(), *(ns_linop->Factory(0,0)))); ns_sol->setVal(0.0); ns_rhs->setVal(0.0);
codereview_cpp_data_2710
******************************************************************************/ #include <SofaMeshCollision/RayTriangleIntersection.h> -#include <SofaMeshCollision/Triangle.h> #include <sofa/helper/LCPSolver.inl> namespace sofa::component::collision Triangle.h instead of TriangleModel.h? I thought Triangle.h was the deprecated one? ******************************************************************************/ #include <SofaMeshCollision/RayTriangleIntersection.h> +#include <SofaMeshCollision/TriangleModel.h> #include <sofa/helper/LCPSolver.inl> namespace sofa::component::collision
codereview_cpp_data_2714
int s2n_recv_server_max_frag_len(struct s2n_connection *conn, struct s2n_stuffer *extension) { - uint16_t max_fragment_length; - GUARD(s2n_stuffer_read_uint16(extension, &max_fragment_length)); - if (max_fragment_length != mfl_code_to_length[conn->config->mfl_code]) { S2N_ERROR(S2N_ERR_MAX_FRAG_LEN_MISMATCH); } Should this be a hard error, or should it be best effort? int s2n_recv_server_max_frag_len(struct s2n_connection *conn, struct s2n_stuffer *extension) { + uint8_t mfl_code; + GUARD(s2n_stuffer_read_uint8(extension, &mfl_code)); + if (mfl_code != conn->config->mfl_code) { S2N_ERROR(S2N_ERR_MAX_FRAG_LEN_MISMATCH); }
codereview_cpp_data_2733
} struct wlr_renderer *wlr_renderer_autocreate_with_drm_fd(int drm_fd) { -#if WLR_HAS_GLES2_RENDERER struct gbm_device *gbm_device = gbm_create_device(drm_fd); if (!gbm_device) { wlr_log(WLR_ERROR, "Failed to create GBM device"); Maybe we should import `IS_ENABLED` from the linux kernel. Edit: Ah, MIT license, than rather import it from zephyr. } struct wlr_renderer *wlr_renderer_autocreate_with_drm_fd(int drm_fd) { struct gbm_device *gbm_device = gbm_create_device(drm_fd); if (!gbm_device) { wlr_log(WLR_ERROR, "Failed to create GBM device");
codereview_cpp_data_2735
template <typename Dtype> void BNLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { top[0]->Reshape(bottom[0]->num(), bottom[0]->channels(), bottom[0]->height(), bottom[0]->width()); line 326 - 327 is redundant and can be deleted. So is the same for the GPU code. template <typename Dtype> void BNLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { + CHECK_NE(top[0], bottom[0]) << this->type() << " Layer does not " + "allow in-place computation."; + top[0]->Reshape(bottom[0]->num(), bottom[0]->channels(), bottom[0]->height(), bottom[0]->width());
codereview_cpp_data_2738
{ if (listener_ == listener) { - return ReturnCode_t::RETCODE_ERROR; } listener_ = listener; return ReturnCode_t::RETCODE_OK; Same question as with `PublisherImpl::set_listener`. { if (listener_ == listener) { + return ReturnCode_t::RETCODE_OK; } listener_ = listener; return ReturnCode_t::RETCODE_OK;
codereview_cpp_data_2741
h2o_configurator_errprintf(cmd, node, "given extension \"%s\" does not start with a \".\"", node->data.scalar); return -1; } - if (strlen(node->data.scalar) == 1) { h2o_configurator_errprintf(cmd, node, "given extension \".\" is invalid: at least 2 characters are required"); return -1; } This is definitely a nitpick, but how about changing to `node->data.scalar[1] == '\0'`? h2o_configurator_errprintf(cmd, node, "given extension \"%s\" does not start with a \".\"", node->data.scalar); return -1; } + if (node->data.scalar[1] == '\0') { h2o_configurator_errprintf(cmd, node, "given extension \".\" is invalid: at least 2 characters are required"); return -1; }
codereview_cpp_data_2750
void HIPInternal::print_configuration(std::ostream &s) const { const HIPInternalDevices &dev_info = HIPInternalDevices::singleton(); -#if defined(KOKKOS_ENABLE_HIP) - s << "macro KOKKOS_ENABLE_HIP : defined" << std::endl; -#endif #if defined(HIP_VERSION) s << "macro HIP_VERSION = " << HIP_VERSION << " = version " - << HIP_VERSION / 100 << "." << HIP_VERSION % 100 << std::endl; #endif for (int i = 0; i < dev_info.m_hipDevCount; ++i) { It feels superfluous to check that the macro is defined. Wouldn't be there otherwise. void HIPInternal::print_configuration(std::ostream &s) const { const HIPInternalDevices &dev_info = HIPInternalDevices::singleton(); + s << "macro KOKKOS_ENABLE_HIP : defined" << '\n'; #if defined(HIP_VERSION) s << "macro HIP_VERSION = " << HIP_VERSION << " = version " + << HIP_VERSION / 100 << "." << HIP_VERSION % 100 << '\n'; #endif for (int i = 0; i < dev_info.m_hipDevCount; ++i) {
codereview_cpp_data_2756
{ cp = skipWhitespace (cp); - /* `^' is not explained the nsis reference manual. However, it is used * in gvim. * e.g. * https://github.com/vim/vim/blob/3dabd718f4b2d8e09de9e2ec73832620b91c2f79/nsis/lang/english.nsi ```suggestion /* `^' is not explained in the nsis reference manual. However, it is used ``` or maybe "mentioned" instead of "explained"? { cp = skipWhitespace (cp); + /* `^' is not explained in the nsis reference manual. However, it is used * in gvim. * e.g. * https://github.com/vim/vim/blob/3dabd718f4b2d8e09de9e2ec73832620b91c2f79/nsis/lang/english.nsi
codereview_cpp_data_2774
} OptPeer GossipPropagationStrategy::visit() { std::lock_guard<std::mutex> lock(m); if (not query or (non_visited.empty() and not initQueue())) { - // either PeerProvider doesn't gives peers return {}; } // or non_visited non-empty What is the reason to check `query`? } OptPeer GossipPropagationStrategy::visit() { + // Make sure that dtor isn't running std::lock_guard<std::mutex> lock(m); if (not query or (non_visited.empty() and not initQueue())) { + // either PeerProvider doesn't gives peers / dtor have been called return {}; } // or non_visited non-empty
codereview_cpp_data_2775
noblacklist ${HOME}/.kde4/share/config/okularpartrc noblacklist ${HOME}/.kde4/share/config/okularrc noblacklist ${HOME}/.local/share/kget -noblacklist ${HOME}/.local/share/kxmlgui5/okular noblacklist ${HOME}/.local/share/okular noblacklist ${HOME}/.local/share/qpdfview There is no `blacklist ${HOME}/.local/share/kxmlgui5/okular`. noblacklist ${HOME}/.kde4/share/config/okularpartrc noblacklist ${HOME}/.kde4/share/config/okularrc noblacklist ${HOME}/.local/share/kget noblacklist ${HOME}/.local/share/okular noblacklist ${HOME}/.local/share/qpdfview
codereview_cpp_data_2783
if ( *pt=='-' && pt[1]=='-' && pt[2]!='\0' ) ++pt; if ( strcmp(pt,"-nosplash")==0 || strcmp(pt,"-quiet")==0 ) /* Skip it */; - else if ( strcmp(pt,"-SkipPythonInitFiles")==0 ) run_python_init_files = false; - else if ( strcmp(pt,"-SkipPythonPlugins")==0 ) import_python_plugins = false; else if ( strcmp(pt,"-lang=py")==0 ) is_python = true; Processing cmdline arguments is a bit of a mess, there's three separate places to check for this flag... if ( *pt=='-' && pt[1]=='-' && pt[2]!='\0' ) ++pt; if ( strcmp(pt,"-nosplash")==0 || strcmp(pt,"-quiet")==0 ) /* Skip it */; + else if ( strcmp(pt,"-SkipPythonInitFiles")==0 || strcmp(pt,"-skippyfile")==0 ) run_python_init_files = false; + else if ( strcmp(pt,"-skippyplug")==0 ) import_python_plugins = false; else if ( strcmp(pt,"-lang=py")==0 ) is_python = true;
codereview_cpp_data_2784
if ( buf.size() ) { Surface surf( Size( head.width, head.height ), /*false*/ true ); // accepting transparency - const RGBA clkey = RGBA( 0xFF, 0, 0xFF ), ColorBlack = RGBA( 0, 0, 0, 0xFF ); surf.Fill( clkey ); surf.SetColorKey( clkey ); - surf.Fill( ColorBlack ); // filling with transparent color if ( 0x20 == head.type ) SpriteDrawICNv2( surf, buf, debug ); Please directly use RGBA here. if ( buf.size() ) { Surface surf( Size( head.width, head.height ), /*false*/ true ); // accepting transparency + const RGBA clkey = RGBA( 0xFF, 0, 0xFF ); surf.Fill( clkey ); surf.SetColorKey( clkey ); + surf.Fill( RGBA( 0, 0, 0, 0xFF ) ); // filling with transparent color if ( 0x20 == head.type ) SpriteDrawICNv2( surf, buf, debug );
codereview_cpp_data_2796
*out_update = NULL; return TRUE; /* NB: early return */ case RPMOSTREE_REFSPEC_TYPE_OSTREE: - case RPMOSTREE_REFSPEC_TYPE_COMMIT: break; } This could just be `if (refspectype == RPMOSTREE_REFSPEC_TYPE_ROJIG)`, right? *out_update = NULL; return TRUE; /* NB: early return */ case RPMOSTREE_REFSPEC_TYPE_OSTREE: + case RPMOSTREE_REFSPEC_TYPE_CHECKSUM: break; }
codereview_cpp_data_2797
"Generate genesis block for new Iroha network"); DEFINE_string(genesis_transaction, "", - "File with transaction in json format for the genesis"); DEFINE_string(peers_address, "", "File with peers address for new Iroha network"); for the genesis block "Generate genesis block for new Iroha network"); DEFINE_string(genesis_transaction, "", + "File with transaction in json format for the genesis block"); DEFINE_string(peers_address, "", "File with peers address for new Iroha network");
codereview_cpp_data_2800
} else { file = pname.service->open(&pname,flags,mode); } - } else if(!pname.service->can_open_dirs() && (flags&O_DIRECTORY)) { - // This is a hack to maintain compatibility with the interpretation - // of O_DIRECTORY used in some of the services. If getdents fails - // on certain remote services or similar strangeness, - // this is a good place to start looking. - file = pname.service->getdir(&pname); } else if(pname.service->is_seekable()) { if(force_cache) { file = pfs_cache_open(&pname,flags,mode); Now that we have `can_open_dirs()`, we don't need to implement `getdir` for `local`, `cvmfs`, and `chirp`. I think it's safe to remove the those. } else { file = pname.service->open(&pname,flags,mode); } + free(fd); } else if(pname.service->is_seekable()) { if(force_cache) { file = pfs_cache_open(&pname,flags,mode);
codereview_cpp_data_2814
} { - const char *dir = dirname(h2o_socket_buffer_mmap_settings.fn_template); - struct stat st; - if (!(stat(dir, &st) == 0 && S_ISDIR(st.st_mode) && access(dir, W_OK) == 0)) { - fprintf(stderr, "temp-buffer-path: '%s' is not a writable directory\n", dir); return EX_CONFIG; } } /* calculate defaults (note: open file cached is purged once every loop) */ * How about actually calling `mkstemp` to make sure that a file can be created? I think that would make things simpler. * I think we might want to move the logic (of checking if a temporary file can be created) into memory.c. } { + int fd = h2o_make_temp_file(h2o_socket_buffer_mmap_settings.fn_template); + if (fd == -1) { + fprintf(stderr, "temp-buffer-path: failed to create temporary file from the mkstemp(3) template '%s': %s\n", h2o_socket_buffer_mmap_settings.fn_template, strerror(errno)); return EX_CONFIG; } + close(fd); } /* calculate defaults (note: open file cached is purged once every loop) */
codereview_cpp_data_2819
/** * @file - * @brief Program to Count number of subsets * * @details Subset problem (https://en.wikipedia.org/wiki/Subset_sum_problem) * @author [Swastika Gupta](https://github.com/swastyy) ```suggestion * array. ``` /** * @file + * @brief Program to Count number of subsets(both continuous and non-continuous + * subarrays) with a given sum * * @details Subset problem (https://en.wikipedia.org/wiki/Subset_sum_problem) * @author [Swastika Gupta](https://github.com/swastyy)
codereview_cpp_data_2832
char a = ModbusClient->read(); rxValue = rxValue | a; LogString += static_cast<int>(a); - LogString += (" "); } switch (incomingValue) { This could be a char `' '` char a = ModbusClient->read(); rxValue = rxValue | a; LogString += static_cast<int>(a); + LogString += ' '; } switch (incomingValue) {
codereview_cpp_data_2843
RedrawTroopCount( *b ); } - // 21 is the last tile in the second row. Draw heroes now, because their position must be between tiles 21 and 22. - if ( ii == 21 ) { RedrawOpponents(); } } Could we please avoid this hardcoded value as use something like: `2 * ARENAW - 1`? At least it will be less `hardcoded` in this sense :) RedrawTroopCount( *b ); } + // Draw heroes now, because their position must be between second and third rows. + if ( ii == 2 * ARENAW - 1 ) { RedrawOpponents(); } }
codereview_cpp_data_2854
SimTK_TEST(b->getStateVariableValue(s, "../subState") == 20); SimTK_TEST(b->getStateVariableValue(s, "../../internalSub/subState") == 10); - top.getStateVariableValue(s, "a/b/subState"); SimTK_TEST_MUST_THROW_EXC( top.getStateVariableValue(s, "typo/b/subState"), OpenSim::Exception); I don't think L1079 is necessary (see L1072). SimTK_TEST(b->getStateVariableValue(s, "../subState") == 20); SimTK_TEST(b->getStateVariableValue(s, "../../internalSub/subState") == 10); SimTK_TEST_MUST_THROW_EXC( top.getStateVariableValue(s, "typo/b/subState"), OpenSim::Exception);
codereview_cpp_data_2855
License: Apache License v2.0 Group: Development Summary: RPC and serialization framework -Version: 0.12.0 Release: 0 URL: http://thrift.apache.org Packager: Thrift Developers <dev@thrift.apache.org> In master this should be changed to 1.0.0-dev? License: Apache License v2.0 Group: Development Summary: RPC and serialization framework +Version: 0.11.0 Release: 0 URL: http://thrift.apache.org Packager: Thrift Developers <dev@thrift.apache.org>
codereview_cpp_data_2872
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 i think it needs a return false if dbgassert 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
codereview_cpp_data_2875
* These should be close to the expected value and variance of the given distribution to pass. * @param dist The distribution to test */ -void sample_test(probability::geometric_dist::geometric_distribution& dist) { uint32_t n_tries = 1000000; std::vector<float> tries; tries.resize(n_tries); This parameter is only being accessed and not modified, so let us use `const`. ```suggestion void sample_test(const probability::geometric_dist::geometric_distribution& dist) { ``` * These should be close to the expected value and variance of the given distribution to pass. * @param dist The distribution to test */ +void sample_test(const probability::geometric_dist::geometric_distribution& dist) { uint32_t n_tries = 1000000; std::vector<float> tries; tries.resize(n_tries);
codereview_cpp_data_2881
h2o_buffer_consume(&generator->resp.receiving, parse_result); } - if (generator->resp.receiving->size == 0) { - h2o_doublebuffer_prepare_empty(&generator->resp.sending); - h2o_send(generator->req, NULL, 0, H2O_SEND_STATE_IN_PROGRESS); - } - return 0; } Would it be better if we placed this code at the end of `on_read`? I would anticipate that it would be natural for a FastCGI application to encode the headers in first FCGI_STDOUT record and body in the next record, and send at once. h2o_buffer_consume(&generator->resp.receiving, parse_result); } return 0; }
codereview_cpp_data_2887
for (ModelComponent& comp : updComponentList<ModelComponent>()) comp.preScale(s, scaleSet); - // Scale the model. if (!updSimbodyEngine().scale(s, scaleSet, finalMass, preserveMassDist)) return false; I kinda feel like the body of `SimbodyEngine::scale()` should be moved here. for (ModelComponent& comp : updComponentList<ModelComponent>()) comp.preScale(s, scaleSet); + // Scale the rest of the model. if (!updSimbodyEngine().scale(s, scaleSet, finalMass, preserveMassDist)) return false;
codereview_cpp_data_2899
* \author [Benjamin Walton](https://github.com/bwalton24) * \author [Shiqi Sheng](https://github.com/shiqisheng00) */ -#include <cassert> /// for assert -#include <cmath> /// for math functions #include <functional> /// for passing in functions #include <iostream> /// for IO operations ```suggestion #include <cassert> /// for assert #include <cmath> /// for mathematical functions #include <functional> /// for passing in functions #include <iostream> /// for IO operations ``` * \author [Benjamin Walton](https://github.com/bwalton24) * \author [Shiqi Sheng](https://github.com/shiqisheng00) */ +#include <cassert> /// for assert +#include <cmath> /// for mathematical functions #include <functional> /// for passing in functions #include <iostream> /// for IO operations
codereview_cpp_data_2907
for (auto entry : pfrom->xVersion.xmap) { auto iter = XVer::keytype.find(entry.first); - if (iter != XVer::keytype.end() && iter->second == "c") { pfrom->xState.emplace(entry); } So yeah, with the hypothetical `enum` above, this and the other places would become `iter->second == Xver::keytype_changeable` (use a better naming..) or so. for (auto entry : pfrom->xVersion.xmap) { auto iter = XVer::keytype.find(entry.first); + if (iter != XVer::keytype.end() && iter->second == XVer::keyTypes::changeable) { pfrom->xState.emplace(entry); }
codereview_cpp_data_2921
} } } // Notify the UI with the new block tip information. if (pindexMostWork->nHeight >= nHeight && pindexNewTip != nullptr && pindexLastNotify != pindexNewTip) why remove? I think at the very least, the next line (notify the UI) should not be run if an invalid block is found (since there's no new tip)... subsequent lines also seem unnecesssary. Is there a reason to continue processing blocks beyond an invalid one? } } } + if (fInvalidFound) + break; // stop processing more blocks if the last one was invalid. // Notify the UI with the new block tip information. if (pindexMostWork->nHeight >= nHeight && pindexNewTip != nullptr && pindexLastNotify != pindexNewTip)
codereview_cpp_data_2922
// Get a convenient and blocking way to interact with actors. caf::scoped_actor self{sys}; // Get VAST node. - auto node_opt = system::spawn_or_connect_to_node(self, "count.node", options, - content(sys.config())); if (auto err = caf::get_if<caf::error>(&node_opt)) return caf::make_message(std::move(*err)); auto& node = caf::holds_alternative<caf::actor>(node_opt) This whole dispatching logic seems very similar to `detail::make_(input|output)_stream`. I wonder if we can reuse this logic here. // Get a convenient and blocking way to interact with actors. caf::scoped_actor self{sys}; // Get VAST node. + auto node_opt + = system::spawn_or_connect_to_node(self, options, content(sys.config())); if (auto err = caf::get_if<caf::error>(&node_opt)) return caf::make_message(std::move(*err)); auto& node = caf::holds_alternative<caf::actor>(node_opt)
codereview_cpp_data_2923
* This will properly maintain the copyright information. DigitalGlobe * copyrights will be updated automatically. * - * @copyright Copyright (C) 2015, 2017 DigitalGlobe (http://www.digitalglobe.com/) */ #include "AddBboxVisitor.h" This new file should only have copyright 2018 * This will properly maintain the copyright information. DigitalGlobe * copyrights will be updated automatically. * + * @copyright Copyright (C) 2015, 2017, 2018 DigitalGlobe (http://www.digitalglobe.com/) */ #include "AddBboxVisitor.h"
codereview_cpp_data_2926
*/ if (!c->may_control(c)) { /* We're done with this container */ - if ( lxc_container_put(c) > 0 ) containers[i] = NULL; continue; You can remove the unnecessary spaces here as well. :) */ if (!c->may_control(c)) { /* We're done with this container */ + if (lxc_container_put(c) > 0) containers[i] = NULL; continue;