id
stringlengths 21
25
| content
stringlengths 164
2.33k
|
|---|---|
codereview_cpp_data_12421
|
_writeChangesetToTable();
}
- _outputFilename.open(QFile::WriteOnly);
QTextStream outStream(&_outputFilename);
for ( std::list<QString>::const_iterator it = _sectionNames.begin();
Do you want `QIODevice::Append` here instead?
_writeChangesetToTable();
}
+ _outputFilename.open(QIODevice::Append);
QTextStream outStream(&_outputFilename);
for ( std::list<QString>::const_iterator it = _sectionNames.begin();
|
codereview_cpp_data_12425
|
}
/**
- * Called when it is still untertain which of the two TLS stacks (picotls or OpenSSL) should handle the handshake.
* The function first tries picotls without consuming the socket input buffer. Then, if picotls returns PTLS_ALERT_PROTOCOL_VERSION
* indicating that the client is using TLS 1.2 or below, switches to using OpenSSL.
*/
Maybe "uncertain"? ```suggestion * Called when it is still uncertain which of the two TLS stacks (picotls or OpenSSL) should handle the handshake. ```
}
/**
+ * Called when it is still uncertain which of the two TLS stacks (picotls or OpenSSL) should handle the handshake.
* The function first tries picotls without consuming the socket input buffer. Then, if picotls returns PTLS_ALERT_PROTOCOL_VERSION
* indicating that the client is using TLS 1.2 or below, switches to using OpenSSL.
*/
|
codereview_cpp_data_12434
|
}
/* ----------------------------------------------------------------------
- write a flag and a char string (including nullptr) into restart file
------------------------------------------------------------------------- */
void WriteRestart::write_string(int flag, const char *value)
This is incorrect. It writes the 0 byte at the end of the string. This has nothing to do with nullptr
}
/* ----------------------------------------------------------------------
+ write a flag and a C-style char string (including the terminating null
+ byte) into the restart file
------------------------------------------------------------------------- */
void WriteRestart::write_string(int flag, const char *value)
|
codereview_cpp_data_12444
|
/* !!! Bug. Lose device tables here */
if ( isv )
space->u.pair.vr[0].v_adv_off = kp->off;
space->u.pair.vr[0].h_adv_off = kp->off;
return( space );
}
There's probably an `else` missing here, and if not the indentation should be adjusted.
/* !!! Bug. Lose device tables here */
if ( isv )
space->u.pair.vr[0].v_adv_off = kp->off;
+ else
space->u.pair.vr[0].h_adv_off = kp->off;
return( space );
}
|
codereview_cpp_data_12469
|
return Spell( spellId ).GetName();
}
}
-}
-namespace Campaign
-{
bool tryGetMatchingFile( const std::string & fileName, std::string & matchingFilePath )
{
static const auto fileNameToPath = []() {
`std::unordered_map` seems to be more suitable especially with `result.reserve(files.size())` call.
return Spell( spellId ).GetName();
}
}
bool tryGetMatchingFile( const std::string & fileName, std::string & matchingFilePath )
{
static const auto fileNameToPath = []() {
|
codereview_cpp_data_12492
|
case Servatrice::AuthenticationNone: return UnknownUser;
case Servatrice::AuthenticationPassword: {
QString configPassword = settingsCache->value("authentication/password").toString();
- if(configPassword == password)
return PasswordRight;
return NotLoggedIn;
Can you space out the comparisons? eg `if (` rather than `if(`, in a lot of places
case Servatrice::AuthenticationNone: return UnknownUser;
case Servatrice::AuthenticationPassword: {
QString configPassword = settingsCache->value("authentication/password").toString();
+ if (configPassword == password)
return PasswordRight;
return NotLoggedIn;
|
codereview_cpp_data_12497
|
out_file.open(file_name.c_str(), std::ofstream::out | std::ofstream::trunc);
// If there is any problem in opening file
if(!out_file.is_open()) {
- std::cerr << "ERROR: Unable to open file: "<< file_name << std::endl;
std::exit(EXIT_FAILURE);
}
/**
```suggestion std::cerr << __func__ << ": ERROR: Unable to open file: "<< file_name << std::endl; ```
out_file.open(file_name.c_str(), std::ofstream::out | std::ofstream::trunc);
// If there is any problem in opening file
if(!out_file.is_open()) {
+ std::cerr << "ERROR (" << __func__ << ") : ";
+ std::cerr << "Unable to open file: "<< file_name << std::endl;
std::exit(EXIT_FAILURE);
}
/**
|
codereview_cpp_data_12507
|
GCancellable *cancellable,
GError **error)
{
- int exit_status = EXIT_FAILURE;
g_autoptr(GOptionContext) context = g_option_context_new ("TREEFILE - Install packages and commit the result to an OSTree repository");
-
if (!rpmostree_option_context_parse (context,
option_entries,
&argc, &argv,
We can also replace the `goto out` in here to `return EXIT_FAILURE` now, right?
GCancellable *cancellable,
GError **error)
{
g_autoptr(GOptionContext) context = g_option_context_new ("TREEFILE - Install packages and commit the result to an OSTree repository");
if (!rpmostree_option_context_parse (context,
option_entries,
&argc, &argv,
|
codereview_cpp_data_12520
|
cout<<"Running tool "<<getName()<<".\n";
- // Get the trial name to label data written to files
- string TrialName = getName();
// Initialize the model's underlying computational system and get its default state.
SimTK::State& s = _model->initSystem();
Variable names should start with a lower case letter; change this to `trialName`
cout<<"Running tool "<<getName()<<".\n";
+ // Get the trial name to label data written to files
+ string trialName = getName();
// Initialize the model's underlying computational system and get its default state.
SimTK::State& s = _model->initSystem();
|
codereview_cpp_data_12523
|
#include "text.h"
#include "world.h"
-using namespace Game;
-
void RedistributeArmy( ArmyTroop & troop1 /* from */, ArmyTroop & troop2 /* to */ )
{
const Army * army1 = troop1.GetArmy();
We do not encourage to use `using namespace`. Please do not use it.
#include "text.h"
#include "world.h"
void RedistributeArmy( ArmyTroop & troop1 /* from */, ArmyTroop & troop2 /* to */ )
{
const Army * army1 = troop1.GetArmy();
|
codereview_cpp_data_12533
|
SP_CLASS_METHOD_DOC(BaseObject, getTarget,
"Returns the target (plugin) that contains the current object.")
SP_CLASS_METHOD(BaseObject,getAsACreateObjectParameter)
-SP_CLASS_METHOD(BaseObject,computeBBox)
SP_CLASS_METHODS_END
It is better to use SP_CLASS_METHOD_DOC() to add a docstring so we can query the object from interactive python environemnt (like Ipython notebook) and we can generate the doc out of code.
SP_CLASS_METHOD_DOC(BaseObject, getTarget,
"Returns the target (plugin) that contains the current object.")
SP_CLASS_METHOD(BaseObject,getAsACreateObjectParameter)
+SP_CLASS_METHOD_DOC(BaseObject, computeBBox, "Recomputes the bounding box of the object")
SP_CLASS_METHODS_END
|
codereview_cpp_data_12542
|
std::shared_ptr<shared_model::interface::Account> account_test = clone(
shared_model::proto::AccountBuilder().accountId("test@test").build());
- EXPECT_CALL(*storage, getWsvQuery()).WillRepeatedly(Return(wsv_query));
- EXPECT_CALL(*storage, getBlockQuery()).WillRepeatedly(Return(block_query));
EXPECT_CALL(*wsv_query,
hasAccountGrantablePermission(
"admin@test", "test@test", can_get_my_acc_detail))
Since there are no failure cases, these `EXPECT`s can be moved to `SetUp`.
std::shared_ptr<shared_model::interface::Account> account_test = clone(
shared_model::proto::AccountBuilder().accountId("test@test").build());
EXPECT_CALL(*wsv_query,
hasAccountGrantablePermission(
"admin@test", "test@test", can_get_my_acc_detail))
|
codereview_cpp_data_12543
|
struct lxc_list *iterator, *network;
int data_sock = handler->data_sock[0];
- if (!handler->root)
return 0;
network = &handler->conf->network;
Why send a ucred along with the info?
struct lxc_list *iterator, *network;
int data_sock = handler->data_sock[0];
+ if (!handler->am_root)
return 0;
network = &handler->conf->network;
|
codereview_cpp_data_12544
|
/* thread-shift so we can check global objects */
cb = PMIX_NEW(pmix_cb_t);
cb->active = true;
- cb->procs = (pmix_proc_t*)proc;
cb->key = (char*)key;
cb->info = (pmix_info_t*)info;
cb->ninfo = ninfo;
@rhc54 I'm seeing problem here. We cannot be sure that caller won't free proc structure after Get_nb returns. This is not so critical now while we are using blocking Get. But may became important in future when Get_nb will be used. Also right now we have both nspace/rank fields and procs fields in pmix_cb_t which are replicating each other. Why can't we go on with nspace/rank as it was before?
/* thread-shift so we can check global objects */
cb = PMIX_NEW(pmix_cb_t);
cb->active = true;
+ (void)strncpy(cb->nspace, proc->nspace, PMIX_MAX_NSLEN);
+ cb->rank = proc->rank;
cb->key = (char*)key;
cb->info = (pmix_info_t*)info;
cb->ninfo = ninfo;
|
codereview_cpp_data_12548
|
// Some wrapper macro for testing:
#define WRAP(...) __VA_ARGS__
-#define GPU_PRINT_TIME(cmd, elapsed, quiet) \
do { \
hipDeviceSynchronize(); \
cmd; \
Just a cosmetic change. But can we rename the MACRO to something else? Say MY_LAUNCH_MACRO or something? GPU_PRINT_TIME seems odd especially since we don't have any GPU timing code or prints in this macro.
// Some wrapper macro for testing:
#define WRAP(...) __VA_ARGS__
+#define MY_LAUNCH_MACRO(cmd, elapsed, quiet) \
do { \
hipDeviceSynchronize(); \
cmd; \
|
codereview_cpp_data_12551
|
Booster* ref_booster = reinterpret_cast<Booster*>(handle);
auto get_row_fun = RowFunctionFromCSR(indptr, indptr_type, indices, data, data_type, nindptr, nelem);
int nrow = static_cast<int>(nindptr - 1);
- ref_booster->Predict(num_iteration, predict_type, nrow, static_cast<int32_t>(num_col), get_row_fun,
config, out_result, out_len);
API_END();
}
Is it safe? Maybe simply change the original type, as it was not used before?
Booster* ref_booster = reinterpret_cast<Booster*>(handle);
auto get_row_fun = RowFunctionFromCSR(indptr, indptr_type, indices, data, data_type, nindptr, nelem);
int nrow = static_cast<int>(nindptr - 1);
+ int ncol = static_cast<int>(num_col);
+ if (ncol <= 0) {
+ ncol = GuessNumColFromCSR(indptr, indptr_type, indices, nindptr);
+ }
+ ref_booster->Predict(num_iteration, predict_type, nrow, ncol, get_row_fun,
config, out_result, out_len);
API_END();
}
|
codereview_cpp_data_12553
|
* @details
* ### Case 1: The given node has the right node/subtree
*
- * In this case the left most deepest node in the right subtree will come
- * just after the given node as we go to left deep in inorder.
* - Go deep to left most node in right subtree.
* OR, we can also say in case if BST, find the minimum of the subtree
* for a given node.
```suggestion * * In this case, the left-most deepest node in the right subtree will come ```
* @details
* ### Case 1: The given node has the right node/subtree
*
+ * * In this case, the left-most deepest node in the right subtree will
+ * come just after the given node as we go to left deep in inorder.
* - Go deep to left most node in right subtree.
* OR, we can also say in case if BST, find the minimum of the subtree
* for a given node.
|
codereview_cpp_data_12554
|
/* Reset sequence number */
conn->secure.client_sequence_number[7] = 0;
- s2n_stuffer_write_bytes(&conn->in, &conn->out.blob.data[S2N_TLS13_AAD_LEN], plaintext.size + 16 + 1); /* tag length + content type */;
/* Make a slice of output bytes to verify */
struct s2n_blob encrypted = {
is it worth corrupting a record and making sure that it doesn't decrypt?
/* Reset sequence number */
conn->secure.client_sequence_number[7] = 0;
+ EXPECT_SUCCESS(s2n_stuffer_write_bytes(&conn->in, &conn->out.blob.data[S2N_TLS13_AAD_LEN], plaintext.size + 16 + 1)); /* tag length + content type */;
/* Make a slice of output bytes to verify */
struct s2n_blob encrypted = {
|
codereview_cpp_data_12567
|
p->path = path;
- p->uid = getuid ();
- p->gid = getgid ();
}
static resolverHandle * elektraGetResolverHandle (Plugin * handle, Key * parentKey)
I think thats wrong, we are not interested in chown to our own user (thats the case anyway), but to do a chown in the case of root to the uid/gid that was present in the file before.
p->path = path;
+ p->uid = 0;
+ p->gid = 0;
}
static resolverHandle * elektraGetResolverHandle (Plugin * handle, Key * parentKey)
|
codereview_cpp_data_12584
|
{
LOG_verbose << "Removing node from database: " << (Base64::btoa((byte*)&((*it)->nodehandle),MegaClient::NODEHANDLE,base64) ? base64 : "");
#ifdef ENABLE_SYNC
- mUnsyncableNodes.erase((*it)->nodehandle);
- if (!(complete = mUnsyncableNodesTable->del((*it)->dbid)))
{
break;
}
Perhaps we shouldn't try to remove the database entry if the handle was not in mUnsyncableNodes? As we might set complete=false unnecessarily. Also, I wonder if this is a case where we could have a bit more encapsulation - just one class to manage the in-RAM map and the database table, and ensure their consistency in a single class? That would also reduce the amount of in-line logic.
{
LOG_verbose << "Removing node from database: " << (Base64::btoa((byte*)&((*it)->nodehandle),MegaClient::NODEHANDLE,base64) ? base64 : "");
#ifdef ENABLE_SYNC
+ if (!(complete = unsyncables->removeNode((*it)->nodehandle)))
{
break;
}
|
codereview_cpp_data_12595
|
S2N_ERROR_IF(compression_method != S2N_TLS_COMPRESSION_METHOD_NULL, S2N_ERR_BAD_MESSAGE);
bool session_ids_match = session_id_len != 0 && session_id_len == conn->session_id_len
- && !memcmp(session_id, conn->session_id, session_id_len);
if (!session_ids_match) {
conn->ems_negotiated = false;
}
should this be: ```suggestion && memcmp(session_id, conn->session_id, session_id_len); ``` Also not sure your test is covering this. The test only seems to be covering `len == 0` case.
S2N_ERROR_IF(compression_method != S2N_TLS_COMPRESSION_METHOD_NULL, S2N_ERR_BAD_MESSAGE);
bool session_ids_match = session_id_len != 0 && session_id_len == conn->session_id_len
+ && memcmp(session_id, conn->session_id, session_id_len) == 0;
if (!session_ids_match) {
conn->ems_negotiated = false;
}
|
codereview_cpp_data_12612
|
async_call_->log_->info(
"Receive votes[size={}] from {}", state.size(), context->peer());
- handler_.lock()->onState(std::move(state));
return grpc::Status::OK;
}
Unconditional lock of the weak pointer will cause undefined behavior when a pointer type does not have a default constructor. Please do something like ``` if (auto notifications = handler_.lock()) { notifications->onState(std::move(state)); } else { // some error handling if applicable } ```
async_call_->log_->info(
"Receive votes[size={}] from {}", state.size(), context->peer());
+ if (auto notifications = handler_.lock()) {
+ notifications->onState(std::move(state));
+ } else {
+ async_call_->log_->error("Unable to lock the subscriber");
+ }
return grpc::Status::OK;
}
|
codereview_cpp_data_12627
|
spin_op_progress (FlatpakCliTransaction *self,
FlatpakTransactionOperation *op)
{
- const char p[] = "/-\\|/-\\|";
set_op_progress (self, op, p[self->op_progress++ % strlen (p)]);
}
Why two copies of the / - \ - | progression?
spin_op_progress (FlatpakCliTransaction *self,
FlatpakTransactionOperation *op)
{
+ const char p[] = "/-\\|";
set_op_progress (self, op, p[self->op_progress++ % strlen (p)]);
}
|
codereview_cpp_data_12635
|
return make_error(ec::unspecified, "unsupported table slice type", x);
}
// TODO: this function will boil down to accessing the chunk inside the table
// slice and then calling GetTableSlice(buf). But until we touch the table
// slice internals, we use this helper.
caf::expected<flatbuffers::Offset<TableSliceBuffer>>
-create_table_slice_buffer(flatbuffers::FlatBufferBuilder& builder,
- table_slice_ptr x) {
// This local builder instance will vanish once we can access the underlying
// chunk of a table slice.
flatbuffers::FlatBufferBuilder local_builder;
The old function `create_table_slice` is still defined in the header.
return make_error(ec::unspecified, "unsupported table slice type", x);
}
+} // namespace
+
// TODO: this function will boil down to accessing the chunk inside the table
// slice and then calling GetTableSlice(buf). But until we touch the table
// slice internals, we use this helper.
caf::expected<flatbuffers::Offset<TableSliceBuffer>>
+pack(flatbuffers::FlatBufferBuilder& builder, table_slice_ptr x) {
// This local builder instance will vanish once we can access the underlying
// chunk of a table slice.
flatbuffers::FlatBufferBuilder local_builder;
|
codereview_cpp_data_12643
|
}
config->xwayland = true;
- config->xwayland_lazy = false;
wl_list_init(&config->outputs);
wl_list_init(&config->devices);
wl_list_init(&config->keyboards);
Technically redundant with calloc, but I actually think this should default to true if it works well.
}
config->xwayland = true;
+ config->xwayland_lazy = true;
wl_list_init(&config->outputs);
wl_list_init(&config->devices);
wl_list_init(&config->keyboards);
|
codereview_cpp_data_12645
|
std::make_shared<std::string>("operation overflows number"));
}
std::string val = val_amount.str();
- if (new_precision) {
val.insert((val.rbegin() + new_precision).base(), '.');
}
return iroha::expected::makeValue(
Same about explicit condition
std::make_shared<std::string>("operation overflows number"));
}
std::string val = val_amount.str();
+ if (new_precision != 0) {
val.insert((val.rbegin() + new_precision).base(), '.');
}
return iroha::expected::makeValue(
|
codereview_cpp_data_12658
|
* @repo: A OstreeRepo
* @old_ref: old ref to use
* @new_ref: New ref to use
- * @out_variant: floating GVariant that represents the differences
- * between the rpm databases on the given refs.
* GCancellable: *cancellable
* GError: **error
*
Same here, I'd say `ref_sink`.
* @repo: A OstreeRepo
* @old_ref: old ref to use
* @new_ref: New ref to use
+ * @out_variant: GVariant that represents the differences between the rpm
+ * databases on the given refs.
* GCancellable: *cancellable
* GError: **error
*
|
codereview_cpp_data_12660
|
CommandResult CommandExecutor::operator()(
const shared_model::interface::AddAssetQuantity &command) {
std::string command_name = "AddAssetQuantity";
- auto result = commands->addAssetQuantity(creator_account_id,
command.assetId(),
command.amount().toStringRepr(),
command.amount().precision());
This class seems redundant now. Maybe create Postgres command executor and remove wsv_command altogether?
CommandResult CommandExecutor::operator()(
const shared_model::interface::AddAssetQuantity &command) {
std::string command_name = "AddAssetQuantity";
+ auto result = executor->addAssetQuantity(creator_account_id,
command.assetId(),
command.amount().toStringRepr(),
command.amount().precision());
|
codereview_cpp_data_12661
|
int s2n_stuffer_rewrite(struct s2n_stuffer *stuffer)
{
stuffer->write_cursor = 0;
- stuffer->read_cursor = MIN(stuffer->read_cursor, stuffer->write_cursor);
return 0;
}
So this is MIN(stuffer->read_cursor, 0). Should we just eliminate the MIN and do `stuffer->write_cursor = 0; stuffer->read_cursor = 0;`
int s2n_stuffer_rewrite(struct s2n_stuffer *stuffer)
{
stuffer->write_cursor = 0;
+ stuffer->read_cursor = 0;
return 0;
}
|
codereview_cpp_data_12672
|
[](mega::UnifiedSync* us, const SyncError&, error e){
if (us && us->mSync)
{
- cout << "Sync added and running. backupId = " << us->mConfig.getBackupId();
}
else if (us)
{
Note: printing and inputing of backupId is done considering it a integer. I wonder if we should try and use a base64 representation :thinking: ... Same applies to MEGAcmd, that would require similar changes. What do you think @mattw-mega ?
[](mega::UnifiedSync* us, const SyncError&, error e){
if (us && us->mSync)
{
+ cout << "Sync added and running. backupId = " << toHandle(us->mConfig.getBackupId());
}
else if (us)
{
|
codereview_cpp_data_12677
|
g_random_set_seed(now);
FindFonts(dirs,exts);
-#ifdef _WIN32
- mkdir(results_dir);
-#else
mkdir(results_dir,0755);
-#endif
for (;;)
do_test();
Not sure I get this one. Why `mkdir` and not `GFileMkDir`? Does something provide that mapping?
g_random_set_seed(now);
FindFonts(dirs,exts);
mkdir(results_dir,0755);
for (;;)
do_test();
|
codereview_cpp_data_12679
|
unsigned enable_mfl:1;
unsigned session_ticket:1;
unsigned session_cache:1;
- const char *ca_dir;
- const char *ca_file;
unsigned insecure:1;
unsigned use_corked_io:1;
};
int handle_connection(int fd, struct s2n_config *config, struct conn_settings settings)
thanks for doing this. can you move these up with the others?
unsigned enable_mfl:1;
unsigned session_ticket:1;
unsigned session_cache:1;
unsigned insecure:1;
unsigned use_corked_io:1;
+ const char *ca_dir;
+ const char *ca_file;
};
int handle_connection(int fd, struct s2n_config *config, struct conn_settings settings)
|
codereview_cpp_data_12681
|
getProcessor(inputProtocol, outputProtocol, client),
inputProtocol, outputProtocol, eventHandler_, client));
- threadManager_->add(pClient, timeout_, taskExpiration_);
} catch (TTransportException& ttx) {
if (inputTransport) {
use make_shared. It shaves off an allocation. For bonus terseness... don't even make a local shared_ptr<TConnectedClient>. Just pass the make_shared result to threadManager_->add.
getProcessor(inputProtocol, outputProtocol, client),
inputProtocol, outputProtocol, eventHandler_, client));
+ threadManager_->add(
+ boost::make_shared<TConnectedClient>(
+ "TThreadPoolServer",
+ getProcessor(inputProtocol, outputProtocol, client),
+ inputProtocol, outputProtocol, eventHandler_, client),
+ timeout_,
+ taskExpiration_);
} catch (TTransportException& ttx) {
if (inputTransport) {
|
codereview_cpp_data_12684
|
RequiredPlugin::RequiredPlugin()
: d_pluginName( initData(&d_pluginName, "pluginName", "plugin name (or several names if you need to load different plugins or a plugin with several alternate names)"))
- , d_searchPath( initData(&d_searchPath, "searchPath", "Directory to scan before the default ones") )
, d_suffixMap ( initData(&d_suffixMap , "suffixMap", "standard->custom suffixes pairs (to be used if the plugin is compiled outside of Sofa with a non standard way of differenciating versions), using ! to represent empty suffix"))
, d_stopAfterFirstNameFound( initData(&d_stopAfterFirstNameFound , false, "stopAfterFirstNameFound", "Stop after the first plugin name that is loaded successfully"))
, d_stopAfterFirstSuffixFound( initData(&d_stopAfterFirstSuffixFound , true, "stopAfterFirstSuffixFound", "For each plugin name, stop after the first suffix that is loaded successfully"))
The name is not required, the altenrative is to set he pluginName in the name field which allows to write: <RequiredPlugin name="Toto"/> instead of <RequiredPlugin pluginName="Toto"/> The nice thing by using <RequiredPlugin name="Toto"/> is that it display in the scene graph view of runSofa the name of the plugin. EDIT: I see your added warning after
RequiredPlugin::RequiredPlugin()
: d_pluginName( initData(&d_pluginName, "pluginName", "plugin name (or several names if you need to load different plugins or a plugin with several alternate names)"))
, d_suffixMap ( initData(&d_suffixMap , "suffixMap", "standard->custom suffixes pairs (to be used if the plugin is compiled outside of Sofa with a non standard way of differenciating versions), using ! to represent empty suffix"))
, d_stopAfterFirstNameFound( initData(&d_stopAfterFirstNameFound , false, "stopAfterFirstNameFound", "Stop after the first plugin name that is loaded successfully"))
, d_stopAfterFirstSuffixFound( initData(&d_stopAfterFirstSuffixFound , true, "stopAfterFirstSuffixFound", "For each plugin name, stop after the first suffix that is loaded successfully"))
|
codereview_cpp_data_12685
|
*/
#include "main/impl/ordering_init.hpp"
-#include "model/peer.hpp"
#include "ametsuchi/ordering_service_persistent_state.hpp"
namespace iroha {
namespace network {
How it's work? Why you remove transport from here?
*/
#include "main/impl/ordering_init.hpp"
#include "ametsuchi/ordering_service_persistent_state.hpp"
+#include "model/peer.hpp"
namespace iroha {
namespace network {
|
codereview_cpp_data_12689
|
// DoLayout reflowed the text.
int text_size = Value((m_link_text->TextLowerRight() - m_link_text->TextUpperLeft()).y);
int icon_size = Value(GetIconSize());
- int maxPanelSize = std::max(text_size, icon_size);
- maxPanelSize += Value(ITEM_VERTICAL_PADDING);
- GG::Pt panel_size = GG::Pt(GG::X(lr.x - ul.x), GG::Y(maxPanelSize));
GG::Control::SizeMove(ul, ul + panel_size );
DoLayout();
}
name variables with all_lower_case_underscore_separated please
// DoLayout reflowed the text.
int text_size = Value((m_link_text->TextLowerRight() - m_link_text->TextUpperLeft()).y);
int icon_size = Value(GetIconSize());
+ int max_panel_size = std::max(text_size, icon_size);
+ max_panel_size += Value(ITEM_VERTICAL_PADDING);
+ GG::Pt panel_size = GG::Pt(GG::X(lr.x - ul.x), GG::Y(max_panel_size));
GG::Control::SizeMove(ul, ul + panel_size );
DoLayout();
}
|
codereview_cpp_data_12692
|
using namespace sofa::defaulttype;
// Register in the Factory
-int SPHFluidSurfaceMappingClass = core::RegisterObject("TODO-SPHFluidSurfaceMappingClass")
.addAlias("MarchingCubeMapping")
.add< SPHFluidSurfaceMapping< Vec3Types, Vec3Types > >()
;
Maybe the chance to update the doc..?
using namespace sofa::defaulttype;
// Register in the Factory
+int SPHFluidSurfaceMappingClass = core::RegisterObject("SPHFluidSurfaceMappingClass")
.addAlias("MarchingCubeMapping")
.add< SPHFluidSurfaceMapping< Vec3Types, Vec3Types > >()
;
|
codereview_cpp_data_12695
|
auto proposal = os->onRequestProposal(target_round);
// since we only sent one transaction,
- // if the proposal is present, there is no need to check for that specific
- // tx
EXPECT_TRUE(proposal);
}
Changes in this file are not really required by clang-format and can be reverted.
auto proposal = os->onRequestProposal(target_round);
// since we only sent one transaction,
+ // if the proposal is present, there is no need to check for that specific tx
EXPECT_TRUE(proposal);
}
|
codereview_cpp_data_12699
|
* @brief Functions for [Strand Sort](https://en.wikipedia.org/wiki/Strand_sort) algorithm
*/
namespace strand {
- template <typename T>
/**
* @brief Apply sorting
* @tparam element type of list
* @param lst List to be sorted
* @returns Sorted list<T> instance
*/
std::list<T> strand_sort(std::list<T> lst) {
if (lst.size() < 2) { // Returns list if empty or contains only one element
return lst; // Returns list
```suggestion /** * @brief Apply sorting * @tparam element type of list * @param lst List to be sorted * @returns Sorted list<T> instance */ template <typename T> std::list<T> strand_sort(std::list<T> lst) { ```
* @brief Functions for [Strand Sort](https://en.wikipedia.org/wiki/Strand_sort) algorithm
*/
namespace strand {
/**
* @brief Apply sorting
* @tparam element type of list
* @param lst List to be sorted
* @returns Sorted list<T> instance
*/
+ template <typename T>
std::list<T> strand_sort(std::list<T> lst) {
if (lst.size() < 2) { // Returns list if empty or contains only one element
return lst; // Returns list
|
codereview_cpp_data_12700
|
auto storage_ptr = std::move(mutableStorage); // get ownership of storage
auto storage = static_cast<MutableStorageImpl *>(storage_ptr.get());
for (const auto &block : storage->block_store_) {
- std::string ss = shared_model::converters::protobuf::modelToJson(
- *std::dynamic_pointer_cast<shared_model::proto::Block>(
- block.second));
-
block_store_->add(
block.first,
stringToBytes(shared_model::converters::protobuf::modelToJson(
Why we need SS here? Maybe use it in add call?
auto storage_ptr = std::move(mutableStorage); // get ownership of storage
auto storage = static_cast<MutableStorageImpl *>(storage_ptr.get());
for (const auto &block : storage->block_store_) {
block_store_->add(
block.first,
stringToBytes(shared_model::converters::protobuf::modelToJson(
|
codereview_cpp_data_12712
|
hasLinkCreationTs = MemAccess::get<char>(ptr);
ptr += sizeof(hasLinkCreationTs);
- const bool syncable = MemAccess::get<bool>(ptr);
- ptr += sizeof(syncable);
for (i = 5; i--;)
{
from cppreference: "bool - type, capable of holding one of the two values: true or false. The value of sizeof(bool) is implementation defined and might differ from 1."
hasLinkCreationTs = MemAccess::get<char>(ptr);
ptr += sizeof(hasLinkCreationTs);
+ const auto syncableInt = MemAccess::get<int8_t>(ptr);
+ ptr += 1;
for (i = 5; i--;)
{
|
codereview_cpp_data_12713
|
}
break;
default:
- for ( i=0; i<cnt; ++i )
- free( parsed[i].entity );
- free(parsed);
return( copy( _("Bad FPST format")) );
}
if ( fpst->format!=pst_reversecoverage ) {
One would have to read the algorithm above very closely to know whether an `entity` could wind up NON-NULL at this point, so freeing them here makes sense, given that whenever one is "used" at the end the pointer is set to NULL. Similarly, one would have to read the algorithm above very closely to know whether a `replacements` could wind up non-NULL at this point, so freeing them makes just as much sense (to me), also given that whenever one is "used" the pointer is set to NULL. So either you've got a better understanding of the algorithm (which is quite possible) or you could also free `replacements` here).
}
break;
default:
return( copy( _("Bad FPST format")) );
}
if ( fpst->format!=pst_reversecoverage ) {
|
codereview_cpp_data_12731
|
int s2n_config_set_max_cert_chain_depth(struct s2n_config *config, uint16_t max_depth) {
notnull_check(config);
- config->max_verify_cert_chain_depth = max_depth;
- config->max_verify_cert_chain_depth_set = 1;
- return 0;
}
We should check for greater than zero here too
int s2n_config_set_max_cert_chain_depth(struct s2n_config *config, uint16_t max_depth) {
notnull_check(config);
+
+ if (max_depth > 0) {
+ config->max_verify_cert_chain_depth = max_depth;
+ config->max_verify_cert_chain_depth_set = 1;
+ return 0;
+ }
+
+ return -1;
}
|
codereview_cpp_data_12734
|
size_t size = 0;
std::ostringstream strs;
strs << (int) latitude << (int) longitude;
- size = strs.str().length() + 1 + 6 * 2 + 1;
char coords[size]; // <lat>;<lon>
- sprintf(coords, "%.6f;%.6f", latitude, longitude);
request->setText(coords);
request->setFlag(true); // is official attribute?
requestQueue.push(request);
It should be 7*2 due to the decimal point
size_t size = 0;
std::ostringstream strs;
strs << (int) latitude << (int) longitude;
+ size = strs.str().length() + 1 + 7 * 2 + 1;
char coords[size]; // <lat>;<lon>
+ snprintf(coords, size, "%.6f;%.6f", latitude, longitude);
request->setText(coords);
request->setFlag(true); // is official attribute?
requestQueue.push(request);
|
codereview_cpp_data_12739
|
m_Socket = zmq_socket(m_Context, ZMQ_REQ);
const std::string fullIP("tcp://" + m_IPAddress + ":" + m_Port);
- std::cout << "full IP = " << fullIP << std::endl;
int err = zmq_connect(m_Socket, fullIP.c_str());
if (m_Profiler.IsActive)
cout in rank zero
m_Socket = zmq_socket(m_Context, ZMQ_REQ);
const std::string fullIP("tcp://" + m_IPAddress + ":" + m_Port);
int err = zmq_connect(m_Socket, fullIP.c_str());
if (m_Profiler.IsActive)
|
codereview_cpp_data_12759
|
CommandResult execute(
const std::unique_ptr<shared_model::interface::Command> &command,
- bool is_genesis = false,
const shared_model::interface::types::AccountIdType &creator =
"id@domain") {
- executor->doValidation(not is_genesis);
executor->setCreatorAccountId(creator);
return boost::apply_visitor(*executor, command->get());
}
Not sure if genesis block should be mentioned here. Maybe use `do_validation`?
CommandResult execute(
const std::unique_ptr<shared_model::interface::Command> &command,
+ bool do_validation = false,
const shared_model::interface::types::AccountIdType &creator =
"id@domain") {
+ executor->doValidation(not do_validation);
executor->setCreatorAccountId(creator);
return boost::apply_visitor(*executor, command->get());
}
|
codereview_cpp_data_12780
|
translateAndMapModelObject(*runPeriod);
// ensure that output table summary reports exists
- boost::optional<model::OutputTableSummaryReports> summaryReports = model.getOptionalUniqueModelObject<model::OutputTableSummaryReports>();
- if (!summaryReports){
- summaryReports = model.getUniqueModelObject<model::OutputTableSummaryReports>();
}
- translateAndMapModelObject(*summaryReports);
// add a global geometry rules object
IdfObject globalGeometryRules(openstudio::IddObjectType::GlobalGeometryRules);
To maintain backward compat, either `OutputTableSummaryReports` needs to have it's Ctor directly call `addSummaryReport("AllSummary")` or you need to do it here by adding a line after 561 `summaryReports.addSummaryReport("AllSummary");`
translateAndMapModelObject(*runPeriod);
// ensure that output table summary reports exists
+ boost::optional<model::OutputTableSummaryReports> outputTableSummaryReports = model.getOptionalUniqueModelObject<model::OutputTableSummaryReports>();
+ if (!outputTableSummaryReports) {
+ outputTableSummaryReports = model.getUniqueModelObject<model::OutputTableSummaryReports>();
+ outputTableSummaryReports.addSummaryReport("AllSummary");
}
+ translateAndMapModelObject(*outputTableSummaryReports);
// add a global geometry rules object
IdfObject globalGeometryRules(openstudio::IddObjectType::GlobalGeometryRules);
|
codereview_cpp_data_12782
|
/* OCSP_basic_verify() returns 1 on success, 0 on error, or -1 on fatal error such as malloc failure. */
if (ocsp_verify_res != _OSSL_SUCCESS) {
- ret_val = S2N_CERT_ERR_UNTRUSTED;
goto clean_up;
}
I think your callout is probably right: `S2N_CERT_ERR_UNTRUSTED` doesn't seem like the correct error. I would suggest either `S2N_ERR_SAFETY` for a generic internal error, or if we think it'll usually be for malloc failures we could do `S2N_ERR_ALLOC`. I think in the end we at least want the error type to be `S2N_ERR_T_INTERNAL` rather than `S2N_ERR_T_PROTO`.
/* OCSP_basic_verify() returns 1 on success, 0 on error, or -1 on fatal error such as malloc failure. */
if (ocsp_verify_res != _OSSL_SUCCESS) {
+ ret_val = ocsp_verify_res == 0 ? S2N_CERT_ERR_UNTRUSTED : S2N_CERT_ERR_INTERNAL_ERROR;
goto clean_up;
}
|
codereview_cpp_data_12785
|
return( true );
}
-static int GFD_Reference(GGadget *g, GEvent *e) {
- if ( e->type==et_controlevent && e->u.control.subtype == et_radiochanged ) {
- struct gfc_data *d = GDrawGetUserData(GGadgetGetWindow(g));
- int ref = GGadgetIsChecked(d->reference);
- }
- return true;
-}
-
static int GFD_Format(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_listselected ) {
struct gfc_data *d = GDrawGetUserData(GGadgetGetWindow(g));
This this block even necessary? It doesn't seem to be doing anything.
return( true );
}
static int GFD_Format(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_listselected ) {
struct gfc_data *d = GDrawGetUserData(GGadgetGetWindow(g));
|
codereview_cpp_data_12790
|
if (err != noErr)
return qhReturn;
- if (input) {
- propertyAddress.mScope = kAudioDevicePropertyScopeInput;
- } else {
- propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
- }
for (UInt32 i = 0; i < ndevs; i++) {
QString qsDeviceName;
Normally I'm not a big fan of 1-liners but in the case of a conditional assignment, I think they are actually more readable: ```suggestion propertyAddress.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; ```
if (err != noErr)
return qhReturn;
+ propertyAddress.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
for (UInt32 i = 0; i < ndevs; i++) {
QString qsDeviceName;
|
codereview_cpp_data_12793
|
void IntroPage::retranslateUi()
{
setTitle(tr("Introduction"));
- label->setText(tr("This wizard will import the list of sets, cards and tokens "
"that will be used by Cockatrice."
- "\nYou will need to specify an URL or a filename that "
"will be used as a source."));
languageLabel->setText(tr("Language:"));
}
add an oxford comma, please `... of sets, cards, and tokens`
void IntroPage::retranslateUi()
{
setTitle(tr("Introduction"));
+ label->setText(tr("This wizard will import the list of sets, cards, and tokens "
"that will be used by Cockatrice."
+ "\nYou will need to specify a URL or a filename that "
"will be used as a source."));
languageLabel->setText(tr("Language:"));
}
|
codereview_cpp_data_12800
|
EXPECT_SUCCESS(s2n_cert_chain_and_key_free(chain_and_key_2));
/* Increment flag counter for sign operation */
- async_handler_called++;
} else {
/* Test decrypt operation passes */
EXPECT_SUCCESS(s2n_async_pkey_op_apply(pkey_op, conn));
-
- /* Increment flag counter for decrypt operation */
- async_handler_called++;
}
/* Free the pkey op */
You check in your test that async_handler_called==1. So if you increment async_handler_called for the decrypt operation, how do you know your signing tests are being run? If the handler is only called once, wouldn't that one call being a decrypt operation be an error?
EXPECT_SUCCESS(s2n_cert_chain_and_key_free(chain_and_key_2));
/* Increment flag counter for sign operation */
+ async_handler_sign_operation_called++;
} else {
/* Test decrypt operation passes */
EXPECT_SUCCESS(s2n_async_pkey_op_apply(pkey_op, conn));
}
/* Free the pkey op */
|
codereview_cpp_data_12802
|
return 0;
}
-string MegaNode::getWritableLinkAuthKey()
{
- return string();
}
bool MegaNode::isFile()
Public interfaces should not return `std::string`, but a `const char *` in order to get bindings automatically created by SWIG. Could we change it to return a `c_str()`?? In the end, the `MegaNode` keeps the ownership.
return 0;
}
+const char * MegaNode::getWritableLinkAuthKey()
{
+ return nullptr;
}
bool MegaNode::isFile()
|
codereview_cpp_data_12803
|
MegaStringListPrivate::MegaStringListPrivate(char **newlist, int size)
{
- if (!size)
- {
- return;
- }
-
for (int i = 0; i < size; i++)
{
mList.push_back(newlist[i]);
We can also get rid of this `if (!size)` :)
MegaStringListPrivate::MegaStringListPrivate(char **newlist, int size)
{
for (int i = 0; i < size; i++)
{
mList.push_back(newlist[i]);
|
codereview_cpp_data_12814
|
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/config.h>
-#include <sofa/config/sharedlibrary_defines.h>
namespace sofa
{
```suggestion ``` sofa/config.h already includes sofa/config/sharedlibrary_defines.h
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/config.h>
namespace sofa
{
|
codereview_cpp_data_12823
|
l.request_output_values == r.request_output_values &&
l.declare_optimization_goal == r.declare_optimization_goal;
}
-enum class MayRequireGlobalFencing : bool { Yes, No };
template <typename Callback, typename... Args>
inline void invoke_kokkosp_callback(
MayRequireGlobalFencing may_require_global_fencing,
Minor: I would have done `{ No, Yes }`, mainly, so that `No` matches `false` and `Yes` matches `true`.
l.request_output_values == r.request_output_values &&
l.declare_optimization_goal == r.declare_optimization_goal;
}
+enum class MayRequireGlobalFencing : bool { No, Yes };
template <typename Callback, typename... Args>
inline void invoke_kokkosp_callback(
MayRequireGlobalFencing may_require_global_fencing,
|
codereview_cpp_data_12831
|
if (!atom->rmass) {
for (int i = 1; i <= atom->ntypes; i++) {
gfactor1[i] = -atom->mass[i] / t_period / force->ftm2v;
- if (!gjfflag)
gfactor2[i] = sqrt(atom->mass[i]) *
- sqrt(24.0*force->boltz/t_period/update->dt/force->mvv2e) /
force->ftm2v;
else
gfactor2[i] = sqrt(atom->mass[i]) *
- sqrt(2.0*force->boltz/t_period/update->dt/force->mvv2e) /
force->ftm2v;
gfactor1[i] *= 1.0/ratio[i];
gfactor2[i] *= 1.0/sqrt(ratio[i]);
this would be easier to read, if the test was `if (gjfflag)` and the cases swapped.
if (!atom->rmass) {
for (int i = 1; i <= atom->ntypes; i++) {
gfactor1[i] = -atom->mass[i] / t_period / force->ftm2v;
+ if (gjfflag)
gfactor2[i] = sqrt(atom->mass[i]) *
+ sqrt(2.0*force->boltz/t_period/update->dt/force->mvv2e) /
force->ftm2v;
else
gfactor2[i] = sqrt(atom->mass[i]) *
+ sqrt(24.0*force->boltz/t_period/update->dt/force->mvv2e) /
force->ftm2v;
gfactor1[i] *= 1.0/ratio[i];
gfactor2[i] *= 1.0/sqrt(ratio[i]);
|
codereview_cpp_data_12832
|
sofa::component::initSofaBaseUtils();
sofa::component::initSofaBaseMechanics();
sofa::component::initSofaMeshCollision();
-
- sofa::helper::system::PluginManager::getInstance().getPluginMap();
- auto& map = PluginManager::getInstance().getPluginMap();
- for (const auto& elem : map)
- {
- std::cout << elem.second.getModuleName() << std::endl;
- }
}
void checkRequiredPlugin(bool missing)
Is this important? You just `cout` something. Or is there side effects?
sofa::component::initSofaBaseUtils();
sofa::component::initSofaBaseMechanics();
sofa::component::initSofaMeshCollision();
}
void checkRequiredPlugin(bool missing)
|
codereview_cpp_data_12840
|
bool collision = true;
std::size_t t = 1;
- while (t <= m_lobby_data->m_players.size() + server.Networking().GetCookiesSize() + 1 &&
- collision)
{
collision = false;
roles.Clear();
reorder to ```` (collision && t <= m_lobby_data ... ```` and indent to match
bool collision = true;
std::size_t t = 1;
+ while (collision &&
+ t <= m_lobby_data->m_players.size() + server.Networking().GetCookiesSize() + 1)
{
collision = false;
roles.Clear();
|
codereview_cpp_data_12850
|
// if we can solve those requests locally (runtime cached values)...
if (!strcmp(an, "firstname") && u->firstname)
{
app->getua_result((byte*) u->firstname->data(), u->firstname->size());
return;
}
else if (!strcmp(an, "lastname") && u->lastname)
{
app->getua_result((byte*) u->lastname->data(), u->lastname->size());
return;
}
client->restag should be set before calling callbacks
// if we can solve those requests locally (runtime cached values)...
if (!strcmp(an, "firstname") && u->firstname)
{
+ restag = reqtag;
app->getua_result((byte*) u->firstname->data(), u->firstname->size());
return;
}
else if (!strcmp(an, "lastname") && u->lastname)
{
+ restag = reqtag;
app->getua_result((byte*) u->lastname->data(), u->lastname->size());
return;
}
|
codereview_cpp_data_12860
|
proj_destroy(P);
}
proj_context_destroy(ctx);
}
that one and the 2 other below objects should be proj_destroy()'ed
proj_destroy(P);
}
+ proj_destroy(epsg27700);
+ proj_destroy(epsg4326);
+ proj_destroy(epsg3857);
proj_context_destroy(ctx);
}
|
codereview_cpp_data_12864
|
/* set transfer-encoding header */
h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_TRANSFER_ENCODING, NULL, H2O_STRLIT("chunked"));
} else {
req->send_server_timing_trailer = 0;
}
Don't we need to do either of: * set this flag to zero if `should_use_chunked_encoding` returns false * clear the flag in `init_request` Otherwise, I believe that there would be a chance of server using chunked encoding even when it should not, while responding to a succeeding HTTP request of a persistent connection.
/* set transfer-encoding header */
h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_TRANSFER_ENCODING, NULL, H2O_STRLIT("chunked"));
} else {
+ self->chunked.enabled = 0;
req->send_server_timing_trailer = 0;
}
|
codereview_cpp_data_12873
|
}
void data_store_merge_features::exchange_data() {
- for (auto store : m_subsidiary_stores) {
- store->set_shuffled_indices_special(m_shuffled_indices);
store->exchange_data();
}
}
perhaps different name as 'no_exchange' instead of 'special'
}
void data_store_merge_features::exchange_data() {
+ for (auto s : m_subsidiary_stores) {
+ data_store_csv *store = dynamic_cast<data_store_csv*>(s);
+ store->set_shuffled_indices(m_shuffled_indices);
store->exchange_data();
}
}
|
codereview_cpp_data_12876
|
}
#pragma warning(pop)
}
-#else
-void SetCurrentThreadName(const char *) {}
#endif
```suggestion void SetCurrentThreadName(const char *) {} ``` (I'm being really nitpicky now)
}
#pragma warning(pop)
}
#endif
|
codereview_cpp_data_12884
|
}
static uint8_t *do_encode_header(h2o_hpack_header_table_t *header_table, uint8_t *dst, const h2o_iovec_t *name,
- const h2o_iovec_t *value, int name_index, h2o_header_flags_t flags)
{
/* try to send as indexed */
{
size_t header_table_index = header_table->entry_start_index, n;
Is there a need to accept `name_index` as a separate argument? I assume the value is available as `flags.http2_static_table_name_index`.
}
static uint8_t *do_encode_header(h2o_hpack_header_table_t *header_table, uint8_t *dst, const h2o_iovec_t *name,
+ const h2o_iovec_t *value, h2o_header_flags_t flags)
{
+ int name_index = flags.http2_static_table_name_index;
+
/* try to send as indexed */
{
size_t header_table_index = header_table->entry_start_index, n;
|
codereview_cpp_data_12889
|
EXPECT_CALL(*query, getTopBlockHeight()).WillOnce(Return(2));
- EXPECT_CALL(*validator, validateProxy(_, _))
- .WillOnce(Return(verified_proposal_and_errors));
EXPECT_CALL(*ordering_gate, on_proposal())
.WillOnce(Return(rxcpp::observable<>::empty<
can't we use invoke here and return unique ptr instead of using proxy?
EXPECT_CALL(*query, getTopBlockHeight()).WillOnce(Return(2));
+ EXPECT_CALL(*validator, validate(_, _))
+ .WillOnce(Invoke([&verified_proposal_and_errors](const auto &p, auto &v) {
+ return std::move(verified_proposal_and_errors);
+ }));
EXPECT_CALL(*ordering_gate, on_proposal())
.WillOnce(Return(rxcpp::observable<>::empty<
|
codereview_cpp_data_12902
|
#define DELIMITER ", "
#define ELEMENT_LONGEST_STR(name) #name "; " SERVER_TIMING_DURATION_LONGEST_STR
-#define EMIT_ELEMENT(req, dst, name, max_len) emit_server_timing_element(req, dst, #name, h2o_time_compute_##name##_time, max_len)
static void emit_server_timing_element(h2o_req_t *req, h2o_iovec_t *dst, const char *name,
int (*compute_func)(h2o_req_t *, int64_t *), size_t max_len)
I believe that the names should match those defined for the Access Timings extensions defined for the access-log handler, with the `-time` suffix being omitted. In other words, how about: 1. changing the names to be: connect, request-header, request-body, request-total, process, response 2. define `total-time` as a synonym of `duration` in the access-log handler 2 ensures us that we can continue to emit `server-timing: total; dur=xxx` as the trailer.
#define DELIMITER ", "
#define ELEMENT_LONGEST_STR(name) #name "; " SERVER_TIMING_DURATION_LONGEST_STR
static void emit_server_timing_element(h2o_req_t *req, h2o_iovec_t *dst, const char *name,
int (*compute_func)(h2o_req_t *, int64_t *), size_t max_len)
|
codereview_cpp_data_12915
|
make_test_subscriber<CallExact>(ordering_gate.on_proposal(), 2);
wrapper_after.subscribe();
- auto proposal = std::make_shared<shared_model::proto::Proposal>(
TestProposalBuilder().build());
- ordering_gate.onProposal(proposal);
- ordering_gate.onProposal(proposal);
ASSERT_TRUE(wrapper_before.validate());
You pass shared pointer to the same proposal twice that will be moved somewhere
make_test_subscriber<CallExact>(ordering_gate.on_proposal(), 2);
wrapper_after.subscribe();
+ auto proposal1 = std::make_shared<shared_model::proto::Proposal>(
+ TestProposalBuilder().build());
+ auto proposal2 = std::make_shared<shared_model::proto::Proposal>(
TestProposalBuilder().build());
+ ordering_gate.onProposal(proposal1);
+ ordering_gate.onProposal(proposal2);
ASSERT_TRUE(wrapper_before.validate());
|
codereview_cpp_data_12916
|
applyForceToPoint(s, *_body, lpoint, forceVec, bodyForces);
// get the velocity of the actuator in ground
- Vec3 velocity(0);
- velocity = _body->findVelocityInGround(s, lpoint);
// the speed of the point is the "speed" of the actuator used to compute
// power
Simply `Vec3 velocity = _body->findVelocityInGround(s, lpoint);`?
applyForceToPoint(s, *_body, lpoint, forceVec, bodyForces);
// get the velocity of the actuator in ground
+ Vec3 velocity = _body->findVelocityInGround(s, lpoint);
// the speed of the point is the "speed" of the actuator used to compute
// power
|
codereview_cpp_data_12924
|
typename sofa::component::forcefield::TetrahedronHyperelasticityFEMForceField<DataTypes>::SPtr FF = sofa::core::objectmodel::New< sofa::component::forcefield::TetrahedronHyperelasticityFEMForceField<DataTypes> >();
sofa::helper::vector<Real> param_vector;
param_vector.resize(3);
- param_vector[0] = 151065.460; //C01
- param_vector[1] = 101709.668; //C10
- param_vector[2] = 1e07; //K0
hyperelasticNode->addObject(FF);
FF->setName("FEM");
Not a big fan of magic numbers. Could we use some constants here?
typename sofa::component::forcefield::TetrahedronHyperelasticityFEMForceField<DataTypes>::SPtr FF = sofa::core::objectmodel::New< sofa::component::forcefield::TetrahedronHyperelasticityFEMForceField<DataTypes> >();
sofa::helper::vector<Real> param_vector;
param_vector.resize(3);
+ // Experimental data gave a deflexion of y=-0.11625 with the following parameters (C01 = 151065.460 ; C10 = 101709.668 1e07 ; D0 = 1e07)
+ param_vector[0] = 151065.460; // Monney parameter C01
+ param_vector[1] = 101709.668; // Monney parameter C10
+ param_vector[2] = 1e07; // Monney parameter K0
hyperelasticNode->addObject(FF);
FF->setName("FEM");
|
codereview_cpp_data_12930
|
Army & bestHeroArmy = humanKingdom.GetBestHero()->GetArmy();
bestHeroArmy.Clean();
- for ( uint32_t j = 0; j < carryOverTroops.size(); ++j )
- bestHeroArmy.GetTroop( j )->Set( carryOverTroops[j] );
break;
}
Could we please use `troopId` instead of `j` to have more readable code?
Army & bestHeroArmy = humanKingdom.GetBestHero()->GetArmy();
bestHeroArmy.Clean();
+ for ( uint32_t troopID = 0; troopID < carryOverTroops.size(); ++troopID )
+ bestHeroArmy.GetTroop( troopID )->Set( carryOverTroops[troopID] );
break;
}
|
codereview_cpp_data_12944
|
#include <hip/hip_runtime.h>
#ifdef __HIP_PLATFORM_HCC__
-#include <elf.h>
#endif
#include <sys/time.h>
I think this include is also not required. We should be able to remove it.
#include <hip/hip_runtime.h>
#ifdef __HIP_PLATFORM_HCC__
#endif
#include <sys/time.h>
|
codereview_cpp_data_12948
|
void KimInteractions::do_setup(int narg, char **arg)
{
- static bool kim_update=0;
bool fixed_types;
const std::string arg_str(arg[0]);
if ((narg == 1) && (arg_str == "fixed_types")) {
Using a static variable for this is a bad idea, since this is single and global storage instance and not a per-LAMMPS instance for information that is a per-LAMMPS instance information. It will thus give the wrong behavior if multiple LAMMPS instances are used either concurrently or consecutively (as people do regularly when using the python interface) and it will not be reset to 0 as needed if the "clear" command is issued. You get the desired behavior by using and extending fix STORE/KIM. which was designed to hold per-instance data. The fix will be created per-instance and will be deleted when the clear command is issued.
void KimInteractions::do_setup(int narg, char **arg)
{
bool fixed_types;
const std::string arg_str(arg[0]);
if ((narg == 1) && (arg_str == "fixed_types")) {
|
codereview_cpp_data_12952
|
const std::vector<WeightsType*>& other_layer_weights =
dynamic_cast<data_type_layer<TensorDataType>*>(other_layer)->get_data_type_weights();
for (size_t i = 0; i < m_weights.size(); ++i) {
- if (m_weights[i] == nullptr) {
- continue;
}
- m_weights[i]->set_values(other_layer_weights[i]->get_values());
}
}
```suggestion if (m_weights[i]) { m_weights[i]->set_values(other_layer_weights[i]->get_values()); } ```
const std::vector<WeightsType*>& other_layer_weights =
dynamic_cast<data_type_layer<TensorDataType>*>(other_layer)->get_data_type_weights();
for (size_t i = 0; i < m_weights.size(); ++i) {
+ if (m_weights[i]) {
+ m_weights[i]->set_values(other_layer_weights[i]->get_values());
}
}
}
|
codereview_cpp_data_12956
|
}
if (i->type != FILENODE) // Only file nodes have size
{
- return nodeNaturalComparatorDESC(i, j);
}
m_off_t r = i->size - j->size;
Why descendant? I think it's more appropriate to have an ascending sorting for folders when sorting by size.
}
if (i->type != FILENODE) // Only file nodes have size
{
+ return nodeNaturalComparatorASC(i, j);
}
m_off_t r = i->size - j->size;
|
codereview_cpp_data_12967
|
int Game::StartGame( void )
{
AI::Get().Reset();
// cursor
This function was being called only in this place. Shall we then remove it?
int Game::StartGame( void )
{
+ SetFixVideoMode();
AI::Get().Reset();
// cursor
|
codereview_cpp_data_12970
|
if (auto dirs = caf::get_if<std::vector<std::string>>( //
&cfg, "vast.plugin-dirs"))
result.insert(dirs->begin(), dirs->end());
- if (auto dirs = caf::get_if<std::vector<std::string>>( //
- &cfg, "vast.plugin-paths")) {
- VAST_WARNING_ANON(__func__, "encountered deprecated vast.plugin-paths "
- "option; use vast.plugin-dirs instead.");
- result.insert(dirs->begin(), dirs->end());
- }
return result;
}
Since we haven't release the plugin API yet, I think we can avoid jumping through the hoop here.
if (auto dirs = caf::get_if<std::vector<std::string>>( //
&cfg, "vast.plugin-dirs"))
result.insert(dirs->begin(), dirs->end());
return result;
}
|
codereview_cpp_data_12978
|
{
CompanyID cid = company->index;
- if (cid == _local_company) SetWindowWidgetDirty(WC_STATUS_BAR, 0, 2);
SetWindowDirty(WC_FINANCES, cid);
}
should this be `WID_S_RIGHT` instead of `2`? (honest question, magic numbers scare me, but I don't know this window system good enough)
{
CompanyID cid = company->index;
+ if (cid == _local_company) SetWindowWidgetDirty(WC_STATUS_BAR, 0, WID_S_RIGHT);
SetWindowDirty(WC_FINANCES, cid);
}
|
codereview_cpp_data_12980
|
sct_list.data = s2n_stuffer_raw_read(extension, sct_list.size);
notnull_check(sct_list.data);
- GUARD(s2n_alloc(&conn->ct_response, sct_list.size));
- memcpy_check(conn->ct_response.data, sct_list.data, sct_list.size);
- conn->ct_response.size = sct_list.size;
return 0;
}
You should be able to replace these 3 lines with `s2n_dup(&sct_list, &conn->ct_response);`
sct_list.data = s2n_stuffer_raw_read(extension, sct_list.size);
notnull_check(sct_list.data);
+ GUARD(s2n_dup(&sct_list, &conn->ct_response));
return 0;
}
|
codereview_cpp_data_12986
|
// verify that yac gate emit expected block
auto gate_wrapper = make_test_subscriber<CallExact>(gate->onOutcome(), 1);
gate_wrapper.subscribe([actual_hash, actual_pubkey](auto outcome) {
- auto concete_outcome = boost::get<iroha::consensus::VoteOther>(outcome);
- auto public_keys = concete_outcome.public_keys;
- auto hash = concete_outcome.hash;
ASSERT_EQ(1, public_keys.size());
ASSERT_EQ(actual_pubkey, public_keys.front());
typo in variable name?
// verify that yac gate emit expected block
auto gate_wrapper = make_test_subscriber<CallExact>(gate->onOutcome(), 1);
gate_wrapper.subscribe([actual_hash, actual_pubkey](auto outcome) {
+ auto concrete_outcome = boost::get<iroha::consensus::VoteOther>(outcome);
+ auto public_keys = concrete_outcome.public_keys;
+ auto hash = concrete_outcome.hash;
ASSERT_EQ(1, public_keys.size());
ASSERT_EQ(actual_pubkey, public_keys.front());
|
codereview_cpp_data_12989
|
}
if (pbs.size() > 4) {
- ae_proxy_model = build_model_from_prototext(argc, argv, *(pbs[4]),
comm, false);
}
I'm unsure if this will do what we're expecting. Every layer overwrites its activations during its forward prop step, so I suspect that the copies done here will be overwritten when `evaluate` is called.
}
if (pbs.size() > 4) {
+ ae_cycgan_model = build_model_from_prototext(argc, argv, *(pbs[4]),
comm, false);
}
|
codereview_cpp_data_13009
|
bool Servatrice_DatabaseInterface::usernameIsValid(const QString &user)
{
- static QRegExp re = QRegExp("[a-zA-Z0-9_\.-]+");
return re.exactMatch(user);
}
Are you sure you need to escape `.` here?
bool Servatrice_DatabaseInterface::usernameIsValid(const QString &user)
{
+ static QRegExp re = QRegExp("[a-zA-Z0-9_\\.-]+");
return re.exactMatch(user);
}
|
codereview_cpp_data_13024
|
/* XXX: right now we don't have a good solution for this:
* https://github.com/projectatomic/rpm-ostree/issues/40 */
- rpmostree_output_message ("WARNING: changes to /etc will not appear in the pending deployment (next reboot)");
/* Write out the origin as having completed this */
if (!write_livefs_state (sysroot, booted_deployment, NULL, target_csum, error))
still seems ambiguous `WARNING: new changes to /etc will not appear in the pending deployment (i.e. will be lost on next reboot)`
/* XXX: right now we don't have a good solution for this:
* https://github.com/projectatomic/rpm-ostree/issues/40 */
+ rpmostree_output_message ("WARNING: any changes to /etc will be lost on next reboot");
/* Write out the origin as having completed this */
if (!write_livefs_state (sysroot, booted_deployment, NULL, target_csum, error))
|
codereview_cpp_data_13029
|
if (dstbag)
dstbagid = dstbag->GetItem()->ID;
}
- if ((srcbagid && srcbag->GetItem()->BagType == EQ::item::BagTypeTradersSatchel) || (dstbagid && dstbag->GetItem()->BagType == EQ::item::BagTypeTradersSatchel) || (srcitemid && src_inst->GetItem()->BagType == EQ::item::BagTypeTradersSatchel) || (dstitemid && dst_inst->GetItem()->BagType == EQ::item::BagTypeTradersSatchel)){
this->Trader_EndTrader();
this->Message(Chat::Red,"You cannot move your Trader Satchels, or items inside them, while Trading.");
}
Breaking each OR condition into a separate line would make this more readable ```cpp if ((srcbagid && srcbag->GetItem()->BagType == EQ::item::BagTypeTradersSatchel) || (dstbagid && dstbag->GetItem()->BagType == EQ::item::BagTypeTradersSatchel) || (srcitemid && src_inst->GetItem()->BagType == EQ::item::BagTypeTradersSatchel) || (dstitemid && dst_inst->GetItem()->BagType == EQ::item::BagTypeTradersSatchel)) { ```
if (dstbag)
dstbagid = dstbag->GetItem()->ID;
}
+ if ((srcbagid && srcbag->GetItem()->BagType == EQ::item::BagTypeTradersSatchel) ||
+ (dstbagid && dstbag->GetItem()->BagType == EQ::item::BagTypeTradersSatchel) ||
+ (srcitemid && src_inst->GetItem()->BagType == EQ::item::BagTypeTradersSatchel) ||
+ (dstitemid && dst_inst->GetItem()->BagType == EQ::item::BagTypeTradersSatchel)) {
this->Trader_EndTrader();
this->Message(Chat::Red,"You cannot move your Trader Satchels, or items inside them, while Trading.");
}
|
codereview_cpp_data_13030
|
const iMultiFab& dmsk = *m_dirichlet_mask[amrlev][mglev];
- bool regular_coarsening = true;
- if (amrlev == 0 and mglev > 0) {
- regular_coarsening = mg_coarsen_ratio_vec[mglev-1] == mg_coarsen_ratio;
- }
-
#ifdef AMREX_USE_GPU
if (Gpu::inLaunchRegion())
{
This is used in a lot of places now. Maybe we can put it in function say `bool is_regular_coarsening(amrlev, fine_mglev)`.
const iMultiFab& dmsk = *m_dirichlet_mask[amrlev][mglev];
#ifdef AMREX_USE_GPU
if (Gpu::inLaunchRegion())
{
|
codereview_cpp_data_13043
|
return;
}
- mThread = std::thread ([this]() {
auto localpath = LocalPath::fromPath(transfer->getPath(), *client->fsaccess);
scanFolder(transfer->getParentHandle(), transfer->getParentHandle(), localpath, transfer->getFileName());
createFolder();
});
- mThread.detach();
}
void MegaFolderUploadController::cancel()
I think it would be easier to read if the `wait()` after createFolder and the call to `uploadFiles()` were all in the lambda for the thread.
return;
}
+ std::thread thread([this]() {
auto localpath = LocalPath::fromPath(transfer->getPath(), *client->fsaccess);
scanFolder(transfer->getParentHandle(), transfer->getParentHandle(), localpath, transfer->getFileName());
createFolder();
});
+ thread.detach();
}
void MegaFolderUploadController::cancel()
|
codereview_cpp_data_13044
|
vString *name = vStringNew ();
/* Found Autocommand Group (augroup) */
- const unsigned char *cp = skipWord (line);
if (isspace ((int) *cp))
{
while (*cp && isspace ((int) *cp))
The use of `skipWord` here skips also `[aug]roupfoobar`, while previously only `[aug]group` would get handled. Same for `parseFunction`. `skipWord` probably needs to get told about what it is allowed to skip?!
vString *name = vStringNew ();
/* Found Autocommand Group (augroup) */
+ const unsigned char *cp = line;
if (isspace ((int) *cp))
{
while (*cp && isspace ((int) *cp))
|
codereview_cpp_data_13047
|
/**
* Delete the MatchSet structure in a safe way.
*/
-struct DeleteMatches
{
- DeleteMatches(MatchSet& ms) : _ms(ms) {}
- ~DeleteMatches()
{
foreach (const Match* m, _ms)
{
This looks like a memory leak to me, particularly since the vector is passed to the constructor by value. If it's passed by ref (as above) ... it might work (I'm a little skeptical, but I'll believe if you say it works!) I would recommend calling these structs something like ScopedMatchDeleter & ScopedMergerDeleter, to make their function a little more clear. Or... maybe just use a vector of shared pointers?
/**
* Delete the MatchSet structure in a safe way.
*/
+struct ScopedMatchDeleter
{
+ ScopedMatchDeleter(MatchSet& ms) : _ms(ms) {}
+ ~ScopedMatchDeleter()
{
foreach (const Match* m, _ms)
{
|
codereview_cpp_data_13049
|
*/
static kdb_unsigned_short_t elektraCryptoGetRandomPasswordLength (KeySet * conf)
{
- Key * k = ksLookupByName (conf, ELEKTRA_CRYPTO_PARAM_MASTER_PWD_LEN, 0);
if (k && keyIsString (k) > 0)
{
const char * value = keyString (k);
again: silent ignoring of wrong values.
*/
static kdb_unsigned_short_t elektraCryptoGetRandomPasswordLength (KeySet * conf)
{
+ Key * k = ksLookupByName (conf, ELEKTRA_CRYPTO_PARAM_MASTER_PASSWORD_LEN, 0);
if (k && keyIsString (k) > 0)
{
const char * value = keyString (k);
|
codereview_cpp_data_13060
|
"<exec cmd=\"!DumpIL /i %s\">%s</exec>", // DML_IL
"<exec cmd=\"!DumpRCW -cw /d %s\">%s</exec>", // DML_ComWrapperRCW
"<exec cmd=\"!DumpCCW -cw /d %s\">%s</exec>", // DML_ComWrapperCCW
- "<exec cmd=\"dps %s L2\">%s</exec>", // DML_TaggedMemory (hardcoded current size to 2 pointer sizes)
};
void ConvertToLower(__out_ecount(len) char *buffer, size_t len)
Is there any way to not hardcode this given we know the size in bytes? The public API has the flexibility of being a Span. Should we maybe not do anything printing DML? The runtime allocates the buffer, but it's a "scratch memory" area, The delegate gets it passed in and they decide how to use it. Also, how is DML used if the feature is for macOS support?
"<exec cmd=\"!DumpIL /i %s\">%s</exec>", // DML_IL
"<exec cmd=\"!DumpRCW -cw /d %s\">%s</exec>", // DML_ComWrapperRCW
"<exec cmd=\"!DumpCCW -cw /d %s\">%s</exec>", // DML_ComWrapperCCW
+ "<exec cmd=\"dps %s L%d\">%s</exec>", // DML_TaggedMemory
};
void ConvertToLower(__out_ecount(len) char *buffer, size_t len)
|
codereview_cpp_data_13067
|
if(dir.back() == Pathname::getPathSeparator().back())
dirsToSearch.push_back(dir);
else
- dirsToSearch.push_back(dir + "/");
}
// Call this on a newly-constructed ModelVisualizer (typically from the Model's
Would OpenSim::Path handle that?
if(dir.back() == Pathname::getPathSeparator().back())
dirsToSearch.push_back(dir);
else
+ dirsToSearch.push_back(dir + Pathname::getPathSeparator());
}
// Call this on a newly-constructed ModelVisualizer (typically from the Model's
|
codereview_cpp_data_13078
|
"@endtsexample\n\n"
"@ingroup Strings" )
{
- char *str = (char *)str1;
- if( str )
{
// skip over any characters that are a member of delim
// no need for special '\0' check since it can never be in delim
I think remove a `const` is a very bad idea :( even if internal code of TS binding make this safe. Better preserve old code and copy to local buffer.
"@endtsexample\n\n"
"@ingroup Strings" )
{
+ char buffer[4096];
+ dStrncpy(buffer, str1, 4096);
+ char *str = buffer;
+
+ if( str[0] )
{
// skip over any characters that are a member of delim
// no need for special '\0' check since it can never be in delim
|
codereview_cpp_data_13091
|
return true;
}
- // TODO: add as a field, add as a constructor parameter, init field from
- // parameter in constructor, add at the call site
ast_t* type = alias(ast_type(refdef));
if(is_typecheck_error(type))
does this TODO need to be handled before merging? Should we create an issue for it?
return true;
}
ast_t* type = alias(ast_type(refdef));
if(is_typecheck_error(type))
|
codereview_cpp_data_13095
|
struct flbgo_output_plugin *plugin;
plugin = (struct flbgo_output_plugin *) inst;
- flb_warn("[GO] running exit callback");
- plugin->cb_exit(context->remote_context);
}
static int flb_proxy_register_output(struct flb_plugin_proxy *proxy,
this could probably be debug
struct flbgo_output_plugin *plugin;
plugin = (struct flbgo_output_plugin *) inst;
+ flb_debug("[GO] running exit callback");
+ plugin->cb_exit();
}
static int flb_proxy_register_output(struct flb_plugin_proxy *proxy,
|
codereview_cpp_data_13096
|
add_overlay("bombarding.png");
}
- // Moving fleets can't be gifted.
if (fleet->OrderedGivenToEmpire() != ALL_EMPIRES && fleet->TravelRoute().empty())
add_overlay("gifting.png");
this doesn't make sense... if the situation somehow arises that a moving fleet is being gifted, it should be displayed. enforcing such a rule should be done where the gifting order is issued and where it is executed, not just when displaying the indicator.
add_overlay("bombarding.png");
}
+ // Moving fleets can't be gifted. The order will be automatically
+ // cancelled on the server. This make the UI appear to cancel the
+ // order when the ship is moved without requiring the player to
+ // re-order the gifting if the ship is stopped.
if (fleet->OrderedGivenToEmpire() != ALL_EMPIRES && fleet->TravelRoute().empty())
add_overlay("gifting.png");
|
codereview_cpp_data_13100
|
void Transpose( const Image & in, Image & out )
{
- assert( !in.empty() );
assert( !out.empty() );
- assert( in.width() == out.height() && in.height() == out.width() );
const int32_t width = in.width();
const int32_t height = in.height();
In this case we can't catch any issues in release mode. What's the benefit doing this in debug build only? Also there could be cases when some images could be missing (due to pirated version of the game) and if we do this we're allowing unexpected behavior on user's systems.
void Transpose( const Image & in, Image & out )
{
assert( !out.empty() );
+ if ( in.empty() || in.width() != out.height() || in.height() != out.width() ) {
+ out.reset();
+ return;
+ }
const int32_t width = in.width();
const int32_t height = in.height();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.