id
stringlengths 21
25
| content
stringlengths 164
2.33k
|
|---|---|
codereview_cpp_data_7972
|
#endif
// default actor batch size
-#define PONY_ACTOR_DEFAULT_BATCH 100
// Ignore padding at the end of the type.
pony_static_assert((offsetof(pony_actor_t, gc) + sizeof(gc_t)) ==
Why the rename from PONY_SCHED_BATCH ? ACTOR_DEFAULT_BATCH is less meaningful to me than SCHED_BATCH.
#endif
// default actor batch size
+#define PONY_SCHED_BATCH 100
// Ignore padding at the end of the type.
pony_static_assert((offsetof(pony_actor_t, gc) + sizeof(gc_t)) ==
|
codereview_cpp_data_7988
|
}
// If first run, set to RR
- if (settingsCache->servers().getPrevioushostName().isEmpty()) {
previousHosts->setCurrentIndex(1);
}
Are we able to guarantee this index exists? What if it fails to get the servers?
}
// If first run, set to RR
+ if (settingsCache->servers().getPrevioushostName().isEmpty() && previousHosts->count() >= 2) {
previousHosts->setCurrentIndex(1);
}
|
codereview_cpp_data_8013
|
* Complex Constructor which initialises the complex number with no
* arguments.
*/
- Complex() { Complex(0.0, 0.0); }
/**
* Member function (getter) to access the class' re value.
please include `double arg() const {` for the argument value of a complex number
* Complex Constructor which initialises the complex number with no
* arguments.
*/
+ Complex() {
+ this->re = 0.0;
+ this->im = 0.0;
+ }
/**
* Member function (getter) to access the class' re value.
|
codereview_cpp_data_8014
|
#include <fstream>
//Boost
-#include <boost/shared_array.hpp>
#include "HdfsConnection.h"
#include "HdfsDevice.hpp"
Does including `shared_array.hpp` instead of `shared_ptr.hpp` give you anything?
#include <fstream>
//Boost
+#include <boost/shared_ptr.hpp>
#include "HdfsConnection.h"
#include "HdfsDevice.hpp"
|
codereview_cpp_data_8017
|
return highlightCells;
}
-std::set<const Battle::Cell *> Battle::Interface::CalculateHighlightCellsForBigUnit( const Cell * cell ) const
{
std::set<const Battle::Cell *> highlightCells;
highlightCells.emplace( cell );
AFAIK it's called wide unit,
return highlightCells;
}
+std::set<const Battle::Cell *> Battle::Interface::CalculateHighlightCellsForWideUnit( const Cell * cell ) const
{
std::set<const Battle::Cell *> highlightCells;
highlightCells.emplace( cell );
|
codereview_cpp_data_8022
|
const shared_model::crypto::Hash &hash,
std::function<void(const shared_model::proto::TransactionResponse &)>
validation) {
- auto response =
- iroha_instance_->getIrohaInstance()->getCommandService()->getStatus(
- hash);
- validation(static_cast<const shared_model::proto::TransactionResponse &>(
- *response));
return *this;
}
`getCommandServiceTransport` should be called here since argument validation is also tested in ITF.
const shared_model::crypto::Hash &hash,
std::function<void(const shared_model::proto::TransactionResponse &)>
validation) {
+ iroha::protocol::TxStatusRequest request;
+ request.set_tx_hash(shared_model::crypto::toBinaryString(hash));
+ iroha::protocol::ToriiResponse response;
+ iroha_instance_->getIrohaInstance()->getCommandServiceTransport()->Status(
+ nullptr, &request, &response);
+ validation(shared_model::proto::TransactionResponse(std::move(response)));
return *this;
}
|
codereview_cpp_data_8026
|
#include "filterbuilder.h"
const QStringList TabDeckEditor::fileNameFilters = QStringList()
- << QObject::tr("Cockatrice set format (*.xml)")
<< QObject::tr("All files (*.*)");
void SearchLineEdit::keyPressEvent(QKeyEvent *event)
There is no "set format" or sth, we just have card databases... People can import a xml database with cards from a whole block or any other combination of cards/sets as well. (whatever kind of cards/sets are in there it needs to be a xml file) `Cockatrice card database (*.xml)` might be more general and better suitable. <br> Thinking further... should the menu say something like `Add custom set(s) or card(s)` or more simple `Add custom sets/cards` ? In this case the wording "set" or "sets" should be exchanged for "sets/cards" in all strings.
#include "filterbuilder.h"
const QStringList TabDeckEditor::fileNameFilters = QStringList()
+ << QObject::tr("Cockatrice card database (*.xml)")
<< QObject::tr("All files (*.*)");
void SearchLineEdit::keyPressEvent(QKeyEvent *event)
|
codereview_cpp_data_8030
|
// Whether skill fails or not is irrelevant, the char ain't idle. [Skotlex]
pc->update_idle_time(sd, BCIDLE_USESKILLTOID);
- bool allow_self_skill = ((tmp & INF_SELF_SKILL) != 0 && (skill->get_nk(skill_id) & NK_NO_DAMAGE) != 0);
- allow_self_skill = (allow_self_skill && battle_config.skill_enabled_npc == SKILLENABLEDNPC_SELF);
-
- if ((sd->npc_id != 0 && !allow_self_skill && battle_config.skill_enabled_npc != SKILLENABLEDNPC_ALL)
- || (sd->state.workinprogress & 1) != 0) {
#if PACKETVER >= 20110308
clif->msgtable(sd, MSG_BUSY);
#else
what if skill remove some item from inventory? or add new item?
// Whether skill fails or not is irrelevant, the char ain't idle. [Skotlex]
pc->update_idle_time(sd, BCIDLE_USESKILLTOID);
+ if (sd->npc_id || sd->state.workinprogress & 1) {
#if PACKETVER >= 20110308
clif->msgtable(sd, MSG_BUSY);
#else
|
codereview_cpp_data_8032
|
* binary number of an integer value it is formed as the combination of 0’s and
* 1’s. So digit 1 is known as a set bit in computer terms. Time Complexity :-
* O(log n) Space complexity :- O(1)
- * @author [Swastika Gupta](https://github.com/swastyy)
*/
#include <cassert> /// for assert
```suggestion * 1's. So digit 1 is known as a set bit in computer terms. * Time Complexity: O(log n) * Space complexity: O(1) ```
* binary number of an integer value it is formed as the combination of 0’s and
* 1’s. So digit 1 is known as a set bit in computer terms. Time Complexity :-
* O(log n) Space complexity :- O(1)
+ * @author [Swastika Gupta](https://github.com/Swastyy)
*/
#include <cassert> /// for assert
|
codereview_cpp_data_8039
|
* SPDX-License-Identifier: Apache-2.0
*/
-#include <interfaces/iroha_internal/query_response_factory.hpp>
#include "model/sha3_hash.hpp"
#include "module/irohad/ametsuchi/ametsuchi_mocks.hpp"
#include "module/irohad/multi_sig_transactions/mst_mocks.hpp"
Please use `""` instead.
* SPDX-License-Identifier: Apache-2.0
*/
#include "model/sha3_hash.hpp"
#include "module/irohad/ametsuchi/ametsuchi_mocks.hpp"
#include "module/irohad/multi_sig_transactions/mst_mocks.hpp"
|
codereview_cpp_data_8044
|
StreamBase & Skill::operator<<( StreamBase & msg, const Primary & skill )
{
- return msg << skill.attack << skill.defense << skill.power << skill.knowledge;
}
StreamBase & Skill::operator>>( StreamBase & msg, Primary & skill )
{
- return msg >> skill.attack >> skill.defense >> skill.power >> skill.knowledge;
}
StreamBase & Skill::operator>>( StreamBase & sb, Secondary & st )
Do we need this change and the change below? Aren't they below to file saving and loading?
StreamBase & Skill::operator<<( StreamBase & msg, const Primary & skill )
{
+ return msg << skill.attack << skill.defense << skill.knowledge << skill.power;
}
StreamBase & Skill::operator>>( StreamBase & msg, Primary & skill )
{
+ return msg >> skill.attack >> skill.defense >> skill.knowledge >> skill.power;
}
StreamBase & Skill::operator>>( StreamBase & sb, Secondary & st )
|
codereview_cpp_data_8046
|
CPPUNIT_TEST(runAccessPublicMapWithoutEmailTest);
CPPUNIT_TEST(runAccessPrivateMapWithoutEmailTest);
CPPUNIT_TEST(runInvalidUserTest);
- // TODO: fix
-// CPPUNIT_TEST(runMultipleMapsSameNameDifferentUsersPrivateTest);
-// CPPUNIT_TEST(runMultipleMapsSameNameDifferentUsersPublicTest);
-// CPPUNIT_TEST(runMultipleMapsSameNameNoUserPublicTest);
CPPUNIT_TEST_SUITE_END();
public:
I know this is a test, but this use is dangerous as it doesn't check if the folder contains other maps and would orphan them.
CPPUNIT_TEST(runAccessPublicMapWithoutEmailTest);
CPPUNIT_TEST(runAccessPrivateMapWithoutEmailTest);
CPPUNIT_TEST(runInvalidUserTest);
+ CPPUNIT_TEST(runMultipleMapsSameNameDifferentUsersPrivateTest);
+ CPPUNIT_TEST(runMultipleMapsSameNameDifferentUsersPublicTest);
+ //TODO: fix
+ //CPPUNIT_TEST(runMultipleMapsSameNameNoUserPublicTest);
CPPUNIT_TEST_SUITE_END();
public:
|
codereview_cpp_data_8058
|
t="file", d=fd;
static bool extractAll = Config_getBool(EXTRACT_ALL);
- //printf(" %s:warnIfUndoc: hasUserDocs=%d isFriendClass=%d isFiend=%d protection=%d isRef=%d isDel=%d\n",
// name().data(),
// hasUserDocumentation(),isFriendClass(),isFriend(),protectionLevelVisible(m_impl->prot),isReference(),isDeleted());
if ((!hasUserDocumentation() && !extractAll) &&
```suggestion //printf(" %s:warnIfUndoc: hasUserDocs=%d isFriendClass=%d isFriend=%d protection=%d isRef=%d isDel=%d\n", ```
t="file", d=fd;
static bool extractAll = Config_getBool(EXTRACT_ALL);
+ //printf(" %s:warnIfUndoc: hasUserDocs=%d isFriendClass=%d isFriend=%d protection=%d isRef=%d isDel=%d\n",
// name().data(),
// hasUserDocumentation(),isFriendClass(),isFriend(),protectionLevelVisible(m_impl->prot),isReference(),isDeleted());
if ((!hasUserDocumentation() && !extractAll) &&
|
codereview_cpp_data_8062
|
cctools_version_debug(D_MAKEFLOW_RUN, argv[0]);
-#ifdef MPI
- //the code assumes sizeof(void*) == UINT64_T
int need_mpi_finalize = 0;
if (batch_queue_type == BATCH_QUEUE_TYPE_MPI) {
MPI_Init(NULL, NULL);
Please put all these code in a function.
cctools_version_debug(D_MAKEFLOW_RUN, argv[0]);
+#ifdef CCTOOLS_WITH_MPI
+ //the code assumes sizeof(void*) == uint64_t
int need_mpi_finalize = 0;
if (batch_queue_type == BATCH_QUEUE_TYPE_MPI) {
MPI_Init(NULL, NULL);
|
codereview_cpp_data_8066
|
char *sandbox_name = string_format("%s/%s",p->sandbox,f->remote_name);
debug(D_WQ,"moving output file from %s to %s",sandbox_name,f->payload);
- if(copy_file_to_file(sandbox_name,f->payload)!=0) {
debug(D_WQ, "could not rename output file %s to %s: %s",sandbox_name,f->payload,strerror(errno));
}
Careful here: If rename works, we want to use it, since it is much cheaper. So, try the rename, and if that fails with errno==EXDEV, then use copy_file_to_file.
char *sandbox_name = string_format("%s/%s",p->sandbox,f->remote_name);
debug(D_WQ,"moving output file from %s to %s",sandbox_name,f->payload);
+ if(rename(sandbox_name, f->payload) != 0) {
+ copy_file_to_file(sandbox_name, f->payload);
+ }
+ if(errno != 0) {
debug(D_WQ, "could not rename output file %s to %s: %s",sandbox_name,f->payload,strerror(errno));
}
|
codereview_cpp_data_8068
|
HIPCHECK(hipGetTextureAlignmentOffset(&offset,&tex));
HIPCHECK(hipUnbindTexture(&tex));
HIPCHECK(hipFreeArray(hipArray));
-return true;
}
Should verify return offset value? Otherwise run_test() is always returning true.
HIPCHECK(hipGetTextureAlignmentOffset(&offset,&tex));
HIPCHECK(hipUnbindTexture(&tex));
HIPCHECK(hipFreeArray(hipArray));
+if(offset != 0)
+ return false;
+ else
+ return true;
}
|
codereview_cpp_data_8070
|
}
fmt::format_to(out,
- "#{:-3i} :: {} :: {}:{:-5} :: {:2} :: {}:{} :: {} :: ({})",
zone_server_data->GetID(),
is_static_string,
addr.c_str(),
fmtlib uses `<` and `>` for alignment instead of a minus sign. Also the `i` is an invalid specifier and will throw suggested fix: `"#{:<3} :: {} :: {}:{:<5} :: {:2} :: {}:{} :: {} :: ({})"`
}
fmt::format_to(out,
+ "#{:<3} :: {} :: {}:{:<5} :: {:2} :: {}:{} :: {} :: ({})",
zone_server_data->GetID(),
is_static_string,
addr.c_str(),
|
codereview_cpp_data_8072
|
std::shared_ptr<network::BlockLoader> blockLoader)
: validator_(std::move(validator)),
mutableFactory_(std::move(mutableFactory)),
- blockLoader_(std::move(blockLoader)),
- subscription_(rxcpp::composite_subscription()) {
log_ = logger::log("synchronizer");
consensus_gate->on_commit().subscribe(
subscription_,
Same for this constructor as above.
std::shared_ptr<network::BlockLoader> blockLoader)
: validator_(std::move(validator)),
mutableFactory_(std::move(mutableFactory)),
+ blockLoader_(std::move(blockLoader)) {
log_ = logger::log("synchronizer");
consensus_gate->on_commit().subscribe(
subscription_,
|
codereview_cpp_data_8073
|
adios2::IO bpIO = adios.DeclareIO("ReadBP");
/** Engine derived class, spawned to start IO operations */
- adios2::Engine bpReader =
- bpIO.Open(filename.c_str(), adios2::Mode::Read);
/** Write variable for buffering */
adios2::Variable<float> bpFloats =
The `IO::Open` call takes an `std::string` for filename so no need for the `c_str`
adios2::IO bpIO = adios.DeclareIO("ReadBP");
/** Engine derived class, spawned to start IO operations */
+ adios2::Engine bpReader = bpIO.Open(filename, adios2::Mode::Read);
/** Write variable for buffering */
adios2::Variable<float> bpFloats =
|
codereview_cpp_data_8077
|
auto error = (boost::format("invalid pagination hash: %s")
% first_hash->hex())
.str();
- // TODO: IR-82 nickaleks 7.12.18
- // add status code for invalid pagination
return this->logAndReturnErrorResponse(
QueryErrorType::kStatefulFailed, error, 4);
}
Remove TODO please
auto error = (boost::format("invalid pagination hash: %s")
% first_hash->hex())
.str();
return this->logAndReturnErrorResponse(
QueryErrorType::kStatefulFailed, error, 4);
}
|
codereview_cpp_data_8078
|
blacklist ${HOME}/.config/VirtualBox
# VeraCrypt
-blacklist /usr/bin/veracrypt
-blacklist /usr/bin/veracrypt-uninstall.sh
blacklist /usr/share/veracrypt
blacklist /usr/share/applications/veracrypt.*
blacklist /usr/share/pixmaps/veracrypt.*
You probably meant to use ${PATH} instead of an absolute path, didn't you?
blacklist ${HOME}/.config/VirtualBox
# VeraCrypt
+blacklist ${PATH}/veracrypt
+blacklist ${PATH}/veracrypt-uninstall.sh
blacklist /usr/share/veracrypt
blacklist /usr/share/applications/veracrypt.*
blacklist /usr/share/pixmaps/veracrypt.*
|
codereview_cpp_data_8082
|
}
void Mob::SetFeigned(bool in_feigned) {
- if (in_feigned)
- {
if (IsClient()) {
- if (RuleB(Character, FeignKillsPet))
- {
SetPet(0);
}
CastToClient()->SetHorseId(0);
Formatting is inconsistent here.
}
void Mob::SetFeigned(bool in_feigned) {
+
+ if (in_feigned) {
+
if (IsClient()) {
+ if (RuleB(Character, FeignKillsPet)){
SetPet(0);
}
CastToClient()->SetHorseId(0);
|
codereview_cpp_data_8083
|
if (xy.y < 0.) lp.phi = -lp.phi;
lp.lam /= V(X[i], t);
if( fabs(lp.lam) > M_PI ) {
- lp.lam = lp.phi = HUGE_VAL;
}
}
return lp;
I think it would be nice to set an error here. Something like: ```suggestion proj_errno_set(P, PJD_ERR_LAT_OR_LON_EXCEED_LIMIT); lp = proj_coord_error().lp; ``` There may be a better error code to set but if I understand the problem correctly this one fits the bill.
if (xy.y < 0.) lp.phi = -lp.phi;
lp.lam /= V(X[i], t);
if( fabs(lp.lam) > M_PI ) {
+ proj_errno_set(P, PJD_ERR_LAT_OR_LON_EXCEED_LIMIT);
+ lp = proj_coord_error().lp;
}
}
return lp;
|
codereview_cpp_data_8104
|
#include "h2d.h"
#include "h2d_file.h"
#include "settings.h"
namespace
{
The choice of the "data" directory is generally logical, but the fact that the original game uses the same directory is a bit confusing I think. This directory may be accidentally removed or replaced by user. May be rename it somehow? Or may be move it to "files", as it done with "fonts" and "lang"?
#include "h2d.h"
#include "h2d_file.h"
#include "settings.h"
+#include "system.h"
namespace
{
|
codereview_cpp_data_8108
|
const uint32_t skill = hero.GetLevelSkill( Skill::Secondary::PATHFINDING );
double maxPriority = -1.0 * Maps::Ground::slowestMovePenalty * world.w() * world.h();
- std::vector<MapObjectNode>::iterator selectedNode = mapObjects.end();
for ( size_t idx = 0; idx < mapObjects.size(); ++idx ) {
const MapObjectNode & node = mapObjects[idx];
if ( HeroesValidObject( hero, node.first ) ) {
We could do something like this: ``` size_t selectedNode = mapObjects.size(); ... selectedNode = idx; ... if ( selectedNode < mapObjects.size() ) { ... mapObjects.erase( selectedNode + mapObjects.begin() ); ```
const uint32_t skill = hero.GetLevelSkill( Skill::Secondary::PATHFINDING );
double maxPriority = -1.0 * Maps::Ground::slowestMovePenalty * world.w() * world.h();
+ int objectID = MP2::OBJ_ZERO;
+ size_t selectedNode = mapObjects.size();
for ( size_t idx = 0; idx < mapObjects.size(); ++idx ) {
const MapObjectNode & node = mapObjects[idx];
if ( HeroesValidObject( hero, node.first ) ) {
|
codereview_cpp_data_8118
|
mg_info_ptr[i]->grid_id = i;
mg_info_ptr[i]->num_grids = numDevices;
mg_info_ptr[i]->all_sum = all_sum;
- mg_info_ptr[i]->prev_sum = 0;
- for (int j = 0; j < i; ++j) {
- const hipLaunchParams& lp1 = launchParamsList[j];
- mg_info_ptr[i]->prev_sum += lp1.blockDim.x * lp1.blockDim.y * lp1.blockDim.z *
- lp1.gridDim.x * lp1.gridDim.y * lp1.gridDim.z;
- }
impCoopParams[0] = &mg_info_ptr[i];
Wouldn't it be easier and faster to keep a running sum in the i loop instead of recalculating prev_sum on each iteration?
mg_info_ptr[i]->grid_id = i;
mg_info_ptr[i]->num_grids = numDevices;
mg_info_ptr[i]->all_sum = all_sum;
+ mg_info_ptr[i]->prev_sum = prev_sum;
+ prev_sum += lp.blockDim.x * lp.blockDim.y * lp.blockDim.z *
+ lp.gridDim.x * lp.gridDim.y * lp.gridDim.z;
+
impCoopParams[0] = &mg_info_ptr[i];
|
codereview_cpp_data_8122
|
__dmul_rn(1.0, 2.0);
__dmul_ru(1.0, 2.0);
__dmul_rz(1.0, 2.0);
-#endif
__drcp_rd(2.0);
__drcp_rn(2.0);
__drcp_ru(2.0);
__drcp_rz(2.0);
-#if defined OCML_BASIC_ROUNDED_OPERATIONS
__dsqrt_rd(4.0);
__dsqrt_rn(4.0);
__dsqrt_ru(4.0);
Why is drcp not hidden? I don't think there is a correct implementation
__dmul_rn(1.0, 2.0);
__dmul_ru(1.0, 2.0);
__dmul_rz(1.0, 2.0);
__drcp_rd(2.0);
__drcp_rn(2.0);
__drcp_ru(2.0);
__drcp_rz(2.0);
__dsqrt_rd(4.0);
__dsqrt_rn(4.0);
__dsqrt_ru(4.0);
|
codereview_cpp_data_8124
|
}
// execute each effects group one by one
- std::map<int, std::vector<std::pair<Effect::EffectsGroup*, Effect::TargetsCauses> > >::reverse_iterator priority_group_it;
- for (priority_group_it = dispatched_targets_causes.rbegin();
- priority_group_it != dispatched_targets_causes.rend(); ++priority_group_it)
{
std::vector<std::pair<Effect::EffectsGroup*, Effect::TargetsCauses> >::iterator effect_group_it;
for (effect_group_it = priority_group_it->second.begin();
Ah, I see, you've reverse iterated here...
}
// execute each effects group one by one
+ std::map<int, std::vector<std::pair<Effect::EffectsGroup*, Effect::TargetsCauses> > >::iterator priority_group_it;
+ for (priority_group_it = dispatched_targets_causes.begin();
+ priority_group_it != dispatched_targets_causes.end(); ++priority_group_it)
{
std::vector<std::pair<Effect::EffectsGroup*, Effect::TargetsCauses> >::iterator effect_group_it;
for (effect_group_it = priority_group_it->second.begin();
|
codereview_cpp_data_8125
|
}
int ret;
- if (ctx->use_udp_gso) {
mess.msg_iov = datagrams;
mess.msg_iovlen = num_datagrams;
while ((ret = (int)sendmsg(h2o_socket_get_fd(ctx->sock.sock), &mess, 0)) == -1 && errno == EINTR)
I think we might want to guard this clause with `#ifdef UDP_SEGMENT`. The rationale is to prohibit erroneous behavior when libh2o is compiled without GSO support but the flag is being set. I understand that such behavior is not expected when the standalone server is being used (as we have the check in src/main.c), but libh2o can be used other ways.
}
int ret;
+ if (ctx->use_gso) {
mess.msg_iov = datagrams;
mess.msg_iovlen = num_datagrams;
while ((ret = (int)sendmsg(h2o_socket_get_fd(ctx->sock.sock), &mess, 0)) == -1 && errno == EINTR)
|
codereview_cpp_data_8130
|
if (ctx->req_insert_count == 0)
return H2O_HTTP3_ERROR_QPACK_DECOMPRESSION_FAILED;
}
/* sign and delta base */
if (*src >= src_end)
I think the upper bound should be smaller than INT64_MAX, because we do in `resolve_dynamic_postbase` we do `base_index + 1`. How about changing the valid maximum value of `req_insert_count` and `delta_base` from 2<sup>63</sup> - 1 to 2<sup>62</sup> - 1? The rationale is that a QPACK encoder using a QUIC v1 stream can never create more than 2<sup>62</sup> QPACK table entries. That is because the smallest size of a QPACK encoder instruction is 1 byte, and because the length of a QPACK encoder stream can be no longer than 2<sup>62</sup> bytes. If we make such a change, then we can be certain that `base_index` would never be as large as 2<sup>63</sup> - 1.
if (ctx->req_insert_count == 0)
return H2O_HTTP3_ERROR_QPACK_DECOMPRESSION_FAILED;
}
+ if (ctx->req_insert_count > PTLS_QUICINT_MAX) {
+ return H2O_HTTP3_ERROR_QPACK_DECOMPRESSION_FAILED;
+ }
/* sign and delta base */
if (*src >= src_end)
|
codereview_cpp_data_8134
|
if (!type.IsValid())
return false;
class_type_or_name.SetCompilerType(type.GetPointerType());
return class_type_or_name.GetCompilerType().IsValid();
}
`address` is passed by-reference. Do we want to still `SetRawAddress` when we get a `class_metadata_ptr`, i.e., ``` if (class_metadata_ptr && class_metadata_ptr != LLDB_INVALID_ADDRESS) address.SetRawAddress(class_metadata_ptr); ``` eliminating the early exit but not the successful case?
if (!type.IsValid())
return false;
+ lldb::addr_t class_metadata_ptr = payload0_sp->GetAddressOf();
+ if (class_metadata_ptr && class_metadata_ptr != LLDB_INVALID_ADDRESS)
+ address.SetRawAddress(class_metadata_ptr);
+
class_type_or_name.SetCompilerType(type.GetPointerType());
return class_type_or_name.GetCompilerType().IsValid();
}
|
codereview_cpp_data_8136
|
authentication_plugin_->return_sharedsecret_handle(shared_secret_handle, exception);
}
DiscoveredParticipantInfo::AuthUniquePtr remote_participant_info = dp_it->second.get_auth();
remove_discovered_participant_info(remote_participant_info);
```suggestion // AuthUniquePtr must be removed after unlock SecurityManager's mutex. // This is to avoid a deadlock with TimedEvents. DiscoveredParticipantInfo::AuthUniquePtr remote_participant_info = dp_it->second.get_auth(); ```
authentication_plugin_->return_sharedsecret_handle(shared_secret_handle, exception);
}
+ // AuthUniquePtr must be removed after unlock SecurityManager's mutex.
+ // This is to avoid a deadlock with TimedEvents.
DiscoveredParticipantInfo::AuthUniquePtr remote_participant_info = dp_it->second.get_auth();
remove_discovered_participant_info(remote_participant_info);
|
codereview_cpp_data_8143
|
node_vector nodes;
for (const auto& item : client->mPublicLinks)
{
- n = client->nodebyhandle(item.second);
if (n)
{
nodes.emplace_back(n);
Would it be possible that `mPublicLinks` stores a `nodehandle` that is not found among the nodes in the account? (so the `n == nullptr`) I think it would be a bug. You may want to add an `assert()` in that case, rather than the if. ```suggestion assert(client->nodebyhandle(item.second)); nodes.emplace_back(client->nodebyhandle(item.second)); ```
node_vector nodes;
for (const auto& item : client->mPublicLinks)
{
+ assert(client->nodebyhandle(item.second));
+ nodes.emplace_back(client->nodebyhandle(item.second));
if (n)
{
nodes.emplace_back(n);
|
codereview_cpp_data_8153
|
qsort(&containers[0], count, sizeof(struct lxc_container *), cmporder);
if (cmd_groups_list && my_args.all)
- ERROR("Specifying -a (all) with -g (groups) doesn't make sense. All option overrides.");
/* We need a default cmd_groups_list even for the -a
* case in order to force a pass through the loop for
Please remove the trailing `.` while you're at it. :)
qsort(&containers[0], count, sizeof(struct lxc_container *), cmporder);
if (cmd_groups_list && my_args.all)
+ ERROR("Specifying -a (all) with -g (groups) doesn't make sense. All option overrides");
/* We need a default cmd_groups_list even for the -a
* case in order to force a pass through the loop for
|
codereview_cpp_data_8155
|
#include <fastrtps/participant/Participant.h>
#include <fastdds/dds/log/Log.hpp>
-#include <utils/SystemInfo.hpp>
-
using namespace eprosima;
using namespace fastrtps;
using namespace std;
This is a private header, and can't be used here
#include <fastrtps/participant/Participant.h>
#include <fastdds/dds/log/Log.hpp>
using namespace eprosima;
using namespace fastrtps;
using namespace std;
|
codereview_cpp_data_8162
|
bool image_data_reader::fetch_label(CPUMat& Y, int data_id, int mb_idx) {
const label_t label = m_image_list[data_id].second;
- if (label >= 0 && label < m_num_labels) {
- Y.Set(label, mb_idx, 1);
- }
- else {
LBANN_ERROR(
"\"",this->get_type(),"\" data reader ",
"expects data with ",m_num_labels," labels, ",
"but data sample ",data_id," has a label of ",label);
}
return true;
}
I would use static_cast<label_t>(0) and static_cast<label_T>(m_num_labels) just in case.
bool image_data_reader::fetch_label(CPUMat& Y, int data_id, int mb_idx) {
const label_t label = m_image_list[data_id].second;
+ if (label < label_t{0} || label >= static_cast<label_t>(m_num_labels)) {
LBANN_ERROR(
"\"",this->get_type(),"\" data reader ",
"expects data with ",m_num_labels," labels, ",
"but data sample ",data_id," has a label of ",label);
}
+ Y.Set(label, mb_idx, 1);
return true;
}
|
codereview_cpp_data_8166
|
void Probe::constructOutputs()
{
- constructOutput<SimTK::Vector>("probeOutputs", &Probe::getProbeOutputs,
Stage::Report);
}
Is the `&` actually required here? I think C++ treats a function name (with no following `()`) as a pointer to the function. What happens if you leave it off?
void Probe::constructOutputs()
{
+ constructOutput<SimTK::Vector>("probe_outputs", &Probe::getProbeOutputs,
Stage::Report);
}
|
codereview_cpp_data_8172
|
}
else
{
- DiscoveredParticipantInfo::AuthUniquePtr remote_participant_info = std::move(auth_ptr);
remove_discovered_participant_info(remote_participant_info);
lock.unlock();
}
```suggestion // AuthUniquePtr must be removed after unlock SecurityManager's mutex. // This is to avoid a deadlock with TimedEvents. DiscoveredParticipantInfo::AuthUniquePtr remote_participant_info = std::move(auth_ptr); ```
}
else
{
+ // AuthUniquePtr must be removed after unlock SecurityManager's mutex.
+ // This is to avoid a deadlock with TimedEvents.
+ DiscoveredParticipantInfo::AuthUniquePtr remote_participant_info = std::move(auth_ptr);
remove_discovered_participant_info(remote_participant_info);
lock.unlock();
}
|
codereview_cpp_data_8178
|
#include "Version.h"
QString MumbleSSL::defaultOpenSSLCipherString() {
- return QLatin1String("ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!CAMELLIA:!MD5:!PSK:!SRP:!DH:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA");
}
QList<QSslCipher> MumbleSSL::ciphersFromOpenSSLCipherString(QString cipherString) {
Unless this is copy and pasted from somewhere - and maybe even then - we should split this up into a line per suite so we can properly read it easily in source and have proper diffs on it.
#include "Version.h"
QString MumbleSSL::defaultOpenSSLCipherString() {
+ return QLatin1String("EECDH+AESGCM:AES256-SHA:AES128-SHA");
}
QList<QSslCipher> MumbleSSL::ciphersFromOpenSSLCipherString(QString cipherString) {
|
codereview_cpp_data_8182
|
offset = 0;
colCounter = 0;
char *lastIndex = "#0";
- if(getColumnCount(lineBuffer, delim) != columns)
- {
- }
while((col = parseLine(lineBuffer, delim, offset)) != NULL)
{
cur = getKeyByOrderNr(header, colCounter);
Can you fix this and rebase this merge request? Then I can apply this before #311.
offset = 0;
colCounter = 0;
char *lastIndex = "#0";
while((col = parseLine(lineBuffer, delim, offset)) != NULL)
{
cur = getKeyByOrderNr(header, colCounter);
|
codereview_cpp_data_8183
|
h2o_header_t *headers, size_t num_headers, int header_requires_dup)
{
struct st_h2o_mruby_http_request_context_t *ctx = client->data;
- if (can_dispose_context(ctx)) {
- ctx->client = NULL;
- dispose_context(ctx);
return NULL;
- }
int gc_arena = mrb_gc_arena_save(ctx->ctx->shared->mrb);
mrb_gc_protect(ctx->ctx->shared->mrb, ctx->refs.request);
I see this code repeated lots of times, wonder if we can avoid repeating the same thing. For example, would it make sense to do something like: ``` if (!context_is_alive_or_dispose(ctx)) return NULL; ``` while defining `context_is_alive_or_dispose` as a function that checks if the context is alive, and if not, disposes it? Admittedly, the name sounds terse (we should preferably choose a better one), but IMO being terse is better than having the same logic copy-pasted.
h2o_header_t *headers, size_t num_headers, int header_requires_dup)
{
struct st_h2o_mruby_http_request_context_t *ctx = client->data;
+ if (try_dispose_context(ctx))
return NULL;
int gc_arena = mrb_gc_arena_save(ctx->ctx->shared->mrb);
mrb_gc_protect(ctx->ctx->shared->mrb, ctx->refs.request);
|
codereview_cpp_data_8187
|
#include "tls/s2n_cipher_suites.h"
-/* This test checks that the compiler correctly implements deferred cleanup */
int main()
{
BEGIN_TEST();
Can you expand on what you mean by this?
#include "tls/s2n_cipher_suites.h"
int main()
{
BEGIN_TEST();
|
codereview_cpp_data_8199
|
d->append((char*)&ou, sizeof ou);
d->append((char*)&ts, sizeof(ts));
- char hasAttachments = attachedNodes.size();
d->append((char*)&hasAttachments, 1);
d->append("\0\0\0\0\0\0\0\0", 9); // additional bytes for backwards compatibility
This should be `char hasAttachments = attachedNodes.size() != 0;`. Otherwise the size could overflow the char.
d->append((char*)&ou, sizeof ou);
d->append((char*)&ts, sizeof(ts));
+ char hasAttachments = attachedNodes.size() != 0;
d->append((char*)&hasAttachments, 1);
d->append("\0\0\0\0\0\0\0\0", 9); // additional bytes for backwards compatibility
|
codereview_cpp_data_8202
|
// 30505 for changing serialization of Joint to create offset frames
// 30506 for testing 30505 conversion code
// 30507 for changing serialization of Coordinates owned by Joint
-// 30509 for changing property Constraint::isDisabled to Constraint::isEnforced
-const int XMLDocument::LatestVersion = 30509;
//=============================================================================
// DESTRUCTOR AND CONSTRUCTOR(S)
//=============================================================================
A note. Since the `Force`, `Constraint` and `Controller` are part of the same *rename* process I would just increment once for these.
// 30505 for changing serialization of Joint to create offset frames
// 30506 for testing 30505 conversion code
// 30507 for changing serialization of Coordinates owned by Joint
+// 30508 for moving Connector's connectee_name to enclosing Component.
+const int XMLDocument::LatestVersion = 30508;
//=============================================================================
// DESTRUCTOR AND CONSTRUCTOR(S)
//=============================================================================
|
codereview_cpp_data_8214
|
}
/**
- * @brief Save the current screen to a screen??.PCX (00-99) in file is avalible, then make the screen red for 200ms.
*/
void CaptureScreen()
{
```suggestion * @brief Save the current screen to a screen??.PCX (00-99) in file if available, then make the screen red for 200ms. ```
}
/**
+ * @brief Save the current screen to a screen??.PCX (00-99) in file if available, then make the screen red for 200ms.
+
*/
void CaptureScreen()
{
|
codereview_cpp_data_8216
|
std::vector<std::function<std::string()>> message_gen = {
[&] {
// TODO(@l4l) 26/06/18 need to be simplified at IR-1479
- const auto &str = perm_converter_->toString(permissions);
const auto perm_debug_str =
std::accumulate(str.begin(), str.end(), std::string());
return (boost::format("failed to insert role permissions, role "
No point in creating a reference
std::vector<std::function<std::string()>> message_gen = {
[&] {
// TODO(@l4l) 26/06/18 need to be simplified at IR-1479
+ const auto str = perm_converter_->toString(permissions);
const auto perm_debug_str =
std::accumulate(str.begin(), str.end(), std::string());
return (boost::format("failed to insert role permissions, role "
|
codereview_cpp_data_8222
|
lp.av->dispatch_hsa_kernel(&aql, config[1] /* kernarg*/, kernArgSize,
(startEvent || stopEvent) ? &cf : nullptr
, f->_name.c_str()
);
Looks like this needs to be guarded using hcc_workweek since ROCm 1.6.x HCC does not support this.
lp.av->dispatch_hsa_kernel(&aql, config[1] /* kernarg*/, kernArgSize,
(startEvent || stopEvent) ? &cf : nullptr
+#if (__hcc_workweek__ >= 17300)
, f->_name.c_str()
+#endif
);
|
codereview_cpp_data_8223
|
LBANN_ASSERT_MSG_HAS_FIELD(proto_layer, scatter);
using BuilderType = Builder<TensorDataType, Layout, Device>;
auto dims = parse_list<int>(proto_layer.scatter().dims());
- auto axis = proto_layer.scatter().axis().value();
return BuilderType::Build(dims, axis);
}
Do we want a default value of 0?
LBANN_ASSERT_MSG_HAS_FIELD(proto_layer, scatter);
using BuilderType = Builder<TensorDataType, Layout, Device>;
auto dims = parse_list<int>(proto_layer.scatter().dims());
+ const auto& params = proto_layer.gather();
+ int axis = -1;
+ if (params.has_axis()){
+ axis = params.axis().value();
+ }
return BuilderType::Build(dims, axis);
}
|
codereview_cpp_data_8242
|
p->Add(exec_treecompare, sequence(text("treecompare"), localFSPath(), remoteFSPath(client, &cwd)));
#endif
p->Add(exec_querytransferquota, sequence(text("querytransferquota"), param("filesize")));
- p->Add(exec_fingerprintsumsizes, sequence(text("fingerprintsumsizes")));
p->Add(exec_getuserquota, sequence(text("getuserquota"), repeat(either(flag("-storage"), flag("-transfer"), flag("-pro")))));
return autocompleteTemplate = std::move(p);
Perhaps we can call it `getcloudstorageused` which is more meaningful for a non-familiar user :)
p->Add(exec_treecompare, sequence(text("treecompare"), localFSPath(), remoteFSPath(client, &cwd)));
#endif
p->Add(exec_querytransferquota, sequence(text("querytransferquota"), param("filesize")));
+ p->Add(exec_getcloudstorageused, sequence(text("getcloudstorageused")));
p->Add(exec_getuserquota, sequence(text("getuserquota"), repeat(either(flag("-storage"), flag("-transfer"), flag("-pro")))));
return autocompleteTemplate = std::move(p);
|
codereview_cpp_data_8244
|
-t <tracepoint> A tracepoint, or fully-qualified probe name to trace. Glob
patterns can be used; e.g., "quicly:accept", "h2o:*".
-S <rate> Enable random sampling per connection (0.0-1.0). Requires
- use of `usdt-selective-tracing: ON` in the h2o config file.
-A <ip-address> Limit connections being traced to those coming from the
specified address. Requries use of `usdt-selective-tracing`.
-N <server-name> Limit connections being traced to those carrying the
Thank you for spotting this. If we are to change the exlanation in alignment with that of `-A`, then maybe something ilke: ```suggestion use of `usdt-selective-tracing`. ``` Alternatively we could say that it "requires `usdt-selective-tracing: ON`" (notice the omission of "use of", I think it sounds strange when we talk about the exact setting rather than naming the setting), but that might be too verbose.
-t <tracepoint> A tracepoint, or fully-qualified probe name to trace. Glob
patterns can be used; e.g., "quicly:accept", "h2o:*".
-S <rate> Enable random sampling per connection (0.0-1.0). Requires
+ use of `usdt-selective-tracing`.
-A <ip-address> Limit connections being traced to those coming from the
specified address. Requries use of `usdt-selective-tracing`.
-N <server-name> Limit connections being traced to those carrying the
|
codereview_cpp_data_8245
|
amrex::LoopOnCpu(section, [&](int i, int j, int k)
{
amrex::Dim3 si = dtos(amrex::Dim3{i,j,k});
- AMREX_ASSERT(array(i,j,k) == (si.x + si.y*nx + si.z*nx*ny));
});
}
return fails == 0;
I suppose we also need `fails += array(i,j,k) != value` in addition to the assert. Otherwise `fails` does not change.
amrex::LoopOnCpu(section, [&](int i, int j, int k)
{
amrex::Dim3 si = dtos(amrex::Dim3{i,j,k});
+ int value = si.x + si.y*nx + si.z*nx*xy;
+ fails += (array(i,j,k) != value);
+
+ AMREX_ASSERT(fails); // If DEBUG, crash on first error.
});
}
return fails == 0;
|
codereview_cpp_data_8246
|
// Append the containing dir to the PATH
auto current_path = std::getenv("PATH");
- std::string new_path = toString(dummy_dir) + ":" + current_path;
setenv("PATH", new_path.c_str(), 1);
setenv("PathWhenSymlinkInPathUnixOnly_Setup", "true", 1);
// Locate the file with only its name
absolute_path_to_dummy = findInSystemPath(dummy_file_path.filename());
- EXPECT_TRUE(exists(absolute_path_to_dummy));
EXPECT_EQ(dummy_file_path, absolute_path_to_dummy);
// Put it back
Needs a Windows case?
// Append the containing dir to the PATH
auto current_path = std::getenv("PATH");
+ std::string new_path = toString(dummy_dir) + getPlatformDelimiterForPath() + current_path;
setenv("PATH", new_path.c_str(), 1);
setenv("PathWhenSymlinkInPathUnixOnly_Setup", "true", 1);
// Locate the file with only its name
absolute_path_to_dummy = findInSystemPath(dummy_file_path.filename());
+ EXPECT_TRUE(exists(absolute_path_to_dummy)) << "Tried to find " << dummy_file_path.filename() << "in path: " << current_path;
EXPECT_EQ(dummy_file_path, absolute_path_to_dummy);
// Put it back
|
codereview_cpp_data_8253
|
reader.block_for_all();
}
TEST(Discovery, StaticDiscoveryFromString)
{
char* value = std::getenv("TOPIC_RANDOM_NUMBER");
I'd like a description of the general purpose of the tests followed by a step by step guide on the actions taken
reader.block_for_all();
}
+/*!
+ * Test Static EDP discovery configured via a XML content in a raw string.
+ */
TEST(Discovery, StaticDiscoveryFromString)
{
char* value = std::getenv("TOPIC_RANDOM_NUMBER");
|
codereview_cpp_data_8254
|
else
{
// This means that the only change is in wire_protocol().builtin.discovery_config.m_DiscoveryServers
- // In that case, we need to ensure that the list in to is strictly contained in the list in from.
- // For that, we check that every server in the current list (to) is also in the incoming one (from)
for (auto existing_server : to.wire_protocol().builtin.discovery_config.m_DiscoveryServers)
{
bool contained = false;
```suggestion // In that case, we need to ensure that the current list (to) is strictly contained in the incoming list (from). // For that, we check that every server in list to is also in the incoming one from. ``` I think that this way is clearer stating explicitly that `to` and `from` is referring to the given parameters.
else
{
// This means that the only change is in wire_protocol().builtin.discovery_config.m_DiscoveryServers
+ // In that case, we need to ensure that the current list (to) is strictly contained in the incoming
+ // list (from). For that, we check that every server in the current list (to) is also in the incoming one
+ // (from)
for (auto existing_server : to.wire_protocol().builtin.discovery_config.m_DiscoveryServers)
{
bool contained = false;
|
codereview_cpp_data_8256
|
boost::optional<iroha::protocol::TxStatus> last_tx_status;
auto rounds_counter{0};
- auto stream_failed = false;
command_service_
->getStatusStream(hash)
// convert to transport objects
It should be possible to refactor without using this variable.
boost::optional<iroha::protocol::TxStatus> last_tx_status;
auto rounds_counter{0};
+ std::mutex stream_write_mutex;
command_service_
->getStatusStream(hash)
// convert to transport objects
|
codereview_cpp_data_8262
|
if (dup (pipe_stdin[0]) < 0)
{
ELEKTRA_SET_ERROR (ELEKTRA_ERROR_CRYPTO_GPG, errorKey, "failed to redirect stdin.");
- return -2;
}
}
close (pipe_stdin[0]);
We have already forked here, this might not do what you expect. (It does not set an error in our process, same problem also 3x below.) See also #1590
if (dup (pipe_stdin[0]) < 0)
{
ELEKTRA_SET_ERROR (ELEKTRA_ERROR_CRYPTO_GPG, errorKey, "failed to redirect stdin.");
+ exit (42);
}
}
close (pipe_stdin[0]);
|
codereview_cpp_data_8264
|
}
else if ( castle.isFriends( conf.CurrentColor() ) ) {
// show all
- Army::DrawMonsterLines( castle.GetArmy(), cur_rt.x - 5, cur_rt.y + 62, 192, Skill::Level::EXPERT, DRAW_SCOUTE, false );
}
// draw enemy castle defenders, dependent on thieves guild count
else if ( thievesGuildCount == 0 ) {
Please cache `castle.GetColor()` value before line 646 and use it everywhere.
}
else if ( castle.isFriends( conf.CurrentColor() ) ) {
// show all
+ Army::DrawMonsterLines( castle.GetArmy(), cur_rt.x - 5, cur_rt.y + 62, 192, Skill::Level::EXPERT, true, false );
}
// draw enemy castle defenders, dependent on thieves guild count
else if ( thievesGuildCount == 0 ) {
|
codereview_cpp_data_8271
|
arena->DialogBattleSummary( result, artifactsToTransfer, false );
}
if ( hero_wins != nullptr && hero_loss != nullptr && loserAbandoned ) {
- transferArtifacts( hero_wins->GetBagArtifacts(), hero_loss->GetBagArtifacts(), artifactsToTransfer );
}
// save count troop
Don't you think that it would be better to actually transfer only artifacts listed in `artifactsToTransfer` in the `transferArtifacts()` itself?
arena->DialogBattleSummary( result, artifactsToTransfer, false );
}
+ // if both armies had heroes and the defeated hero didn't flee or surrender: capture the artifacts
if ( hero_wins != nullptr && hero_loss != nullptr && loserAbandoned ) {
+ clearArtifacts( hero_loss->GetBagArtifacts() );
+ transferArtifacts( hero_wins->GetBagArtifacts(), artifactsToTransfer );
}
// save count troop
|
codereview_cpp_data_8292
|
for (int i = 0; i < train_data_->num_features(); ++i) {
total_histogram_size += sizeof(HistogramBinEntry) * train_data_->FeatureAt(i)->num_bin();
}
- max_cache_size = static_cast<int>(histogram_pool_size_ * 1024 * 1024 * 1024 / total_histogram_size);
-
}
// at least need 2 leaves
max_cache_size = Common::Max(2, max_cache_size);
here is assuming the num_leaves couldn't less than 2, right?
for (int i = 0; i < train_data_->num_features(); ++i) {
total_histogram_size += sizeof(HistogramBinEntry) * train_data_->FeatureAt(i)->num_bin();
}
+ max_cache_size = static_cast<int>(histogram_pool_size_ * 1024 * 1024 / total_histogram_size);
}
// at least need 2 leaves
max_cache_size = Common::Max(2, max_cache_size);
|
codereview_cpp_data_8302
|
Kokkos::Impl::initialize_space_factory<SYCLSpaceInitializer>("170_SYCL");
void SYCLSpaceInitializer::initialize(const InitArguments& args) {
- // If there a no GPUs return whatever else we can run on if no specific GPU is
// requested.
const auto num_gpus =
sycl::device::get_devices(sycl::info::device_type::gpu).size();
```suggestion // If there are no GPUs return whatever else we can run on if no specific GPU is ```
Kokkos::Impl::initialize_space_factory<SYCLSpaceInitializer>("170_SYCL");
void SYCLSpaceInitializer::initialize(const InitArguments& args) {
+ // If there are no GPUs return whatever else we can run on if no specific GPU is
// requested.
const auto num_gpus =
sycl::device::get_devices(sycl::info::device_type::gpu).size();
|
codereview_cpp_data_8311
|
#include <cassert>
namespace sorting {
/**
* Function to shuffle the elements of an array.
```suggestion /** * @namespace sorting * @brief Sorting algorithms */ namespace sorting { ```
#include <cassert>
+/**
+ * @namespace sorting
+ * @brief Sorting algorithms
+ */
namespace sorting {
/**
* Function to shuffle the elements of an array.
|
codereview_cpp_data_8315
|
if(o->type==JX_OP_CALL && jx_istype(o->left,JX_SYMBOL)) {
const char *name = o->left->u.symbol_name;
- if(!strcmp("select",name) || !strcmp("project",name) || !strcmp("like",name)) {
struct jx *r = jx_array_shift(o->right);
r = jx_string(jx_print_string((r)));
jx_array_insert(o->right, r);
Is quoting the first argument necessary here? If I try to get the regex from a variable, it crashes expression: like(infile,"test") jx_function_like: jx_function.c:794[DEVELOPMENT]: Assertion 'jx_istype(val, JX_STRING)' failed. Aborted (core dumped)
if(o->type==JX_OP_CALL && jx_istype(o->left,JX_SYMBOL)) {
const char *name = o->left->u.symbol_name;
+ if(!strcmp("select",name) || !strcmp("project",name)) {
struct jx *r = jx_array_shift(o->right);
r = jx_string(jx_print_string((r)));
jx_array_insert(o->right, r);
|
codereview_cpp_data_8324
|
GUARD(s2n_stuffer_write_bytes(out, client_protocol_version, S2N_TLS_PROTOCOL_VERSION_LEN));
GUARD(s2n_stuffer_copy(&client_random, out, S2N_TLS_RANDOM_DATA_LEN));
GUARD(s2n_stuffer_write_uint8(out, session_id_len));
- GUARD(s2n_stuffer_write_uint16(out, conn->config->cipher_preferences->count * 2));
- GUARD(s2n_stuffer_write_bytes(out, conn->config->cipher_preferences->wire_format, conn->config->cipher_preferences->count * 2));
/* Zero compression methods */
GUARD(s2n_stuffer_write_uint8(out, 1));
how about using S2N_TLS_CIPHER_SUITE_LEN instead of 2?
GUARD(s2n_stuffer_write_bytes(out, client_protocol_version, S2N_TLS_PROTOCOL_VERSION_LEN));
GUARD(s2n_stuffer_copy(&client_random, out, S2N_TLS_RANDOM_DATA_LEN));
GUARD(s2n_stuffer_write_uint8(out, session_id_len));
+ GUARD(s2n_stuffer_write_uint16(out, conn->config->cipher_preferences->count * S2N_TLS_CIPHER_SUITE_LEN));
+ GUARD(s2n_stuffer_write_bytes(out, conn->config->cipher_preferences->wire_format, conn->config->cipher_preferences->count * S2N_TLS_CIPHER_SUITE_LEN));
/* Zero compression methods */
GUARD(s2n_stuffer_write_uint8(out, 1));
|
codereview_cpp_data_8327
|
#include "vast/format/csv.hpp"
#include "vast/concept/parseable/core.hpp"
-#include "vast/concept/parseable/string.hpp"
#include "vast/concept/parseable/string/char_class.hpp"
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast.hpp"
You should be able to remove this include.
#include "vast/format/csv.hpp"
#include "vast/concept/parseable/core.hpp"
#include "vast/concept/parseable/string/char_class.hpp"
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast.hpp"
|
codereview_cpp_data_8348
|
}
const fheroes2::Sprite & panel = fheroes2::AGG::GetICN( ICN::REQSBKG, 0 );
- Rect rt( ( display.width() - panel.width() ) - 35, 10, panel.width(), panel.height() );
fheroes2::ImageRestorer background( display, rt.x - SHADOWWIDTH, rt.y, rt.w + SHADOWWIDTH, rt.h + SHADOWWIDTH );
Hi @kant2002 , we might need to revert this and similar change in **game_scenarioinfo.cpp** file as the description of the original issue might be outdated. Please do not do any change as of now.
}
const fheroes2::Sprite & panel = fheroes2::AGG::GetICN( ICN::REQSBKG, 0 );
+ Rect rt( ( display.width() - panel.width() ) / 2, ( display.height() - panel.height() ) / 2, panel.width(), panel.height() );
fheroes2::ImageRestorer background( display, rt.x - SHADOWWIDTH, rt.y, rt.w + SHADOWWIDTH, rt.h + SHADOWWIDTH );
|
codereview_cpp_data_8366
|
* "cap_net_raw" (no use for this in %post, and major source of security vulnerabilities)
* "cap_mknod" (%post should not be making devices, it wouldn't be persistent anyways)
* "cap_audit_write" (we shouldn't be auditing anything from here)
*
* But crucially we're dropping a lot of other capabilities like
* "cap_sys_admin", "cap_sys_module", etc that Docker also drops by default.
* We don't want RPM scripts to be doing any of that. Instead, do it from
* systemd unit files.
*/
if (getuid () == 0)
rpmostree_bwrap_append_bwrap_argv (ret, "--cap-drop", "ALL",
Can we drop this one too?
* "cap_net_raw" (no use for this in %post, and major source of security vulnerabilities)
* "cap_mknod" (%post should not be making devices, it wouldn't be persistent anyways)
* "cap_audit_write" (we shouldn't be auditing anything from here)
+ * "cap_net_bind_service" (nothing should be doing IP networking at all)
*
* But crucially we're dropping a lot of other capabilities like
* "cap_sys_admin", "cap_sys_module", etc that Docker also drops by default.
* We don't want RPM scripts to be doing any of that. Instead, do it from
* systemd unit files.
+ *
+ * Also this way we drop out any new capabilities that appear.
*/
if (getuid () == 0)
rpmostree_bwrap_append_bwrap_argv (ret, "--cap-drop", "ALL",
|
codereview_cpp_data_8370
|
const Army enemy( tile );
return army.isStrongerThan( enemy, AI::ARMY_STRENGTH_ADVANTAGE_LARGE );
}
- else {
- return true;
- }
}
break;
:warning: **readability\-else\-after\-return** :warning: do not use `` else `` after `` return `` ```suggestion return true ```
const Army enemy( tile );
return army.isStrongerThan( enemy, AI::ARMY_STRENGTH_ADVANTAGE_LARGE );
}
+
+ return true;
}
break;
|
codereview_cpp_data_8376
|
struct _RpmostreedTransactionPrivate {
GDBusMethodInvocation *invocation;
- gboolean active;
GCancellable *cancellable;
/* For the duration of the transaction, we hold a ref to a new
Bikeshed: maybe `done`, or `executed`, or `finished`? `active` could be misleading given that there are other things in this context that could be said to be "active".
struct _RpmostreedTransactionPrivate {
GDBusMethodInvocation *invocation;
+ gboolean executed; /* TRUE if the transaction has completed (successfully or not) */
GCancellable *cancellable;
/* For the duration of the transaction, we hold a ref to a new
|
codereview_cpp_data_8382
|
g_str_equal (group, "root"))
continue;
g_assert (fn != NULL);
fn += strspn (fn, "/");
g_assert (fn[0]);
Hmm, can we leave this and instead augment it with `S_ISLNK`? E.g. it's technically possible for the RPM to contain block devices, right? (And plus the unpacker uses `ignore_unsupported_content`).
g_str_equal (group, "root"))
continue;
+ /* In theory, RPMs could contain block devices or FIFOs; we would normally
+ * have rejected that at the import time, but let's also be sure here.
+ */
+ if (!(S_ISREG (mode) ||
+ S_ISLNK (mode) ||
+ S_ISDIR (mode)))
+ continue;
+
g_assert (fn != NULL);
fn += strspn (fn, "/");
g_assert (fn[0]);
|
codereview_cpp_data_8386
|
/* compile code (must be done for each thread) */
int arena = mrb_gc_arena_save(handler_ctx->mrb);
mrb_value proc = h2o_mruby_compile_code(handler_ctx->mrb, &handler->config, NULL);
- validate_proc(handler_ctx->mrb, proc);
handler_ctx->proc = mrb_funcall_argv(handler_ctx->mrb, mrb_ary_entry(handler_ctx->constants, H2O_MRUBY_PROC_APP_TO_FIBER),
handler_ctx->symbols.sym_call, 1, &proc);
Thank you for implementing the check in the way I suggested in our discussion. I am sorry to say this, but after reading this, I think we should better let the mruby script _set_ an optional callback for validating the Rack handler, instead of having a hard-coded check implemented in the C side. WDYT?
/* compile code (must be done for each thread) */
int arena = mrb_gc_arena_save(handler_ctx->mrb);
mrb_value proc = h2o_mruby_compile_code(handler_ctx->mrb, &handler->config, NULL);
handler_ctx->proc = mrb_funcall_argv(handler_ctx->mrb, mrb_ary_entry(handler_ctx->constants, H2O_MRUBY_PROC_APP_TO_FIBER),
handler_ctx->symbols.sym_call, 1, &proc);
|
codereview_cpp_data_8387
|
void MegaApiImpl::backupput_result(const Error& e, handle backupId)
{
- mHeartBeatMonitor->digestPutResult(backupId);
if (requestMap.find(client->restag) == requestMap.end()) return;
MegaRequestPrivate* request = requestMap.at(client->restag);
if (!request || (request->getType() != MegaRequest::TYPE_BACKUP_PUT)) return;
fireOnRequestFinish(request, make_unique<MegaErrorPrivate>(e));
}
Requests have to end (fireOnRequestFinish) even if they fail
void MegaApiImpl::backupput_result(const Error& e, handle backupId)
{
if (requestMap.find(client->restag) == requestMap.end()) return;
MegaRequestPrivate* request = requestMap.at(client->restag);
if (!request || (request->getType() != MegaRequest::TYPE_BACKUP_PUT)) return;
+ request->setBackupId(backupId);
+ mHeartBeatMonitor->digestPutResult(backupId);
fireOnRequestFinish(request, make_unique<MegaErrorPrivate>(e));
}
|
codereview_cpp_data_8390
|
return 0;
}
-bool Battle::Catapult::GetHitOrMiss() const
{
// Miss chance is 25%
return !( canMiss && Rand::Get( 1, 20 ) < 6 );
The name of the method is not very clear. What's about call it "IsNextShotHit"? Not an ideal one, of course.
return 0;
}
+bool Battle::Catapult::IsNextShotHit() const
{
// Miss chance is 25%
return !( canMiss && Rand::Get( 1, 20 ) < 6 );
|
codereview_cpp_data_8395
|
initResult = F(""); // Clear any previous result
// check model ID register (value specified in datasheet)
uint8_t modelId = readReg(IDENTIFICATION_MODEL_ID);
- if (!(modelId == 0xEE || modelId == 0xEA)) { // Recognize VL53L0X (0xEE) and VL53L1X (0xEA)
initResult = F("VL53L0X: Init: unrecognized Model-ID: 0x");
initResult += String(modelId, HEX);
return false;
Can't help it, but my brain keeps telling me: "Why not `(modelId != 0xEE && modelId != 0xEA)` ?" You don't need to change it, but it took me slightly longer to parse it in my head.
initResult = F(""); // Clear any previous result
// check model ID register (value specified in datasheet)
uint8_t modelId = readReg(IDENTIFICATION_MODEL_ID);
+ if (modelId != 0xEE && modelId != 0xEA) { // Recognize VL53L0X (0xEE) and VL53L1X (0xEA)
initResult = F("VL53L0X: Init: unrecognized Model-ID: 0x");
initResult += String(modelId, HEX);
return false;
|
codereview_cpp_data_8399
|
bool found = false;
- struct wlr_drm_format_set *dmabuf_formats[WLR_VK_IMAGE_USAGE_COUNT] = {
- [WLR_VK_IMAGE_USAGE_RENDER] = &dev->dmabuf_render_formats,
- [WLR_VK_IMAGE_USAGE_SAMPLED] = &dev->dmabuf_texture_formats,
- };
-
for (unsigned i = 0u; i < modp.drmFormatModifierCount; ++i) {
VkDrmFormatModifierPropertiesEXT m =
modp.pDrmFormatModifierProperties[i];
You never add to this format_set anymore more if I didn't miss anything. This seems like a problem.
bool found = false;
for (unsigned i = 0u; i < modp.drmFormatModifierCount; ++i) {
VkDrmFormatModifierPropertiesEXT m =
modp.pDrmFormatModifierProperties[i];
|
codereview_cpp_data_8408
|
text.Set( _( "Select town to port to." ), Font::BIG );
text.Blit( dst.x + 140 - text.w() / 2, dst.y + 25 );
- int32_t offsetY = 45;
- const fheroes2::Sprite & upperPart = fheroes2::AGG::GetICN( conf.ExtGameEvilInterface() ? ICN::LISTBOX_EVIL : ICN::LISTBOX, 0 );
- const fheroes2::Sprite & middlePart = fheroes2::AGG::GetICN( conf.ExtGameEvilInterface() ? ICN::LISTBOX_EVIL : ICN::LISTBOX, 1 );
- const fheroes2::Sprite & lowerPart = fheroes2::AGG::GetICN( conf.ExtGameEvilInterface() ? ICN::LISTBOX_EVIL : ICN::LISTBOX, 2 );
fheroes2::Blit( upperPart, display, dst.x + 2, dst.y + offsetY );
offsetY += upperPart.height();
Please cache `const int listId = conf.ExtGameEvilInterface() ? ICN::LISTBOX_EVIL : ICN::LISTBOX;`.
text.Set( _( "Select town to port to." ), Font::BIG );
text.Blit( dst.x + 140 - text.w() / 2, dst.y + 25 );
+ const int listId = isEvilInterface ? ICN::LISTBOX_EVIL : ICN::LISTBOX;
+ const fheroes2::Sprite & upperPart = fheroes2::AGG::GetICN( listId, 0 );
+ const fheroes2::Sprite & middlePart = fheroes2::AGG::GetICN( listId, 1 );
+ const fheroes2::Sprite & lowerPart = fheroes2::AGG::GetICN( listId, 2 );
+ int32_t offsetY = 45;
fheroes2::Blit( upperPart, display, dst.x + 2, dst.y + offsetY );
offsetY += upperPart.height();
|
codereview_cpp_data_8414
|
QFile f(fileName);
if (f.open(IO_WriteOnly))
{
- QCString htmlFileExtension=Config_getString(HTML_FILE_EXTENSION);
- htmlFileExtension=htmlFileExtension.stripWhiteSpace();
- if (htmlFileExtension.isEmpty())
- {
- htmlFileExtension = ".html";
- }
-
FTextStream t(&f);
t << substituteHtmlKeywords(g_header,"Search","");
I don't think this correction of the extension is necessary as in `configimpl.l` we see: ``` // check & correct HTML_FILE_EXTENSION QCString htmlFileExtension=Config_getString(HTML_FILE_EXTENSION); htmlFileExtension=htmlFileExtension.stripWhiteSpace(); if (htmlFileExtension.isEmpty()) { htmlFileExtension = ".html"; } Config_updateString(HTML_FILE_EXTENSION,htmlFileExtension); ``` so the correction is done and and the corrected value is placed back in `HTML_FILE_EXTENSION` so that subsequent calls to `Config_getString(HTML_FILE_EXTENSION)` directly return the corrected value. I think you can even use: `Doxygen::htmlFileExtension`.
QFile f(fileName);
if (f.open(IO_WriteOnly))
{
FTextStream t(&f);
t << substituteHtmlKeywords(g_header,"Search","");
|
codereview_cpp_data_8416
|
//#include <boost/multiprecision/cpp_int.hpp>
// using namespace boost::multiprecision;
const int mx = 1e6 + 5;
-typedef int64_t ll;
std::array<ll, mx> parent;
ll node, edge;
```suggestion using ll = int64_t; ```
//#include <boost/multiprecision/cpp_int.hpp>
// using namespace boost::multiprecision;
const int mx = 1e6 + 5;
+using ll = int64_t;
std::array<ll, mx> parent;
ll node, edge;
|
codereview_cpp_data_8421
|
transfer->setLastError(megaError);
transfer->setPriority(tr->priority);
transfer->setState(MegaTransfer::STATE_RETRYING);
-
- if (e == API_EOVERQUOTA)
- {
- unique_ptr<MegaNode> targetNode(getNodeByHandle(tr->target));
- unique_ptr<MegaNode> targetRootNode(getRootNode(targetNode.get()));
- unique_ptr<MegaNode> ownRootNode(getRootNode());
- bool foreignOverquota = (ownRootNode->getHandle() != targetRootNode->getHandle()) ? true : false;
- transfer->setForeignOverquota(foreignOverquota);
- }
-
fireOnTransferTemporaryError(transfer, megaError);
}
In order to avoid a deleted node for storage overquota error, it would be better to store the `mForeignTarget` at the `Trasfer`, instead of the nodehandle, which requires lookups.
transfer->setLastError(megaError);
transfer->setPriority(tr->priority);
transfer->setState(MegaTransfer::STATE_RETRYING);
+ transfer->setStreamingTransfer(tr->foreignTarget);
fireOnTransferTemporaryError(transfer, megaError);
}
|
codereview_cpp_data_8427
|
CheckCursMove();
track_process();
}
- if (gbProcessPlayers) { //gbProcessPlayers is only set to false when Diablo dies, otherwise it's true
ProcessPlayers();
}
if (leveltype != DTYPE_TOWN) {
This should be moved to where `gbProcessPlayers` is defined.
CheckCursMove();
track_process();
}
+ if (gbProcessPlayers) {
ProcessPlayers();
}
if (leveltype != DTYPE_TOWN) {
|
codereview_cpp_data_8440
|
m_is_initialized = true;
// FIXME_OPENMPTARGET: Only fix the number of teams for NVIDIA architectures.
-#if defined(KOKKOS_ARCH_VOLTA70) || defined(KOKKOS_ARCH_PASCAL60)
#if defined(KOKKOS_COMPILER_CLANG) && (KOKKOS_COMPILER_CLANG >= 1300)
omp_set_num_teams(512);
#endif
What about `VOLTA72`, `TURING75`, `AMPERE80` and `AMPERE86`? We only want to set the number of teams for these two architectures or for all the architectures newer than Maxwell?
m_is_initialized = true;
// FIXME_OPENMPTARGET: Only fix the number of teams for NVIDIA architectures.
+#if defined(KOKKOS_ARCH_PASCAL60) || defined(KOKKOS_ARCH_PASCAL61) || \
+ defined(KOKKOS_ARCH_VOLTA) || defined(KOKKOS_ARCH_VOLTA70) || \
+ defined(KOKKOS_ARCH_VOLTA72) || defined(KOKKOS_ARCH_TURING75) || \
+ defined(KOKKOS_ARCH_AMPERE80) || defined(KOKKOS_ARCH_AMPERE86)
#if defined(KOKKOS_COMPILER_CLANG) && (KOKKOS_COMPILER_CLANG >= 1300)
omp_set_num_teams(512);
#endif
|
codereview_cpp_data_8467
|
return;
}
- msgtable[msgcnt] = e; // BUGFIX: this can cause an OOB
if (msgcnt < (BYTE)sizeof(msgtable))
msgcnt++;
```suggestion msgtable[msgcnt] = e; // BUGFIX: missing out-of-bounds check ```
return;
}
+ msgtable[msgcnt] = e; // BUGFIX: missing out-of-bounds check
if (msgcnt < (BYTE)sizeof(msgtable))
msgcnt++;
|
codereview_cpp_data_8473
|
/// Note that the template wrapper method should generally be used to have the correct return type,
void* BaseContext::getObject(const ClassInfo& /*class_info*/, SearchDirection /*dir*/) const
{
- serr << "calling unimplemented getObject method" << sendl;
return nullptr;
}
maybe good time to remove the serr ?
/// Note that the template wrapper method should generally be used to have the correct return type,
void* BaseContext::getObject(const ClassInfo& /*class_info*/, SearchDirection /*dir*/) const
{
+ msg_warning("calling unimplemented getObject method");
return nullptr;
}
|
codereview_cpp_data_8492
|
Kingdom::Kingdom()
: color( Color::NONE )
, lost_town_days( 0 )
, visited_tents_colors( 0 )
- , _lastBattleWinHeroID( 0 )
{
heroes_cond_loss.reserve( 4 );
}
:warning: **clang\-diagnostic\-reorder\-ctor** :warning: field `` visited_tents_colors `` will be initialized after field `` _lastBattleWinHeroID ``
Kingdom::Kingdom()
: color( Color::NONE )
+ , _lastBattleWinHeroID( 0 )
, lost_town_days( 0 )
, visited_tents_colors( 0 )
{
heroes_cond_loss.reserve( 4 );
}
|
codereview_cpp_data_8495
|
qos_.m_reliability.kind = RELIABLE_RELIABILITY_QOS;
topic_.topicKind = NO_KEY;
topic_.topicDataType = "HelloWorld";
- topic_.topicName = "HelloWorldTopic";
return true;
}
When running the example, I get some error messages from the subscriber: ``` 2019-09-25 09:51:23.096 [DYN_TYPES Error] Error building type. The current descriptor isn't consistent. -> Function build ``` although it seems that the messages are being received. Could you have a look? As a user it gives the impression that something went wrong. Edit: I haven't seen the error reported above again. But I do see that the subscriber says "Message 24 RECEIVED" five times, is this the expected behaviour?
qos_.m_reliability.kind = RELIABLE_RELIABILITY_QOS;
topic_.topicKind = NO_KEY;
topic_.topicDataType = "HelloWorld";
+ topic_.topicName = "DDSDynHelloWorldTopic";
return true;
}
|
codereview_cpp_data_8507
|
ksRewind (result);
return result;
}
- ksAppendKey (result, (Key *)meta);
Key * currentKey = keyDup (meta);
keyAddName (currentKey, "#");
elektraArrayIncName (currentKey);
Key * curMeta = NULL;
while ((curMeta = (Key *)keyGetMeta (key, keyName (currentKey))) != NULL)
{
- ksAppendKey (result, curMeta);
elektraArrayIncName (currentKey);
}
keyDel (currentKey);
its a dangerous operation, why not keyDup?
ksRewind (result);
return result;
}
+ ksAppendKey (result, keyDup (meta));
Key * currentKey = keyDup (meta);
keyAddName (currentKey, "#");
elektraArrayIncName (currentKey);
Key * curMeta = NULL;
while ((curMeta = (Key *)keyGetMeta (key, keyName (currentKey))) != NULL)
{
+ ksAppendKey (result, keyDup (curMeta));
elektraArrayIncName (currentKey);
}
keyDel (currentKey);
|
codereview_cpp_data_8532
|
flow make_##protocol##_flow(std::string_view orig_h, uint16_t orig_p, \
std::string_view resp_h, uint16_t resp_p) { \
constexpr auto proto = port::port_type::protocol; \
- auto x = make_flow<proto>(orig_h, orig_p, resp_h, resp_p); \
- REQUIRE(x); \
- return *x; \
}
FLOW_FACTORY(icmp)
```suggestion return unbox(make_flow<proto>(orig_h, orig_p, resp_h, resp_p)); ```
flow make_##protocol##_flow(std::string_view orig_h, uint16_t orig_p, \
std::string_view resp_h, uint16_t resp_p) { \
constexpr auto proto = port::port_type::protocol; \
+ return unbox(make_flow<proto>(orig_h, orig_p, resp_h, resp_p)); \
}
FLOW_FACTORY(icmp)
|
codereview_cpp_data_8535
|
Real64 const c = -2.40977632412045e-8;
if (T < LowerLimit) {
- ShowWarningMessage("Air temperature out of limits for conductivity calculation");
T = LowerLimit;
} else if (T > UpperLimit) {
- ShowWarningMessage("Air temperature out of limits for conductivity calculation");
T = UpperLimit;
}
I know this is not your change. I prefer to revise a warning message slightly to add either lower or Upper limit with number. ShowWarningMessage("Air temperature out of lower limit of -20C for conductivity calculation");
Real64 const c = -2.40977632412045e-8;
if (T < LowerLimit) {
+ ShowWarningMessage("Air temperature below lower limit of -20C for conductivity calculation");
T = LowerLimit;
} else if (T > UpperLimit) {
+ ShowWarningMessage("Air temperature above upper limit of 70C for conductivity calculation");
T = UpperLimit;
}
|
codereview_cpp_data_8537
|
const QString output = args[1].trimmed();
bool ok = false;
- long maxNodes = args[2].toLong(&ok);
if (!ok || maxNodes < 1)
{
throw HootException("Invalid maximum node count: " + args[2]);
This is passed into a function below as an integer, it should just be read from the command line as an integer. ``` const int maxNodes = args[2].toInt(&ok); ```
const QString output = args[1].trimmed();
bool ok = false;
+ const int maxNodes = args[2].toInt(&ok);
if (!ok || maxNodes < 1)
{
throw HootException("Invalid maximum node count: " + args[2]);
|
codereview_cpp_data_8561
|
if (request->getType() == MegaRequest::TYPE_FETCH_NODES)
{
-#ifdef ENABLE_SYNC
- const bool resumeSyncs = request->getFlag();
- // resetting to default in case it was set by fetchNodes()
- request->setFlag(false);
-#endif
-
if (e == API_OK)
{
// check if we fetched a folder link and the key is invalid
Same than above, do not overwrite an already in use parameter. Better to use another one
if (request->getType() == MegaRequest::TYPE_FETCH_NODES)
{
if (e == API_OK)
{
// check if we fetched a folder link and the key is invalid
|
codereview_cpp_data_8566
|
TEST(suricata) {
using reader_type = format::json::reader<format::json::suricata>;
- reader_type reader{defaults::system::table_slice_type,
- std::make_unique<std::istringstream>(
- std::string{eve_log})};
std::vector<table_slice_ptr> slices;
auto add_slice = [&](table_slice_ptr ptr) {
slices.emplace_back(std::move(ptr));
You could factor the `make_unique` call in a separate line for improved readability.
TEST(suricata) {
using reader_type = format::json::reader<format::json::suricata>;
+ auto input = std::make_unique<std::istringstream>(std::string{eve_log});
+ reader_type reader{defaults::system::table_slice_type, std::move(input)};
std::vector<table_slice_ptr> slices;
auto add_slice = [&](table_slice_ptr ptr) {
slices.emplace_back(std::move(ptr));
|
codereview_cpp_data_8567
|
// castle name
text.set( castle.GetName(), smallWhiteFont );
dst_pt.x = cur_rt.x + ( cur_rt.width - text.width() ) / 2;
- dst_pt.y = cur_rt.y + 2;
text.draw( dst_pt.x, dst_pt.y, display );
// castle icon
Please remove this line and declare **text** at line 692 instead of **set** call.
// castle name
text.set( castle.GetName(), smallWhiteFont );
dst_pt.x = cur_rt.x + ( cur_rt.width - text.width() ) / 2;
+ dst_pt.y = cur_rt.y + 3;
text.draw( dst_pt.x, dst_pt.y, display );
// castle icon
|
codereview_cpp_data_8568
|
#include <iostream>
-#define n 9
-bool isPossible(int mat[][9], int i, int j, int no) {
/// Row or col nahin hona chahiye
for (int x = 0; x < n; x++) {
if (mat[x][j] == no || mat[i][x] == no) {
haha.. nice trick to replace ambiguous global variables with macro. but not a good idea either.
#include <iostream>
+bool isPossible(int &mat[][9], int i, int j, int no, int n) {
/// Row or col nahin hona chahiye
for (int x = 0; x < n; x++) {
if (mat[x][j] == no || mat[i][x] == no) {
|
codereview_cpp_data_8579
|
walk = &((*walk)->nextNameObject);
}
#else
- const char* name = StringTable->insert(obj->objectName);
- if (root[name])
root.erase(name);
#endif
Mutex::unlockMutex(mutex);
This create a default contructed entry on `unordered_map` adding innecesary data to map. Better to use `find`
walk = &((*walk)->nextNameObject);
}
#else
+ const char* name = obj->objectName;
+ if (root.find(name) != root.end())
root.erase(name);
#endif
Mutex::unlockMutex(mutex);
|
codereview_cpp_data_8586
|
++m_current_step;
do_batch_end_cbs(execution_mode::training);
- if(num_batches && m_current_step % num_batches == 0) return true;
-
return finished;
}
I don't like that the model doesn't train for `num_batches` when `m_current_step` is not initially a multiple of `num_batches`.
++m_current_step;
do_batch_end_cbs(execution_mode::training);
return finished;
}
|
codereview_cpp_data_8592
|
struct s2n_connection *conn;
EXPECT_NOT_NULL(conn = s2n_connection_new(S2N_SERVER));
s2n_extension_type_id extension_id = 0;
- EXPECT_SUCCESS(s2n_extension_supported_iana_value_to_id(TLS_EXTENSION_KEY_SHARE, &extension_id));
- S2N_CBIT_SET(conn->extension_requests_received, extension_id);
- EXPECT_SUCCESS(s2n_extension_supported_iana_value_to_id(TLS_EXTENSION_SUPPORTED_VERSIONS, &extension_id));
- S2N_CBIT_SET(conn->extension_requests_received, extension_id);
EXPECT_SUCCESS(s2n_extension_supported_iana_value_to_id(TLS_EXTENSION_SESSION_TICKET, &extension_id));
S2N_CBIT_SET(conn->extension_requests_received, extension_id);
EXPECT_SUCCESS(s2n_connection_set_config(conn, config));
If you're going to change this, why not only turn on the session ticket extension and update the expected size? That seems more in line with what the test wants to do. Same for the other tests that are trying to test a single extension.
struct s2n_connection *conn;
EXPECT_NOT_NULL(conn = s2n_connection_new(S2N_SERVER));
s2n_extension_type_id extension_id = 0;
EXPECT_SUCCESS(s2n_extension_supported_iana_value_to_id(TLS_EXTENSION_SESSION_TICKET, &extension_id));
S2N_CBIT_SET(conn->extension_requests_received, extension_id);
EXPECT_SUCCESS(s2n_connection_set_config(conn, config));
|
codereview_cpp_data_8602
|
return icn_cache[icn].count;
}
-int AGG::GetMaxICNOffset( int icn )
{
int result = 0;
It is a very tricky function. Please try it on Phoenix or Cyclops for example. The height of their Sprites is huge. The proper way to calculate maximum offset is to use static frame height.
return icn_cache[icn].count;
}
+// return height of the biggest frame in specific ICN
+int AGG::GetAbsoluteICNHeight( int icn )
{
int result = 0;
|
codereview_cpp_data_8615
|
return ret;
}
-void OpenSimContext::setLocation(AbstractPathPoint& mp, int i, double d) {
- PathPoint* spp = dynamic_cast<PathPoint*>(&mp);
- if (spp) {
- spp->setLocationCoord(*_configState, i, d);
- _configState->invalidateAll(SimTK::Stage::Position);
- _model->getMultibodySystem().realize(*_configState, SimTK::Stage::Position);
- }
}
void OpenSimContext::setEndPoint(PathWrap& mw, int newEndPt) {
I suggest throwing an exception in an `else` block here. Two classes derive from AbstractPathPoint: MovingPathPoint and PathPoint. If this method is called on a MovingPathPoint, that's a mistake and I think an exception should be thrown rather than quietly doing nothing.
return ret;
}
+void OpenSimContext::setLocation(PathPoint& mp, int i, double d) {
+ mp.setLocationCoord(*_configState, i, d);
+ _configState->invalidateAll(SimTK::Stage::Position);
+ _model->getMultibodySystem().realize(*_configState, SimTK::Stage::Position);
}
void OpenSimContext::setEndPoint(PathWrap& mw, int newEndPt) {
|
codereview_cpp_data_8616
|
#else // When USE_APPIMAGE_UPDATER_BRIDGE is defined
// USE_APPIMAGE_UPDATER_BRIDGE implies that we are on a linux machine
// so we are going to assume that.
-
m_UpdaterDialog = nullptr;
m_Revisioner = new AppImageDeltaRevisioner(/*singleThreaded=*/true,/*parent=*/this);
Is this enforced somewhere? Aka does the build system throw an error if I define `USE_APPIMAGE_UPDATER_BRIDGE` on another OS than Linux, will it throw an error?
#else // When USE_APPIMAGE_UPDATER_BRIDGE is defined
// USE_APPIMAGE_UPDATER_BRIDGE implies that we are on a linux machine
// so we are going to assume that.
+ Q_UNUSED(focus)
m_UpdaterDialog = nullptr;
m_Revisioner = new AppImageDeltaRevisioner(/*singleThreaded=*/true,/*parent=*/this);
|
codereview_cpp_data_8618
|
while (next && next->playback_short)
next = playlist_entry_get_rel(next, -1);
// Always allow jumping to first file
- if (!next && mpctx->opts->loop_times == 1){
next = playlist_get_first(mpctx->playlist);
while (next && next->playback_short)
- next = playlist_entry_get_rel(next, 1);
}
}
if (!next && mpctx->opts->loop_times != 1) {
a missing space
while (next && next->playback_short)
next = playlist_entry_get_rel(next, -1);
// Always allow jumping to first file
+ if (!next && mpctx->opts->loop_times == 1) {
next = playlist_get_first(mpctx->playlist);
while (next && next->playback_short)
+ next = playlist_entry_get_rel(next, -1);
}
}
if (!next && mpctx->opts->loop_times != 1) {
|
codereview_cpp_data_8619
|
return *this;
}
-void IO::CwdChanger::reset() {
chDir(_existingDir);
_existingDir.clear();
}
-void IO::CwdChanger::release() noexcept {
_existingDir.clear();
}
My understanding of the use case of this class is that we'll bake the change/restore in the construction/destruction, why do we need move and reset is a bit surprising but may become clear from the rest of the changes. Could we do without these?
return *this;
}
+void IO::CwdChanger::restore() {
chDir(_existingDir);
_existingDir.clear();
}
+void IO::CwdChanger::stay() noexcept {
_existingDir.clear();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.