id
stringlengths 21
25
| content
stringlengths 164
2.33k
|
|---|---|
codereview_cpp_data_1359
|
dofs->resize(nbrDofs);
/// Add PointSetTopology
- typename sofa::component::topology::PointSetTopologyContainer::SPtr tCon = sofa::core::objectmodel::New<sofa::component::topology::PointSetTopologyContainer>();
- typename sofa::component::topology::PointSetTopologyModifier::SPtr tMod = sofa::core::objectmodel::New<sofa::component::topology::PointSetTopologyModifier>();
tCon->setNbPoints(nbrDofs);
node->addObject(tCon);
node->addObject(tMod);
Is it possible to write `Deriv force = { 10 };` ?
dofs->resize(nbrDofs);
/// Add PointSetTopology
+ auto tCon = sofa::core::objectmodel::New<sofa::component::topology::PointSetTopologyContainer>();
+ auto tMod = sofa::core::objectmodel::New<sofa::component::topology::PointSetTopologyModifier>();
tCon->setNbPoints(nbrDofs);
node->addObject(tCon);
node->addObject(tMod);
|
codereview_cpp_data_1360
|
}
if(elektraMountGlobals(handle, ksDup(keys), handle->modules, errorKey) == -1)
{
- //TODO: errorhandling here
#if DEBUG && VERBOSE
printf("Mounting global plugins failed\n");
#endif
Yes, should be done!
}
if(elektraMountGlobals(handle, ksDup(keys), handle->modules, errorKey) == -1)
{
#if DEBUG && VERBOSE
printf("Mounting global plugins failed\n");
#endif
|
codereview_cpp_data_1383
|
//----------------------------------------------------------------------------
__device__
void verify_warp_convergence( const char * const where )
{
This function can go into `#ifdef KOKKOS_DEBUG`
//----------------------------------------------------------------------------
+#if defined( KOKKOS_DEBUG )
+
__device__
void verify_warp_convergence( const char * const where )
{
|
codereview_cpp_data_1388
|
// Check if the best chain has changed while we were disconnecting or processing blocks.
// If so then we need to return and continue processing the newer chain.
pindexNewMostWork = FindMostWorkChain();
if (pindexNewMostWork->nChainWork > pindexMostWork->nChainWork)
{
LogPrint("parallel", "Returning because chain work has changed while connecting blocks\n");
FindMostWorkChain() can return NULL
// Check if the best chain has changed while we were disconnecting or processing blocks.
// If so then we need to return and continue processing the newer chain.
pindexNewMostWork = FindMostWorkChain();
+ if (!pindexMostWork)
+ return false;
+
if (pindexNewMostWork->nChainWork > pindexMostWork->nChainWork)
{
LogPrint("parallel", "Returning because chain work has changed while connecting blocks\n");
|
codereview_cpp_data_1400
|
{
QPixmap resizedPixmap = avatarPixmap.scaled(avatarLabel.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
avatarLabel.setPixmap(resizedPixmap);
- resize(sizeHint());
QWidget::resizeEvent(event);
}
resizing the window will result in an infinite recursion now....
{
QPixmap resizedPixmap = avatarPixmap.scaled(avatarLabel.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
avatarLabel.setPixmap(resizedPixmap);
QWidget::resizeEvent(event);
}
|
codereview_cpp_data_1404
|
/* grep keys */
if (obj->type == MSGPACK_OBJECT_MAP) {
map_num = obj->via.map.size;
/* allocate map_num + guard byte */
bool_map = flb_calloc(map_num+1, sizeof(bool_map_t));
if (bool_map == NULL) {
I think we should have a limit, what do you think ?
/* grep keys */
if (obj->type == MSGPACK_OBJECT_MAP) {
map_num = obj->via.map.size;
+ if (map_num > BOOL_MAP_LIMIT) {
+ flb_plg_error(ctx->ins, "The number of elements exceeds limit %d",
+ BOOL_MAP_LIMIT);
+ return -1;
+ }
/* allocate map_num + guard byte */
bool_map = flb_calloc(map_num+1, sizeof(bool_map_t));
if (bool_map == NULL) {
|
codereview_cpp_data_1411
|
if (!ofs)
throw std::runtime_error(UNABLE_TO_OPEN_FILE);
ofs << design.Dump();
} catch (const std::exception& e) {
ErrorLogger() << "Error writing design file. Exception: " << ": " << e.what();
Seems like there should be some sent to InfoLogger when the design write succeeds, and possibly also to the messages window...
if (!ofs)
throw std::runtime_error(UNABLE_TO_OPEN_FILE);
ofs << design.Dump();
+ TraceLogger() << "Wrote ship design to " << PathString(file);
} catch (const std::exception& e) {
ErrorLogger() << "Error writing design file. Exception: " << ": " << e.what();
|
codereview_cpp_data_1412
|
{
struct rp_handler_t *self = (void *)_self;
- if (self->config.ssl_ctx != NULL)
- SSL_CTX_free(self->config.ssl_ctx);
h2o_socketpool_dispose(&self->sockpool);
}
void h2o_proxy_register_reverse_proxy(h2o_pathconf_t *pathconf, h2o_url_t *upstreams, size_t num_upstreams,
- h2o_proxy_config_vars_t *config, void **lb_per_target_conf)
{
assert(num_upstreams != 0);
To me having many arguments that configures the socket pool (i.e., `upstreams`, `config->lb`, `lb_per_target_conf`) seems like a yellow signal. Could we reduce the complexity by generating the socket pool in the configurator and passing it as an argument to `h2o_proxy_register_reverse_proxy`?
{
struct rp_handler_t *self = (void *)_self;
h2o_socketpool_dispose(&self->sockpool);
}
void h2o_proxy_register_reverse_proxy(h2o_pathconf_t *pathconf, h2o_url_t *upstreams, size_t num_upstreams,
+ uint64_t keepalive_timeout, SSL_CTX *ssl_ctx, h2o_proxy_config_vars_t *config,
+ void **lb_per_target_conf)
{
assert(num_upstreams != 0);
|
codereview_cpp_data_1417
|
{
void GetSummaryParams(int res1, int res2, const HeroBase &, u32 exp, int &, std::string &);
void SpeedRedraw(const Point &);
- void doOnButtonClicked(ButtonWithText& button, Display & display, Cursor& cursor);
- void initButtonState(bool state, ButtonWithText& button);
}
void Battle::SpeedRedraw(const Point & dst)
Please swap input parameters to be consistent.
{
void GetSummaryParams(int res1, int res2, const HeroBase &, u32 exp, int &, std::string &);
void SpeedRedraw(const Point &);
+ void DoOnButtonClicked(LabeledButton& button, Display & display, Cursor& cursor);
+ void InitButtonState(LabeledButton& button, bool state);
}
void Battle::SpeedRedraw(const Point & dst)
|
codereview_cpp_data_1421
|
#include <stdio.h>
#include <sys/stat.h>
#include <iostream>
-#include <nonstd/optional.hpp>
std::string id_to_name(uint32_t id) {
std::string new_id(16, '\0');
Can it be `nonstd::optional`?
#include <stdio.h>
#include <sys/stat.h>
#include <iostream>
std::string id_to_name(uint32_t id) {
std::string new_id(16, '\0');
|
codereview_cpp_data_1424
|
ret = prepare_destroy_conn(u_conn);
- if (u->thread_safe == FLB_TRUE && locked) {
pthread_mutex_unlock(&u->mutex_lists);
}
`locked` is only assigned if `u->thread_safe` is `FLB_TRUE` so in the unlock section we could just do `if (locked) {`
ret = prepare_destroy_conn(u_conn);
+ if (locked) {
pthread_mutex_unlock(&u->mutex_lists);
}
|
codereview_cpp_data_1436
|
convertOps.setProgress(
Progress(
ConfigOptions().getJobId(), JOB_SOURCE, Progress::JobState::Running,
- (_currentTaskNum - 1) / _numTotalTasks, 1.0 / _numTotalTasks));
convertOps.apply(fullMap);
// get back into wgs84 in case some op changed the proj
MapProjector::projectToWgs84(fullMap);
The problem that is flagged here is that `1.0` is actually a `double` and not a `float`. The correct way to fix this is to do the following: ``` (float)(_currentTaskNum - 1) / (float)_numTotalTasks, 1.0f / (float)_numTotalTasks)); ```
convertOps.setProgress(
Progress(
ConfigOptions().getJobId(), JOB_SOURCE, Progress::JobState::Running,
+ (float)(_currentTaskNum - 1) / (float)_numTotalTasks, 1.0f / (float)_numTotalTasks));
+
convertOps.apply(fullMap);
// get back into wgs84 in case some op changed the proj
MapProjector::projectToWgs84(fullMap);
|
codereview_cpp_data_1448
|
soci::session sql(*connection_);
// rollback current prepared transaction
// if there exists any since last session
- rollbackPrepared(sql);
sql << init_;
prepareStatements(*connection_, pool_size_);
}
```suggestion if (prepared_blocks_enabled_) rollbackPrepared(sql); ``` or add this conditional to `rollbackPrepared`.
soci::session sql(*connection_);
// rollback current prepared transaction
// if there exists any since last session
+ if (prepared_blocks_enabled_) {
+ rollbackPrepared(sql);
+ }
sql << init_;
prepareStatements(*connection_, pool_size_);
}
|
codereview_cpp_data_1454
|
/* UDP multicast network layer specific internal data */
typedef struct {
int ai_family; /* Protocol family for socket. IPv4/IPv6 */
- struct sockaddr_storage *ai_addr; /* https://msdn.microsoft.com/de-de/library/windows/desktop/ms740496(v=vs.85).aspx */
- struct sockaddr_storage *intf_addr;
UA_UInt32 messageTTL;
UA_Boolean enableLoopback;
UA_Boolean enableReuse;
I would prefer if both `sockaddr_storage` were not pointers but direct members. That removes a lot of the allocation and cleanup logic.
/* UDP multicast network layer specific internal data */
typedef struct {
int ai_family; /* Protocol family for socket. IPv4/IPv6 */
+ struct sockaddr_storage ai_addr; /* https://msdn.microsoft.com/de-de/library/windows/desktop/ms740496(v=vs.85).aspx */
+ struct sockaddr_storage intf_addr;
UA_UInt32 messageTTL;
UA_Boolean enableLoopback;
UA_Boolean enableReuse;
|
codereview_cpp_data_1458
|
core::CollisionModel* model1 = outputsIt->first.first;
core::CollisionModel* model2 = outputsIt->first.second;
- msg_error_when(model1 == nullptr) << "Contact found with a nullptr collision model";
- msg_error_when(model2 == nullptr) << "Contact found with a nullptr collision model";
std::string responseUsed = getContactResponse(model1, model2);
Too me, an error message usually tagets users, not developers. How can a collision model be null? Can this be avoided by the user setting things differently in its sene? Or does it only happen when another component malfunction?
core::CollisionModel* model1 = outputsIt->first.first;
core::CollisionModel* model2 = outputsIt->first.second;
+ dmsg_error_when(model1 == nullptr || model2 == nullptr) << "Contact found with an invalid collision model";
std::string responseUsed = getContactResponse(model1, model2);
|
codereview_cpp_data_1472
|
!sep->IsNumber(3)
) {
c->Message(Chat::White, "Usage: #zsafecoords [X] [Y] [Z] [Heading] [Permanent (0 = False, 1 = True)]");
return;
}
Did you want to show defaults here?
!sep->IsNumber(3)
) {
c->Message(Chat::White, "Usage: #zsafecoords [X] [Y] [Z] [Heading] [Permanent (0 = False, 1 = True)]");
+ c->Message(Chat::White, "Not sending Heading defaults to current Heading and the change is temporary.");
return;
}
|
codereview_cpp_data_1484
|
bool isApplicable = highlightCell->isPassable1( false );
if ( isApplicable ) {
const Unit * highlightedUnit = highlightCell->GetUnit();
- if ( highlightedUnit != nullptr ) {
- isApplicable = !( highlightedUnit->GetMagicResist( humanturn_spell, spellPower ) < 100 && highlightedUnit->Modes( SP_ANTIMAGIC )
- && humanturn_spell.isValid() );
- }
}
if ( isApplicable ) {
This is not exactly a correct way to fix the problem. We need to move the check for Anti Magic mode in `GetMagicResist` method and remove the check in `Battle::Unit::AllowApplySpell` method since it internally calls `GetMagicResist`. Also here we need to call `isMagicResist` instead to simplify reading.
bool isApplicable = highlightCell->isPassable1( false );
if ( isApplicable ) {
const Unit * highlightedUnit = highlightCell->GetUnit();
+ isApplicable = highlightedUnit == nullptr || !highlightedUnit->isMagicResist( humanturn_spell, spellPower );
}
if ( isApplicable ) {
|
codereview_cpp_data_1487
|
* @param informationKey contains the statistics in its meta information
* @param metaName which statistic to set
* @param value which value to set it to, must be a number
- * @returns 0 on success, 1 otherwise.
*
* This enforces that a number is set.
*/
You can use retval here.
* @param informationKey contains the statistics in its meta information
* @param metaName which statistic to set
* @param value which value to set it to, must be a number
+ * @retval 0 on success, 1 otherwise.
*
* This enforces that a number is set.
*/
|
codereview_cpp_data_1493
|
#include <ctime> // clock(), clock_t, CLOCKS_PER_SEC
#include <OpenSim/Simulation/osimSimulation.h>
#include <OpenSim/Analyses/osimAnalyses.h>
#include <OpenSim/Auxiliary/auxiliaryTestFunctions.h>
using namespace OpenSim;
A user won't run into this issue?
#include <ctime> // clock(), clock_t, CLOCKS_PER_SEC
#include <OpenSim/Simulation/osimSimulation.h>
#include <OpenSim/Analyses/osimAnalyses.h>
+#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Auxiliary/auxiliaryTestFunctions.h>
using namespace OpenSim;
|
codereview_cpp_data_1511
|
const char* megaFolderLink = request->getLink();
const char* base64pwkey = request->getPrivateKey();
const char* sessionKey = request->getSessionKey();
- const char* folderAuthKey = request->getSessionKey();
if (!megaFolderLink && (!(login && password)) && !sessionKey && (!(login && base64pwkey)))
{
Unused variable :thinking:
const char* megaFolderLink = request->getLink();
const char* base64pwkey = request->getPrivateKey();
const char* sessionKey = request->getSessionKey();
if (!megaFolderLink && (!(login && password)) && !sessionKey && (!(login && base64pwkey)))
{
|
codereview_cpp_data_1522
|
m_aStdColNameOrder->Insert(_("Progress"), COLUMN_PROGRESS);
m_aStdColNameOrder->Insert(_("Status"), COLUMN_STATUS);
m_aStdColNameOrder->Insert(_("Elapsed"), COLUMN_CPUTIME);
- m_aStdColNameOrder->Insert(_("Remaining"), COLUMN_TOCOMPLETION);
m_aStdColNameOrder->Insert(_("Estimated Completion"), COLUMN_ESTIMATEDCOMPLETION);
m_aStdColNameOrder->Insert(_("Deadline"), COLUMN_REPORTDEADLINE);
m_aStdColNameOrder->Insert(_("Application"), COLUMN_APPLICATION);
This time is stil estimated, and could not be not accurate.
m_aStdColNameOrder->Insert(_("Progress"), COLUMN_PROGRESS);
m_aStdColNameOrder->Insert(_("Status"), COLUMN_STATUS);
m_aStdColNameOrder->Insert(_("Elapsed"), COLUMN_CPUTIME);
+ m_aStdColNameOrder->Insert(_("Remaining (estimated)"), COLUMN_TOCOMPLETION);
m_aStdColNameOrder->Insert(_("Estimated Completion"), COLUMN_ESTIMATEDCOMPLETION);
m_aStdColNameOrder->Insert(_("Deadline"), COLUMN_REPORTDEADLINE);
m_aStdColNameOrder->Insert(_("Application"), COLUMN_APPLICATION);
|
codereview_cpp_data_1525
|
#if defined(__has_builtin)
# if __has_builtin(__builtin_add_overflow) && !defined(__ibmxl__)
-# define HAVE_BUILTIN_OVERFLOW
# endif
#elif defined(__GNUC__) && (__GNUC__ >= 5) && (!defined(__INTEL_COMPILER) || (__INTEL_COMPILER >= 1800))
-# define HAVE_BUILTIN_OVERFLOW
#endif
#if defined(__GNUC__)
I think most macros like this start with `CYTHON_` (e.g. `CYTHON_HAVE_BUILTIN_OVERFLOW`), just to reduce the chances of conflicting with someone else's macro.
#if defined(__has_builtin)
# if __has_builtin(__builtin_add_overflow) && !defined(__ibmxl__)
+# define __PYX_HAVE_BUILTIN_OVERFLOW
# endif
#elif defined(__GNUC__) && (__GNUC__ >= 5) && (!defined(__INTEL_COMPILER) || (__INTEL_COMPILER >= 1800))
+# define __PYX_HAVE_BUILTIN_OVERFLOW
#endif
#if defined(__GNUC__)
|
codereview_cpp_data_1528
|
case BUILD_CAPTAIN:
return { 223, 122, 37, 52 };
case BUILD_MAGEGUILD1:
- return { 285, 32, 55, 129 };
case BUILD_MAGEGUILD2:
- return { 285, 32, 55, 129 };
case BUILD_MAGEGUILD3:
- return { 285, 32, 55, 129 };
case BUILD_MAGEGUILD4:
- return { 285, 32, 55, 129 };
case BUILD_MAGEGUILD5:
- return { 285, 32, 55, 129 };
case BUILD_TENT:
return { 104, 130, 59, 42 };
case DWELLING_MONSTER1:
:warning: **bugprone\-branch\-clone** :warning: switch has 5 consecutive identical branches
case BUILD_CAPTAIN:
return { 223, 122, 37, 52 };
case BUILD_MAGEGUILD1:
+ return { 280, 21, 60, 143 };
case BUILD_MAGEGUILD2:
case BUILD_MAGEGUILD3:
case BUILD_MAGEGUILD4:
case BUILD_MAGEGUILD5:
+ return { 280, 0, 60, 164 };
case BUILD_TENT:
return { 104, 130, 59, 42 };
case DWELLING_MONSTER1:
|
codereview_cpp_data_1547
|
}
}
- WHEN ("A required argument is added")
{
auto optional_int =
parser.add_argument(
```suggestion WHEN ("An optional argument is added") ```
}
}
+ WHEN ("An optional argument is added")
{
auto optional_int =
parser.add_argument(
|
codereview_cpp_data_1561
|
namespace lbann {
-void im2col(const AbsMat& im,
- AbsMat& col,
const int num_channels,
const int im_num_dims,
const int * im_dims,
I think im2col should only accommodate CPUMat.
namespace lbann {
+void im2col(const CPUMat& im,
+ CPUMat& col,
const int num_channels,
const int im_num_dims,
const int * im_dims,
|
codereview_cpp_data_1574
|
GetOptionsDB().Get<bool>("verbose-combat-logging");
m_wnd.DeleteChildren();
- GG::Layout* layout = new GG::DeferredLayout(m_wnd.UpperLeft().x, m_wnd.UpperLeft().y
- , m_wnd.Width(), m_wnd.Height()
- , 1, 1 ///< numrows, numcols
- , 0, 0 ///< wnd margin, cell margin
- );
m_wnd.SetLayout(layout);
int client_empire_id = HumanClientApp::GetApp()->EmpireID();
not from this PR, but the indenting here is odd
GetOptionsDB().Get<bool>("verbose-combat-logging");
m_wnd.DeleteChildren();
+ GG::Layout* layout = new GG::DeferredLayout(m_wnd.UpperLeft().x, m_wnd.UpperLeft().y,
+ m_wnd.Width(), m_wnd.Height(),
+ 1, 1, ///< numrows, numcols
+ 0, 0 ///< wnd margin, cell margin
+ );
m_wnd.SetLayout(layout);
int client_empire_id = HumanClientApp::GetApp()->EmpireID();
|
codereview_cpp_data_1583
|
void CachedStorage::restoreCache(TableInfo::Ptr table, const std::string& key, Cache::Ptr cache)
{
RWMutexScoped lockCache(m_cachesMutex, false);
auto cacheKey = table->name + "_" + key;
Why `tuple` still here ?
void CachedStorage::restoreCache(TableInfo::Ptr table, const std::string& key, Cache::Ptr cache)
{
+ /*
+ If the checkAndClear() run ahead of commit() at same key, commit() may flush data to the cache object which erased in m_caches, the data will lost, to avoid this, re-insert the data into the m_caches
+ */
+
RWMutexScoped lockCache(m_cachesMutex, false);
auto cacheKey = table->name + "_" + key;
|
codereview_cpp_data_1596
|
return num;
}
-void wlr_egl_destroy_surface(struct wlr_egl *egl, EGLSurface surface) {
- eglDestroySurface(egl->display, surface);
}
Could you add a NULL check on surface, and then remove the checks from the DRM backend?
return num;
}
+bool wlr_egl_destroy_surface(struct wlr_egl *egl, EGLSurface surface) {
+ if (!surface) {
+ return true;
+ }
+ return eglDestroySurface(egl->display, surface);
}
|
codereview_cpp_data_1624
|
ids select(const counts& xs, vast::count y, F pred) {
ids result;
for (auto x : xs)
- result.append_bits(pred(x, y), 1);
return result;
}
The single-argument function `append_bit` allows you to skip the second argument.
ids select(const counts& xs, vast::count y, F pred) {
ids result;
for (auto x : xs)
+ result.append_bit(pred(x, y));
return result;
}
|
codereview_cpp_data_1633
|
VAST_DEBUG(this, "ignores empty line at", lines_->line_number());
continue;
}
- if (!p(line))
- return make_error(ec::type_clash, "unable to parse CSV line", line);
++produced;
if (builder_->rows() == max_slice_size)
if (auto err = finish(callback))
For JSON, we skip over invalid lines. Can we do this for CSV as well?
VAST_DEBUG(this, "ignores empty line at", lines_->line_number());
continue;
}
+ ++num_lines_;
+ if (!p(line)) {
+ if (num_invalid_lines_ == 0)
+ VAST_WARNING(this, "failed to parse line", lines_->line_number(), ":",
+ line);
+ ++num_invalid_lines_;
+ continue;
+ }
++produced;
if (builder_->rows() == max_slice_size)
if (auto err = finish(callback))
|
codereview_cpp_data_1647
|
if(p) {
*p = 0;
if(!work_queue_task_specify_file(t, f, p + 1, WORK_QUEUE_INPUT, caching_flag)){
- exit(1);
}
*p = '=';
} else {
if(!work_queue_task_specify_file(t, f, f, WORK_QUEUE_INPUT, caching_flag)){
- exit(1);
}
}
f = strtok(0, " \t,");
We want a fatal message here.
if(p) {
*p = 0;
if(!work_queue_task_specify_file(t, f, p + 1, WORK_QUEUE_INPUT, caching_flag)){
+ fatal("Failed to specify file %s->%s in Work Queue", f, p+1);
}
*p = '=';
} else {
if(!work_queue_task_specify_file(t, f, f, WORK_QUEUE_INPUT, caching_flag)){
+ fatal("Failed to specify file %s in Work Queue", f);
}
}
f = strtok(0, " \t,");
|
codereview_cpp_data_1649
|
static NewSyncConfig from(const SyncConfig& config)
{
- auto type = SyncConfig::TYPE_TWOWAY;
- if (config.isUpSync() && !config.isDownSync())
- {
- type = SyncConfig::TYPE_UP;
- }
- else if (!config.isUpSync() && config.isDownSync())
- {
- type = SyncConfig::TYPE_DOWN;
- }
- return NewSyncConfig{type, config.syncDeletions(), config.forceOverwrite()};
}
};
Would it make sense to add `SyncConfig::Type SyncConfig::getType()`?? and avoid the if-else-if above, which I've already seen in other parts of the code. And perhaps a convenience method for `string SyncConfig::getTypeStr()` or similar, which could be used at `syncConfigToString()` and at other places in the code, probably. Just thinking loud :)
static NewSyncConfig from(const SyncConfig& config)
{
+ return NewSyncConfig{config.getType(), config.syncDeletions(), config.forceOverwrite()};
}
};
|
codereview_cpp_data_1661
|
// fix extra border part on higher resolutions
if ( displayHeight > fheroes2::Display::DEFAULT_HEIGHT ) {
srcrt.x = 478;
- srcrt.y = conf.ExtGameEvilInterface() ? 328 : 345;
srcrt.width = 3;
- srcrt.height = conf.ExtGameEvilInterface() ? 15 : 20;
dstpt.x += 14;
dstpt.y += 18;
fheroes2::Blit( icnadv, srcrt.x, srcrt.y, display, dstpt.x, dstpt.y, srcrt.width, srcrt.height );
Please cache the value of `ExtGameEvilInterface()` call as it's not an inline function. You could do something like this: ```cpp const bool isEvilInterface = conf.ExtGameEvilInterface(); ``` Please declare such variable before line 53.
// fix extra border part on higher resolutions
if ( displayHeight > fheroes2::Display::DEFAULT_HEIGHT ) {
srcrt.x = 478;
+ srcrt.y = isEvilInterface ? 328 : 345;
srcrt.width = 3;
+ srcrt.height = isEvilInterface ? 15 : 20;
dstpt.x += 14;
dstpt.y += 18;
fheroes2::Blit( icnadv, srcrt.x, srcrt.y, display, dstpt.x, dstpt.y, srcrt.width, srcrt.height );
|
codereview_cpp_data_1665
|
rank_in_world = std::to_string(comm->get_rank_in_world());
}
rng_name = dirname + "/rng_io_generator_" + rank_in_world;
std::ofstream rng_io(rng_name);
rng_io << ::io_generator;
rng_name = dirname + "/rng_fast_io_generator_" + rank_in_world;
std::ofstream rng_fast_io(rng_name);
rng_fast_io << ::fast_io_generator;
This will not work right, because it saves only the state for a single thread. I think we should raise a warning until it is fixed properly, since otherwise this will confuse people.
rank_in_world = std::to_string(comm->get_rank_in_world());
}
+ /// @todo - Note that the RNG with thread local data is not correct
rng_name = dirname + "/rng_io_generator_" + rank_in_world;
std::ofstream rng_io(rng_name);
rng_io << ::io_generator;
+ /// @todo - Note that the RNG with thread local data is not correct
rng_name = dirname + "/rng_fast_io_generator_" + rank_in_world;
std::ofstream rng_fast_io(rng_name);
rng_fast_io << ::fast_io_generator;
|
codereview_cpp_data_1675
|
}
void wlr_keyboard_destroy(struct wlr_keyboard *kb) {
- if (!kb) {
- return;
- }
-
- if (kb->impl && kb->impl->destroy) {
kb->impl->destroy(kb);
} else {
free(kb);
Better to update the if statement below to ```c if (kb && kb->impl && kb->impl->destroy) ``` imo
}
void wlr_keyboard_destroy(struct wlr_keyboard *kb) {
+ if (kb && kb->impl && kb->impl->destroy) {
kb->impl->destroy(kb);
} else {
free(kb);
|
codereview_cpp_data_1677
|
}
return emsActuator;
} else {
- LOG(Error, "ATTENTION: Actuated Object " + wsObject.nameString() + " does not reverse translate. ActuatedComponent is NOT set.");
openstudio::model::EnergyManagementSystemActuator emsActuator(m_model);
OptionalString s1 = workspaceObject.getString(EnergyManagementSystem_ActuatorFields::Name);
emsActuator.setName(*s1);
`getObjectsByTypeAndName` is faster lookup. `workspace.getObjectsByTypeAndName(openstudio::model::EnergyManagementSystemActuator::iddObjectType(), *s);`
}
return emsActuator;
} else {
+ LOG(Warn, "ATTENTION: Actuated Object " + wsObject.nameString() + " does not reverse translate. ActuatedComponent is NOT set.");
openstudio::model::EnergyManagementSystemActuator emsActuator(m_model);
OptionalString s1 = workspaceObject.getString(EnergyManagementSystem_ActuatorFields::Name);
emsActuator.setName(*s1);
|
codereview_cpp_data_1680
|
precision_(0),
multiprecision_repr_([this] {
static const std::regex r(
- "[1-9][0-9]*(\\.([0-9]+))?|0\\.([0-9]*[1-9])");
// 123.456 will have the following groups:
// [0] -> 123.456 [1] -> .456 [2] -> 456 [3] ->
//
The same regex pattern is repeated twice - not good, of something will change. Can't you reuse it from `FieldValidator::amount_pattern_`? Or maybe declare the way both classes would see and use it?
precision_(0),
multiprecision_repr_([this] {
static const std::regex r(
+ "[1-9][0-9]*(\\.([0-9]*[1-9]|0))?|0\\.([0-9]*[1-9])");
// 123.456 will have the following groups:
// [0] -> 123.456 [1] -> .456 [2] -> 456 [3] ->
//
|
codereview_cpp_data_1689
|
auto
checking_transaction =
[&command_validator](auto &tx, auto &executor, auto &query) {
for (auto command : tx.commands) {
executor.execute(*command);
if (!command_validator.validate(*command)) {
Should add a line that `// TODO permission validation`. Becouse permission validation needs tx.signatures.
auto
checking_transaction =
[&command_validator](auto &tx, auto &executor, auto &query) {
+ // TODO: Check permissions of tx to execute commands
for (auto command : tx.commands) {
executor.execute(*command);
if (!command_validator.validate(*command)) {
|
codereview_cpp_data_1701
|
}
}
- bool anydata = true;
- while (anydata)
{
- anydata = false;
for (int i = 0; i < connections; ++i)
{
// synchronous writes for all remaining outstanding data (for raid, there can be a sequence of output pieces. for non-raid, one piece per connection)
should be `anyData`
}
}
+ bool anyData = true;
+ while (anyData)
{
+ anyData = false;
for (int i = 0; i < connections; ++i)
{
// synchronous writes for all remaining outstanding data (for raid, there can be a sequence of output pieces. for non-raid, one piece per connection)
|
codereview_cpp_data_1703
|
dwellingTobuild = ( Race::NECR == race ? BUILD_SHRINE : BUILD_TAVERN );
return ConstructionDialogResult::Build;
}
- else if ( le.MouseCursor( buildingThievesGuild.GetArea() ) && buildingThievesGuild.QueueEventProcessing( buttonExit ) ) {
dwellingTobuild = BUILD_THIEVESGUILD;
return ConstructionDialogResult::Build;
}
:warning: **readability\-else\-after\-return** :warning: do not use `` else `` after `` return `` ```suggestion if ( le.MouseCursor( buildingThievesGuild.GetArea() ) && buildingThievesGuild.QueueEventProcessing( buttonExit ) ) { dwellingTobuild = BUILD_THIEVESGUILD; return ConstructionDialogResult::Build; } ```
dwellingTobuild = ( Race::NECR == race ? BUILD_SHRINE : BUILD_TAVERN );
return ConstructionDialogResult::Build;
}
+ if ( le.MouseCursor( buildingThievesGuild.GetArea() ) && buildingThievesGuild.QueueEventProcessing( buttonExit ) ) {
dwellingTobuild = BUILD_THIEVESGUILD;
return ConstructionDialogResult::Build;
}
|
codereview_cpp_data_1715
|
RESULT_ENSURE_LTE(digest_length, data_len);
- RESULT_CHECKED_MEMCPY(data, digest_data, data_len);
return S2N_RESULT_OK;
}
Should be `digest_length` otherwise by providing a large buffer the code will cause ub.
RESULT_ENSURE_LTE(digest_length, data_len);
+ RESULT_CHECKED_MEMCPY(data, digest_data, digest_length);
return S2N_RESULT_OK;
}
|
codereview_cpp_data_1716
|
pb.model());
model->setup(io_thread_pool);
- if(opts->has_bool("disable_background_io_activity") && opts->get_bool("disable_background_io_activity")) {
model->allow_background_io_activity(false);
}
You don't need has_bool(); The code was changed; instead of throwing an exception if the option doesn't exist, 'false' is returned. (other get_XX() methods still throw exceptions, since there's no reasonable default value)
pb.model());
model->setup(io_thread_pool);
+ if(opts->get_bool("disable_background_io_activity")) {
model->allow_background_io_activity(false);
}
|
codereview_cpp_data_1753
|
#include <algorithm> // for std::swap
#include <array> // for std::array
#include <iostream> // for io operations
/**
Please make it look like C++ code: ```suggestion if (size <= 1) { return; } ``` Same in other parts of the code.
#include <algorithm> // for std::swap
#include <array> // for std::array
+#include <cassert> // for assertions
#include <iostream> // for io operations
/**
|
codereview_cpp_data_1759
|
*/
GUARD(s2n_config_set_session_cache_onoff(config, 1));
GUARD(config->wall_clock(config->sys_clock_ctx, &now));
- EXPECT_SUCCESS(s2n_config_add_ticket_crypto_key(config, ticket_key_name, strlen((char *)ticket_key_name), ticket_key, strlen((char *)ticket_key), now/ONE_SEC_IN_NANOS));
EXPECT_SUCCESS(s2n_connection_set_config(conn, config));
you will overrun on `strlen(ticket_key)`; you want `sizeof(ticket_key)`
*/
GUARD(s2n_config_set_session_cache_onoff(config, 1));
GUARD(config->wall_clock(config->sys_clock_ctx, &now));
+ EXPECT_SUCCESS(s2n_config_add_ticket_crypto_key(config, ticket_key_name, strlen(ticket_key_name), ticket_key, sizeof(ticket_key), now/ONE_SEC_IN_NANOS));
EXPECT_SUCCESS(s2n_connection_set_config(conn, config));
|
codereview_cpp_data_1761
|
}
catch (std::bad_alloc &e)
{
- throw std::runtime_error("ERROR: bad_alloc detected when resizing "
- "data buffer with size " +
- std::to_string(size) + "\ndescription: " +
- std::string(e.what()) + "\n");
}
}
else
Would these be better suited to use `std::throw_with_nested`? ```cpp std::throw_with_nested( std::runtime_error("ERROR: bad_alloc detected when resizing " "data buffer with size " + std::to_string(size) + "\n")); ```
}
catch (std::bad_alloc &e)
{
+ std::throw_with_nested(
+ std::runtime_error("ERROR: bad_alloc detected when resizing "
+ "data buffer with size " +
+ std::to_string(size) + "\n"));
}
}
else
|
codereview_cpp_data_1766
|
psb->m_cfg.kDF = 1;
psb->m_cfg.collisions = btSoftBody::fCollision::SDF_RD;
getDeformableDynamicsWorld()->addSoftBody(psb);
- getDeformableDynamicsWorld()->addForce(psb, new btDeformableMassSpringForce(2, 0.01, false));
- getDeformableDynamicsWorld()->addForce(psb, new btDeformableGravityForce(gravity));
// add a few rigid bodies
Ctor_RbUpStack(1);
}
forces need to be deleted in exitPhysics
psb->m_cfg.kDF = 1;
psb->m_cfg.collisions = btSoftBody::fCollision::SDF_RD;
getDeformableDynamicsWorld()->addSoftBody(psb);
+ btDeformableMassSpringForce* mass_spring = new btDeformableMassSpringForce(2,0.01, false);
+ getDeformableDynamicsWorld()->addForce(psb, mass_spring);
+ forces.push_back(mass_spring);
+
+ btDeformableGravityForce* gravity_force = new btDeformableGravityForce(gravity);
+ getDeformableDynamicsWorld()->addForce(psb, gravity_force);
+ forces.push_back(gravity_force);
// add a few rigid bodies
Ctor_RbUpStack(1);
}
|
codereview_cpp_data_1767
|
{
if ( isValidIndex( position ) && dir != UNKNOWN ) {
Board * board = Arena::GetBoard();
- if ( dir == CENTER )
return &board->at( position );
- else if ( isValidDirection( position, dir ) )
return &board->at( GetIndexDirection( position, dir ) );
}
return nullptr;
:warning: **readability-else-after-return** :warning: do not use 'else' after 'return' ```suggestion if ( isValidDirection( position, dir ) ) return &board->at( GetIndexDirection( position, dir ) ) ```
{
if ( isValidIndex( position ) && dir != UNKNOWN ) {
Board * board = Arena::GetBoard();
+ if ( dir == CENTER ) {
return &board->at( position );
+ }
+ if ( isValidDirection( position, dir ) ) {
return &board->at( GetIndexDirection( position, dir ) );
+ }
}
return nullptr;
|
codereview_cpp_data_1773
|
return result;
}
- boost::optional<ModelObject> Space_Impl::buildingUnitAsModelObject() const {
- OptionalModelObject result;
- boost::optional<BuildingUnit> intermediate = buildingUnit();
- if (intermediate) {
- result = *intermediate;
- }
- return result;
- }
-
std::vector<ModelObject> Space_Impl::shadingSurfaceGroupsAsModelObjects() const {
ModelObjectVector result = castVector<ModelObject>(shadingSurfaceGroups());
return result;
these methods were to support Q_PROPERTY access, we don't support those anymore so there is no need to implement this method
return result;
}
std::vector<ModelObject> Space_Impl::shadingSurfaceGroupsAsModelObjects() const {
ModelObjectVector result = castVector<ModelObject>(shadingSurfaceGroups());
return result;
|
codereview_cpp_data_1793
|
{
char path[MAXPATHLEN];
int ret, fd;
if (console->path && !strcmp(console->path, "none"))
return 0;
- ret = snprintf(path, sizeof(path), "%s/dev/console", rootfs->path ? rootfs->mount : "");
if (ret < 0 || (size_t)ret >= sizeof(path))
return -1;
Could you please perform this check atop the function once: char rootfs_path = rootfs->path ? rootfs->mount : ""; and then just use `rootfs_path` everywhere, please?
{
char path[MAXPATHLEN];
int ret, fd;
+ char *rootfs_path = rootfs->path ? rootfs->mount : "";
if (console->path && !strcmp(console->path, "none"))
return 0;
+ ret = snprintf(path, sizeof(path), "%s/dev/console", rootfs_path);
if (ret < 0 || (size_t)ret >= sizeof(path))
return -1;
|
codereview_cpp_data_1795
|
static char **opt_extensions;
static char **opt_metadata;
static gboolean opt_no_exports;
-static int opt_extension_prio = -10000;
static char *opt_sdk;
static char *opt_runtime;
Might be slightly better to use `G_MININT`
static char **opt_extensions;
static char **opt_metadata;
static gboolean opt_no_exports;
+static int opt_extension_prio = G_MININT;
static char *opt_sdk;
static char *opt_runtime;
|
codereview_cpp_data_1797
|
// benchmarks helpers
static int32_t * getRandomSeed (int32_t * seed);
-static FILE * openOutFileWithR_PARTITEpostfix (const char * name);
static const char * elektraGetString (void * data);
static size_t getPower (size_t p, size_t q);
size_t getNCount (void);
Can you please avoid all-caps and underscore in the middle of a camelcase word?
// benchmarks helpers
static int32_t * getRandomSeed (int32_t * seed);
+static FILE * openOutFileWithRPartitepostfix (const char * name);
static const char * elektraGetString (void * data);
static size_t getPower (size_t p, size_t q);
size_t getNCount (void);
|
codereview_cpp_data_1799
|
return H2O_HTTP2_ERROR_FRAME_SIZE;
}
if (conn->timestamps.settings_acked_at.tv_sec == 0 && conn->timestamps.settings_sent_at.tv_sec != 0) {
- gettimeofday(&conn->timestamps.settings_acked_at, NULL);
}
} else {
uint32_t prev_initial_window_size = conn->peer_settings.initial_window_size;
How about using `h2o_gettimeofday` instead? It is faster, and provides sufficient accuracy for measuring RTT.
return H2O_HTTP2_ERROR_FRAME_SIZE;
}
if (conn->timestamps.settings_acked_at.tv_sec == 0 && conn->timestamps.settings_sent_at.tv_sec != 0) {
+ conn->timestamps.settings_acked_at = h2o_gettimeofday(conn->super.ctx->loop);
}
} else {
uint32_t prev_initial_window_size = conn->peer_settings.initial_window_size;
|
codereview_cpp_data_1816
|
if (debug_mode_key_inverted_v) {
sprintf(tempstr, "PX = %i PY = %i", plr[myplr]._px, plr[myplr]._py);
NetSendCmdString(1 << myplr, tempstr);
- // BUGFIX: out-of-bounds access to dungeon; should be `dungeon[(cursmx-16)/2][(cursmy-16)/2]`, was `dungeon[cursmx][cursmy]`.
sprintf(tempstr, "CX = %i CY = %i DP = %i", cursmx, cursmy, dungeon[cursmx][cursmy]);
NetSendCmdString(1 << myplr, tempstr);
}
Yep, I fixed this one many moons ago. You can see the string says "DP" for "dungeon piece" but they used the wrong array. It should be `dPiece[cursmx][cursmy]` :)
if (debug_mode_key_inverted_v) {
sprintf(tempstr, "PX = %i PY = %i", plr[myplr]._px, plr[myplr]._py);
NetSendCmdString(1 << myplr, tempstr);
+ // BUGFIX: out-of-bounds access to dungeon; should be `dPiece[cursmx][cursmy]`, was `dungeon[cursmx][cursmy]`.
sprintf(tempstr, "CX = %i CY = %i DP = %i", cursmx, cursmy, dungeon[cursmx][cursmy]);
NetSendCmdString(1 << myplr, tempstr);
}
|
codereview_cpp_data_1821
|
{
// Base class
if (versionNumber < 30506) {
- // Convert body property into a socket to PhysicalFrame with name "frame"
SimTK::Xml::element_iterator bodyElement = aNode.element_begin("body");
std::string frame_name("");
if (bodyElement != aNode.element_end()) {
this is still a `connector` here
{
// Base class
if (versionNumber < 30506) {
+ // Convert body property into a connector to PhysicalFrame with name "frame"
SimTK::Xml::element_iterator bodyElement = aNode.element_begin("body");
std::string frame_name("");
if (bodyElement != aNode.element_end()) {
|
codereview_cpp_data_1828
|
" RETURNING id");
}
_insertFolder->bindValue(":displayName", displayName);
- _insertFolder->bindValue(":parentId", parentId == -1 ? QVariant() : (qlonglong)parentId);
_insertFolder->bindValue(":userId", (qlonglong)userId);
_insertFolder->bindValue(":public", isPublic);
return _insertRecord(*_insertFolder);
}
Let's get @bmarchant or @bwitham feedback on this change Would parentId be null here now that we allow it?
" RETURNING id");
}
_insertFolder->bindValue(":displayName", displayName);
_insertFolder->bindValue(":userId", (qlonglong)userId);
_insertFolder->bindValue(":public", isPublic);
+ if (parentId != -1)
+ {
+ _insertFolder->bindValue(":parentId", (qlonglong)parentId);
+ }
return _insertRecord(*_insertFolder);
}
|
codereview_cpp_data_1833
|
#include "ElectricEquipmentITEAirCooled.hpp"
#include "ElectricEquipmentITEAirCooled_Impl.hpp"
-// TODO: Check the following class names against object getters and setters.
#include "ElectricEquipmentITEAirCooledDefinition.hpp"
#include "ElectricEquipmentITEAirCooledDefinition_Impl.hpp"
#include "Schedule.hpp"
Was this added to the DefaultScheduleType object? I didn't see that change in the IDD.
#include "ElectricEquipmentITEAirCooled.hpp"
#include "ElectricEquipmentITEAirCooled_Impl.hpp"
#include "ElectricEquipmentITEAirCooledDefinition.hpp"
#include "ElectricEquipmentITEAirCooledDefinition_Impl.hpp"
#include "Schedule.hpp"
|
codereview_cpp_data_1838
|
std::string readData;
detail::loggerStatus(detail::db->Get(leveldb::ReadOptions(), key, &readData));
- if (not readData.empty()) {
return readData;
} else {
return "";
`not readData.empty()` really? Maybe `!readData.empty()`?
std::string readData;
detail::loggerStatus(detail::db->Get(leveldb::ReadOptions(), key, &readData));
+ if (!readData.empty()) {
return readData;
} else {
return "";
|
codereview_cpp_data_1848
|
mp_err(log, "Failed to retrieve the Prime Handle from handle %d (%d).\n", object, descriptor->objects[object].fd);
goto fail;
}
- if(object == 0 && descriptor->objects[object].format_modifier) {
modifiers[object] = descriptor->objects[object].format_modifier;
- } else if (object == 0) {
- modifiers[object] = 0;
}
}
Can't this be shortened to ```c if (object == 0) { modifiers[object] = descriptor->objects[object].format_modifier; } ``` ?
mp_err(log, "Failed to retrieve the Prime Handle from handle %d (%d).\n", object, descriptor->objects[object].fd);
goto fail;
}
+ if(object == 0) {
modifiers[object] = descriptor->objects[object].format_modifier;
}
}
|
codereview_cpp_data_1855
|
DiscoveryDataBase::DiscoveryDataBase(
fastrtps::rtps::GuidPrefix_t server_guid_prefix)
: server_guid_prefix_(server_guid_prefix)
- , server_acked_by_all_(true)
{
}
I would not change this until the list of servers is defined in the database construction. Better to change it with the implementation that @EduPonz is going to do in the pinging PR.
DiscoveryDataBase::DiscoveryDataBase(
fastrtps::rtps::GuidPrefix_t server_guid_prefix)
: server_guid_prefix_(server_guid_prefix)
+ , server_acked_by_all_(false)
{
}
|
codereview_cpp_data_1859
|
int flag = 0;
for (int i = 0; i < modify->nfix; i++) {
if (strcmp(id,modify->fix[i]->id) == 0) before = 0;
- else if ((modify->fmask[i] && strcmp(modify->fix[i]->style,"nve")==0) && before) flag = 1;
}
if (flag && comm->me == 0)
error->all(FLERR,"Fix langevin gjf should come before fix nve");
this `strcmp()` test is not compatible with using various styles with suffixes. better would be to use: something like `utils::strmatch(modify->fix[i]->style,"^nve")`
int flag = 0;
for (int i = 0; i < modify->nfix; i++) {
if (strcmp(id,modify->fix[i]->id) == 0) before = 0;
+ else if ((modify->fmask[i] && utils::strmatch(modify->fix[i]->style,"^nve")) && before) flag = 1;
}
if (flag && comm->me == 0)
error->all(FLERR,"Fix langevin gjf should come before fix nve");
|
codereview_cpp_data_1872
|
/**
* @brief Checks if it's time for the logic to advance
* @param unused
- * @return True if the engine shold tick
*/
BOOL nthread_has_500ms_passed(BOOL unused)
{
```suggestion * @return True if the engine should tick ```
/**
* @brief Checks if it's time for the logic to advance
* @param unused
+ * @return True if the engine should tick
+
*/
BOOL nthread_has_500ms_passed(BOOL unused)
{
|
codereview_cpp_data_1880
|
char errmsg[256];
snprintf(errmsg, 256, "step%d-hbondchk failed: H=%d end(H)=%d str(H+1)=%d\n",
step, Hindex, End_Index(Hindex,hbonds), comp );
- system->error_ptr->all(FLERR, errmsg);
}
}
}
Same issue here. This looks more likely for calling `error->one()` instead of `error->all()`.
char errmsg[256];
snprintf(errmsg, 256, "step%d-hbondchk failed: H=%d end(H)=%d str(H+1)=%d\n",
step, Hindex, End_Index(Hindex,hbonds), comp );
+ system->error_ptr->one(FLERR, errmsg);
}
}
}
|
codereview_cpp_data_1881
|
g2 = guild->search(gid2);
if (g1 == NULL || g2 == NULL) {
- ShowWarning("buildin_checkguildally: requesting non-existent guild ID.\n"); //guild->search already tell the guild ID
script_pushint(st, -1);
return false;
}
guild->search doesn't tell the ID
g2 = guild->search(gid2);
if (g1 == NULL || g2 == NULL) {
+ if (g1 == NULL)
+ ShowWarning("buildin_checkguildally: requesting non-existent guild ID '%d'.\n", gid1);
+ if (g2 == NULL)
+ ShowWarning("buildin_checkguildally: requesting non-existent guild ID '%d'.\n", gid2);
script_pushint(st, -1);
return false;
}
|
codereview_cpp_data_1933
|
**/
#include <iostream>
-#include <climits>
-bool isprime[INT_MAX];
/**
* This is the function that finds the primes and eliminates
use dynamic memory allocation try to allocate the memory using the `new` keyword instead of using `INT_MAX` and also deallocate the memory after use using `delete` keyword if you wish to allocate a bool array of size 20 (say) then you should write `bool *arr = new bool[20];` and to delete this allocated memory write `delete [] arr;` i hope now things are clear
**/
#include <iostream>
+bool* isprime = new bool[100000];
/**
* This is the function that finds the primes and eliminates
|
codereview_cpp_data_1934
|
InitDataDir();
ReadConfigs();
- // generates the default high score list if necessary
- GenerateDefaultHighScoreForStandard();
-
// getopt
{
int opt;
We should generate it only at the time of opening High Scores. Please remove this code from here.
InitDataDir();
ReadConfigs();
// getopt
{
int opt;
|
codereview_cpp_data_1962
|
#include "stringtools.h"
#include "list.h"
#include "makeflow_summary.h"
-#include "../../dttools/src/catalog_query.h"
-#include "../../dttools/src/json.h"
-#include "../../dttools/src/json_aux.h"
-#include "../../dttools/src/username.h"
#include <stdlib.h>
#include <stdio.h>
I believe you can write this simply as `catalog_query.h` and the build system will set the paths correctly.
#include "stringtools.h"
#include "list.h"
#include "makeflow_summary.h"
+#include "catalog_query.h"
+#include "json.h"
+#include "json_aux.h"
+#include "username.h"
+#include "batch_job.h"
#include <stdlib.h>
#include <stdio.h>
|
codereview_cpp_data_1971
|
EXPECT_NOT_NULL(client_conn);
EXPECT_NOT_NULL(server_conn);
- if (security_policy_selection[policy_index].security_policy->minimum_protocol_version == S2N_TLS13
- && !s2n_is_tls13_fully_supported()) {
/* We purposefully do not allow users to configure Security Policies with a minimum allowed TLS
- * Version of TLS 1.3, if TLS 1.3 algorithms aren't fully supported by the libcrypto we're using */
EXPECT_FAILURE(s2n_config_set_cipher_preferences(config, security_policy_selection[policy_index].version));
} else {
-
EXPECT_SUCCESS(s2n_config_set_cipher_preferences(config, security_policy_selection[policy_index].version));
EXPECT_SUCCESS(s2n_config_set_verification_ca_location(config, S2N_DEFAULT_TEST_CERT_CHAIN, NULL));
EXPECT_NOT_NULL(config->default_certs_by_type.certs[S2N_PKEY_TYPE_RSA]);
Can we test this failure behavior once, and then restrict the rest of these tests to only TLS1.3? Mixing this failure case in with other tests makes them harder to follow.
EXPECT_NOT_NULL(client_conn);
EXPECT_NOT_NULL(server_conn);
+ if (security_policy_selection[policy_index].security_policy->minimum_protocol_version > s2n_get_highest_fully_supported_tls_version()) {
/* We purposefully do not allow users to configure Security Policies with a minimum allowed TLS
+ * versions that are greater than what libcrypto supports. */
EXPECT_FAILURE(s2n_config_set_cipher_preferences(config, security_policy_selection[policy_index].version));
} else {
EXPECT_SUCCESS(s2n_config_set_cipher_preferences(config, security_policy_selection[policy_index].version));
EXPECT_SUCCESS(s2n_config_set_verification_ca_location(config, S2N_DEFAULT_TEST_CERT_CHAIN, NULL));
EXPECT_NOT_NULL(config->default_certs_by_type.certs[S2N_PKEY_TYPE_RSA]);
|
codereview_cpp_data_1973
|
void MegaApiImpl::syncFolder(const char *localFolder, MegaHandle megaHandle, MegaRegExp *regExp, long long localfp, MegaRequestListener *listener)
{
MegaRequestPrivate *request = new MegaRequestPrivate(MegaRequest::TYPE_ADD_SYNC);
- if (megaHandle != INVALID_HANDLE) request->setNodeHandle(megaHandle);
if(localFolder)
{
string path(localFolder);
```suggestion cpp request->setNodeHandle(megaHandle); ``` The test was intended to avoid a crash if the input param was null. Now it's not a pointer :)
void MegaApiImpl::syncFolder(const char *localFolder, MegaHandle megaHandle, MegaRegExp *regExp, long long localfp, MegaRequestListener *listener)
{
MegaRequestPrivate *request = new MegaRequestPrivate(MegaRequest::TYPE_ADD_SYNC);
+ request->setNodeHandle(megaHandle);
if(localFolder)
{
string path(localFolder);
|
codereview_cpp_data_1989
|
}
else if ((option == "-Setup") || (option == "-S")) {
if (argc < 3) {
- cout << "Setup file .xml is expected after -S option. Please fix and retry." << endl;
PrintUsage(argv[0], cout);
exit(-1);
}
`A setup (.xml) file was expected but no file was provided. If no setup file exists, use the -PS option to print a default setup file that can be edited.`
}
else if ((option == "-Setup") || (option == "-S")) {
if (argc < 3) {
+ cout << "A setup(.xml) file was expected but no file was provided. If no setup file exists, use the - PS option to print a default setup file that can be edited." << endl;
PrintUsage(argv[0], cout);
exit(-1);
}
|
codereview_cpp_data_1994
|
*# A client that attempts to send 0-RTT data MUST fail a connection if
*# it receives a ServerHello with TLS 1.2 or older.
*/
- {
EXPECT_SUCCESS(s2n_reset_tls13());
struct s2n_config *config = s2n_config_new();
EXPECT_SUCCESS(s2n_config_add_cert_chain_and_key_to_store(config, chain_and_key));
/* Succeeds when negotiating TLS1.3 */
- if (s2n_is_tls13_fully_supported()) {
struct s2n_connection *client_conn = s2n_connection_new(S2N_CLIENT);
EXPECT_SUCCESS(s2n_connection_set_config(client_conn, config));
EXPECT_SUCCESS(s2n_connection_set_cipher_preferences(client_conn, "test_all"));
I would just move this if and the one on line 617 to line 581. Both the success/failures versions of this test require the client to use TLS1.3 because the client must request early data.
*# A client that attempts to send 0-RTT data MUST fail a connection if
*# it receives a ServerHello with TLS 1.2 or older.
*/
+ if (s2n_is_tls13_fully_supported()) {
EXPECT_SUCCESS(s2n_reset_tls13());
struct s2n_config *config = s2n_config_new();
EXPECT_SUCCESS(s2n_config_add_cert_chain_and_key_to_store(config, chain_and_key));
/* Succeeds when negotiating TLS1.3 */
+ {
struct s2n_connection *client_conn = s2n_connection_new(S2N_CLIENT);
EXPECT_SUCCESS(s2n_connection_set_config(client_conn, config));
EXPECT_SUCCESS(s2n_connection_set_cipher_preferences(client_conn, "test_all"));
|
codereview_cpp_data_1996
|
// Move syncedmem head to HEAD_AT_GPU
const vector<Blob<Dtype>*>& params = solver_->net()->learnable_params();
- Dtype* mutable_gpu_data;
for (int i = 0; i < params.size(); ++i) {
- mutable_gpu_data = params[i]->mutable_gpu_data();
- mutable_gpu_data++; // added to prevent the warning message of compilers
- // warning: statement has no effect [-Wunused-value]
}
#endif
}
Why do you need to hold onto the return value? You could just call the `mutable_gpu_data` function: ``` for (int i = 0; i < params.size(); ++i) { params[i]->mutable_gpu_data(); } ```
// Move syncedmem head to HEAD_AT_GPU
const vector<Blob<Dtype>*>& params = solver_->net()->learnable_params();
for (int i = 0; i < params.size(); ++i) {
+ params[i]->mutable_gpu_data();
}
#endif
}
|
codereview_cpp_data_1998
|
struct and_op {
inline DataType operator()(const DataType& x1,
const DataType& x2) const {
- const auto& b1 = x1 >= DataType(0.5);
- const auto& b2 = x2 >= DataType(0.5);
return (b1 && b2) ? one : zero;
}
inline void operator()(const DataType& x1,
I think that it makes more sense to keep these with the standard definition of non-zero is true and zero is false.
struct and_op {
inline DataType operator()(const DataType& x1,
const DataType& x2) const {
+ const auto& b1 = x1 != zero && !std::isnan(x1);
+ const auto& b2 = x2 != zero && !std::isnan(x2);
return (b1 && b2) ? one : zero;
}
inline void operator()(const DataType& x1,
|
codereview_cpp_data_2000
|
} else if ( strmatch(fullname+strlen(strippedname)-4, ".svg")==0 && checked!='S' ) {
sf = SFReadSVG(fullname,0);
} else if ( strmatch(fullname+strlen(fullname)-4, ".ufo")==0 && checked!='u' ||
- strmatch(fullname+strlen(fullname)-4, ".ufo2")==0 && checked!='u' ||
- strmatch(fullname+strlen(fullname)-4, ".ufo3")==0 && checked!='u' ) {
sf = SFReadUFO(fullname,0);
} else if ( strmatch(fullname+strlen(fullname)-4, ".bdf")==0 && checked!='b' ) {
sf = SFFromBDF(fullname,0,false);
And same with these `4`s?
} else if ( strmatch(fullname+strlen(strippedname)-4, ".svg")==0 && checked!='S' ) {
sf = SFReadSVG(fullname,0);
} else if ( strmatch(fullname+strlen(fullname)-4, ".ufo")==0 && checked!='u' ||
+ strmatch(fullname+strlen(fullname)-5, ".ufo2")==0 && checked!='u' ||
+ strmatch(fullname+strlen(fullname)-5, ".ufo3")==0 && checked!='u' ) {
sf = SFReadUFO(fullname,0);
} else if ( strmatch(fullname+strlen(fullname)-4, ".bdf")==0 && checked!='b' ) {
sf = SFFromBDF(fullname,0,false);
|
codereview_cpp_data_2003
|
* @author ali-mir
*/
-#include <limits.h>
#include <iostream>
/**
Please use `climits`.
* @author ali-mir
*/
+#include <climits>
#include <iostream>
/**
|
codereview_cpp_data_2006
|
}
FakePeer &FakePeer::setProposalStorage(
- const std::shared_ptr<ProposalStorage> &proposal_storage) {
- proposal_storage_ = proposal_storage;
return *this;
}
please use pass by value for shared pointers
}
FakePeer &FakePeer::setProposalStorage(
+ std::shared_ptr<ProposalStorage> proposal_storage) {
+ proposal_storage_ = std::move(proposal_storage);
return *this;
}
|
codereview_cpp_data_2019
|
TEST_P(ValidProtoPaginationQueryValidatorTest, ValidPaginationQuery) {
auto answer = validator.validate(GetParam());
- ASSERT_FALSE(answer.hasErrors());
}
INSTANTIATE_TEST_CASE_P(
Maybe print answer and query, the same way as in transaction tests
TEST_P(ValidProtoPaginationQueryValidatorTest, ValidPaginationQuery) {
auto answer = validator.validate(GetParam());
+ ASSERT_FALSE(answer.hasErrors()) << GetParam().DebugString() << std::endl
+ << answer.reason();
}
INSTANTIATE_TEST_CASE_P(
|
codereview_cpp_data_2024
|
return "";
// beginning of a batch
if (not batch1) {
- if (batch2.get()->transactionHashes().size() == 0)
return (boost::format("Tx %s has a batch of 0 transactions")
% tr2->hash().hex())
.str();
- if (batch2.get()->transactionHashes().front() != tr2->reduced_hash())
return (boost::format("Tx %s is a first transaction of a batch, but "
"it's reduced hash %s doesn't match the first "
"reduced hash in batch %s")
Please be consistent with other parts of the project and use curly braces even for the single line statements. That improves readability IMO
return "";
// beginning of a batch
if (not batch1) {
+ if (batch2.get()->transactionHashes().size() == 0) {
return (boost::format("Tx %s has a batch of 0 transactions")
% tr2->hash().hex())
.str();
+ }
+ if (batch2.get()->transactionHashes().front() != tr2->reduced_hash()) {
return (boost::format("Tx %s is a first transaction of a batch, but "
"it's reduced hash %s doesn't match the first "
"reduced hash in batch %s")
|
codereview_cpp_data_2033
|
boost::optional<protocol::Block> result;
storage_->getBlocksFrom(1)
- .filter([hash](auto block) { return block->hash() == hash; })
.map([](auto block) {
- return std::static_pointer_cast<shared_model::proto::Block>(block)
->getTransport();
})
.as_blocking()
Capture hash by reference
boost::optional<protocol::Block> result;
storage_->getBlocksFrom(1)
+ .filter([&hash](auto block) { return block->hash() == hash; })
.map([](auto block) {
+ return std::dynamic_pointer_cast<shared_model::proto::Block>(block)
->getTransport();
})
.as_blocking()
|
codereview_cpp_data_2038
|
{
case NEW_PUBLIC:
case NEW_NODE:
- snk.add((nn + i)->nodekey, (nn + i)->nodehandle, tn, 0);
break;
case NEW_UPLOAD:
- snk.add((nn + i)->nodekey, (nn + i)->nodehandle, tn, 0, nn[i].uploadtoken, (int)sizeof nn->uploadtoken);
break;
}
}
`nn[i]` instead of `(nn + i)` like in other places?
{
case NEW_PUBLIC:
case NEW_NODE:
+ snk.add(nn[i].nodekey, nn[i].nodehandle, tn, 0);
break;
case NEW_UPLOAD:
+ snk.add(nn[i].nodekey, nn[i].nodehandle, tn, 0, nn[i].uploadtoken, (int)sizeof nn->uploadtoken);
break;
}
}
|
codereview_cpp_data_2042
|
_WriteBestBlock(hashBlock);
bool ret = db.WriteBatch(batch);
- LOG(COINDB, "Committing1 %u changed transactions (out of %u) to coin database with %u batch writes...\n",
(unsigned int)changed, (unsigned int)count, (unsigned int)nBatchWrites);
return ret;
committing1? (extra 1 in there)
_WriteBestBlock(hashBlock);
bool ret = db.WriteBatch(batch);
+ LOG(COINDB, "Committing %u changed transactions (out of %u) to coin database with %u batch writes...\n",
(unsigned int)changed, (unsigned int)count, (unsigned int)nBatchWrites);
return ret;
|
codereview_cpp_data_2050
|
return std::atoi(id.c_str());
}
int get_gpu(const InitArguments& args) {
int use_gpu = args.device_id;
const int ndevices = args.ndevices;
Why did you define it outside the anonymous namespace?
return std::atoi(id.c_str());
}
+namespace {
+
int get_gpu(const InitArguments& args) {
int use_gpu = args.device_id;
const int ndevices = args.ndevices;
|
codereview_cpp_data_2065
|
return defaultPenalty;
}
-int AIWorldPathfinder::getFogDiscoveryTile( const Heroes & hero, const bool considerWhirlpools )
{
// paths have to be pre-calculated to find a spot where we're able to move
- reEvaluateIfNeeded( hero, considerWhirlpools );
const int start = hero.GetIndex();
const int scouteValue = hero.GetScoute();
:warning: **readability\-function\-cognitive\-complexity** :warning: function `` getFogDiscoveryTile `` has cognitive complexity of 44 \(threshold 25\)
return defaultPenalty;
}
+int AIWorldPathfinder::getFogDiscoveryTile( const Heroes & hero )
{
// paths have to be pre-calculated to find a spot where we're able to move
+ reEvaluateIfNeeded( hero );
const int start = hero.GetIndex();
const int scouteValue = hero.GetScoute();
|
codereview_cpp_data_2066
|
int Heroes::GetMobilityIndexSprite( void ) const
{
// valid range (0 - 25)
- int index = !CanMove() ? 0 : static_cast<int>( std::round( move_point / 100.0f ) );
return 25 >= index ? index : 25;
}
An alternative solution would be `const int index = CanMove() ? ( move_point + 50 ) / 100 : 0;` without type conversion and std::round. Also it'll be faster and integer operations are always faster.
int Heroes::GetMobilityIndexSprite( void ) const
{
// valid range (0 - 25)
+ int index = CanMove() ? ( move_point + 50 ) / 100 : 0;
return 25 >= index ? index : 25;
}
|
codereview_cpp_data_2071
|
-#include "hip/hip_runtime.h"
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014-2019, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
OCD: Let's move this after the boilerplate.
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014-2019, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
|
codereview_cpp_data_2073
|
derived from this software without specific prior
written permission of the assimp team.
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
PLease remove the star at the end :-).
derived from this software without specific prior
written permission of the assimp team.
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
codereview_cpp_data_2082
|
blacklist ${PATH}/roxterm
blacklist ${PATH}/roxterm-config
blacklist ${PATH}/terminix
Please also add urxvtc.
blacklist ${PATH}/roxterm
blacklist ${PATH}/roxterm-config
blacklist ${PATH}/terminix
+blacklist ${PATH}/urxvtc
+blacklist ${PATH}/urxvtcd
|
codereview_cpp_data_2086
|
conn->req.res.reason = "Request Timeout";
}
close_idle_connection(&conn->super);
}
I think you're assuming `conn->sock->input->size == 0` is always true here, but I'm not sure why it is. could you tell me that when you get a chance? And if it's always true, how about adding `assert(conn->sock->input->size == 0)`?
conn->req.res.reason = "Request Timeout";
}
+ assert(conn->sock->input->size == 0);
close_idle_connection(&conn->super);
}
|
codereview_cpp_data_2090
|
FCMoveContent(temp_objects, matches);
}
- // No operand condition was selected. State is restored...
}
- // ... Nothing should match, so move all to non_matches input set.
- non_matches.reserve(matches.size() + non_matches.size());
- FCMoveContent(matches, non_matches);
}
bool OrderedAlternativesOf::RootCandidateInvariant() const {
Does it make sense to always do the samething here, independent if thesearch domain? If searching `NON_MATCHES`, the contents of `matches` shouldn't be modified.
FCMoveContent(temp_objects, matches);
}
+ // No operand condition was selected. Objects in matches input set do not match, so move those to non_matches input set.
+ non_matches.reserve(matches.size() + non_matches.size());
+ FCMoveContent(matches, non_matches);
}
}
bool OrderedAlternativesOf::RootCandidateInvariant() const {
|
codereview_cpp_data_2091
|
if (peer_wire_prefs != NULL && peer_wire_prefs->len > 0) {
int result = s2n_choose_sig_scheme(conn, peer_wire_prefs, &chosen_scheme);
- /* Previous versions can fall back to the default */
if (conn->actual_protocol_version == S2N_TLS13 && result != S2N_SUCCESS) {
- /* make the best match we can (https://tools.ietf.org/html/rfc8446#section-4.4.2.2) */
- S2N_ERROR_IF(s2n_preferred_sig_scheme(conn, &chosen_scheme) != S2N_SUCCESS, S2N_ERR_INVALID_SIGNATURE_SCHEME);
}
} else {
/* we can keep this here since we have not found any offending clients for this error */
Just `GUARD` instead, as function already sets the error.
if (peer_wire_prefs != NULL && peer_wire_prefs->len > 0) {
int result = s2n_choose_sig_scheme(conn, peer_wire_prefs, &chosen_scheme);
+ /* If we can't find a match in TLS 1.3, we pick the best signature algorithm to use */
+ /* https://tools.ietf.org/html/rfc8446#section-4.4.2.2 */
if (conn->actual_protocol_version == S2N_TLS13 && result != S2N_SUCCESS) {
+ GUARD(s2n_tls13_preferred_sig_scheme(conn, &chosen_scheme));
}
} else {
/* we can keep this here since we have not found any offending clients for this error */
|
codereview_cpp_data_2092
|
if ( config.Exists( "vita_keep_aspect_ratio" ) ) {
vita_keep_aspect_ratio = config.IntParams( "vita_keep_aspect_ratio" );
- fheroes2::Display::instance().engine()->vitaKeepAspectRatio = vita_keep_aspect_ratio;
}
#endif
This parameter we will re-implement again in the future.
if ( config.Exists( "vita_keep_aspect_ratio" ) ) {
vita_keep_aspect_ratio = config.IntParams( "vita_keep_aspect_ratio" );
+ fheroes2::Display::instance().engine()->SetVitaKeepAspectRatio( vita_keep_aspect_ratio );
}
#endif
|
codereview_cpp_data_2095
|
m_Socket = zmq_socket(m_Context, ZMQ_REP);
const std::string fullIP("tcp://" + m_IPAddress + ":" + m_Port);
- std::cout << "full IP = " << fullIP << std::endl;
zmq_bind(m_Socket, fullIP.c_str());
if (m_Profiler.IsActive)
cout in rank 0
m_Socket = zmq_socket(m_Context, ZMQ_REP);
const std::string fullIP("tcp://" + m_IPAddress + ":" + m_Port);
zmq_bind(m_Socket, fullIP.c_str());
if (m_Profiler.IsActive)
|
codereview_cpp_data_2098
|
if (missingattr)
{
- #if defined(_WIN32)
client->gfx->gendimensionsputfa(NULL, localname, n->nodehandle, n->nodecipher(), missingattr);
- #else
- client->gfx->gendimensionsputfa(NULL, localname, n->nodehandle, n->nodecipher(), missingattr);
- #endif
}
addAnyMissingMediaFileAttributes(n, localname);
Should there be any difference between these 2 blocks or always use one of them?
if (missingattr)
{
client->gfx->gendimensionsputfa(NULL, localname, n->nodehandle, n->nodecipher(), missingattr);
}
addAnyMissingMediaFileAttributes(n, localname);
|
codereview_cpp_data_2103
|
// convert from local encoding, then unescape escaped forbidden characters
void FileSystemAccess::local2name(string *filename, const string *localPath) const
{
string t = *filename;
local2path(&t, filename);
Maybe we can check if `filename` or `localPath` are null
// convert from local encoding, then unescape escaped forbidden characters
void FileSystemAccess::local2name(string *filename, const string *localPath) const
{
+ assert(filename);
+
string t = *filename;
local2path(&t, filename);
|
codereview_cpp_data_2109
|
using sofa::simulation::PythonEnvironment ;
using sofa::core::topology::BaseMeshTopology ;
using sofa::helper::vector ;
-typedef BaseMeshTopology::Tetra Tetra;
static Base* get_base(PyObject* self) {
return sofa::py::unwrap<Base>(self);
A factory would be beter :) Something like : BaseData* bf = factory(dataRawType[0]);
using sofa::simulation::PythonEnvironment ;
using sofa::core::topology::BaseMeshTopology ;
using sofa::helper::vector ;
+using namespace sofa::core::objectmodel;
+using sofa::helper::Factory;
+
+typedef sofa::helper::Factory< std::string, BaseData> PSDEDataFactory;
static Base* get_base(PyObject* self) {
return sofa::py::unwrap<Base>(self);
|
codereview_cpp_data_2116
|
}
auto YacInit::createTimer(std::chrono::milliseconds delay_milliseconds) {
- return std::make_shared<TimerImpl>(delay_milliseconds,
- rxcpp::observe_on_new_thread());
}
std::shared_ptr<YacGate> YacInit::initConsensusGate(
I think here we can consider an opportunity to reuse thread from MST-propagator. I am okay with both fix or todo.
}
auto YacInit::createTimer(std::chrono::milliseconds delay_milliseconds) {
+ return std::make_shared<TimerImpl>(
+ delay_milliseconds,
+ // TODO 2019-04-10 andrei: IR-441 Share a thread between MST and YAC
+ rxcpp::observe_on_new_thread());
}
std::shared_ptr<YacGate> YacInit::initConsensusGate(
|
codereview_cpp_data_2125
|
return (long)(floor(x * (10 * (precision - 1)) + 0.5) / (10 * (precision - 1)));
}
}
I'm looking at this, and... I'm thinking it's wrong. I think 10 should be raised to the power of (precision-1), not simply multiplied by (precision-1). Like use pow(10, precision-1) or something.
return (long)(floor(x * (10 * (precision - 1)) + 0.5) / (10 * (precision - 1)));
}
+long ApiDb::round2(double x, int precision)
+{
+ return (long)(floor(x * (pow(10, precision - 1)) + 0.5) / (pow(10, precision - 1)));
+}
+
}
|
codereview_cpp_data_2132
|
//Read each byte into our buffer
Vector<U8> buffer(readFile.getStreamSize());
- U8 byte;
- while(readFile.read(&byte))
- {
- buffer.push_back(byte);
- }
//Send the buffer
send(buffer.address(), buffer.size());
This is not guaranteed to send all the data, especially with a large file. What you need is a mechanism to send chunks of the file data per tick.
//Read each byte into our buffer
Vector<U8> buffer(readFile.getStreamSize());
+ readFile.read(buffer.size(), &buffer);
//Send the buffer
send(buffer.address(), buffer.size());
|
codereview_cpp_data_2145
|
for (auto& [id, partition] : qm) {
self->state.open_requests.emplace(id, 1 /*qm.size()*/);
// TODO: Add a proper configurable timeout.
- self->request(partition, caf::infinite, expr, client)
.then([=, id = id](atom::done) {
auto& num_evaluators = self->state.open_requests[id];
if (--num_evaluators == 0) {
Even in the old design I don't think there could be more than 1. I think `open_requests` can be replaced by a count, and we can refactor to use `fan_out_request` when we drop compatibility with CAF 0.17.
for (auto& [id, partition] : qm) {
self->state.open_requests.emplace(id, 1 /*qm.size()*/);
// TODO: Add a proper configurable timeout.
+ // TODO: Handle the error case for the `then()` handler.
+ self
+ ->request(partition, caf::infinite, expr,
+ caf::actor_cast<partition_client_actor>(client))
.then([=, id = id](atom::done) {
auto& num_evaluators = self->state.open_requests[id];
if (--num_evaluators == 0) {
|
codereview_cpp_data_2147
|
char* aws_secret_access_key;
char* aws_region;
char* aws_email;
- char* manager_env_prefix;
}initialized_data;
static unsigned int gen_guid(){
Maybe just `env_prefix`, I don't think this is referring to the WQ manager.
char* aws_secret_access_key;
char* aws_region;
char* aws_email;
+ char* env_prefix;
}initialized_data;
static unsigned int gen_guid(){
|
codereview_cpp_data_2168
|
protected:
/** Component Interface */
- void connect(Component& root, const bool topLevel) override {
Super::connect(root, topLevel);
// do any internal wiring
world = dynamic_cast<TheWorld*>(&root);
I don't like the extra bool argument in connect. What is it for? And what does a const bool do? should be const bool& so it isn't copied.
protected:
/** Component Interface */
+ void connect(Component& root, bool topLevel) override {
Super::connect(root, topLevel);
// do any internal wiring
world = dynamic_cast<TheWorld*>(&root);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.