text
stringlengths
1
2.12k
source
dict
c++, callback // Adds a request path "svc1/test1" interface.addRequest(pid, 0, "test1",[this](const std::string& ctx, const ReferenceData& pload){ std::cout << "Received on test1\n"; return std::make_pair(RequestErrors::OK, ConcreteDataContainer{std::string{"Hello from test1"}}); }, {}); // Adds a request path "svc1/onestring" interface.addRequest(pid, 0, "onestring",[this](const std::string& ctx, const ReferenceData& pload){ std::cout << "Received on onestring\n"; return std::make_pair(RequestErrors::OK, ConcreteDataContainer{std::string{"Hello from onestring"}}); }, {&c1Guard, &sGuard}); } }; class Logger : public ServiceManager { // dummy logger int level; public: Logger() : ServiceManager("logger") { interface.addRequest(REQ_ROOT, REQ_LOGGER, "logger", nullptr, {}); // LevelID interface.addRequest(REQ_LOGGER, 0, "level", [this](const std::string& ctx, const ReferenceData& pload){ std::cout << "Received on level ctx=" << ctx << "\n"; if (ctx == "set") { if ((pload.size() == 1)) { if (auto plevel = std::get_if<std::string_view>(&pload[0])) { // MUST be true with the sGuard. level = std::atoi(std::string(*plevel).c_str()); } } else { return std::make_pair(RequestErrors::TOO_FEW_INPUTS, ConcreteDataContainer{}); } } else if (ctx != "get") { return std::make_pair(RequestErrors::NOT_FOUND, ConcreteDataContainer{}); } return std::make_pair(RequestErrors::OK, ConcreteDataContainer{std::to_string(level)}); }, {&sGuard, &nGuard}); } }; Service1 svc1; Logger logger;
{ "domain": "codereview.stackexchange", "id": 45094, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, callback", "url": null }
c++, callback Service1 svc1; Logger logger; And here's a compiler explorer link with a simple example. Lastly, I'd like to attribute Philbowles (Passed) who is the original author of SystemInterface's internal methods which inspired me. With Thanks, Hamza Hajeir Answer: Avoid macros whenever possible Macros are notoriously difficult to write correctly, and will easily fail with different use cases. For example, the following will fail to compile: CHOP_FRONT(std::vector<std::string>{"Aap", "Noot", "Mies"});
{ "domain": "codereview.stackexchange", "id": 45094, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, callback", "url": null }
c++, callback If you had written a regular function, as already suggested by Davislor, you would have avoided this issue. Naming I strongly recommend you use verbs for functions, and nouns for types and variables. For example, isBinaryData() and isPrintable(). Be consistent: why use snake_case in to_string(), but camelCase in toStringCorrector()? Why does struct request not start with a capital when other types do? Why are some type aliases in ALL_CAPS? Never use double underscores: these are always reserved. I also recommend not using leading underscores at all. Either use trailing underscores (1 at most), or use some other prefix, like m_ for class members. What is the significance of a leading underscore anyway? I see you have some public member functions also starting with an underscore, so it definitely doesn't mean "private", otherwise you could have made those functions explicitly private. Incorrect error handling I see a lot of information messages, warnings and error messages all being written to std::cout. However, all this should go to std::log and std::cerr as appropriate. Furthermore, if you encounter an error, you must do something about it. Just printing something like "Already assigned path!\n" is not enough; the program will happily continue running, the user looking at the output thinks "What path? Is this good or bad? I'll just ignore it." Consider throwing an exception; either this will cause the program to abort, or the caller can catch it if it has some way to recover from this error. If you really can't use exceptions, use some other way to panic or to return the error to the caller somehow. This is unnecessarily complex
{ "domain": "codereview.stackexchange", "id": 45094, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, callback", "url": null }
c++, callback This is unnecessarily complex There are several issues with this design that make it unnecessarily complex. Let's start with the levels and owners. Why have these at all? Why split the command path into its components, and then have a std::unordered_multimap sorted by components, when you can just have a map ordered by the full request path? I think you can greatly simplify things by writing: class SystemInterface { std::unordered_map<std::string request, CallbackSignature> requestsMap; … void addRequest(const std::string& path, CallbackSignature cbf) { … } };
{ "domain": "codereview.stackexchange", "id": 45094, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, callback", "url": null }
c++, callback Another issue are the guarders. It might seem like this is convenient, so the callback functions don't have to validate the payload. But you could easily rewrite the guarders so the callback functions can call them, such that the code is just as short as with your solution. Consider: interface.addRequest("logger/level", [this](auto& ctx, auto& pload) { … if (auto plevel = GetNumber(pload[0])) { level = *plevel; } … }); Where you created helper functions to deal with the data encapsulated in BasicReferenceData: std::optional<int> GetNumber(const BasicReferenceData& data) { if (/* checks to see it data actually contains a valid number */) { return std::atoi(std::get<std::string_view>(data)); } else { return std::nullopt; } } With C++23 you will get std::expected<>, so you can also have it return a more specific error code. Your RequestReturn type is a bit similar in that it holds some desired data and a possible error code, but it's hardcoded to return ConcreteData, which still requires the caller to further unpack that, and it doesn't have any of the handy features of std::optional and std::expected, like conversion to bool returning if it has an expected value or not, as well as monadic operations since C++23. If you cannot use that yet but still want to return something like RequestReturn, consider making that a proper class that emulates std::expected Anyway, with these changes, SystemInterface is greatly simplified: it mostly is a std::unordered_map with some access control. help() no longer needs to flatten anything, as the paths are already stored flattened.
{ "domain": "codereview.stackexchange", "id": 45094, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, callback", "url": null }
c, octree Title: 32x32x32 Units Octree With 15-Bit Voxels: Second Edition Question: A while back I made an octree system that stores 15-bit voxel in a 32x32x32 voxel octree: 32x32x32 units octree, that supports 15-bit data units I have since improved upon this system. The new octree structure is largely the same except for a key difference, being that that index nodes are now relative to the branch (referred to as set in the code) they are in as opposed to being relative to the start of the entire structure. The variables have been given more descriptive names. Here is a description of the new system:
{ "domain": "codereview.stackexchange", "id": 45095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, octree", "url": null }
c, octree Voxels are stored as 15-bit values in an octree comprising a 32^3 region of voxels. Each node is a 16-bit object that is either a 15-bit value or a 15-bit index to another set of 8 nodes, as determined by the 16th bit. This index is relative to the start of the set the node is in. The relative indices mean that any given branch, including all its descendants, are independent of where they are in the tree, vastly reducing the number of indices to update when inserting or deleting items in the center of the tree. Maximum of 5 layers (6 including the root node (Octree.base)), so for nodes in the 5th-divided layer, the 16th bit no longer affects structure of the octree and is used for a different purpose, specifying if the object is either a 15-bit value or yet another 15-bit index to a list of 64-bit objects (Octree.data), allowing for more complicated voxels that require extra data to be stored in the tree, without inflating the size of all voxels. The idea is to have a recursive hierarchical structure, where any given node can represent the 8 nodes in the next divided layer, so if any given set of 8 nodes are identical, their value can just be stored once in the previous divided layer. This has potential memory saving and performance benefits as any 8 identical nodes do not need to be individually stored or handled. For example, if a region contains only 0s, the 0 is stored only once as the root node, instead of being stored 32^3 = 32768 times individually as would be the case with an array. And checking that this region is all 0s would entail one operation, checking that the root node is 0, which is much faster than checking if 32768 objects are 0 individually.
{ "domain": "codereview.stackexchange", "id": 45095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, octree", "url": null }
c, octree When the octree is reallocated, the new capacity is 2^Octree.set_alloc plus all powers of 8 less than 2^Octree.set_alloc where Octree.set_alloc is set to the smallest solution where the resulting capacity is not smaller than the new size. Since this scheme naturally leads up to the maximum possible size of the octree (4681 sets of 8 nodes) where all nodes are fully divided, it seems less arbitrary, (to me at least) than simply doubling each time and capping the allocation size at the maximum size. The purpose of the node_dup variables are vectorization, to assign and compare the values 4 nodes (8 bytes) at at time. The purpose of the extra fields in the NodeN unions is again vectorization, so that in the future I can add other code that can handle 2 or 4 nodes at a time.
{ "domain": "codereview.stackexchange", "id": 45095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, octree", "url": null }
c, octree The code: #include <stdlib.h> #include <string.h> #include <stdint.h> #include <assert.h> #include <stdio.h> typedef union Node2 { uint16_t x[2]; uint32_t z; } Node2; typedef union Node4 { uint16_t x[4]; Node2 z[2]; uint64_t y; } Node4; typedef union Node8 { uint16_t x[8]; Node2 z[4]; Node4 y[2]; } Node8; typedef union Ptr { union Ptr *p; uint64_t u; } Ptr; typedef struct Octree { Ptr data; uint8_t data_alloc, set_alloc; uint16_t data_size, set_size, base; Node8 set[]; } Octree; static_assert(sizeof(Node8)==sizeof(uint16_t[8]), "sizeof(Node8)!=sizeof(uint16_t[8])"); static_assert(sizeof(Ptr)==sizeof(uint64_t), "sizeof(Ptr)!=sizeof(uint64_t)"); static_assert(sizeof(Octree)==sizeof(Node8), "sizeof(Octree)!=sizeof(Node8)"); typedef struct State { unsigned level, offset[5]; } State; static unsigned octree_index(const unsigned x, const unsigned z, const unsigned y, const unsigned level) { return (x>>level&1)|(z>>level&1)<<1|(y>>level&1)<<2; } unsigned octree_get(Octree *const octree, State *const state, const unsigned x, const unsigned z, const unsigned y) { unsigned node = octree->base, set = 0; state->level = 5; while (node&0x8000 && state->level) { --state->level; node = ((uint16_t *)octree->set)[state->offset[state->level] = (set += node&0x7FFF)<<3|octree_index(x, z, y, state->level)]; } return node; } static size_t octree_alloc(const unsigned alloc) { // Calculate the size from an allocation step const size_t power = 1<<alloc; return (power-1&4681)|power>>1; } Octree *octree_set(Octree *octree, const unsigned x, const unsigned z, const unsigned y, const unsigned new) { State state; const unsigned node = octree_get(octree, &state, x, z, y); if (node != new) { if (state.level) { const unsigned prev_size = octree->set_size; octree->set_size += state.level; { // Reallocate the tree
{ "domain": "codereview.stackexchange", "id": 45095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, octree", "url": null }
c, octree octree->set_size += state.level; { // Reallocate the tree size_t alloc_size; unsigned alloc = octree->set_alloc; while ((alloc_size = octree_alloc(alloc)) < octree->set_size) ++alloc; if (octree->set_alloc != alloc) { if (!(octree = realloc(octree, alloc_size*sizeof(Node8)+sizeof(Octree)))) abort(); octree->set_alloc = alloc; } } Node8 *set_ptr = octree->set; if (state.level == 5) octree->base = 0x8000; else { unsigned set = 0; unsigned level = state.level; do { // This loop does 2 things: Find the insertion point for new branches, and offsets all the relevant indices in all the ancestry unsigned offset = state.offset[level]; while (++offset&7) { uint16_t *const node_ptr = (uint16_t *)octree->set+offset; if (*node_ptr&0x8000) { if (!set) set = (offset>>3)+(*node_ptr&0x7FFF); *node_ptr += state.level; } } } while (++level != 5); const unsigned offset = state.offset[state.level]; ((uint16_t *)octree->set)[offset] = (set // If no set was found, it means there is nothing to shift over, and the new data should be placed at the end of the tree ? (set_ptr += set, memmove(set_ptr+state.level, set_ptr, (prev_size-set)*sizeof(Node8)), set) : (set_ptr += prev_size, prev_size) )-(offset>>3)|0x8000; } uint16_t *node_ptr; Node4 node_dup; node_dup.x[1] = node_dup.x[0] = node; node_dup.z[1] = node_dup.z[0];
{ "domain": "codereview.stackexchange", "id": 45095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, octree", "url": null }
c, octree node_dup.x[1] = node_dup.x[0] = node; node_dup.z[1] = node_dup.z[0]; for (;;) { set_ptr->y[1] = set_ptr->y[0] = node_dup; node_ptr = (uint16_t *)set_ptr+octree_index(x, z, y, --state.level); if (state.level) { *node_ptr = 0x8001; ++set_ptr; continue; } break; } *node_ptr = new; } else { unsigned set; Node4 node_dup; node_dup.x[1] = node_dup.x[0] = new; node_dup.z[1] = node_dup.z[0]; for (;;) { const unsigned offset = state.offset[state.level], next_set = offset>>3; ((uint16_t *)octree->set)[offset] = new; Node8 *const set_ptr = octree->set+next_set; if (set_ptr->y[0].y == node_dup.y && set_ptr->y[1].y == node_dup.y) { set = next_set; if (++state.level == 5) { // If level is 5, then all of the data is in the entire octree is the same, and all the sets can be deleted right off the bat, however this is extremely rare, so is including these lines worth it instead of just skipping to the reallocation part? octree->set_alloc = 0; octree->set_size = 0; octree->base = new; Octree *const prev_octree = realloc(octree, sizeof(Octree)); return prev_octree ? prev_octree : octree; } continue; } break; } if (state.level) { Node8 *set_ptr = octree->set+set; memmove(set_ptr, set_ptr+state.level, (octree->set_size-set)*sizeof(Node8)); unsigned level = state.level; do { uint_fast16_t offset = state.offset[level];
{ "domain": "codereview.stackexchange", "id": 45095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, octree", "url": null }
c, octree do { uint_fast16_t offset = state.offset[level]; while (++offset&7) { uint16_t *const node_ptr = (uint16_t *)octree->set+offset; if (*node_ptr&0x8000) { *node_ptr -= state.level; } } } while (++level != 5); octree->set_size -= state.level; size_t alloc_size; unsigned alloc; { // Calculate new allocation size, starting at the current size and then stopping once the newest try is less than the actual octree size size_t next_alloc_size; unsigned next_alloc = octree->set_alloc; while (alloc = next_alloc, (next_alloc_size = octree_alloc(--next_alloc)) >= octree->set_size) { alloc_size = next_alloc_size; } } if (octree->set_alloc != alloc) { Octree *const prev_octree = realloc(octree, alloc_size*sizeof(Node8)+sizeof(Octree)); if (prev_octree) octree = prev_octree; octree->set_alloc = alloc; } } } } return octree; }
{ "domain": "codereview.stackexchange", "id": 45095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, octree", "url": null }
c, octree Some concerns: Stability: This code very complicated and, while it has passed some brief testing that should invoke all code paths, such as inserting nodes before and after other nodes, to see if the parent indices are updated properly, etc. I am still not 100 percent confident that all of this code is 100 percent correct. Duplicate code: The code to update the indices in the parents after making new space for new branches is almost the same as the code to update the indices in the parents after filling in a gap after deleting a branch (if all nodes in a branch are identical, the branch is deleted and the node referencing it is simply replaced with the value), except for the if (!set) set = (offset>>3)+(*node_ptr&0x7FFF); and += parts. The reason the first line is necessary in the first part but not the second is the correct insertion point for the new branches needs to be located, and it just so happens that the first parent index that needs to be updated is a reference to the location where the new branches need to be inserted. Related: How can I make code that is both DRY and fast where intermediate values in a calculation may or may not be needed? Portability: As usual, I try to make my code portable within reason (yes, uintN_t types are optional and unavailable on some systems) but other than that, I try to avoid compiler extensions or anything not outlined in the standard. Uninitialized variable warnings: Some variables such as set and alloc_size in the second branch will in fact never be used while they are not initialized, but the compiler is not so sure. Can the logic be improved so that these warnings will disappear without the cop-out of initializing the variables to silence the warnings? Is the special case that all of the nodes are the same and all the sets can be deleted immediately being handled by its own few lines of code worth it?
{ "domain": "codereview.stackexchange", "id": 45095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, octree", "url": null }
c, octree I would like an overall review, but with some emphasis on the concerns listed above. Here is the code I used to test the system (no review required): void dump(Octree *octree) { printf("%d\n", octree->base); for (int i = 0; i < octree->set_size; ++i) { for (int j = 0; j < 8; ++j) { printf("%d ", octree->set[i].x[j]); } putchar('\n'); } } #include <stdio.h> size_t malloc_size(const void *); int main(void) { Octree *octree = memset(malloc(sizeof(Octree)), 0, sizeof(Octree)); octree->base = 0; for (;;) { char buf[64], *p = buf; fgets(buf, 64, stdin); switch (*(p++)) { case 's': octree = octree_set(octree, strtol(p, &p, 0), strtol(p, &p, 0), strtol(p, &p, 0), strtol(p, NULL, 0)); break; case 'g': {State state; printf("%d %d\n", octree_get(octree, &state, strtol(p, &p, 0), strtol(p, &p, 0), strtol(p, &p, 0)), state.level);} break; case 'm': printf("%d %zu\n", octree->set_size, malloc_size(octree)); break; case 'd': dump(octree); break; case 'q': free(octree); return 0; } } }
{ "domain": "codereview.stackexchange", "id": 45095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, octree", "url": null }
c, octree Here is a test that proves that deletion and insertion work (this is command line I/O while using the test code): s 31 31 31 1 s 15 15 15 2 s 3 3 3 4 s 1 1 1 5 d 32768 32769 0 0 0 0 0 0 32777 32769 0 0 0 0 0 0 32773 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 32770 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 1 s 1 1 1 d 32768 32769 0 0 0 0 0 0 32776 32769 0 0 0 0 0 0 32772 32769 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 1 s 1 1 1 5 d 32768 32769 0 0 0 0 0 0 32777 32769 0 0 0 0 0 0 32773 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 32770 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 1 s 31 31 31 d 32768 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 32773 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 32770 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 2 g 31 31 31 0 4
{ "domain": "codereview.stackexchange", "id": 45095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, octree", "url": null }
c, octree And even when the X Y and Z coordinates differ significantly: s 1 15 31 7888 s 30 16 2 886 d 32768 0 0 0 32769 32773 0 0 0 0 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 0 0 0 0 32769 0 0 886 0 0 0 0 0 0 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 0 7888 g 1 15 31 7888 0 g 30 16 2 886 0 g 0 15 31 0 0 s 24 8 18 70 d 32768 0 0 0 32769 32773 32777 0 0 0 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 0 0 0 0 32769 0 0 886 0 0 0 0 0 0 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 0 7888 0 0 0 32769 0 0 0 0 32769 0 0 0 0 0 0 0 0 0 0 0 32769 0 0 0 70 0 0 0 0 0 0 0 s 30 16 2 d 32768 0 0 0 0 32769 32773 0 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 32769 0 0 0 0 0 0 0 0 7888 0 0 0 32769 0 0 0 0 32769 0 0 0 0 0 0 0 0 0 0 0 32769 0 0 0 70 0 0 0 0 0 0 0 g 30 16 2 0 4 g 24 8 18 70 0 g 1 15 31 7888 0 It is really supposed to behave like a 3-dimentional array. Set a value at certain coordinates and retrieve the same value if you query those same coordinates. The difference being that in the octree, any power-of-2 aligned region of all the same type are only stored as a single entry. Answer: In the time between now and when I asked the question, there are a few improvements I have made to the code. Magic numbers I have decided to use these instead of using the magic numbers in the code: #define FLAG_MASK 0x8000 #define DATA_MASK 0x7FFF #define MAX_LEVEL 5 #define node_to_set(ptr) (Node8 *)((uintptr_t)(ptr)&-sizeof(Node8))
{ "domain": "codereview.stackexchange", "id": 45095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, octree", "url": null }
c, octree Duplicate ancestry updating code It turns out there are are 2 ways to obtain the correct bounds for the second memmove(). One is to find the start of the sets to delete as the destination and add state.level for the source (the start of the sets to delete is the last set to be all the same type, or the one encountered before the first set with not all nodes of the same type). The other is to find the start of the next sets after the deleted region as the source, and subtract state.level to get the destination. The latter means no previous set needs to be recorded in the first loop in the delete branch, but also means that the 'first index that needs to be updated' needs to be found via the loop that updates the indices. As such, the duplication can be resolved by creating this function: static unsigned octree_offset(Octree *const octree, const State *const state, const int delta) { unsigned set = 0, level = state->level; do { unsigned offset = state->offset[level]; while (++offset&7) { uint16_t *const node_ptr = (uint16_t *)octree->set+offset; if (*node_ptr&FLAG_MASK) { if (!set) set = (offset>>3)+(*node_ptr&DATA_MASK); *node_ptr += delta; } } } while (++level != MAX_LEVEL); if (set) { Node8 *const set_ptr = octree->set+set; memmove(set_ptr+delta, set_ptr, (octree->set_size-set)*sizeof(Node8)); return set; } return octree->set_size; } The entire else branch containing the first do while in the old code was replaced with: else { const unsigned offset = state.offset[state.level], set = octree_offset(octree, &state, state.level); ((uint16_t *)octree->set)[offset] = set-(offset>>3)|FLAG_MASK; set_ptr += set; } octree->set_size = new_size;
{ "domain": "codereview.stackexchange", "id": 45095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, octree", "url": null }
c, octree However, this requires the old octree->set_size so without the prev_size variable, I created a new_size variable and simply set octree->set_size to new_size afterwards. const unsigned new_size = octree->set_size+state.level; This also means the condition in the reallocation while () needs to be updated too: while ((alloc_size = octree_alloc(alloc)) < new_size) At this point, the prev_size variable is not needed and was removed entirely. Duplicate reallocation code/special case I was worried about duplicating the realloc call and subsequent check in the 'special case' that all the represented nodes are identical and thus no sets need to be allocated at all. While breaking the loop instead of invoking the second case would result in some number of redundant tests and unnecessary calculation, I have decided to simply goto the relevant code in the case of the special case. if (++state.level == MAX_LEVEL) { *octree = (struct Octree){.base = new}; alloc_size = 0; goto dealloc; } The declaration of alloc_size had to be moved to the start of the main else branch. if (octree->set_alloc != alloc) { octree->set_alloc = alloc; dealloc: { Octree *const prev_octree = realloc(octree, alloc_size*sizeof(Node8)+sizeof(Octree)); if (prev_octree) octree = prev_octree; } }
{ "domain": "codereview.stackexchange", "id": 45095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, octree", "url": null }
c, octree Subtle bug I discovered a subtle subtle bug, that would be a big vulnerability if this code had to be secure against attacks (which it currently does not). But vulnerabilities are still bad practice, so I went ahead and fixed it. If the set function is called with a new where new&FLAG_MASK is true, with identical values for all 8 nodes in a bottom level branch, they will be merged by the set function resulting in a non-bottom level node with its index flag bit set and an arbitrary data, which is interpreted as an arbitrary array index if the flag bit is set in a non-bottom level branch. This could potentially have catastrophic consequences. Values bigger than 32767 are only supported at the bottom level where the flag bit is irrelevant, but I failed to check that this bit was not set before attempting to merge. This was fixed here: uint16_t *node_ptr = (uint16_t *)octree->set+*state.offset; if (new&FLAG_MASK) *node_ptr = new; else { // All the code that was originally in the main `else` branch } Index of octree->base Currently all the indices contained in nodes are relative to the start of the set they are in. This means that the set referenced by any given node can be obtained using only a pointer to the node. (Unlike with absolute indices, which also require a pointer to the start of the entire octree). All, that is, except octree->base which will always refer to the same place, but to stay consistent with the others, should be able to be handled the same way, i.e. node_to_set(node_ptr)+(*node_ptr&DATA_MASK) should work with node_ptr == &octree->base. To make this work, when the base node is split (and is assigned to an index) the index should be 0x8001 instead of 0x8000: if (state.level == 5) octree->base = 0x8001; else // ...
{ "domain": "codereview.stackexchange", "id": 45095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, octree", "url": null }
c, octree But doing this breaks the octree_get() function, which already treats octree->base as being in the first set even though conceptually it is not. The fix to this is easy too, which is to initialize the set variable in the octree_get() function to -1 instead of 0 (and make it signed). Although this capability is not used in any of the provided code, it becomes useful down the road.
{ "domain": "codereview.stackexchange", "id": 45095, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, octree", "url": null }
c, game-of-life Title: implementation of Conway's game of life in C for ansi terminals Question: I've been learning C for some quite time now and wanted to test my skills by implementing the game of life in C. Please give me a general review, and include the style. Is code like that of function fetch_pop good or should I be more clear? Should I put more comments? If so, can you give me some examples? Can I improve the algorithm in any way? #include <stdio.h> #include <stdlib.h> #include <ctype.h> #define clear_screen printf("\033[2J\033[H") #define WIDTH 20 #define LENGTH 50 enum cell { dead, alive }; int world[WIDTH][LENGTH]; int main(int argc, char *argv[]) { int isnum(char *p); void initialize(int width, int length, int level), draw(int width, int length), evolve(int width, int length); int level = 10; while (--argc > 0) { if (isnum(*(++argv))) { level = atoi(*argv); break; } } initialize(WIDTH, LENGTH, level); do { clear_screen; draw(WIDTH, LENGTH); evolve(WIDTH, LENGTH); } while (getchar() == '\n'); return 0; } int isnum(char *p) { while (*p != '\0') if (!isdigit(*p++)) return 0; return 1; } void initialize(int width, int length, int level) { int col, ln; for (ln = 0; ln < width; ln++) for (col = 0; col < length; col++) world[ln][col] = rand() < RAND_MAX / level; } void draw(int width, int length) { int col, ln; for (ln = 0; ln < width; ln++) { for (col = 0; col < length; col++) printf("%c", world[ln][col] ? '@' : ' '); printf("\n"); } }
{ "domain": "codereview.stackexchange", "id": 45096, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, game-of-life", "url": null }
c, game-of-life void evolve(int width, int length) { int fetch_pop(int ln, int col, int width, int length); /* fetch population number of cell ln, col's neighbors exclusive */ int temp[width][length]; int ln, col, pop; for (ln = 0; ln < width; ln++) { for (col = 0; col < length; col++) { if ((pop = fetch_pop(ln, col, width, length)) == 3) temp[ln][col] = alive; else if (pop == 2) temp[ln][col] = world[ln][col]; else temp[ln][col] = dead; } } for (ln = 0; ln < width; ln++) for (col = 0; col < length; col++) world[ln][col] = temp[ln][col]; } int fetch_pop(int ln, int col, int width, int length) { int pop; int lns, lne, cols, cole; lns = ln - (ln > 0); lne = ln + (ln < width-1); cols = col - (col > 0); cole = col + (col < length-1); pop = 0; for (int i = lns; i <= lne; i++) for (int j = cols; j <= cole; j++) pop += world[i][j]; return pop - world[ln][col]; } Answer: isnum() improvements isdigit(*p++) risks undefined behavior (UB) when *p < 0. This is possible when char is signed. In general, standard library string functions operate on the characters as if they were unsigned char, even when char is signed. Rather than 2 checks per iteration, use one by taking advantage that isdigit('\0') == 0. Use pointers to const data when possible - potentially faster and has wider application. Pedantic: I'd expect isnum("") to return 0, so check that at least 1 digit found. #include <ctype.h> int isnum(const char *p) { const unsigned char *u = (const unsigned char*) p; while (isdigit(*u)) { u++; } return *p == '\0' && u > (const unsigned char*) p; } Do not allow bad program arguments Instead of allowing multiple arguments and ignoring non-numeric ones, be pickier. int level = 10;
{ "domain": "codereview.stackexchange", "id": 45096, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, game-of-life", "url": null }
c, game-of-life //while (--argc > 0) { // if (isnum(*(++argv))) { // level = atoi(*argv); // break; // } //} if (argc == 2 && isnum(argv[1])) { level = atoi(argv[1]); } else if (argc > 1) { ; // TBD error message return EXIT_FAILURE; } Consider strtol() rather than isnum() and atof(). Consider a range check on level. Reduce memory int world[][] only ever use 2 values: 0 & 1. Consider signed char[][] instead. Makes little difference in OP's code, but when the array dimensions are 100000s, 1000000s, sure to improve throughput. Likewise for temp[][] Use memcpy() when one can Copying the array deserves performance considerations. for (ln = 0; ln < width; ln++) // for (col = 0; col < length; col++) // world[ln][col] = temp[ln][col]; memcpy(world[ln], temp[ln], sizeof temp[ln]); I/O Rather than print 1 char at a time, consider printing a line at a time to reduce the heavy I/O overhead. Minor: maybe clearer code "\033[2J\033[H" can be unclear. Perhaps a comment with a URL table of escape sequences? Avoid printf(s) as a later version of s may include a '%'. An alternative: //#define clear_screen printf("\033[2J\033[H") // https://en.wikipedia.org/wiki/ANSI_escape_code#Description #define ESC "\033" #define ANSI_CLEAR_ENTIRE_SCREEN ESC "[2J" #define ANSI_CURSOR_POSITION_UPPER_LEFT ESC "[H" #define clear_screen fputs(ANSI_CLEAR_ENTIRE_SCREEN ANSI_CURSOR_POSITION_UPPER_LEFT, stdout) Better as a function @G. Sliepen. Off-by-1 ? world[ln][col] = rand() < RAND_MAX / level; looks amiss. What does one really mean by level? At least a comment is deserved in code. Common function names Use less likely to collide function names. Then easier to import this code as part of a larger code set. // draw() // evolve() gol_draw() // gol --> game of life gol_evolve()
{ "domain": "codereview.stackexchange", "id": 45096, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, game-of-life", "url": null }
java, tic-tac-toe Title: Java Tic-Tac-Toe Game Implementation - Seeking Feedback and Best Practices Question: I have recently developed a Java program for a simple Tic-Tac-Toe game and would like to request a code review to improve its quality and learn from experienced developers. Below is the code for my game: Board.java import java.util.Scanner; public class Board { private char [] [] board; private final int SIZE; private char currentPlayer; private int validMoves; private static final char PLAYER_X = 'X'; private static final char PLAYER_O = 'O'; private static final char EMPTY_CELL = '.'; private static final int DEFAULT_SIZE = 3; public Board() { this(DEFAULT_SIZE); } public Board(int size) { this.SIZE = size; reset(); } public void reset() { board = new char [SIZE][SIZE]; for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { board[i][j] = EMPTY_CELL; } } currentPlayer = PLAYER_X; validMoves = 0; } void togglePlayer() { currentPlayer = (currentPlayer == PLAYER_X ? PLAYER_O : PLAYER_X); } public char getCurrentPlayer() { return currentPlayer; } boolean isBoardFull() { return validMoves == SIZE * SIZE; } public void print() { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { System.out.print(board[i][j] + " "); } System.out.println(); } }
{ "domain": "codereview.stackexchange", "id": 45097, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, tic-tac-toe", "url": null }
java, tic-tac-toe int [] getValidCell() { int row, col; boolean boardPrinted = true; do { // print the board when user makes an invalid move if (!boardPrinted) print(); System.out.println("It's " + currentPlayer + " turn"); System.out.println("Enter row and column number you want to play: "); System.out.println("Please choose an empty cell from 1 to " + SIZE + " "); Scanner sc = new Scanner(System.in); row = sc.nextInt() - 1; col = sc.nextInt() - 1; boardPrinted = false; } while(isValidCell(row, col)); return new int [] {row, col}; } boolean isValidCell(int row, int col) { return row >= 0 && row < SIZE && col >= 0 && col < SIZE && board[row][col] != EMPTY_CELL; } public boolean checkWin() { // Check rows, columns, and diagonals for a win for (int i = 0; i < SIZE; i++) { // Check row if (board[i][0] != EMPTY_CELL && board[i][0] == board[i][1] && board[i][1] == board[i][2]) { return true; } // Check column if (board[0][i] != EMPTY_CELL && board[0][i] == board[1][i] && board[1][i] == board[2][i]) { return true; } } // Check diagonals if (board[0][0] != EMPTY_CELL && board[0][0] == board[1][1] && board[1][1] == board[2][2]) { return true; } if (board[0][2] != EMPTY_CELL && board[0][2] == board[1][1] && board[1][1] == board[2][0]) { return true; } return false; } public boolean isGameOver() { return checkWin() || isBoardFull(); } public void makeMove() { int [] cell = getValidCell(); int row = cell[0]; int col = cell[1]; validMoves++; board[row][col] = currentPlayer;
{ "domain": "codereview.stackexchange", "id": 45097, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, tic-tac-toe", "url": null }
java, tic-tac-toe if (!isGameOver()) { togglePlayer(); } } } TicTacToe.java public class TicTacToe { Board board; public TicTacToe(int size) { board = new Board(size); } public void play() { while (!board.isGameOver()) { board.print(); board.makeMove(); } board.print(); System.out.println("Game is over"); if (!board.isBoardFull()) { System.out.print("Winner is " + board.getCurrentPlayer()); } else { System.out.println("Draw"); } } } Main.java public class Main { public static void main(String[] args) { TicTacToe tic = new TicTacToe(3); tic.play(); } } Questions: Are there any potential issues or inefficiencies in the code that I should be aware of? Are there any best practices I should follow or refactorings I should consider? Is my code readable and well-documented? Are there places where I can improve comments or method names for clarity? Have I correctly handled user input and error scenarios? Any suggestions for improving the overall structure and organization of the code? Do you notice any possible improvements in terms of code maintainability and extensibility?
{ "domain": "codereview.stackexchange", "id": 45097, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, tic-tac-toe", "url": null }
java, tic-tac-toe Answer: First of all, look up SOLID pronciples and study them. Especially the "S" which stands for "single responsibility principle": each component should be responsible for one thing only. These are the most important things I have learned as a programmer and I wish I had learned them 10 years sooner. Board By the name I would assume Board class contains the state of the game: the size of the board and the locations of played moves. Nothing else. I might think that it could even be a generic board class that could be used for chess, checkers, etc. The class however is responsible for managing user input, player turn, etc. There's output written in the middle of the game logic controlled by boolean flags. A lot of responsibilities violating the "S" in SOLID. It's a bit of spaghetti code. TicTacToe The TicTacToe class has very little to do with "Tic Tac Toe" the game. It is just a generic "main loop" for a turn based game. The fundamentals of "Tic Tac Toe" are actually written into the Board class. Whatever is in the TicTacToe could as well be put into the Main class. The naming is thus a bit misleading. I would refactor the classes so that Board only contains the game state without other logic. It would provide a method for checking what a board location contains (X, O or empty) and a method for placing a marker in a location. TicTacToe then provides a metod for making a move while enforcing legality and information of whose turn it is and whether the game has ended or not. It would thus contain the rules to the Tic Tac Toe game. Then I would write a new class that would only handle reading user input and printing the game state to console. Maybe it could be called "TicTacToeCLI" (for command line interface). And the main class would set these three classes up and run the main loop.
{ "domain": "codereview.stackexchange", "id": 45097, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, tic-tac-toe", "url": null }
c#, performance Title: Count the number of triplets from an array with sums divisible by 'd'? Question: I got this question on my test and I did the only logical thing I could think of, which is run 3 nested loops and count each triplet. I obviously wouldn't pass test cases for large arrays... How can I make this code more efficient? public static int CountTriplets(int d, List<int> a) { int count = 0; int n = a.Count; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { if ((a[i] + a[j] + a[k]) % d == 0) count++; } } } return count; } Answer: I don't see a way to avoid the O(n^3) complexity because as far as I can tell, we have to calculate n * (n-1) * (n-2) values. I hope someone can prove me wrong. However the code can still be optimized. You access a[i] in the innermost loop, so that is being done (n-1) * (n-2) times. Same for a[j] and the addition a[i] + a[j] which both happen (n-2) times. Here is a variant without those redundancies: public static int CountTriplets2(int d, List<int> a) { int count = 0; int n = a.Count; for (int i = 0; i < n; i++) { var ai = a[i]; for (int j = i + 1; j < n; j++) { var aij = ai + a[j]; for (int k = j + 1; k < n; k++) if ((aij + a[k]) % d == 0) count++; } } return count; }
{ "domain": "codereview.stackexchange", "id": 45098, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance", "url": null }
c#, performance Both methods calculate the modulus value n * (n-1) * (n-2) times, which can also be optimized. To know if (x+y) % d == 0 we can do (x % d) + (y % d) and check if that equals either 0 or d. The values x % d can be calculated just once for every value in the list. Or alternatively, we can subtract d if possible and then check only for 0. This logic can be extended to any number of added values. This gives us a new variant, which is becoming less readable but I would expect to be faster: public static int CountTriplets3(int d, List<int> b) { int n = b.Count; var a = new int[n]; for (int i = 0; i < n; i++) a[i] = b[i] % d; int count = 0; for (int i = 0; i < n; i++) { var ai = a[i]; for (int j = i + 1; j < n; j++) { var aij = ai + a[j]; if (aij >= d) aij -= d; for (int k = j + 1; k < n; k++) { var aijk = aij + a[k]; if (aijk == 0 || aijk == d) count++; } } } return count; } We can still optimize this further because we are doing an addition in the innermost loop, but we can actually calculate which a[k] value we would need for a match: public static int CountTriplets4(int d, List<int> b) { int n = b.Count; var a = new int[n]; for (int i = 0; i < n; i++) a[i] = b[i] % d; int count = 0; for (int i = 0; i < n; i++) { var ai = a[i]; for (int j = i + 1; j < n; j++) { var aij = ai + a[j]; if (aij >= d) aij -= d; var neededForK = aij > 0 ? d - aij : 0; for (int k = j + 1; k < n; k++) if (a[k] == neededForK) count++; } } return count; } Test results with 2000 integers on my system, in Release mode, and the same count result:
{ "domain": "codereview.stackexchange", "id": 45098, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance", "url": null }
c#, performance Test results with 2000 integers on my system, in Release mode, and the same count result: CountTriplets -> 3.82 sec CountTriplets2 -> 3.30 sec (14% less time) CountTriplets3 -> 1.09 sec (72% less time) CountTriplets4 -> 0.93 sec (76% less time)
{ "domain": "codereview.stackexchange", "id": 45098, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance", "url": null }
c++, array, collections, c++20 Title: C++20 "FixedArray" Container (dynamically allocated fixed-size array) Question: I've wrote a FixedArray to fit seamlessly (function-wise) with the default C++ containers, including working with algorithms/etc. It is a dynamically allocated, but fixed size array. Code #pragma once #include <cstddef> #include <initializer_list> #include <algorithm> #include <limits> #include <concepts> #include <iterator> #include <stdexcept>
{ "domain": "codereview.stackexchange", "id": 45099, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, collections, c++20", "url": null }
c++, array, collections, c++20 namespace Util { template<typename C, typename T=typename C::value_type> concept Container = std::input_iterator<typename C::iterator> && std::is_same_v<typename C::value_type,T> && requires(C c,const C cc,size_t i) { { c.begin() } -> std::same_as<typename C::iterator>; { c.end() } -> std::same_as<typename C::iterator>; { cc.begin() } -> std::same_as<typename C::const_iterator>; { cc.end() } -> std::same_as<typename C::const_iterator>; { c.size() } -> std::same_as<typename C::size_type>; }; template<typename T, bool _reassignable=false, typename Alloc=std::allocator<T>> class FixedArray { public: using value_type=T; using allocator_type=Alloc; using size_type=size_t; using difference_type=std::ptrdiff_t; using reference=T&; using pointer=T*; using iterator=T*; using reverse_iterator=std::reverse_iterator<T*>; using const_reference=const T&; using const_pointer=const T*; using const_iterator=const T*; using const_reverse_iterator=std::reverse_iterator<const T*>; private: value_type * _data; size_type _size; [[no_unique_address]] Alloc allocator; void _cleanup() { // destroy all objects, deallocate all memory, leaves container in a valid empty state if(_data) { for(size_t i=0;i<_size;i++) { _data[i].~value_type(); } allocator.deallocate(_data,_size); _data=nullptr; } _size=0; } template<typename C> void _container_assign(const C &container) { // allocate memory and copy contents from generic container of type C if(container.size()==0) { _size=0; _data=nullptr; } else {
{ "domain": "codereview.stackexchange", "id": 45099, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, collections, c++20", "url": null }
c++, array, collections, c++20 _size=0; _data=nullptr; } else { _size=container.size(); _data=allocator.allocate(_size); typename C::const_iterator it=container.begin(); for(size_t i=0;i<_size;i++,it++){ new(_data+i) value_type(*it); } } } public: FixedArray() : _data(nullptr), _size(0) { } FixedArray(std::nullptr_t) : _data(nullptr), _size(0) { } FixedArray(std::initializer_list<T> data) requires std::is_copy_constructible_v<value_type> { _container_assign(data); } template<typename U> FixedArray(std::initializer_list<U> data) requires (!std::is_same_v<T,U>) && requires (U x){ T(x); } { _container_assign(data); } FixedArray(const FixedArray & other) requires std::is_copy_constructible_v<value_type> { _container_assign(other); } FixedArray(FixedArray && other) : _data(other._data), _size(other._size) { other._data=nullptr; other._size=0; } template<typename C> FixedArray(const C& container) requires Container<C,value_type> && std::is_copy_constructible_v<value_type> { _container_assign(container); } template<typename C> FixedArray(const C& container) requires Container<C> && (!std::is_same_v<T,typename C::value_type>) && requires (typename C::value_type v) { T(v); } { _container_assign(container); } FixedArray(size_t n) requires std::is_default_constructible_v<value_type> : _data(nullptr), _size(n) { if(_size>0){ _data=allocator.allocate(_size); for(size_t i=0;i<_size;i++){ new(_data+i) value_type();
{ "domain": "codereview.stackexchange", "id": 45099, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, collections, c++20", "url": null }
c++, array, collections, c++20 for(size_t i=0;i<_size;i++){ new(_data+i) value_type(); } } } ~FixedArray() { _cleanup(); } // --- optional reassignment methods --- void operator=(std::nullptr_t) requires _reassignable { _cleanup(); } void clear() requires _reassignable { _cleanup(); } FixedArray & operator=(std::initializer_list<T> data) requires _reassignable { _cleanup(); _container_assign(data); return *this; } template<typename U> FixedArray & operator=(std::initializer_list<U> data) requires _reassignable && requires (U x){ T(x); } { _cleanup(); _container_assign(data); return *this; } FixedArray & operator=(const FixedArray & other) requires _reassignable { _cleanup(); _container_assign(other); return *this; } FixedArray & operator=(FixedArray && other) requires _reassignable { _cleanup(); _data=other._data; _size=other._size; other._data=nullptr; other._size=0; return *this; } template<typename C> FixedArray & operator=(const C& container) requires _reassignable && Container<C,value_type> { _cleanup(); _container_assign(container); return *this; } template<typename C> FixedArray & operator=(const C& container) requires _reassignable && Container<C> && (!std::is_same_v<T,typename C::value_type>) && requires (typename C::value_type v) { T(v); } { _cleanup(); _container_assign(container); return *this; }
{ "domain": "codereview.stackexchange", "id": 45099, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, collections, c++20", "url": null }
c++, array, collections, c++20 _container_assign(container); return *this; } void swap(FixedArray & other) requires _reassignable { value_type * temp_data=_data; size_t temp_size=_size; _data=other._data; _size=other._size; other._data=temp_data; other._size=temp_size; } static void swap(FixedArray & lhs,FixedArray & rhs) requires _reassignable { lhs.swap(rhs); } // --- container boilerplate after this --- template<typename C> bool operator==(const C& container) const { return _size==container.size()&&std::equal(container.begin(),container.end(),begin(),end()); } template<typename C> bool operator!=(const C& container) const { return _size!=container.size()||!std::equal(container.begin(),container.end(),begin(),end()); } size_type size() const noexcept { return _size; } static size_type max_size() noexcept { return (std::numeric_limits<size_type>::max()/sizeof(value_type))-1; } size_type empty() const noexcept { return _size==0; } iterator begin() noexcept { return _data; } iterator end() noexcept { return _data+_size; } const_iterator begin() const noexcept { return _data; } const_iterator end() const noexcept { return _data+_size; } const_iterator cbegin() const noexcept { return _data; } const_iterator cend() const noexcept { return _data+_size; } reverse_iterator rbegin() noexcept { return std::make_reverse_iterator(end()); }
{ "domain": "codereview.stackexchange", "id": 45099, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, collections, c++20", "url": null }
c++, array, collections, c++20 return std::make_reverse_iterator(end()); } reverse_iterator rend() noexcept { return std::make_reverse_iterator(begin()); } const_reverse_iterator rbegin() const noexcept { return std::make_reverse_iterator(end()); } const_reverse_iterator rend() const noexcept { return std::make_reverse_iterator(begin()); } const_reverse_iterator crbegin() const noexcept { return std::make_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return std::make_reverse_iterator(begin()); } pointer data() noexcept { return _data; } const_pointer data() const noexcept { return _data; } reference front() noexcept { return _data[0]; } const_reference front() const noexcept { return _data[0]; } reference back() noexcept { return _data[_size-1]; } const_reference back() const noexcept { return _data[_size-1]; } reference operator[](size_t i) noexcept { return _data[i]; } const_reference operator[](size_t i) const noexcept { return _data[i]; } reference at(size_t i) { if(i>=_size) throw std::out_of_range("Index "+std::to_string(i)+" is out of range for FixedArray of size "+std::to_string(_size)); return _data[i]; } const_reference at(size_t i) const { if(i>=_size) throw std::out_of_range("Index "+std::to_string(i)+" is out of range for FixedArray of size "+std::to_string(_size)); return _data[i]; } }; }
{ "domain": "codereview.stackexchange", "id": 45099, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, collections, c++20", "url": null }
c++, array, collections, c++20 After testing it, it seems to work without any problems, but a second pair of eyes could help find anything i might have overlooked. Answer: Consider not using this class Your class basically reimplements almost all of std::vector, except the functions that resized the container. The only feature I can see that it has over regular std::vector is that you can easily assign another container to it without using a pair of iterators. In this case, I would recommend considering not using this class, but just a regular std::vector, so that you don't have to maintain this code. Alternatively, you could perhaps consider deriving your class from std::vector, but delete all the functions that resize. For example: template<typename T, typename Alloc = std::allocator<T>> class FixedArray: public std::vector<T, Alloc> { public: // Delete functions you don't want: void resize(size_t) = delete; ... // Pull in the constructors of the parent class: using std::vector<T, Alloc>::vector; // Add more constructors/functions if needed: template<typename C> FixedArray(const C& container) : std::vector<T, Alloc>(std::begin(container), std::end(container)) {} ... };
{ "domain": "codereview.stackexchange", "id": 45099, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, collections, c++20", "url": null }
c++, array, collections, c++20 Inheriting from a container class this way has its own drawbacks, so I wouldn't recommend this either, but I do think this approach will require much less code to be written. For the rest of the review I'm assuming you do want to use your own class as it is. Make better use of existing concepts Instead of defining your own concept Container, make use of the concepts from the Ranges library, like std::ranges::range, or even better the more specific ones like std::ranges::input_range. Also, instead of writing requires (typename C::value_type v) { T(v); }, consider using requires std::is_constructible_v<T, C::value_type>. Use concepts directly inside a template parameter list A nice thing about concepts is that you can use them instead of typename in a template parameter list. This avoids some typing, and makes the code a little easier to read. For example, instead of: template<typename C> FixedArray(const C& container) requires Container<C> && (!std::is_same_v<T,typename C::value_type>) && requires (typename C::value_type v) { T(v); } { _container_assign(container); } You can write: template<std::ranges::input_range C> FixedArray(const C& container) requires (!std::is_same_v<T,typename C::value_type> && std::is_constructible_v(T, C::value_type)) { _container_assign(container); } Use default member value initialization You can avoid some typing by using member value initialization: pointer _data{}; size_type _size{}; This avoids repeating the default initialization in several of the constructors. In fact, this way the default constructor can really be made default: FixedArray() = default;
{ "domain": "codereview.stackexchange", "id": 45099, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, collections, c++20", "url": null }
c++, array, collections, c++20 Avoid code duplication There are several ways you can reduce the amount of code you have written: Reuse your own functions You can make use of your own member functions and iterators. For example, you can use range-for to loop over the elements of _data: void _cleanup() { // destroy all objects, deallocate all memory, leaves container in a valid empty state if(_data) { for(auto &el: *this) { el.~value_type(); } allocator.deallocate(_data, _size); _data = nullptr; } _size = 0; } Also, when moving data from another container, make use of your own swap() function. Combined with the default member initialization, this removes a lot of lines, for example the move constructor becomes: FixedArray(FixedArray && other) { swap(other); } Merge (template) overloads where possible There are several places where you have multiple overloads for dealing with other containers of the same value_type or of another, when they can be merged into one. For example, the constructors taking initializer lists can be merged into this single one: template<typename U> FixedArray(std::initializer_list<U> data) requires std::is_constructible_v<value_type, U> { _container_assign(data); } Since this will also handle the case of a std::initializer_list<value_type> just fine. The same goes for the other cases where you used !std::is_same_v<>. Define operator!= in terms of operator== It's always best to define one of those operators in terms of the other, so you cannot have a small mistake give subtly different behaviour. So: template<std::ranges::input_range C> bool operator!=(const C& container) const { return !operator==(container); }
{ "domain": "codereview.stackexchange", "id": 45099, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, collections, c++20", "url": null }
c++, array, collections, c++20 Be consistent using std::size(), std::begin() and std::end() To ensure your class works with all possible containers, don't use member functions .size(), .begin() and .end() directly, but use the free-standing std::size() and related functions. For example: template<std::ranges::input_range C> bool operator==(const C& container) const { return std::equal(std::begin(container), std::end(container), begin(), end()); } Note that you also don't need to use std::size() in this example, std::equal() will already check whether the sizes match. Use your own type aliases consistently If you define an alias, you should use it yourself as well. This ensures that if you need to change a type, you only need to do it on one line. So replace size_t with size_type everywhere, use value_type instead of T in a few places, and so on. Use consistent code formatting Your code does not use consistent formatting, in some places there are spaces around operators, in other places there are none. I recommend using a code formatting tool to do this for you, for example Artistic Style or ClangFormat.
{ "domain": "codereview.stackexchange", "id": 45099, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, collections, c++20", "url": null }
c++, security, repository Title: Banking System console app in C++ Question: I built a banking system in C++ (still a lot of features to do but (I decided to post it here to see what can I change so I wont make those mistakes in the future). User header and c++ files Header #pragma once #include <string> class User { private: int id; std::string username; std::string password; std::string balance; public: User(int id, std::string username, std::string &password, int balance); ~User(); int GetId(); std::string GetUsername(); }; CPP #include <iostream> #include "HashPassword.h" #include "User.h" User::User(int uId, std::string uUsername, std::string& uPassword, int uBalance) { id = uId; username = uUsername; password = uPassword; HashPassword(password); std::cout << password << '\n'; balance = uBalance; std::cout << balance << '\n'; } User::~User() { } int User::GetId() { return id; } std::string User::GetUsername() { return username; } all of this is pretty easy to understand (I hope) but a couple of point: first of all the HashPassword method will be posted here so scroll down a bit for the implementation, but basically I used the picosha2 header file I got from GitHub and it does some magic I don't understand and hashes a string using sha256 algorithm. second point I got a weird feeling about how I use pointers and pass by reference here so I would like some directions on that topic. HashPassword #include "HashPassword.h" void HashPassword(std::string& password) { std::vector<unsigned char> hash(picosha2::k_digest_size); picosha2::hash256(password.begin(), password.end(), hash.begin(), hash.end()); password = picosha2::bytes_to_hex_string(hash.begin(), hash.end()); }
{ "domain": "codereview.stackexchange", "id": 45100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, security, repository", "url": null }
c++, security, repository password = picosha2::bytes_to_hex_string(hash.begin(), hash.end()); } this is my hashing process I took straight from the GitHub example and I have a broad idea on how it works but I don't understand it deeply. my main concern here is the use of pointers and references. UserRepository #include <iostream> #include <vector> #include "User.h" class UserRepository { private: std::vector<User> userRepo; public: UserRepository() { } ~UserRepository(){} void AddUser(std::string& username, std::string &password, int& balance) { int id = userRepo.size() + 1; User user(id, username, password, balance); userRepo.push_back(user); } void PrintAllUsers() { for(User user : userRepo) { std::cout << user.GetUsername() << ", "; } std::cout << '\n'; } User* FindUserByUsername(std::string username) { for (User user : userRepo) { if (user.GetUsername() == username) { User* p_user = &user; return p_user; } } return NULL; } }; Here im using a vector as a repository that, and I just add users to it via AddUser and the id gets generated automatically based on how many users there are so if there are 7 users and another one joins then his id will be 8. and this is it for now, working on adding authentication process and changing the way I go about using pointers and references. Answer: Preface: Code reviews can happen on different levels. Others have already pointed out many of the issues regarding potential bugs, syntax, stylistic choices and idiomatic use of the language. This answer tries to review the code regarding the overall design and fit to the (implied) "requirements", especially as the question starts with
{ "domain": "codereview.stackexchange", "id": 45100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, security, repository", "url": null }
c++, security, repository (still a lot of features to do but (I decided to post it here to see what can I change so I wont make those mistakes in the future). Given you are implementing a "banking system", it is a bit unexpected to see "user" as the first thing to implement. I would expect domain terms like "customer" and "(bank) account" to be reflected in the code first. Your User class seems to model kind of both, but it also focuses on the "less important" aspects of the domain. It is currently concerned mainly with the aspects of authenticating a user via a basic username/password combination (it actually does not implement that yet, but I assume this is your intent). It does have a "balance", which would cover the "account" aspect to a very limited degree. I would recommend to start with a proper analysis of the domain and come up with a design where each domain concept is represented separately in your code and also that the various operations and processes that need to happen in your banking system are also explicitly represented and potentially separated. Based on my simplistic understanding of a "bank", you would have at least:
{ "domain": "codereview.stackexchange", "id": 45100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, security, repository", "url": null }
c++, security, repository A Customer class, which represents a single customer of your bank. That typically includes name and contact/address information as well as a customer number/ID for internal references. It likely will have additional administrative information like when they first became a customer or if they are still an active customer or not (maybe you have to delete/anonymize personal data after a certain time?). A customer does not have a password or a balance, as these are separate concepts and concerns. A Account class, which represents a bank account which belongs to one (or many?) customer. It would have an account number and provides the operations to compute its balance, put money into it, withdraw money or transfer money from one account to another (possibly to/from another bank?) and most importantly, list all transactions which took place on it (may need to be limited at some point?). This already indicates that it cannot just store a simple balance, but that it needs to store "transactions" which happen over time. So, we also need... A Transaction class. This would hold information about what amount of money was transferred between which accounts by whom and when. Typically, transactions are immutable and the list of transactions on an account is "append-only".
{ "domain": "codereview.stackexchange", "id": 45100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, security, repository", "url": null }
c++, security, repository Based on that you would then have some kind of repositories to manage all of your customers and accounts. That is similar to what you have with the UserRepository already. As your entities have a primary key (customer number or account number), it would make sense to use a std::map to get a fast lookup of those by that key. If you want to search customers by their name or other attributes, that would be implemented in additional methods. I would strongly suggest to not have functionality like printAllUsers in there. Instead the repository only provides the access methods to get an iterator for users/accounts/customers/... and implement the user interface related functionality elsewhere (the same applies to the "entity" classes themselves too!). At this point, you have to think about where the business constraints and rules can be implemented. For example, where do you check if a transaction should actually be carried out on an account? You may need to put those into additional classes/functions as they operate on a higher level and a single entity. Another thing to think about how it can be modeled/represented in your system is the fact that banks usually do not exist in isolation, but (have to) allow transferring money to and from other banks. Only then would you start to model aspects of an "online banking system", which would then have things like "users" with authentication related information. There, it would in this day and age also be more likely that the authentication part is not a simple username/password combination, but possibly some sort of MFA. In addition, you would have to think about how individual transactions are authorized by the user (in the old days, this was done with pre-generated TAN lists, nowadays it would be some kind of "OTP token" system).
{ "domain": "codereview.stackexchange", "id": 45100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, security, repository", "url": null }
c++, security, repository Of course, as this project is likely just an excercise and/or for fun, many points can be left out and shortened to reduce the overall scope. E.g. only allowing transactions within the bank and only providing username/password authentication.
{ "domain": "codereview.stackexchange", "id": 45100, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, security, repository", "url": null }
php, laravel Title: How to reduce a POST request duplicate in Laravel/PHP for payment system? Question: I'm using PHP/Laravel and I have two controllers. Controllers/PaymentController Controllers/PaymentExpressControler They both create an request which is exactly the same, but it has some differences. Let's say, they both use createRequest(Request $Request) which is a POST request to a third-party api. I'm wondering how can I reduce the code, because it's clearly duplicated. I was thinking of two options, a trait or a class. Controllers/Payment/(NameOfThirdParty).php which is a class with createRequest How would this sound like? My current createRequest protected function createRequest(Request $request) { $this->cartCollection(); $availableMethods = ['mb', 'mbw', 'cc', 'dd']; $tkey = uniqid(Auth::id(), true);
{ "domain": "codereview.stackexchange", "id": 45101, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, laravel", "url": null }
php, laravel $availableMethods = ['mb', 'mbw', 'cc', 'dd']; $tkey = uniqid(Auth::id(), true); if (in_array($request->type, $availableMethods)) { $payment_body = [ "method" => $request->type, "value" => (float)\Cart::getTotal(), "currency" => "EUR", "key" => $tkey, "type" => "sale", "customer" => [ "name" => Auth::user()->name, "email" => Auth::user()->email, "phone" => isset($request->telm) ? $request->telm : "", ], "capture" => [ "descriptive" => "Order", "transaction_key" => $tkey, ], ]; if ($request->type == 'dd') { $sdd_mandate = ['sdd_mandate' => [ "iban" => $request->iban, "account_holder" => Auth::user()->name, "name" => Auth::user()->name, "email" => Auth::user()->email, "phone" => isset($request->telm) ? $request->telm : "0000000", "country_code" => "EU", ]]; $payment_body = array_merge($payment_body, $sdd_mandate); } $response = Http::withHeaders([ 'AccountId' => config('payment.accountId'), 'ApiKey' => config('payment.apiKey'), 'Content-Type' => 'application/json', ])->post('REMOVED API LINK', $payment_body); $this->addToPreOrdersTable($tkey); return $response->collect(); } } } protected function addToPreOrdersTable(string $hash) { $this->cartCollection(); OrderService::createPreOrder($this->contents, $hash, 'buy'); }
{ "domain": "codereview.stackexchange", "id": 45101, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, laravel", "url": null }
php, laravel addToPreOrdersTable Is also in both controllers. protected function index(Request $request) { if (isset($request->type)) { $result = $this->createRequest($request); $status = $result['status']; if ($status == 'ok') { $type = $result['method']['type']; switch ($type) { case 'cc': return redirect($result['method']['url']); case 'mb': return view('payment', ['type' => 'mb', 'data' => $result['method']]); case 'mbw': return view('payment', ['type' => 'mbw']); case 'dd': return view('payment', ['type' => 'dd', 'data' => $result['method']]); } } return back()->withInput()->withErrors(['Error' => 'An error has occured.']); } return view('payment'); } Answer: Let's implements following: separate logic, refactoring of methods Separate logic Validate Requests/PaymentRequest.php add rule for validation use Illuminate\Foundation\Http\FormRequest; class PaymentRequest extends FormRequest { public function rules(): array { return [ 'name' => ['required', 'string', 'in:cc,mb,mbw,dd'], 'telm' => ['string'], 'iban' => ['required', 'string'] ]; } } take out the logic and leave the thin controller: Controllers/PaymentController public function index(PaymentRequest $request, PaymentService $service) { return $service->run($request); } Now we are separating to service and external service. ExternalService - external request, service -our logic; add Services/PaymentService.php and change method createRequest to send class PaymentService implements PaymentServiceInterface {
{ "domain": "codereview.stackexchange", "id": 45101, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, laravel", "url": null }
php, laravel private $externalPaymentService; public function __construct(ExternalPaymentService $externalPaymentService) { $this->externalPaymentService = $externalPaymentService; } public function run(PaymentRequest $request) { // Validate rule in PaymentRequest will not let you go further // if (isset($request->type)) { $tkey = uniqid(Auth::id(), true); $result = $this->externalPaymentService->send($request, $tkey); $this->addToPreOrdersTable($tkey); $status = $result['status']; if ($status == 'ok') { $type = $result['method']['type']; switch ($type) { case 'cc': return redirect($result['method']['url']); case 'mb': return view('payment', ['type' => 'mb', 'data' => $result['method']]); case 'mbw': return view('payment', ['type' => 'mbw']); case 'dd': return view('payment', ['type' => 'dd', 'data' => $result['method']]); } } return back()->withInput()->withErrors(['Error' => 'An error has occured.']); //} // return view('payment'); } protected function addToPreOrdersTable(string $hash) { $this->cartCollection(); OrderService::createPreOrder($this->contents, $hash, 'buy'); } } Services/PaymentServiceInterface.php interface PaymentServiceInterface { run(Request $request); } ExternalService/ExternalPaymentService.php class ExternalPaymentService { public function send(Request $request, $tkey) { $this->cartCollection(); $availableMethods = ['mb', 'mbw', 'cc', 'dd'];
{ "domain": "codereview.stackexchange", "id": 45101, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, laravel", "url": null }
php, laravel $availableMethods = ['mb', 'mbw', 'cc', 'dd']; if (in_array($request->type, $availableMethods)) { $payment_body = [ "method" => $request->type, "value" => (float)\Cart::getTotal(), "currency" => "EUR", "key" => $tkey, "type" => "sale", "customer" => [ "name" => Auth::user()->name, "email" => Auth::user()->email, "phone" => isset($request->telm) ? $request->telm : "", ], "capture" => [ "descriptive" => "Order", "transaction_key" => $tkey, ], ]; if ($request->type == 'dd') { $sdd_mandate = ['sdd_mandate' => [ "iban" => $request->iban, "account_holder" => Auth::user()->name, "name" => Auth::user()->name, "email" => Auth::user()->email, "phone" => isset($request->telm) ? $request->telm : "0000000", "country_code" => "EU", ]]; $payment_body = array_merge($payment_body, $sdd_mandate); } $response = Http::withHeaders([ 'AccountId' => config('payment.accountId'), 'ApiKey' => config('payment.apiKey'), 'Content-Type' => 'application/json', ])->post('REMOVED API LINK', $payment_body); return $response->collect(); } } }
{ "domain": "codereview.stackexchange", "id": 45101, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, laravel", "url": null }
php, laravel return $response->collect(); } } } Okay, we made first level, separated logic! Refactoring of methods Let's create Services/PaymentsRenderStrategy.php and will changing run in PaymentService Services/PaymentsRenderStrategy.php class PaymentsRenderStrategy { private function cc($method) { return redirect($method['url']); } private function mb($method) { return view('payment', ['type' => 'mb', 'data' => $method]); } private function mbw($method) { return view('payment', ['type' => 'mbw']); } private function dd($method) { return view('payment', ['type' => 'dd', 'data' => $method]); } public function render($type, $data) { try { return $this->$type($data); } catch (Exception $e) { throw new Exception('some error in methods'); } } } rewrite Services/PaymentService.php class PaymentService implements PaymentServiceInterface { private $externalPaymentService; public function __construct(ExternalPaymentService $externalPaymentService) { $this->externalPaymentService = $externalPaymentService; } public function run(PaymentRequest $request) { try { $tkey = uniqid(Auth::id(), true); $this->cartCollection(); $result = $this->externalPaymentService->collect($request, $tkey)->send($request, $tkey); $this->addToPreOrdersTable($tkey); $status = $result['status']; if ($status != 'ok') { throw new Exception('Bad request'); } return (new PaymentsRenderStrategy())->render($request->type, ($result['method']); } catch (Exception $e) { return back()->withInput()->withErrors(['Error' => 'An error has occured.']); } }
{ "domain": "codereview.stackexchange", "id": 45101, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, laravel", "url": null }
php, laravel protected function addToPreOrdersTable(string $hash) { $this->cartCollection(); OrderService::createPreOrder($this->contents, $hash, 'buy'); } } Validateon we moved in PaymentRequest and we don't need extra checks like if (in_array($request->type, $availableMethods)). $this->$type($data); - call need method by type (note: use $this->$type) also we took the logic out of ExternalPaymentService and serparate method send by collect and send ExternalServices/PaymentExternalService.php class ExternalPaymentService { private $paymentBody; public function collect(PaymentRequest $request, $tkey) { $this->paymentBody = [ "method" => $request->type, "value" => (float)\Cart::getTotal(), "currency" => "EUR", "key" => $tkey, "type" => "sale", "customer" => [ "name" => Auth::user()->name, "email" => Auth::user()->email, "phone" => isset($request->telm) ? $request->telm : "", ], "capture" => [ "descriptive" => "Order", "transaction_key" => $tkey, ], ]; if ($request->type == 'dd') { $sdd_mandate = ['sdd_mandate' => [ "iban" => $request->iban, "account_holder" => Auth::user()->name, "name" => Auth::user()->name, "email" => Auth::user()->email, "phone" => isset($request->telm) ? $request->telm : "0000000", "country_code" => "EU", ]]; $this->paymentBody = array_merge($this->paymentBody, $sdd_mandate); } return $this; } public function send() {
{ "domain": "codereview.stackexchange", "id": 45101, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, laravel", "url": null }
php, laravel return $this; } public function send() { $response = Http::withHeaders([ 'AccountId' => config('payment.accountId'), 'ApiKey' => config('payment.apiKey'), 'Content-Type' => 'application/json', ])->post('REMOVED API LINK', $this->paymentBody); return $response->collect(); } } Here we refactor I hope helped you. Next stage: take out magic constants (cc,mb,mbw,dd), to short methods ...etc. See more
{ "domain": "codereview.stackexchange", "id": 45101, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, laravel", "url": null }
ruby, file, automation Title: Ruby-function for reading, parsing a text-file, removing data-duplicates Question: Task description: Implement a generate_unique_phone_numbers function. The function shall parse the given text-file. Content-example: Trinidad Kemp,(838) 352-2212 Noel Bush,(647) 477-7093 Claudette Davila,(686) 868-8153 Shaun Mcbride,(433) 380-7556 Katy Blanchard,(792) 460-2468 ... Then return a Set with unique phone-numbers. Means: Some phone-numbers might be included multiple times. My solution: require "set" def generate_unique_phone_numbers(path) numbs = Set.new if File.exist?(path) lines = File.readlines(path) lines.each do |line| numbs.add line.chomp.split(",").last end else puts "File does not exist." end numbs end Are there any improvements concerning my solution, which should be implemented? Would you have done it completely differently? Then how and why? Answer: This is how I'd do it: require "set" require "csv" def csv_to_iterator(path) CSV.open(path).collect { |(_name, number)| number } rescue Errno::ENOENT [] end def unique(iterator) iterator.to_set end def generate_unique_phone_numbers(path) unique(csv_to_iterator(path)) end Ideally I would wrap it in a class, but for simplicity methods will do for this example. I'm not sure how I feel about handling exception in the first method, but I decided to include it here since you have some handling in case a file doesn't exist in your example as well. Rationale: My methods are targeting an interface instead of a concrete implementation. So for instance, it will be easier to replace csv_to_iterator to something else, let's say a DB call in case our data source changes, as long as they quack like an Enumerable. The methods are congruent. In the example you might return a Set or nil (due to puts), in my case I'm always returning a set, doesn't matter what. This create a coherent interface for the execution.
{ "domain": "codereview.stackexchange", "id": 45102, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "ruby, file, automation", "url": null }
ruby, file, automation Well defined responsibilities. In the example, a single method is managing opening a file, verifying its stats, parsing, and removing duplicates. I broke down this into multiple steps and in smaller functions.
{ "domain": "codereview.stackexchange", "id": 45102, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "ruby, file, automation", "url": null }
c#, .net, recursion, file-system, wpf Title: Recursively create a TreeView for file paths using C# and WPF Question: I'm building a program that allows the user to monitor files on their local system. To display the files, I created a TreeView using System.Windows.Controls from the WPF framework. The files are added recursively. What suggestions would you give to improve this code for cleanliness, structure, or efficiency? Could I have made better use of the C# and WPF libraries? Could this code be made more scalable, in the event of having to display hundreds or thousands of files? Any guidance from the Code Review community would be welcomed and appreciated. using System.Collections.Generic; using System.Linq; using System.Windows.Controls; namespace WpfApp1 { /// <summary> /// A class for creating a Windows File Explorer tree view. /// </summary> public class FileExplorerTreeView { /// <summary> /// The public <see cref="TreeView"/> property to bind to the UI. /// </summary> public TreeView FileTree { get; } /// <summary> /// The <see cref="FileExplorerTreeView"/> class constructor. /// </summary> public FileExplorerTreeView() { FileTree = new TreeView(); } /// <summary> /// Add a single path to the <see cref="TreeView"/>. /// </summary> public void AddPath(string path) { // Split the file path components then add them to a Queue. var pathElements = new Queue<string>(path.Split(Path.DirectorySeparatorChar).ToList()); AddNodes(pathElements, FileTree.Items); } /// <summary> /// Add multiple paths to the <see cref="TreeView"/>. /// </summary> public void AddPaths(IEnumerable<string> paths) { foreach (var path in paths) AddPath(path); }
{ "domain": "codereview.stackexchange", "id": 45103, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, recursion, file-system, wpf", "url": null }
c#, .net, recursion, file-system, wpf // Add each file path element recursively to the TreeView. private void AddNodes(Queue<string> pathElements, ItemCollection childItems) { if (pathElements.Count == 0) return; var first = new TreeViewItem(); TreeViewItem? match; first.Header = pathElements.Dequeue(); if (HasItem(childItems, first, out match)) { AddNodes(pathElements, match.Items); } else { childItems.Add(first); AddNodes(pathElements, first.Items); } } // If the TreeViewItem is contained in childItems, return true and return the "item" object as an out // parameter. private bool HasItem(ItemCollection childItems, TreeViewItem item, out TreeViewItem? match) { foreach (var childItem in childItems) { var cast = childItem as TreeViewItem; if (cast == null) { match = null; return false; } if (item.Header.Equals(cast.Header)) { match = cast; return true; } } match = null; return false; } } } Here is the MainWindow class along with some client code to test FileExplorerTreeView with: using System.Collections.Generic; using System.Windows; namespace WpfApp1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent();
{ "domain": "codereview.stackexchange", "id": 45103, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, recursion, file-system, wpf", "url": null }
c#, .net, recursion, file-system, wpf var paths = new List<string>() { "C:\\DIR\\ANOTHERDIR\\FOO.TXT", "C:\\DIR\\FOO.TXT", "C:\\ANOTHERDIR\\FOO.TXT", "C:\\DIR\\ANOTHERDIR\\BAR.TXT", "C:\\DIR\\DIR\\DIR\\FOO.TXT", }; var tree = new FileExplorerTreeView(); tree.AddPaths(paths); DataContext = tree; } } } And here is the XAML: <Window x:Class="WpfApp1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp1" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid> <TreeView x:Name="FileTreeDisplayed" ItemsSource="{Binding FileTree.Items}"/> </Grid> </Window> Answer: Comments I am not a really big fan of adding documentation comments to trivial things (like this is the constructor). On the other hand I do appreciate consistency (every public member is annotated). I would like to encourage you try to avoid echoing comments (the comment tells exactly the same thing as the code), like this // Split the file path components then add them to a Queue. var pathElements = new Queue<string>(path.Split(Path.DirectorySeparatorChar).ToList());
{ "domain": "codereview.stackexchange", "id": 45103, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, recursion, file-system, wpf", "url": null }
c#, .net, recursion, file-system, wpf I try to follow this guideline: use comments to document the whys and why nots. In other words, you should capture the reasoning why did you prefer this solution over other viable alternatives. This information is known at the time of code writing but it will be lost if it is not captured as a comment. This could help future code maintainers to better understand your intent. Readonly At the first glace this code seems to be fine to expose the TreeView as read-only: public TreeView FileTree { get; } The problem with this: its Items collection is not exposed as read-only. In other words, both the FileExplorerTreeView class and its consumer(s) can manipulate concurrently the Items collection. Without proper locking this can cause problems. Ease of usage The AddPaths provides a way to specify multiple paths at the same time. But as you have showed in the MainWindow code you had to create a List and pass that to the AddPaths methods. In C# you could use the params keyword to ease the usage of the method: void AddPaths(params string[] paths) ... tree.AddPaths("C:\\DIR\\ANOTHERDIR\\FOO.TXT", ..., "C:\\DIR\\DIR\\DIR\\FOO.TXT"); Naming convention Your HasItem method follows the tester-doer pattern (sometimes referred as error hiding pattern). Most of the cases in .NET these methods are prefixed with Try, for example TryParse, TryCreate, TryAdd or TryGetValue. The TryGetMatch IMHO would be a more convenient name for this method. Single return In your code you have used 3 return statements. 2 out of 3 are used as early exits. As an alternative you could take advantage of break: private bool TryGetMatch(ItemCollection childItems, TreeViewItem item, out TreeViewItem? match) { bool result = false; match = default; foreach (var childItem in childItems) { var cast = childItem as TreeViewItem; if (cast == null) break;
{ "domain": "codereview.stackexchange", "id": 45103, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, recursion, file-system, wpf", "url": null }
c#, .net, recursion, file-system, wpf if (item.Header.Equals(cast.Header)) { match = cast; result = true; break; } } return result; } Depending on your C# you could take advantage of the is pattern matching: private bool TryGetMatch(ItemCollection childItems, TreeViewItem item, out TreeViewItem? match) { bool result = false; match = default; foreach (var childItem in childItems) { if (childItem is TreeViewItem viewItem) { if (!item.Header.Equals(viewItem.Header)) continue; match = viewItem; result = true; } break; } return result; } UPDATE #1 You pointed out that the TreeView is readonly, but the Items collection is not. Is it even possible to make Items readonly since this is a built in class? Well you don't need to expose the entire TreeView component. It is enough to expose only its Items property. This property's data type is ItemCollection which implements the IList. So, exposing the ItemCollection as readonly prevents you to overwrite the property with other ItemCollection instance but it still allows you to add/remove items from the collection. private TreeView FileTree { get; } public ItemCollection Items => FileTree.Items; So, what can you do? Gladly it is enough (in this particular case) to use the AsEnumerable to prevent modification on the collection. private TreeView FileTree { get; } public IEnumerable Items => FileTree.Items.AsEnumerable(); <TreeView x:Name="FileTreeDisplayed" ItemsSource="{Binding Items}"/> Are there any notable benefits to using the is pattern matching over the as operator? The as operator can be used only with reference types and nullable types. So, for instance the following code won't event compile: object o = 1.0; var x = o as double; The is operator and expression do not have this constraint. var x = o is double; //operator if(o is double y) //expression { }
{ "domain": "codereview.stackexchange", "id": 45103, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, recursion, file-system, wpf", "url": null }
c#, .net, recursion, file-system, wpf Another notable difference is that you can define a lots pattern with is whereas as can be used only with types. Here are some examples: object o = TimeSpan.FromSeconds(1); if (o is not null) { //... } if (o is TimeSpan { Days: 0, TotalSeconds: > 0 } ts) { // You can use o and ts } if (o is TimeSpan { Minutes: 0 or 1 } ts) { // You can use o and ts } if (o is TimeSpan { TotalMilliseconds: var milliseconds } ts) { // You can use o, ts and milliseconds } ...
{ "domain": "codereview.stackexchange", "id": 45103, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, recursion, file-system, wpf", "url": null }
c, array Title: Automation of array allocation in C Question: I recently have been working on moving from projects written in Java and C++ to C and realized that the lack of std::vector in C makes it a bit more difficult to create multi-dimensional arrays. Also, without the std::string in C, it's harder to store arrays of strings and keep track of their sizes. To automate the process, I created a typedef'd struct: varray. varray attempts to emulate some basic functions of std::vector, e.g. storing sizes of the elements in an easily accessible location and allowing for allocation of multi-dimensional objects with "relative ease". I've attached the header "varray.h" and a bit of sample code with comments to demonstrate its use. Please note that at this point, I haven't tried to dynamically expand the arrays, though I'll look into it as I practice more with the language. If there is any feedback (syntax, memory allocation, anything), I'd greatly appreciate it - I'm still just getting started with C, C++, and Java. varray.h #ifndef VARRAY_H #define VARRAY_H #define VARRAY_DISPLAYDEBUG 0 #define VARRAY_STRSIZE(x) ((sizeof(char) * strlen(x)) + 1) #include <stdlib.h> #include <string.h> #include <stdio.h> typedef struct { int* getInt; char* getChar; double* getDbl; char* str; int size; } varray; typedef enum { v_char = 0, v_int = 1, v_double = 2, v_varray = 3, v_tdvarray = 4 } varrayType; void* createArray(varrayType arrayType, int arraySize); varray varrayPush(const char* data); varray allocateNumArray(varrayType type, const int size); varray allocateCharArray(const int size); varray* allocateVarray(const int size); varray** allocateTDVarray(const int size);
{ "domain": "codereview.stackexchange", "id": 45104, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, array", "url": null }
c, array inline void* createArray(varrayType arrayType, int arraySize) { varray* target; varray** vtarget; varray*** tdvtarget; if (arrayType == v_char) { target = malloc(sizeof(varray) * arraySize); *target = allocateCharArray(arraySize); return target; } else if (arrayType == v_int || arrayType == v_double) { target = malloc(sizeof(varray) * arraySize); *target = allocateNumArray(arrayType, arraySize); return target; } else if (arrayType == v_varray) { vtarget = malloc(sizeof(varray*) * arraySize); *vtarget = allocateVarray(arraySize); return *vtarget; } else if (arrayType == v_tdvarray) { tdvtarget = malloc(sizeof(varray**) * arraySize); *tdvtarget = allocateTDVarray(arraySize); return *tdvtarget; } else { return NULL; } } inline varray varrayPush(const char* data) { varray target; if (VARRAY_DISPLAYDEBUG) { printf("%s%d%s%s\n", "Allocating array with size: ", (int)VARRAY_STRSIZE(data) - 1, " with contents: ", data); } target.str = malloc(VARRAY_STRSIZE(data)); strcpy(target.str, data); if (VARRAY_DISPLAYDEBUG) { printf("%s%s\n", "String created successfully. Contents reads: ", target.str); printf("%s%d\n", "Memory address: ", (int)target.str); } target.size = VARRAY_STRSIZE(data); return target; }
{ "domain": "codereview.stackexchange", "id": 45104, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, array", "url": null }
c, array inline varray allocateNumArray(varrayType type, const int size) { int i; varray target; if (type == v_int) { if (VARRAY_DISPLAYDEBUG) { printf("%s%d\n", "Allocating array of type v_int with size ", size); } target.getInt = malloc(sizeof(int) * size); for (i = 0; i < size; i++) { target.getInt[i] = 0; } } else if (type == v_double) { if (VARRAY_DISPLAYDEBUG) { printf("%s%d\n", "Allocating array of type v_double with size ", size); } target.getDbl = malloc(sizeof(double) * size); for (i = 0; i < size; i++) { target.getDbl[i] = 0.0; } } target.size = size; return target; } inline varray allocateCharArray(const int size) { varray target; int i; if (VARRAY_DISPLAYDEBUG) { printf("%s%d\n", "Allocating array of type v_char with size ", size); } target.getChar = malloc(sizeof(char) * size); for (i = 0; i < size; i++) { target.getChar[i] = 0; } target.size = size; return target; } inline varray* allocateVarray(const int size) { varray* target = malloc(sizeof(varray) * (size + 1)); if (VARRAY_DISPLAYDEBUG) { printf("%s%d\n", "Allocated array of type v_varray with size ", size); } target[0].size = size; return target; } inline varray** allocateTDVarray(const int size) { varray** target = malloc(sizeof(varray*) * (size + 1)); if (VARRAY_DISPLAYDEBUG) { printf("%s%d\n", "Allocated array of type v_tdvarray with size ", size); } target[0] = malloc(sizeof(varray)); target[0][0].size = size; return target; } #endif Example implementation #include "varray.h"
{ "domain": "codereview.stackexchange", "id": 45104, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, array", "url": null }
c, array #endif Example implementation #include "varray.h" void varrayDemo() { varray sampleInt; /* * Functions as a normal array but also stores * the size of the array at sampleInt.size. * Accessing data elements used the syntax * VARRAY.getInt[POSITION] */ varray* sampleString; /* * Since a C string is an array of char, creating * an array of varray objects can easily store multiple * strings. The size of the varray array can be accessed * via VARRAY[0].size Individual elements can be * accessed at VARRAY[POSITION].str with position >= 1 */ varray** sampleContainer; /* * The container of varrays can store multiple data types * at each element's position. For example, the syntax * VARRAY[1][1].str will return the string, if stored. * while VARRAY[2][2].getDbl[POSITION] returns the double */ sampleInt = *(varray*)createArray(v_int, 5); /* * The function createArray(TYPE, SIZE) initializes the array * NOTE: I am not sure if there is a more "aesthetically pleasing" * way to initialize the array, since createArray returns a void * pointer. When initialized, all values are set to 0 */ printf("The size of sampleInt is: %d\n", sampleInt.size); printf("The data at position 0 is: %d\n", sampleInt.getInt[0]);
{ "domain": "codereview.stackexchange", "id": 45104, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, array", "url": null }
c, array sampleString = createArray(v_varray, 2); /* * Each varray can contain one string. Initialize each element * with the createArray command. */ printf("The size of sampleString is: %d\n", sampleString[0].size); /* * As noted above, the size is stored in a varray at position 0 * in the container */ sampleString[1] = varrayPush("This is a sample string"); sampleString[2] = varrayPush("This is also a sample string!"); /* * To store a string within a varray, the function varrayPush is used * with the desired string as the argument. The function initializes * another varray object within the container. */ printf("The string at position 1 is: %s\n", sampleString[1].str); printf("The size of the string stored at position 1 is: %d\n", sampleString[1].size); printf("The char at position 5 in sampleString[1] is: %c\n", sampleString[1].str[5]); sampleContainer = createArray(v_tdvarray, 2); sampleContainer[1] = createArray(v_varray, 1); sampleContainer[1][1] = *(varray*)createArray(v_double, 5); sampleContainer[1][1].getDbl[4] = 3.14; sampleContainer[2] = createArray(v_varray, 1); sampleContainer[2][1] = varrayPush("yet another sample string"); /* * As noted with the original sampleInt example, the *(varray*) * syntax is used again. */ printf("sampleContainer[1][1] has size: %d with data %lf at position 4\n", sampleContainer[1][1].size, sampleContainer[1][1].getDbl[4]); printf("sampleContainer[2][1] has size %d with string \"%s\"\n", sampleContainer[2][1].size, sampleContainer[2][1].str); } Answer: Too much memory target = malloc(sizeof(varray) * arraySize); *target = allocateCharArray(arraySize); allocates that many varray entries, and uses just one of them. If you insist on double indirection, target = malloc(sizeof(varray)); is just enough. OTOH I don't see a need for a double indirection at all.
{ "domain": "codereview.stackexchange", "id": 45104, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, array", "url": null }
c, array is just enough. OTOH I don't see a need for a double indirection at all. All pointers smell the same There is no need to have pointers to all possible types. A single void * data would serve the same purpose. You should have getWhatever as accessor functions. You may want to associate the accessor function with the varray instance, eg: typedef struct varray { void * (*get)(struct varray * v, size_t index); void * data; size_t size; } struct varray * allocateCharArray(size_t size) { .... v->get = vGetChar; } where void * vGetChar(varray * v, size_t index) { return (char *) v->data + index; } Missing deallocations Client has no resources to deallocate varrays. Use standard library To zero out allocated memory, use calloc. To copy a string, use strdup.
{ "domain": "codereview.stackexchange", "id": 45104, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, array", "url": null }
c++, object-oriented, classes, embedded, namespaces Title: Defining hardware components structure Question: I'm writing firmware for my Arduino project, and I'm struggling with a clean, scalable hardware mapping structure. Initially, I had the following namespace: namespace Motherboard { extern DRV8825 xAxisMotor; extern MP6500 yAxisMotor; extern DRV8876 zAxisMotor; extern ClickEncoder encoder; extern SSD1331 display; extern RGBLed rgbIndicator; extern Relay heaterRelay; void performMainSequence(); void begin(const EepromData &initialData); }; // namespace Motherboard Which I initialized like this: namespace Motherboard { //=================== Public ==================== DRV8825 xAxisMotor = { 23, // ENABLE PIN 25, // MS0 PIN 27, // MS1 PIN 29, // MS2 PIN 31, // RESET PIN 33, // SLEEP PIN 35, // STEP PIN 37, // DIRECTION PIN 39, // FAULT PIN MOTHERBOARD_X_AXIS_MAX_SPEED, MOTHERBOARD_X_AXIS_MIN_POSITION, MOTHERBOARD_X_AXIS_MAX_POSITION, }; MP6500 yAxisMotor = { 22, // ENABLE PIN 24, // MS1 PIN 26, // MS2 PIN 28, // SLEEP PIN 30, // STEP PIN 32, // DIRECTION PIN 34, // FAULT PIN MOTHERBOARD_Y_AXIS_MAX_SPEED, MOTHERBOARD_Y_AXIS_MIN_POSITION, MOTHERBOARD_Y_AXIS_MAX_POSITION, }; DRV8876 zAxisMotor = { 44, // ENABLE PIN 36, // PHASE PIN 38, // PMODE PIN 40, // SLEEP PIN 42, // FAULT PIN MOTHERBOARD_Z_AXIS_MAX_SPEED}; ClickEncoder encoder = { 45, // A PIN 43, // B PIN 41, // SW PIN 2, // STEPS PER NOTCH }; SSD1331 display = { 53, // CS PIN 48, // DC PIN 49, // RESET PIN }; RGBLed rgbIndicator = { 13, // R PIN 12, // G PIN 11, // B PIN RGBLed::COMMON_CATHODE, // COMMON }; Relay heaterRelay = { 47 // SWITCH PIN }; void performMainSequence() { // } void begin(const EepromData &initialData) { // } //=============================================== }; // namespace Motherboard
{ "domain": "codereview.stackexchange", "id": 45105, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, classes, embedded, namespaces", "url": null }
c++, object-oriented, classes, embedded, namespaces A senior in my company saw this piece of code, suggested moving this to a class and create interfaces for hardware related classes. Therefore, I've created this: struct MotherboardDevices { IStepperDriver* xAxisMotor; IStepperDriver* yAxisMotor; IDcDriver* zAxisMotor; ISwitch* heaterRelay; RGBLed* rgbIndicator; ClickEncoder* encoder; IDisplay* display; }; class Motherboard { public: MotherboardDevices devices; Motherboard(); Motherboard(const MotherboardDevices _devices); void motherboardIsr(); void performMainSequence(); void begin(const EepromData &initialData); }; I was struggling with the way of initializing this class. I eventualy created separate file: namespace Hardware { namespace { DRV8825 initXAxisMotor() { DRV8825Pinout xAxisPinout = { 23, // ENABLE PIN 25, // MS0 PIN 27, // MS1 PIN 29, // MS2 PIN 31, // RESET PIN 33, // SLEEP PIN 35, // STEP PIN 37, // DIRECTION PIN 39, // FAULT PIN }; DRV8825 xAxisMotor = { xAxisPinout, MOTHERBOARD_X_AXIS_MAX_SPEED, MOTHERBOARD_X_AXIS_MIN_POSITION, MOTHERBOARD_X_AXIS_MAX_POSITION, }; return xAxisMotor; } MP6500 initYAxisMotor() { MP6500Pinout yAxisPinout = { 22, // ENABLE PIN 24, // MS1 PIN 26, // MS2 PIN 28, // SLEEP PIN 30, // STEP PIN 32, // DIRECTION PIN 34, // FAULT PIN }; MP6500 yAxisMotor = { yAxisPinout, MOTHERBOARD_Y_AXIS_MAX_SPEED, MOTHERBOARD_Y_AXIS_MIN_POSITION, MOTHERBOARD_Y_AXIS_MAX_POSITION, }; return yAxisMotor; } DRV8876 initZAxisMotor() { DRV8876Pinout zAxisPinout = { 44, // ENABLE PIN 36, // PHASE PIN 38, // PMODE PIN 40, // SLEEP PIN 42, // FAULT PIN }; DRV8876 zAxisMotor = { zAxisPinout, MOTHERBOARD_Z_AXIS_MAX_SPEED, };
{ "domain": "codereview.stackexchange", "id": 45105, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, classes, embedded, namespaces", "url": null }
c++, object-oriented, classes, embedded, namespaces DRV8876 zAxisMotor = { zAxisPinout, MOTHERBOARD_Z_AXIS_MAX_SPEED, }; return zAxisMotor; } Relay initHeaterRelay() { Relay heaterRelay = { 47 // SWITCH PIN }; return heaterRelay; } SSD1331 initDisplay() { SSD1331 display = { 53, // CS PIN 48, // DC PIN 49, // RESET PIN }; return display; } ClickEncoder initEncoder() { ClickEncoder encoder = { 45, // A PIN 43, // B PIN 41, // SW PIN 2, // STEPS PER NOTCH }; return encoder; } RGBLed initRgbIndicator() { RGBLed rgbIndicator = { 13, // R PIN 12, // G PIN 11, // B PIN RGBLed::COMMON_CATHODE, // COMMON }; return rgbIndicator; } MotherboardDevices createDevices() { static auto xAxisMotor = initXAxisMotor(); static auto yAxisMotor = initYAxisMotor(); static auto zAxisMotor = initZAxisMotor(); static auto heaterRelay = initHeaterRelay(); static auto rgbIndicator = initRgbIndicator(); static auto encoder = initEncoder(); static auto display = initDisplay(); return { &xAxisMotor, &yAxisMotor, &zAxisMotor, &heaterRelay, &rgbIndicator, &encoder, &display, }; } MotherboardDevices devices = createDevices(); } // namespace Motherboard motherboard = Motherboard(devices); } // namespace Hardware
{ "domain": "codereview.stackexchange", "id": 45105, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, classes, embedded, namespaces", "url": null }
c++, object-oriented, classes, embedded, namespaces } // namespace Motherboard motherboard = Motherboard(devices); } // namespace Hardware I feel like now it's messier than before and I could've done that better. It also creates a problem with my UI layer. I'm using ArduinoMenu library for creating UI menu system. This UI is built using macros and needs static, compile time access to hardware related methods. That means I can't use dependency injection and pass created Motherboard object to UI class. I would have to pass global Motherboard instance via extern which is ugly. It also doesn't make sense to create multiple instance of this class. Would keeping this structure as namespace with hardware interfaces better? It would be statically available for the UI, there wouldn't be a way of creating multiple instances. I could initialize all the hardware in the related to header, cpp file. However, what I would essentially do here is create a bunch of global variables. I also don't like the idea of the possibility to modify this namespace from every place. Edit, adding more context Motherboard::devices would be accessed from non members, UI event handler example: result updateZAxisSpeed(eventMask event) { if (event == enterEvent) { Hardware::motherboard.devices.zAxisMotor->start(); } else if (event == updateEvent) { uint8_t updatedValue = EepromManager::currentSettings.zSpeed; Hardware::motherboard.devices.zAxisMotor->setSpeed(updatedValue); } else if (event == exitEvent) { EepromManager::syncEeprom(); Hardware::motherboard.devices.zAxisMotor->stop(); } return proceed; } Motherboard::begin is a late initialization method. It configures provided devices, like: devices.encoder->setAccelerationEnabled(false); devices.encoder->setButtonHeldEnabled(false); devices.encoder->setDoubleClickEnabled(false); Motherboard::performMainSequence method: void Motherboard::performMainSequence() { devices.heaterRelay->toggleOn(); delay(5000);
{ "domain": "codereview.stackexchange", "id": 45105, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, classes, embedded, namespaces", "url": null }
c++, object-oriented, classes, embedded, namespaces long xHalfWay = devices.xAxisMotor->getEndPosition() / 2; devices.yAxisMotor->moveToEnd(); devices.xAxisMotor->moveTo(xHalfWay); devices.zAxisMotor->start(); devices.xAxisMotor->moveToEnd(); delay(2000); devices.xAxisMotor->moveTo(xHalfWay); devices.zAxisMotor->stop(); devices.heaterRelay->toggleOff(); devices.xAxisMotor->moveToStart(); devices.yAxisMotor->moveToStart(); } Motherboard::motherboardIsr() is an interrupt routine: void Motherboard::motherboardIsr() { devices.encoder->service(); } When Motherboard was a namespace I could just directly asign service() method of my encoder to microcontroller's timer interrupt. Since interrupts needs global context and Motherboard now is a class I had to expose isr routine method and asign it globally: Timer1.attachInterrupt([]() { Hardware::motherboard.motherboardIsr(); }); Answer: Namespace vs. struct It's great that you created a namespace, that already avoids some of the problems global variables have. However, a struct has some advantages, and it's rather trivial to go from a namespace to a struct: extern struct { DRV8825 xAxisMotor; MP6500 yAxisMotor; DRV8876 zAxisMotor; … void performMainSequence(); void begin(const EepromData &initialData); } Motherboard;
{ "domain": "codereview.stackexchange", "id": 45105, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, classes, embedded, namespaces", "url": null }
c++, object-oriented, classes, embedded, namespaces This declares a global variable Motherboard whose type is a struct holding all the actuator objects. Instead of Motherboard::zAxisMotor.stop(), you then just have to write Motherboard.zAxisMotor.stop(). However, now we can give the struct a name, pass it around, have multiple instances of it, add access control (public/private), and so on. These are all benefits that are not available with a namespace. In particular, you can mostly avoid needing global variables this way, but since you have the interrupt service routine, you really do need something global; either the object itself, or a pointer to the object which can then be allocated elsewhere. For an embedded device, I would just make a global object, to avoid the overhead of pointer dereferencing. Interfaces and inheritance It's great if each device has a consistent interface, however if you go the route of abstract base classes, then you need to use pointers which have to be dereferenced, and those pointers point to vtables which contain the pointers to the actual functions. So that's more dereferencing, which adds some overhead. For an embedded project where you know exactly which type each actuator is, I think that is unnecessary. You can write code so the compiler can check that all your classes follow a given interface (see this StackOverflow post). Having a well-defined interface is handy if you want to write generic functions that work with multiple types of actuators. For example, if you want something that moves to start, then moves to end, then moves back to start (maybe for some initialization sequence where it finds the end stops and records encoder positions). You want to write this once so it works for all tyeps of motors. It would then either pass a pointer to an abstract base class: void doInitSequence(IStepperMotor* motor) { motor->moveToStart(); … motor->moveToEnd(); … motor->moveToStart(); }
{ "domain": "codereview.stackexchange", "id": 45105, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, classes, embedded, namespaces", "url": null }
c++, object-oriented, classes, embedded, namespaces Or you can make it a template: template<typename Motor> void doInitSequence(Motor* motor) { motor->moveToStart(); … motor->moveToEnd(); … motor->moveToStart(); } In the latter case, you can directly pass it a pointer to a DRV8825 without needing inheritance.
{ "domain": "codereview.stackexchange", "id": 45105, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, classes, embedded, namespaces", "url": null }
java, object-oriented, design-patterns Title: Business logic verification template Question: I have a use case of template design pattern with generics as mentioned below. I have AbstractVerificationHandler that provides template for verification business logic which is used by different domain verification handlers e.g UserVerifier depending on the db type and file type POJOs. Can the below code be simplified using simpler constructs or by reducing the scope of generics? class VerificationJob { public void execute() { String domainType = "user"; VerificationHandler verifier = getVerifierInstance(domainType); boolean result = verifier.verify(); } VerificationHandler getVerifierInstance() { return domainType.equals("user") ? new UserVerifier() : null // or a switch case etc. } } interface VerificationHandler { boolean verify(); // omitted common inputs for verification } interface Identify { String identity(); } abstract class AbstractVerificationHandler<F extends Identity, D extends Identity> implements VerificationHandler { boolean verify() { List<D> dbRecords = fetchAllDBRecords(); Map<String, F> fileRecords = identityMap(fetchAllFileRecords()); for(D record: dbRecords) { if(!verify(record, fileRecords.get(record.identity()))) { return false; } } return true; } private Map<String, F> identityMap(List<F> fileRecords) { // map creation using F.identity() } abstract List<D> fetchAllDBRecords(); abstract List<F> fetchAllFileRecords(); abstract boolean verify(D dbRec, F fileRec); } class UserVerifier extends AbstractVerificationHandler<DBUser, FileUser> { List<DBUser> fetchAllDBRecords() { // code omitted } List<FileUser> fetchAllFileRecords() { // code omitted } boolean verify(DBUser dbuser, FileUser fileuser) { // code omitted // fields specific comparison with different names etc. } }
{ "domain": "codereview.stackexchange", "id": 45106, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, object-oriented, design-patterns", "url": null }
java, object-oriented, design-patterns } } class DBUser implements Identity { // code omitted } class FileUser implements Identity { // code omitted } Answer: As I mentioned in the comment, you should strive to using composition instead of inheritance. The AbstractVerificationHandler exists only as an extension point for the user to provide access to the data. Instead of implementing fetching and verifing as abstract methods, use suppliers and predicates. For example: public class VerificationTask<T extends Identifiable, U extends Identifiable> { // Provide these in a constructor. final Supplier<Collection<T>> supplierT; final Supplier<Collection<U>> supplierU; final BiPredicate<T, U> verifier; public boolean verify() { Collection<T> tRecords = supplierT.get(); Map<String, U> uRecords = identityMap(supplierU.get()); for (T record: tRecords) { if (!verifier.test(record, uRecords.get(record.identity()))) { return false; } } return true; } } The users are loaded with one purpose suppliers: public class DBUserLoader implements Supplier<Collection<DBUser>> { public Collection<DBUser> get() { // Load users from DB. } } UserVerifier becomes a simple one purpose predicate: public class UserVerifier extends BiPredicate<DBUser, FileUser> { public boolean test(DBUser dbuser, FileUser fileuser) { // fields specific comparison with different names etc. } }
{ "domain": "codereview.stackexchange", "id": 45106, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, object-oriented, design-patterns", "url": null }
java, object-oriented, design-patterns Following this your code doesn't violate the single responsibility principle. In your code the UserVerifier class is responsible for three things: loading data from DB, loading data from file and comparing the entries. I renamed the Identify interface as Identifiable as the word "identify" describes a command while "identifiable" describes a capability. It also follows the custom used in the Java standard libraries (e.g. Comparable, Iterable). You should use as generic collection classes as you canget away with. Requiring a List when the code does not require any list specific operations unnecessarily limits the programmer who implements your API. Maybe they are forced to use another API that provides a Set, which would require them to repack their data to a List before handing it over to you.
{ "domain": "codereview.stackexchange", "id": 45106, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, object-oriented, design-patterns", "url": null }
java, file, lambda, file-structure Title: Add offset to all filenames Question: From all the files in a directory, the method shiftFilenamesOffset is to increment the numeric part (int) of the alphanumeric filename by offset each time, and rename the files. A negative offset is also allowed. Example: offset: -2 Old filename: New filename: Textdokument (neu) 3.txt -> Textdokument (neu) 1.txt Textdokument (neu) 5.4.1txt -> Textdokument (neu) 5.2.1txt Textdokument (neu) 5.txt -> Textdokument (neu) 3.txt Textdokument (neu) 6.txt -> Textdokument (neu) 4.txt import java.io.File; import java.util.Arrays; import java.util.Comparator; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NFiles { record Filename(File file, String prefix, int number, String ending) { } private static final String regex = "(.*)(\\d+)\\.([^.]*)"; private static final Pattern pattern = Pattern.compile(regex); public static void shiftFilenamesOffset(final File dir, final int offset) { Comparator<Filename> filenameComparator = offset <= 0 ? Comparator.comparingInt(Filename::number) : Comparator.comparingInt(Filename::number) .reversed(); Arrays.stream(Objects.requireNonNull(dir.listFiles())) .filter(f -> pattern.matcher(f.getName()).find()) .map(f -> { Matcher mat = pattern.matcher(f.getName()); mat.find(); return new Filename(f, mat.group(1), Integer.parseInt(mat.group(2)), mat.group(3)); }) .sorted(filenameComparator) .forEach(fn -> { File nf = new File(fn.file().getParent(), fn.prefix() + (fn.number() + offset) + "." + fn.ending()); System.out.println(fn + " -> " + nf + " -> " + fn.file().renameTo(nf)); }); }
{ "domain": "codereview.stackexchange", "id": 45107, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, file, lambda, file-structure", "url": null }
java, file, lambda, file-structure public static void main(final String[] args) { shiftFilenamesOffset(new File("test1"), -3); } } Answer: Reusing function You can create a constant with Comparator function and reuse it in method. private static final Comparator<Filename> comparator = Comparator.comparingInt(Filename::number); enter code here public static void shiftFilenamesOffset(final File dir, final int offset) { Comparator<Filename> filenameComparator = offset <= 0 ? comparator : comparator.reversed(); ----- ----- } Duplicate computation pattern.matcher(f.getName()).find() is done twice and can be done once. Something like this Arrays.stream(Objects.requireNonNull(dir.listFiles())) .map(f -> { Matcher mat = pattern.matcher(f.getName()); return mat.find() ? new Filename(f, mat.group(1), Integer.parseInt(mat.group(2)), mat.group(3)) : null; }) .filter(Objects::nonNull) Invariants Validation You can add Invariants/Input validation at the beginning of method. Also you've put non null check on dir.listFiles() which is good. Objects.requireNonNull(dir.listFiles()) you can add further validation if dir or offset are valid or not in the beginning. Minor Comment Rename your constants to match the regular expression '^[A-Z][A-Z0-9](_[A-Z0-9]+)$' meaning that they should be uppercase separated by underscore generally. Good Points In your code Used latest Java Features like records. Used fluent APIs and streams to iterate over directory structure and using comparator.
{ "domain": "codereview.stackexchange", "id": 45107, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, file, lambda, file-structure", "url": null }
python, performance, time-limit-exceeded Title: Find all combinations of two companies grouped by the projects they are tendering for Question: I am working on the task to get all possible combinations (pairs) of ID's (companies) which participated in one bid and create a new data frame with ID_1, ID_2, matching parameter (tender ID). I have prepared the following two functions which provide me with the required result however the execution time exceeds several hours when applying to df with more than 500k lines. import pandas as pd from itertools import combinations def get_pairs(dataframe, items): return ( (c1, c2, item) for item in items for c1, c2 in combinations(dataframe[dataframe['tender_product'] == item]['ID_name'], 2) ) def get_all_pairs(df): pairs = get_pairs(df,df['tender_product']) df= pd.DataFrame(pairs, columns=['ID_name1', 'ID_name2','tender_product']) df=df.query('ID_name1 != ID_name2') df=df.drop_duplicates() df['pair'] = df['ID_name1'].astype(str)+'_'+df['ID_name2'].astype(str) df['reversed_pair'] =df['ID_name1'].astype(str)+'_'+df['ID_name2'].astype(str) return df What are the options to optimize the code to make it work faster with the same result? The sample of intial data: ID tender_product 1 tender_1 2 tender_1 3 tender_2 4 tender_2 The sample of current output: ID1 ID2 tender_product pair reversed_pair 1 2 tender_1 1_2 2_1 3 4 tender_2 3_4 4_3 Answer: What are the options to optimize the code You wrote ... for item in items ... dataframe['tender_product'] == item ... and complained that this takes a Long Time. Even in the example data we can see that the "find all rows containing item" scan happens multiple times. And then we discard duplicates. What you wanted was to .groupby() items. That lets you generate just the required rows rather than generating tons of dups only to later drop them.
{ "domain": "codereview.stackexchange", "id": 45108, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, time-limit-exceeded", "url": null }
c#, .net, entity-framework-core Title: Mapping Entity Database Table to Model Question: I am not sure of the correct way to do this. I want to separate my Entity database model from the model I use throughout my application, as it will have fields in it that I may not want added to the database. This means, after any Entity call I am doing mapping. I have come up with this solution rather than use automapper or have mapping calls everywhere in my program (breaking the DRY principal). My Entity DdSet Model: public class PeopleTable { [Key] public string Id { get; set; } public string Name { get; set; } public string Age { get; set; } } The Model I would use throughout the application. It has some additional fields and a MapList() mapping function. public class People : PeopleTable { public string Job { get; set; } public string Hobby { get; set; } public List<People> MapList(List<PeopleTable> input) { List<People> list = new List<People>(); foreach (People entry in input) { People person = new People(); person.Id = entry.Id; person.Name = entry.Name; person.Age = entry.Age; list.Add(person); } return list; } } Getting the data List<PeopleTable> peopleTableList = await _context.PeopleTable.Select(s => s).ToListAsync(); List<People> peopleList = new People().MapList(peopleTableList); foreach (person in peopleList){ Console.WriteLine($"{person.Name} is {person.Age} years old"); } Is this ok? What is best practice? I am thinking there must be something better using the class constructor instead? Or does everyone just use automapper? I'd rather not have another dependency.
{ "domain": "codereview.stackexchange", "id": 45109, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, entity-framework-core", "url": null }
c#, .net, entity-framework-core Answer: Mapping objects is a subject in it's own. It is not how do you do it, but rather, which way is it going to be suitable to your overall project. There are a lot of mapping NuGets out there such as AutoMapper and Mapperly, but if you don't want to add extra dependencies to your project, then I would suggest using extension methods instead. Using extension methods would separate your mapping from your actual objects, and keep everything in one place, not to mention the maintainability of this approach. Here is how things would go : // define a DTO model (Data Transfer Object) public sealed class PeopleDto { public string Id { get; set; } public string Name { get; set; } public string Age { get; set; } public string Job { get; set; } public string Hobby { get; set; } } public static class PeopleTableExtensions { public static PeopleDto ToPeopleDto(this PeopleTable source) { if(source is null) return null; return new PeopleDto { Id = source.Id, Name = source.Name, Age = source.Age }; } public static IEnumerable<PeopleDto> ToPeopleDto(this IEnumerable<PeopleTable> source) { if(source is null) yield break; foreach(var item in source) { if(item is null) continue; yield return source.ToPeopleDto(); } } public static PeopleTable ToPeopleTable(this PeopleDto source) { if(source is null) return null; return new PeopleTable { Id = source.Id, Name = source.Name, Age = source.Age }; } public static IEnumerable<PeopleTable> ToPeopleTable(this IEnumerable<PeopleDto> source) { if(source is null) yield break;
{ "domain": "codereview.stackexchange", "id": 45109, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, entity-framework-core", "url": null }
c#, .net, entity-framework-core foreach(var item in source) { if(item is null) continue; yield return source.ToPeopleTable(); } } } Usage : var peopleTableList = await _context.PeopleTable.Select(s => s).ToListAsync(); var peopleDotList = peopleTableList.ToPeopleDto(); foreach (person in peopleDotList){ Console.WriteLine($"{person.Name} is {person.Age} years old"); }
{ "domain": "codereview.stackexchange", "id": 45109, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, entity-framework-core", "url": null }
c#, error-handling, wpf Title: Error Reporting in WPF app Question: I want to add an error reporting feature to my WPF app. I have the view for it created; I just need to know when to call it. I am used to web development and this is my first WPF app. public static void Get<T>(Func<T> func, Action<BaseResult<T>> callback, bool report = false){ BaseResult<T> result; try { result = new BaseResult<T>(func()); } catch (Exception ex){ if (report) new ErrorWindow(ex.Message).Show(); result = new BaseResult<T>(false, ex.Message); } callback(result); } The BaseResult class stores the result if the call was successful and an error message if it isn't. Sometimes I don't want to report the result of the call to an error screen, sometimes I just want to know if the call was successful. Does this violate Single Responsibility Principle? This can't be the best way of implementing this. Has anyone done this before? My way seems overly complicated. Answer: Let's split your logic into two methods public static void Get<T>(Func<T> func, Action<BaseResult<T>> callback, bool report = false) { var result = GetSafe(func, report); if (report && result.IsFault) { new ErrorWindow(ex.Message).Show(); } callback(result); //does not fit here nicely } private static BaseResult<T> GetSafe<T>(Func<T> func) { try { return new(func()); } catch (Exception ex) { return new(false, ex.Message); } } The GetSafe's responsibility is to execute the provided user delegate and map the execution outcome accordingly The Get's responsibility is to call GetSafe and notify user about failure And that's where the callback does not fit in. Change return type public static BaseResult<T> Get<T>(Func<T> func, bool report = false) { var result = GetSafe(func, report); if (report && result.IsFault) { new ErrorWindow(ex.Message).Show(); } return result; }
{ "domain": "codereview.stackexchange", "id": 45110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, error-handling, wpf", "url": null }
c#, error-handling, wpf return result; } private static BaseResult<T> GetSafe<T>(Func<T> func) { try { return new(func()); } catch (Exception ex) { return new(false, ex.Message); } } With this approach the consumer of the Get API does not have to provide an "execution outcome handler" rather than they can do the handling by their own.
{ "domain": "codereview.stackexchange", "id": 45110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, error-handling, wpf", "url": null }
rust, heap Title: implementing a min/max Heap in rust Question: I am more on data analyst than a programmer, but I do enjoy coding for fun. I tried to implement a Heap in rust. I would appreciate any return you may have, so I can improve. //! a minimal heap implementation support minimum and maximum heap, insertion, //! heapify and pop/peeks at the top node. //! Support optional data attached to a node #[derive(Debug)] /// /// T is a numeric value used to sort the heap /// D is the attached type, if max is true the heap is maximum heap else it is minimum heap ///``` rust /// let mut my_heap = Heap::new(5, Some(Box::new("chocolate")), false); /// ``` pub struct Heap<T, D>{ data: Option<Vec<(T, Option<Box<D>>)>>, max: bool} impl <T, D> Heap<T, D> where T: PartialEq + Copy + std::cmp::PartialOrd + std::fmt::Debug, D: std::fmt::Debug + Copy, { /// create a new non empty heap ///``` rust /// let mut my_heap = Heap::new(5, Some(Box::new("chocolate")), false); /// // or /// let mut my_heap<i32, &str> = Heap::new(5, None, false); /// ``` pub fn new(value: T, data: Option<Box<D>>, max: bool) -> Self { Heap{data: Some(vec![(value, data)]), max } } pub fn new_empty(max: bool) -> Self { Heap{data: None, max } } pub fn is_empty(&self) -> bool{ match &self.data{ Some(_x) => false, _ => true } } /// swap 2 values from the heap fn swap(&mut self, x: usize, y: usize) -> Result<(), &'static str> { if self.is_empty(){ return Err("can't swap value of an empty heap"); } let heap_size = self.get_size()?; if (heap_size <= x) | (heap_size <= y){ return Err("swapping indice are out of index"); }
{ "domain": "codereview.stackexchange", "id": 45111, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, heap", "url": null }
rust, heap match self.data{ Some(ref mut data) => { let p = data[x].clone(); data[x] = data[y].clone(); data[y] = p; return Ok(()); }, _ => {return Err("error unwrapping heap while swapping");} }; //let p = self.data[x].clone(); //self.data[x] = self.data[y].clone(); // self.data[y] = p; //() } /// insert a new values in the heap ///``` rust /// let mut my_heap = Heap::new(5, Some(Box::new("chocolate")), true); /// result.insert(8, Some(Box::new("beast"))); /// result.insert(2, None); ///``` pub fn insert(&mut self, value: T, data: Option<Box<D>>) -> Result<(), &'static str>{ if self.is_empty(){ self.data.as_mut().unwrap().push((value, data)); return Ok(()); } self.data.as_mut().unwrap().push((value, data)); let mut current_index = self.get_size()? - 1; let mut parent = self.get_parent(current_index)?; match self.max{ false => { while parent.1 > value{ self.swap(current_index, parent.0)?; current_index = parent.0; if current_index != 0{ parent = self.get_parent(current_index)?;} else{break} } }, true => { while parent.1 < value{ self.swap(current_index, parent.0)?; current_index = parent.0; if current_index != 0{ parent = self.get_parent(current_index)?;} else{break} } } } Ok(()) }
{ "domain": "codereview.stackexchange", "id": 45111, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, heap", "url": null }
rust, heap /// return a tuple, cloned value T / data D of the top node. pub fn peeks_top(&self) -> Result<(T, Option<Box<D>>), &'static str>{ if self.is_empty(){ return Err("can't peeks at an empty heap"); } match &self.data{ Some(data) => Ok((data[0].0, data[0].1.clone())), _ => return Err("unwrapping while peeking") } //Ok((self.data.unwrap()[0].0, self.data.unwrap()[0].1.clone())) } fn heapify(&mut self, indice: usize) -> Result<(), &'static str>{ if self.is_empty(){ return Err("can't heapify empty Heap"); } let length_heap = self.get_size()?; println!("{} {}", indice, length_heap); let mut should_be_on_top = indice; let l = Self::get_left_child(indice); let r = Self::get_right_child(indice); match self.max{ true => { if r < length_heap{ if self.data.as_ref().unwrap()[r].0 > self.data.as_ref().unwrap()[should_be_on_top].0{ should_be_on_top = r } } if l < length_heap { if self.data.as_ref().unwrap()[l].0 > self.data.as_ref().unwrap()[should_be_on_top].0 { should_be_on_top = l } } }, false => { if r < length_heap { if self.data.as_ref().unwrap()[r].0 < self.data.as_ref().unwrap()[should_be_on_top].0{ should_be_on_top = r } } if l < length_heap { if self.data.as_ref().unwrap()[l].0 < self.data.as_ref().unwrap()[should_be_on_top].0{ should_be_on_top = l } } } }
{ "domain": "codereview.stackexchange", "id": 45111, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, heap", "url": null }
rust, heap if should_be_on_top != indice{ self.swap(indice, should_be_on_top); self.heapify(should_be_on_top); } Ok(()) } pub fn get_size(&self) -> Result<usize, &'static str>{ if self.is_empty(){ return Err("empty Heap has no size"); } Ok(self.data.as_ref().unwrap().len()) } /// remove the top node from the heap, heapify the heap. Finaly, return the tuple (value<T>/data<D>) from the removed top node pub fn pop(&mut self) -> Result<(T, Option<Box<D>>), &'static str>{ self.swap(0, self.get_size()? - 1)?; let popped = self.data.as_mut().unwrap().pop(); self.heapify(0); match popped{ Some(x) => Ok(x), _ => return Err("error unwrapping after pop and heapify") } } fn get_parent(&self, position: usize) -> Result<(usize, T), &'static str>{ if self.is_empty(){ return Err("no parent in empty Heap"); } let x = (position - 1) / 2; Ok((x, self.data.as_ref().unwrap()[x].0)) } fn get_left_child(indice: usize) -> usize { indice * 2 + 1 } fn get_right_child(indice : usize) -> usize{ indice * 2 + 2 } }
{ "domain": "codereview.stackexchange", "id": 45111, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, heap", "url": null }
rust, heap fn get_right_child(indice : usize) -> usize{ indice * 2 + 2 } } Answer: Formatting Your current code is hard to read. The indentation of e.g. the trait bounds seems weird to me. Also the indentation and extra newlines in Heap::new() seems off to me. You can format your code accoring to the standard code style guidelines using cargo fmt or rustfmt respectively. Unnecessary trait bounds You require PartialEq and PartialOrd as trait bounds. But PartialOrd implies PartialEq. Therefore, the trait bound PartialEq is superfluous. Furthermore, the trait bound to Copy is a rather heavy restriction. Consider relaxing it to Clone and call T.clone() explicitly where necessary. Useless use of match match self.max {} seems like overkill. match is intended for structural pattern matching. Since self.max is a bool a plain old if self.max {} else {} would suffice. API design You only use self.max in insert() and heapify(). Consider removing it as a struct member and making it a method parameter instead. This would also allow for new_empty() to be replaced by an appropriate implementation of Default. I.e.: use std::fmt::Debug; pub struct Heap<T, D> { data: Option<Vec<(T, Option<Box<D>>)>>, } impl<T, D> Heap<T, D> where T: Clone + PartialOrd + Debug, D: Clone + Debug, { pub fn new(value: T, data: Option<Box<D>>) -> Self { Self { data: Some(vec![(value, data)]), } } pub fn is_empty(&self) -> bool { self.data.is_none() } // ... pub fn insert( &mut self, value: T, data: Option<Box<D>>, max: bool, ) -> Result<(), &'static str> { if self.is_empty() { self.data.as_mut().unwrap().push((value, data)); return Ok(()); } self.data.as_mut().unwrap().push((value, data)); let mut current_index = self.get_size()? - 1; let mut parent = self.get_parent(current_index)?;
{ "domain": "codereview.stackexchange", "id": 45111, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, heap", "url": null }
rust, heap if max { while parent.1 < value { self.swap(current_index, parent.0)?; current_index = parent.0; if current_index != 0 { parent = self.get_parent(current_index)?; } else { break; } } } else { while parent.1 > value { self.swap(current_index, parent.0)?; current_index = parent.0; if current_index != 0 { parent = self.get_parent(current_index)?; } else { break; } } } Ok(()) } } impl<T, D> Default for Heap<T, D> { fn default() -> Self { Self { data: None } } }
{ "domain": "codereview.stackexchange", "id": 45111, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, heap", "url": null }
python, beginner, time Title: Time Format Conversion Utility Question: The code defines a Python script for converting time between 12-hour and 24-hour formats. Review Goals: Is the code idiomatic? (Am I using any outdated practices or functions?) Is there a simpler way to achieve the same thing? Are the tests well thought of? Does any part of my code require a comment? How can I improve the code? The code was formatted with autopep8. #!/usr/bin/env python3 def _convert_to_24_hr(hr: int, mins: int, time_ind: str) -> str: if time_ind.upper() == 'PM': hr = hr + 12 if hr != 12 else 0 return f'{hr}:{mins:0>2} {time_ind.upper()}' def _convert_to_12_hr(hr: int, mins: int) -> str: time_ind = 'PM' if hr >= 12 else 'AM' hr = 12 if hr == 0 else (hr - 12 if hr > 12 else hr) return f'{hr}:{mins:0>2} {time_ind.upper()}' def time_conversion(hr: int, mins: int, fmt: str, time_ind: str = None) -> str: """Converts a time from one format to another (either 12-hour or 24-hour). Args: hr: The hour part of the time. mins: The minute part of the time. format: A string representing the desired time format ('12-hour' or '24-hour'). time_ind: An optional time indicator ('AM' or 'PM') used in 12-hour format conversion. Returns: The converted time as a string in the specified format on success. Else, it returns 'Invalid arguments.'. Note: - If '24-hour' format is selected, the time_ind argument must be provided. - The function handles both upper and lower case format and time indicator strings. """ conditions_24 = [1 <= hr <= 12, 0 <= mins <= 59, time_ind and time_ind.upper() in ['AM', 'PM']] conditions_12 = [0 <= hr <= 23, 0 <= mins <= 59]
{ "domain": "codereview.stackexchange", "id": 45112, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, time", "url": null }
python, beginner, time conditions_12 = [0 <= hr <= 23, 0 <= mins <= 59] if fmt.lower() == '24-hour': if all(conditions_24): # Valid 12-hour format return _convert_to_24_hr(hr, mins, time_ind) return 'Invalid arguments.' if fmt.lower() == '12-hour': if all(conditions_12): # Valid 12-hr format return _convert_to_12_hr(hr, mins) return 'Invalid arguments.' def _test(got: str, expected: str) -> None: if got == expected: prefix = ' OK ' else: prefix = ' X ' print(f'{prefix.ljust(4)} | got: {got.ljust(20)} | ' f'expected: {expected.ljust(20)}') def _main(): _test(time_conversion(15, 30, '12-hour'), '3:30 PM') _test(time_conversion(3, 30, '24-hour', 'PM'), '15:30 PM') _test(time_conversion(13, 30, '24-hour', 'AM'), 'Invalid arguments.') _test(time_conversion(25, 20, '12-hour'), 'Invalid arguments.') _test(time_conversion(13, 5, '12-hour'), '1:05 PM') _test(time_conversion(13, 5, '24-hour'), 'Invalid arguments.') _test(time_conversion(10, 5, '24-hour', 'am'), '10:05 AM') _test(time_conversion(10, 5, '24-hour', 'PM'), '22:05 PM') _test(time_conversion(17, 5, '12-hour'), '5:05 PM') _test(time_conversion(25, 32, '12-hour'), 'Invalid arguments.') _test(time_conversion(0, 23, '12-hour'), '12:23 AM') _test(time_conversion(12, 0, '12-hour'), '12:00 PM') _test(time_conversion(-4, -3, '13-hour'), 'Invalid arguments.') _test(time_conversion(1003, 29, '39 hour', None), 'Invalid arguments.') if __name__ == '__main__': _main() P.S: I would like to mention that this is my first Python script, or at least the first one I am posting for review. Feel free to expatiate. Answer: #!/usr/bin/env python3 Nice shebang! Very portable. Should comments be added? No, everything was quite clear. plural agreement def _convert_to_24_hr(hr: int, mins: int, time_ind: str) -> str:
{ "domain": "codereview.stackexchange", "id": 45112, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, time", "url": null }
python, beginner, time plural agreement def _convert_to_24_hr(hr: int, mins: int, time_ind: str) -> str: Thank you for the hinting. I suppose you wanted to avoid the identifier min, fair enough. But being out of step with singular "hour" is distracting. Consider using {hrs, mins}, or mn, or min_, or perhaps {hh, mm}. mod math The hr + 12 if hr != 12 else 0 expression is nice enough, but it kind of screams "modulo 24" to me. Which then would admit of hr += ... And down in _convert_to_12_hr things only get worse. Single-digit formatting with f'{hr}: seems odd for 24-hour time. I would expect to see leading zeros, e.g. "00:00" for midnight. enum Thank you for the very nice docstring in time_conversion, I found it helpful. For one or both of the last two args, consider demanding that an Enum be passed in. Then we wouldn't need .lower() translations. exceptions The docs explain: "Else, it returns 'Invalid arguments.'". Consider a raise of ValueError instead. This would affect your non-standard unit tests, I feel in a good way, as you could then code some of them using a with self.assertRaises context handler. Prefer to write a test suite in the usual way. Or use pytest if you'd rather. representation Dealing with midnight / zero-hour is a rough edge in this codebase. Consider turning hours and minutes immediately into a datetime and then rely on .strftime() for output. Doing that would also enable expressions like adding a 12-hour timedelta, but at that point you'd no longer have a need for adding twelve hours. EDIT Thank you @Reinderien, quite right, I intended a time object. I'm afraid my code seldom talks about HH:MM outside the context of "some particular instant" that happened N seconds after 1970. comments lie! if all(conditions_24): # Valid 12-hour format Looks like a copy-pasta error. This codebase achieves its design goals. I would be willing to delegate or accept maintenance tasks on it.
{ "domain": "codereview.stackexchange", "id": 45112, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, time", "url": null }
python Title: Python script to answer Rosalind test 2 (sum of two squares) Question: The test: https://rosalind.info/problems/ini2/ Problem Given: Two positive integers a and b, each less than 1000. Return: The integer corresponding to the square of the hypotenuse of the right triangle whose legs have lengths a and b. Sample Dataset 3 5 Sample Output 34 My script: #!/bin/env python3 import argparse import os.path import sys def int_sq(n): return int(n)**2 def square_hyp_triangle(a,b): #check int sq_sum=sum(int_sq(i) for i in [a,b]) return sq_sum def main(argv=None): parser = argparse.ArgumentParser( prog="intro", description='Import a file with integers') parser.add_argument('filename', type=argparse.FileType('r'), nargs='?', help='an existing filename') args = parser.parse_args(argv) if not args.filename: sys.exit("Please provide an input file, or pipe it via stdin") for line in args.filename: line = line.rstrip().split() res = square_hyp_triangle(line[0],line[1]) #print(line[0], line[1]) print(res) #print(res) if __name__ == '__main__': main() If you saved the above script named intro.py You can run it : echo "3 5" | ./intro.py - Which parts can be improved? Answer: Imports are sorted -- nice! optional type hinting def int_sq(n): Consider using this signature: def int_sq(n: float) -> int: (Recall that float includes int for hinting purposes.) sum, map sq_sum = sum(int_sq(i) for i in [a, b]) Consider phrasing this as sq_sum = sum(map(int_sq, [a, b])) since the temp var i is uninteresting and could be anonymous. Also, delete the meaningless "#check int" comment. And maybe just return the expression without giving it a name.
{ "domain": "codereview.stackexchange", "id": 45113, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python docstring The identifier square_hyp_triangle is fine. But do write an English sentence for it: def square_hyp_triangle(a: float, b: float) -> float: """Finds the squared length of a triangle's hypotenuse. """ Consider writing another few lines so that $ python -m doctest *.py does an automated test to verify things work as intended. """Finds the squared length of a triangle's hypotenuse. >>> square_hyp_triangle(3, 5) 34 """ typer In main the parser is nice enough, though "import" perhaps is a slightly odd verb. I'm glad you're using that library; it reduces the documentation burden for end users. Consider switching to typer, which gives you similar functionality "for free" (if you're using type hints). I'm slightly surprised by the absence of ... , default=sys.stdin), but I guess your defaulting must work fine. The filename identifier seems to have the wrong name, given that you want it be an open file descriptor rather than a name. In line.rstrip().split() maybe you had some CR/LF trouble? I don't see why you need to strip, given that split will discard whitespace for you. tuple unpack Avoid cryptic [0] / [1] subscripts, preferring a, b = line.split(). Or better, convert from str right here using: a, b = map(float, line.split())
{ "domain": "codereview.stackexchange", "id": 45113, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python Aha, now I understand that return int(n)**2 expression. That doesn't seem a very sensible place to do the conversion. I wouldn't really expect that a function could square "3". And even if it did, should I get back "9" instead of 9? Best to not even explore such territory, and stick to numeric values, so the squaring function has a single responsibility and is not also responsible for type conversions. Better to allocate that responsibility to the CLI interface called main. Rejecting fractional inputs like 3.1 is maybe an unusual design choice. Guess it stems from the "Given:" and "Return:" parts of the spec, OK. Rosalind's "download a one-line text file dataset" requirement pushes this code in a slightly odd direction. old debugs #print(line[0], line[1]) It served a purpose at one time. But now that your code is "done" and you're requesting review, it is the right time to tidy up and delete debug statements. Which parts can be improved? Adhere to Single Responsibility. Recommend you adopt black auto-formatting, so expressions have a uniform appearance without even having to think about it.
{ "domain": "codereview.stackexchange", "id": 45113, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
javascript, vue.js Title: v-for loop generating list items that will get rearranged based on an associated value (ranking system) Question: A counter gets incremented by a custom value. Each increment value gets stored with its refcount that tracks how many times it occurred. An ordered list shows all increment values entered so far by number of occurrences. Higher rank means more occurrence. Before venturing futher, a disclaimer: I can't make prettier work on my VS Code, so I resort to formatting (often poorly) the code myself. #No longer the case The reason behind the variable names is that I need long (to the point of excess) names so I can reason about my code and I find udnerscores soothing for some reason. That being said: I will welcome every remark, reproach, fist shaking with the same amount (a lot) of gratitude that I will welcome criticism (of any kind) and advice. The code: Two components: Parent: CounterInDis.vue and child: CounterDisplay.vue. CounterInDis.vue: <script> import CounterDisplay from './CounterDisplay.vue'; let count = 0; let increment = 0; let last_value = 0; let values_occurrence = {}; let sorted_values = []; export default { components: { CounterDisplay }, data() { return { count: count, last_value: last_value, increment: increment, values_occurrence: values_occurrence, sorted_values: sorted_values, } }, methods: { increment_count() { let checked = this.is_increment_a_number(this.increment) if (checked == 0) { return } this.last_value = checked; this.count += checked; this.update_values_occurrence(checked); this.sort_by_occurrence(); }, is_increment_a_number(amount) { if (typeof amount != 'number') { amount = 0; }; return amount; },
{ "domain": "codereview.stackexchange", "id": 45114, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, vue.js", "url": null }
javascript, vue.js update_values_occurrence(amount) { if (!values_occurrence[amount]) { values_occurrence[amount] = 0; } values_occurrence[amount] += 1 }, sort_by_occurrence() { const keys_n_values = Object.entries(this.values_occurrence); keys_n_values.sort((a, b) => b[1] - a[1]); sorted_values = keys_n_values.map((entry) => entry[0]); }, }, computed: { to_the_doms_with_you() { return { current_count: this.count, last_value: this.last_value, current_increment: this.increment, values_occurrence: this.values_occurrence, sorted_values: sorted_values, //this.sorted_values won't make the list display, idk why } }, }, } </script> <template> <div> <h3>Counter</h3> <h4>Welcome to the new and improved counter!</h4> <CounterDisplay :counter_display_values="to_the_doms_with_you" /> <button v-on:click="increment_count">Increment dat count</button> <div> <label for="increment">Increment by</label> <input type="number" v-model="increment"> </div> </div> </template> CounterDisplay.vue. <script> export default { props: { counter_display_values: { type: Object, required: true, }, } } </script> <template> <p>The Counter is at {{ counter_display_values.current_count }}.</p> <p v-if="counter_display_values.last_value == 0">Click the button and start counting.</p> <p v-else>Last increment's value: {{ counter_display_values.last_value }}</p> <div class="fixed_width"> <p class="half">To each value, its number of occurrences: <pre>{{ counter_display_values.values_occurrence }}</pre> </p>
{ "domain": "codereview.stackexchange", "id": 45114, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, vue.js", "url": null }