id
stringlengths
21
25
content
stringlengths
164
2.33k
codereview_cpp_data_10871
* the multiples. */ void sieve(uint32_t N, bool *isprime) { - isprime[0] = false; - isprime[1] = false; for (uint32_t i = 2; i * i <= N; i++) { - if (isprime[i]) { for (uint32_t j = i * i; j <= N; j = j + i) { - isprime[j] = false; } } } The original implementation was correct. * `i<<1` -> this means, start from `i*2` and mark all multiples of i as not-prime * What you have done: `i*i` -> this means, start from `i*i` and mark all multiples of i as not-prime. Thus, you have lost all numbers from `i*2` to `i*i`! * the multiples. */ void sieve(uint32_t N, bool *isprime) { + isprime[0] = true; + isprime[1] = true; for (uint32_t i = 2; i * i <= N; i++) { + if (!isprime[i]) { for (uint32_t j = i * i; j <= N; j = j + i) { + isprime[j] = true; } } }
codereview_cpp_data_10882
void GenericConstraintProblem::freeConstraintResolutions() { - for(unsigned int i=0; i<constraintsResolutions.size(); i++) { - if (constraintsResolutions[i] != nullptr) - { - delete constraintsResolutions[i]; - constraintsResolutions[i] = nullptr; - } } } Maybe if we want to keep the modern for-loop, the fix would be like this: (cannot make a suggestion) ``` for(auto* constraintsResolution : constraintsResolutions) { if (constraintsResolution != nullptr) { delete constraintsResolution; constraintsResolution = nullptr; } } ``` void GenericConstraintProblem::freeConstraintResolutions() { + for(auto*& constraintsResolution : constraintsResolutions) { + delete constraintsResolution; + constraintsResolution = nullptr; } }
codereview_cpp_data_10890
if (len == 1) { /* bind=src */ m->dest = construct_path(mntarray[0], false); } else if (len == 2) { /* bind=src:option or bind=src:dest */ - if (!strncmp(mntarray[1], "rw", strlen(mntarray[1]))) m->options = strdup("rw"); - if (!strncmp(mntarray[1], "ro", strlen(mntarray[1]))) m->options = strdup("ro"); if (m->options) Same as above,`== 0` syntax, please :) if (len == 1) { /* bind=src */ m->dest = construct_path(mntarray[0], false); } else if (len == 2) { /* bind=src:option or bind=src:dest */ + if (strncmp(mntarray[1], "rw", strlen(mntarray[1])) == 0) m->options = strdup("rw"); + if (strncmp(mntarray[1], "ro", strlen(mntarray[1])) == 0) m->options = strdup("ro"); if (m->options)
codereview_cpp_data_10896
struct jx *result = NULL; //Capture expression for select query before it gets evaluated - if(!strcmp("select", jx_print_string(o->left))) select_expr = jx_array_index(o->right, 0); right = jx_eval(o->right,context); if (jx_istype(right, JX_ERROR)) { If I'm reading this right, the goal here is to quote (in the lisp sense) the expression, so that it can be held over and evaluated solely against the target expressions, right? Two thoughts: - Is it necessary for select_expr to be a global? (I think that could be a problem if you have nested or parallel select expressions.) - What happens if the select expression refers to values in the current context? For example: `y = 10; select( x>y, fetch(url) )` This makes me wonder whether this problem will come up in other contexts, and perhaps we need to isolate the functionality in a quote function/operator, so you would write: `select( quote(x>y), fetch(url) )` struct jx *result = NULL; //Capture expression for select query before it gets evaluated + //Stringify it to prevent early evaluation + if(!strcmp("select", jx_print_string(o->left))) { + struct jx *r = jx_array_shift(o->right); + r = jx_string(jx_print_string((r))); + jx_array_insert(o->right, r); + fprintf(stderr, "inserting: %s\n", jx_print_string(o->right)); + } right = jx_eval(o->right,context); if (jx_istype(right, JX_ERROR)) {
codereview_cpp_data_10901
statusBar.SetCenter( dst_pt.x + bar.width() / 2, dst_pt.y + 12 ); // redraw resource panel - const Rect rectResource = RedrawResourcePanel( cur_pt ); // button exit dst_pt.x = cur_pt.x + 553; Please use `const reference`. statusBar.SetCenter( dst_pt.x + bar.width() / 2, dst_pt.y + 12 ); // redraw resource panel + const Rect & rectResource = RedrawResourcePanel( cur_pt ); // button exit dst_pt.x = cur_pt.x + 553;
codereview_cpp_data_10905
wlr_log(L_INFO, "Found %zu GPUs", num_gpus); for (size_t i = 0; i < num_gpus; ++i) { - struct wlr_backend *drm = wlr_drm_backend_create(display, session, gpus[i]); if (!drm) { wlr_log(L_ERROR, "Failed to open DRM device"); continue; Something that might be useful in the future is to specify a list of GPUs to use - then maybe you can run a different compositor on each GPU, for example. wlr_log(L_INFO, "Found %zu GPUs", num_gpus); for (size_t i = 0; i < num_gpus; ++i) { + struct wlr_backend *drm = wlr_drm_backend_create(display, session, + gpus[i], primary_drm); if (!drm) { wlr_log(L_ERROR, "Failed to open DRM device"); continue;
codereview_cpp_data_10916
std::shared_ptr<MockOrderingServicePersistentState> fake_persistent_state; }; TEST_F(OrderingGateServiceTest, SplittingBunchTransactions) { // 8 transaction -> proposal -> 2 transaction -> proposal Add given, when, then std::shared_ptr<MockOrderingServicePersistentState> fake_persistent_state; }; +/** + * @given ordering service + * @when a bunch of transaction has arrived + * @then proposal is sent + */ TEST_F(OrderingGateServiceTest, SplittingBunchTransactions) { // 8 transaction -> proposal -> 2 transaction -> proposal
codereview_cpp_data_10919
} } -void launchKernel(float* C, float* A, float* B, int N, bool manual){ hipDeviceProp_t devProp; HIP_CHECK(hipGetDeviceProperties(&devProp, 0)); We are effectively only checking if there are errors in the output of the 2nd kernel execution. Maybe we should either move the verification into the launchKernel function or get the kernel output into different buffers for both the kernel runs such as C0d and C1d. } } +void launchKernel(float* C, float* A, float* B, bool manual){ hipDeviceProp_t devProp; HIP_CHECK(hipGetDeviceProperties(&devProp, 0));
codereview_cpp_data_10927
EXPECT_FAILURE_WITH_ERRNO(s2n_find_security_policy_from_version("PQ-SIKE-TEST-TLS-1-0-2019-11", &security_policy), S2N_ERR_INVALID_SECURITY_POLICY); EXPECT_FAILURE_WITH_ERRNO(s2n_find_security_policy_from_version("PQ-SIKE-TEST-TLS-1-0-2020-02", &security_policy), S2N_ERR_INVALID_SECURITY_POLICY); EXPECT_FAILURE_WITH_ERRNO(s2n_find_security_policy_from_version("KMS-PQ-TLS-1-0-2020-02", &security_policy), S2N_ERR_INVALID_SECURITY_POLICY); - EXPECT_FAILURE_WITH_ERRNO(s2n_find_security_policy_from_version("KMS-PQ-TLS-1-0-2020-05", &security_policy), S2N_ERR_INVALID_SECURITY_POLICY); #endif security_policy = NULL; Typo in the security policy string, should read `KMS-PQ-TLS-1-0-2020-07` EXPECT_FAILURE_WITH_ERRNO(s2n_find_security_policy_from_version("PQ-SIKE-TEST-TLS-1-0-2019-11", &security_policy), S2N_ERR_INVALID_SECURITY_POLICY); EXPECT_FAILURE_WITH_ERRNO(s2n_find_security_policy_from_version("PQ-SIKE-TEST-TLS-1-0-2020-02", &security_policy), S2N_ERR_INVALID_SECURITY_POLICY); EXPECT_FAILURE_WITH_ERRNO(s2n_find_security_policy_from_version("KMS-PQ-TLS-1-0-2020-02", &security_policy), S2N_ERR_INVALID_SECURITY_POLICY); + EXPECT_FAILURE_WITH_ERRNO(s2n_find_security_policy_from_version("KMS-PQ-TLS-1-0-2020-07", &security_policy), S2N_ERR_INVALID_SECURITY_POLICY); #endif security_policy = NULL;
codereview_cpp_data_10941
Status ClusterAdminClient::MasterLeaderStepDown( const string& leader_uuid, - const string& new_leader_uuid = std::string()) { auto master_proxy = std::make_unique<ConsensusServiceProxy>(proxy_cache_.get(), leader_addr_); - return LeaderStepDown(leader_uuid, yb::master::kSysCatalogTabletId, new_leader_uuid, &master_proxy); } CHECKED_STATUS ClusterAdminClient::LeaderStepDownWithNewLeader( Default value for argument must be written in header file only. Status ClusterAdminClient::MasterLeaderStepDown( const string& leader_uuid, + const string& new_leader_uuid) { auto master_proxy = std::make_unique<ConsensusServiceProxy>(proxy_cache_.get(), leader_addr_); + return LeaderStepDown(leader_uuid, yb::master::kSysCatalogTabletId, + new_leader_uuid, &master_proxy); } CHECKED_STATUS ClusterAdminClient::LeaderStepDownWithNewLeader(
codereview_cpp_data_10949
EXPECT_SUCCESS(s2n_connection_free(conn)); } - /* The default s2n socket read/write setup can be used with a user-defined send/recv context */ { static const int READFD = 1; static const int WRITEFD = 2; A customer doesn't have access to the internal structure we expect for the default socket read/write, so there's no way they could set a valid custom context to use with that callback. We need the managed/custom status of the callback and context to match. Maybe set the callback to NULL if the context is set first and io was managed (and vice versa)? EXPECT_SUCCESS(s2n_connection_free(conn)); } + /* The default s2n socket read/write setup can be used with a user-defined send/recv setup */ { static const int READFD = 1; static const int WRITEFD = 2;
codereview_cpp_data_10952
for (int i = 0; i < numLoop; ++i) { model.setStateVariableValues(s, stateValues); - // Direct set values for coordinates does not ensure they // satisfy kinematic constraints. Explicitly enforce constraints - // by performing and assembly, now. model.assemble(s); } - "Direct set" -> "Directly setting" - "an~d~ assembly" for (int i = 0; i < numLoop; ++i) { model.setStateVariableValues(s, stateValues); + // Directly setting values for coordinates does not ensure they // satisfy kinematic constraints. Explicitly enforce constraints + // by performing an assembly, now. model.assemble(s); }
codereview_cpp_data_10957
return 0; if (tsc != NULL) { if (tsc->option&hide_flag - && !is_boss - && (tsd->special_state.perfect_hiding || !is_detect || tsc->data[SC_CLOAKINGEXCEED] != NULL || tsc->data[SC_NEWMOON] != NULL) ) return 0; if (tsc->data[SC_CAMOUFLAGE] && !(is_boss || is_detect) && flag == 0) this condition can be simplified into this ``&& (tsd->special_state.perfect_hiding || !is_detect || tsc->data[SC_CLOAKINGEXCEED] != NULL || tsc->data[SC_NEWMOON] != NULL)`` return 0; if (tsc != NULL) { if (tsc->option&hide_flag + && !is_boss + && ((tsd->special_state.perfect_hiding || !is_detect) || ((tsc->data[SC_CLOAKINGEXCEED] != NULL || tsc->data[SC_NEWMOON] != NULL) && is_detect)) ) return 0; if (tsc->data[SC_CAMOUFLAGE] && !(is_boss || is_detect) && flag == 0)
codereview_cpp_data_10971
{ if (result) { - printf("ScaFaCoS Error: Caught error on task %d.\n", comm_rank); std::string err_msg; std::stringstream ss; Please don't use `printf()`, but `fprintf(screen,...)` and `fprintf(logfile, ...)` provided either FILE pointer is non-NULL. Please note, that calling error->all() requires, that this function is called from *all* MPI ranks on the communicator `world`, otherwise you need to call error->one(). If however `check_results()` *is* called from all MPI ranks on `world`, then only MPI rank 0 should be producing output from `fprintf()` or else the screen would have all messages replicated by the number of MPI ranks in use. { if (result) { + fprintf(stdout,"ScaFaCoS Error: Caught error on task %d.\n", comm_rank); std::string err_msg; std::stringstream ss;
codereview_cpp_data_10973
t << endl << "clean:" << endl - << "\trm -f " - << "rm -f $(CLEAN_FILES)" << endl; } static void writeMakeBat() Look a bit double here, shouldn't this just be `\t"rm -f $(CLEAN_FILES)" << endl;` t << endl << "clean:" << endl + << "\trm -f $(CLEAN_FILES)" << endl; } static void writeMakeBat()
codereview_cpp_data_10979
return [=](const curried_predicate&) { return row_ids; }; }); } - // Predicate of form "&time == ..." if (ex.attr == system::time_atom::value) { VAST_ASSERT(caf::holds_alternative<timestamp>(x)); // Find the column with attribute 'time'. Is this really always an equality? It seems the `if` statement below is enough to tell the user that we're dealing with a `&time` extractor. return [=](const curried_predicate&) { return row_ids; }; }); } if (ex.attr == system::time_atom::value) { VAST_ASSERT(caf::holds_alternative<timestamp>(x)); // Find the column with attribute 'time'.
codereview_cpp_data_10981
label->setStyleSheet("QLabel { font: bold; }"); vLayout->addWidget(label); m_northAxisEdit = new OSQuantityEdit(m_isIP); - bool isConnected = connect(this, SIGNAL(toggleUnitsClicked(bool)), m_northAxisEdit, SLOT(onUnitSystemChange(bool))); OS_ASSERT(isConnected); vLayout->addWidget(m_northAxisEdit); @axelstudios We commonly define the isConnected variable first and then use it when there are a lot of connects, that way you can change the order of the connects easily label->setStyleSheet("QLabel { font: bold; }"); vLayout->addWidget(label); + bool isConnected = false; + m_northAxisEdit = new OSQuantityEdit(m_isIP); + isConnected = connect(this, SIGNAL(toggleUnitsClicked(bool)), m_northAxisEdit, SLOT(onUnitSystemChange(bool))); OS_ASSERT(isConnected); vLayout->addWidget(m_northAxisEdit);
codereview_cpp_data_10987
if ( !needRedraw && !listbox.IsNeedRedraw() ) { continue; } - currentPressedButton->press(); listbox.Redraw(); buttonOk.draw(); This needs a bit of explanation as I see such change as a hack. Could you please provide more information why we need to this? if ( !needRedraw && !listbox.IsNeedRedraw() ) { continue; } listbox.Redraw(); buttonOk.draw();
codereview_cpp_data_10991
} for ( kc = sf->kerns; kc!=NULL; kc=kc->next ) { - firsts = malloc(kc->first_cnt*sizeof(SplineChar *)); map1 = calloc(kc->first_cnt,sizeof(int)); seconds = malloc(kc->second_cnt*sizeof(SplineChar **)); map2 = calloc(kc->second_cnt,sizeof(int)); `firsts` and `seconds` have the same type and are first assigned in the same way. So why the difference here? } for ( kc = sf->kerns; kc!=NULL; kc=kc->next ) { + firsts = malloc(kc->first_cnt*sizeof(SplineChar **)); map1 = calloc(kc->first_cnt,sizeof(int)); seconds = malloc(kc->second_cnt*sizeof(SplineChar **)); map2 = calloc(kc->second_cnt,sizeof(int));
codereview_cpp_data_11005
--throughput_publisher_.data_discovery_count_; } - lock.unlock(); - if (throughput_publisher_.data_discovery_count_ == static_cast<int>(throughput_publisher_.subscribers_)) { throughput_publisher_.data_discovery_cv_.notify_one(); } } // ******************************************************************************************* Should this be done before unlocking, as it is done below? --throughput_publisher_.data_discovery_count_; } if (throughput_publisher_.data_discovery_count_ == static_cast<int>(throughput_publisher_.subscribers_)) { throughput_publisher_.data_discovery_cv_.notify_one(); } + lock.unlock(); } // *******************************************************************************************
codereview_cpp_data_11006
/* Store public key at cert_chain to cut down expensive use of s2n_asn1der_to_public_key_and_type */ chain_and_key->cert_chain->head->public_key = public_key; /* Populate name information from the SAN/CN for the leaf certificate */ POSIX_GUARD(s2n_cert_chain_and_key_set_names(chain_and_key, &chain_and_key->cert_chain->head->raw)); - ZERO_TO_DISABLE_DEFER_CLEANUP(public_key); return 0; } What if line 346 fails? Shouldn't you ZERO_TO_DISABLE_DEFER_CLEANUP immediately before/after line 343? /* Store public key at cert_chain to cut down expensive use of s2n_asn1der_to_public_key_and_type */ chain_and_key->cert_chain->head->public_key = public_key; + ZERO_TO_DISABLE_DEFER_CLEANUP(public_key); /* Populate name information from the SAN/CN for the leaf certificate */ POSIX_GUARD(s2n_cert_chain_and_key_set_names(chain_and_key, &chain_and_key->cert_chain->head->raw)); return 0; }
codereview_cpp_data_11022
// the location of the point in the inertial reference frame. upd_location() = currentFrame.findLocationInAnotherFrame(s, get_location(), body); - // now assign this point's body to point to aBody setParentFrame(body); } Perhaps clearer as `// now make "body" this PathPoint's parent Frame` // the location of the point in the inertial reference frame. upd_location() = currentFrame.findLocationInAnotherFrame(s, get_location(), body); + // now make "body" this PathPoint's parent Frame setParentFrame(body); }
codereview_cpp_data_11023
} else { track_sendmsg_success(); } - track_sendmsg_flush(ctx->loop); return 1; } I wonder if we need to log anything when there is no loss. To paraphrase, it might make sense to convert `track_sendmsg_flush` into a subroutine of `track_sendmsg_failure`. The other benefit of merging `track_sendmsg_flush` into `track_sendmsg_failure` is that we can get rid of `last_errno`. `errno` would always be available when we log the message. } else { track_sendmsg_success(); } return 1; }
codereview_cpp_data_11040
if(ast_childcount(params) != 1) { ast_error(opt->check.errors, params, - "A Main actor must have a create constructor which takes a single Env " "parameter"); ok = false; } How do you feel about "The Main actor" instead of "A Main actor", while we're already here changing the message? if(ast_childcount(params) != 1) { ast_error(opt->check.errors, params, + "The Main actor must have a create constructor which takes a single Env " "parameter"); ok = false; }
codereview_cpp_data_11051
for(auto chr=s.begin();chr<=s.end(); ++chr) { if(*chr == '.' || *chr == 0) continue; - id += std::tolower(*chr); } return id; } `id += std::tolower(*chr); ` >> `id += tolower(*chr); ` Hi~, If it change like this, it might be successfully compiled on Appveyor ci. for(auto chr=s.begin();chr<=s.end(); ++chr) { if(*chr == '.' || *chr == 0) continue; + id += tolower(*chr); } return id; }
codereview_cpp_data_11055
_AssertBoosterHandleNotNull(handle); R_API_BEGIN(); CHECK_CALL(LGBM_BoosterAddValidData(R_ExternalPtrAddr(handle), R_ExternalPtrAddr(valid_data))); - R_API_END(); return R_NilValue; } SEXP LGBM_BoosterResetTrainingData_R(SEXP handle, Same question. ```suggestion _AssertBoosterHandleNotNull(handle); _AssertDatasetHandleNotNull(train_data); ``` _AssertBoosterHandleNotNull(handle); R_API_BEGIN(); CHECK_CALL(LGBM_BoosterAddValidData(R_ExternalPtrAddr(handle), R_ExternalPtrAddr(valid_data))); return R_NilValue; + R_API_END(); } SEXP LGBM_BoosterResetTrainingData_R(SEXP handle,
codereview_cpp_data_11087
if (is_present) { std::shared_ptr<shared_model::interface::TransactionResponse> response = - status_factory_->makeCommitted(request, "", 0, 0); cache_->addItem(request, response); return response; } else { log_->warn("Asked non-existing tx: {}", request.hex()); - return status_factory_->makeNotReceived(request, "", 0, 0); } } I have two suggestions here: * Use default parameters from the factory. * And move error plus codes to one entity. It should be like ```suggestion status_factory_->makeCommitted(request, TxStatusFactory::emptyError()); ``` Where empty error returns class which contains: {error_msg, index, code} if (is_present) { std::shared_ptr<shared_model::interface::TransactionResponse> response = + status_factory_->makeCommitted(request); cache_->addItem(request, response); return response; } else { log_->warn("Asked non-existing tx: {}", request.hex()); + return status_factory_->makeNotReceived(request); } }
codereview_cpp_data_11106
return mItems[i]->mId; } - return 0; } //------------------------------------------------------------------------------ mmmmm welcome to the fucking world of TS ids... -1 or 0 for invalid? return mItems[i]->mId; } + return -1; } //------------------------------------------------------------------------------
codereview_cpp_data_11110
fheroes2::Button buttonOk( rt.x + 34, rt.y + 315, ICN::REQUEST, 1, 2 ); fheroes2::Button buttonCancel( rt.x + 244, rt.y + 315, ICN::REQUEST, 3, 4 ); - bool edit_mode = true; MapsFileInfoList lists = GetSortedMapsFileInfoList(); FileInfoListBox listbox( rt.getPosition(), edit_mode ); This change allows to edit save files for Save file Loading screen. fheroes2::Button buttonOk( rt.x + 34, rt.y + 315, ICN::REQUEST, 1, 2 ); fheroes2::Button buttonCancel( rt.x + 244, rt.y + 315, ICN::REQUEST, 3, 4 ); + bool edit_mode = editor; MapsFileInfoList lists = GetSortedMapsFileInfoList(); FileInfoListBox listbox( rt.getPosition(), edit_mode );
codereview_cpp_data_11121
hasStatus = true; if (_textStatus) { - writer.writeAttribute("v", QString("%1").arg(n->getStatus().toTextStatus())); } else { My eyeball compiler seems to think that you could write this line as: `writer.writeAttribute("v", n->getStatus().toTextStatus());` Without the `QString("%1").arg` business. hasStatus = true; if (_textStatus) { + writer.writeAttribute("v", n->getStatus().toTextStatus()); } else {
codereview_cpp_data_11138
return mrb_funcall(mrb, mrb_top_self(mrb), "eval", 1, mrb_str_new_cstr(mrb, expr)); } -void h2o_mruby_define_callback(mrb_state *mrb, const char *name, h2o_mruby_callback callback) { h2o_mruby_shared_context_t *shared_ctx = mrb->ud; - h2o_vector_reserve(NULL, &shared_ctx->callbacks, ++shared_ctx->callbacks.size); - shared_ctx->callbacks.entries[shared_ctx->callbacks.size - 1] = callback; mrb_value args[2]; args[0] = mrb_str_new_cstr(mrb, name); I would appreciate it if you could change the code to the following. It is kind-of aesthetic, but by doing so we can have the guarantee that all the objects stored in the vector are initialized. ``` h2o_vector_reserve(NULL, &shared_ctx->callbacks, shared_ctx->callbacks.size + 1); shared_ctx->callbacks.entries[shared_ctx->callbacks.size++] = callback; ``` return mrb_funcall(mrb, mrb_top_self(mrb), "eval", 1, mrb_str_new_cstr(mrb, expr)); } +void h2o_mruby_define_callback(mrb_state *mrb, const char *name, h2o_mruby_callback_t callback) { h2o_mruby_shared_context_t *shared_ctx = mrb->ud; + h2o_vector_reserve(NULL, &shared_ctx->callbacks, shared_ctx->callbacks.size + 1); + shared_ctx->callbacks.entries[shared_ctx->callbacks.size++] = callback; mrb_value args[2]; args[0] = mrb_str_new_cstr(mrb, name);
codereview_cpp_data_11159
return; // helpers for combining building effects into a single line - std::vector<std::string> combinedNames; - float combinedChange = 0.0; // add label-value pairs for each alteration recorded for this meter for (auto it = maybe_info_vec->begin(); it != maybe_info_vec->end(); ++it) { auto info = *it; prefer `combined_names` and `combined_change` format put `0.0f` for float constants return; // helpers for combining building effects into a single line + std::vector<std::string> combined_names; + float combined_meter_change = 0.0f; // add label-value pairs for each alteration recorded for this meter for (auto it = maybe_info_vec->begin(); it != maybe_info_vec->end(); ++it) { auto info = *it;
codereview_cpp_data_11161
for (int i = 0; i < preferences->count; ++i) { if (0 == strcmp(preferences->suites[i]->name, conn->secure.cipher_suite->name) && /* make sure we dont use a tls version lower than that configured by the version */ - conn->secure.cipher_suite->minimum_required_tls_version >= preferences->suites[i]->minimum_required_tls_version) { return 0; } } minimum_required_tls_version in cipher is used to verify if cipher is supposed to be available for this TLS version - it's not a strict enforcement on which protocol version connection needs to use. You need to check `preference->minimum_protocol_version` against `conn->actual_protocol_verison` to achieve what you want. for (int i = 0; i < preferences->count; ++i) { if (0 == strcmp(preferences->suites[i]->name, conn->secure.cipher_suite->name) && /* make sure we dont use a tls version lower than that configured by the version */ + s2n_connection_get_actual_protocol_version(conn) >= preferences->suites[i]->minimum_required_tls_version) { return 0; } }
codereview_cpp_data_11172
-// Copyright 2013 Yangqing Jia #include "caffe/common.hpp" Copyright should no longer be me :) +// Copyright 2014 Sergio Guadarrama #include "caffe/common.hpp"
codereview_cpp_data_11177
#ifdef VAST_HAVE_SNAPPY methods.push_back(compression::snappy); #endif - std::vector<size_t> block_sizes = {1, 2, 64, 256, 1_KiB, 16_MiB}; auto data = "Im Kampf zwischen dir und der Welt sekundiere der Welt."s; auto inflation = 1000; for (auto block_size : block_sizes) { Was this wrong before or did you mean to write `16_KiB`? #ifdef VAST_HAVE_SNAPPY methods.push_back(compression::snappy); #endif + std::vector<size_t> block_sizes = {1, 2, 64, 256, 1_KiB, 16_KiB}; auto data = "Im Kampf zwischen dir und der Welt sekundiere der Welt."s; auto inflation = 1000; for (auto block_size : block_sizes) {
codereview_cpp_data_11181
/** * Default constructor. */ -Station::Station() : Super() { setNull(); constructInfrastructure(); } Station::Station(const PhysicalFrame& frame, const SimTK::Vec3& location) - : Super() { setNull(); constructInfrastructure(); No need to change, but we don't use this convention in general (of using the `Super` typedef in constructors); we should be consistent. /** * Default constructor. */ +Station::Station() : Point() { setNull(); constructInfrastructure(); } Station::Station(const PhysicalFrame& frame, const SimTK::Vec3& location) + : Point() { setNull(); constructInfrastructure();
codereview_cpp_data_11188
m_Impl << "!" << valName << ".IsString())" << std::endl << "\t\t\t\t" << "BOOST_THROW_EXCEPTION(ValidationError(dynamic_cast<ConfigObject *>(this), { \"" - << field.Name << R"(" }, "Object '" + )" << valName << R"( + "' of type ')" - << field.Type.TypeName - << "' has an invalid name.\"));" << std::endl; } m_Impl << "\t\t\t" << "if ("; That part of the condition structure differs from the already existing one. Why? m_Impl << "!" << valName << ".IsString())" << std::endl << "\t\t\t\t" << "BOOST_THROW_EXCEPTION(ValidationError(dynamic_cast<ConfigObject *>(this), { \"" + << field.Name << R"(" }, "It is not allowed to specify '" + )" << valName << R"( + "' of type '" + )" + << valName << ".GetTypeName()" << R"( + "' as ')" << field.Type.TypeName + << "' name. Expected type of '" << field.Type.TypeName << "' name 'String'.\"));" << std::endl; } m_Impl << "\t\t\t" << "if (";
codereview_cpp_data_11191
{ "UniformConstraint", Pluginized("v20.12", "SofaConstraint") }, { "UnilateralInteractionConstraint", Pluginized("v20.12", "SofaConstraint") }, - // LMConstraint was pluginized in #1592 { "BaseLMConstraint", Pluginized("v20.12", "LMConstraint") }, { "LMConstraint", Pluginized("v20.12", "LMConstraint") }, { "TetrahedronBarycentricDistanceLMConstraintContact", Pluginized("v20.12", "LMConstraint") }, Copy-paste is bad #1659 { "UniformConstraint", Pluginized("v20.12", "SofaConstraint") }, { "UnilateralInteractionConstraint", Pluginized("v20.12", "SofaConstraint") }, + // LMConstraint was pluginized in #1659 { "BaseLMConstraint", Pluginized("v20.12", "LMConstraint") }, { "LMConstraint", Pluginized("v20.12", "LMConstraint") }, { "TetrahedronBarycentricDistanceLMConstraintContact", Pluginized("v20.12", "LMConstraint") },
codereview_cpp_data_11196
return details.rewards.at(index).award_id; } - return 0; } long long MegaAchievementsDetailsPrivate::getRewardStorage(unsigned int index) Better to return -1 to signal the index was not found, so you cannot use the returned value as a valid award id return details.rewards.at(index).award_id; } + return -1; } long long MegaAchievementsDetailsPrivate::getRewardStorage(unsigned int index)
codereview_cpp_data_11209
} /** - * @brief Self-test implementations to test - * the `integral_approx` function. * * @returns `void` */ ```suggestion * @brief Self-test implementations to * test the `integral_approx` function. ``` } /** + * @brief Self-test implementations to + * test the `integral_approx` function. * * @returns `void` */
codereview_cpp_data_11210
#if !AMREX_DEVICE_COMPILE namespace { -// Having both host and device versions to avoid compiler warning -AMREX_GPU_HOST_DEVICE void write_lib_id(const char* msg) { Seems that we can remove these 2 lines now. It was added for HIP. But with the new way, it's not needed anymore. #if !AMREX_DEVICE_COMPILE namespace { void write_lib_id(const char* msg) {
codereview_cpp_data_11211
settingsCache->setPicsPath(dataDir + "/pics"); } if (!QDir().mkpath(settingsCache->getPicsPath() + "/CUSTOM")) - qDebug("Could not create " + settingsCache->getPicsPath().toLatin1() + "/CUSTOM. Will fall back on default card images."); #ifdef Q_OS_MAC if(settingsCache->getHandBgPath().isEmpty() && This should probably be `.toUtf8` settingsCache->setPicsPath(dataDir + "/pics"); } if (!QDir().mkpath(settingsCache->getPicsPath() + "/CUSTOM")) + qDebug("Could not create " + settingsCache->getPicsPath().toUtf8() + "/CUSTOM. Will fall back on default card images."); #ifdef Q_OS_MAC if(settingsCache->getHandBgPath().isEmpty() &&
codereview_cpp_data_11214
" \"http2-errors.connect\": %" PRIu64 ", \n" " \"http2-errors.enhance-your-calm\": %" PRIu64 ", \n" " \"http2-errors.inadequate-security\": %" PRIu64 ", \n" - " \"http2-errors.idle-timeout\": %" PRIu64 ", \n" " \"http2.read-closed\": %" PRIu64 ", \n" " \"http2.write-closed\": %" PRIu64 ", \n" " \"ssl.errors\": %" PRIu64 ", \n" I think this should be named "http2.idle-timeout", and be placed after "http2.write_closed", due to the following reasons: * Doing so aligns the order with h2o_context_t and st_events_status_ctx_t. * Closing a connection due to idle timeout is not an error. It is much closer to "read-close" or "write-close" that we have right below. " \"http2-errors.connect\": %" PRIu64 ", \n" " \"http2-errors.enhance-your-calm\": %" PRIu64 ", \n" " \"http2-errors.inadequate-security\": %" PRIu64 ", \n" + " \"http2.idle-timeout\": %" PRIu64 ", \n" " \"http2.read-closed\": %" PRIu64 ", \n" " \"http2.write-closed\": %" PRIu64 ", \n" " \"ssl.errors\": %" PRIu64 ", \n"
codereview_cpp_data_11216
g_return_val_if_fail (repo != NULL, FALSE); g_return_val_if_fail (ref != NULL, FALSE); g_return_val_if_fail (out_rev != NULL, FALSE); if (ostree_repo_resolve_rev (repo, ref, FALSE, out_rev, &my_error)) return TRUE; Shouldn't this be a `g_return_val_if_fail` at the top of the function? It is not under this function's (direct) control. g_return_val_if_fail (repo != NULL, FALSE); g_return_val_if_fail (ref != NULL, FALSE); g_return_val_if_fail (out_rev != NULL, FALSE); + g_return_val_if_fail (*out_rev == NULL, FALSE); if (ostree_repo_resolve_rev (repo, ref, FALSE, out_rev, &my_error)) return TRUE;
codereview_cpp_data_11219
if (larger_leaf_histogram_array_ != nullptr && !use_subtract) { // construct larger leaf hist_t* ptr_larger_leaf_hist_data = - larger_leaf_histogram_array_[0].RawData() - kHistOffset * offset; train_data_->ConstructHistograms( is_feature_used, larger_leaf_splits_->data_indices(), larger_leaf_splits_->num_data_in_leaf(), gradients_, hessians_, need to update the distributed learner accordingly. if (larger_leaf_histogram_array_ != nullptr && !use_subtract) { // construct larger leaf hist_t* ptr_larger_leaf_hist_data = + larger_leaf_histogram_array_[0].RawData() - kHistOffset * first_feature_hist_offset_; train_data_->ConstructHistograms( is_feature_used, larger_leaf_splits_->data_indices(), larger_leaf_splits_->num_data_in_leaf(), gradients_, hessians_,
codereview_cpp_data_11226
// utf8 output with std::cout (since we already use cout so much and it's compatible with other platforms) // unicode input with windows ReadConsoleInput api // drag and drop filenames from explorer to the console window // upload and download unicode/utf-8 filenames to/from Mega // input a unicode/utf8 password without displaying anything - // normal cmd window type editing (but no autocomplete, as yet - we could add it now though) // the console must have a suitable font selected for the characters to diplay properly BOOL ok; autocomplete is working too now, isn't it? // utf8 output with std::cout (since we already use cout so much and it's compatible with other platforms) // unicode input with windows ReadConsoleInput api // drag and drop filenames from explorer to the console window + // copy and paste unicode filenames from 'ls' output into your next command // upload and download unicode/utf-8 filenames to/from Mega // input a unicode/utf8 password without displaying anything + // normal cmd window type editing, including autocomplete (with runtime selectable unix style or dos style, default to local platform rules) // the console must have a suitable font selected for the characters to diplay properly BOOL ok;
codereview_cpp_data_11242
case ATTR_AUTHCU255: // fall-through case ATTR_AUTHRSA: // fall-through case ATTR_MY_BACKUPS_FOLDER: // fall-through -#ifdef ENABLE_SYNC case ATTR_BACKUP_NAMES: // fall-through -#endif { LOG_debug << User::attr2string(type) << " has changed externally. Fetching..."; if (User::isAuthring(type)) mAuthRings.erase(type); this shouldn't be restricted to SYNCS, shouldn't it? case ATTR_AUTHCU255: // fall-through case ATTR_AUTHRSA: // fall-through case ATTR_MY_BACKUPS_FOLDER: // fall-through case ATTR_BACKUP_NAMES: // fall-through { LOG_debug << User::attr2string(type) << " has changed externally. Fetching..."; if (User::isAuthring(type)) mAuthRings.erase(type);
codereview_cpp_data_11256
* * Once we've determined all the needed data, we make a temporary directory, and * start writing out files inside it. This temporary directory is then turned - * into the OIRPM (what looks like a plain old RPM) by invoking `rpmbuild` using * a `.spec` file. * - * The resulting "rojig set" is then that OIRPM, plus the exact NEVRAs - we also * record the repodata checksum (normally sha256), to ensure that we get the * *exact* RPMs we require bit-for-bit. */ We might as well also `s/OIRPM/rojigRPM/` throughout when we rename the whole codebase too. WDYT? (Not for this pass, since as you mentioned, this is focusing on user-visible bits only). * * Once we've determined all the needed data, we make a temporary directory, and * start writing out files inside it. This temporary directory is then turned + * into the rojigRPM (what looks like a plain old RPM) by invoking `rpmbuild` using * a `.spec` file. * + * The resulting "rojig set" is then that rojigRPM, plus the exact NEVRAs - we also * record the repodata checksum (normally sha256), to ensure that we get the * *exact* RPMs we require bit-for-bit. */
codereview_cpp_data_11258
auto signatories = wsv_query->getSignatories(qry.creatorAccountId()); const auto &sig = qry.signatures(); - return boost::range_detail::range_calculate_size(sig) == 1 && signatories | [&sig](const auto &signatories) { return validation::signaturesSubset(sig, signatories); }; use boost::size instead auto signatories = wsv_query->getSignatories(qry.creatorAccountId()); const auto &sig = qry.signatures(); + return boost::size(sig) == 1 && signatories | [&sig](const auto &signatories) { return validation::signaturesSubset(sig, signatories); };
codereview_cpp_data_11259
ksAppendKey (ks, keyNew ("user/named/key", KEY_VALUE, "myvalue", KEY_END)); ksAppendKey (ks, keyNew ("system/named/syskey", KEY_VALUE, "syskey", KEY_END)); ksAppendKey (ks, keyNew ("system/sysonly/key", KEY_VALUE, "sysonlykey", KEY_END)); - ksAppendKey (ks, keyNew ("user/named/bin", KEY_BINARY, KEY_SIZE, sizeof ("binary\1\2data"), KEY_VALUE, "binary\1\2data", KEY_END)); - ksAppendKey (ks, keyNew ("system/named/bin", KEY_BINARY, KEY_SIZE, sizeof ("sys\1bin\2"), KEY_VALUE, "sys\1bin\2", KEY_END)); - ksAppendKey (ks, keyNew ("system/named/key", KEY_BINARY, KEY_SIZE, sizeof ("syskey"), KEY_VALUE, "syskey", KEY_END)); succeed_if (ksGetSize (ks) == 8, "could not append all keys"); // a positive testcase I am not sure if this was on purpose here, but we definitely should have tests where KEY_SIZE is shorter than the string. ksAppendKey (ks, keyNew ("user/named/key", KEY_VALUE, "myvalue", KEY_END)); ksAppendKey (ks, keyNew ("system/named/syskey", KEY_VALUE, "syskey", KEY_END)); ksAppendKey (ks, keyNew ("system/sysonly/key", KEY_VALUE, "sysonlykey", KEY_END)); + ksAppendKey (ks, keyNew ("user/named/bin", KEY_BINARY, KEY_SIZE, 10, KEY_VALUE, "binary\1\2data", KEY_END)); + ksAppendKey (ks, keyNew ("system/named/bin", KEY_BINARY, KEY_SIZE, 8, KEY_VALUE, "sys\1bin\2", KEY_END)); + ksAppendKey (ks, keyNew ("system/named/key", KEY_BINARY, KEY_SIZE, 6, KEY_VALUE, "syskey", KEY_END)); succeed_if (ksGetSize (ks) == 8, "could not append all keys"); // a positive testcase
codereview_cpp_data_11273
fheroes2::Rect ArmyBar::UpgradeButtonPos( const fheroes2::Rect & itemPos ) { - return fheroes2::Rect( itemPos.x + itemPos.width - 23, itemPos.y + 3, 20, 10 ); } bool ArmyBar::CanUpgradeNow( const ArmyTroop & troop ) const :warning: **modernize\-return\-braced\-init\-list** :warning: avoid repeating the return type from the declaration; use a braced initializer list instead ```suggestion return { itemPos.x + itemPos.width - 23, itemPos.y + 3, 20, 10 }; ``` fheroes2::Rect ArmyBar::UpgradeButtonPos( const fheroes2::Rect & itemPos ) { + return { itemPos.x + itemPos.width - 23, itemPos.y + 3, 20, 10 }; } bool ArmyBar::CanUpgradeNow( const ArmyTroop & troop ) const
codereview_cpp_data_11276
// For simplicity, we assume f(chi) ~ f(x), and | f'''''(xi) | ~ 1. // If step size is not specified, then we choose h so that // E_fl <= sqrt(epsilon) - const EvalType epsilon = std::pow(std::numeric_limits<EvalType>::epsilon(), 0.9); - const EvalType step_size = (m_step_size > DataType{0} ? m_step_size : std::fabs(objective) * El::Sqrt(epsilon)); EvalType expected_error = (epsilon * objective / step_size This means that we expect the numerical accuracy corresponding to `double`, so I'd expect all of our gradient checking with `float` layers to fail. Now that I think about it, the idea of a default error tolerance is tricky with mixed precision models. I think we should make the default correspond to `float`, and require the user to manually put in a tolerance if they're working with a model with non-`float` layers. ```suggestion const EvalType epsilon = std::pow(std::numeric_limits<float>::epsilon(), 0.9); ``` // For simplicity, we assume f(chi) ~ f(x), and | f'''''(xi) | ~ 1. // If step size is not specified, then we choose h so that // E_fl <= sqrt(epsilon) + // For the integrity of the test, the current implementation uses an + // epsilon based on the minimum step size of the float data type + const EvalType epsilon = std::pow(std::numeric_limits<DataType>::epsilon(), 0.9); + const EvalType step_size = (m_step_size > EvalType{0} ? m_step_size : std::fabs(objective) * El::Sqrt(epsilon)); EvalType expected_error = (epsilon * objective / step_size
codereview_cpp_data_11289
#include <inttypes.h> #include <netdb.h> #include <netinet/in.h> -#ifndef __ANDROID__ -#include <spawn.h> -#endif #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> Could you please remove `#include <spawn.h>` as a whole and see what happens? I believe that this is no longer needed; it was necessary when we called `posix_spawnp` directly, but now we use `h2o_spawnp`. #include <inttypes.h> #include <netdb.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <sys/socket.h>
codereview_cpp_data_11290
int s2n_connection_enable_quic(struct s2n_connection *conn) { - /* The QUIC RFC is not yet finalized, so all QUIC APIs are - * considered experimental and subject to change. - * They should only be used for testing purposes. - */ - ENSURE_POSIX(S2N_IN_TEST, S2N_ERR_NOT_IN_TEST); - /* The QUIC protocol doesn't use pre-1.3 TLS */ ENSURE_POSIX(s2n_is_tls13_enabled(), S2N_ERR_PROTOCOL_VERSION_UNSUPPORTED); I'm not a huge fan of conflating test mode with enabling QUIC support, as test mode could be opting in to other behavior outside of QUIC. Could it be an explicit define instead (e.g. `S2N_UNSTABLE_ENABLE_QUIC`)? int s2n_connection_enable_quic(struct s2n_connection *conn) { /* The QUIC protocol doesn't use pre-1.3 TLS */ ENSURE_POSIX(s2n_is_tls13_enabled(), S2N_ERR_PROTOCOL_VERSION_UNSUPPORTED);
codereview_cpp_data_11296
uint256 bitcoinCashForkBlockHash = uint256S("000000000000000000651ef99cb9fcbe0dadde1d424bd9f15ff20136191a5eec"); #ifdef ENABLE_MUTRACE -class PrintSomePointers { public: - PrintSomePointers() { printf("csBestBlock %p\n", &csBestBlock); printf("cvBlockChange %p\n", &cvBlockChange); sloppy class name? uint256 bitcoinCashForkBlockHash = uint256S("000000000000000000651ef99cb9fcbe0dadde1d424bd9f15ff20136191a5eec"); #ifdef ENABLE_MUTRACE +class CPrintSomePointers { public: + CPrintSomePointers() { printf("csBestBlock %p\n", &csBestBlock); printf("cvBlockChange %p\n", &cvBlockChange);
codereview_cpp_data_11311
ALLOCSET_DEFAULT_SIZES); OnConflictAction onconflict_action = ts_chunk_dispatch_get_on_conflict_action(dispatch); ResultRelInfo *resrelinfo, *relinfo; - bool has_compressed_chunk = (chunk->fd.compressed_chunk_id != 0); /* permissions NOT checked here; were checked at hypertable level */ if (check_enable_rls(chunk->table_id, InvalidOid, false) == RLS_ENABLED) Should `is_compressed` now be given by the chunk's compression status flag? Otherwise it looks like we have different ways of determining compression status. ALLOCSET_DEFAULT_SIZES); OnConflictAction onconflict_action = ts_chunk_dispatch_get_on_conflict_action(dispatch); ResultRelInfo *resrelinfo, *relinfo; + bool is_compressed = (chunk->fd.compressed_chunk_id != 0); /* permissions NOT checked here; were checked at hypertable level */ if (check_enable_rls(chunk->table_id, InvalidOid, false) == RLS_ENABLED)
codereview_cpp_data_11319
} void ReqRepHelloWorldRequester::init_with_latency( - eprosima::fastrtps::Duration_t latency_budget_duration_pub, - eprosima::fastrtps::Duration_t latency_budget_duration_sub) { ParticipantAttributes pattr; participant_ = Domain::createParticipant(pattr); Change arguments to const reference. } void ReqRepHelloWorldRequester::init_with_latency( + const eprosima::fastrtps::Duration_t& latency_budget_duration_pub, + const eprosima::fastrtps::Duration_t& latency_budget_duration_sub) { ParticipantAttributes pattr; participant_ = Domain::createParticipant(pattr);
codereview_cpp_data_11322
std::string name ) { - user = user; - pass = pass; - host = host; - name = name; - uint32 errnum = 0; char errbuf[MYSQL_ERRMSG_SIZE]; if (!Open( These members need renamed, otherwise it's just local self assignment std::string name ) { uint32 errnum = 0; char errbuf[MYSQL_ERRMSG_SIZE]; if (!Open(
codereview_cpp_data_11323
{ h2o_iovec_t value; - value.base = h2o_mem_alloc_pool(&req->pool, *value.base, - prefix_len + suffix_len + - sizeof(ELEMENT_LONGEST_STR("response") DELIMITER ELEMENT_LONGEST_STR("total"))); value.len = 0; if (prefix_len != 0) { Do we have enough space here now that we might also be sending timings for proxy-response and proxy-total? { h2o_iovec_t value; +#define LONGEST_STR \ + ELEMENT_LONGEST_STR("response") \ + DELIMITER ELEMENT_LONGEST_STR("total") DELIMITER ELEMENT_LONGEST_STR("proxy-response") \ + DELIMITER ELEMENT_LONGEST_STR("proxy-total") + + value.base = h2o_mem_alloc_pool(&req->pool, *value.base, prefix_len + suffix_len + sizeof(LONGEST_STR) - 1); value.len = 0; if (prefix_len != 0) {
codereview_cpp_data_11333
// and a full read of the subtree is initiated Sync::Sync(MegaClient* cclient, SyncConfig config, string* crootpath, const char* cdebris, string* clocaldebris, Node* remotenode, fsfp_t cfsfp, bool cinshare, int ctag, void *cappdata) -: localroot{new LocalNode} -, mConfig{config} { isnetwork = false; client = cclient; the round brackets that were already here definitely call a constructor - curlies add a lot more possibilities. Why change something that's perfectly fine, and possibly introduce problems? // and a full read of the subtree is initiated Sync::Sync(MegaClient* cclient, SyncConfig config, string* crootpath, const char* cdebris, string* clocaldebris, Node* remotenode, fsfp_t cfsfp, bool cinshare, int ctag, void *cappdata) +: localroot(new LocalNode) +, mConfig(config) { isnetwork = false; client = cclient;
codereview_cpp_data_11340
: dds::core::Reference<detail::DomainParticipant>( eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->create_participant( did, - eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->get_default_participant_qos())) { } Why not using the constant `PARTICIPANT_QOS_DEFAULT` here? : dds::core::Reference<detail::DomainParticipant>( eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->create_participant( did, + eprosima::fastdds::dds::PARTICIPANT_QOS_DEFAULT)) { }
codereview_cpp_data_11345
log_->info("Downloaded an empty chain"); continue; } else { - log_->info("Successfully downloaded {} blocks:", blocks.size()); } auto chain = I thing, this log entry should be moved under `if` below - we are not very interested in the fact of block download, only in successful one, and here we are not sure they will be applied log_->info("Downloaded an empty chain"); continue; } else { + log_->info("Successfully downloaded {} blocks", blocks.size()); } auto chain =
codereview_cpp_data_11346
*/ TEST_F(ChainValidationTest, ValidWhenValidateChainFromOnePeer) { // Valid previous hash, has supermajority, correct peers subset => valid - auto block = std::make_shared<BlockMock>(); - setupBlock(*block); - EXPECT_CALL(*supermajority_checker, hasSupermajority(_, _)) .WillOnce(Return(true)); Upwards value, here pointer. Is this done for purpose? */ TEST_F(ChainValidationTest, ValidWhenValidateChainFromOnePeer) { // Valid previous hash, has supermajority, correct peers subset => valid EXPECT_CALL(*supermajority_checker, hasSupermajority(_, _)) .WillOnce(Return(true));
codereview_cpp_data_11349
#include <iostream> #include <cstdint> /* Program that computes a^b in O(logN) time. Would it be possible to create some tests of the form: ```cpp #include <cassert> assert (fast_power_recursive(10, 3) == 1000); ``` that would raise an error if __fast_power_recursive()__ was modified incorrectly? Should we also test zero and negative values in our tests? #include <iostream> #include <cstdint> +#include <cassert> +#include <ctime> +#include <cmath> /* Program that computes a^b in O(logN) time.
codereview_cpp_data_11352
size_t offset = 0; UA_Connection *c = UA_NULL; UA_SecureChannel *sc = session->channel; - if(!sc) { response->responseHeader.serviceResult = UA_STATUSCODE_BADINTERNALERROR; return; } are you sure, you need to delete it? Here a connection was checked and not the secure channel. size_t offset = 0; UA_Connection *c = UA_NULL; UA_SecureChannel *sc = session->channel; + if(sc) + // FIXME: sc does not exist + c = session->sc; + if(!c) { response->responseHeader.serviceResult = UA_STATUSCODE_BADINTERNALERROR; return; }
codereview_cpp_data_11376
upgrader_flags |= RPMOSTREE_SYSROOT_UPGRADER_FLAGS_ALLOW_OLDER; OstreeSysroot *sysroot = rpmostreed_transaction_get_sysroot (transaction); - glnx_unref_object RpmOstreeSysrootUpgrader *upgrader = rpmostree_sysroot_upgrader_new (sysroot, self->osname, upgrader_flags, cancellable, error); if (upgrader == NULL) These can be `g_autoptr()` now too. upgrader_flags |= RPMOSTREE_SYSROOT_UPGRADER_FLAGS_ALLOW_OLDER; OstreeSysroot *sysroot = rpmostreed_transaction_get_sysroot (transaction); + g_autoptr(RpmOstreeSysrootUpgrader) upgrader = rpmostree_sysroot_upgrader_new (sysroot, self->osname, upgrader_flags, cancellable, error); if (upgrader == NULL)
codereview_cpp_data_11378
Py_INCREF(v); } } -#else -static CYTHON_INLINE void __Pyx_fill_sequence_from_array(PyObject *const *src, PyObject* dest, Py_ssize_t length) { - Py_ssize_t i; - for (i = 0; i < length; i++) { - PySequence_SetItem(dest, i, src[i]); - } -} -#endif static CYTHON_INLINE PyObject * __Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) This can fail and needs error handling. Py_INCREF(v); } } static CYTHON_INLINE PyObject * __Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n)
codereview_cpp_data_11389
if (boost::optional<Json::Value> _standardsArr = standard.getPrimaryKey(primaryKey)) { m_standardsArr = _standardsArr.get(); } } } should print a warning or error if not found right? if (boost::optional<Json::Value> _standardsArr = standard.getPrimaryKey(primaryKey)) { m_standardsArr = _standardsArr.get(); + } else { + // This should never happen really, until we implement the ability to supply a custom StandardsJSON + LOG(Error, "Cannot find the primaryKey '" << primaryKey << "' in the StandardsJSON"); } } }
codereview_cpp_data_11408
makedir(dirname.c_str()); std::string rng_name; rng_name = dirname + "/rng_seq_generator"; std::ofstream rng_seq(rng_name); rng_seq << ::data_seq_generator; Apparently, we have never been saving this RNG's state correctly. makedir(dirname.c_str()); std::string rng_name; + /// @todo - Note that the RNG with thread local data is not correct rng_name = dirname + "/rng_seq_generator"; std::ofstream rng_seq(rng_name); rng_seq << ::data_seq_generator;
codereview_cpp_data_11412
HandleAutoscroll(); } -#define TICK_15_INTERVAL (15 * MILLISECONDS_PER_TICK) -#define TICK_100_INTERVAL (100 * MILLISECONDS_PER_TICK) /** * Update the continuously changing contents of the windows, such as the viewports ick. Use consts instead? HandleAutoscroll(); } +static const uint TICK_15_INTERVAL = 15 * MILLISECONDS_PER_TICK; +static const uint TICK_100_INTERVAL = 100 * MILLISECONDS_PER_TICK; /** * Update the continuously changing contents of the windows, such as the viewports
codereview_cpp_data_11417
peer_query, storage, crypto_provider, - std::make_shared<shared_model::validation::BlockValidator>()); } std::shared_ptr<BlockLoader> BlockLoaderInit::initBlockLoader( this is your default value peer_query, storage, crypto_provider, + std::make_shared<shared_model::validation::DefaultBlockValidator>()); } std::shared_ptr<BlockLoader> BlockLoaderInit::initBlockLoader(
codereview_cpp_data_11425
shared_model::crypto::Keypair keypair = shared_model::crypto::DefaultCryptoAlgorithmType::generateKeypair(); - shared_model::crypto::Keypair pair = - shared_model::crypto::DefaultCryptoAlgorithmType::generateKeypair(); std::vector<shared_model::interface::types::PubkeyType> signatories = { keypair.publicKey()}; }; It looks like ```pair``` is not used at all. shared_model::crypto::Keypair keypair = shared_model::crypto::DefaultCryptoAlgorithmType::generateKeypair(); std::vector<shared_model::interface::types::PubkeyType> signatories = { keypair.publicKey()}; };
codereview_cpp_data_11431
blacklist ${HOME}/.config/Google blacklist ${HOME}/.config/Google Play Music Desktop Player blacklist ${HOME}/.config/Gpredict -blacklist ${HOME}/.config/homebank blacklist ${HOME}/.config/INRIA blacklist ${HOME}/.config/InSilmaril blacklist ${HOME}/.config/Jitsi Meet disable-programs is sorted alphabetically (as you saw) and case sensitive [with ~/.cache/* in a extra block]. So move it down (239:hexchat). blacklist ${HOME}/.config/Google blacklist ${HOME}/.config/Google Play Music Desktop Player blacklist ${HOME}/.config/Gpredict blacklist ${HOME}/.config/INRIA blacklist ${HOME}/.config/InSilmaril blacklist ${HOME}/.config/Jitsi Meet
codereview_cpp_data_11434
if (req->proxy_stats.ssl.cipher_bits == 0) goto EmitNull; RESERVE(sizeof(H2O_INT16_LONGEST_STR)); - pos += sprintf(pos, "%" PRIu16, req->proxy_stats.ssl.cipher_bits); break; case ELEMENT_TYPE_PROXY_SSL_PROTOCOL_VERSION: APPEND_SAFE_STRING(pos, req->proxy_stats.ssl.protocol_version); While it is fine to assume that the number of bits is below UINT16_MAX, I think we need to cast `req->proxy_stats.ssl.cipher_bits` to `uint16_t` explicitly. The type of the variable is `int`. if (req->proxy_stats.ssl.cipher_bits == 0) goto EmitNull; RESERVE(sizeof(H2O_INT16_LONGEST_STR)); + pos += sprintf(pos, "%" PRIu16, (uint16_t) req->proxy_stats.ssl.cipher_bits); break; case ELEMENT_TYPE_PROXY_SSL_PROTOCOL_VERSION: APPEND_SAFE_STRING(pos, req->proxy_stats.ssl.protocol_version);
codereview_cpp_data_11440
{ setAuthors("Matt DeMers, Ayman Habib, Ajay Seth"); constructProperties(); - FrameGeometry* frm = new FrameGeometry(0.2); - frm->setName("frame_geometry"); - frm->set_display_radius(.004); - frm->setRepresentation(Geometry::Hide); - append_GeometrySet(*frm); } This FrameGeometry object gets leaked at the end of this method. Since it is _copied_ to the GeometrySet property, it shouldn't be heap allocated here. { setAuthors("Matt DeMers, Ayman Habib, Ajay Seth"); constructProperties(); + FrameGeometry frm(0.2); + frm.setName("frame_geometry"); + frm.set_display_radius(.004); + frm.setRepresentation(Geometry::Hide); + append_GeometrySet(frm); }
codereview_cpp_data_11451
} } int main() { std::cout << "\nEnter the capacity of the knapsack : "; float capacity; ```suggestion } // namespace knapsack } // namespace greedy_algorithms using greedy_algorithms::knapsack::Item; using greedy_algorithms::knapsack::quickSort; ``` } } +} // namespace knapsack +} // namespace greedy_algorithms + +using greedy_algorithms::knapsack::Item; +using greedy_algorithms::knapsack::quickSort; + int main() { std::cout << "\nEnter the capacity of the knapsack : "; float capacity;
codereview_cpp_data_11455
*/ #include <gtest/gtest.h> -#include <ed25519/ed25519.h> -#include "backend/protobuf/common_objects/amount.hpp" #include "backend/protobuf/common_objects/proto_common_objects_factory.hpp" #include "builders/default_builders.hpp" #include "cryptography/crypto_provider/crypto_defaults.hpp" Can't it be substituted with just ```ASSERT_TRUE(err(peer));```? */ #include <gtest/gtest.h> #include "backend/protobuf/common_objects/proto_common_objects_factory.hpp" #include "builders/default_builders.hpp" #include "cryptography/crypto_provider/crypto_defaults.hpp"
codereview_cpp_data_11457
aiMatrix4x4 rx, ry, rz; aiMatrix4x4::RotationX(imp.rot.x, rx); - aiMatrix4x4::RotationX(imp.rot.y, ry); - aiMatrix4x4::RotationX(imp.rot.z, rz); pOut->mRootNode->mTransformation *= rx; pOut->mRootNode->mTransformation *= ry; pOut->mRootNode->mTransformation *= rz; Is this correct? Y have always used the x rotation. aiMatrix4x4 rx, ry, rz; aiMatrix4x4::RotationX(imp.rot.x, rx); + aiMatrix4x4::RotationY(imp.rot.y, ry); + aiMatrix4x4::RotationZ(imp.rot.z, rz); pOut->mRootNode->mTransformation *= rx; pOut->mRootNode->mTransformation *= ry; pOut->mRootNode->mTransformation *= rz;
codereview_cpp_data_11488
{ if (verbose > 2) { - printf("set Step selection: from %llu read %llu steps\n", s[0], - c[0]); } variable->SetStepSelection({s[0], c[0]}); } This format should be "... %" PRIu64 " steps\n", because s is uint64_t. { if (verbose > 2) { + printf("set Step selection: from %" PRIu64 " read %" PRIu64 + " steps\n", + s[0], c[0]); } variable->SetStepSelection({s[0], c[0]}); }
codereview_cpp_data_11489
num_discarded = 0; }, [=](size_t& num_discarded, const std::vector<table_slice>& slices) { - const auto num_rows - = std::transform_reduce(slices.begin(), slices.end(), size_t{}, - std::plus<>{}, [](const auto& slice) { - return slice.rows(); - }); - num_discarded += num_rows; }, [=](size_t& num_discarded, const caf::error& err) { if (num_discarded > 0) Style nit: This could just be ``` for (const auto& slice : slices) num_discarded += slice.rows(); ``` num_discarded = 0; }, [=](size_t& num_discarded, const std::vector<table_slice>& slices) { + for (const auto& slice : slices) + num_discarded += slice.rows(); }, [=](size_t& num_discarded, const caf::error& err) { if (num_discarded > 0)
codereview_cpp_data_11497
status_factory, cache_, tx_presence_cache_); - service_transport_ = std::make_shared<torii::CommandServiceTransportGrpc>( - service_, - status_bus, - status_factory, - cache_, - tx_presence_cache_, ); service_transport_ = std::make_shared<iroha::torii::CommandServiceTransportGrpc>( service_, Please check line 117, it is the same. The file does not compile. status_factory, cache_, tx_presence_cache_); service_transport_ = std::make_shared<iroha::torii::CommandServiceTransportGrpc>( service_,
codereview_cpp_data_11503
if (tables.size() > 1) { cout << "Storage: cannot read data files with multiple tables. " << "Only the first table '" << tables.begin()->first << "' will " - << "loaded as Storage." << endl; } convertTableToStorage(tables.begin()->second.get(), *this); return; will be loaded? if (tables.size() > 1) { cout << "Storage: cannot read data files with multiple tables. " << "Only the first table '" << tables.begin()->first << "' will " + << "be loaded as Storage." << endl; } convertTableToStorage(tables.begin()->second.get(), *this); return;
codereview_cpp_data_11520
"", 0.0, true, RangedValidator<double>(0.0, 30.0)); rules.Add<double>("RULE_PRODUCTION_QUEUE_TOPPING_UP_FACTOR", "RULE_PRODUCTION_QUEUE_TOPPING_UP_FACTOR_DESC", - "", 20.0, true, RangedValidator<double>(0.0, 30.0)); } bool temp_bool = RegisterGameRules(&AddRules); these as rules seems to make a lot of sense. "", 0.0, true, RangedValidator<double>(0.0, 30.0)); rules.Add<double>("RULE_PRODUCTION_QUEUE_TOPPING_UP_FACTOR", "RULE_PRODUCTION_QUEUE_TOPPING_UP_FACTOR_DESC", + "", 0.0, true, RangedValidator<double>(0.0, 30.0)); } bool temp_bool = RegisterGameRules(&AddRules);
codereview_cpp_data_11527
#include "ametsuchi/impl/postgres_ordering_service_persistent_state.hpp" #include "ametsuchi/impl/wsv_restorer_impl.hpp" #include "consensus/yac/impl/supermajority_checker_impl.hpp" using namespace iroha; using namespace iroha::ametsuchi; `algorithm` is not required here, and memory is probably already transitively included, so these lines can be removed. #include "ametsuchi/impl/postgres_ordering_service_persistent_state.hpp" #include "ametsuchi/impl/wsv_restorer_impl.hpp" #include "consensus/yac/impl/supermajority_checker_impl.hpp" +#include "multi_sig_transactions/gossip_propagation_strategy.hpp" +#include "multi_sig_transactions/mst_processor_impl.hpp" +#include "multi_sig_transactions/mst_processor_stub.hpp" +#include "multi_sig_transactions/mst_time_provider_impl.hpp" +#include "multi_sig_transactions/storage/mst_storage_impl.hpp" +#include "multi_sig_transactions/transport/mst_transport_grpc.hpp" using namespace iroha; using namespace iroha::ametsuchi;
codereview_cpp_data_11529
double Troops::GetStrength() const { double strength = 0; - for ( const Troop * troop : *this ) if ( troop && troop->isValid() ) strength += troop->GetStrength(); return strength; } Please change it into: ``` for ( const Troop * troop : *this ) { if ( troop && troop->isValid() ) strength += troop->GetStrength(); } ``` so it'll be easier to separate on loop from another :) double Troops::GetStrength() const { double strength = 0; + for ( const Troop * troop : *this ) { if ( troop && troop->isValid() ) strength += troop->GetStrength(); + } return strength; }
codereview_cpp_data_11533
#include <caf/actor_system.hpp> #include <caf/actor_system_config.hpp> #include <caf/binary_deserializer.hpp> -#include <caf/binary_serializer.hpp> #include <caf/deserializer.hpp> #include <caf/error.hpp> #include <caf/execution_unit.hpp> This one is not used in this file. #include <caf/actor_system.hpp> #include <caf/actor_system_config.hpp> #include <caf/binary_deserializer.hpp> #include <caf/deserializer.hpp> #include <caf/error.hpp> #include <caf/execution_unit.hpp>
codereview_cpp_data_11540
// void show(int* arr, const int size); /** - * Function to merge two sub-arrays. merge() function is called - * from mergeSort() to merge the array after it split for sorting * by the mergeSort() funtion. * * In this case the merge fuction will also count and return ```suggestion * @brief Function to merge two sub-arrays. * @details merge() function is called ``` // void show(int* arr, const int size); /** + * @brief Function to merge two sub-arrays. + * + * @details + * merge() function is called from mergeSort() + * to merge the array after it split for sorting * by the mergeSort() funtion. * * In this case the merge fuction will also count and return
codereview_cpp_data_11542
return { [=](const curried_predicate&) { return row_ids; }, [](atom::shutdown) { - die("received shutdown request as one-shot indexer"); }, }; }); `self->quit()` should be enough here, no need to kill the process. return { [=](const curried_predicate&) { return row_ids; }, [](atom::shutdown) { + VAST_DEBUG_ANON("one-shot-indexer received shutdown request"); }, }; });
codereview_cpp_data_11552
* * Memory used: 1.7MB */ -boost::scoped_ptr<CRollingBloomFilter> recentRejects GUARDED_BY(cs_recentRejects); uint256 hashRecentRejectsChainTip; /** why not using `std::unique_ptr` like we did below for `txn_recently_in_block`? * * Memory used: 1.7MB */ +std::unique_ptr<CRollingBloomFilter> recentRejects GUARDED_BY(cs_recentRejects); uint256 hashRecentRejectsChainTip; /**
codereview_cpp_data_11561
#define CGALPLUGIN_MESHGENERATIONFROMIMAGE_CPP #include <CGALPlugin/MeshGenerationFromImage.h> -//#include <image/ImageTypes.h> namespace cgal { you can remove the line definitively #define CGALPLUGIN_MESHGENERATIONFROMIMAGE_CPP #include <CGALPlugin/MeshGenerationFromImage.h> namespace cgal {
codereview_cpp_data_11571
} /** - * @brief Compares two integer. * * @param a first integer * @param b second integer description misleading, better to write "comparison between integers suitable as qsort callback" } /** + * @brief comparison between integers suitable as qsort callback. * * @param a first integer * @param b second integer
codereview_cpp_data_11575
wxASSERT(pDoc); wxASSERT(wxDynamicCast(pDoc, CMainDocument)); - // ? why use these instead of ifdefs? if (strstr(pDoc->state.host_info.os_name, "Darwin")) { hostIsMac = true; } else if (strstr(pDoc->state.host_info.os_name, "Microsoft")) { I think the answer is 'because Manager could be run on one OS (e.g. Windows) and manage a client that run different OS (e.g. MacOS)' wxASSERT(pDoc); wxASSERT(wxDynamicCast(pDoc, CMainDocument)); if (strstr(pDoc->state.host_info.os_name, "Darwin")) { hostIsMac = true; } else if (strstr(pDoc->state.host_info.os_name, "Microsoft")) {
codereview_cpp_data_11579
"The amount of time since the last UpdateConsensus request from the " "leader."); -METRIC_DEFINE_gauge_int32(tablet, is_leader, - "Is tablet leader", yb::MetricUnit::kUnits, - "Keeps track whether tablet is leader" - "1 indicates that the tablet is leader"); METRIC_DEFINE_histogram( tablet, dns_resolve_latency_during_update_raft_config, Call this is_raft_leader to make it clear this is a raft level metric. "The amount of time since the last UpdateConsensus request from the " "leader."); +METRIC_DEFINE_gauge_int64(tablet, is_raft_leader, + "Is tablet raft leader", yb::MetricUnit::kUnits, + "Keeps track whether tablet is raft leader" + "1 indicates that the tablet is raft leader"); METRIC_DEFINE_histogram( tablet, dns_resolve_latency_during_update_raft_config,
codereview_cpp_data_11587
std::string last_name; int save_version = CURRENT_FORMAT_VERSION; std::vector<int> reserved_vols( LOOPXX_COUNT, 0 ); - std::map<std::string, StreamBuf> map_players; namespace ObjectFadeAnimation { Please use camelCase variable naming such as mapPlayers. std::string last_name; int save_version = CURRENT_FORMAT_VERSION; std::vector<int> reserved_vols( LOOPXX_COUNT, 0 ); + std::map<std::string, std::vector<Player>> mapPlayers; namespace ObjectFadeAnimation {
codereview_cpp_data_11588
TEST_F(SimulatorTest, ValidWhenPreviousBlock) { // proposal with height 2 => height 1 block present => new block generated - std::vector<shared_model::proto::Transaction> txs; - txs.push_back(makeTx()); - txs.push_back(makeTx()); auto validation_result = std::make_unique<iroha::validation::VerifiedProposalAndErrors>(); Could you please also address the problem of temporary protocol transactions captured by reference in these cases? It seems that this problem may arise somewhere without being noticed. TEST_F(SimulatorTest, ValidWhenPreviousBlock) { // proposal with height 2 => height 1 block present => new block generated + std::vector<shared_model::proto::Transaction> txs = {makeTx(), makeTx()}; auto validation_result = std::make_unique<iroha::validation::VerifiedProposalAndErrors>();
codereview_cpp_data_11618
CastleIndexListBox listbox( area, result ); - listbox.SetScrollButtonUp( conf.ExtGameEvilInterface() ? ICN::LISTBOX_EVIL : ICN::LISTBOX, 3, 4, fheroes2::Point( area.x + 256, area.y + 45 ) ); - listbox.SetScrollButtonDn( conf.ExtGameEvilInterface() ? ICN::LISTBOX_EVIL : ICN::LISTBOX, 5, 6, fheroes2::Point( area.x + 256, area.y + 190 ) ); - listbox.SetScrollSplitter( fheroes2::AGG::GetICN( conf.ExtGameEvilInterface() ? ICN::LISTBOX_EVIL : ICN::LISTBOX, 10 ), - fheroes2::Rect( area.x + 260, area.y + 68, 14, 120 ) ); listbox.SetAreaMaxItems( 5 ); listbox.SetAreaItems( fheroes2::Rect( area.x + 6, area.y + 49, 250, 160 ) ); listbox.SetListContent( castles ); Please name it as `buttonIcnId` for just easier reading. CastleIndexListBox listbox( area, result ); + const int listId = isEvilInterface ? ICN::LISTBOX_EVIL : ICN::LISTBOX; + listbox.SetScrollButtonUp( listId, 3, 4, fheroes2::Point( area.x + 256, area.y + 45 ) ); + listbox.SetScrollButtonDn( listId, 5, 6, fheroes2::Point( area.x + 256, area.y + 190 ) ); + listbox.SetScrollSplitter( fheroes2::AGG::GetICN( listId, 10 ), fheroes2::Rect( area.x + 260, area.y + 68, 14, 120 ) ); listbox.SetAreaMaxItems( 5 ); listbox.SetAreaItems( fheroes2::Rect( area.x + 6, area.y + 49, 250, 160 ) ); listbox.SetListContent( castles );
codereview_cpp_data_11620
bool CDlgAdvPreferences::ConfirmSetLocal() { wxString strMessage = wxEmptyString; - strMessage.Printf( - _("Changing to use the local BOINC preferences defined on this page. BOINC will ignore your web-based preferences, even if you subsequently make changes there. Do you want to proceed?") - ); int res = wxGetApp().SafeMessageBox( strMessage, _("Confirmation"),wxCENTER | wxICON_QUESTION | wxYES_NO | wxNO_DEFAULT,this); @CharlieFenton Does this need branding? @RichardHaselgrove Or maybe you can find a good wording that doesn't mention BOINC? bool CDlgAdvPreferences::ConfirmSetLocal() { wxString strMessage = wxEmptyString; + strMessage.Printf( + _("Changing to use the local preferences defined on this page. This will override your web-based preferences, even if you subsequently make changes there. Do you want to proceed?") + ); int res = wxGetApp().SafeMessageBox( strMessage, _("Confirmation"),wxCENTER | wxICON_QUESTION | wxYES_NO | wxNO_DEFAULT,this);
codereview_cpp_data_11629
return; } - for (int i = 0; i <= MAX_APPEARANCE_EFFECTS; i++) { Message(Chat::Red, "ID: %i :: App Effect ID %i :: Slot %i", i, appearance_effects_id[i], appearance_effects_slot[i]); } } You're using < max +1, <= max, etc. in other places, not sure your intentions there or here. return; } + for (int i = 0; i < MAX_APPEARANCE_EFFECTS; i++) { Message(Chat::Red, "ID: %i :: App Effect ID %i :: Slot %i", i, appearance_effects_id[i], appearance_effects_slot[i]); } }
codereview_cpp_data_11632
} } -#if SOFA_NO_UPDATE_BBOX == 0 { ScopedAdvancedTimer timer("UpdateBBox"); gnode->execute<UpdateBoundingBoxVisitor>(params); } -#endif #ifdef SOFA_DUMP_VISITOR_INFO simulation::Visitor::printCloseNode("Step"); So it seems to you are doing the inverse move from what I consider the best way to do...could you elaborate a bit why ? } } + if (!SOFA_NO_UPDATE_BBOX) { ScopedAdvancedTimer timer("UpdateBBox"); gnode->execute<UpdateBoundingBoxVisitor>(params); } #ifdef SOFA_DUMP_VISITOR_INFO simulation::Visitor::printCloseNode("Step");
codereview_cpp_data_11633
/** @file console_cmds.cpp Implementation of the console hooks. */ -#include <time.h> #include "stdafx.h" #include "console_internal.h" #include "debug.h" There's no hard-and-fast rule for this, but standard headers are generally put at the bottom of the list on their own (but before safeguards.h) /** @file console_cmds.cpp Implementation of the console hooks. */ #include "stdafx.h" #include "console_internal.h" #include "debug.h"