id
stringlengths 21
25
| content
stringlengths 164
2.33k
|
|---|---|
codereview_cpp_data_11636
|
if (n_runnable_jobs >= n_not_excluded
&& queue_est > (gstate.work_buf_min() * n_not_excluded)/rwf.ninstances
) {
- printf("%s: setting reason to BUFFER_FULL\n", p->project_name);
return RSC_REASON_BUFFER_FULL;
}
}
This looks like debug message and should be put behind debug flag or if it's leftover from debugging session just removed.
if (n_runnable_jobs >= n_not_excluded
&& queue_est > (gstate.work_buf_min() * n_not_excluded)/rwf.ninstances
) {
+ if (log_flags.work_fetch_debug) {
+ printf("%s: setting reason to BUFFER_FULL\n", p->project_name);
+ }
return RSC_REASON_BUFFER_FULL;
}
}
|
codereview_cpp_data_11642
|
h2o_configurator_define_command(&c->super, "proxy.emit-x-forwarded-headers",
H2O_CONFIGURATOR_FLAG_GLOBAL | H2O_CONFIGURATOR_FLAG_EXPECT_SCALAR,
on_config_emit_x_forwarded_headers);
-#define DEFINE_CMD(name, cb) \
- h2o_configurator_define_command(&c->super, name, H2O_CONFIGURATOR_FLAG_ALL_LEVELS | H2O_CONFIGURATOR_FLAG_EXPECT_SCALAR, cb)
- DEFINE_CMD("proxy.header.add", on_config_header_add);
- DEFINE_CMD("proxy.header.append", on_config_header_append);
- DEFINE_CMD("proxy.header.merge", on_config_header_merge);
- DEFINE_CMD("proxy.header.set", on_config_header_set);
- DEFINE_CMD("proxy.header.setifempty", on_config_header_setifempty);
- DEFINE_CMD("proxy.header.unset", on_config_header_unset);
-#undef DEFINE_CMD
}
How about creating a function that adds various favors (e.g. `add`, `append`, ...) in lib/handler/configurator/util.c, instead of adding `h2o_on_config_header_2arg` and using macro to create variations in each source file. E.g., How aboutcreating a function that looks something like `h2o_configurator_define_headers_commands(h2o_configurator_t *conf, const char *prefix, h2o_headers_commands_t *(*get_commands)(h2o_configurator_t *))`, and call it here like: ```c h2o_configurator_define_headers_comands(&c->super, "proxy.header", get_commands); ``` The invocation would define all the `proxy.header.*` directives. `get_commands` function could be defined as: ```c static h2o_headers_commands_t *get_commands(h2o_configurator_t *conf) { struct proxy_configurator_t *self = (void *)cmd->configurator; return &self->vars->header_cmds; } ``` The merits of using this approach would be that the code will become less redundant, and that new directives that modifies the header modification commands can be added just be changing one place.
h2o_configurator_define_command(&c->super, "proxy.emit-x-forwarded-headers",
H2O_CONFIGURATOR_FLAG_GLOBAL | H2O_CONFIGURATOR_FLAG_EXPECT_SCALAR,
on_config_emit_x_forwarded_headers);
+ h2o_configurator_define_headers_commands(conf, &c->super, "proxy.header", get_headers_commands);
}
|
codereview_cpp_data_11643
|
delete stringMap;
}
-void MegaApiImpl::getUsersAliases(MegaRequestListener *listener)
-{
- MegaRequestPrivate *request = new MegaRequestPrivate(MegaRequest::TYPE_GET_ATTR_USER, listener);
- request->setParamType(MegaApi::USER_ATTR_ALIAS);
- requestQueue.push(request);
- waiter->notify();
-}
-
void MegaApiImpl::getUserAlias(MegaHandle uh, MegaRequestListener *listener)
{
MegaRequestPrivate *request = new MegaRequestPrivate(MegaRequest::TYPE_GET_ATTR_USER, listener);
For new usages of `btoa` we should be using the new methods prepared by Matt: `Base64Str` It would be something like: ```request->setText(Base64Str<MegaClient::USERHANDLE>(uh));```
delete stringMap;
}
void MegaApiImpl::getUserAlias(MegaHandle uh, MegaRequestListener *listener)
{
MegaRequestPrivate *request = new MegaRequestPrivate(MegaRequest::TYPE_GET_ATTR_USER, listener);
|
codereview_cpp_data_11650
|
#include "testlib/s2n_testlib.h"
-S2N_RESULT s2n_validate_negotiate_result(int result, bool peer_is_done, bool *is_done)
{
/* If we succeeded, we're done. */
- if(result == S2N_SUCCESS) {
*is_done = true;
return S2N_RESULT_OK;
}
Shouldn't this still be static?
#include "testlib/s2n_testlib.h"
+static S2N_RESULT s2n_validate_negotiate_result(bool success, bool peer_is_done, bool *is_done)
{
/* If we succeeded, we're done. */
+ if(success) {
*is_done = true;
return S2N_RESULT_OK;
}
|
codereview_cpp_data_11656
|
* To construct a max heap the comparison function VheapComp (a, b), must return
* 1 on a > b and 0 otherwise. For a min heap 1 on a < b and 0 otherwise.
*
- *
* @param comp the comparison function of the heap
* @param minSize the minimum size of the heap
* @return a Vheap pointer
Maybe we can add a group "Internal Datastructures" and vheap, vstack and trie are subgroups?
* To construct a max heap the comparison function VheapComp (a, b), must return
* 1 on a > b and 0 otherwise. For a min heap 1 on a < b and 0 otherwise.
*
+ * @ingroup vheap
* @param comp the comparison function of the heap
* @param minSize the minimum size of the heap
* @return a Vheap pointer
|
codereview_cpp_data_11679
|
bool transactions = (numDetails & 0x08) != 0;
bool purchases = (numDetails & 0x10) != 0;
bool sessions = (numDetails & 0x20) != 0;
- request->setNumber(numDetails); // allow client to know which flags were used
-
- numDetails = 1;
- if(transactions) numDetails++;
- if(purchases) numDetails++;
- if(sessions) numDetails++;
- request->setNumDetails(numDetails);
client->getaccountdetails(request->getAccountDetails(), storage, transfer, pro, transactions, purchases, sessions);
break;
Rather than copy the `flags` in the `MegaRequest::number` and replace the existing value in `Request::numDetails`, I suggest to keep the flags in the expected member and use the `number` internally to control the number of flags received.
bool transactions = (numDetails & 0x08) != 0;
bool purchases = (numDetails & 0x10) != 0;
bool sessions = (numDetails & 0x20) != 0;
+ int numReqs = int(storage || transfer || pro) + int(transactions) + int(purchases) + int(sessions);
+ request->setNumber(numReqs);
client->getaccountdetails(request->getAccountDetails(), storage, transfer, pro, transactions, purchases, sessions);
break;
|
codereview_cpp_data_11683
|
else if (strcmpi(w1, "start_point_re") == 0) {
char map[MAP_NAME_LENGTH_EXT];
int x, y;
- if (sscanf(w2, "%15[^,], %d, %d", map, &x, &y) < 3)
continue;
start_point.map = mapindex->name2id(map);
if (!start_point.map)
Why adding spaces here and in second sscanf?
else if (strcmpi(w1, "start_point_re") == 0) {
char map[MAP_NAME_LENGTH_EXT];
int x, y;
+ if (sscanf(w2, "%15[^,],%d,%d", map, &x, &y) < 3)
continue;
start_point.map = mapindex->name2id(map);
if (!start_point.map)
|
codereview_cpp_data_11688
|
}
hit = random(68, 100);
- hper = 90 - (unsigned char)monster[m].mArmorClass - dist;
if (hper < 5)
hper = 5;
if (hper > 95)
```suggestion hper = 90 - (BYTE)monster[m].mArmorClass - dist; ```
}
hit = random(68, 100);
+ hper = 90 - (BYTE)monster[m].mArmorClass - dist;
if (hper < 5)
hper = 5;
if (hper > 95)
|
codereview_cpp_data_11692
|
EXPECT_FAILURE_WITH_ERRNO(s2n_negotiate_test_server_and_client(server_conn, client_conn),
S2N_ERR_BAD_MESSAGE);
- /* Read the remaining early data properly */
server_conn->closed = false;
client_conn->closed = false;
EXPECT_SUCCESS(s2n_recv_early_data(server_conn, actual_payload, sizeof(actual_payload),
&data_size, &blocked));
This seems like an issue no? If we can't continue to read early data without changing the conn->closed value? Is the user expected to change these values?
EXPECT_FAILURE_WITH_ERRNO(s2n_negotiate_test_server_and_client(server_conn, client_conn),
S2N_ERR_BAD_MESSAGE);
+ /* Pretend we didn't test the above error condition.
+ * The S2N_ERR_BAD_MESSAGE error triggered S2N to close the connection. */
server_conn->closed = false;
client_conn->closed = false;
+
+ /* Read the remaining early data properly */
EXPECT_SUCCESS(s2n_recv_early_data(server_conn, actual_payload, sizeof(actual_payload),
&data_size, &blocked));
|
codereview_cpp_data_11693
|
label_idx_ = 0;
weight_idx_ = NO_SPECIFIC;
group_idx_ = NO_SPECIFIC;
- if (filename != nullptr && CheckCanLoadFromBin(filename) == "") {
- // SetHeader should only be called when loading from text file
- SetHeader(filename);
- }
store_raw_ = false;
if (io_config.linear_tree) {
store_raw_ = true;
The testing cases are failing because `SetHeader` does not only handle cases where input are from files. It also reads categorical feature indices from the config parameters (see the part outside the `if (filename != nullptr) { ... }`). Skipping `SetHeader` directly here will cause errors when we load data from numpy or pandas arrays (where `filename == nullptr`) and use categorical features. So I think we should move the the check `filename != nullptr && CheckCanLoadFromBin(filename) == ""` into `SetHeader`. That is, we change `if (filename != nullptr) { ... }` into `if (filename != nullptr && CheckCanLoadFromBin(filename) == "") { ... }`
label_idx_ = 0;
weight_idx_ = NO_SPECIFIC;
group_idx_ = NO_SPECIFIC;
+ SetHeader(filename);
store_raw_ = false;
if (io_config.linear_tree) {
store_raw_ = true;
|
codereview_cpp_data_11705
|
}
sofa::helper::AdvancedTimer::stepEnd("UpdateMapping");
-#if SOFA_NO_UPDATE_BBOX == 0
{
sofa::helper::ScopedAdvancedTimer timer("UpdateBBox");
gnode->execute< UpdateBoundingBoxVisitor >(params);
}
-#endif
#ifdef SOFA_DUMP_VISITOR_INFO
simulation::Visitor::printCloseNode("Step");
Hi alex, If possible, the rules is to do as much as possible ```cpp if(SOFA_NO_UPDATE_BBOX) { .... } ``` The rational behind is that the conditional content is still compiled (eg: in the CI) so this ease maintenance and code refactoring while the compiler's optimizer can strip-out the if() when it is false.
}
sofa::helper::AdvancedTimer::stepEnd("UpdateMapping");
+ if (!SOFA_NO_UPDATE_BBOX)
{
sofa::helper::ScopedAdvancedTimer timer("UpdateBBox");
gnode->execute< UpdateBoundingBoxVisitor >(params);
}
#ifdef SOFA_DUMP_VISITOR_INFO
simulation::Visitor::printCloseNode("Step");
|
codereview_cpp_data_11710
|
// TODO: 31.10.2017 luckychess move tx3hash case into a separate test after
// ametsuchi_test redesign
- auto tx1hash = txs[0].hash();
- auto tx2hash = txs[1].hash();
auto tx3hash = shared_model::crypto::Hash("some garbage");
auto tx1 = blocks->getTxByHashSync(tx1hash);
It is probably more safe to use `.at()` since it will throw if someone will modify test without noticing.
// TODO: 31.10.2017 luckychess move tx3hash case into a separate test after
// ametsuchi_test redesign
+ auto tx1hash = txs.at(0).hash();
+ auto tx2hash = txs.at(1).hash();
auto tx3hash = shared_model::crypto::Hash("some garbage");
auto tx1 = blocks->getTxByHashSync(tx1hash);
|
codereview_cpp_data_11721
|
#include "lbann/utils/summary.hpp"
#include <lbann/utils/image.hpp>
-#include <lbann/utils/opencv.hpp>
namespace lbann {
```suggestion ``` I don't see any OpenCV calls in this file, so we shouldn't need this header. It will make it easier to make OpenCV an optional dependency.
#include "lbann/utils/summary.hpp"
#include <lbann/utils/image.hpp>
namespace lbann {
|
codereview_cpp_data_11732
|
rhs == llvm::Triple::UnknownEnvironment)
return true;
- // If any of the environment is unknown then they are compatible
- if (lhs == llvm::Triple::UnknownEnvironment ||
- rhs == llvm::Triple::UnknownEnvironment)
- return true;
-
// If one of the environment is Android and the other one is EABI then they
// are considered to be compatible. This is required as a workaround for
// shared libraries compiled for Android without the NOTE section indicating
This condition is duplicated with the above code.
rhs == llvm::Triple::UnknownEnvironment)
return true;
// If one of the environment is Android and the other one is EABI then they
// are considered to be compatible. This is required as a workaround for
// shared libraries compiled for Android without the NOTE section indicating
|
codereview_cpp_data_11737
|
network_address, async_call);
ordering_service_transport =
- std::make_shared<ordering::OrderingServiceTransportGrpc>(async_call);
ordering_service = createService(wsv,
max_size,
delay_milliseconds,
Consider moving the `async-call`, as it's the last time you use it here
network_address, async_call);
ordering_service_transport =
+ std::make_shared<ordering::OrderingServiceTransportGrpc>(
+ std::move(async_call));
ordering_service = createService(wsv,
max_size,
delay_milliseconds,
|
codereview_cpp_data_11749
|
l_topology.set(this->getContext()->getMeshTopology());
}
- _topology = l_topology.get();
- if(_topology){
msg_error(this) << "Unable to retreive a valid MeshTopology component in the current context. \n"
"The component cannot be initialized and thus is de-activated. \n "
"To supress this warning you can add a Topology component in the parent node of'<"<< this->getName() <<">'.\n" ;
don't you want to change `_topology` into `m_topology`
l_topology.set(this->getContext()->getMeshTopology());
}
+ m_topology = l_topology.get();
+ if(m_topology){
msg_error(this) << "Unable to retreive a valid MeshTopology component in the current context. \n"
"The component cannot be initialized and thus is de-activated. \n "
"To supress this warning you can add a Topology component in the parent node of'<"<< this->getName() <<">'.\n" ;
|
codereview_cpp_data_11754
|
SetMissDir(mi, GetDirection16(sx, sy, dx, dy));
#ifdef HELLFIRE
if (missile[mi]._mixvel & 0xFFFF0000 || missile[mi]._miyvel & 0xFFFF0000)
-#endif
missile[mi]._mirange = 5 * (monster[id]._mint + 4);
-#ifdef HELLFIRE
else
missile[mi]._mirange = 1;
#endif
missile[mi]._mlid = -1;
missile[mi]._miVar1 = sx;
Again I think `#else` is better for this
SetMissDir(mi, GetDirection16(sx, sy, dx, dy));
#ifdef HELLFIRE
if (missile[mi]._mixvel & 0xFFFF0000 || missile[mi]._miyvel & 0xFFFF0000)
missile[mi]._mirange = 5 * (monster[id]._mint + 4);
else
missile[mi]._mirange = 1;
+#else
+ missile[mi]._mirange = 5 * (monster[id]._mint + 4);
#endif
missile[mi]._mlid = -1;
missile[mi]._miVar1 = sx;
|
codereview_cpp_data_11766
|
#include <fstream>
#include <regex>
-#include "../../core/vendor/json/src/json.hpp"
using json = nlohmann::json;
Change back to ``` #include <vendor/json/src/json.hpp> ``` Don't forget to add ``` include_directories( ${PROJECT_SOURCE_DIR}/core ) ``` into local CMakeLists.txt
#include <fstream>
#include <regex>
+#include <vendor/json/src/json.hpp>
using json = nlohmann::json;
|
codereview_cpp_data_11767
|
// This space intentionally left blank
}
-void IndexElementsVisitor::setOsmMap(OsmMap* map)
-{
- // Do nothing with this map. We want to conform to the interface,
- // but prefer to use the ptr supplied in the constructor
- (void) map;
-}
-
void IndexElementsVisitor::visit(const ConstElementPtr& e)
{
if (!_filter || _filter->isSatisfied(e))
This kinda violates the interface, doesn't it? Why not have `_pMap = map->shared_from_this();` in setOsmMap? Does this break something else in the class?
// This space intentionally left blank
}
void IndexElementsVisitor::visit(const ConstElementPtr& e)
{
if (!_filter || _filter->isSatisfied(e))
|
codereview_cpp_data_11775
|
SQLDO("CREATE UNIQUE INDEX `%1channel_info_id` ON `%1channel_info`(`server_id`, `channel_id`, `key`)");
SQLDO("CREATE TRIGGER `%1channel_info_del_channel` AFTER DELETE on `%1channels` FOR EACH ROW BEGIN DELETE FROM `%1channel_info` WHERE `channel_id` = old.`channel_id` AND `server_id` = old.`server_id`; END;");
- SQLDO("CREATE TABLE `%1users` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `pw` TEXT, `salt` TEXT, `kdfmeter` INTEGER, `lastchannel` INTEGER, `texture` BLOB, `last_active` DATE)");
SQLDO("CREATE UNIQUE INDEX `%1users_name` ON `%1users` (`server_id`,`name`)");
SQLDO("CREATE UNIQUE INDEX `%1users_id` ON `%1users` (`server_id`, `user_id`)");
SQLDO("CREATE TRIGGER `%1users_server_del` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM `%1users` WHERE `server_id` = old.`server_id`; END;");
Shouldn't `kdfmeter` just be called `kdfiter`? That'd make it fit better in with our C++ naming. (Also, s/kdfmeter/kdfiter/g?)
SQLDO("CREATE UNIQUE INDEX `%1channel_info_id` ON `%1channel_info`(`server_id`, `channel_id`, `key`)");
SQLDO("CREATE TRIGGER `%1channel_info_del_channel` AFTER DELETE on `%1channels` FOR EACH ROW BEGIN DELETE FROM `%1channel_info` WHERE `channel_id` = old.`channel_id` AND `server_id` = old.`server_id`; END;");
+ SQLDO("CREATE TABLE `%1users` (`server_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `pw` TEXT, `salt` TEXT, `kdfiterations` INTEGER, `lastchannel` INTEGER, `texture` BLOB, `last_active` DATE)");
SQLDO("CREATE UNIQUE INDEX `%1users_name` ON `%1users` (`server_id`,`name`)");
SQLDO("CREATE UNIQUE INDEX `%1users_id` ON `%1users` (`server_id`, `user_id`)");
SQLDO("CREATE TRIGGER `%1users_server_del` AFTER DELETE ON `%1servers` FOR EACH ROW BEGIN DELETE FROM `%1users` WHERE `server_id` = old.`server_id`; END;");
|
codereview_cpp_data_11778
|
/* run code and generate handler */
mrb_value result =
mrb_funcall(mrb, mrb_obj_value(mrb->kernel_module), "_h2o_prepare_app", 1, conf);
assert(mrb_array_p(result));
return result;
I believe that we cannot have the assertion here. My understanding that we need to check test if `mrb->exc` is NULL or not and take appropriate actions (which is done in the caller) before asserting that the value being returned is an array.
/* run code and generate handler */
mrb_value result =
mrb_funcall(mrb, mrb_obj_value(mrb->kernel_module), "_h2o_prepare_app", 1, conf);
+ h2o_mruby_assert(mrb);
assert(mrb_array_p(result));
return result;
|
codereview_cpp_data_11789
|
#include "world.h"
Castle::Castle()
- : Castle( -1, -1, Race::NONE )
-{}
Castle::Castle( s32 cx, s32 cy, int rc )
: MapPosition( Point( cx, cy ) )
Hi @tau3 , could you please do not use delegated constructor as it's very hard to understand the code. To avoid this just make `Castle::Castle( s32 cx, s32 cy, int rc )` constructor to have default arguments.
#include "world.h"
Castle::Castle()
+ : race( Race::NONE )
+ , building( 0 )
+ , captain( *this )
+ , army( NULL )
+ , _rumorOfWeek( RumorOfWeek() )
+{
+ std::fill( dwelling, dwelling + CASTLEMAXMONSTER, 0 );
+ army.SetCommander( &captain );
+}
Castle::Castle( s32 cx, s32 cy, int rc )
: MapPosition( Point( cx, cy ) )
|
codereview_cpp_data_11793
|
* @returns index of the minimum element
*/
template <typename T>
-uint64_t findMinIndex(std::vector<T> &in_arr, uint64_t current_position = 0) {
if (current_position + 1 == in_arr.size()) {
return current_position;
}
```suggestion uint64_t findMinIndex(const std::vector<T> &in_arr, uint64_t current_position = 0) { ```
* @returns index of the minimum element
*/
template <typename T>
+uint64_t findMinIndex(const std::vector<T> &in_arr, uint64_t current_position = 0) {
if (current_position + 1 == in_arr.size()) {
return current_position;
}
|
codereview_cpp_data_11803
|
const std::string kNewAssetId =
kNewAsset + "#" + IntegrationTestFramework::kDefaultDomain;
const auto kPrecision = 5;
- const std::string kInitial = "500.00000";
- const std::string kForTransfer = "1.00000";
- const std::string kLeft = "499.00000";
auto create_asset =
baseTx()
Please use `db.precision >= command.precision` instead of `=` so that previous value would be valid.
const std::string kNewAssetId =
kNewAsset + "#" + IntegrationTestFramework::kDefaultDomain;
const auto kPrecision = 5;
+ const std::string kInitial = "500";
+ const std::string kForTransfer = "1";
+ const std::string kLeft = "499";
auto create_asset =
baseTx()
|
codereview_cpp_data_11818
|
framework::SpecifiedVisitor<
shared_model::interface::AccountAssetResponse>(),
resp.get());
- std::cout << asset_resp.toString() << std::endl;
// Check if the fields in account asset response are correct
ASSERT_EQ(asset_resp.accountAssets()[0].assetId(),
account_asset->assetId());
You forgot to remove something :)
framework::SpecifiedVisitor<
shared_model::interface::AccountAssetResponse>(),
resp.get());
// Check if the fields in account asset response are correct
ASSERT_EQ(asset_resp.accountAssets()[0].assetId(),
account_asset->assetId());
|
codereview_cpp_data_11835
|
uint64_t nSigOps = 0;
uint64_t nTx = 0; // BU: count the number of transactions in case the CheckExcessive function wants to use this as criteria
- uint64_t nTxSize = 0; // BU: track the longest transaction
- uint64_t nLargestTx = 0; // BU: track the longest transaction
-
BOOST_FOREACH(const CTransaction& tx, block.vtx)
{
nTx++;
nSigOps += GetLegacySigOpCount(tx);
- nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
- if (nTxSize > nLargestTx) nLargestTx = nTxSize;
}
if (fConservative && (nSigOps > BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS)) // BU only enforce sigops during block generation not acceptance
Nit: nTxSize is only used in the scope of a for loop, so declare it there?
uint64_t nSigOps = 0;
uint64_t nTx = 0; // BU: count the number of transactions in case the CheckExcessive function wants to use this as criteria
BOOST_FOREACH(const CTransaction& tx, block.vtx)
{
nTx++;
nSigOps += GetLegacySigOpCount(tx);
}
if (fConservative && (nSigOps > BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS)) // BU only enforce sigops during block generation not acceptance
|
codereview_cpp_data_11836
|
tableGroupBox->setTitle(tr("Table grid layout"));
invertVerticalCoordinateCheckBox.setText(tr("Invert vertical coordinate"));
minPlayersForMultiColumnLayoutLabel.setText(tr("Minimum player count for multi-column layout:"));
- maxFontSizeForCardsLabel.setText(tr("Maximum size font for displaying card attributes"));
}
UserInterfaceSettingsPage::UserInterfaceSettingsPage()
Isn't it `font size` ?! I would also consider adding `on the table`, or maybe better: rephrase to `information displayed on cards`.
tableGroupBox->setTitle(tr("Table grid layout"));
invertVerticalCoordinateCheckBox.setText(tr("Invert vertical coordinate"));
minPlayersForMultiColumnLayoutLabel.setText(tr("Minimum player count for multi-column layout:"));
+ maxFontSizeForCardsLabel.setText(tr("Maximum font size for information displayed on cards"));
}
UserInterfaceSettingsPage::UserInterfaceSettingsPage()
|
codereview_cpp_data_11855
|
m_enc_detail_panel(0),
m_layout_panel(0),
m_tech_list(0),
- m_initially_hide_tree(initially_hidden)
{
Sound::TempUISoundDisabler sound_disabler;
Minor gripe, should this be something like `m_init_flag`? The current name suggests it reflects the initial state.
m_enc_detail_panel(0),
m_layout_panel(0),
m_tech_list(0),
+ m_init_flag(initially_hidden)
{
Sound::TempUISoundDisabler sound_disabler;
|
codereview_cpp_data_11874
|
#include <s2n.h>
#include "tls/s2n_connection.h"
#include "tls/s2n_handshake.h"
Data corruption errors in s2n_send/recv are unlikely, but can we have the client check the value of the bytes it receives? Something like: ``` Server: for (int i = 0 ; i < sizeof(buffer) ; ++i) { buffer[i] = i; } // server sends buffer ... Client: // client receives buffer ... for (int i = 0; i < recvd_len; ++i) { ASSERT_EQUAL(i, recvd_buf[i]); } ```
#include <s2n.h>
+#include "utils/s2n_random.h"
+
#include "tls/s2n_connection.h"
#include "tls/s2n_handshake.h"
|
codereview_cpp_data_11880
|
#include "rev.h"
#include "video/video_driver.hpp"
#include "music/music_driver.hpp"
-#include <gui.h>
#include <vector>
#include <iterator>
`<>` is for system includes, OpenTTD includes are done with `""`
#include "rev.h"
#include "video/video_driver.hpp"
#include "music/music_driver.hpp"
+#include "gui.h"
#include <vector>
#include <iterator>
|
codereview_cpp_data_11883
|
}
else
{
- double v = (cost / maxCost) * 255.0;
c.setRgb(255, v, 0);
}
If you change `v` to `double` then the following line needs to cast `v` to `int`. My preference would be to keep `v` an `int` and do the cast on assignment: ``` int v = std::static_cast<int>((cost / maxCost) * 255.0); ```
}
else
{
+ int v = (int)((cost / maxCost) * 255.0);
c.setRgb(255, v, 0);
}
|
codereview_cpp_data_11885
|
#ifndef SPAWN
#include "all.h"
-/** This will be true if a lava pool as been generated for the level */
BOOLEAN lavapool;
/** unused */
int abyssx;
```suggestion /** This will be true if a lava pool has been generated for the level */ ```
#ifndef SPAWN
#include "all.h"
+/** This will be true if a lava pool has been generated for the level */
+
BOOLEAN lavapool;
/** unused */
int abyssx;
|
codereview_cpp_data_11894
|
// All critical/corner cases have been taken care of.
// Input your required values: (not hardcoded)
-int32_t main() {
std::cin >> N;
make_set();
int edges;
There is no need of 'int32_t' data type, use only int
// All critical/corner cases have been taken care of.
// Input your required values: (not hardcoded)
+int main() {
std::cin >> N;
make_set();
int edges;
|
codereview_cpp_data_11895
|
// Projectile data
for ( size_t i = 0; i < 3; ++i ) {
- projectileOffset.push_back( fheroes2::Point( getValue<int16_t>( data, 174 + ( i * 4 ) ), getValue<int16_t>( data, 176 + ( i * 4 ) ) ) );
}
// Elves and Grand Elves have incorrect start Y position for lower shooting attack
:warning: **modernize\-use\-emplace** :warning: use emplace\_back instead of push\_back ```suggestion projectileOffsetemplace_back(( getValue<int16_t>( data, 174 + ( i * 4 ) ), getValue<int16_t>( data, 176 + ( i * 4 ) ) ); ```
// Projectile data
for ( size_t i = 0; i < 3; ++i ) {
+ projectileOffset.emplace_back( getValue<int16_t>( data, 174 + ( i * 4 ) ), getValue<int16_t>( data, 176 + ( i * 4 ) ) );
}
// Elves and Grand Elves have incorrect start Y position for lower shooting attack
|
codereview_cpp_data_11906
|
// Check and ignore these labels.
auto xyz_labels_found = nextLine();
// erase blank labels, e.g. due to Frame# and Time columns
- eraseEmptyElements(xyz_labels_found);
for(unsigned i = 1; i <= num_markers_expected; ++i) {
unsigned j = 0;
Just so I understand: the reason the calls to `eraseEmptyElemnts()` is necessary now is because space is no longer a delimiter?
// Check and ignore these labels.
auto xyz_labels_found = nextLine();
// erase blank labels, e.g. due to Frame# and Time columns
+ IO::eraseEmptyElements(xyz_labels_found);
for(unsigned i = 1; i <= num_markers_expected; ++i) {
unsigned j = 0;
|
codereview_cpp_data_11915
|
// See the License for the specific language governing permissions and
// limitations under the License.
-
-#include <thread>
#include <mutex>
#include <fstream>
```suggestion #include <mutex> #include <fstream> ``` Unused header
// See the License for the specific language governing permissions and
// limitations under the License.
#include <mutex>
#include <fstream>
|
codereview_cpp_data_11919
|
}
if (auxts)
{
- dstime diff = dstime((now - auxts) * 10);
dstime current = client->btugexpiration.backoffdelta();
if (current > diff)
{
Static cast syntax is preferred: ```suggestion dstime diff = static_cast<dstime>((now - auxts) * 10); ```
}
if (auxts)
{
+ dstime diff = static_cast<dstime>((now - auxts) * 10);
dstime current = client->btugexpiration.backoffdelta();
if (current > diff)
{
|
codereview_cpp_data_11948
|
(sql_.prepare
<< (cmd % getAccountRolePermissionCheckSql(permission)).str(),
soci::use(account_id, "role_account_id"));
-
- if (not st.begin()->get<0>()) {
- return false;
- }
} catch (const std::exception &e) {
log_->error("Failed to validate query: {}", e.what());
return false;
}
- return true;
}
PostgresQueryExecutorVisitor::PostgresQueryExecutorVisitor(
Is not `error` log level too high?
(sql_.prepare
<< (cmd % getAccountRolePermissionCheckSql(permission)).str(),
soci::use(account_id, "role_account_id"));
+ return st.begin()->get<0>();
} catch (const std::exception &e) {
log_->error("Failed to validate query: {}", e.what());
return false;
}
}
PostgresQueryExecutorVisitor::PostgresQueryExecutorVisitor(
|
codereview_cpp_data_11949
|
*/
TEST_F(ToriiServiceTest, CommandClient) {
iroha::protocol::TxStatusRequest tx_request;
- tx_request.set_tx_hash("asdads");
iroha::protocol::ToriiResponse toriiResponse;
auto client1 = torii::CommandSyncClient(Ip, Port);
Set valid hash size: `std::string(32, '\x0')`
*/
TEST_F(ToriiServiceTest, CommandClient) {
iroha::protocol::TxStatusRequest tx_request;
+ tx_request.set_tx_hash(std::string('1', 32));
iroha::protocol::ToriiResponse toriiResponse;
auto client1 = torii::CommandSyncClient(Ip, Port);
|
codereview_cpp_data_11955
|
const bool DEFAULT_SHOW_PASSWORD_PROTECTED_GAMES = true;
const bool DEFAULT_SHOW_BUDDIES_ONLY_GAMES = true;
const bool DEFAULT_HIDE_IGNORED_USER_GAMES = false;
-const bool DEFAULT_SHOW_ONLY_IF_SPECTATORS_CAN_WATCH = true;
const bool DEFAULT_SHOW_SPECTATOR_PASSWORD_PROTECTED = true;
const bool DEFAULT_SHOW_ONLY_IF_SPECTATORS_CAN_CHAT = false;
const bool DEFAULT_SHOW_ONLY_IF_SPECTATORS_CAN_SEE_HANDS = false;
I think this should be false by default
const bool DEFAULT_SHOW_PASSWORD_PROTECTED_GAMES = true;
const bool DEFAULT_SHOW_BUDDIES_ONLY_GAMES = true;
const bool DEFAULT_HIDE_IGNORED_USER_GAMES = false;
+const bool DEFAULT_SHOW_ONLY_IF_SPECTATORS_CAN_WATCH = false;
const bool DEFAULT_SHOW_SPECTATOR_PASSWORD_PROTECTED = true;
const bool DEFAULT_SHOW_ONLY_IF_SPECTATORS_CAN_CHAT = false;
const bool DEFAULT_SHOW_ONLY_IF_SPECTATORS_CAN_SEE_HANDS = false;
|
codereview_cpp_data_11969
|
}
//_____________________________________________________________________________
-/**
* Connect properties to local pointers.
*/
void MovingPathPoint::constructProperties()
`_zCoordinate` -> `!_zCoordinate.empty()` to agree with changes to x and y cases (above)?
}
//_____________________________________________________________________________
+/*
* Connect properties to local pointers.
*/
void MovingPathPoint::constructProperties()
|
codereview_cpp_data_11972
|
}
if (IsEffectInSpell(spell_id, SE_Charm) && !PassCharmTargetRestriction(entity_list.GetMobID(target_id))) {
- if (IsClient()) {
- CastToClient()->SendSpellBarEnable(spell_id);
}
if (casting_spell_id && IsNPC()) {
CastToNPC()->AI_Event_SpellCastFinished(false, static_cast<uint16>(casting_spell_slot));
We don't need to cast to client here. (well, from spell gem not AA etc) We should also make sure the charm is a casted spell before calling SendSpellBarEnable.
}
if (IsEffectInSpell(spell_id, SE_Charm) && !PassCharmTargetRestriction(entity_list.GetMobID(target_id))) {
+ if ((item_slot != -1 && cast_time > 0) || !aa_id) {
+ Shout("Pass");
+ SendSpellBarEnable(spell_id);
}
if (casting_spell_id && IsNPC()) {
CastToNPC()->AI_Event_SpellCastFinished(false, static_cast<uint16>(casting_spell_slot));
|
codereview_cpp_data_11982
|
static void UA_Client_init(UA_Client* client, UA_ClientConfig config) {
client->state = UA_CLIENTSTATE_READY;
- client->connection = UA_calloc(1, sizeof(UA_Connection));
- UA_Connection_init(client->connection);
- client->channel = UA_calloc(1, sizeof(UA_SecureChannel));
- UA_SecureChannel_init(client->channel);
- client->channel->connection = client->connection;
UA_String_init(&client->endpointUrl);
client->requestId = 0;
- indention - calloc and init is a double affort, I'd suggest to go for change calloc to malloc
static void UA_Client_init(UA_Client* client, UA_ClientConfig config) {
client->state = UA_CLIENTSTATE_READY;
+ client->connection = UA_malloc(sizeof(UA_Connection));
+ UA_Connection_init(client->connection);
+ client->channel = UA_malloc(sizeof(UA_SecureChannel));
+ UA_SecureChannel_init(client->channel);
+ client->channel->connection = client->connection;
UA_String_init(&client->endpointUrl);
client->requestId = 0;
|
codereview_cpp_data_11990
|
.WillRepeatedly(
Return<shared_model::interface::types::SignatureRangeType>({}));
auto prev_hash = Hash("prev hash");
EXPECT_CALL(*block, prevHash())
.WillRepeatedly(testing::ReturnRefOfCopy(prev_hash));
EXPECT_CALL(*block, hash())
- .WillRepeatedly(testing::ReturnRefOfCopy(prev_hash));
expected_block = block;
auto signature = std::make_shared<MockSignature>();
Such values can be misleading for people not familiar with the project, as we expect prev hash to be different from block hash. Event though it is possible with current types and interfaces, I suggest not to create such cases.
.WillRepeatedly(
Return<shared_model::interface::types::SignatureRangeType>({}));
auto prev_hash = Hash("prev hash");
+ auto current_hash = Hash("current hash");
EXPECT_CALL(*block, prevHash())
.WillRepeatedly(testing::ReturnRefOfCopy(prev_hash));
EXPECT_CALL(*block, hash())
+ .WillRepeatedly(testing::ReturnRefOfCopy(current_hash));
expected_block = block;
auto signature = std::make_shared<MockSignature>();
|
codereview_cpp_data_11991
|
EXPECT_EQUAL(memcmp(conn->pending.server_random, zero_to_thirty_one, 32), 0);
/* Check that the server hello message was not processed, we're stuck in SERVER_CERT */
- EXPECT_EQUAL(conn->handshake.message_number, 2);
/* Clean up */
EXPECT_EQUAL(waitpid(pid, &status, 0), pid);
I think we can use the "ACTIVE_STATE" macro here to assert the exact state. `EXPECT_EQUAL(ACTIVE_STATE(conn), SERVER_CERT)`
EXPECT_EQUAL(memcmp(conn->pending.server_random, zero_to_thirty_one, 32), 0);
/* Check that the server hello message was not processed, we're stuck in SERVER_CERT */
+ EXPECT_EQUAL(s2n_conn_get_current_message_type(conn), SERVER_CERT);
/* Clean up */
EXPECT_EQUAL(waitpid(pid, &status, 0), pid);
|
codereview_cpp_data_11992
|
cursorFrom.setPosition( rect_from.x - 2, rect_from.y - 2 );
- if ( resourceTo )
cursorTo.hide();
RedrawToResource( pt2, true, kingdom, fromTradingPost, resourceFrom );
- if ( resourceTo )
cursorTo.show();
- if ( resourceTo )
gui.ShowTradeArea( kingdom, resourceFrom, resourceTo, max_buy, max_sell, count_buy, count_sell, fromTradingPost );
display.render();
}
I know this was already like this, but do you really need to check the same condition twice ?
cursorFrom.setPosition( rect_from.x - 2, rect_from.y - 2 );
+ if ( resourceTo ) {
cursorTo.hide();
+ }
RedrawToResource( pt2, true, kingdom, fromTradingPost, resourceFrom );
+ if ( resourceTo ) {
cursorTo.show();
gui.ShowTradeArea( kingdom, resourceFrom, resourceTo, max_buy, max_sell, count_buy, count_sell, fromTradingPost );
+ }
display.render();
}
|
codereview_cpp_data_11996
|
}
__sync_sub_and_fetch(&req->pool->_shared.count, 1);
req->sock = NULL;
- errstr = err;
} else {
h2o_url_t *target_url = &req->pool->targets.entries[req->selected_target]->url;
if (target_url->scheme->is_ssl) {
This looks like a fine change, though I think we can just get rid of `errstr`, and pass `err` as the argument to `call_connect_cb`?
}
__sync_sub_and_fetch(&req->pool->_shared.count, 1);
req->sock = NULL;
} else {
h2o_url_t *target_url = &req->pool->targets.entries[req->selected_target]->url;
if (target_url->scheme->is_ssl) {
|
codereview_cpp_data_11998
|
* SPDX-License-Identifier: Apache-2.0
*/
-#include "backend/protobuf/query_responses/proto_transaction_page_response.hpp"
#include "common/byteutils.hpp"
namespace shared_model {
Looks like lambda can be removed.
* SPDX-License-Identifier: Apache-2.0
*/
+#include "backend/protobuf/query_responses/proto_transactions_page_response.hpp"
#include "common/byteutils.hpp"
namespace shared_model {
|
codereview_cpp_data_11999
|
LOG_verbose << " Megaclient exec is pending resolutions."
<< " scpaused=" << scpaused
<< " stopsc=" << stopsc
<< " jsonsc.pos=" << jsonsc.pos
<< " syncsup=" << syncsup
<< " statecurrent=" << statecurrent
```suggestion << " stopsc=" << stopsc << " mScStoppedDueToBlock=" << mScStoppedDueToBlock ```
LOG_verbose << " Megaclient exec is pending resolutions."
<< " scpaused=" << scpaused
<< " stopsc=" << stopsc
+ << " mScStoppedDueToBlock=" << mScStoppedDueToBlock
<< " jsonsc.pos=" << jsonsc.pos
<< " syncsup=" << syncsup
<< " statecurrent=" << statecurrent
|
codereview_cpp_data_12001
|
* @param n number
* @return Sum of binomial coefficients of number
*/
- int binomialCoeffSum(int n)
{
// Calculating 2^n
return (1 << n);
```suggestion uint64_t binomialCoeffSum(uint64_t n) ``` as `n >= 0` always
* @param n number
* @return Sum of binomial coefficients of number
*/
+ uint64_t binomialCoeffSum(uint64_t n)
{
// Calculating 2^n
return (1 << n);
|
codereview_cpp_data_12005
|
const std::vector<u8> & AGG::ReadChunk( const std::string & key, bool ignoreExpansion )
{
- if ( heroes2x_agg.isGood() && !ignoreExpansion ) {
const std::vector<u8> & buf = heroes2x_agg.Read( key );
if ( buf.size() )
return buf;
Please swap these 2 conditions. Boolean variable check is faster so in case of `ignoreExpansion` being **true** we will have a little performance boost.
const std::vector<u8> & AGG::ReadChunk( const std::string & key, bool ignoreExpansion )
{
+ if ( !ignoreExpansion && heroes2x_agg.isGood() ) {
const std::vector<u8> & buf = heroes2x_agg.Read( key );
if ( buf.size() )
return buf;
|
codereview_cpp_data_12018
|
struct wlr_wl_shell_surface *surface = data;
wlr_log(L_DEBUG, "new shell surface: title=%s, class=%s",
- surface->title, surface->class_);
//wlr_wl_shell_surface_ping(surface); // TODO: segfaults
struct roots_wl_shell_surface *roots_surface =
FWIW I think you could implement the whole ping/pong workflow entirely in wlr_wl_shell, no need to expose this function (though I understand this wasn't part of your changes).
struct wlr_wl_shell_surface *surface = data;
wlr_log(L_DEBUG, "new shell surface: title=%s, class=%s",
+ surface->title, surface->class);
//wlr_wl_shell_surface_ping(surface); // TODO: segfaults
struct roots_wl_shell_surface *roots_surface =
|
codereview_cpp_data_12021
|
const UINT _consoleOutputCP;
};
- ConsoleCPSwitcher consoleCPSwitcher;
#endif
}
Let's please make this variable `const` as we don't modify it.
const UINT _consoleOutputCP;
};
+ const ConsoleCPSwitcher consoleCPSwitcher;
#endif
}
|
codereview_cpp_data_12024
|
T* d_a;
hipMalloc(&d_a, sizeof(T) * size);
hipMemcpy(d_a, &a, sizeof(T) * size, hipMemcpyDefault);
- hipLaunchKernelGGL(shflUpSum, 1, size, 0, 0, d_a, size);
hipMemcpy(&a, d_a, sizeof(T) * size, hipMemcpyDefault);
if (a[size - 1] != cpuSum) {
hipFree(d_a);
Can we also enable the test for int and float as well for completeness sake?
T* d_a;
hipMalloc(&d_a, sizeof(T) * size);
hipMemcpy(d_a, &a, sizeof(T) * size, hipMemcpyDefault);
+ hipLaunchKernelGGL(shflUpSum<T>, 1, size, 0, 0, d_a, size);
hipMemcpy(&a, d_a, sizeof(T) * size, hipMemcpyDefault);
if (a[size - 1] != cpuSum) {
hipFree(d_a);
|
codereview_cpp_data_12026
|
tile.RedrawBottom( dst, tileROI, isPuzzleDraw, *this );
tile.RedrawObjects( dst, isPuzzleDraw, *this );
}
- int object = tile.GetObject();
if ( MP2::OBJ_ZERO != object ) {
if ( drawMonstersAndBoats ) {
if ( MP2::OBJ_BOAT == object ) {
Please create 2 separate variables: one for heroes and one for boat so that in the later loop we don't need to check object type.
tile.RedrawBottom( dst, tileROI, isPuzzleDraw, *this );
tile.RedrawObjects( dst, isPuzzleDraw, *this );
}
+ const int object = tile.GetObject();
if ( MP2::OBJ_ZERO != object ) {
if ( drawMonstersAndBoats ) {
if ( MP2::OBJ_BOAT == object ) {
|
codereview_cpp_data_12045
|
InitQTextMsg(TEXT_MUSH12);
quests[Q_MUSHROOM]._qactive = QUEST_DONE;
towner[t]._tMsgSaid = TRUE;
- AllItemsList[Item->IDidx].iUsable = TRUE; /// BUGFIX: This will cause the elixier to be usable in the next game
} else if (PlrHasItem(p, IDI_BRAIN, i) != NULL && quests[Q_MUSHROOM]._qvar2 != TEXT_MUSH11) {
towner[t]._tbtcnt = 150;
towner[t]._tVar1 = p;
```suggestion AllItemsList[Item->IDidx].iUsable = TRUE; /// BUGFIX: This will cause the elixir to be usable in the next game ```
InitQTextMsg(TEXT_MUSH12);
quests[Q_MUSHROOM]._qactive = QUEST_DONE;
towner[t]._tMsgSaid = TRUE;
+ AllItemsList[Item->IDidx].iUsable = TRUE; /// BUGFIX: This will cause the elixir to be usable in the next game
+
} else if (PlrHasItem(p, IDI_BRAIN, i) != NULL && quests[Q_MUSHROOM]._qvar2 != TEXT_MUSH11) {
towner[t]._tbtcnt = 150;
towner[t]._tVar1 = p;
|
codereview_cpp_data_12056
|
{
namespace qt
{
- sofa::helper::system::FileRepository GuiDataRepository("RUNSOFA_DATA_PATH", "../share/sofa/runSofa/ressources/");
}
}
}
Why not using current resources dirs (e.g. share/icons)? BTW, only one S for **resources** ;-)
{
namespace qt
{
+ sofa::helper::system::FileRepository GuiDataRepository("GUI_DATA_PATH", "../share/sofa/gui/ressources/");
}
}
}
|
codereview_cpp_data_12057
|
putshort(gsub,pcnt);
if ( pcnt>=max ) {
max = pcnt+100;
- ligoffsets = realloc(ligoffsets,max*sizeof(uint16));
}
lig_list_start = ftell(gsub);
for ( j=0; j<pcnt; ++j )
This one is "unsafe" as an individual line, but in context it looks correct. (See line 1906 and how it's used as an array.)
putshort(gsub,pcnt);
if ( pcnt>=max ) {
max = pcnt+100;
+ ligoffsets = realloc(ligoffsets,max*2*sizeof(uint16));
}
lig_list_start = ftell(gsub);
for ( j=0; j<pcnt; ++j )
|
codereview_cpp_data_12058
|
return Status::OK();
}
Status CatalogManager::LaunchBackfillIndexForTable(
const LaunchBackfillIndexForTableRequestPB* req,
LaunchBackfillIndexForTableResponsePB* resp,
we need to return/populate an error in the response in case this flush operation fails. see GetBackfillJobs just above this for an example: ``` if (indexed_table == nullptr) { Status s = STATUS(NotFound, "Requested table $0 does not exist", table_id.ShortDebugString()); return SetupError(resp->mutable_error(), MasterErrorPB::OBJECT_NOT_FOUND, s); } ```
return Status::OK();
}
+Status CatalogManager::CompactSysCatalog(
+ const CompactSysCatalogRequestPB* req,
+ CompactSysCatalogResponsePB* resp,
+ rpc::RpcContext* rpc){
+ return Status::OK();
+}
+
Status CatalogManager::LaunchBackfillIndexForTable(
const LaunchBackfillIndexForTableRequestPB* req,
LaunchBackfillIndexForTableResponsePB* resp,
|
codereview_cpp_data_12065
|
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#include <LightGBM/config.h>
-#include <LightGBM/metric.h>
-#include <LightGBM/objective_function.h>
#include <LightGBM/utils/common.h>
#include <LightGBM/utils/log.h>
I guess that these includes are not needed anymore.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#include <LightGBM/config.h>
#include <LightGBM/utils/common.h>
#include <LightGBM/utils/log.h>
|
codereview_cpp_data_12070
|
return ihipLogStatus(e);
}
-hipError_t hipExtMemcpyWithStream(void* dst, const void* src, size_t sizeBytes,
- hipMemcpyKind kind, hipStream_t stream) {
- HIP_INIT_SPECIAL_API(hipExtMemcpyWithStream, (TRACE_MCMD), dst, src,
- sizeBytes, kind, stream);
-
- return ihipLogStatus(hip_internal::memcpySync(dst, src, sizeBytes, kind,
- stream));
-}
-
namespace {
template <uint32_t block_dim, uint32_t items_per_lane,
typename RandomAccessIterator, typename N, typename T>
Is this still needed?
return ihipLogStatus(e);
}
namespace {
template <uint32_t block_dim, uint32_t items_per_lane,
typename RandomAccessIterator, typename N, typename T>
|
codereview_cpp_data_12080
|
return S2N_SUCCESS;
}
-int s2n_cert_get_cert_der(const struct s2n_cert *cert, const uint8_t **out_cert_der, uint32_t *cert_length)
{
POSIX_ENSURE_REF(cert);
POSIX_ENSURE_REF(out_cert_der);
For all your "cert_get_cert" -- maybe drop the second "cert"? So for example, "s2n_cert_get_der" instead of "s2n_cert_get_cert_der"
return S2N_SUCCESS;
}
+int s2n_cert_get_der(const struct s2n_cert *cert, const uint8_t **out_cert_der, uint32_t *cert_length)
{
POSIX_ENSURE_REF(cert);
POSIX_ENSURE_REF(out_cert_der);
|
codereview_cpp_data_12084
|
}
}
if (sh->init) {
- h2o_iovec_t err = {NULL, 0};
- void *p;
- p = sh->init(&err);
- if (!p) {
- h2o_send_error_400(req, "Invalid Request", err.base, 0);
- return 0;
- }
- collector->status_ctx.entries[collector->status_ctx.size].ctx = p;
}
collector->status_ctx.entries[collector->status_ctx.size].active = 1;
Skip:
Unless there is a specific reason, I believe we should not allow `init` callback to fail. They should be implemented to always succeed (and that makes the code that calls the handlers simpler), and in case there is a chance of a init callback to fail, then the status handler should retain the error within the handler and emit an error message as part of the JSON when its `final` callback is called.
}
}
if (sh->init) {
+ collector->status_ctx.entries[collector->status_ctx.size].ctx = sh->init();
}
collector->status_ctx.entries[collector->status_ctx.size].active = 1;
Skip:
|
codereview_cpp_data_12089
|
return msg;
}
-std::map<Monster::monster_t, Monster::level_t> Monster::monsterLevel = InitializeMonsterLevels();
-
float Monster::GetUpgradeRatio(void)
{
return GameStatic::GetMonsterUpgradeRatio();
Could you please put this variable into unnamed namespace and make it `const`?
return msg;
}
float Monster::GetUpgradeRatio(void)
{
return GameStatic::GetMonsterUpgradeRatio();
|
codereview_cpp_data_12107
|
if (it != master_server_addrs_.end()) {
master_server_addrs_.erase(it);
}
-
for(const auto& a : master_server_addrs_) {
updated_addrs += a;
}
}
Are we missing commas (",") here when concatenating. Previously, we were doing ToCommaSeparatedString().
if (it != master_server_addrs_.end()) {
master_server_addrs_.erase(it);
}
+ bool need_comma = false;
for(const auto& a : master_server_addrs_) {
+ if (need_comma) {
+ updated_addrs +=',';
+ }
updated_addrs += a;
+ need_comma = true;
}
}
|
codereview_cpp_data_12110
|
{
// The original CDRMessage buffer (msg) now points to the proprietary temporary buffer crypto_msg_.
// The auxiliary buffer now points to the propietary temporary buffer crypto_submsg_.
- // This way each decoded submessage will be process using the crypto_submsg_ buffer.
msg = auxiliary_buffer;
auxiliary_buffer = &crypto_submsg_;
}
```suggestion // This way each decoded sub-message will be processed using the crypto_submsg_ buffer. ```
{
// The original CDRMessage buffer (msg) now points to the proprietary temporary buffer crypto_msg_.
// The auxiliary buffer now points to the propietary temporary buffer crypto_submsg_.
+ // This way each decoded sub-message will be processed using the crypto_submsg_ buffer.
msg = auxiliary_buffer;
auxiliary_buffer = &crypto_submsg_;
}
|
codereview_cpp_data_12114
|
{
std::lock_guard<RecursiveTimedMutex> guard(mp_mutex);
- min_low_mark = next_all_acked_notify_sequence_;
}
SequenceNumber_t calc = min_low_mark < get_seq_num_min() ? SequenceNumber_t() :
We should remove 1 in order to be consistent ```suggestion min_low_mark = next_all_acked_notify_sequence_ - 1; ```
{
std::lock_guard<RecursiveTimedMutex> guard(mp_mutex);
+ min_low_mark = next_all_acked_notify_sequence_ - 1;
}
SequenceNumber_t calc = min_low_mark < get_seq_num_min() ? SequenceNumber_t() :
|
codereview_cpp_data_12116
|
// initialize ordered gradients and hessians
ordered_gradients_.resize(num_data_);
ordered_hessians_.resize(num_data_);
- // if has ordered bin, need allocate a buffer to fast split
if (has_ordered_bin_) {
is_data_in_leaf_.resize(num_data_);
}
// if has ordered bin, need to allocate a buffer to fast split
// initialize ordered gradients and hessians
ordered_gradients_.resize(num_data_);
ordered_hessians_.resize(num_data_);
+ // if has ordered bin, need to allocate a buffer to fast split
if (has_ordered_bin_) {
is_data_in_leaf_.resize(num_data_);
}
|
codereview_cpp_data_12119
|
const std::vector<image_data_reader::sample_t> &image_list = image_reader->get_image_list();
for (auto t : sizes) {
int data_id = t.first;
- int label = image_list[data_id].second; //TODO FIXME
if (m_image_offsets.find(data_id) == m_image_offsets.end()) {
LBANN_ERROR("m_image_offsets.find(data_id) == m_image_offsets.end() for data_id: ", data_id);
}
Is this still broken?
const std::vector<image_data_reader::sample_t> &image_list = image_reader->get_image_list();
for (auto t : sizes) {
int data_id = t.first;
+ int label = image_list[data_id].second;
if (m_image_offsets.find(data_id) == m_image_offsets.end()) {
LBANN_ERROR("m_image_offsets.find(data_id) == m_image_offsets.end() for data_id: ", data_id);
}
|
codereview_cpp_data_12145
|
h2o_url_t *origin)
{
if (errstr != NULL) {
- char buf[128];
- on_error(client->ctx, "%s:%s", errstr,
- h2o_strerror_r(errno, buf, sizeof(buf)));
return NULL;
}
I do not think that we should be using `h2o_strerror_r` in the HTTP-level callbacks. There is no guarantee that the cause of `on_connect` failing is due to an error returned from a syscall (consider TLS certificate mismatch for an example).
h2o_url_t *origin)
{
if (errstr != NULL) {
+ on_error(client->ctx, errstr);
return NULL;
}
|
codereview_cpp_data_12153
|
cmpctBlock->vTxHashes.insert(it, iterShortID, shorttxids.end());
}
- // Create a map of all 8 bytes tx hashes pointing to their full tx hash counterpart
// We need to check all transaction sources (orphan list, mempool, and new (incoming) transactions in this block)
int missingCount = 0;
int unnecessaryCount = 0;
didn't we use 6 bytes txid in compact blocks?
cmpctBlock->vTxHashes.insert(it, iterShortID, shorttxids.end());
}
+ // Create a map of all short tx hashes pointing to their full tx hash counterpart
// We need to check all transaction sources (orphan list, mempool, and new (incoming) transactions in this block)
int missingCount = 0;
int unnecessaryCount = 0;
|
codereview_cpp_data_12154
|
#include <../include/openpty.h>
#endif
-#ifdef HAVE_LINUX_MEMFD_H
-#include <linux/memfd.h>
-#endif
-
#include "af_unix.h"
#include "bdev.h"
#include "caps.h" /* for lxc_caps_last_cap() */
You don't have a configure.ac entry for this
#include <../include/openpty.h>
#endif
#include "af_unix.h"
#include "bdev.h"
#include "caps.h" /* for lxc_caps_last_cap() */
|
codereview_cpp_data_12162
|
// FIXME: the cast is wrong and cause a warning on clang 5.0
// disable this code for now, fix it later
ai_assert(false && "Bad pointer cast");
- pcFirstFrame = NULL;
#else
BE_NCONST MDL::GroupFrame* pcFrames2 = (BE_NCONST MDL::GroupFrame*)pcFrames;
pcFirstFrame = (BE_NCONST MDL::SimpleFrame*)(&pcFrames2->time + pcFrames->type);
Prefer C++11 `nullptr` instead of `NULL`.
// FIXME: the cast is wrong and cause a warning on clang 5.0
// disable this code for now, fix it later
ai_assert(false && "Bad pointer cast");
+ pcFirstFrame = nullptr; // Workaround: msvc++ C4703 error
#else
BE_NCONST MDL::GroupFrame* pcFrames2 = (BE_NCONST MDL::GroupFrame*)pcFrames;
pcFirstFrame = (BE_NCONST MDL::SimpleFrame*)(&pcFrames2->time + pcFrames->type);
|
codereview_cpp_data_12170
|
else ptr = alocal[m];
// to make sure dx, dy and dz are always from the lower to the higher id
- double directionCorrection = i > j ? -1.0 : 1.0;
for (n = 0; n < nvalues; n++) {
switch (pstyle[n]) {
Shouldn't this be using `itag` and `jtag`?
else ptr = alocal[m];
// to make sure dx, dy and dz are always from the lower to the higher id
+ double directionCorrection = itag > jtag ? -1.0 : 1.0;
for (n = 0; n < nvalues; n++) {
switch (pstyle[n]) {
|
codereview_cpp_data_12171
|
.transactions(std::vector<shared_model::proto::Transaction>{tx})
.build());
auto tx_errors = iroha::validation::TransactionsErrors{
- std::make_pair(validation::CommandError{"SomeCommand", 1, true},
shared_model::crypto::Hash(std::string(32, '0'))),
- std::make_pair(validation::CommandError{"SomeCommand", 1, true},
shared_model::crypto::Hash(std::string(32, '0')))};
shared_model::proto::Block block = makeBlock(proposal->height() - 1);
maybe add some number variable to avoid magic number here and upwards in this PR?
.transactions(std::vector<shared_model::proto::Transaction>{tx})
.build());
auto tx_errors = iroha::validation::TransactionsErrors{
+ std::make_pair(validation::CommandError{"SomeCommand", "SomeError", true},
shared_model::crypto::Hash(std::string(32, '0'))),
+ std::make_pair(validation::CommandError{"SomeCommand", "SomeError", true},
shared_model::crypto::Hash(std::string(32, '0')))};
shared_model::proto::Block block = makeBlock(proposal->height() - 1);
|
codereview_cpp_data_12179
|
* being used. For the s2n_low_level_hash implementation, new is a no-op.
*/
- state->is_ready_for_input = 0;
- state->currently_in_hash = 0;
- memset(&state->digest,0,sizeof(state->digest));
return S2N_SUCCESS;
}
This works, but you could zero everything at once for completeness. Maybe just: ```suggestion *state = (struct s2n_hash_state) { 0 }; ``` or ``` memset(state, 0, sizeof(struct s2n_hash_state)); ```
* being used. For the s2n_low_level_hash implementation, new is a no-op.
*/
+ *state = (struct s2n_hash_state) { 0 };
return S2N_SUCCESS;
}
|
codereview_cpp_data_12180
|
auto contents = detail::load_contents(config);
if (!contents)
return contents.error();
- // Skip empty config files.
- if (std::all_of(contents->begin(), contents->end(), [](char ch) {
- return std::isspace(ch);
- }))
- continue;
auto yaml = from_yaml(*contents);
if (!yaml)
return yaml.error();
auto* rec = caf::get_if<record>(&*yaml);
if (!rec)
return caf::make_error(ec::parse_error, "config file not a map of "
```suggestion // Skip empty config files. if (contents->empty()) continue; // Skip config files only containing whitespace. ```
auto contents = detail::load_contents(config);
if (!contents)
return contents.error();
auto yaml = from_yaml(*contents);
if (!yaml)
return yaml.error();
+ // Skip empty config files.
+ if (caf::holds_alternative<caf::none_t>(*yaml))
+ continue;
auto* rec = caf::get_if<record>(&*yaml);
if (!rec)
return caf::make_error(ec::parse_error, "config file not a map of "
|
codereview_cpp_data_12205
|
bool tryGetMatchingFile( const std::string & fileName, std::string & matchingFilePath )
{
- const std::string fileExtension = fileName.substr( fileName.rfind( '.' ) + 1 );
- static const ListFiles files = Settings::FindFiles( "maps", fileExtension, false );
const auto iterator = std::find_if( files.begin(), files.end(), [&fileName]( const std::string & filePath ) { return isCampaignMap( filePath, fileName ); } );
I think that such a "naive" approach will lead to problems. For example, maps from original campaign (SW) have the ".H2C" extension, while maps from PoL campaign have the ".HXC" extension. What if I will switch from one campaign type to another without restarting the game?
bool tryGetMatchingFile( const std::string & fileName, std::string & matchingFilePath )
{
+ static const ListFiles files = Settings::FindFiles( "maps" );
const auto iterator = std::find_if( files.begin(), files.end(), [&fileName]( const std::string & filePath ) { return isCampaignMap( filePath, fileName ); } );
|
codereview_cpp_data_12212
|
goto out;
old_path = g_file_resolve_relative_path (root, commit_filepath);
if (!g_file_load_contents (old_path, cancellable, &old_contents, NULL, NULL, error))
goto out;
}
Any reason we can't use `glnx_file_get_contents_utf8_at` here? Or just keep the previous logic of only setting `old_path` and changing the `gs_file_load_contents_utf8` in the deleted hunk below to `glnx_file_get_contents_utf8_at` ?
goto out;
old_path = g_file_resolve_relative_path (root, commit_filepath);
+ /* Note this one can't be ported to glnx_file_get_contents_utf8_at() because
+ * we're loading from ostree via `OstreeRepoFile`.
+ */
if (!g_file_load_contents (old_path, cancellable, &old_contents, NULL, NULL, error))
goto out;
}
|
codereview_cpp_data_12218
|
void DLBus::attachDLBusInterrupt(void)
{
ISR_Receiving = false;
attachInterrupt(digitalPinToInterrupt(ISR_DLB_Pin), ISR, CHANGE);
}
Why is there code for P092 in this PR?
void DLBus::attachDLBusInterrupt(void)
{
ISR_Receiving = false;
+ IsISRset = true;
+ IsNoData = false;
attachInterrupt(digitalPinToInterrupt(ISR_DLB_Pin), ISR, CHANGE);
}
|
codereview_cpp_data_12223
|
* Helper function that returns zero (0) if the contents of the buffers b1 and b2 match
* and non-zero otherwise.
*/
-int cmp_buffers(const unsigned char *b1, size_t len1, const unsigned char* b2, size_t len2)
{
unsigned int i;
should be static; or even better: a macro that plays nicely with the testing framework (and prints outs where exactly the buffers differ)
* Helper function that returns zero (0) if the contents of the buffers b1 and b2 match
* and non-zero otherwise.
*/
+static int cmp_buffers(const unsigned char *b1, size_t len1, const unsigned char* b2, size_t len2)
{
unsigned int i;
|
codereview_cpp_data_12239
|
auto ctx = ihipGetTlsDefaultCtx();
hipError_t ret = hipSuccess;
if (ctx == nullptr) {
ret = hipErrorInvalidDevice;
Please avoid hardcoded constants in code, instead use const MAX_VGPR_SIZE or the like with description of the reasoning behind that magic value.
auto ctx = ihipGetTlsDefaultCtx();
hipError_t ret = hipSuccess;
+ std::size_t blockSize = hip_impl::get_program_state().get_kernattribute(f->_name);
+ if (blockSize < (localWorkSizeX * localWorkSizeY * localWorkSizeZ))
+ {
+ return hipErrorLaunchFailure;
+ }
+
if (ctx == nullptr) {
ret = hipErrorInvalidDevice;
|
codereview_cpp_data_12242
|
}
if (f != 0.0)
Q->xy_factor *= f;
- if (normalized_name != nullptr && strcmp(normalized_name, "Radian") == 0)
- P->left = PJ_IO_UNITS_RADIANS;
}
if ((name = pj_param (P->ctx, P->params, "sxy_out").s) != nullptr) {
in case a numeric value is passed, normalized_name will be nullptr, so this should be tested Same below. Strange that it doesn't crash on tests
}
if (f != 0.0)
Q->xy_factor *= f;
}
if ((name = pj_param (P->ctx, P->params, "sxy_out").s) != nullptr) {
|
codereview_cpp_data_12264
|
delete[] vecs;
}
-//_____________________________________________________________________________
-/**
- * Smooth spline each of the columns in the storage. Note that as a part
- * of this operation, the storage is resampled so that the statevectors are
- * at equal spacing.
- *
- * @param aOrder Order of the spline.
- * @param aCutoffFrequency Cutoff frequency.
- */
void Storage::
smoothSpline(int aOrder,double aCutoffFrequency)
{
+1. The only way for the minimum DT and the average DT to be the same is if you have uniform DT.
delete[] vecs;
}
void Storage::
smoothSpline(int aOrder,double aCutoffFrequency)
{
|
codereview_cpp_data_12268
|
EXPECT_THROW(ViewFactor(s, z, 0.9), openstudio::Exception);
EXPECT_THROW(ViewFactor(z, s, 0.9), openstudio::Exception);
-
- // TODO: JM 2019-09-13 NOT SURE WHETHER WE WANT TO ALLOW TO==FROM here
- // Test that you cannot add a view factor if toSurface == fromSurface
- EXPECT_THROW(ViewFactor(s, s, 0.25), openstudio::Exception);
}
TEST_F(ModelFixture, ZonePropertyUserViewFactorsBySurfaceName_ZonePropertyUserViewFactorsBySufaceName_Ctor) {
Will want to change this to no throw.
EXPECT_THROW(ViewFactor(s, z, 0.9), openstudio::Exception);
EXPECT_THROW(ViewFactor(z, s, 0.9), openstudio::Exception);
+ // Test that you can add a view factor if toSurface == fromSurface
+ EXPECT_NO_THROW(ViewFactor(s, s, 0.25));
}
TEST_F(ModelFixture, ZonePropertyUserViewFactorsBySurfaceName_ZonePropertyUserViewFactorsBySufaceName_Ctor) {
|
codereview_cpp_data_12279
|
SCInsertImage(sc,image,scale,sc->parent->ascent,0,layer);
}
-int FVImportImages(FontViewBase *fv,char *path,int format,int toback, bool reference, int flags) {
GImage *image;
int tot;
char *start = path, *endpath=path;
int i;
What's the point of this change? It doesn't look like this is actually used in the function?
SCInsertImage(sc,image,scale,sc->parent->ascent,0,layer);
}
+int FVImportImages(FontViewBase *fv,char *path,int format,int toback, int flags) {
GImage *image;
+ /*struct _GImage *base;*/
int tot;
char *start = path, *endpath=path;
int i;
|
codereview_cpp_data_12284
|
const auto arbitrary_large_number = 999999.9f;
std::shared_ptr<UniverseObject> location = GetUniverseObject(location_id);
- if (!location) {
- ErrorLogger() << "Location is missing using production cost of " << arbitrary_large_number;
return arbitrary_large_number;
- }
std::shared_ptr<const UniverseObject> source = Empires().GetSource(empire_id);
if (!source && !m_production_cost->SourceInvariant()) {
not necessarily an error... pedia can show stuff even when there's no game ongoing.
const auto arbitrary_large_number = 999999.9f;
std::shared_ptr<UniverseObject> location = GetUniverseObject(location_id);
+ if (!location)
return arbitrary_large_number;
std::shared_ptr<const UniverseObject> source = Empires().GetSource(empire_id);
if (!source && !m_production_cost->SourceInvariant()) {
|
codereview_cpp_data_12289
|
storageResult.match(
[&](expected::Value<std::unique_ptr<ametsuchi::MutableStorage>> &_storage) {
storage = std::move(_storage.value);
- }, [](expected::Error<std::string> &error) {}
);
if (not storage) {
- log_->error("cannot create storage");
return;
}
auto chain = blockLoader_->retrieveBlocks(signature.pubkey);
Again, empty "error" branch
storageResult.match(
[&](expected::Value<std::unique_ptr<ametsuchi::MutableStorage>> &_storage) {
storage = std::move(_storage.value);
+ }, [&](expected::Error<std::string> &error) {
+ storage = nullptr;
+ log_->error(error.error);
+ }
);
if (not storage) {
return;
}
auto chain = blockLoader_->retrieveBlocks(signature.pubkey);
|
codereview_cpp_data_12294
|
regEx.append("A-Z");
if(settingsCache->value("users/allownumerics", true).toBool())
regEx.append("0-9");
- regEx.append(allowedPunctuation);
regEx.append("]+");
static QRegExp re = QRegExp(regEx);
I mean that we need to regEx.append(QRegexp::escape(allowedPunctuation)) here. Otherway a configuration like:`allowedpunctuation=_.-]` will lead to a bad regexp: ``` (gdb) printq5string regEx [a-zA-Z0-9_.-]]+ ``` that will return false for any possible nickname.
regEx.append("A-Z");
if(settingsCache->value("users/allownumerics", true).toBool())
regEx.append("0-9");
+ regEx.append(QRegExp::escape(allowedPunctuation));
regEx.append("]+");
static QRegExp re = QRegExp(regEx);
|
codereview_cpp_data_12301
|
}
}
}
free(strings);
free(dicts);
free(fontnames);
return( 1 );
}
These are string arrays. Looking at line 6428, this will free the array structure of `strings` but not the strings. (Line 5574 analogous.)
}
}
}
+ for ( i = 0; strings[i] != NULL; ++i)
+ free(strings[i]);
free(strings);
+
+ for ( i = 0; dicts[i] != NULL; ++i)
+ free(dicts[i]);
free(dicts);
+
+ for ( i = 0; fontnames[i] != NULL; ++i)
+ free(fontnames[i]);
free(fontnames);
return( 1 );
}
|
codereview_cpp_data_12311
|
*/
#include "module/shared_model/mock_objects_factories/mock_command_factory.hpp"
using ::testing::Return;
using ::testing::ReturnRef;
Maybe we should provide a meaningful return for the `toString()` method too?
*/
#include "module/shared_model/mock_objects_factories/mock_command_factory.hpp"
+#include "backend/protobuf/permissions.hpp"
+#include "utils/string_builder.hpp"
using ::testing::Return;
using ::testing::ReturnRef;
|
codereview_cpp_data_12315
|
sp->prevcp = sp->me;
if ( sp->prev->from->pointtype!=pt_tangent)
sp->prev->from->pointtype = pt_corner;
- if ( sp->prev->order2 ) {
BasePoint inter;
if ( IntersectLines(&inter,&sp->me,&sp->prev->from->me,&sp->nextcp,&sp->next->to->me) ) {
sp->nextcp = inter;
sp->next->to->prevcp = inter;
- SplineRefigure(sp->prev);
} /* else just leave things as they are */
}
else {
Since review cycles are limited I'm dropping my "too much input to review" standard for this. My only question about the code at this stage is whether this part (with the `IntersectLines()`) is something already built into `SplineRefigureFixup()`, already used below in the curve case. Did you look at that?
sp->prevcp = sp->me;
if ( sp->prev->from->pointtype!=pt_tangent)
sp->prev->from->pointtype = pt_corner;
+ if ( sp->next->order2 ) {
BasePoint inter;
if ( IntersectLines(&inter,&sp->me,&sp->prev->from->me,&sp->nextcp,&sp->next->to->me) ) {
sp->nextcp = inter;
sp->next->to->prevcp = inter;
+ SplineRefigure(sp->prev); /* display straight line */
} /* else just leave things as they are */
}
else {
|
codereview_cpp_data_12334
|
return 0;
}
-int LLVMFuzzerTestOneInput(const uint8_t *buf, size_t len) {
- struct s2n_blob server_shared_secret = { 0 };
- struct s2n_blob ciphertext = { 0 };
GUARD(s2n_alloc(&ciphertext, len));
/* Need to memcpy since blobs expect a non-const value and LLVMFuzzer does expect a const */
Same `{0}` looks nicer than `{ 0 }`
return 0;
}
+int LLVMFuzzerTestOneInput(const uint8_t *buf, size_t len)
+{
+ struct s2n_blob server_shared_secret = {0};
+ struct s2n_blob ciphertext = {0};
GUARD(s2n_alloc(&ciphertext, len));
/* Need to memcpy since blobs expect a non-const value and LLVMFuzzer does expect a const */
|
codereview_cpp_data_12336
|
keyboard->modifiers.latched = latched;
keyboard->modifiers.locked = locked;
keyboard->modifiers.group = group;
}
static void keyboard_key_update(struct wlr_keyboard *keyboard,
Why did you move the `emit` call outside this function? The X11 backend is still not calling `wlr_keyboard_notify_modifiers` so emiting the event here is necessary. Plus, the purpose of this function is to only emit the event when needed (when modifiers really changed).
keyboard->modifiers.latched = latched;
keyboard->modifiers.locked = locked;
keyboard->modifiers.group = group;
+
+ wl_signal_emit(&keyboard->events.modifiers, keyboard);
}
static void keyboard_key_update(struct wlr_keyboard *keyboard,
|
codereview_cpp_data_12343
|
return true;
}
-bool python_reader::fetch_datum(CPUMat& X, int data_id, int col) {
- return true;
-}
-
bool python_reader::fetch_label(CPUMat& Y, int data_id, int col) {
return true;
}
It might be better to leave the default implementation (throws an error) than this, in case something changes and this gets called directly.
return true;
}
bool python_reader::fetch_label(CPUMat& Y, int data_id, int col) {
return true;
}
|
codereview_cpp_data_12351
|
if (!ostree_repo_mark_commit_partial (repo, checksum, FALSE, error))
return FALSE;
- *out_changed = FALSE;
return TRUE;
}
This should be `TRUE`, no?
if (!ostree_repo_mark_commit_partial (repo, checksum, FALSE, error))
return FALSE;
+ *out_changed = TRUE;
return TRUE;
}
|
codereview_cpp_data_12353
|
boost::optional<double> People_Impl::spaceFloorAreaPerPerson() const {
OptionalDouble temp = peopleDefinition().spaceFloorAreaperPerson();
if (temp) {
- return temp.get() * multiplier();
}
return temp;
}
This should get divided by the load instance multiplier right?
boost::optional<double> People_Impl::spaceFloorAreaPerPerson() const {
OptionalDouble temp = peopleDefinition().spaceFloorAreaperPerson();
if (temp) {
+ double mult = multiplier();
+ if (mult > 0) {
+ return temp.get() / mult;
+ }
}
return temp;
}
|
codereview_cpp_data_12392
|
void Neighbor::print_pairwise_info()
{
int i,m;
- char str[256];
NeighRequest *rq;
FILE *out;
missing the changes of `sprintf` to `snprintf` in this file.
void Neighbor::print_pairwise_info()
{
int i,m;
NeighRequest *rq;
FILE *out;
|
codereview_cpp_data_12399
|
if (g_hostRuntimeDirectory == nullptr)
{
#ifdef FEATURE_PAL
char* line = nullptr;
size_t lineLen = 0;
The new code suggests that FreeBSD or NetBSD would be supported if they used /etc/dotnet/install_location. If we don't expect these platforms to ever work I'd move the error check back to the top of the method and if we do expect them to have it I'd change the error text to say that.
if (g_hostRuntimeDirectory == nullptr)
{
#ifdef FEATURE_PAL
+#if defined (__FreeBSD__) || defined(__NetBSD__)
+ ExtErr("Hosting on FreeBSD or NetBSD not supported\n");
+ return E_FAIL;
+#else
char* line = nullptr;
size_t lineLen = 0;
|
codereview_cpp_data_12406
|
{
MultiFab& S_new = get_new_data(Phi_Type);
- // Create temporary multifab with properly filled patches
- const Real cur_time = state[Phi_Type].curTime();
MultiFab phi(S_new.boxArray(), S_new.DistributionMap(), NUM_STATE, 1);
- FillPatch(*this, phi, phi.nGrow(), cur_time, Phi_Type, 0, NUM_STATE);
const char tagval = TagBox::SET;
// const char clearval = TagBox::CLEAR;
We do not need to create a new temporary MulitFab here. It's OK to call FillPatch on S_new. We also do not need to fill all ghost cells, just one is sufficient for computing grad phi. Finally, if level >= max_phigrad_lev, we do not need to call FillPatch.
{
MultiFab& S_new = get_new_data(Phi_Type);
+ // Properly fill patches and ghost cells for phi gradient check.
MultiFab phi(S_new.boxArray(), S_new.DistributionMap(), NUM_STATE, 1);
+ if (level < max_phigrad_lev) {
+ const Real cur_time = state[Phi_Type].curTime();
+ FillPatch(*this, phi, 1, cur_time, Phi_Type, 0, NUM_STATE);
+ }
const char tagval = TagBox::SET;
// const char clearval = TagBox::CLEAR;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.