id
stringlengths
27
29
content
stringlengths
226
3.24k
codereview_new_cpp_data_6512
bool do_process_c017_delay_queue(int controller_number, const Queue_element_base continue; // Zabbix will ignore an empty key anyway } JsonObject block = data.createNestedObject(); - block[F("host")] = Settings.getUnitname(); // Zabbix hostname, Unit Name for the ESP easy block[F("key")] = taskValueName; // Zabbix item key // Value Name for the ESP easy float value = 0.0f; validFloatFromString(element.txt[i], value); This may break existing setups (if any, as some users reported Zabbix controller seems broken) bool do_process_c017_delay_queue(int controller_number, const Queue_element_base continue; // Zabbix will ignore an empty key anyway } JsonObject block = data.createNestedObject(); + block[F("host")] = Settings.getName(); // Zabbix hostname, Unit Name for the ESP easy block[F("key")] = taskValueName; // Zabbix item key // Value Name for the ESP easy float value = 0.0f; validFloatFromString(element.txt[i], value);
codereview_new_cpp_data_6514
bool SettingsStruct_tmpl<N_TASKS>::isEthernetPinOptional(int8_t pin) const { #if FEATURE_ETHERNET if (pin < 0) return false; if (NetworkMedium == NetworkMedium_t::Ethernet) { - if (((ETH_Clock_Mode == EthClockMode_t::Int_50MHz_GPIO_0) && (pin == 0)) || - ((ETH_Clock_Mode == EthClockMode_t::Int_50MHz_GPIO_16) && (pin == 16)) || - ((ETH_Clock_Mode == EthClockMode_t::Int_50MHz_GPIO_17_inv) && (pin == 17))) return true; if (ETH_Pin_mdc == pin) return true; if (ETH_Pin_mdio == pin) return true; if (ETH_Pin_power == pin) return true; Maybe better to have this (duplicate) code next to the EthClockMode_t definition? bool SettingsStruct_tmpl<N_TASKS>::isEthernetPinOptional(int8_t pin) const { #if FEATURE_ETHERNET if (pin < 0) return false; if (NetworkMedium == NetworkMedium_t::Ethernet) { + if (isGpioUsedInETHClockMode(ETH_Clock_Mode, pin)) return true; if (ETH_Pin_mdc == pin) return true; if (ETH_Pin_mdio == pin) return true; if (ETH_Pin_power == pin) return true;
codereview_new_cpp_data_6515
void handle_json() stream_next_json_object_value(F("Type"), getPluginNameFromDeviceIndex(DeviceIndex)); stream_next_json_object_value(F("TaskName"), getTaskDeviceName(TaskIndex)); stream_next_json_object_value(F("TaskDeviceNumber"), Settings.TaskDeviceNumber[TaskIndex]); - if (getPluginNameFromDeviceIndex(DeviceIndex) == "Switch input - Switch") { stream_next_json_object_value(F("TaskDeviceGPIO"), Settings.TaskDevicePin1[TaskIndex]); } - #if FEATURE_I2CMULTIPLEXER if (Device[DeviceIndex].Type == DEVICE_TYPE_I2C && isI2CMultiplexerEnabled()) { int8_t channel = Settings.I2C_Multiplexer_Channel[TaskIndex]; Few points of critique: Constant strings, should be wrapped in the `F()` macro, to make sure they are not stored in memory, but read from flash when used. `F("Switch input - Switch")` Second, better try to match the plugin ID nr and not the string. What if someone updates the name to `F("Switch Input - Switch")`, then this fails without clear notice. The plugin ID (`1`) does not change. So better use `getPluginID_from_TaskIndex(TaskIndex) == 1` void handle_json() stream_next_json_object_value(F("Type"), getPluginNameFromDeviceIndex(DeviceIndex)); stream_next_json_object_value(F("TaskName"), getTaskDeviceName(TaskIndex)); stream_next_json_object_value(F("TaskDeviceNumber"), Settings.TaskDeviceNumber[TaskIndex]); + if (Settings.TaskDeviceNumber[TaskIndex] == 1) { stream_next_json_object_value(F("TaskDeviceGPIO"), Settings.TaskDevicePin1[TaskIndex]); } + #if FEATURE_I2CMULTIPLEXER if (Device[DeviceIndex].Type == DEVICE_TYPE_I2C && isI2CMultiplexerEnabled()) { int8_t channel = Settings.I2C_Multiplexer_Channel[TaskIndex];
codereview_new_cpp_data_6516
void handle_json() stream_next_json_object_value(F("Type"), getPluginNameFromDeviceIndex(DeviceIndex)); stream_next_json_object_value(F("TaskName"), getTaskDeviceName(TaskIndex)); stream_next_json_object_value(F("TaskDeviceNumber"), Settings.TaskDeviceNumber[TaskIndex]); - if (getPluginNameFromDeviceIndex(DeviceIndex) == "Switch input - Switch") { stream_next_json_object_value(F("TaskDeviceGPIO"), Settings.TaskDevicePin1[TaskIndex]); } - #if FEATURE_I2CMULTIPLEXER if (Device[DeviceIndex].Type == DEVICE_TYPE_I2C && isI2CMultiplexerEnabled()) { int8_t channel = Settings.I2C_Multiplexer_Channel[TaskIndex]; On the devices page, we already have something to show the port description. Maybe we can extend that part to make it more universal for all tasks/plugins to get a generic description of the ports used. For GPIO pins, we already have the `DEVICE_TYPE_SINGLE`, etc. to indicate how many GPIO pins are being used. See where `usesTaskDevicePin` is being called in the code. void handle_json() stream_next_json_object_value(F("Type"), getPluginNameFromDeviceIndex(DeviceIndex)); stream_next_json_object_value(F("TaskName"), getTaskDeviceName(TaskIndex)); stream_next_json_object_value(F("TaskDeviceNumber"), Settings.TaskDeviceNumber[TaskIndex]); + if (Settings.TaskDeviceNumber[TaskIndex] == 1) { stream_next_json_object_value(F("TaskDeviceGPIO"), Settings.TaskDevicePin1[TaskIndex]); } + #if FEATURE_I2CMULTIPLEXER if (Device[DeviceIndex].Type == DEVICE_TYPE_I2C && isI2CMultiplexerEnabled()) { int8_t channel = Settings.I2C_Multiplexer_Channel[TaskIndex];
codereview_new_cpp_data_6517
void handle_json() stream_next_json_object_value(F("Type"), getPluginNameFromDeviceIndex(DeviceIndex)); stream_next_json_object_value(F("TaskName"), getTaskDeviceName(TaskIndex)); stream_next_json_object_value(F("TaskDeviceNumber"), Settings.TaskDeviceNumber[TaskIndex]); - for(int i = 0; i < 3; i++) - { if (Settings.TaskDevicePin[i][TaskIndex] != -1) { - int gpioNr = Settings.TaskDevicePin[i][TaskIndex]; - if (i==0) {stream_next_json_object_value(F("TaskDeviceGPIO1"), gpioNr);} - if (i==1) {stream_next_json_object_value(F("TaskDeviceGPIO2"), gpioNr);} - if (i==2) {stream_next_json_object_value(F("TaskDeviceGPIO3"), gpioNr);} - } } #if FEATURE_I2CMULTIPLEXER if (Device[DeviceIndex].Type == DEVICE_TYPE_I2C && isI2CMultiplexerEnabled()) { This will show 3x the same JSON label. Maybe use `concat(F("TaskDeviceGPIO"), i)` This may need `#include "../Helpers/StringConverter.h" ` (not sure about the exact name, you may need to check it) void handle_json() stream_next_json_object_value(F("Type"), getPluginNameFromDeviceIndex(DeviceIndex)); stream_next_json_object_value(F("TaskName"), getTaskDeviceName(TaskIndex)); stream_next_json_object_value(F("TaskDeviceNumber"), Settings.TaskDeviceNumber[TaskIndex]); + for(int i = 0; i < 3; i++) { if (Settings.TaskDevicePin[i][TaskIndex] != -1) { + stream_next_json_object_value(concat(F("TaskDeviceGPIO"), i + 1) , String(Settings.TaskDevicePin[i][TaskIndex])); } + } #if FEATURE_I2CMULTIPLEXER if (Device[DeviceIndex].Type == DEVICE_TYPE_I2C && isI2CMultiplexerEnabled()) {
codereview_new_cpp_data_6518
void handle_json() stream_next_json_object_value(F("TaskName"), getTaskDeviceName(TaskIndex)); stream_next_json_object_value(F("TaskDeviceNumber"), Settings.TaskDeviceNumber[TaskIndex]); for(int i = 0; i < 3; i++) { - if (Settings.TaskDevicePin[i][TaskIndex] != -1) { stream_next_json_object_value(concat(F("TaskDeviceGPIO"), i + 1) , String(Settings.TaskDevicePin[i][TaskIndex])); } } - #if FEATURE_I2CMULTIPLEXER if (Device[DeviceIndex].Type == DEVICE_TYPE_I2C && isI2CMultiplexerEnabled()) { int8_t channel = Settings.I2C_Multiplexer_Channel[TaskIndex]; Maybe best to use the `Device[DeviceIndex].usesTaskDevicePin(i)` function here. (next to checking for the pin >= 0) This also requires you to fetch the `DeviceIndex` (outside the loop please ;) ). This way you don't output a value from a previous setting or some perhaps uninitialized value. void handle_json() stream_next_json_object_value(F("TaskName"), getTaskDeviceName(TaskIndex)); stream_next_json_object_value(F("TaskDeviceNumber"), Settings.TaskDeviceNumber[TaskIndex]); for(int i = 0; i < 3; i++) { + if (Settings.TaskDevicePin[i][TaskIndex] >= 0) { stream_next_json_object_value(concat(F("TaskDeviceGPIO"), i + 1) , String(Settings.TaskDevicePin[i][TaskIndex])); } } + #if FEATURE_I2CMULTIPLEXER if (Device[DeviceIndex].Type == DEVICE_TYPE_I2C && isI2CMultiplexerEnabled()) { int8_t channel = Settings.I2C_Multiplexer_Channel[TaskIndex];
codereview_new_cpp_data_6519
void addTextBox(const String & id, { addHtml(F("<input ")); addHtmlAttribute(F("class"), classname); - addHtmlAttribute(F("type"), F("text")); addHtmlAttribute(F("name"), id); if (maxlength > 0) { addHtmlAttribute(F("maxlength"), maxlength); Just curious, what is the difference between these types? void addTextBox(const String & id, { addHtml(F("<input ")); addHtmlAttribute(F("class"), classname); + addHtmlAttribute(F("type"), F("search")); addHtmlAttribute(F("name"), id); if (maxlength > 0) { addHtmlAttribute(F("maxlength"), maxlength);
codereview_new_cpp_data_6520
bool isLoggedIn(bool mustProvideLogin) String getControllerSymbol(uint8_t index) { - String ret = F("<p style='font-size:20px; background: #00000000;line-height:21px;'>&#"); ret += 10102 + index; - ret += F(";</p>"); return ret; } What’s the line-height for? In my browser it looks actually a little bit better without it.. (or almost no difference visible) with: <img width="236" alt="Bildschirmfoto 2022-09-03 um 23 30 32" src="https://user-images.githubusercontent.com/33860956/188288313-43c058d3-cdef-4fd3-9198-085915498255.png"> without: <img width="236" alt="Bildschirmfoto 2022-09-03 um 23 30 25" src="https://user-images.githubusercontent.com/33860956/188288318-fe848755-3c3c-4daf-84ab-672301cc17d0.png"> bool isLoggedIn(bool mustProvideLogin) String getControllerSymbol(uint8_t index) { + String ret = F("<span style='font-size:20px; background: #00000000;'>&#"); ret += 10102 + index; + ret += F(";</span>"); return ret; }
codereview_new_cpp_data_6521
void html_add_script(bool defer) { if (defer) { addHtml(F(" defer")); } - addHtml(F('>')); } void html_add_script_end() { The F macro can only be applied to strings not on chars, this line should be: `addHtml('>');` (that's why the build failed) void html_add_script(bool defer) { if (defer) { addHtml(F(" defer")); } + addHtml('>'); } void html_add_script_end() {
codereview_new_cpp_data_6522
* checkI2CConfigValid_toHtml(taskIndex, onlyCheck) * Check if I2C is correctly configured and usable for this task * taskIndex: will be used in planned enhancements - * onlyCheck = true: no html output is generated * Outputs an error message and returns false if not correct **********************************************************************/ bool checkI2CConfigValid_toHtml(taskIndex_t taskIndex, - bool onlyCheck) { if ((Settings.Pin_i2c_sda == -1) || (Settings.Pin_i2c_scl == -1)) { - if (!onlyCheck) { addHtml(F("Incomplete I2C configuration.")); } return false; } #if FEATURE_I2CMULTIPLEXER if ((Settings.I2C_Multiplexer_Type != I2C_MULTIPLEXER_NONE) && (Settings.I2C_Multiplexer_Addr == -1)) { // Multiplexer selected, but no port configured - if (!onlyCheck) { addHtml(F("Incomplete I2C Multiplexer configuration.")); } return false; } #endif // if FEATURE_I2CMULTIPLEXER Maybe change `onlyCheck` to `outputToHtml` as I had to read the source to grasp what it does. * checkI2CConfigValid_toHtml(taskIndex, onlyCheck) * Check if I2C is correctly configured and usable for this task * taskIndex: will be used in planned enhancements + * outputToHtml = false: no html output is generated * Outputs an error message and returns false if not correct **********************************************************************/ bool checkI2CConfigValid_toHtml(taskIndex_t taskIndex, + bool outputToHtml) { if ((Settings.Pin_i2c_sda == -1) || (Settings.Pin_i2c_scl == -1)) { + if (outputToHtml) { addHtml(F("Incomplete I2C configuration.")); } return false; } #if FEATURE_I2CMULTIPLEXER if ((Settings.I2C_Multiplexer_Type != I2C_MULTIPLEXER_NONE) && (Settings.I2C_Multiplexer_Addr == -1)) { // Multiplexer selected, but no port configured + if (outputToHtml) { addHtml(F("Incomplete I2C Multiplexer configuration.")); } return false; } #endif // if FEATURE_I2CMULTIPLEXER
codereview_new_cpp_data_6523
P134_data_struct::P134_data_struct(uint8_t config_port, { const ESPEasySerialPort port = static_cast<ESPEasySerialPort>(_config_port); - delete P134_Serial; - P134_Serial = new ESPeasySerial(port, _config_pin1, _config_pin2); if (P134_Serial != nullptr) { Why is delete needed in the constructor? The member should be made nullptr initially instead. There simply cannot be an object assigned to the pointer during the constructor. P134_data_struct::P134_data_struct(uint8_t config_port, { const ESPEasySerialPort port = static_cast<ESPEasySerialPort>(_config_port); P134_Serial = new ESPeasySerial(port, _config_pin1, _config_pin2); if (P134_Serial != nullptr) {
codereview_new_cpp_data_6524
void handle_notifications() { } else { - //MFD: we display the GPIO - if (NotificationSettings.Pin1>=0){ - addHtml(F("GPIO-")); - addHtmlInt(NotificationSettings.Pin1); - } if (NotificationSettings.Pin2>=0) { html_BR(); - addHtml(F("GPIO-")); - addHtmlInt(NotificationSettings.Pin2); } html_TD(3); } The default pin config is -1 (or at least it should be) So better check for `>= 0` or else you cannot connect a buzzer to GPIO-0 (or at least not get it to display this) void handle_notifications() { } else { + //MFD: we display the GPIO + addGpioHtml(NotificationSettings.Pin1); + if (NotificationSettings.Pin2>=0) { html_BR(); + addGpioHtml(NotificationSettings.Pin2); } html_TD(3); }
codereview_new_cpp_data_6526
void getWebPageTemplateDefaultHead(WebTemplateParser& parser, bool addMeta, bool if (parser.isTail()) return; parser.process(F("<!DOCTYPE html><html lang='en'>" "<head>" - "<link rel='stylesheet' href='codemirror.css'>" "<script src='codemirror.min.js'></script>" - "<script src='espeasy.js'></script>" - "<script src='anyword-hint.js' id='anyword'></script>" "<meta charset='utf-8'/>" "<meta name='viewport' content='width=device-width, initial-scale=1.0'>" "<title>{{name}}</title>")); i guess this all must be in "WebStaticData" but this is beyond my capabilities... 😳 void getWebPageTemplateDefaultHead(WebTemplateParser& parser, bool addMeta, bool if (parser.isTail()) return; parser.process(F("<!DOCTYPE html><html lang='en'>" "<head>" + "<link rel='stylesheet' href='codemirror.min.css'>" "<script src='codemirror.min.js'></script>" + "<script src='espeasy.min.js'></script>" + "<script src='anyword-hint.min.js' id='anyword'></script>" "<meta charset='utf-8'/>" "<meta name='viewport' content='width=device-width, initial-scale=1.0'>" "<title>{{name}}</title>"));
codereview_new_cpp_data_6537
HOOT_FACTORY_REGISTER(ElementVisitor, AddElementIdVisitor) void AddElementIdVisitor::visit(const ElementPtr& pElement) { Tags& tags = pElement->getTags(); - tags[MetadataTags::HootId()] = QString::number(pElement->getId()); } } I think we need an indicator of the table (Node, Way, Relation) as well as the numeric ID. `getElementId().toString()` provides this `Way(758208161)` This unit test should also assert the format of the `hoot:id`. HOOT_FACTORY_REGISTER(ElementVisitor, AddElementIdVisitor) void AddElementIdVisitor::visit(const ElementPtr& pElement) { Tags& tags = pElement->getTags(); + tags[MetadataTags::HootId()] = pElement->getElementId().toString(); } }
codereview_new_cpp_data_6540
bool GenFaceNormalsProcess::GenMeshFaceNormals(aiMesh *pMesh) { const aiVector3D *pV1 = &pMesh->mVertices[face.mIndices[0]]; const aiVector3D *pV2 = &pMesh->mVertices[face.mIndices[1]]; const aiVector3D *pV3 = &pMesh->mVertices[face.mIndices[face.mNumIndices - 1]]; - if (flippedWindingOrder_ != leftHanded_) // Boolean XOR std::swap(pV2, pV3); const aiVector3D vNor = ((*pV2 - *pV1) ^ (*pV3 - *pV1)).NormalizeSafe(); Add comment explaining _why_. bool GenFaceNormalsProcess::GenMeshFaceNormals(aiMesh *pMesh) { const aiVector3D *pV1 = &pMesh->mVertices[face.mIndices[0]]; const aiVector3D *pV2 = &pMesh->mVertices[face.mIndices[1]]; const aiVector3D *pV3 = &pMesh->mVertices[face.mIndices[face.mNumIndices - 1]]; + // Boolean XOR - if either but not both of these flags is set, then the winding order has + // changed and the cross product to calculate the normal needs to be reversed + if (flippedWindingOrder_ != leftHanded_) std::swap(pV2, pV3); const aiVector3D vNor = ((*pV2 - *pV1) ^ (*pV3 - *pV1)).NormalizeSafe();
codereview_new_cpp_data_6544
void generateOutput() Portable::getSysElapsedTime() ); g_s.print(); - bool restore=FALSE; - if (Debug::isFlagSet(Debug::Time)) - { - Debug::clearFlag("time"); - restore=TRUE; - } msg("finished...\n"); - if (restore) Debug::setFlag("time"); } else { the same check is already done at line 12689 it seems, so I would expect this guard is always true and the code can be simplified. void generateOutput() Portable::getSysElapsedTime() ); g_s.print(); + + Debug::clearFlag("time"); msg("finished...\n"); + Debug::setFlag("time"); } else {
codereview_new_cpp_data_6545
void searchInputFiles() } if (Doxygen::inputNameLinkedMap->empty()) { - warn_uncond("No files to be processed, please check your settings, in particular INPUT, FILE_PATTERNS, and RECURSIVE\n"); } g_s.end(); } Good catch though it would be better to have such a change not hidden in another PR but in a separate PR. void searchInputFiles() } if (Doxygen::inputNameLinkedMap->empty()) { + warn_uncond("No files to be processed, please check your settings, in particular INPUT, FILE_PATTERNS, and RECURSIVE"); } g_s.end(); }
codereview_new_cpp_data_6546
void XmlDocVisitor::operator()(const DocImage &img) bool ambig; if (url.isEmpty() && (fd=findFileDef(Doxygen::imageNameLinkedMap,img.name(),ambig))) { - if (fd) copyFile(fd->absFilePath(),Config_getString(XML_OUTPUT)+"/"+baseName); } visitChildren(img); visitPostEnd(m_t, "image"); this extra `if (fd)` should not be needed, `fd` is already checked in the expression on the previous line. void XmlDocVisitor::operator()(const DocImage &img) bool ambig; if (url.isEmpty() && (fd=findFileDef(Doxygen::imageNameLinkedMap,img.name(),ambig))) { + copyFile(fd->absFilePath(),Config_getString(XML_OUTPUT)+"/"+baseName); } visitChildren(img); visitPostEnd(m_t, "image");
codereview_new_cpp_data_6547
void DocParser::defaultHandleTitleAndSize(const int cmd, DocNodeVariant *parent, } else if (tok==TK_HTMLTAG) { break; } if (!defaultHandleToken(parent,tok,children)) should we not unput the string like is done below? For a closing tag is it probably ok to ignore it, but an opening tag should not be ignored, like in the following example: ```html <table border=0> <tr> <td>\image html sphere.png<tr align="center"> <td>(a) Sphere</td> </tr> </table> ``` void DocParser::defaultHandleTitleAndSize(const int cmd, DocNodeVariant *parent, } else if (tok==TK_HTMLTAG) { + tokenizer.unputString(context.token->name); break; } if (!defaultHandleToken(parent,tok,children))
codereview_new_cpp_data_6548
void linkifyText(const TextGeneratorIntf &out, const Definition *scope, // set next start point in the string //printf("index=%d/%d\n",index,txtStr.length()); skipIndex=index=newIndex+matchLen; - if (insideString) index++; } // add last part of the string to the result. //ol.docify(txtStr.right(txtStr.length()-skipIndex)); @albert-github I wonder in which situation this is needed? void linkifyText(const TextGeneratorIntf &out, const Definition *scope, // set next start point in the string //printf("index=%d/%d\n",index,txtStr.length()); skipIndex=index=newIndex+matchLen; } // add last part of the string to the result. //ol.docify(txtStr.right(txtStr.length()-skipIndex));
codereview_new_cpp_data_6549
static bool stylist_validate_requirements(struct map_session_data *sd, int type, return false; if (entry->id >= 0) { - if (entry->zeny != 0 && pc->payzeny(sd, entry->zeny, LOG_TYPE_OTHER, NULL) != 0) { return false; } else if (entry->itemid != 0) { it.nameid = entry->itemid; i not sure, but may be add new log type for stylist? static bool stylist_validate_requirements(struct map_session_data *sd, int type, return false; if (entry->id >= 0) { + if (entry->zeny != 0 && pc->payzeny(sd, entry->zeny, LOG_TYPE_STYLIST, NULL) != 0) { return false; } else if (entry->itemid != 0) { it.nameid = entry->itemid;
codereview_new_cpp_data_6552
class CppGenerator : public BaseGenerator { code_ += " int KeyCompareWithValue(const {{INPUT_TYPE}} *_{{FIELD_NAME}}" ") const { "; - code_ += " auto curr_{{FIELD_NAME}} = {{FIELD_NAME}}();"; code_ += " for (auto i = 0; i < curr_{{FIELD_NAME}}->size(); i++) {"; code_ += " const auto {{FIELD_NAME}}_l = curr_{{FIELD_NAME}}->Get(i);"; I recommend using `const auto* curr_{{FIELD_NAME}} = {{FIELD_NAME}}();` class CppGenerator : public BaseGenerator { code_ += " int KeyCompareWithValue(const {{INPUT_TYPE}} *_{{FIELD_NAME}}" ") const { "; + code_ += " const auto* curr_{{FIELD_NAME}} = {{FIELD_NAME}}();"; code_ += " for (auto i = 0; i < curr_{{FIELD_NAME}}->size(); i++) {"; code_ += " const auto {{FIELD_NAME}}_l = curr_{{FIELD_NAME}}->Get(i);";
codereview_new_cpp_data_6554
CheckedError Parser::ParseProtoFields(StructDef *struct_def, bool isextend, while (!Is(';')) { if (token_ == kTokenIntegerConstant) { if (range) { - for (voffset_t id = std::stoul(from) + 1; id <= stoul(attribute_); id++) struct_def->reserved_ids.push_back(id); range = false; } else ## Comparison of narrow type with wide type in loop condition Comparison between [id](1) of type voffset_t and [call to stoul](2) of wider type unsigned long. [Show more details](https://github.com/google/flatbuffers/security/code-scanning/179) CheckedError Parser::ParseProtoFields(StructDef *struct_def, bool isextend, while (!Is(';')) { if (token_ == kTokenIntegerConstant) { if (range) { + for (voffset_t id = std::stoul(from) + 1; id <= stoul(attribute_); + id++) struct_def->reserved_ids.push_back(id); range = false; } else
codereview_new_cpp_data_6555
const static FlatCOption options[] = { { "", "proto-namespace-suffix", "SUFFIX", "Add this namespace to any flatbuffers generated from protobufs." }, { "", "oneof-union", "", "Translate .proto oneofs to flatbuffer unions." }, - { "", "keep-proto-id", "", "Keep protobuf ids in generated fbs file." }, { "", "proto-id-gap", "", "Action that should be taken when a gap between protobuf ids found. " "Supported values: * " protobuf field ids const static FlatCOption options[] = { { "", "proto-namespace-suffix", "SUFFIX", "Add this namespace to any flatbuffers generated from protobufs." }, { "", "oneof-union", "", "Translate .proto oneofs to flatbuffer unions." }, + { "", "keep-proto-id", "", "Keep protobuf field ids in generated fbs file." }, { "", "proto-id-gap", "", "Action that should be taken when a gap between protobuf ids found. " "Supported values: * "
codereview_new_cpp_data_6556
void EvolutionTest(const std::string &tests_data_path) { #endif } void ConformTest() { const char ref[] = "table T { A:int; } enum E:byte { A }"; I would reduce your PRs to remove misc formatting issues. They just add noise. void EvolutionTest(const std::string &tests_data_path) { #endif } + void ConformTest() { const char ref[] = "table T { A:int; } enum E:byte { A }";
codereview_new_cpp_data_6557
class SwiftGenerator : public BaseGenerator { std::string SwiftConstant(const FieldDef& field) { const auto default_value = StringIsFlatbufferNan(field.value.constant) ? ".nan" : - StringIsFlatbufferPositiveInfinity(field.value.constant) ? "+.infinity" : StringIsFlatbufferNegativeInfinity(field.value.constant) ? "-.infinity" : // IsEnum(field.value.type) ? (field.IsOptional() ? "nil" : GenEnumDefaultValue(field)) : IsBool(field.value.type.base_type) ? ("0" == field.value.constant ? "false" : "true") : do we have `.nan` in swift? class SwiftGenerator : public BaseGenerator { std::string SwiftConstant(const FieldDef& field) { const auto default_value = StringIsFlatbufferNan(field.value.constant) ? ".nan" : + StringIsFlatbufferPositiveInfinity(field.value.constant) ? ".infinity" : StringIsFlatbufferNegativeInfinity(field.value.constant) ? "-.infinity" : // IsEnum(field.value.type) ? (field.IsOptional() ? "nil" : GenEnumDefaultValue(field)) : IsBool(field.value.type.base_type) ? ("0" == field.value.constant ? "false" : "true") :
codereview_new_cpp_data_6558
class SwiftGenerator : public BaseGenerator { StringIsFlatbufferNan(field.value.constant) ? ".nan" : StringIsFlatbufferPositiveInfinity(field.value.constant) ? ".infinity" : StringIsFlatbufferNegativeInfinity(field.value.constant) ? "-.infinity" : - // IsEnum(field.value.type) ? (field.IsOptional() ? "nil" : GenEnumDefaultValue(field)) : IsBool(field.value.type.base_type) ? ("0" == field.value.constant ? "false" : "true") : field.value.constant; return default_value; nit: remove commented line class SwiftGenerator : public BaseGenerator { StringIsFlatbufferNan(field.value.constant) ? ".nan" : StringIsFlatbufferPositiveInfinity(field.value.constant) ? ".infinity" : StringIsFlatbufferNegativeInfinity(field.value.constant) ? "-.infinity" : IsBool(field.value.type.base_type) ? ("0" == field.value.constant ? "false" : "true") : field.value.constant; return default_value;
codereview_new_cpp_data_6725
static pmix_status_t unpack_return(pmix_buffer_t *data) /* provide an opportunity to store any data (or at least how to access * any data) that was included in the fence */ - // TODO(skg) Is this peer correct? It seems to work. PMIX_GDS_RECV_MODEX_COMPLETE(rc, pmix_client_globals.myserver, data); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); yes, that is the correct peer - sorry for the error! static pmix_status_t unpack_return(pmix_buffer_t *data) /* provide an opportunity to store any data (or at least how to access * any data) that was included in the fence */ PMIX_GDS_RECV_MODEX_COMPLETE(rc, pmix_client_globals.myserver, data); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc);
codereview_new_cpp_data_6726
BaseObject::BaseObject() , l_slaves(initLink("slaves","Sub-objects used internally by this object")) , l_master(initLink("master","nullptr for regular objects, or master object for which this object is one sub-objects")) { - l_context.setValidator(std::bind(&sofa::core::objectmodel::BaseObject::changeContextLink, this, std::placeholders::_1, std::placeholders::_2)); l_context.set(BaseContext::getDefault()); - l_slaves.setValidator(std::bind(&sofa::core::objectmodel::BaseObject::changeSlavesLink, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); f_listening.setAutoLink(false); } replace `std::bind` by lambdas https://clang.llvm.org/extra/clang-tidy/checks/modernize/avoid-bind.html BaseObject::BaseObject() , l_slaves(initLink("slaves","Sub-objects used internally by this object")) , l_master(initLink("master","nullptr for regular objects, or master object for which this object is one sub-objects")) { + auto bindChangeContextLink = [this](auto&& before, auto&& after) { return this->changeContextLink(before, after); }; + l_context.setValidator(bindChangeContextLink); l_context.set(BaseContext::getDefault()); + + auto bindChangeSlavesLink = [this](auto&& ptr, auto&& index, auto&& add) { return this->changeSlavesLink(ptr, index, add); }; + l_slaves.setValidator(bindChangeSlavesLink); f_listening.setAutoLink(false); }
codereview_new_cpp_data_6727
void Base::initData0( BaseData* field, BaseData::BaseInitData& res, const char* res.helpMsg = help; res.dataFlags = dataFlags; - if (strlen(name) >= 3) { std::string_view prefix = std::string_view(name).substr(0, 4); shouldnt it be `>= 4` ? void Base::initData0( BaseData* field, BaseData::BaseInitData& res, const char* res.helpMsg = help; res.dataFlags = dataFlags; + if (strlen(name) >= 4) { std::string_view prefix = std::string_view(name).substr(0, 4);
codereview_new_cpp_data_6728
int LineAxisClass = core::RegisterObject("Display scene axis") using namespace sofa::defaulttype; -void LineAxis::parse(sofa::core::objectmodel::BaseObjectDescription* arg) -{ - if (std::string(arg->getAttribute("type")) == lineAxisDeprecatedName) - { - msg_warning(lineAxisDeprecatedName) << lineAxisDeprecatedName << " is deprecated since SOFA v22.12, and has" - " been replaced by " << this->getClassName() << ". Please modify your scene. Note that the new component " - << this->getClassName() << " is located in another module (Sofa.Component.Visual). It means that you " - "probably need to update also the appropriate RequiredPlugin in your scene. For example, in XML, " - "consider removing the line <RequiredPlugin name=\"Sofa.GL.Component.Rendering3D\"> to replace it by " - "<RequiredPlugin name=\"Sofa.Component.Visual\">."; - } - Inherit1::parse(arg); -} - LineAxis::LineAxis() : d_axis(initData(&d_axis, std::string("xyz"), "axis", "Axis to draw")) , d_size(initData(&d_size, 10.f, "size", "Size of the squared grid")) It makes me think that we dont have a mechanism to warn the user at run-time that one alias has been deleted (and to tell him to use `LineAxis` in this example) Maybe adding a "Renamed" in `sofa::helper::lifecycle::ComponentChange` ? int LineAxisClass = core::RegisterObject("Display scene axis") using namespace sofa::defaulttype; LineAxis::LineAxis() : d_axis(initData(&d_axis, std::string("xyz"), "axis", "Axis to draw")) , d_size(initData(&d_size, 10.f, "size", "Size of the squared grid"))
codereview_new_cpp_data_6729
ObjectElement::~ObjectElement() bool ObjectElement::init() { - [[maybe_unused]] int i=0; for (child_iterator<> it = begin(); it != end(); ++it) { - i++; it->init(); } is it actually used .. ? ObjectElement::~ObjectElement() bool ObjectElement::init() { for (child_iterator<> it = begin(); it != end(); ++it) { it->init(); }
codereview_new_cpp_data_6730
AttributeElement::~AttributeElement() bool AttributeElement::init() { - [[maybe_unused]] int i=0; for (child_iterator<> it = begin(); it != end(); ++it) { - i++; it->initNode(); } return initNode(); is it actually used .. ? AttributeElement::~AttributeElement() bool AttributeElement::init() { for (child_iterator<> it = begin(); it != end(); ++it) { it->initNode(); } return initNode();
codereview_new_cpp_data_6731
void DefaultPipeline::doCollisionDetection(const type::vector<core::CollisionMod else { std::string msg = "Compute BoundingTree: " + (*it)->getName(); - ScopedAdvancedTimer tmpbboxtimer(msg.c_str()); (*it)->computeBoundingTree(used_depth); } ```suggestion ScopedAdvancedTimer BoundingTreeTimer(msg.c_str()); ``` void DefaultPipeline::doCollisionDetection(const type::vector<core::CollisionMod else { std::string msg = "Compute BoundingTree: " + (*it)->getName(); + ScopedAdvancedTimer BoundingTreeTimer(msg.c_str()); (*it)->computeBoundingTree(used_depth); }
codereview_new_cpp_data_6732
void DefaultPipeline::doCollisionDetection(const type::vector<core::CollisionMod else { std::string msg = "Compute BoundingTree: " + (*it)->getName(); - ScopedAdvancedTimer BoundingTreeTimer(msg.c_str()); (*it)->computeBoundingTree(used_depth); } ```suggestion ScopedAdvancedTimer boundingTreeTimer(msg.c_str()); ``` void DefaultPipeline::doCollisionDetection(const type::vector<core::CollisionMod else { std::string msg = "Compute BoundingTree: " + (*it)->getName(); + ScopedAdvancedTimer boundingTreeTimer(msg.c_str()); (*it)->computeBoundingTree(used_depth); }
codereview_new_cpp_data_6733
namespace sofa Transform baseDevice_H_endDevice(pos*data.scale, quat); Transform world_H_virtualTool = data.world_H_baseDevice * baseDevice_H_endDevice * data.endDevice_H_virtualTool; lastToolPosition = world_H_virtualTool; - /* unused code Transform baseDevice_H_endDevice2 = data.world_H_baseDevice.inversed() * world_H_virtualTool * data.endDevice_H_virtualTool.inversed(); sout << "bHe = " << baseDevice_H_endDevice << sendl; sout << "wHb = " << data.world_H_baseDevice << sendl; I think this is un-needed ```suggestion /* ``` namespace sofa Transform baseDevice_H_endDevice(pos*data.scale, quat); Transform world_H_virtualTool = data.world_H_baseDevice * baseDevice_H_endDevice * data.endDevice_H_virtualTool; lastToolPosition = world_H_virtualTool; + /* Transform baseDevice_H_endDevice2 = data.world_H_baseDevice.inversed() * world_H_virtualTool * data.endDevice_H_virtualTool.inversed(); sout << "bHe = " << baseDevice_H_endDevice << sendl; sout << "wHb = " << data.world_H_baseDevice << sendl;
codereview_new_cpp_data_6734
class StdTaskAllocator : public Task::Allocator } }; -// mac clang 3.5 doesn't support thread_local vars -//static WorkerThread* WorkerThread::_workerThreadIndex = nullptr; -// SOFA_THREAD_SPECIFIC_PTR(WorkerThread, workerThreadIndex); - -// std::map< std::thread::id, WorkerThread*> DefaultTaskScheduler::_threads; - - DefaultTaskScheduler* DefaultTaskScheduler::create() { return new DefaultTaskScheduler(); you are keeping these lines as comments on purpose? class StdTaskAllocator : public Task::Allocator } }; DefaultTaskScheduler* DefaultTaskScheduler::create() { return new DefaultTaskScheduler();
codereview_new_cpp_data_6735
void SparseGridTopology::init() } } - m_upperElementType = core::topology::TopologyElementType::HEXAHEDRON; } ```suggestion m_upperElementType = core::topology::TopologyElementType::HEXAHEDRON; ``` just a indent issue. Otherwise good to go. I'm surprised sparseGrid is not calling inherit::init() If you could change your editor to use 4 spaces as Tab void SparseGridTopology::init() } } + m_upperElementType = core::topology::TopologyElementType::HEXAHEDRON; }
codereview_new_cpp_data_6736
ConstraintAnimationLoop::ConstraintAnimationLoop(simulation::Node* gnode) , d_tol( initData(&d_tol, 0.00001_sreal, "tolerance", "Tolerance of the Gauss-Seidel")) , d_maxIt( initData(&d_maxIt, 1000, "maxIterations", "Maximum number of iterations of the Gauss-Seidel")) , d_doCollisionsFirst(initData(&d_doCollisionsFirst, false, "doCollisionsFirst","Compute the collisions first (to support penality-based contacts)")) - , d_SRealBuffer( initData(&d_SRealBuffer, false, "SRealBuffer","Buffer the constraint problem in a SReal buffer to be accessible with an other thread")) , d_scaleTolerance( initData(&d_scaleTolerance, true, "scaleTolerance","Scale the error tolerance with the number of constraints")) , d_allVerified( initData(&d_allVerified, false, "allVerified","All contraints must be verified (each constraint's error < tolerance)")) , d_sor( initData(&d_sor, 1.0_sreal, "sor","Successive Over Relaxation parameter (0-2)")) ```suggestion , d_doubleBuffer( initData(&d_doubleBuffer, false, "doubleBuffer","Buffer the constraint problem in a doublebuffer to be accessible with an other thread")) ``` ConstraintAnimationLoop::ConstraintAnimationLoop(simulation::Node* gnode) , d_tol( initData(&d_tol, 0.00001_sreal, "tolerance", "Tolerance of the Gauss-Seidel")) , d_maxIt( initData(&d_maxIt, 1000, "maxIterations", "Maximum number of iterations of the Gauss-Seidel")) , d_doCollisionsFirst(initData(&d_doCollisionsFirst, false, "doCollisionsFirst","Compute the collisions first (to support penality-based contacts)")) + , d_doubleBuffer( initData(&d_doubleBuffer, false, "doubleBuffer","Buffer the constraint problem in a doublebuffer to be accessible with an other thread")) , d_scaleTolerance( initData(&d_scaleTolerance, true, "scaleTolerance","Scale the error tolerance with the number of constraints")) , d_allVerified( initData(&d_allVerified, false, "allVerified","All contraints must be verified (each constraint's error < tolerance)")) , d_sor( initData(&d_sor, 1.0_sreal, "sor","Successive Over Relaxation parameter (0-2)"))
codereview_new_cpp_data_6737
void DynamicSparseGridTopologyModifier::init() if(!m_DynContainer) { - msg_error() << "DynamicSparseGridTopologyContainer not found in context"; d_componentState.setValue(sofa::core::objectmodel::ComponentState::Invalid); return; } Uhh... Didn't know this guy! void DynamicSparseGridTopologyModifier::init() if(!m_DynContainer) { + msg_error() << "DynamicSparseGridTopologyContainer not found in current node: " << this->getContext()->getName(); d_componentState.setValue(sofa::core::objectmodel::ComponentState::Invalid); return; }
codereview_new_cpp_data_6738
void EdgeSetTopologyModifier::init() if(!m_container) { - msg_error() << "EdgeSetTopologyContainer not found in context"; d_componentState.setValue(sofa::core::objectmodel::ComponentState::Invalid); return; } Does "context" is enough clear for users? Or maybe "current Node" / same Node as this->getName() void EdgeSetTopologyModifier::init() if(!m_container) { + msg_error() << "EdgeSetTopologyContainer not found in current node: " << this->getContext()->getName(); d_componentState.setValue(sofa::core::objectmodel::ComponentState::Invalid); return; }
codereview_new_cpp_data_6739
bool TopologicalMapping::checkTopologyInputTypes() { if (m_inputType == TopologyElementType::UNKNOWN) { - dmsg_error() << "The input TopologyElementType has not be set. Define 'm_inputType' to the correct TopologyElementType in the constructor."; return false; } if (m_outputType == TopologyElementType::UNKNOWN) { - dmsg_error() << "The output TopologyElementType has not be set. Define 'm_outputType' to the correct TopologyElementType in the constructor."; return false; } ```suggestion dmsg_error() << "The input TopologyElementType has not been set. Define 'm_inputType' to the correct TopologyElementType in the constructor."; ``` bool TopologicalMapping::checkTopologyInputTypes() { if (m_inputType == TopologyElementType::UNKNOWN) { + dmsg_error() << "The input TopologyElementType has not been set. Define 'm_inputType' to the correct TopologyElementType in the constructor."; return false; } if (m_outputType == TopologyElementType::UNKNOWN) { + dmsg_error() << "The output TopologyElementType has not been set. Define 'm_outputType' to the correct TopologyElementType in the constructor."; return false; }
codereview_new_cpp_data_6740
void RegularGridTopology::setPos(SReal xmin, SReal xmax, SReal ymin, SReal ymax, SReal p0x=xmin, p0y=ymin, p0z=zmin; const Vec3i _n = d_n.getValue() - Vec3i(1,1,1); - if (_n[0] > 0.0) setDx(Vector3((xmax - xmin) / _n[0], 0_sreal, 0_sreal)); else { ```suggestion if (_n[0] > 0) ``` void RegularGridTopology::setPos(SReal xmin, SReal xmax, SReal ymin, SReal ymax, SReal p0x=xmin, p0y=ymin, p0z=zmin; const Vec3i _n = d_n.getValue() - Vec3i(1,1,1); + if (_n[0] > 0) setDx(Vector3((xmax - xmin) / _n[0], 0_sreal, 0_sreal)); else {
codereview_new_cpp_data_6741
ImageCImgCreators::ImageCImgCreators() const std::string& ext = cimgSupportedExtensions[i]; if (!sofa::helper::io::Image::FactoryImage::HasKey(ext)) { - creators.push_back(std::make_unique<Creator<helper::io::Image::FactoryImage, ImageCImg>>(ext)); } } ```suggestion creators.push_back(std::make_shared<Creator<helper::io::Image::FactoryImage, ImageCImg>>(ext)); ``` ImageCImgCreators::ImageCImgCreators() const std::string& ext = cimgSupportedExtensions[i]; if (!sofa::helper::io::Image::FactoryImage::HasKey(ext)) { + creators.push_back(std::make_shared<Creator<helper::io::Image::FactoryImage, ImageCImg>>(ext)); } }
codereview_new_cpp_data_6742
void MeshTopology::init() BaseMeshTopology::init(); - const auto& hexahedra = seqHexahedra.getValue(); - const auto& tetrahedra = seqTetrahedra.getValue(); - const auto& quads = seqQuads.getValue(); - const auto& triangles = seqTriangles.getValue(); - const auto& edges = seqEdges.getValue(); if (nbPoints==0) { Shouldn't it be better to use an accessor there ? void MeshTopology::init() BaseMeshTopology::init(); + const auto hexahedra = sofa::helper::getReadAccessor(seqHexahedra); + const auto tetrahedra = sofa::helper::getReadAccessor(seqTetrahedra); + const auto quads = sofa::helper::getReadAccessor(seqQuads); + const auto triangles = sofa::helper::getReadAccessor(seqTriangles); + const auto edges = sofa::helper::getReadAccessor(seqEdges); if (nbPoints==0) {
codereview_new_cpp_data_6743
CarvingManager::CarvingManager() void CarvingManager::init() { // Search for collision model corresponding to the tool. - if (l_toolModel.empty()) { m_toolCollisionModel = getContext()->get<core::CollisionModel>(core::objectmodel::Tag("CarvingTool"), core::objectmodel::BaseContext::SearchRoot); } ```suggestion if (l_toolModel.get()) ``` CarvingManager::CarvingManager() void CarvingManager::init() { // Search for collision model corresponding to the tool. + if (l_toolModel.get()) { m_toolCollisionModel = getContext()->get<core::CollisionModel>(core::objectmodel::Tag("CarvingTool"), core::objectmodel::BaseContext::SearchRoot); }
codereview_new_cpp_data_6744
const int CarvingManagerClass = core::RegisterObject("Manager handling carving o CarvingManager::CarvingManager() - : l_toolModel(initLink("toolModel", "link to the carving collision model, if not set, manager wi will search for a collision model with tag: CarvingTool")) , d_surfaceModelPath( initData(&d_surfaceModelPath, "surfaceModelPath", "TriangleSetModel or SphereCollisionModel<sofa::defaulttype::Vec3Types> path")) , d_carvingDistance( initData(&d_carvingDistance, 0.0, "carvingDistance", "Collision distance at which cavring will start. Equal to contactDistance by default.")) , d_active( initData(&d_active, false, "active", "Activate this object.\nNote that this can be dynamically controlled by using a key") ) ```suggestion : l_toolModel(initLink("toolModel", "link to the carving collision model, if not set, manager will search for a collision model with tag: CarvingTool")) ``` const int CarvingManagerClass = core::RegisterObject("Manager handling carving o CarvingManager::CarvingManager() + : l_toolModel(initLink("toolModel", "link to the carving collision model, if not set, manager will search for a collision model with tag: CarvingTool")) , d_surfaceModelPath( initData(&d_surfaceModelPath, "surfaceModelPath", "TriangleSetModel or SphereCollisionModel<sofa::defaulttype::Vec3Types> path")) , d_carvingDistance( initData(&d_carvingDistance, 0.0, "carvingDistance", "Collision distance at which cavring will start. Equal to contactDistance by default.")) , d_active( initData(&d_active, false, "active", "Activate this object.\nNote that this can be dynamically controlled by using a key") )
codereview_new_cpp_data_6745
int MeshDiscreteIntersection::computeIntersection(Triangle& e1, Line& e2, Output const Line::Coord& P = e2.p1(); const Line::Coord PQ = e2.p2()-P; Mat<3, 3, Triangle::Coord::value_type> M(NOINIT); - Mat<3, 3, Triangle::Coord::value_type> Minv; Triangle::Coord right(NOINIT); for (int i=0; i<3; i++) { ```suggestion Mat<3, 3, Triangle::Coord::value_type> Minv(NOINIT); ``` int MeshDiscreteIntersection::computeIntersection(Triangle& e1, Line& e2, Output const Line::Coord& P = e2.p1(); const Line::Coord PQ = e2.p2()-P; Mat<3, 3, Triangle::Coord::value_type> M(NOINIT); + Mat<3, 3, Triangle::Coord::value_type> Minv(NOINIT); Triangle::Coord right(NOINIT); for (int i=0; i<3; i++) {
codereview_new_cpp_data_6746
std::istream& operator>>(std::istream& i, Tag& t) return i; } -} Usually in SOFA the namespace is repeated in a comment after the closing curly bracket. std::istream& operator>>(std::istream& i, Tag& t) return i; } +} // namespace sofa::core::objectmodel
codereview_new_cpp_data_6747
void TopologyContainer::resetTopologyHandlerList() { for (auto& topologyHandlerList : m_topologyHandlerListPerElement) { - std::for_each(topologyHandlerList.begin(), topologyHandlerList.end(), [](TopologyHandler* topoHandler) - { - topoHandler = nullptr; - }); - topologyHandlerList.clear(); } I am not sure this is doing what you think. `topoHandler` is a copy, not a reference void TopologyContainer::resetTopologyHandlerList() { for (auto& topologyHandlerList : m_topologyHandlerListPerElement) { topologyHandlerList.clear(); }
codereview_new_cpp_data_6748
void DrawToolGL::drawLines(const std::vector<Vector3> &points, float size, const std::map<RGBAColor, std::vector<Vector3> > colorPointsMap; for (std::size_t i = 0; i < colors.size(); ++i) { - if (colorPointsMap.find(colors[i]) == colorPointsMap.end()) - { - colorPointsMap.insert({ colors[i] , {} }); - } - colorPointsMap[colors[i]].push_back(points[2 * i]); colorPointsMap[colors[i]].push_back(points[2 * i + 1]); } // call the drawLine method which takes only one color - for (auto [color, points] : colorPointsMap) { drawLines(points, size, color); } Here is what I suggest to replace your loop: ```cpp for (std::size_t i = 0; i < colors.size(); ++i) { auto& colorPoints = colorsPointsMap[colors[i]]; colorPoints.push_back(points[2 * i]); colorPoints.push_back(points[2 * i + 1]); } ``` With your version: 3 searches in the map With my version: 1 search in the map (and more concise) void DrawToolGL::drawLines(const std::vector<Vector3> &points, float size, const std::map<RGBAColor, std::vector<Vector3> > colorPointsMap; for (std::size_t i = 0; i < colors.size(); ++i) { colorPointsMap[colors[i]].push_back(points[2 * i]); colorPointsMap[colors[i]].push_back(points[2 * i + 1]); } // call the drawLine method which takes only one color + for (const auto& [color, points] : colorPointsMap) { drawLines(points, size, color); }
codereview_new_cpp_data_6749
void DrawToolGL::drawLines(const std::vector<Vector3> &points, float size, const std::map<RGBAColor, std::vector<Vector3> > colorPointsMap; for (std::size_t i = 0; i < colors.size(); ++i) { - if (colorPointsMap.find(colors[i]) == colorPointsMap.end()) - { - colorPointsMap.insert({ colors[i] , {} }); - } - colorPointsMap[colors[i]].push_back(points[2 * i]); colorPointsMap[colors[i]].push_back(points[2 * i + 1]); } // call the drawLine method which takes only one color - for (auto [color, points] : colorPointsMap) { drawLines(points, size, color); } an `unordered_map` should be faster void DrawToolGL::drawLines(const std::vector<Vector3> &points, float size, const std::map<RGBAColor, std::vector<Vector3> > colorPointsMap; for (std::size_t i = 0; i < colors.size(); ++i) { colorPointsMap[colors[i]].push_back(points[2 * i]); colorPointsMap[colors[i]].push_back(points[2 * i + 1]); } // call the drawLine method which takes only one color + for (const auto& [color, points] : colorPointsMap) { drawLines(points, size, color); }
codereview_new_cpp_data_6750
void DrawToolGL::drawLines(const std::vector<Vector3> &points, float size, const std::map<RGBAColor, std::vector<Vector3> > colorPointsMap; for (std::size_t i = 0; i < colors.size(); ++i) { - if (colorPointsMap.find(colors[i]) == colorPointsMap.end()) - { - colorPointsMap.insert({ colors[i] , {} }); - } - colorPointsMap[colors[i]].push_back(points[2 * i]); colorPointsMap[colors[i]].push_back(points[2 * i + 1]); } // call the drawLine method which takes only one color - for (auto [color, points] : colorPointsMap) { drawLines(points, size, color); } I am not sure here if you copy a pair of key/value or if it is implicitly a reference. That's why I would have written `for (const auto& [color, points] : colorPointsMap)` void DrawToolGL::drawLines(const std::vector<Vector3> &points, float size, const std::map<RGBAColor, std::vector<Vector3> > colorPointsMap; for (std::size_t i = 0; i < colors.size(); ++i) { colorPointsMap[colors[i]].push_back(points[2 * i]); colorPointsMap[colors[i]].push_back(points[2 * i + 1]); } // call the drawLine method which takes only one color + for (const auto& [color, points] : colorPointsMap) { drawLines(points, size, color); }
codereview_new_cpp_data_6751
Index TopologicalChangeManager::removeItemsFromLineModel(LineCollisionModel<sofa topo_curr = model->getCollisionTopology(); if(dynamic_cast<EdgeSetTopologyContainer*>(topo_curr) == nullptr){ - msg_warning("TopologicalChangeManager") << " Topology is not an EdgeSetTopologyContainer. Only EdgeSetTopologyContainer implemented."; return 0; } // copy indices to have a mutable version of the vector type::vector<Index> unique_indices = indices; // sort followed by unique, to remove all duplicates std::sort(unique_indices.begin(), unique_indices.end()); - unique_indices.erase( std::unique(unique_indices.begin(), unique_indices.end()), unique_indices.end()); - simulation::Node *node_curr = dynamic_cast<simulation::Node*>(topo_curr->getContext()); - sofa::core::topology::TopologyModifier* topoMod; - topo_curr->getContext()->get(topoMod); - topoMod->removeItems(unique_indices); - topoMod->notifyEndingEvent(); - topoMod->propagateTopologicalChanges(); return indices.size(); } Is such syntax possible ? ```cpp auto topoMod = topo_curr->getContext()->get<sofa::core::topology::TopologyModifier>() ``` Index TopologicalChangeManager::removeItemsFromLineModel(LineCollisionModel<sofa topo_curr = model->getCollisionTopology(); if(dynamic_cast<EdgeSetTopologyContainer*>(topo_curr) == nullptr){ + msg_warning("TopologicalChangeManager") << "Topology is not an EdgeSetTopologyContainer. Only EdgeSetTopologyContainer implemented."; return 0; } // copy indices to have a mutable version of the vector type::vector<Index> unique_indices = indices; // sort followed by unique, to remove all duplicates std::sort(unique_indices.begin(), unique_indices.end()); + unique_indices.erase(std::unique(unique_indices.begin(), unique_indices.end()), unique_indices.end()); + auto topo_mod = topo_curr->getContext()->get<sofa::core::topology::TopologyModifier>(); + if(dynamic_cast<EdgeSetTopologyModifier*>(topo_mod) == nullptr){ + msg_warning("TopologicalChangeManager") << "Cannot find an EdgeSetTopologyModifier to perform the changes."; + return 0; + } + topo_mod->removeItems(unique_indices); + topo_mod->notifyEndingEvent(); + topo_mod->propagateTopologicalChanges(); return indices.size(); }
codereview_new_cpp_data_6752
Index TopologicalChangeManager::removeItemsFromLineModel(LineCollisionModel<sofa std::sort(unique_indices.begin(), unique_indices.end()); unique_indices.erase(std::unique(unique_indices.begin(), unique_indices.end()), unique_indices.end()); - auto topo_mod = topo_curr->getContext()->get<sofa::core::topology::TopologyModifier>(); - if(dynamic_cast<EdgeSetTopologyModifier*>(topo_mod) == nullptr){ msg_warning("TopologicalChangeManager") << "Cannot find an EdgeSetTopologyModifier to perform the changes."; return 0; } ```suggestion auto topo_mod = topo_curr->getContext()->get<EdgeSetTopologyModifier>(); if(topo_mod == nullptr) { msg_warning("TopologicalChangeManager") << "Cannot find an EdgeSetTopologyModifier to perform the changes."; return 0; } ``` Index TopologicalChangeManager::removeItemsFromLineModel(LineCollisionModel<sofa std::sort(unique_indices.begin(), unique_indices.end()); unique_indices.erase(std::unique(unique_indices.begin(), unique_indices.end()), unique_indices.end()); + auto topo_mod = topo_curr->getContext()->get<EdgeSetTopologyModifier>(); + if(topo_mod == nullptr){ msg_warning("TopologicalChangeManager") << "Cannot find an EdgeSetTopologyModifier to perform the changes."; return 0; }
codereview_new_cpp_data_6753
void GenericConstraintCorrection::bwdInit() { BaseContext* context = this->getContext(); - // Find linear solvers if (l_linearSolver.empty()) { msg_info() << "Link \"linearSolver\" to the desired linear solver should be set to ensure right behavior." << msgendl ```suggestion // Find linear solver ``` void GenericConstraintCorrection::bwdInit() { BaseContext* context = this->getContext(); + // Find linear solver if (l_linearSolver.empty()) { msg_info() << "Link \"linearSolver\" to the desired linear solver should be set to ensure right behavior." << msgendl
codereview_new_cpp_data_6754
objectmodel::BaseObject::SPtr ObjectFactory::createObject(objectmodel::BaseConte using sofa::helper::lifecycle::uncreatableComponents; if(it == registry.end()) { - arg->logError("The object '"+classname+"' is not in the factory."); auto uuncreatableComponent = uncreatableComponents.find(classname); if( uuncreatableComponent != uncreatableComponents.end() ) { ```suggestion arg->logError("The object '" + classname + "' is not in the factory."); ``` objectmodel::BaseObject::SPtr ObjectFactory::createObject(objectmodel::BaseConte using sofa::helper::lifecycle::uncreatableComponents; if(it == registry.end()) { + arg->logError("The object '" + classname + "' is not in the factory."); auto uuncreatableComponent = uncreatableComponents.find(classname); if( uuncreatableComponent != uncreatableComponents.end() ) {
codereview_new_cpp_data_6755
const int CudaLinearSolverConstraintCorrectionClass = core::RegisterObject("Supp .add< LinearSolverConstraintCorrection< CudaVec3f1Types > >() ; -} // namespace sofa::component::constraintset ```suggestion } // namespace sofa::component::constraint::lagrangian::correction ``` const int CudaLinearSolverConstraintCorrectionClass = core::RegisterObject("Supp .add< LinearSolverConstraintCorrection< CudaVec3f1Types > >() ; +} // namespace sofa::component::constraint::lagrangian::correction
codereview_new_cpp_data_6949
get_bundle_appstream_data (GFile *root, GCancellable *cancellable, GError **error) { - g_autoptr(GFile) xmls_dir = NULL; - g_autofree char *appstream_basename = NULL; g_autoptr(GFile) appstream_file = NULL; g_autoptr(GInputStream) xml_in = NULL; *result = NULL; - - appstream_file = g_file_resolve_relative_path (root, "files/share/swcatalog/xml/flatpak.xml.gz"); - if (!g_file_test (g_file_peek_path (appstream_file), G_FILE_TEST_EXISTS)) - { - g_clear_object (&appstream_file); - xmls_dir = g_file_resolve_relative_path (root, "files/share/app-info/xmls"); - appstream_basename = g_strconcat (name, ".xml.gz", NULL); - appstream_file = g_file_get_child (xmls_dir, appstream_basename); - } xml_in = (GInputStream *) g_file_read (appstream_file, cancellable, NULL); if (xml_in) As I mentioned in the other PR. This same logic is repeated like 3 times. I think this could be pulled out into a function to just get the correct path in `flatpak-utils.c` perhaps. get_bundle_appstream_data (GFile *root, GCancellable *cancellable, GError **error) { g_autoptr(GFile) appstream_file = NULL; g_autoptr(GInputStream) xml_in = NULL; *result = NULL; + + flatpak_appstream_get_xml_path (root, &appstream_file, NULL, name, NULL); xml_in = (GInputStream *) g_file_read (appstream_file, cancellable, NULL); if (xml_in)
codereview_new_cpp_data_6950
iterate_bundle_icons (GFile *root, g_autoptr(GFile) icons_dir = g_file_resolve_relative_path (root, "files/share/app-info/icons/flatpak"); - if (!g_file_test(g_file_peek_path(icons_dir), G_FILE_TEST_IS_DIR)) { icons_dir = g_file_resolve_relative_path (root, "files/share/swcatalog/icons/flatpak"); } ```suggestion if (!g_file_test (g_file_peek_path (icons_dir), G_FILE_TEST_IS_DIR)) { ``` iterate_bundle_icons (GFile *root, g_autoptr(GFile) icons_dir = g_file_resolve_relative_path (root, "files/share/app-info/icons/flatpak"); + if (!g_file_test (g_file_peek_path (icons_dir), G_FILE_TEST_IS_DIR)) { icons_dir = g_file_resolve_relative_path (root, "files/share/swcatalog/icons/flatpak"); }
codereview_new_cpp_data_6951
void FixAmoebaBiTorsion::init() // error check that PairAmoeba or PairHiippo exist pair = nullptr; - pair = force->pair_match("amoeba",1,0); - if (!pair) pair = force->pair_match("amoeba/gpu",1,0); - if (!pair) pair = force->pair_match("hippo",1,0); - if (!pair) pair = force->pair_match("hippo/gpu",1,0); if (!pair) error->all(FLERR,"Cannot use fix amoeba/bitorsion w/out pair amoeba/hippo"); This section could also be done as: ``` pair = force->pair_match("^amoeba",0,0); if (!pair) pair = force->pair_match("^hippo",0,0); ``` void FixAmoebaBiTorsion::init() // error check that PairAmoeba or PairHiippo exist pair = nullptr; + pair = force->pair_match("^amoeba",0,0); + if (!pair) pair = force->pair_match("^hippo",0,0); if (!pair) error->all(FLERR,"Cannot use fix amoeba/bitorsion w/out pair amoeba/hippo");
codereview_new_cpp_data_6952
PPPMGPU::PPPMGPU(LAMMPS *lmp) : PPPM(lmp) PPPMGPU::~PPPMGPU() { PPPM_GPU_API(clear)(poisson_time); } /* ---------------------------------------------------------------------- This will introduce a memory leak. PPPMGPU::PPPMGPU(LAMMPS *lmp) : PPPM(lmp) PPPMGPU::~PPPMGPU() { PPPM_GPU_API(clear)(poisson_time); + destroy_3d_offset(density_brick_gpu,nzlo_out,nylo_out); + destroy_3d_offset(vd_brick,nzlo_out,nylo_out); } /* ----------------------------------------------------------------------
codereview_new_cpp_data_6953
void Atom::setup_sort_bins() } #ifdef LMP_GPU - if (userbinsize == 0.0) { - int ifix = modify->find_fix("package_gpu"); - if (ifix >= 0) { const double subx = domain->subhi[0] - domain->sublo[0]; const double suby = domain->subhi[1] - domain->sublo[1]; const double subz = domain->subhi[2] - domain->sublo[2]; - - FixGPU *fix = static_cast<FixGPU *>(modify->fix[ifix]); - binsize = fix->binsize(subx, suby, subz, atom->nlocal, - 0.5 * neighbor->cutneighmax); } } #endif This is using obsolescent internal APIs. The modern way to do this is: ``` if (userbinsize == 0.0) { auto ifix = dynamic_cast<FixGPU *>(modify->get_fix_by_id("package_gpu")); if (ifix) { const double subx = domain->subhi[0] - domain->sublo[0]; const double suby = domain->subhi[1] - domain->sublo[1]; const double subz = domain->subhi[2] - domain->sublo[2]; binsize = ifix->binsize(subx, suby, subz, atom->nlocal, 0.5 * neighbor->cutneighmax); } } ``` void Atom::setup_sort_bins() } #ifdef LMP_GPU + if (userbinsize == 0.0) { + auto ifix = dynamic_cast<FixGPU *>(modify->get_fix_by_id("package_gpu")); + if (ifix) { const double subx = domain->subhi[0] - domain->sublo[0]; const double suby = domain->subhi[1] - domain->sublo[1]; const double subz = domain->subhi[2] - domain->sublo[2]; + binsize = ifix->binsize(subx, suby, subz, atom->nlocal, 0.5 * neighbor->cutneighmax); } } #endif
codereview_new_cpp_data_6954
FixPair::FixPair(LAMMPS *lmp, int narg, char **arg) : if (nevery < 1) error->all(FLERR,"Illegal fix pair every value: {}", nevery); pairname = utils::strdup(arg[4]); - if(lmp->suffix) { - strcat(pairname,"/"); - strcat(pairname,lmp->suffix); } - pstyle = force->pair_match(pairname,1,0); if (pstyle == nullptr) error->all(FLERR,"Pair style {} for fix pair not found", pairname); nfield = (narg-5) / 2; In other places we use the `^` regex. This logic will not work for `suffix2`. FixPair::FixPair(LAMMPS *lmp, int narg, char **arg) : if (nevery < 1) error->all(FLERR,"Illegal fix pair every value: {}", nevery); pairname = utils::strdup(arg[4]); + char *cptr; + int nsub = 0; + if ((cptr = strchr(pairname,':'))) { + *cptr = '\0'; + nsub = utils::inumeric(FLERR,cptr+1,false,lmp); } + + if (lmp->suffix_enable) { + if (lmp->suffix) + pstyle = force->pair_match(fmt::format("{}/{}",pairname,lmp->suffix),1,nsub); + if ((pstyle == nullptr) && lmp->suffix2) + pstyle = force->pair_match(fmt::format("{}/{}",pairname,lmp->suffix2),1,nsub); + } + if (pstyle == nullptr) pstyle = force->pair_match(pairname,1,nsub); if (pstyle == nullptr) error->all(FLERR,"Pair style {} for fix pair not found", pairname); nfield = (narg-5) / 2;
codereview_new_cpp_data_6955
LAMMPS::LAMMPS(int narg, char **arg, MPI_Comm communicator) : while (iarg < narg && arg[iarg][0] != '-') iarg++; } else { - std::string errmsg("Invalid command-line argument"); - errmsg += arg[iarg]; - error->universe_all(FLERR,errmsg.c_str()); } } ```suggestion std::string errmsg("Unknown pair style mliap argument: "); ``` LAMMPS::LAMMPS(int narg, char **arg, MPI_Comm communicator) : while (iarg < narg && arg[iarg][0] != '-') iarg++; } else { + error->universe_all(FLERR, fmt::format("Unknown pair style mliap argument: {}", arg[iarg]) ); } }
codereview_new_cpp_data_6956
LAMMPS::LAMMPS(int narg, char **arg, MPI_Comm communicator) : while (iarg < narg && arg[iarg][0] != '-') iarg++; } else { - std::string errmsg("Invalid command-line argument"); - errmsg += arg[iarg]; - error->universe_all(FLERR,errmsg.c_str()); } } ```suggestion error->universe_all(FLERR,errmsg); ``` Alternately, it should be possible to use just a single line like this: `error->universe_all(FLERR, fmt::format("Unknown pair style mliap argument: {}", arg[iarg]));` LAMMPS::LAMMPS(int narg, char **arg, MPI_Comm communicator) : while (iarg < narg && arg[iarg][0] != '-') iarg++; } else { + error->universe_all(FLERR, fmt::format("Unknown pair style mliap argument: {}", arg[iarg]) ); } }
codereview_new_cpp_data_6957
template<class DeviceType> PairDPDExtKokkos<DeviceType>::PairDPDExtKokkos(class LAMMPS *_lmp) : PairDPDExt(_lmp) , #ifdef DPD_USE_RAN_MARS - rand_pool(0 /* unused */, lmp) #else rand_pool() #endif @akohlmey is changing `lmp` to `_lmp` necessary? Looks like this change was missed here (for `#ifdef DPD_USE_RAN_MARS`) template<class DeviceType> PairDPDExtKokkos<DeviceType>::PairDPDExtKokkos(class LAMMPS *_lmp) : PairDPDExt(_lmp) , #ifdef DPD_USE_RAN_MARS + rand_pool(0 /* unused */, _lmp) #else rand_pool() #endif
codereview_new_cpp_data_6958
void Domain::subbox_too_small_check(double thresh) this should not be used if atom has moved infinitely far outside box b/c while could iterate forever e.g. fix shake prediction of new position with highly overlapped atoms - use minimum_image_once() instead ------------------------------------------------------------------------- */ -#ifdef LAMMPS_BIGBIG -static constexpr double MAXIMGCOUNT = 1<<21; -#else -static constexpr double MAXIMGCOUNT = 1<<10; -#endif void Domain::minimum_image(double &dx, double &dy, double &dz) { Why not make MAXIMGCOUNT much smaller, e.g. 1024 or even 4. Are there cases when a value > 4 between a pair of atoms is not an indication of a bad dynamics ? void Domain::subbox_too_small_check(double thresh) this should not be used if atom has moved infinitely far outside box b/c while could iterate forever e.g. fix shake prediction of new position with highly overlapped atoms + uses minimum_image_once() instead ------------------------------------------------------------------------- */ +static constexpr double MAXIMGCOUNT = 16; void Domain::minimum_image(double &dx, double &dy, double &dz) {
codereview_new_cpp_data_6959
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator https://www.lammps.org/, Sandia National Laboratories - The LAMMPS Developers, developers@lammps.org Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains i'd prefer this line be like this everywhere: LAMMPS development team: developers@lammps.org /* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator https://www.lammps.org/, Sandia National Laboratories + LAMMPS development team: developers@lammps.org Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
codereview_new_cpp_data_6960
void Replicate::command(int narg, char **arg) int nrep = nx*ny*nz; if (me == 0) - utils::logmesg(lmp,"Replicating atoms for a {}x{}x{} = {} times size system...\n", nx, ny, nz, nrep); int bbox_flag = 0; if (narg == 4) Replication is creating a {}x{}x{} = {}x larger system void Replicate::command(int narg, char **arg) int nrep = nx*ny*nz; if (me == 0) + utils::logmesg(lmp, "Replication is creating a {}x{}x{} = {} times larger system...\n", + nx, ny, nz, nrep); int bbox_flag = 0; if (narg == 4)
codereview_new_cpp_data_6961
#include <cmath> using namespace LAMMPS_NS; -using namespace MathConst; static constexpr double SMALL = 0.001; static constexpr double A_CC = 1.421; ```suggestion using MathConst::MY_PI; using MathConst::MY_2PI; ``` #include <cmath> using namespace LAMMPS_NS; +using MathConst::MY_PI; +using MathConst::MY_2PI; static constexpr double SMALL = 0.001; static constexpr double A_CC = 1.421;
codereview_new_cpp_data_6962
enum{ISO,ANISO,TRICLINIC}; // citation info static const char cite_user_uef_package[] = - "UEF package: src:10.1063/1.4972894\n\n" "@Article{NicholsonRutledge16,\n" "author = {David A. Nicholson and Gregory C. Rutledge},\n" "title = {Molecular Simulation of Flow-Enhanced Nucleation in\n", ```suggestion "UEF package: doi:10.1063/1.4972894\n\n" ``` enum{ISO,ANISO,TRICLINIC}; // citation info static const char cite_user_uef_package[] = + "UEF package: doi:10.1063/1.4972894\n\n" "@Article{NicholsonRutledge16,\n" "author = {David A. Nicholson and Gregory C. Rutledge},\n" "title = {Molecular Simulation of Flow-Enhanced Nucleation in\n",
codereview_new_cpp_data_6963
enum{ISO,ANISO,TRICLINIC}; // citation info static const char cite_user_uef_package[] = - "UEF package: src:10.1063/1.4972894\n\n" "@Article{NicholsonRutledge16,\n" "author = {David A. Nicholson and Gregory C. Rutledge},\n" "title = {Molecular Simulation of Flow-Enhanced Nucleation in\n", ```suggestion "title = {Molecular Simulation of Flow-Enhanced Nucleation in" ``` enum{ISO,ANISO,TRICLINIC}; // citation info static const char cite_user_uef_package[] = + "UEF package: doi:10.1063/1.4972894\n\n" "@Article{NicholsonRutledge16,\n" "author = {David A. Nicholson and Gregory C. Rutledge},\n" "title = {Molecular Simulation of Flow-Enhanced Nucleation in\n",
codereview_new_cpp_data_6964
static const char cite_gpu_package[] = "}\n\n" "@Article{Trung17,\n" " author = {T. D. Nguyen},\n" - " title = {{GPU}-Accelerated {T}ersoff Potentials for Massively Parallel Molecular Dynamics Simulations},\n" - " journal = {Comput.\ Phys.\ Commun.},\n" " year = 2017,\n" " doi = {10.1016/j.cpc.2016.10.020},\n" " volume = 212,\n" " pages = {113--122}\n" "}\n\n" "@inproceedings{Nikolskiy19,\n" - " author = {V. Nikolskiy, V. Stegailov},\n" " title = {{GPU} Acceleration of Four-Site Water Models in {LAMMPS}},\n" - " booktitle = {Proceedings of the International Conference on Parallel Computing (ParCo 2019), Prague, Czech Republic},\n" - " doi = {10.3233/APC200086}\n" " year = 2019\n" "}\n\n"; ```suggestion " journal = {Comput.\\ Phys.\\ Commun.},\n" ``` static const char cite_gpu_package[] = "}\n\n" "@Article{Trung17,\n" " author = {T. D. Nguyen},\n" + " title = {{GPU}-Accelerated {T}ersoff Potentials for Massively Parallel\n" + " Molecular Dynamics Simulations},\n" + " journal = {Comput.\\ Phys.\\ Commun.},\n" " year = 2017,\n" " doi = {10.1016/j.cpc.2016.10.020},\n" " volume = 212,\n" " pages = {113--122}\n" "}\n\n" "@inproceedings{Nikolskiy19,\n" + " author = {V. Nikolskiy and V. Stegailov},\n" " title = {{GPU} Acceleration of Four-Site Water Models in {LAMMPS}},\n" + " booktitle = {Proceedings of the International Conference on Parallel\n" + " Computing (ParCo 2019), Prague, Czech Republic},\n" + " doi = {10.3233/APC200086},\n" " year = 2019\n" "}\n\n";
codereview_new_cpp_data_6965
static const char cite_user_uef_package[] = "volume = {145},\n" "number = {24},\n" "pages = {244903},\n" - "doi = {10.1063/1.4972894},\n", "year = {2016}\n" "}\n\n"; ```suggestion "doi = {10.1063/1.4972894},\n" ``` static const char cite_user_uef_package[] = "volume = {145},\n" "number = {24},\n" "pages = {244903},\n" + "doi = {10.1063/1.4972894},\n" "year = {2016}\n" "}\n\n";
codereview_new_cpp_data_6966
void FixMDIQM::post_force(int vflag) if (ierr) error->all(FLERR, "MDI: <STRESS command"); ierr = MDI_Recv(qm_virial, 9, MDI_DOUBLE, mdicomm); if (ierr) error->all(FLERR, "MDI: <STRESS data"); - //for (int i = 0; i < 9; i++) { - // qm_virial[i] = 0.0; - //} MPI_Bcast(qm_virial, 9, MPI_DOUBLE, 0, world); qm_virial_symmetric[0] = qm_virial[0] * mdi2lmp_pressure; delete these lines? void FixMDIQM::post_force(int vflag) if (ierr) error->all(FLERR, "MDI: <STRESS command"); ierr = MDI_Recv(qm_virial, 9, MDI_DOUBLE, mdicomm); if (ierr) error->all(FLERR, "MDI: <STRESS data"); MPI_Bcast(qm_virial, 9, MPI_DOUBLE, 0, world); qm_virial_symmetric[0] = qm_virial[0] * mdi2lmp_pressure;
codereview_new_cpp_data_6968
double FixPair::memory_usage() else bytes += (double)atom->nmax*ncols * sizeof(double); return bytes; } - -int FixPair::modify_param(int narg, char **arg) { - int processed_args=0; - int iarg = 0; - while (iarg < narg) { - if (strcmp(arg[iarg], "every") == 0) { - nevery = utils::inumeric(FLERR, arg[iarg+1], false, lmp); - if (nevery < 1) error->all(FLERR, "Illegal fix_modify pair every value: {}", nevery); - iarg += 2; - processed_args+=2; - } else - iarg +=1; - } - - return processed_args; // how many arguments were processed -} This added feature needs to be documented. double FixPair::memory_usage() else bytes += (double)atom->nmax*ncols * sizeof(double); return bytes; }
codereview_new_cpp_data_7067
flb_sds_t flb_get_s3_key(const char *format, time_t time, const char *tag, sprintf(seq_index_str, "%"PRIu64, seq_index); seq_index_str[seq_index_len] = '\0'; tmp_key = replace_uri_tokens(s3_key, INDEX_STRING, seq_index_str); - if (!tmp_key) { goto error; } if (strlen(tmp_key) > S3_KEY_SIZE) { I think you're missing a `flb_free(seq_index_str);` there. Other than that, would you mind change that comparison to `if (tmp_key == NULL) {` instead? I'd really appreciate it. flb_sds_t flb_get_s3_key(const char *format, time_t time, const char *tag, sprintf(seq_index_str, "%"PRIu64, seq_index); seq_index_str[seq_index_len] = '\0'; tmp_key = replace_uri_tokens(s3_key, INDEX_STRING, seq_index_str); + if (tmp_key == NULL) { + flb_free(seq_index_str); goto error; } if (strlen(tmp_key) > S3_KEY_SIZE) {
codereview_new_cpp_data_7068
struct flb_config *flb_config_init() memset(&config->tasks_map, '\0', sizeof(config->tasks_map)); /* Environment */ config->env = flb_env_create(); - if (!config->env) { flb_error("[config] environment creation failed"); flb_config_exit(config); return NULL; } /* Multiline core */ - mk_list_init(&config->multiline_parsers); ret = flb_ml_init(config); if (ret == -1) { flb_error("[config] multiline core initialization failed"); Would you mind changing this comparison to `if (config->env == NULL)` if you happen to make the change requested in the other file? struct flb_config *flb_config_init() memset(&config->tasks_map, '\0', sizeof(config->tasks_map)); + /* Initialize multiline-parser list. We need this here, because from now + * on we use flb_config_exit to cleanup the config, which requires + * the config->multiline_parsers list to be initialized. */ + mk_list_init(&config->multiline_parsers); + /* Environment */ config->env = flb_env_create(); + if (config->env == NULL) { flb_error("[config] environment creation failed"); flb_config_exit(config); return NULL; } /* Multiline core */ ret = flb_ml_init(config); if (ret == -1) { flb_error("[config] multiline core initialization failed");
codereview_new_cpp_data_7069
static void update_retry_metric(struct flb_stackdriver *ctx, uint64_t ts, int http_status, int ret_code) { if (ret_code != FLB_RETRY) { return; } - char tmp[32]; - char *name = (char *) flb_output_name(ctx->ins); - /* convert status to string format */ snprintf(tmp, sizeof(tmp) - 1, "%i", http_status); cmt_counter_add(ctx->cmt_retried_records_total, define vars at the top of the function: https://github.com/fluent/fluent-bit/blob/master/CONTRIBUTING.md#variable-definitions static void update_retry_metric(struct flb_stackdriver *ctx, uint64_t ts, int http_status, int ret_code) { + char tmp[32]; + char *name = (char *) flb_output_name(ctx->ins); + if (ret_code != FLB_RETRY) { return; } /* convert status to string format */ snprintf(tmp, sizeof(tmp) - 1, "%i", http_status); cmt_counter_add(ctx->cmt_retried_records_total,
codereview_new_cpp_data_7070
static void pipeline_config_add_properties(flb_sds_t *buf, struct mk_list *props flb_sds_printf(buf, " %s ", kv->key); if (is_sensitive_property(kv->key)) { - flb_sds_cat(*buf, "--redacted--", strlen("--redacted--")); } else { - flb_sds_cat(*buf, kv->val, strlen(kv->val)); } - flb_sds_cat(*buf, "\n", 1); } } } can you use flb_sds_cat_safe() version ?, that version will take care if a realloc happens and the address change. static void pipeline_config_add_properties(flb_sds_t *buf, struct mk_list *props flb_sds_printf(buf, " %s ", kv->key); if (is_sensitive_property(kv->key)) { + flb_sds_cat_safe(*buf, "--redacted--", strlen("--redacted--")); } else { + flb_sds_cat_safe(*buf, kv->val, strlen(kv->val)); } + flb_sds_cat_safe(*buf, "\n", 1); } } }
codereview_new_cpp_data_7071
static int flb_proxy_input_cb_exit(void *in_context, struct flb_config *config) if (proxy->def->proxy == FLB_PROXY_GOLANG) { #ifdef FLB_HAVE_PROXY_GO - proxy_go_output_destroy(ctx); #endif } Is proxy_go_input_destroy correct here? `proxy_go_output_destroy` does not proceed to handle `struct flb_plugin_input_proxy_context ` variable. static int flb_proxy_input_cb_exit(void *in_context, struct flb_config *config) if (proxy->def->proxy == FLB_PROXY_GOLANG) { #ifdef FLB_HAVE_PROXY_GO + proxy_go_input_destroy(ctx); #endif }
codereview_new_cpp_data_7072
static flb_sds_t add_aws_auth(struct flb_http_client *c, signature = flb_signv4_do(c, FLB_TRUE, FLB_TRUE, time(NULL), ctx->aws_region, "es", - 0, ctx->aws_provider); if (!signature) { flb_plg_error(ctx->ins, "could not sign request with sigv4"); @matthewfala We need to test this with opensearch without using the new option to ensure there is no regression. Since this applies to all requests, even if the new option is not set. Need to check if opensearch always allows S3 signing mode. static flb_sds_t add_aws_auth(struct flb_http_client *c, signature = flb_signv4_do(c, FLB_TRUE, FLB_TRUE, time(NULL), ctx->aws_region, "es", + 0, NULL, ctx->aws_provider); if (!signature) { flb_plg_error(ctx->ins, "could not sign request with sigv4");
codereview_new_cpp_data_7073
static flb_sds_t add_aws_auth(struct flb_http_client *c, signature = flb_signv4_do(c, FLB_TRUE, FLB_TRUE, time(NULL), ctx->aws_region, "es", - 0, ctx->aws_provider); if (!signature) { flb_plg_error(ctx->ins, "could not sign request with sigv4"); So I've heard that: > You can't include Content-Length as a signed header, otherwise you'll get an invalid signature error. Currently, content-length is added in the http client `add_host_and_content_length` function which is called when you create a client- do we need to add some code here to ignore that header? I think I remember that when we worked on this before we did... static flb_sds_t add_aws_auth(struct flb_http_client *c, signature = flb_signv4_do(c, FLB_TRUE, FLB_TRUE, time(NULL), ctx->aws_region, "es", + 0, NULL, ctx->aws_provider); if (!signature) { flb_plg_error(ctx->ins, "could not sign request with sigv4");
codereview_new_cpp_data_7074
static flb_sds_t add_aws_auth(struct flb_http_client *c, signature = flb_signv4_do(c, FLB_TRUE, FLB_TRUE, time(NULL), ctx->aws_region, "es", - 0, ctx->aws_provider); if (!signature) { flb_plg_error(ctx->ins, "could not sign request with sigv4"); Don't we want to add the AWS unsigned headers in `es` as well? Otherwise there is no point in adding the AWS_Service_Name field to this plugin I think? static flb_sds_t add_aws_auth(struct flb_http_client *c, signature = flb_signv4_do(c, FLB_TRUE, FLB_TRUE, time(NULL), ctx->aws_region, "es", + 0, NULL, ctx->aws_provider); if (!signature) { flb_plg_error(ctx->ins, "could not sign request with sigv4");
codereview_new_cpp_data_7075
TEST_LIST = { {"filter_parser_ignore_malformed_time", flb_test_filter_parser_ignore_malformed_time }, {"filter_parser_preserve_original_field", flb_test_filter_parser_preserve_original_field }, {"filter_parser_first_matched_when_multiple_parser", flb_test_filter_parser_first_matched_when_mutilple_parser }, - {"filter_parser_skip_empty_values_false", flb_test_filter_parser_skip_empty_values_false }, {NULL, NULL} }; Unexpected adding trailing space here? TEST_LIST = { {"filter_parser_ignore_malformed_time", flb_test_filter_parser_ignore_malformed_time }, {"filter_parser_preserve_original_field", flb_test_filter_parser_preserve_original_field }, {"filter_parser_first_matched_when_multiple_parser", flb_test_filter_parser_first_matched_when_mutilple_parser }, + {"filter_parser_skip_empty_values_false", flb_test_filter_parser_skip_empty_values_false}, {NULL, NULL} };
codereview_new_cpp_data_7076
static struct flb_config_map config_map[] = { { FLB_CONFIG_MAP_BOOL, "use_ansi", "false", 0, FLB_TRUE, offsetof(struct winevtlog_config, ignore_missing_channels), - "Use ANSI encoding on eventlog messages" }, /* EOF */ Could you use the actual description and parameter here like as `ignore_missing_channels` or similar? static struct flb_config_map config_map[] = { { FLB_CONFIG_MAP_BOOL, "use_ansi", "false", 0, FLB_TRUE, offsetof(struct winevtlog_config, ignore_missing_channels), + "Whether to ignore channels missing in eventlog" }, /* EOF */
codereview_new_cpp_data_7077
struct mk_list *winevtlog_open_all(const char *channels, int read_existing_event if (ch) { mk_list_add(&ch->_head, list); } } else { if (!ch) { Suppress errors on subscribing non-existent channel is fine. But, we should display warnings when subscribing non-existent channels like as: ```c else { flb_warn("channel %s does not exist", ch); } ``` struct mk_list *winevtlog_open_all(const char *channels, int read_existing_event if (ch) { mk_list_add(&ch->_head, list); } + else { + flb_debug("[in_winevtlog] channel '%s' does not exist", channel); + } } else { if (!ch) {
codereview_new_cpp_data_7078
static int msgpack_object_to_ra_value(msgpack_object o, /* Handle cases where flb_sds_create_len fails */ if (result->val.string == NULL) { - return -1; } return 0; } please align to 4 spaces as indentation static int msgpack_object_to_ra_value(msgpack_object o, /* Handle cases where flb_sds_create_len fails */ if (result->val.string == NULL) { + return -1; } return 0; }
codereview_new_cpp_data_7079
char *flb_tail_file_name(struct flb_tail_file *file) break; } } - flb_free(file_entries); #endif return buf; } This should be a `free` call because the system uses `malloc` to reserve that memory whereas fluent-bit could be using its own allocator and that could cause an issue. char *flb_tail_file_name(struct flb_tail_file *file) break; } } + free(file_entries); #endif return buf; }
codereview_new_cpp_data_7080
static int parser_conf_file(const char *cfg, struct flb_cf *cf, } if (types_len) { for (i=0; i<types_len; i++){ - if (types[i].key != NULL) { flb_free(types[i].key); - } } flb_free(types); } Could you check indentation level ? static int parser_conf_file(const char *cfg, struct flb_cf *cf, } if (types_len) { for (i=0; i<types_len; i++){ + if (types[i].key != NULL) { flb_free(types[i].key); + } } flb_free(types); }
codereview_new_cpp_data_7081
int flb_input_collector_fd(flb_pipefd_t fd, struct flb_config *config) else { if (collector->cb_collect(collector->instance, config, collector->instance->context) == -1) { - return -1; - } } return 0; Could you check indentation level ? int flb_input_collector_fd(flb_pipefd_t fd, struct flb_config *config) else { if (collector->cb_collect(collector->instance, config, collector->instance->context) == -1) { + return -1; + } } return 0;
codereview_new_cpp_data_7082
static void cb_stdout_flush(struct flb_event_chunk *event_chunk, printf("%"PRIu32".%09lu, ", (uint32_t)tmp.tm.tv_sec, tmp.tm.tv_nsec); msgpack_object_print(stdout, *p); printf("]\n"); - } } msgpack_unpacked_destroy(&result); flb_free(buf); Could you check indentation level ? static void cb_stdout_flush(struct flb_event_chunk *event_chunk, printf("%"PRIu32".%09lu, ", (uint32_t)tmp.tm.tv_sec, tmp.tm.tv_nsec); msgpack_object_print(stdout, *p); printf("]\n"); + } } msgpack_unpacked_destroy(&result); flb_free(buf);
codereview_new_cpp_data_7083
void test_multiline_parser(msgpack_object *root2, int rand_val) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { if (random_strings[j] != NULL) { - /* stream_ids index by j, random_strings index by i */ flb_ml_append(ml, stream_ids[j], FLB_ML_TYPE_TEXT, &tm2, random_strings[i], strlen(random_strings[i])); flb_ml_append(ml, stream_ids[j], Could you check indentation level ? void test_multiline_parser(msgpack_object *root2, int rand_val) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { if (random_strings[j] != NULL) { + /* stream_ids index by j, random_strings index by i */ flb_ml_append(ml, stream_ids[j], FLB_ML_TYPE_TEXT, &tm2, random_strings[i], strlen(random_strings[i])); flb_ml_append(ml, stream_ids[j],
codereview_new_cpp_data_7091
double proj_strtod(const char *str, char **endptr) { if (strncmp(p, "NaN", 3) == 0) { if (endptr) *endptr = const_cast<char *>(p + 3); - return NAN; } /* non-numeric? */ I'm not sure how strict/flexible this code needs to be. It specifically checks for only NaN (not "nan", not "NAN", etc). It also doesn't do anything if the character after NaN is a whitespace. For a valid NaN it should be, but right now someone could technically enter the next coordinate number right after a NaN (ex. `NaN0.0m` would be two values I think). double proj_strtod(const char *str, char **endptr) { if (strncmp(p, "NaN", 3) == 0) { if (endptr) *endptr = const_cast<char *>(p + 3); + return std::numeric_limits<double>::quiet_NaN(); } /* non-numeric? */
codereview_new_cpp_data_7092
double proj_strtod(const char *str, char **endptr) { if (strncmp(p, "NaN", 3) == 0) { if (endptr) *endptr = const_cast<char *>(p + 3); - return NAN; } /* non-numeric? */ ```suggestion return std::numeric_limits<double>::quiet_NaN(); ``` double proj_strtod(const char *str, char **endptr) { if (strncmp(p, "NaN", 3) == 0) { if (endptr) *endptr = const_cast<char *>(p + 3); + return std::numeric_limits<double>::quiet_NaN(); } /* non-numeric? */
codereview_new_cpp_data_7093
PJ_COORD proj_trans(PJ *P, PJ_DIRECTION direction, PJ_COORD coord) { coord.xyzt.t = P->coordinateEpoch; if (isnan(coord.v[0]) || isnan(coord.v[1]) || isnan(coord.v[2]) || isnan(coord.v[3])) - coord.v[0] = coord.v[1] = coord.v[2] = coord.v[3] = NAN; else if (direction == PJ_FWD) pj_fwd4d(coord, P); else ```suggestion coord.v[0] = coord.v[1] = coord.v[2] = coord.v[3] = std::numeric_limits<double>::quiet_NaN(); ``` PJ_COORD proj_trans(PJ *P, PJ_DIRECTION direction, PJ_COORD coord) { coord.xyzt.t = P->coordinateEpoch; if (isnan(coord.v[0]) || isnan(coord.v[1]) || isnan(coord.v[2]) || isnan(coord.v[3])) + coord.v[0] = coord.v[1] = coord.v[2] = coord.v[3] = std::numeric_limits<double>::quiet_NaN(); else if (direction == PJ_FWD) pj_fwd4d(coord, P); else
codereview_new_cpp_data_7129
TEST(defaultdevicetype, scoped_profile_region) { ASSERT_TRUE(test_region_stack.empty()); - // Unnamed guard! Profile region is popped at the end of the statement. - Kokkos::Profiling::ScopedProfileRegion("bug"); - - ASSERT_TRUE(test_region_stack.empty()); - { std::string outer_identifier = "outer"; Kokkos::Profiling::ScopedProfileRegion guard_outer(outer_identifier); Actually you should keep it open until the end of the file TEST(defaultdevicetype, scoped_profile_region) { ASSERT_TRUE(test_region_stack.empty()); { std::string outer_identifier = "outer"; Kokkos::Profiling::ScopedProfileRegion guard_outer(outer_identifier);
codereview_new_cpp_data_7130
void initialize_host_hip_lock_arrays() { copy_hip_lock_arrays_to_device(); init_lock_array_kernel_atomic<<< (KOKKOS_IMPL_HIP_SPACE_ATOMIC_MASK + 1 + 255) / 256, 256, 0, nullptr>>>(); - HIP::impl_static_fence( - "Kokkos::Impl::initialize_host_hip_lock_arrays: Post Init Lock Arrays"); } void finalize_host_hip_lock_arrays() { This fence is new (and we have it in the `CUDA` implementation). void initialize_host_hip_lock_arrays() { copy_hip_lock_arrays_to_device(); init_lock_array_kernel_atomic<<< (KOKKOS_IMPL_HIP_SPACE_ATOMIC_MASK + 1 + 255) / 256, 256, 0, nullptr>>>(); } void finalize_host_hip_lock_arrays() {
codereview_new_cpp_data_7131
Kokkos::HIP::size_type *HIPInternal::scratch_functor_host( m_scratchFunctorHost = reinterpret_cast<size_type *>(r->data()); } - return m_scratchFunctor; } int HIPInternal::acquire_team_scratch_space() { ```suggestion return m_scratchFunctorHost; ``` Kokkos::HIP::size_type *HIPInternal::scratch_functor_host( m_scratchFunctorHost = reinterpret_cast<size_type *>(r->data()); } + return m_scratchFunctorHost; } int HIPInternal::acquire_team_scratch_space() {