id
stringlengths
21
25
content
stringlengths
164
2.33k
codereview_cpp_data_6637
if (!pfrom->ThinBlockCapable()) { LOCK(cs_main); - Misbehaving(pfrom->GetId(), 100); return error("%s message received from a non thinblock node, peer %s", strCommand, pfrom->GetLogName()); } ptschip made this a 5 not 100 in expedited.cpp; we should do the same here if (!pfrom->ThinBlockCapable()) { LOCK(cs_main); + Misbehaving(pfrom->GetId(), 5); return error("%s message received from a non thinblock node, peer %s", strCommand, pfrom->GetLogName()); }
codereview_cpp_data_6654
{ tagEntryInfo tag; /* check if a container before kind is modified by prototype */ /* BTW should we create a context for a prototype? */ bool container = isContainer(kind); (This is not a must.) How about putting "Assert (kind >= 0);" here? { tagEntryInfo tag; + /* FIXME: This if-clause should be removed. */ + if (kind == K_UNDEFINED || kind == K_IDENTIFIER) + { + verbose ("Unexpected token kind %d\n", kind); + return; + } + /* check if a container before kind is modified by prototype */ /* BTW should we create a context for a prototype? */ bool container = isContainer(kind);
codereview_cpp_data_6660
struct st_h2o_http3_server_conn_t *conn = get_conn(stream); if (stream->tunnel->datagram_flow_id != UINT64_MAX) { khiter_t iter = kh_get(stream, conn->datagram_flows, stream->tunnel->datagram_flow_id); - /* the tunnel wasn't established yet */ - if (iter == kh_end(conn->datagram_flows)) - return; - kh_del(stream, conn->datagram_flows, iter); } } I wonder if we should avoid early return here. The rationale is that the function is expected to dispose all the properties, where `datagram_flow_id` is just one among them. Therefore, I tend to believe that a statement (or a block) that disposes each element should not do an early return, and that applies to the last property as well for the sake of consistency. struct st_h2o_http3_server_conn_t *conn = get_conn(stream); if (stream->tunnel->datagram_flow_id != UINT64_MAX) { khiter_t iter = kh_get(stream, conn->datagram_flows, stream->tunnel->datagram_flow_id); + /* it's possible the tunnel wasn't established yet */ + if (iter != kh_end(conn->datagram_flows)) + kh_del(stream, conn->datagram_flows, iter); } }
codereview_cpp_data_6661
{ S2N_ERROR_IF(initialized == false, S2N_ERR_NOT_INITIALIZED); notnull_check(b); - POSIX_ENSURE(b->size == 0, S2N_ERR_ALLOC); const struct s2n_blob temp = {0}; *b = temp; GUARD(s2n_realloc(b, size)); Shouldn't you be checking b->allocated instead of b->size? { S2N_ERROR_IF(initialized == false, S2N_ERR_NOT_INITIALIZED); notnull_check(b); + POSIX_ENSURE(b->allocated == 0, S2N_ERR_ALLOC); const struct s2n_blob temp = {0}; *b = temp; GUARD(s2n_realloc(b, size));
codereview_cpp_data_6677
{ const uint8_t *src = payload, *end = src + len; - /* quicly_decodev below will reject len == 0 case */ - if (len > PTLS_ENCODE_QUICINT_CAPACITY) goto Fail; - if ((frame->stream_or_push_id = quicly_decodev(&src, end)) == UINT64_MAX) goto Fail; return 0; I think this error check is insufficient. Consider the case where the given payload was `0100` (len = 2 bytes). This should be considered invalid, as the second byte is a junk. I think the correct thing to do in this function is to assert `src == end` after returning successfully from `quicly_decodev`. { const uint8_t *src = payload, *end = src + len; + if ((frame->stream_or_push_id = quicly_decodev(&src, end)) == UINT64_MAX) goto Fail; + if (src != end) { + /* there was an extra byte(s) after a valid QUIC variable-length integer */ goto Fail; + } return 0;
codereview_cpp_data_6679
#include <wlr/types/wlr_linux_dmabuf_v1.h> #include <wlr/util/log.h> #include "render/pixel_format.h" #include "types/wlr_buffer.h" #include "util/signal.h" I think we can just use a `wl_array` instead, since this is a flat list of pointers. #include <wlr/types/wlr_linux_dmabuf_v1.h> #include <wlr/util/log.h> #include "render/pixel_format.h" +#include "render/wlr_texture.h" #include "types/wlr_buffer.h" #include "util/signal.h"
codereview_cpp_data_6687
s2n_x509_validator_wipe(&validator); } - /*/* test validator in safe mode, but no configured trust store */ { struct s2n_x509_trust_store trust_store; s2n_x509_trust_store_init_empty(&trust_store); double /* at start of line s2n_x509_validator_wipe(&validator); } + /* test validator in safe mode, but no configured trust store */ { struct s2n_x509_trust_store trust_store; s2n_x509_trust_store_init_empty(&trust_store);
codereview_cpp_data_6697
if (fleet) return std::make_pair(fleet->PreviousSystemID(), fleet->NextSystemID()); - if (auto field = std::dynamic_pointer_cast<const Field>(obj)) return nullptr; // Don't generate an error message for temporary objects. the `auto field = ` is probably unnecessary and likely to produce an unused variable warning. if (fleet) return std::make_pair(fleet->PreviousSystemID(), fleet->NextSystemID()); + if (std::dynamic_pointer_cast<const Field>(obj)) return nullptr; // Don't generate an error message for temporary objects.
codereview_cpp_data_6698
/* Copyright (C) 2000-2012 by George Williams */ /* Copyright (C) 2012-2013 by Khaled Hosny */ /* Copyright (C) 2013 by Matthew Skala */ -/* Copyright (C) 2020 by Rajeesh KV */ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: I would prefer you instead add your name to the AUTHORS file, if that's OK with you. Same for `fontview.c`. /* Copyright (C) 2000-2012 by George Williams */ /* Copyright (C) 2012-2013 by Khaled Hosny */ /* Copyright (C) 2013 by Matthew Skala */ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met:
codereview_cpp_data_6707
Color fg = g->state==gs_disabled?g->box->disabled_foreground: g->box->main_foreground==COLOR_DEFAULT?GDrawGetDefaultForeground(GDrawGetDisplayOfWindow(pixmap)): g->box->main_foreground; - for (c=0, i=0; c<=6; c++) { angle=(30+c/6.*120)*M_PI/180; pts[i].x=.5*w*cos(angle)+x+w/2; pts[i].y=.5*h*sin(angle)+y+h/4; /* draw lashes */ if (i>0 && i<6) GDrawDrawLine(pixmap, pts[i].x,pts[i].y, .75*w*cos(angle)+x+w/2, .75*h*sin(angle)+y+h/4, fg); - ++i; } GDrawDrawPoly(pixmap, pts, i, fg); } I would favor moving this `++i` after `c++` (and a comma) in the for loop, as that is the logic, they're initialized together, and having the iteration separate is confusing. Color fg = g->state==gs_disabled?g->box->disabled_foreground: g->box->main_foreground==COLOR_DEFAULT?GDrawGetDefaultForeground(GDrawGetDisplayOfWindow(pixmap)): g->box->main_foreground; + for (c=0, i=0; c<=6; c++, i++) { angle=(30+c/6.*120)*M_PI/180; pts[i].x=.5*w*cos(angle)+x+w/2; pts[i].y=.5*h*sin(angle)+y+h/4; /* draw lashes */ if (i>0 && i<6) GDrawDrawLine(pixmap, pts[i].x,pts[i].y, .75*w*cos(angle)+x+w/2, .75*h*sin(angle)+y+h/4, fg); } GDrawDrawPoly(pixmap, pts, i, fg); }
codereview_cpp_data_6711
/* -Copyright (C) 2003-2004 Douglas Thain and the University of Wisconsin -Copyright (C) 2005- The University of Notre Dame This software is distributed under the GNU General Public License. See the file COPYING for details. */ Update the dates of the copyright to be correct for the creation of this file. Also remove the copyright from Wisconsin as I don't think that applies. /* + * Copyright (C) 2018- The University of Notre Dame This software is distributed under the GNU General Public License. See the file COPYING for details. */
codereview_cpp_data_6714
{ "nltransform", (PyCFunction)PyFFFont_NLTransform, METH_VARARGS, "Transform a font by non-linear expessions for x and y." }, { "validate", (PyCFunction)PyFFFont_validate, METH_VARARGS, "Check whether a font is valid and return True if it is." }, { "reencode", (PyCFunction)PyFFFont_reencode, METH_VARARGS, "Reencodes the current font into the given encoding." }, - { "clearSpecialData", (PyCFunction)PyFFFont_clearSpecialData, METH_VARARGS, "Reencodes the current font into the given encoding." }, // { "CollabSessionStart", (PyCFunction) PyFFFont_CollabSessionStart, METH_VARARGS, "Start a collab session at the given address (or the public IP address by default)" }, It seems like you verbatim-copied the description of the previous element. { "nltransform", (PyCFunction)PyFFFont_NLTransform, METH_VARARGS, "Transform a font by non-linear expessions for x and y." }, { "validate", (PyCFunction)PyFFFont_validate, METH_VARARGS, "Check whether a font is valid and return True if it is." }, { "reencode", (PyCFunction)PyFFFont_reencode, METH_VARARGS, "Reencodes the current font into the given encoding." }, + { "clearSpecialData", (PyCFunction)PyFFFont_clearSpecialData, METH_NOARGS, "Clear special data not accessible in FontForge." }, // { "CollabSessionStart", (PyCFunction) PyFFFont_CollabSessionStart, METH_VARARGS, "Start a collab session at the given address (or the public IP address by default)" },
codereview_cpp_data_6715
forEachCard(formatDeckListForExport); mainBoardCards.chop(3); sideBoardCards.chop(3); deckString+="deckmain="+mainBoardCards+"&deckside="+sideBoardCards; return deckString; } I think this needs to be url escaped forEachCard(formatDeckListForExport); mainBoardCards.chop(3); sideBoardCards.chop(3); + if((QString::compare(mainBoardCards, "", Qt::CaseInsensitive) == 0) && + (QString::compare(sideBoardCards, "", Qt::CaseInsensitive) == 0)) { + return ""; + } deckString+="deckmain="+mainBoardCards+"&deckside="+sideBoardCards; return deckString; }
codereview_cpp_data_6716
hipError_t e = hipSuccess; - if(dst==NULL || src==NULL) - { - e=hipErrorInvalidValue; - return ihipLogStatus(e); } try { stream->locked_copySync((void*)dst, (void*)src, sizeBytes, hipMemcpyHostToDevice, false); Here and below: 1. formatting: left parenthesis should be placed on the same line as 'if' statement; 2. Excessive assignment. hipError_t e = hipSuccess; + if(dst==NULL || src==NULL){ + return ihipLogStatus(hipErrorInvalidValue); } try { stream->locked_copySync((void*)dst, (void*)src, sizeBytes, hipMemcpyHostToDevice, false);
codereview_cpp_data_6717
if (pfrom->nPingUsecTime < ACCEPTABLE_PING_USEC) return true; -#if 0 // TODO: this needs to be calculated periodically (rarely) and outside of any locks // Calculate average ping time of all nodes uint16_t nValidNodes = 0; std::vector<uint64_t> vPingTimes; is this PR to consider WIP till you implement the above TODO? if (pfrom->nPingUsecTime < ACCEPTABLE_PING_USEC) return true; // Calculate average ping time of all nodes uint16_t nValidNodes = 0; std::vector<uint64_t> vPingTimes;
codereview_cpp_data_6738
std::array<vector<Transfer*>, 6> TransferList::nexttransfers(std::function<bool(Transfer*)>& continuefunction) { - std::array<vector<Transfer*>, 6> v; static direction_t putget[] = { PUT, GET }; Please, lets give a meaningful name to every variable. Perhaps `transfers`?? std::array<vector<Transfer*>, 6> TransferList::nexttransfers(std::function<bool(Transfer*)>& continuefunction) { + std::array<vector<Transfer*>, 6> chosenTransfers; static direction_t putget[] = { PUT, GET };
codereview_cpp_data_6745
/** * @file * @brief Get list of prime numbers using Sieve of Eratosthenes * Sieve of Eratosthenes is an algorithm that finds all the primes * between 2 and N. * ```suggestion * @details * Sieve of Eratosthenes is an algorithm that finds all the primes ``` /** * @file * @brief Get list of prime numbers using Sieve of Eratosthenes + * @details * Sieve of Eratosthenes is an algorithm that finds all the primes * between 2 and N. *
codereview_cpp_data_6751
if (score == 0) { const char *app_id = as_app_get_id_filename (app); - if (g_strstr_len (app_id, -1, search_text) != NULL) score = 50; else continue; Not important but why not just `strstr()`, probably more optimized implementation. EDIT: Actually now that I think of it this should be case insensitive. if (score == 0) { const char *app_id = as_app_get_id_filename (app); + if (strcasestr (app_id, search_text) != NULL) score = 50; else continue;
codereview_cpp_data_6771
* @then there is an empty proposal */ TEST_F(AddAssetQuantity, NonexistentAccount) { - const std::string &nonexistent = "inexist@test"s; IntegrationTestFramework(1) .setInitialState(kAdminKeypair) .sendTx(makeUserWithPerms()) Not really sure this convoluted form grants us any benefits. IMO it better to write `std::string nonexistent = "blabla"`. We still perform one construction, but a reader of the code no longer has to be aware of things such as lifetime extensions etc. * @then there is an empty proposal */ TEST_F(AddAssetQuantity, NonexistentAccount) { + std::string nonexistent = "inexist@test"; IntegrationTestFramework(1) .setInitialState(kAdminKeypair) .sendTx(makeUserWithPerms())
codereview_cpp_data_6775
#include "race.h" #include "settings.h" #define LENGTHNAME 16 #define LENGTHDESCRIPTION 143 Please add this code to fix compilation on MacOS: ``` #ifdef WITH_XML #include "tinyxml.h" #endif ``` #include "race.h" #include "settings.h" +#ifdef WITH_XML +#include "tinyxml.h" +#endif + #define LENGTHNAME 16 #define LENGTHDESCRIPTION 143
codereview_cpp_data_6779
* @returns 0 on exit */ int main() { - // running predefined tests - tests(); uint64_t vertices = uint64_t(); uint64_t edges = uint64_t(); std::cout << "Enter the number of vertices : "; ```suggestion tests(); // running predefined tests ``` * @returns 0 on exit */ int main() { + tests(); // running predefined tests uint64_t vertices = uint64_t(); uint64_t edges = uint64_t(); std::cout << "Enter the number of vertices : ";
codereview_cpp_data_6789
batch_queue_set_option(remote_queue, "mesos-path", mesos_path); batch_queue_set_option(remote_queue, "mesos-master", mesos_master); batch_queue_set_option(remote_queue, "mesos-preload", mesos_preload); - batch_queue_set_feature(remote_queue, "batch_log_name", batchlogfilename); } if(batch_queue_type == BATCH_QUEUE_TYPE_DRYRUN) { Is setting the batch log name specific to Mesos? This should be covered by the if statement just previous using the feature you set in batch_job_mesos.c batch_queue_set_option(remote_queue, "mesos-path", mesos_path); batch_queue_set_option(remote_queue, "mesos-master", mesos_master); batch_queue_set_option(remote_queue, "mesos-preload", mesos_preload); } if(batch_queue_type == BATCH_QUEUE_TYPE_DRYRUN) {
codereview_cpp_data_6795
expected<ids> enumeration_index::lookup_impl(relational_operator op, data_view d) const { - if (offset() == 0) // FIXME: why do we need this check again? - return ids{}; return caf::visit(detail::overload( [&](auto x) -> expected<ids> { return make_error(ec::type_clash, materialize(x)); It's really just an optimization. If there's nothing in the index, there's nothing to return. to keep the logic as simple as possible, I'd remove this statement. It's premature anyway. expected<ids> enumeration_index::lookup_impl(relational_operator op, data_view d) const { return caf::visit(detail::overload( [&](auto x) -> expected<ids> { return make_error(ec::type_clash, materialize(x));
codereview_cpp_data_6798
<h1>Error 503 Backend is unhealthy</h1> <p>Backend is unhealthy</p> <h3>Guru Mediation:</h3> - <p>Details: cache-sea4446-SEA 1645537786 747776169</p> <hr> <p>Varnish cache server</p> </body> Code style here is pretty bad <h1>Error 503 Backend is unhealthy</h1> <p>Backend is unhealthy</p> <h3>Guru Mediation:</h3> + <p>Details: cache-sea4456-SEA 1645537786 1191598900</p> <hr> <p>Varnish cache server</p> </body>
codereview_cpp_data_6802
const FArrayBox& statein = Sborder[mfi]; FArrayBox& stateout = S_new[mfi]; - // Add elixir for output state fab - Elixir steli = stateout.elixir(); - // Resize temporary fabs for fluxes and face velocities. for (int i = 0; i < BL_SPACEDIM ; i++) { const Box& bxtmp = amrex::surroundingNodes(bx,i); ```suggestion ``` This should be removed. Elixir is supposed to be used on temporary Fabs, not on `S_new`. const FArrayBox& statein = Sborder[mfi]; FArrayBox& stateout = S_new[mfi]; // Resize temporary fabs for fluxes and face velocities. for (int i = 0; i < BL_SPACEDIM ; i++) { const Box& bxtmp = amrex::surroundingNodes(bx,i);
codereview_cpp_data_6804
uint8_t index = ((const uint8_t *)key)[0]; - if(cache[index].key_len != 0) { - S2N_ERROR_IF(cache[index].key_len != key_size, S2N_ERR_INVALID_ARGUMENT); - S2N_ERROR_IF(memcmp(cache[index].key, key, key_size), S2N_ERR_INVALID_ARGUMENT); - } cache[index].key_len = 0; cache[index].value_len = 0; nit: spacing between `if` and `(` is off. Alternatively. you could rewrite the lines as: ``` S2N_ERROR_IF(cache[index].key_len != 0 && cache[index].key_len != key_size, S2N_ERR_INVALID_ARGUMENT); S2N_ERROR_IF(cache[index].key_len != 0 && memcmp(cache[index].key, key, key_size), S2N_ERR_INVALID_ARGUMENT); ``` uint8_t index = ((const uint8_t *)key)[0]; + S2N_ERROR_IF(cache[index].key_len != 0 && cache[index].key_len != key_size, S2N_ERR_INVALID_ARGUMENT); + S2N_ERROR_IF(cache[index].key_len != 0 && memcmp(cache[index].key, key, key_size), S2N_ERR_INVALID_ARGUMENT); cache[index].key_len = 0; cache[index].value_len = 0;
codereview_cpp_data_6808
using namespace iroha::network; using namespace shared_model::crypto; using namespace shared_model::interface; -namespace val = shared_model::validation; namespace { const char *kPeerNotFound = "Cannot find peer"; Is this function needed? As I see, later you unpack nonempty block with it and then immediately write a visitor again, but to unpack a result created by yourself. Maybe, it's better to match the block emptiness directly in the code, so you wouldn't have two visitors? using namespace iroha::network; using namespace shared_model::crypto; using namespace shared_model::interface; namespace { const char *kPeerNotFound = "Cannot find peer";
codereview_cpp_data_6822
command_add("tattoo", "- Change the tattoo of your target (Drakkin Only)", AccountStatus::QuestTroupe, command_tattoo) || command_add("tempname", "[newname] - Temporarily renames your target. Leave name blank to restore the original name.", AccountStatus::GMAdmin, command_tempname) || command_add("petname", "[newname] - Temporarily renames your pet. Leave name blank to restore the original name.", AccountStatus::GMAdmin, command_petname) || - command_add("texture", "[Texture] [Helmet Texture] - Change your or your target's texture (Helmet Texture defaults to 0 if not sued)", AccountStatus::Steward, command_texture) || command_add("time", "[HH] [MM] - Set EQ time", AccountStatus::EQSupport, command_time) || command_add("timers", "- Display persistent timers for target", AccountStatus::GMMgmt, command_timers) || command_add("timezone", "[HH] [MM] - Set timezone. Minutes are optional", AccountStatus::EQSupport, command_timezone) || Needs a lawyer command_add("tattoo", "- Change the tattoo of your target (Drakkin Only)", AccountStatus::QuestTroupe, command_tattoo) || command_add("tempname", "[newname] - Temporarily renames your target. Leave name blank to restore the original name.", AccountStatus::GMAdmin, command_tempname) || command_add("petname", "[newname] - Temporarily renames your pet. Leave name blank to restore the original name.", AccountStatus::GMAdmin, command_petname) || + command_add("texture", "[Texture] [Helmet Texture] - Change your or your target's texture (Helmet Texture defaults to 0 if not used)", AccountStatus::Steward, command_texture) || command_add("time", "[HH] [MM] - Set EQ time", AccountStatus::EQSupport, command_time) || command_add("timers", "- Display persistent timers for target", AccountStatus::GMMgmt, command_timers) || command_add("timezone", "[HH] [MM] - Set timezone. Minutes are optional", AccountStatus::EQSupport, command_timezone) ||
codereview_cpp_data_6827
Json::nextToken(json, index); //Loop through all of the key/value pairs of the object - while(true) { //Get the upcoming token token = Json::lookAhead(json, index); Did you mean to do this? Json::nextToken(json, index); //Loop through all of the key/value pairs of the object + bool done = false; + while(!done) { //Get the upcoming token token = Json::lookAhead(json, index);
codereview_cpp_data_6830
<h1>Error 503 Backend is unhealthy</h1> <p>Backend is unhealthy</p> <h3>Guru Mediation:</h3> - <p>Details: cache-sea4426-SEA 1645537787 1400032596</p> <hr> <p>Varnish cache server</p> </body> How could the serial be validated? Serial validation is currently thought to be a responsibility of rootston. Should we add the ability for the seat itself to validate serials and use this approach in rootston as well? <h1>Error 503 Backend is unhealthy</h1> <p>Backend is unhealthy</p> <h3>Guru Mediation:</h3> + <p>Details: cache-sea4456-SEA 1645537788 1191610181</p> <hr> <p>Varnish cache server</p> </body>
codereview_cpp_data_6831
* @when the transaction is sent to ITF twice * @then the second submission should be rejected */ -TEST_F(ReplayFixture, DISABLE_OrderingGateReplay) { /* * Disabled because now it is not clear how to test replays. * In case of replay Iroha will just produce a warning in std output. Maybe leave a todo here? * @when the transaction is sent to ITF twice * @then the second submission should be rejected */ +TEST_F(ReplayFixture, DISABLED_OrderingGateReplay) { + // TODO igor-egorov 20.02.2019 IR-348 Rework OG replay test /* * Disabled because now it is not clear how to test replays. * In case of replay Iroha will just produce a warning in std output.
codereview_cpp_data_6841
AudioOutputSpeech *speech = qobject_cast<AudioOutputSpeech *>(aop); if (speech) { - const ClientUser* user = speech->p; volumeAdjustment *= user->fLocalVolume; if (prioritySpeakerActive) { `*` should be placed at the variable name, not the type. AudioOutputSpeech *speech = qobject_cast<AudioOutputSpeech *>(aop); if (speech) { + const ClientUser *user = speech->p; volumeAdjustment *= user->fLocalVolume; if (prioritySpeakerActive) {
codereview_cpp_data_6845
int i; int action = 3; // 1=add, 2=remove, 3=help+list (default), 4=reset - nullpo_retr(-1, sd); - if (message && *message) { if (message[0] == '+') { message++; nullpo_retr are no longer necessary in ACMD() definitions, and should be removed (see 8e4bc1905c6a5f0e3c17b70c0b37b4d901363ed9 ) int i; int action = 3; // 1=add, 2=remove, 3=help+list (default), 4=reset if (message && *message) { if (message[0] == '+') { message++;
codereview_cpp_data_6868
int value = si.x + si.y*nx + si.z*nx*ny; fails += (array(i,j,k) != value); - AMREX_ASSERT(fails); // If DEBUG, crash on first error. }); } return fails == 0; It should be `AMREX_ASSERT(fails == 0);` int value = si.x + si.y*nx + si.z*nx*ny; fails += (array(i,j,k) != value); + AMREX_ASSERT(fails==0); // If DEBUG, crash on first error. }); } return fails == 0;
codereview_cpp_data_6872
#ifdef HELLFIRE char *jogging_toggle_names[] = { "Jog", "Walk", "Fast Walk" }; #endif char *color_cycling_toggle_names[] = { "Color Cycling Off", "Color Cycling On" }; void gamemenu_previous() { just wondering, isn't this a good moment to add #ifndef HELLFIRE around color_cycling_toggle_names? :P #ifdef HELLFIRE char *jogging_toggle_names[] = { "Jog", "Walk", "Fast Walk" }; #endif +#ifndef HELLFIRE char *color_cycling_toggle_names[] = { "Color Cycling Off", "Color Cycling On" }; +#endif void gamemenu_previous() {
codereview_cpp_data_6875
if (self->client && self->client->sock && overrides && self->client->sock->input->size > overrides->max_buffer_size) { self->await_send = await_send; - self->await_send_arg.proxy_generator = self; - self->await_send_arg.cb = self->client->sock->_cb.read; - h2o_socket_read_stop(self->client->sock); } return 0; How about creating functions that stops / resumes reading the body in http1client? I assume that by doing so there would no longer be a need to introduce `await_send_arg_t`, since: * it is possible to determine if the reader is active by calling `h2o_socket_is_reading(self->client->sock)` * in http1client the callback function that needs to be passed to `h2o_socket_read_start` is known to be a constant if (self->client && self->client->sock && overrides && self->client->sock->input->size > overrides->max_buffer_size) { self->await_send = await_send; + h2o_http1client_body_read_stop(self->client); } return 0;
codereview_cpp_data_6883
{round.block_round, currentRejectRoundConsumer(round.reject_round)}); } -void OnDemandOrderingServiceImpl::tryErase() { - while (proposal_map_.size() > number_of_proposals_) { log_->info("tryErase: erasing {}", proposal_map_.begin()->first); proposal_map_.erase(proposal_map_.begin()); } I would rather use the previous logic, where this loop operated only on subset of `proposal_map_` with `map.round < packNextProposals.round`. I would suggest to first `it = proposal_map_.find(round)`, and then operate on `range(proposal_map_.begin(), it)`. {round.block_round, currentRejectRoundConsumer(round.reject_round)}); } +void OnDemandOrderingServiceImpl::tryErase( + const consensus::Round &current_round) { + auto current_proposal = proposal_map_.find(current_round); + auto proposal_range_size = boost::size( + boost::make_iterator_range(proposal_map_.begin(), current_proposal)); + + while (proposal_range_size > number_of_proposals_ + and proposal_map_.begin()->first < current_round) { log_->info("tryErase: erasing {}", proposal_map_.begin()->first); proposal_map_.erase(proposal_map_.begin()); }
codereview_cpp_data_6896
/** * flatpak_transaction_set_disable_dependencies: * @self: a #FlatpakTransaction - * @disable_dependencies: whether to disable dependencies * - * Sets whether the transaction should ignore dependencies when resolving - * operations. */ void flatpak_transaction_set_disable_dependencies (FlatpakTransaction *self, Maybe we should mention what dependencies are (i.e. the runtime the app needs). /** * flatpak_transaction_set_disable_dependencies: * @self: a #FlatpakTransaction + * @disable_dependencies: whether to disable runtime dependencies * + * Sets whether the transaction should ignore runtime dependencies + * when resolving operations for applications. */ void flatpak_transaction_set_disable_dependencies (FlatpakTransaction *self,
codereview_cpp_data_6899
flb_free(*s_val); /* release before overwriting */ } - *s_val = malloc(flb_sds_len(tmp) * sizeof(char) + 1); - strcpy(*s_val, tmp); flb_sds_destroy(tmp); break; default: flb_strdup() should do the work here. note: use Fluent Bit memory wrappers flb_free(*s_val); /* release before overwriting */ } + *s_val = flb_strdup(tmp); flb_sds_destroy(tmp); break; default:
codereview_cpp_data_6905
input->getName().length(), ' ') << input->getName() << " : "; if (input->getNumConnectees() == 0 || - (input->getNumConnectees() == 1 && !input.isConnected())) { std::cout << "no connectees" << std::endl; } else { for (unsigned i = 0; i < input->getNumConnectees(); ++i) { This logic assumes that `input->getConnecteeName(i)` is nonempty for all `i` if `input->getNumConnectees() > 1`. Is this assumption correct? input->getName().length(), ' ') << input->getName() << " : "; if (input->getNumConnectees() == 0 || + (input->getNumConnectees() == 1 && !input->isConnected())) { std::cout << "no connectees" << std::endl; } else { for (unsigned i = 0; i < input->getNumConnectees(); ++i) {
codereview_cpp_data_6912
if (not doc.HasMember("prev_hash")) { return nonstd::nullopt; } - std::string prev_hash_str(doc["prev_hash"].GetString(), - doc["prev_hash"].GetStringLength()); auto prev_hash_bytes = hex2bytes(prev_hash_str); std::copy(prev_hash_bytes.begin(), prev_hash_bytes.end(), block.prev_hash.begin()); Shall we return here false when created_ts is absent? I think this field is necessary for stateless validation, so we should not allow keep it empty if (not doc.HasMember("prev_hash")) { return nonstd::nullopt; } + std::string prev_hash_str = doc["prev_hash"].GetString(); auto prev_hash_bytes = hex2bytes(prev_hash_str); std::copy(prev_hash_bytes.begin(), prev_hash_bytes.end(), block.prev_hash.begin());
codereview_cpp_data_6920
* maximum sum subarray problem is the task of finding a contiguous subarray * with the largest sum * - * Algorithm * The simple idea of the algorithm is to search for all positive * contiguous segments of the array and keep track of maximum sum contiguous * segment among all positive segments(curr_sum is used for this) ```suggestion * ### Algorithm ``` * maximum sum subarray problem is the task of finding a contiguous subarray * with the largest sum * + * ### Algorithm * The simple idea of the algorithm is to search for all positive * contiguous segments of the array and keep track of maximum sum contiguous * segment among all positive segments(curr_sum is used for this)
codereview_cpp_data_6925
namespace AI { - constexpr int temporaryHeroScanDist = 15; bool MoveHero( Heroes & hero ) { Please put this variable to an unnamed namespace without **constexpr** as it does nothing in this situation: ``` namespace { const int temporaryHeroScanDist = 15; } ``` namespace AI { + namespace + { + const int temporaryHeroScanDist = 15; + } bool MoveHero( Heroes & hero ) {
codereview_cpp_data_6941
} else { if (sgpCurrItem == dword_634480) sgpCurrItem = &dword_634480[dword_63448C]; - --sgpCurrItem; } if ((sgpCurrItem->dwFlags & 0x80000000) != 0) { if (i) Maybe use `sgpCurrItem++` and `sgpCurrItem--` as usual ? } else { if (sgpCurrItem == dword_634480) sgpCurrItem = &dword_634480[dword_63448C]; + sgpCurrItem--; } if ((sgpCurrItem->dwFlags & 0x80000000) != 0) { if (i)
codereview_cpp_data_6954
const uint32_t maxSupportedCharacter = fheroes2::AGG::ASCIILastSupportedCharacter( _font ); - for ( std::string::const_iterator it = _message.begin(); it != _message.end(); ++it ) { if ( maxw && ( ax - sx ) >= maxw ) break; - const uint8_t character = static_cast<uint8_t>( *it ); // space or unknown letter if ( character < 0x21 || character > maxSupportedCharacter ) { :warning: **modernize-loop-convert** :warning: use range-based for loop instead ```suggestion for (char it : _message) { it ``` const uint32_t maxSupportedCharacter = fheroes2::AGG::ASCIILastSupportedCharacter( _font ); + for ( const char ch : _message ) { if ( maxw && ( ax - sx ) >= maxw ) break; + const uint8_t character = static_cast<uint8_t>( ch ); // space or unknown letter if ( character < 0x21 || character > maxSupportedCharacter ) {
codereview_cpp_data_6957
/* Same keys in both formats */ PListAddString(dictnode,"familyName",sf->familyname_with_timestamp ? sf->familyname_with_timestamp : sf->familyname); PListAddString(dictnode,"styleName",SFGetModifiers(sf)); { // We attempt to get numeric major and minor versions for U. F. O. out of the FontForge version string. int versionMajor = -1; We could fallback to the code up here (maybe that's what you intend to do before merging). /* Same keys in both formats */ PListAddString(dictnode,"familyName",sf->familyname_with_timestamp ? sf->familyname_with_timestamp : sf->familyname); PListAddString(dictnode,"styleName",SFGetModifiers(sf)); + if (sf->pfminfo.os2_family_name != NULL) PListAddString(dictnode,"styleMapFamilyName", sf->pfminfo.os2_family_name); + if (sf->pfminfo.os2_style_name != NULL) PListAddString(dictnode,"styleMapStyleName", sf->pfminfo.os2_style_name); { // We attempt to get numeric major and minor versions for U. F. O. out of the FontForge version string. int versionMajor = -1;
codereview_cpp_data_6958
area.DrawTile( dst, fheroes2::AGG::GetTIL( TIL::STON, 32 + ( mp.y % 4 ), 0 ), mp ); } else { - area.DrawTile( dst, fheroes2::AGG::GetTIL( TIL::STON, ( std::abs( (int)mp.y ) % 4 ) * 4 + std::abs( (int)mp.x ) % 4, 0 ), mp ); } } } Hi @undef21 could you please post warning message from compilation? Converting short to double doesn't narrow down the variable. area.DrawTile( dst, fheroes2::AGG::GetTIL( TIL::STON, 32 + ( mp.y % 4 ), 0 ), mp ); } else { +#if ( __GNUC__ == 6 ) + //workaround for gcc 6, which uses abs( double ) overload for short arg + area.DrawTile( dst, fheroes2::AGG::GetTIL( TIL::STON, ( std::abs( static_cast<int>( mp.y ) ) % 4 ) * 4 + std::abs( static_cast<int>( mp.x ) ) % 4, 0 ), mp ); +#else + area.DrawTile( dst, fheroes2::AGG::GetTIL( TIL::STON, ( std::abs( mp.y ) % 4 ) * 4 + std::abs( mp.x ) % 4, 0 ), mp ); +#endif } } }
codereview_cpp_data_6962
/* Turn on the flags for OCSP */ server_conn->status_type = S2N_STATUS_REQUEST_OCSP; server_conn->handshake_params.our_chain_and_key = &chain_and_key; const uint32_t EXPECTED_CERTIFICATE_EXTENSIONS_SIZE = 2 /* status request extensions header */ what about some failure cases? /* Turn on the flags for OCSP */ server_conn->status_type = S2N_STATUS_REQUEST_OCSP; + + /* Configure chain and key */ server_conn->handshake_params.our_chain_and_key = &chain_and_key; const uint32_t EXPECTED_CERTIFICATE_EXTENSIONS_SIZE = 2 /* status request extensions header */
codereview_cpp_data_6971
double stepSize = max(width, height) / 20.0; double stepsX = (width) / stepSize; double stepsY = (height) / stepSize; - double stepSizeX = (width) / (double)stepsX; - double stepSizeY = (height) / (double)stepsY; std::shared_ptr<geos::geom::Envelope> e(GeometryUtils::toEnvelope(env)); bool success = true; If `stepsX` is now a `double` there is no need to cast it to a `double` in these two lines. double stepSize = max(width, height) / 20.0; double stepsX = (width) / stepSize; double stepsY = (height) / stepSize; + double stepSizeX = (width) / stepsX; + double stepSizeY = (height) / stepsY; std::shared_ptr<geos::geom::Envelope> e(GeometryUtils::toEnvelope(env)); bool success = true;
codereview_cpp_data_6980
userLevelText = tr("Unregistered user"); userLevelLabel3.setText(userLevelText); - switch (user.user_role()) { case (0): userLevelLabel5.setText("Regular"); break; The `()` aren't really needed here userLevelText = tr("Unregistered user"); userLevelLabel3.setText(userLevelText); + switch (user.user_role) { case (0): userLevelLabel5.setText("Regular"); break;
codereview_cpp_data_6982
using sofa::helper::Factory; using namespace sofa::core::objectmodel; -// TODO (Stefan Escaida 13.02.2018): this factory code is redundant to the Communication plugin, but should easily be mergeable, when an adequate spot is found. typedef sofa::helper::Factory< std::string, BaseData> PSDEDataFactory; PSDEDataFactory* getFactoryInstance(){ Nice ! What did you plan for the redundant part ? using sofa::helper::Factory; using namespace sofa::core::objectmodel; +// TODO (sescaida 13.02.2018): this factory code is redundant to the Communication plugin, but should easily be mergeable, when an adequate spot is found. typedef sofa::helper::Factory< std::string, BaseData> PSDEDataFactory; PSDEDataFactory* getFactoryInstance(){
codereview_cpp_data_6988
// todo: add this test once the sync can keep up with file system notifications - at the moment -// it's too slow becuase we wait for the cloud before processing the next layer of files+folders. // So if we add enough changes to exercise the notification queue, we can't check the results because // it's far too slow at the syncing stage. GTEST_TEST(Sync, BasicSync_MassNotifyFromLocalFolderTree) ```suggestion // it's too slow because we wait for the cloud before processing the next layer of files+folders. ``` // todo: add this test once the sync can keep up with file system notifications - at the moment +// it's too slow because we wait for the cloud before processing the next layer of files+folders. // So if we add enough changes to exercise the notification queue, we can't check the results because // it's far too slow at the syncing stage. GTEST_TEST(Sync, BasicSync_MassNotifyFromLocalFolderTree)
codereview_cpp_data_6989
int s2n_stuffer_writev_bytes(struct s2n_stuffer *stuffer, const struct iovec* iov, int iov_count, size_t offs, size_t size) { - GUARD(s2n_stuffer_skip_write(stuffer, size)); - - void *ptr = stuffer->blob.data + stuffer->write_cursor - size; notnull_check(ptr); size_t size_left = size, to_skip = offs; I think `s2n_stuffer_raw_write` should do what you want here int s2n_stuffer_writev_bytes(struct s2n_stuffer *stuffer, const struct iovec* iov, int iov_count, size_t offs, size_t size) { + void *ptr = s2n_stuffer_raw_write(stuffer, size); notnull_check(ptr); size_t size_left = size, to_skip = offs;
codereview_cpp_data_7007
std::string filename; utf8::utf16to8(path_native.begin(), path_native.end(), std::back_inserter(filename)); #else - std::string filename = path.generic_string()); #endif excess closing bracket std::string filename; utf8::utf16to8(path_native.begin(), path_native.end(), std::back_inserter(filename)); #else + std::string filename = path.generic_string(); #endif
codereview_cpp_data_7029
data_coordinator& dc, sgd_termination_criteria const& term) { - // Setup a "training-global" validation context: - using ValidationContext = sgd_execution_context; - static ValidationContext evaluation_context( - execution_mode::validation, dc.get_mini_batch_size(execution_mode::validation)); - static size_t num_validation_epochs = 1UL; // Initialize some state so it knows we're training now. c.set_execution_mode(execution_mode::training); Won't making this `static` prevent us from juggling multiple instances of `sgd_training_algorithm`, or at least make for weird side-effects? data_coordinator& dc, sgd_termination_criteria const& term) { + auto& evaluation_context = m_validation_context; + auto& num_validation_epochs = m_validation_epochs; + evaluation_context.set_current_mini_batch_size( + dc.get_mini_batch_size(execution_mode::validation)); + evaluation_context.set_effective_mini_batch_size( dc.get_mini_batch_size(execution_mode::validation)); // Initialize some state so it knows we're training now. c.set_execution_mode(execution_mode::training);
codereview_cpp_data_7032
<< "A FreeJoint will be added to connect it to ground." << endl; Ground* ground = static_cast<Ground*>(mob.getInboardBodyRef()); - // Verify that this is an orphan and it was assigned to ground - assert(*ground == getGround()); - std::string jname = "free_" + child->getName(); SimTK::Vec3 zeroVec(0.0); Joint* free = new FreeJoint(jname, *ground, *child); Does this change make L788 redundant? << "A FreeJoint will be added to connect it to ground." << endl; Ground* ground = static_cast<Ground*>(mob.getInboardBodyRef()); std::string jname = "free_" + child->getName(); SimTK::Vec3 zeroVec(0.0); Joint* free = new FreeJoint(jname, *ground, *child);
codereview_cpp_data_7038
return sitrep; } -SitRepEntry CreatePlanetStarvedToDeathSitRep(int planet_id) { SitRepEntry sitrep(UserStringNop("SITREP_PLANET_DEPOPULATED"), "icons/sitrep/colony_destroyed.png"); sitrep.AddVariable(VarText::PLANET_ID_TAG, boost::lexical_cast<std::string>(planet_id)); return sitrep; Possibly because this function isn't renamed, but references to it are? return sitrep; } +SitRepEntry CreatePlanetDepopulatedSitRep(int planet_id) { SitRepEntry sitrep(UserStringNop("SITREP_PLANET_DEPOPULATED"), "icons/sitrep/colony_destroyed.png"); sitrep.AddVariable(VarText::PLANET_ID_TAG, boost::lexical_cast<std::string>(planet_id)); return sitrep;
codereview_cpp_data_7043
#include "torii/impl/status_bus_impl.hpp" #include "validators/default_validator.hpp" #include "validators/field_validator.hpp" -#include "validators/proposal_validator.hpp" #include "validators/protobuf/proto_block_validator.hpp" #include "validators/protobuf/proto_proposal_validator.hpp" #include "validators/protobuf/proto_query_validator.hpp" Is there any sense to import both interface and proto parts? Just proto should be enough #include "torii/impl/status_bus_impl.hpp" #include "validators/default_validator.hpp" #include "validators/field_validator.hpp" #include "validators/protobuf/proto_block_validator.hpp" #include "validators/protobuf/proto_proposal_validator.hpp" #include "validators/protobuf/proto_query_validator.hpp"
codereview_cpp_data_7057
opcodetype opcode; if (!GetOp(pc, opcode)) break; - if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY || opcode == OP_DATASIGVERIFY) n++; else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY) { Should this be `|| (enableDataSigVerify && opcode == OP_DATASIGVERIFY)`? opcodetype opcode; if (!GetOp(pc, opcode)) break; + if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY || (enableDataSigVerify && (opcode == OP_DATASIGVERIFY))) n++; else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY) {
codereview_cpp_data_7067
{ PlayerStruct *p = &plr[pnum]; - if (cii >= 7 || cii == 0 || (cii > 3 && cii <= 6)) { if (OilItem(&p->InvBody[cii], p)) { CalcPlrInv(pnum, TRUE); if (pnum == myplr) { ```suggestion if (cii >= NUM_INVLOC || cii == INVLOC_HEAD || (cii > INVLOC_AMULET && cii <= INVLOC_CHEST)) { // BUGFIX: access InvList for indexes >= NUM_INVLOC instead of using this OOB hack ``` { PlayerStruct *p = &plr[pnum]; + if (cii >= NUM_INVLOC || cii == INVLOC_HEAD || (cii > INVLOC_AMULET && cii <= INVLOC_CHEST)) { if (OilItem(&p->InvBody[cii], p)) { CalcPlrInv(pnum, TRUE); if (pnum == myplr) {
codereview_cpp_data_7072
h2o_mruby_eval_expr(mrb, "$LOAD_PATH << \"#{$H2O_ROOT}/share/h2o/mruby\""); h2o_mruby_assert(mrb); - /* require and include built-in libraries */ - h2o_mruby_eval_expr(mrb, "require \"h2o.rb\"\n" - "require \"acl.rb\"\n" - "include H2O::ACL\n"); h2o_mruby_assert(mrb); } Just one more thing... How about doing all of the following? 1. renaming h2o.rb to bootstrap.rb 2. require and include the acl code _from_ bootstrap.rb h2o_mruby_eval_expr(mrb, "$LOAD_PATH << \"#{$H2O_ROOT}/share/h2o/mruby\""); h2o_mruby_assert(mrb); + /* require core modules and include built-in libraries */ + h2o_mruby_eval_expr(mrb, "require \"bootstrap.rb\""); h2o_mruby_assert(mrb); }
codereview_cpp_data_7078
array[0]->width = pAllocateArray->Width; array[0]->height = pAllocateArray->Height; array[0]->depth = pAllocateArray->Depth; array[0]->isDrv = true; array[0]->textureType = hipTextureType3D; void** ptr = &array[0]->data; Below properties are not set and being accessed in ihipBindTextureToArrayImpl. So when 3D array is mapped to textures it fails with segmentation fault. array[0]->Format = pAllocateArray->Format; array[0]->NumChannels = pAllocateArray->NumChannels; array[0]->width = pAllocateArray->Width; array[0]->height = pAllocateArray->Height; array[0]->depth = pAllocateArray->Depth; + array[0]->Format = pAllocateArray->Format; + array[0]->NumChannels = pAllocateArray->NumChannels; array[0]->isDrv = true; array[0]->textureType = hipTextureType3D; void** ptr = &array[0]->data;
codereview_cpp_data_7087
Castle * castle = hero.inCastle(); if ( castle ) { ReinforceHeroInCastle( hero, *castle, castle->GetKingdom().GetFunds() ); - - if ( !hero.HaveSpellBook() && castle->GetLevelMageGuild() > 0 && !hero.IsFullBagArtifacts() ) { - // this call will check if AI kingdom have enough resources to buy book - hero.BuySpellBook( castle ); - } } } We miss a code buying a book after a purchase of a hero in castle. Castle * castle = hero.inCastle(); if ( castle ) { ReinforceHeroInCastle( hero, *castle, castle->GetKingdom().GetFunds() ); } }
codereview_cpp_data_7093
const int inner_feature_index = train_data_->InnerFeatureIndex(best_split_info.feature); if(!config_->cegb_penalty_feature_coupled.empty() && !feature_used[inner_feature_index]){ feature_used[inner_feature_index] = true; - for(int i = 0; i < tree->num_leaves(); i++){ if(i == best_leaf) continue; auto split = &splits_per_leaf_[i*train_data_->num_features() + inner_feature_index]; split->gain += config_->cegb_tradeoff*config_->cegb_penalty_feature_coupled[best_split_info.feature]; `++i` for the consistency with other codebase. const int inner_feature_index = train_data_->InnerFeatureIndex(best_split_info.feature); if(!config_->cegb_penalty_feature_coupled.empty() && !feature_used[inner_feature_index]){ feature_used[inner_feature_index] = true; + for(int i = 0; i < tree->num_leaves(); ++i){ if(i == best_leaf) continue; auto split = &splits_per_leaf_[i*train_data_->num_features() + inner_feature_index]; split->gain += config_->cegb_tradeoff*config_->cegb_penalty_feature_coupled[best_split_info.feature];
codereview_cpp_data_7124
} if(!infer_locals(opt, left, r_type)) - { - /* - TODO: maybe add an ast_error here too, but I don't - know what error would happen here ~ mateus-md - */ return false; - } // Inferring locals may have changed the left type. l_type = ast_type(left); This should be removed before this would be merged. } if(!infer_locals(opt, left, r_type)) return false; // Inferring locals may have changed the left type. l_type = ast_type(left);
codereview_cpp_data_7137
int s2n_stuffer_read(struct s2n_stuffer *stuffer, struct s2n_blob *out) { - // null check the out structure - if (NULL == out) { - return -1; - } return s2n_stuffer_read_bytes(stuffer, out->data, out->size); } please use notnull_check(out), which is the pattern used thoughout s2n for error checking. int s2n_stuffer_read(struct s2n_stuffer *stuffer, struct s2n_blob *out) { + notnull_check(out); return s2n_stuffer_read_bytes(stuffer, out->data, out->size); }
codereview_cpp_data_7144
if ((s < BIZ_STATUS_EXPIRED || s > BIZ_STATUS_GRACE_PERIOD) // status not received or invalid || (m == BIZ_MODE_UNKNOWN)) // master flag not received or invalid { - LOG_err << "GetUserData: invalid business status / account mode"; - client->app->notify_business_status(BIZ_STATUS_UNKNOWN); } else { Check with the apps teams the expected behavior for an unknown business status. Also, if an unknown status is notified, it must update the client's state: `MegaClient::mBizStatus` and the related class members as well. Perhaps, a possible workaround would be fallback to `BIZ_STATUS_INACTIVE` and send an event to the stats server to record the unexpected data received from API. if ((s < BIZ_STATUS_EXPIRED || s > BIZ_STATUS_GRACE_PERIOD) // status not received or invalid || (m == BIZ_MODE_UNKNOWN)) // master flag not received or invalid { + std::string err = "GetUserData: invalid business status / account mode"; + LOG_err << err; + client->sendevent(99450, err.c_str()); + + client->mBizStatus = BIZ_STATUS_EXPIRED; + client->mBizMode = BIZ_MODE_SUBUSER; + client->mBizExpirationTs = client->mBizGracePeriodTs = 0; + client->app->notify_business_status(client->mBizStatus); } else {
codereview_cpp_data_7153
using namespace iroha::consensus::yac; using namespace framework::test_subscriber; -// TODO mboldyrev 13.12.2018 IR- Parametrize the tests with consistency models static const iroha::consensus::yac::ConsistencyModel kConsistencyModel = iroha::consensus::yac::ConsistencyModel::kBft; There are two issues: first, missed IR number. Second, I am not sure that the task is required. Because in these tests we want to check how it works in general. So, for checking another consistency model we have to check such things - yac invokes supermajority checker, verify cft supermajority checker and ideally, test application's method which invokes different models. Another argument to not do it is the following: cft model is one round consensus, but new yac will have two phases. In this perspective, I think we will have two different consensus classes. using namespace iroha::consensus::yac; using namespace framework::test_subscriber; +// TODO mboldyrev 14.02.2019 IR-324 Use supermajority checker mock static const iroha::consensus::yac::ConsistencyModel kConsistencyModel = iroha::consensus::yac::ConsistencyModel::kBft;
codereview_cpp_data_7155
++increase; } - // If a castle is defenseless we should probably capture it ? - if ( army.GetStrength() <= 0.0 ) { - value += 10; - } - return value; } This definitely shouldn't be in this method since it's not building related. Also `army` references garrison only, so this will trigger even if there's defending hero in the castle. ++increase; } return value; }
codereview_cpp_data_7157
copy = std::string(copy.begin(), std::remove_if(copy.begin(), copy.end(), isspace)); size_t plus = copy.find('+'); - bool hasModifier = plus != std::string::npos; GG::Flags<GG::ModKey> mod = GG::MOD_KEY_NONE; - if (hasModifier) { // We have a modifier. Things get a little complex, since we need // to handle the |-separated flags: std::string m = copy.substr(0, plus); please use lowercase_underscore_separated_variable_names copy = std::string(copy.begin(), std::remove_if(copy.begin(), copy.end(), isspace)); size_t plus = copy.find('+'); + bool has_modifier = plus != std::string::npos; GG::Flags<GG::ModKey> mod = GG::MOD_KEY_NONE; + if (has_modifier) { // We have a modifier. Things get a little complex, since we need // to handle the |-separated flags: std::string m = copy.substr(0, plus);
codereview_cpp_data_7160
if (rebuild_from_initramfs) { - g_assert (argv == NULL); rebuild_argv = g_ptr_array_new (); g_ptr_array_add (rebuild_argv, "--rebuild"); g_ptr_array_add (rebuild_argv, (char*)rebuild_from_initramfs); This can be non-NULL in the `initramfs --enable --arg=ARG` case, no? if (rebuild_from_initramfs) { rebuild_argv = g_ptr_array_new (); g_ptr_array_add (rebuild_argv, "--rebuild"); g_ptr_array_add (rebuild_argv, (char*)rebuild_from_initramfs);
codereview_cpp_data_7168
loadModel(const string &aToolSetupFileName, ForceSet *rOriginalForceSet ) { OPENSIM_THROW_IF_FRMOBJ(_modelFile.empty(), Exception, - "No model file was specified (<model_file> tag is empty) in the " - "Tool's Setup file. Consider passing `false` for the constructor's " - "`aLoadModel` parameter"); string saveWorkingDirectory = IO::getCwd(); string directoryOfSetupFile = IO::getParentDirectory(aToolSetupFileName); IO::chDir(directoryOfSetupFile); I think "element" is more precise than "tag" (the tag is "<model_file>"). loadModel(const string &aToolSetupFileName, ForceSet *rOriginalForceSet ) { OPENSIM_THROW_IF_FRMOBJ(_modelFile.empty(), Exception, + "No model file was specified (<model_file> element is empty) in " + "the Tool's Setup file. Consider passing `false` for the " + "constructor's `aLoadModel` parameter"); string saveWorkingDirectory = IO::getCwd(); string directoryOfSetupFile = IO::getParentDirectory(aToolSetupFileName); IO::chDir(directoryOfSetupFile);
codereview_cpp_data_7170
} #define PROTO(T) \ - template class data_type_optimizer<T>; #define LBANN_INSTANTIATE_CPU_HALF #include "lbann/macros/instantiate.hpp" ```suggestion template class data_type_optimizer<T> ``` } #define PROTO(T) \ + template class data_type_optimizer<T> #define LBANN_INSTANTIATE_CPU_HALF #include "lbann/macros/instantiate.hpp"
codereview_cpp_data_7178
} /* add date: if it's missing from the response */ - if (h2o_find_header(&req->res.headers, H2O_TOKEN_DATE, 0) < 0) h2o_resp_add_date_header(req); return 0; Could we use `!= -1` as a check? It means the same, but it might be a good idea to be consistent with other parts of the code that invoke the same function. } /* add date: if it's missing from the response */ + if (h2o_find_header(&req->res.headers, H2O_TOKEN_DATE, 0) == -1) h2o_resp_add_date_header(req); return 0;
codereview_cpp_data_7188
std::begin(batch3), std::end(batch3), std::back_inserter(transactions)); transactions.push_back(createTransaction()); auto val = framework::expected::val( - TransportBuilder<interface::TransactionSequence, - validation::SignedTransactionsCollectionValidator< - validation::TransactionValidator< - validation::FieldValidator, - validation::CommandValidatorVisitor< - validation::FieldValidator>>, - validation::BatchOrderValidator>>() - .build(transactions)); ASSERT_TRUE(val); val | [](auto &seq) { ASSERT_EQ(boost::size(seq.value.transactions()), 24); }; } Please introduce using for transport builder std::begin(batch3), std::end(batch3), std::back_inserter(transactions)); transactions.push_back(createTransaction()); auto val = framework::expected::val( + TransactionSequenceBuilder().build(transactions)); ASSERT_TRUE(val); val | [](auto &seq) { ASSERT_EQ(boost::size(seq.value.transactions()), 24); }; }
codereview_cpp_data_7192
ILP_firstneigh[i] = neighptr; ILP_numneigh[i] = n; - if (n > 3) error->all(FLERR,"There are too many neighbors for some atoms, please check your configuration"); ipage->vgot(n); if (ipage->status()) error->one(FLERR,"Neighbor list overflow, boost neigh_modify one"); shouldn't this be a call to error->one(), i.e. what is needed in a situation, where the error condition would **not** always happen on *all* MPI ranks. ILP_firstneigh[i] = neighptr; ILP_numneigh[i] = n; + if (n > 3) error->one(FLERR,"There are too many neighbors for some atoms, please check your configuration"); ipage->vgot(n); if (ipage->status()) error->one(FLERR,"Neighbor list overflow, boost neigh_modify one");
codereview_cpp_data_7205
return AbstractBlock::operator==(rhs); } - bool BlockVariant::containsEmptyBlock() const { - return which() == 1; - } - BlockVariant *BlockVariant::clone() const { return new BlockVariant(*this); } Please don't do that. I believe we can do everything without that function return AbstractBlock::operator==(rhs); } BlockVariant *BlockVariant::clone() const { return new BlockVariant(*this); }
codereview_cpp_data_7209
OS_ASSERT(usePriceEscalationFile); for (IdfObject object : usePriceEscalationFile->objects()){ - std::string name = object.getString(LifeCycleCost_UsePriceEscalationFields::Name).get(); if ((name.find(*region) == 0) && (name.find(*sector) != string::npos)){ m_idfObjects.push_back(object); You can use `nameString()` instead here now! OS_ASSERT(usePriceEscalationFile); for (IdfObject object : usePriceEscalationFile->objects()){ + std::string name = object.nameString(); if ((name.find(*region) == 0) && (name.find(*sector) != string::npos)){ m_idfObjects.push_back(object);
codereview_cpp_data_7224
const char *name; char *log_file; char *log_priority; - int quiet; const char *lxcpath; /* remaining arguments */ Sort-of bikeshedding but this could be a `bool`. const char *name; char *log_file; char *log_priority; + bool quiet; const char *lxcpath; /* remaining arguments */
codereview_cpp_data_7231
const uint8_t *ours = security_policy->cipher_preferences->suites[i]->iana_value; if (memcmp(wire, ours, S2N_TLS_CIPHER_SUITE_LEN) == 0) { cipher_suite = security_policy->cipher_preferences->suites[i]; } } ENSURE_POSIX(cipher_suite != NULL, S2N_ERR_CIPHER_NOT_SUPPORTED); Should we short-circuit on a match rather than always searching every case in a policy? const uint8_t *ours = security_policy->cipher_preferences->suites[i]->iana_value; if (memcmp(wire, ours, S2N_TLS_CIPHER_SUITE_LEN) == 0) { cipher_suite = security_policy->cipher_preferences->suites[i]; + break; } } ENSURE_POSIX(cipher_suite != NULL, S2N_ERR_CIPHER_NOT_SUPPORTED);
codereview_cpp_data_7237
{"docker-opt", required_argument, 0, LONG_OPT_DOCKER_OPT}, {"amazon-config", required_argument, 0, LONG_OPT_AMAZON_CONFIG}, {"lambda-config", required_argument, 0, LONG_OPT_LAMBDA_CONFIG}, - {"amazon-ami", required_argument, 0, LONG_OPT_AMAZON_AMI}, {"amazon-batch-img",required_argument,0,LONG_OPT_AMAZON_BATCH_IMG}, {"amazon-batch-config",required_argument,0,LONG_OPT_AMAZON_BATCH_CFG}, {"json", no_argument, 0, LONG_OPT_JSON}, AMAZON_AMI is added here and in long_opts but I don't see it handled in the cases you added. Is this a preexisting case or should it be removed. {"docker-opt", required_argument, 0, LONG_OPT_DOCKER_OPT}, {"amazon-config", required_argument, 0, LONG_OPT_AMAZON_CONFIG}, {"lambda-config", required_argument, 0, LONG_OPT_LAMBDA_CONFIG}, {"amazon-batch-img",required_argument,0,LONG_OPT_AMAZON_BATCH_IMG}, {"amazon-batch-config",required_argument,0,LONG_OPT_AMAZON_BATCH_CFG}, {"json", no_argument, 0, LONG_OPT_JSON},
codereview_cpp_data_7242
void replace_prefix_dot(flb_sds_t s, int tag_prefix_len) { int str_len; char c; defining a variable inside the loop will break old compilers. Please move the variable declaration at top void replace_prefix_dot(flb_sds_t s, int tag_prefix_len) { + int i; int str_len; char c;
codereview_cpp_data_7269
// not a direct successor. if (IsChainNearlySyncd()) // only download headers if we're not doing IBD. The IBD process will take care of it's own headers. { - LogPrint("thin", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, obj.hash.ToString(), pfrom->id); pfrom->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), obj.hash); } this GETHEADERS req is not thin block specific... // not a direct successor. if (IsChainNearlySyncd()) // only download headers if we're not doing IBD. The IBD process will take care of it's own headers. { + LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, obj.hash.ToString(), pfrom->id); pfrom->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), obj.hash); }
codereview_cpp_data_7276
} /* namespace ddb */ } /* namespace rtps */ } /* namespace fastdds */ -} /* namespace eprosima */ \ No newline at end of file In general, blank line at the end of files } /* namespace ddb */ } /* namespace rtps */ } /* namespace fastdds */ \ No newline at end of file +} /* namespace eprosima */
codereview_cpp_data_7279
} break; case pt_setmiterlimit: - if ( sp>=0 ) miterlimit = stack[--sp].u.val; break; case pt_currentpacking: This doesn't look right, if sp is 0 you're addressing -1 into the stack? } break; case pt_setmiterlimit: + if ( sp>=1 ) miterlimit = stack[--sp].u.val; break; case pt_currentpacking:
codereview_cpp_data_7280
template <typename TensorDataType> bool adagrad<TensorDataType>::save_to_checkpoint_shared(persist& p, std::string name_prefix) { if (this->get_comm().am_trainer_master()) { - write_cereal_archive<adagrad<TensorDataType>>(*this, p, "adagrad.xml"); } char l_name[512]; ```suggestion write_cereal_archive(*this, p, "adagrad.xml"); ``` template <typename TensorDataType> bool adagrad<TensorDataType>::save_to_checkpoint_shared(persist& p, std::string name_prefix) { if (this->get_comm().am_trainer_master()) { + write_cereal_archive(*this, p, "adagrad.xml"); } char l_name[512];
codereview_cpp_data_7283
BOOST_CHECK(pblocktemplate->block.nBlockSize <= maxGeneratedBlock); unsigned int blockSize = pblocktemplate->block.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION); BOOST_CHECK(blockSize <= maxGeneratedBlock); - // printf("%lu %lu <= %lu\n", (long unsigned int) blockSize, (long unsigned int) pblocktemplate->block.nBlockSize, (long unsigned int) maxGeneratedBlock); delete pblocktemplate; } coinbaseReserve.value=0; // Test no reserve // Now generate lots of full size blocks and verify that none exceed the maxGeneratedBlock value - for (unsigned int i = 2000; i <= 80000; i+=37) { maxGeneratedBlock = i; @gandrewstone 1) I think that by the time you get to running the second loop of tests there will be no more transactions in the pool since they would have been mined out by then, so you'll just be mining empty blocks. (2) I think you should put a step in there that modifies the miner string "after" the block is created and before we submit the block the way the miners do it...and then we submit the block and check that it was still accepted to and updates the blockchain. BOOST_CHECK(pblocktemplate->block.nBlockSize <= maxGeneratedBlock); unsigned int blockSize = pblocktemplate->block.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION); BOOST_CHECK(blockSize <= maxGeneratedBlock); + //printf("%lu %lu <= %lu\n", (long unsigned int) blockSize, (long unsigned int) pblocktemplate->block.nBlockSize, (long unsigned int) maxGeneratedBlock); delete pblocktemplate; } coinbaseReserve.value=0; // Test no reserve // Now generate lots of full size blocks and verify that none exceed the maxGeneratedBlock value + for (unsigned int i = 2000; i <= 40000; i+=73) { maxGeneratedBlock = i;
codereview_cpp_data_7288
* * This program uses a more efficient logic to rotate the array as each element * is roated d times in only single iteration. This uses less time for more long - * arrays. */ void rotateArray(int *a, int size, int no_of_rotate) { // Rotating the Array int *arr = new int[no_of_rotate]; can you provide a breif description of how is this function working, i mean what is the underlying algorithm you are using please provide a breif description, it will help the reader to understand eailsy the idea behind all this * * This program uses a more efficient logic to rotate the array as each element * is roated d times in only single iteration. This uses less time for more long + * arrays. + * + * The Algorithm used is: + * 1) Input array, size, and no of times to rotate. + * 2) Create a new array and save first no_of_rotate elements into it. + * 3) Copy the remaining elements from starting index of the input array. + * 4) Copy back the elements saved in the new array to the input array. + * 5) Print the array. */ void rotateArray(int *a, int size, int no_of_rotate) { // Rotating the Array int *arr = new int[no_of_rotate];
codereview_cpp_data_7313
LOG_debug << "There are no storage problems"; client->setstoragestatus(STORAGE_GREEN); } } break; Perhaps we could log a warning in an `else`, just in case. LOG_debug << "There are no storage problems"; client->setstoragestatus(STORAGE_GREEN); } + else + { + LOG_err << "Unknown state of storage. State: " << value; + } } break;
codereview_cpp_data_7314
return mConfiguration_.max_logical_port; } -std::vector<std::string> TCPv4Transport::GetInterfacesList(const Locator_t& locator) { std::vector<std::string> vOutputInterfaces; if (IsInterfaceWhiteListEmpty() || (!IPLocator::isAny(locator) && !IPLocator::isMulticast(locator))) Change to more intuitive name the function. return mConfiguration_.max_logical_port; } +std::vector<std::string> TCPv4Transport::GetBindingInterfacesList(const Locator_t& locator) { std::vector<std::string> vOutputInterfaces; if (IsInterfaceWhiteListEmpty() || (!IPLocator::isAny(locator) && !IPLocator::isMulticast(locator)))
codereview_cpp_data_7323
std::shared_ptr<shared_model::interface::EmptyBlock> makeEmptyCommit( size_t time = iroha::time::now()) const { - using TestUnsignedEmptyBlockBuilder = - shared_model::proto::TemplateEmptyBlockBuilder< - (1 << shared_model::proto::TemplateEmptyBlockBuilder<>::total) - 1, - shared_model::validation::AlwaysValidValidator, - shared_model::proto::UnsignedWrapper< - shared_model::proto::EmptyBlock>>; auto block = TestUnsignedEmptyBlockBuilder() .height(5) .createdTime(time) Please move that to `test_empty_block_builder.hpp` std::shared_ptr<shared_model::interface::EmptyBlock> makeEmptyCommit( size_t time = iroha::time::now()) const { auto block = TestUnsignedEmptyBlockBuilder() .height(5) .createdTime(time)
codereview_cpp_data_7334
cmd = (cmd % creator_account_id_ % role_id % perm_str); - auto str_args = [&role_id, &perm_str]() { return (boost::format("role_id: %s, perm_str: %s") % role_id % perm_str) .str(); }; Is it better to output a readable string for permissions rather than bit string? cmd = (cmd % creator_account_id_ % role_id % perm_str); + auto str_args = [&role_id, &perm_str] { + // TODO [IR-1889] Akvinikym 21.11.18: integrate + // PermissionSet::toString() instead of bit string, when it is created return (boost::format("role_id: %s, perm_str: %s") % role_id % perm_str) .str(); };
codereview_cpp_data_7337
last_errno = proj_errno_reset(P); - if (!P->skip_fwd_prepare && 0 != strcmp(P->short_name, "s2")) coo = fwd_prepare (P, coo); if (HUGE_VAL==coo.v[0] || HUGE_VAL==coo.v[1]) return proj_coord_error ().xy; Why is this hack needed ? Ideally, we shouldn't need that. last_errno = proj_errno_reset(P); + if (!P->skip_fwd_prepare) coo = fwd_prepare (P, coo); if (HUGE_VAL==coo.v[0] || HUGE_VAL==coo.v[1]) return proj_coord_error ().xy;
codereview_cpp_data_7342
} uint32_t featureFlags = 0; - if (IsMay2020Enabled(chainparams.GetConsensus(), chainActive.Tip())) { - // Put your next network upgrade features HERE - // featureFlags |= SCRIPT_ENABLE_CHECKDATASIG; } uint32_t flags = STANDARD_SCRIPT_VERIFY_FLAGS | featureFlags; I don't see where SCRIPT_ENABLE_SCHNORR_MULTISIG is added to any of either the Standard or Manadatory flags (in policy.h or script/standard.h), SCRIPT_VERIFY_MINIMALDATA however is defined in the Standard flags...also, in the lines above you could probably take out "featureFlags |= SCRIPT_ENABLE_CHECKDATASIG;" since it's already defined in Standard flags? } uint32_t featureFlags = 0; + if (IsNov2018Activated(chainparams.GetConsensus(), chainActive.Tip())) + { + featureFlags |= SCRIPT_ENABLE_CHECKDATASIG; + } + if (IsNov2019Activated(chainparams.GetConsensus(), chainActive.Tip())) { + featureFlags |= SCRIPT_ENABLE_SCHNORR_MULTISIG; + featureFlags |= SCRIPT_VERIFY_MINIMALDATA; } uint32_t flags = STANDARD_SCRIPT_VERIFY_FLAGS | featureFlags;
codereview_cpp_data_7344
4 && parsed_len == host.len && d1 <= UCHAR_MAX && d2 <= UCHAR_MAX && d3 <= UCHAR_MAX && d4 <= UCHAR_MAX) { if (sscanf(port.base, "%" SCNd32 "%n", &_port, &parsed_len) == 1 && parsed_len == port.len && _port <= USHRT_MAX) { - struct sockaddr_in sin = {}; sin.sin_family = AF_INET; sin.sin_port = htons(_port); sin.sin_addr.s_addr = ntohl((d1 << 24) + (d2 << 16) + (d3 << 8) + d4); IIRC we need to use memset, because an empty brace is not C99 comformant, and because we cannot use `{0}` because how the struct is organized is not defined in POSIX (the initializer cannot be `{0}` if the first property of the struct is a struct). 4 && parsed_len == host.len && d1 <= UCHAR_MAX && d2 <= UCHAR_MAX && d3 <= UCHAR_MAX && d4 <= UCHAR_MAX) { if (sscanf(port.base, "%" SCNd32 "%n", &_port, &parsed_len) == 1 && parsed_len == port.len && _port <= USHRT_MAX) { + struct sockaddr_in sin; + memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons(_port); sin.sin_addr.s_addr = ntohl((d1 << 24) + (d2 << 16) + (d3 << 8) + d4);
codereview_cpp_data_7349
struct LoopSoundTask { - LoopSoundTask( const std::vector<int> & vols_, const int soundVolume_ ) - : vols( vols_ ) , soundVolume( soundVolume_ ) {} :warning: **modernize-pass-by-value** :warning: pass by value and use std::move ```suggestion #include <utility> LoopSoundTask( std::vector<int> vols_, const int soundVolume_ ) std::move() ``` struct LoopSoundTask { + LoopSoundTask( std::vector<int> vols_, const int soundVolume_ ) + : vols( std::move( vols_ ) ) , soundVolume( soundVolume_ ) {}
codereview_cpp_data_7351
struct s2n_stuffer *out = &conn->handshake.io; const int total_size = s2n_encrypted_extensions_send_size(conn); - - GUARD(total_size); - S2N_ERROR_IF(total_size > 65535, S2N_ERR_INTEGER_OVERFLOW); /* Write length of extensions */ GUARD(s2n_stuffer_write_uint16(out, total_size)); This could be the first use of `inclusive_range_check` outside the tests :) just a nit. This is a good check. Can this also be done for the regular server hello (which also covers HRR, which can have cookies which can be arbitrarily large). struct s2n_stuffer *out = &conn->handshake.io; const int total_size = s2n_encrypted_extensions_send_size(conn); + inclusive_range_check(0, total_size, 65535); /* Write length of extensions */ GUARD(s2n_stuffer_write_uint16(out, total_size));
codereview_cpp_data_7359
void FixPrecessionSpin::setup(int vflag) { - if (strstr(update->integrate_style,"verlet")) post_force(vflag); else { ((Respa *) update->integrate)->copy_flevel_f(ilevel_respa); this change should be reverted void FixPrecessionSpin::setup(int vflag) { + if (utils::strmatch(update->integrate_style,"^verlet")) post_force(vflag); else { ((Respa *) update->integrate)->copy_flevel_f(ilevel_respa);
codereview_cpp_data_7361
} else if (sit > min_seq_in_history) { gap_builder.add(sit); } }); Should we `assert(sit > changes_low_mark_);` here? } else if (sit > min_seq_in_history) { + assert(sit > changes_low_mark_); gap_builder.add(sit); } });
codereview_cpp_data_7365
sql << queries.second; } - /// returns string of concatenates query arguments to pass them further, if - /// error happened - using QueryArgsLambda = std::function<std::string()>; - iroha::expected::Error<iroha::ametsuchi::CommandError> makeCommandError( std::string &&command_name, const iroha::ametsuchi::CommandError::ErrorCodeType code, - QueryArgsLambda &&query_args) noexcept { return iroha::expected::makeError(iroha::ametsuchi::CommandError{ std::move(command_name), code, query_args()}); } Is there a point in passing an rvalue? sql << queries.second; } + template <typename QueryArgsCallable> iroha::expected::Error<iroha::ametsuchi::CommandError> makeCommandError( std::string &&command_name, const iroha::ametsuchi::CommandError::ErrorCodeType code, + QueryArgsCallable &&query_args) noexcept { return iroha::expected::makeError(iroha::ametsuchi::CommandError{ std::move(command_name), code, query_args()}); }