text stringlengths 1 2.12k | source dict |
|---|---|
c++, design-patterns, graph
template <bool Directed, typename ContainerTraitTag> struct GraphTraits {
template <Descriptor VertexType>
using Impl = GraphTraitsImpl<VertexType, Directed, ContainerTraitTag>;
};
template <typename ContainerTraitTag>
using DiGraphTraits = GraphTraits<true, ContainerTraitTag>;
template <Descriptor VertexType, typename... BaseProperties>
struct GraphProperties : public BaseProperties::template Impl<VertexType>... {
using BaseProperties::template Impl<VertexType>::operator()...;
};
template <Arithmetic WeightType, typename EdgeType> struct EdgeWeightImpl {
WeightType &operator()(EdgeWeightTag, const EdgeType &edge) {
return weights_[edge];
}
const WeightType &operator()(EdgeWeightTag, const EdgeType &edge) const {
return weights_.at(edge);
}
std::map<EdgeType, WeightType> weights_;
};
template <Arithmetic WeightType> struct EdgeWeightProperty {
template <Descriptor VertexType>
using Impl = EdgeWeightImpl<WeightType, std::pair<VertexType, VertexType>>;
};
template <Arithmetic DistanceType, Descriptor VertexType>
struct VertexDistanceImpl {
DistanceType &operator()(VertexDistanceTag, const VertexType &vertex) {
return distances_[vertex];
}
const DistanceType &operator()(VertexDistanceTag,
const VertexType &vertex) const {
return distances_.at(vertex);
}
std::unordered_map<VertexType, DistanceType> distances_;
};
template <Arithmetic DistanceType> struct VertexDistanceProperty {
template <Descriptor VertexType>
using Impl = VertexDistanceImpl<DistanceType, VertexType>;
};
template <Arithmetic DistType> struct DijkstraProperties {
template <Descriptor VertexType>
using Impl = GraphProperties<VertexType, VertexDistanceProperty<DistType>,
EdgeWeightProperty<DistType>>;
};
} // namespace frozenca
Test code(Dijkstra's algorithm):
#include <graph.h>
#include <iostream>
#include <limits>
#include <vector>
#include <queue>
namespace fc = frozenca; | {
"domain": "codereview.stackexchange",
"id": 43663,
"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++, design-patterns, graph",
"url": null
} |
c++, design-patterns, graph
namespace fc = frozenca;
using DijkstraGraph = fc::Graph<int, fc::DiGraphTraits<fc::AdjListTraitTag>, fc::DijkstraProperties<float>>;
std::pair<float, int> dijkstra(DijkstraGraph &g, int src) {
auto min_dist_comp = [&g](int v1, int v2) {
return g(fc::v_dist, v1) > g(fc::v_dist, v2);
};
constexpr auto INF = std::numeric_limits<float>::max();
std::priority_queue<int, std::vector<int>, decltype(min_dist_comp)> q(min_dist_comp);
for (auto vertex : g.vertices()) {
g(fc::v_dist, vertex) = INF;
}
int min_dst = -1;
float min_dist = INF;
g(fc::v_dist, src) = 0;
q.push(src);
while (!q.empty()) {
auto u = q.top();
q.pop();
for (auto [_, v] : g.adj(u)) {
auto alt = g(fc::v_dist, u) + g(fc::e_w, {u, v});
if (alt < g(fc::v_dist, v) && g(fc::v_dist, u) != INF) {
g(fc::v_dist, v) = alt;
min_dst = v;
min_dist = std::min(min_dist, alt);
}
}
}
return {min_dist, min_dst};
}
int main() {
DijkstraGraph g;
g.add_edge(0, 2);
g.add_edge(1, 3);
g.add_edge(1, 4);
g.add_edge(2, 1);
g.add_edge(2, 3);
g.add_edge(3, 4);
g.add_edge(4, 0);
g.add_edge(4, 1);
g(fc::e_w, {0, 2}) = 1;
g(fc::e_w, {1, 3}) = 1;
g(fc::e_w, {1, 4}) = 2;
g(fc::e_w, {2, 1}) = 7;
g(fc::e_w, {2, 3}) = 3;
g(fc::e_w, {3, 4}) = 1;
g(fc::e_w, {4, 0}) = 1;
g(fc::e_w, {4, 1}) = 1;
auto [dist, dst] = dijkstra(g, 0);
std::cout << "Shortest distance: " << dist << " with destination " << dst << '\n';
}
Output
Shortest distance: 1 with destination 2
I'm not sure I can handle this TMP monstrosity...
Answer: Miscellaneous issues
You can use [] instead of .at() in the non-const adj().
#include <vector> is not necessary.
#include <graph.h> is dangerous, use "graph.h" instead, otherwise you risk a graph.h that's in the system header search path from being found before your local header file. | {
"domain": "codereview.stackexchange",
"id": 43663,
"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++, design-patterns, graph",
"url": null
} |
c++, design-patterns, graph
Store adjacency lists directly in out_edges_
I don't see why you have a std::list storing adjacency lists, and a std::unordered_map that maps vertices to iterators into that std::list. Why not store the adjacency lists directly in the std::unordered_map? This simplifies the code.
Use of std::list
A std::list has the problem that looking up things is slow. Consider has_edge(), which has \$O(V)\$ complexity because it has to do a linear search.
Use of std::map
Nothing in EdgeWeightImpl depends on weights_ being sorted. So ideally, you would use a std::unordered_map instead. Of course, the issue is that there is no overload for std::hash for EdgeType. However, you could make one yourself, or pass a custom hash function to the constructor of weights_ if you make it a std::unordered_map.
Make things private where appropriate
If you add accessor functions to a struct or class to access its member variables, I expect those member variables to be private. Even if some of your structs are only used internally, it is good practice to use public/protected/private to reduce bugs in your own code.
Missing typename?
C++20 is supposed to reduce the need for writing typename. I am not a language lawyer, so I won't comment on whether your code is techinally correct, however Clang seems to think typename is missing in some of your using declarations. So from a practical standpoint, add typename whenever there is a dependent type to avoid compiler issues.
Naming things
There are a few things I would do differently regarding naming. First, adding Type to template parameter names seems unnecessary; you already make them start with a capital so they are easily distinguished from the (member) variables. I think it just adds noise.
Properties vs traits: these words mean very similar things. Without reading the code, I wouldn't know where to put what if I had to create a custom trait and a custom property class. | {
"domain": "codereview.stackexchange",
"id": 43663,
"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++, design-patterns, graph",
"url": null
} |
c++, design-patterns, graph
DijkstraProperties is misnamed and hints at possible issues. First, there might be other algorithms that work on a graph that has edge weights and vertex distances. You might also want to run multiple algorithms on a given graph. Naming a graph type after one of the possible algorithms you could use on it doesn't seem like a good idea. Furthermore, storing information in a graph that is only used while a given algorithm runs on it wastes memory when you are not running that algorithm, and also prevents you from running that algorithm on a const graph. Of course, if you run Dijkstra's a lot and it's the fastest way to do it, it is fine, but I wouldn't expect this from such a generic graph library.
Usability | {
"domain": "codereview.stackexchange",
"id": 43663,
"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++, design-patterns, graph",
"url": null
} |
c++, design-patterns, graph
I'm not sure I can handle this TMP monstrosity...
It's just lots of templates, I don't see any real metaprogramming here. But yes, it's a bit of a monstrosity. And while the end-user doesn't have to look at the implementation, they still have to write things like this:
using DijkstraGraph = fc::Graph<int, fc::DiGraphTraits<fc::AdjListTraitTag>, fc::DijkstraProperties<float>>;
Which doesn't look particularly appealing. Again, I don't think it's clear what the distinction between the Trait and Property is, so I'd much rather see Graph having just one template parameter that contains all the information necessary. That type will then be more complicated of course, but with some real template meta-programming you can have it deduce many of the traits and properties instead of having to explicitly specify them. | {
"domain": "codereview.stackexchange",
"id": 43663,
"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++, design-patterns, graph",
"url": null
} |
algorithm, c, bloom-filter
Title: Bloom Filter C implementation
Question: this is my first C program. It creates a bloom filter from an array of N char arrays and k hash functions.
I'm not particularly concerned about maximum performance at this point, as I'm just starting with C. Any suggestions on making my code more idiomatic would be highly appreciated.
// Bloomfilter.c
#include <stdio.h>
// Function headers
int modularHash(char string[], int R, int M);
int sh1(char string[]);
int sh2(char string[]);
int sh3(char string[]);
int main()
{
enum
{
N = 3, // the number of strings
M = 10, // the size of the bloom filter
k = 3, // the number of hash functions
};
char *strings[N] = {"abc", "777", "xyz"};
int bloom_filter[M] = {0}; // array of `n` 0s.
// array of pointers to hash functions.
int (*hashers[k])() = {sh1, sh2, sh3};
// Fill the bloom filter
for (int j = 0; j < N; j++)
for (int i = 0; i < k; i++)
{
{
// Compute the hash of string j using the k'th hash function
// Map the hash to a position in the bloom filter
// then add this position to the bloom filter.
int result = hashers[i](strings[j]);
int position = result % M;
bloom_filter[position] = 1;
}
}
// Print the bloom filter
for (int i = 0; i < M; i++)
printf("%d ", bloom_filter[i]);
// TODO implement a function for checking a string against the bloom filter.
return 0;
}
/*
Compute the modular hash of a char array
@param string, array of characters to hash
@param R: a seed value, should be a prime
@param M: a seed value, should also be a prime
*/
int modularHash(char string[], int R, int M)
{
int chars = 3; // the number of characters
int hash = 0;
char s;
int n; | {
"domain": "codereview.stackexchange",
"id": 43664,
"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": "algorithm, c, bloom-filter",
"url": null
} |
algorithm, c, bloom-filter
char s;
int n;
for (int i = 0; i < chars - 1; i++)
s = string[i];
n = (int)s;
hash = (R * hash + n) % M;
return hash;
}
int sh1(char string[])
{
int M = 3;
int R = 31;
return modularHash(string, M, R);
}
int sh2(char string[])
{
int M = 47;
int R = 17;
return modularHash(string, M, R);
}
int sh3(char string[])
{
int M = 97;
int R = 29;
return modularHash(string, M, R);
}
```
Answer: Questionable code
Why assign s multiple times?
for (int i = 0; i < chars - 1; i++)
s = string[i];
Above is same as
s = string[chars - 1 - 1];
Instead of one % operation after the loop (R * hash + n) % M, I'd expect that in the loop.
% is not mod
modularHash() returns values in the (-M ... M) range, not [0 ... M) as char may be signed.
Consider the UB caused when result < 0.
int result = hashers[i](strings[j]);
int position = result % M;
bloom_filter[position] = 1; // UB
Instead, use unsigned math.
unsigned modularHash(char string[], unsigned R, unsigned M) {
unsigned char *ustring = (unsigned char *) string;
...
unsigned hash = 0;
...
s = ustring[i];
Avoid signed overflow
R * hash + n, with int math, may overflow with large R leading to undefined behavior (UB). Does not apply with this code given the modest constants.
Use const
In functions that do not alter referenced data, use const. This allows for wider function application, self-documents code's usage and allows select optimization not allows otherwise seen by a compiler.
// int modularHash(char string[], int R, int M)
int modularHash(const char string[], int R, int M)
Avoid hard coded limits
Rather than 3 (an undescribed magic number), consider iterating to end of the string.
unsigned modularHash(const char string[], unsigned char R, unsigned char M) {
const unsigned char *ustring = (const unsigned char *) string;
unsigned hash = 0;
while (*ustring) {
hash = (R*hash + *ustring) % M;
}
return hash;
} | {
"domain": "codereview.stackexchange",
"id": 43664,
"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": "algorithm, c, bloom-filter",
"url": null
} |
algorithm, c, bloom-filter
while (*ustring) {
hash = (R*hash + *ustring) % M;
}
return hash;
}
If looking to limit up to 3, use more descriptive names and consider a string may be shorter than 3.
int limit = 3;
for (int i = 0; i < limit && *ustring; i++) {
hash = (R*hash + *ustring) % M;
}
Avoid defining twice
Below defines the number of strings twice, once with 3 and once with initializers.
N = 3, // the number of strings
char *strings[N] = {"abc", "777", "xyz"};
Consider below, where the string size is only defined by the number of initializers.
char *strings[] = {"abc", "777", "xyz"};
size_t N = sizeof strings / sizeof strings[0];
Likewise for hashers[].
Unclear code
Why -1 in for (int i = 0; i < chars - 1; i++)? | {
"domain": "codereview.stackexchange",
"id": 43664,
"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": "algorithm, c, bloom-filter",
"url": null
} |
javascript, array, functional-programming
Title: Simplify a function which performs manipulation of data in Javascript
Question: Upon suggestion in the original question within Stack Overflow, I'm bringing my question here.
We have created a function that will convert the data into the desired format, but it has a lot of code and is difficult to understand. If a new person has seen this code means, it's very hard for them to know the functionalities.
below is the code for it | {
"domain": "codereview.stackexchange",
"id": 43665,
"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, array, functional-programming",
"url": null
} |
javascript, array, functional-programming
const data = [{"id":"Client 1","advisorName":"Dhanush","managerName":"Nikolai","clientName":"Thor Odin","goalName":"","goalAmount":"","goals":2,"score":0.855,"lastModified":"22/1/2022","equityFixedIncome":"","subRows":[{"id":"goal-1","clientName":"","managerName":"","advisorName":"","goalName":"Retirement1","goalAmount":10000,"goals":1,"equityFixedIncome":"60/40","lastModified":"22/1/2022","score":0.99},{"id":"goal-2","clientName":"","managerName":"","advisorName":"","goalName":"Save For Child Education","goalAmount":70000,"goals":1,"equityFixedIncome":"55/45","lastModified":"5/12/2023","score":0.72}]},{"id":"Client 2","advisorName":"Dhanush","managerName":"Nikolai","clientName":"Steve Rogers","goalName":"Save for Investment","goalAmount":67000,"goals":1,"score":0.7,"lastModified":"22/1/2022","equityFixedIncome":"60/40"},{"id":"Client 3","advisorName":"Dhanush","managerName":"Nikolai","clientName":"Wanda Vision","goals":0,"score":0.9,"lastModified":"","equityFixedIncome":""},{"id":"Client 4","advisorName":"Dhanush","managerName":"Nikolai","clientName":"Tony Stark","goalName":"","goalAmount":"","goals":2,"score":0.29,"lastModified":"27/10/2019","equityFixedIncome":"","subRows":[{"id":"goal-4","clientName":"","managerName":"","advisorName":"","goalName":"Education Loan","goalAmount":500,"goals":1,"equityFixedIncome":"60/40","lastModified":"27/10/2019","score":0.29},{"id":"goal-5","clientName":"","managerName":"","advisorName":"","goalName":"House Loan","goalAmount":23000,"goals":1,"equityFixedIncome":"30/70","lastModified":"16/6/2022","score":0.29}]},{"id":"Client 5","advisorName":"Joe","managerName":"Nikolai","clientName":"Hack Eye","goalName":"Save For World Tour","goalAmount":400000,"goals":1,"score":0.74,"lastModified":"","equityFixedIncome":"60/40"},{"id":"Client 6","advisorName":"Joe","managerName":"Nikolai","clientName":"Nick | {
"domain": "codereview.stackexchange",
"id": 43665,
"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, array, functional-programming",
"url": null
} |
javascript, array, functional-programming
6","advisorName":"Joe","managerName":"Nikolai","clientName":"Nick Fury","goalName":"","goalAmount":"","goals":2,"score":0.44499999999999995,"lastModified":"9/3/2022","equityFixedIncome":"","subRows":[{"id":"goal-7","clientName":"","managerName":"","advisorName":"","goalName":"To Build A Workspace","goalAmount":42340,"goals":1,"equityFixedIncome":"60/40","lastModified":"9/3/2022","score":0.6},{"id":"goal-8","clientName":"","managerName":"","advisorName":"","goalName":"Cloud Examination","goalAmount":8730,"goals":1,"equityFixedIncome":"30/70","lastModified":"9/11/2021","score":0.29}]},{"id":"Client 7","advisorName":"Joe","managerName":"Nikolai","clientName":"Star Lord","goalName":"Save For Child Education","goalAmount":400000,"goals":1,"score":0.93,"lastModified":"","equityFixedIncome":"55/45"},{"id":"Client 8","advisorName":"Pal","managerName":"Rohan","clientName":"Thanos","goalName":"","goalAmount":"","goals":3,"score":0.29,"lastModified":"2/11/2019","equityFixedIncome":"","subRows":[{"id":"goal-10","clientName":"","managerName":"","advisorName":"","goalName":"Relocation Expense Goal","goalAmount":400000,"goals":1,"equityFixedIncome":"22/78","lastModified":"2/11/2019","score":0.29},{"id":"goal-11","clientName":"","managerName":"","advisorName":"","goalName":"Save for to buy bike","goalAmount":400000,"goals":1,"equityFixedIncome":"50/50","lastModified":"1/1/2020","score":0.29},{"id":"goal-12","clientName":"","managerName":"","advisorName":"","goalName":"Save For Education","goalAmount":400000,"goals":1,"equityFixedIncome":"65/35","lastModified":"9/5/2022","score":0.29}]},{"id":"Client 9","advisorName":"Pal","managerName":"Rohan","clientName":"Ego","goalName":"Save For Education","goalAmount":400000,"goals":1,"score":0.72,"lastModified":"","equityFixedIncome":"65/35"},{"id":"Client 10","advisorName":"Pal","managerName":"Rohan","clientName":"Bruce | {
"domain": "codereview.stackexchange",
"id": 43665,
"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, array, functional-programming",
"url": null
} |
javascript, array, functional-programming
10","advisorName":"Pal","managerName":"Rohan","clientName":"Bruce Banner","goalName":"","goalAmount":"","goals":2,"score":0.975,"lastModified":"9/10/2018","equityFixedIncome":"","subRows":[{"id":"goal-14","clientName":"","managerName":"","advisorName":"","goalName":"Car Loan","goalAmount":23000,"goals":1,"equityFixedIncome":"60/40","lastModified":"9/10/2018","score":0.99},{"id":"goal-15","clientName":"","managerName":"","advisorName":"","goalName":"Bike Loan","goalAmount":4600,"goals":1,"equityFixedIncome":"30/70","lastModified":"9/11/2021","score":0.96}]}] | {
"domain": "codereview.stackexchange",
"id": 43665,
"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, array, functional-programming",
"url": null
} |
javascript, array, functional-programming
function firstLevelRestructure(data){
return data.reduce(
(acc, row) => {
if (row.advisorName !== acc.level1.clientName) {
let newRow1 = {
advisorName: row.advisorName,
managerName: row.managerName,
id: "",
clientName: "",
goalName: "",
goalAmount: "",
goals: "",
score: "",
lastModified: "",
equityFixedIncome: "",
subRows: [],
};
acc.result.push(newRow1);
acc.level1.clientName = row.advisorName;
acc.level1.arr = newRow1.subRows;
}
let newRow2 = {
advisorName: "",
managerName: "",
id: row.id,
clientName: row.clientName,
goalName: row.goalName,
goalAmount: row.goalAmount,
goals: row.goals,
score: row.score,
lastModified: row.lastModified,
equityFixedIncome: row.equityFixedIncome,
};
if(row.subRows) {
acc.level2.arr = newRow2.subRows = [];
}
acc.level1.arr.push(newRow2);
if (row.subRows) {
row.subRows.forEach((subRow) => {
acc.level2.arr.push({ ...subRow });
});
}
return acc;
},
{
result: [],
level1: { clientName: "", arr: null },
level2: { arr: null },
}
).result;
}
const restructure = (data, keyName) => {
let val = firstLevelRestructure(data)
const emptyNode = {
managerName: "",
advisorName: "",
id: "",
clientName: "",
goalName: "",
goalAmount: "",
goals: "",
score: "",
lastModified: "",
equityFixedIncome: "",
subRows: [],
};
const groups = val.reduce((acc, item) => {
acc[item[keyName]] ??= [];
acc[item[keyName]].push({ ...item, [keyName]: "" });
return acc;
}, {});
return Object.entries(groups)
.map(([keyValue, subRows]) => (
{ ...emptyNode, [keyName]: keyValue , subRows }
));
}; | {
"domain": "codereview.stackexchange",
"id": 43665,
"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, array, functional-programming",
"url": null
} |
javascript, array, functional-programming
console.log(JSON.stringify(restructure(data, 'managerName')));
And why am doing this conversion because, we are creating a multi level nested row expansion table which requires this kind of structure. You can get the working demo link here - https://codesandbox.io/s/tanstack-table-expansion-1t77ks?file=/src/styles.css
And the structured data will be used to create the table with the expansion like in the above image.
Here u can see the formatted data - https://codesandbox.io/s/tanstack-table-expansion-1t77ks?file=/src/data/table-data.json
Instead of calling the function firstLevelRestructure Is there a way to use the function restructure to handle it?
I am in need of your help to solve this. Please let me know the feasibility of that.
Answer: I think you should work on the spirit of information synthesis, it should help you get a simpler way of coding | {
"domain": "codereview.stackexchange",
"id": 43665,
"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, array, functional-programming",
"url": null
} |
javascript, array, functional-programming
const data = [{id:'Client 1',advisorName:'Dhanush',managerName:'Nikolai',clientName:'Thor Odin',goalName:'',goalAmount:'',goals:2,score:0.855,lastModified:'22/1/2022',equityFixedIncome:'',subRows:[{id:'goal-1',clientName:'',managerName:'',advisorName:'',goalName:'Retirement1',goalAmount:10000,goals:1,equityFixedIncome:'60/40',lastModified:'22/1/2022',score:0.99},{id:'goal-2',clientName:'',managerName:'',advisorName:'',goalName:'Save For Child Education',goalAmount:70000,goals:1,equityFixedIncome:'55/45',lastModified:'5/12/2023',score:0.72}]},{id:'Client 2',advisorName:'Dhanush',managerName:'Nikolai',clientName:'Steve Rogers',goalName:'Save for Investment',goalAmount:67000,goals:1,score:0.7,lastModified:'22/1/2022',equityFixedIncome:'60/40'},{id:'Client 3',advisorName:'Dhanush',managerName:'Nikolai',clientName:'Wanda Vision',goals:0,score:0.9,lastModified:'',equityFixedIncome:''},{id:'Client 4',advisorName:'Dhanush',managerName:'Nikolai',clientName:'Tony Stark',goalName:'',goalAmount:'',goals:2,score:0.29,lastModified:'27/10/2019',equityFixedIncome:'',subRows:[{id:'goal-4',clientName:'',managerName:'',advisorName:'',goalName:'Education Loan',goalAmount:500,goals:1,equityFixedIncome:'60/40',lastModified:'27/10/2019',score:0.29},{id:'goal-5',clientName:'',managerName:'',advisorName:'',goalName:'House Loan',goalAmount:23000,goals:1,equityFixedIncome:'30/70',lastModified:'16/6/2022',score:0.29}]},{id:'Client 5',advisorName:'Joe',managerName:'Nikolai',clientName:'Hack Eye',goalName:'Save For World Tour',goalAmount:400000,goals:1,score:0.74,lastModified:'',equityFixedIncome:'60/40'},{id:'Client 6',advisorName:'Joe',managerName:'Nikolai',clientName:'Nick Fury',goalName:'',goalAmount:'',goals:2,score:0.44499999999999995,lastModified:'9/3/2022',equityFixedIncome:'',subRows:[{id:'goal-7',clientName:'',managerName:'',advisorName:'',goalName:'To Build A | {
"domain": "codereview.stackexchange",
"id": 43665,
"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, array, functional-programming",
"url": null
} |
javascript, array, functional-programming
Build A Workspace',goalAmount:42340,goals:1,equityFixedIncome:'60/40',lastModified:'9/3/2022',score:0.6},{id:'goal-8',clientName:'',managerName:'',advisorName:'',goalName:'Cloud Examination',goalAmount:8730,goals:1,equityFixedIncome:'30/70',lastModified:'9/11/2021',score:0.29}]},{id:'Client 7',advisorName:'Joe',managerName:'Nikolai',clientName:'Star Lord',goalName:'Save For Child Education',goalAmount:400000,goals:1,score:0.93,lastModified:'',equityFixedIncome:'55/45'},{id:'Client 8',advisorName:'Pal',managerName:'Rohan',clientName:'Thanos',goalName:'',goalAmount:'',goals:3,score:0.29,lastModified:'2/11/2019',equityFixedIncome:'',subRows:[{id:'goal-10',clientName:'',managerName:'',advisorName:'',goalName:'Relocation Expense Goal',goalAmount:400000,goals:1,equityFixedIncome:'22/78',lastModified:'2/11/2019',score:0.29},{id:'goal-11',clientName:'',managerName:'',advisorName:'',goalName:'Save for to buy bike',goalAmount:400000,goals:1,equityFixedIncome:'50/50',lastModified:'1/1/2020',score:0.29},{id:'goal-12',clientName:'',managerName:'',advisorName:'',goalName:'Save For Education',goalAmount:400000,goals:1,equityFixedIncome:'65/35',lastModified:'9/5/2022',score:0.29}]},{id:'Client 9',advisorName:'Pal',managerName:'Rohan',clientName:'Ego',goalName:'Save For Education',goalAmount:400000,goals:1,score:0.72,lastModified:'',equityFixedIncome:'65/35'},{id:'Client 10',advisorName:'Pal',managerName:'Rohan',clientName:'Bruce Banner',goalName:'',goalAmount:'',goals:2,score:0.975,lastModified:'9/10/2018',equityFixedIncome:'',subRows:[{id:'goal-14',clientName:'',managerName:'',advisorName:'',goalName:'Car Loan',goalAmount:23000,goals:1,equityFixedIncome:'60/40',lastModified:'9/10/2018',score:0.99},{id:'goal-15',clientName:'',managerName:'',advisorName:'',goalName:'Bike Loan',goalAmount:4600,goals:1,equityFixedIncome:'30/70',lastModified:'9/11/2021',score:0.96}]}] | {
"domain": "codereview.stackexchange",
"id": 43665,
"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, array, functional-programming",
"url": null
} |
javascript, array, functional-programming
const
nodOrder =
{ managerName: '', advisorName: '', clientName: '', id: ''
, goalName: '' , goalAmount: '', goals: '', score: ''
, lastModified: '', equityFixedIncome: ''
}
, levels =
{ managerName: { arr: null, val: '' }
, advisorName: { arr: null, val: '' }
, clientName: { arr: null }
}
, ResultData = []
;
data.forEach( ({ managerName, advisorName, ...otherProps }) =>
{
let
row_0 = Object.assign({}, nodOrder, { managerName })
, row_1 = Object.assign({}, nodOrder, { advisorName })
, row_2 = Object.assign({}, nodOrder, otherProps )
;
if (levels.managerName.val !== managerName )
{
levels.managerName.val = managerName
levels.managerName.arr = row_0.subRows = []
levels.advisorName.val = ''
ResultData.push( row_0 )
}
if (levels.advisorName.val !== advisorName )
{
levels.advisorName.val = advisorName
levels.advisorName.arr = row_1.subRows = []
levels.managerName.arr.push( row_1 )
}
levels.clientName.arr = (otherProps.subRows) ? (row_2.subRows = []) : null
levels.advisorName.arr.push( row_2 )
if (otherProps.subRows)
{
otherProps.subRows.forEach( subRow =>
{
let sRow = Object.assign({}, nodOrder, subRow )
levels.clientName.arr.push( sRow )
})
}
})
console.log( ResultData )
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;} | {
"domain": "codereview.stackexchange",
"id": 43665,
"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, array, functional-programming",
"url": null
} |
c++, queue
Title: Queue array based implementation in C++
Question: I wrote my implementation to Queue array based. And I need a review for it to improve it and improve my coding skill. I also will put this implementation on my GitHub account.
Thanks in advance.
//======================================================
// Author : Omar_Hafez
// Created : 29 July 2022 (Friday) 5:42:53 AM
//======================================================
#include <iostream>
enum InsertStatus { FailedQueueEmpty = -1, FailedQueueFull = -2, OK = 0 };
template <class T>
class Queue {
private:
int MAX_SIZE;
T* array;
int left = 0, right = 0, elementsCount = 0;
public:
Queue(int MAX_SIZE = 1000000)
: MAX_SIZE(MAX_SIZE), array((T*)malloc(MAX_SIZE * sizeof(T))) {}
bool empty() const {
return elementsCount == 0;
}
bool full() const {
return elementsCount == MAX_SIZE;
}
int size() const { return elementsCount; }
InsertStatus push(T const& t) {
if (full()) return FailedQueueFull;
array[right] = t;
right = (right+1)%MAX_SIZE;
elementsCount++;
return OK;
}
InsertStatus pop() {
if (empty()) return FailedQueueEmpty;
left = (left+1)%MAX_SIZE;
elementsCount--;
return OK;
}
T top() const { return array[left]; }
void clear() {
left = 0;
right = 0;
elementsCount = 0;
}
~Queue() {
delete(array);
array = nullptr;
}
};
Answer: Advice 1
private:
int MAX_SIZE;
T* array;
int left = 0, right = 0, elementsCount = 0;
I would clean it a bit:
private:
size_t max_capacity;
size_t head_index;
size_t _size;
T* array; | {
"domain": "codereview.stackexchange",
"id": 43666,
"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++, queue",
"url": null
} |
c++, queue
The first idea is that you should favor size_t over int for indexing and counting. The second idea here is to denote the front value by array[head_index] and the next tail insertion point by array[(head_index + size) % max_capacity].
Advice 2
enum InsertStatus { FailedQueueEmpty = -1, FailedQueueFull = -2, OK = 0 };
With modern C++ you can use:
enum class InsertStatus { FailedQueueEmpty, FailedQueueFull, OK };
Advice 3
The method names push and pop are usually used in stacks. Since you are dealing with a FIFO queue, the more customary method names are enqueue and dequeue.
Alternative implementation
All in all, I had this in mind:
#ifndef COM_YOURCOMPANY_UTIL_ARRAY_QUEUE
#define COM_YOURCOMPANY_UTIL_ARRAY_QUEUE
#include <stdexcept>
namespace com::yourcompany::util {
template <class T>
class Queue {
private:
size_t max_capacity;
size_t head_index;
size_t _size;
T* array;
public:
enum class OperationStatus {
FailedQueueEmpty,
FailedQueueFull,
OK,
};
Queue(size_t max_capacity = 1_000_000)
: max_capacity(max_capacity),
head_index(0),
_size(0),
array(new T[max_capacity]) {}
bool empty() const {
return _size == 0;
}
bool full() const {
return _size == max_capacity;
}
size_t size() const {
return _size;
}
OperationStatus enqueue(T const& t) {
if (full()) {
return OperationStatus::FailedQueueFull;
}
array[(head_index + _size++) % max_capacity] = t;
return OperationStatus::OK;
}
OperationStatus dequeue() {
if (empty()) {
return OperationStatus::FailedQueueEmpty;
}
head_index = (head_index + 1) % max_capacity;
_size--;
return OperationStatus::OK;
}
T top() const {
if (empty()) {
throw std::runtime_error{"top() from empty queue."};
}
return array[head_index];
} | {
"domain": "codereview.stackexchange",
"id": 43666,
"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++, queue",
"url": null
} |
c++, queue
return array[head_index];
}
void clear() {
head_index = 0;
size = 0;
}
~Queue() {
delete[] array;
}
};
}; // namespace com::yourcompany::util
#endif // COM_YOURCOMPANY_UTIL_ARRAY_QUEUE
Hope that helps. | {
"domain": "codereview.stackexchange",
"id": 43666,
"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++, queue",
"url": null
} |
python, pandas
Title: Grouping and summing only n variables of m with m>n using a column as key in pandas
Question: I have the following df
df_dict = {"week":[1,1,1,4,5],
"store":["A","B","C","A","C"],
"var": [1,1,1,1,1]}
df = pd.DataFrame(df_dict)
week store var
0 1 A 1
1 1 B 1
2 1 C 1
3 4 A 1
4 5 C 1
My goal is to sum variable A and C by week, but not variable B.
df["store"] = df["store"].str.replace("A","X")
df["store"] = df["store"].str.replace("C","X")
And this is the final output
df.groupby(by=["week","store"]).sum().reset_index()
week store var
0 1 B 1
1 1 X 2
2 4 X 1
3 5 X 1
The code works perfectly but I am pretty sure there is a better way to do that in pandas
Answer: Probably my biggest issue with the current implementation is that X is not a very good placeholder - we should prefer NaN instead - and even over B, you still sum. I would sooner split the data between grouped and non-grouped, with no store replacement:
import pandas as pd
df = pd.DataFrame({
"week": (1,1,1,4,5),
"store": ("A","B","C","A","C"),
"var": (1,1,1,1,1),
})
should_group = df.store != 'B'
totals = (
df[should_group]
.groupby('week')['var']
.sum()
.reset_index()
)
result = pd.concat((
df[~should_group], totals
), ignore_index=True)
print(result)
week store var
0 1 B 1
1 1 NaN 2
2 4 NaN 1
3 5 NaN 1 | {
"domain": "codereview.stackexchange",
"id": 43667,
"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, pandas",
"url": null
} |
c++, monads
Title: Composite expected in C++
Question: I'm interested in creating a successor to the expected monad in C++. Specifically I want it to be capable of storing error which may has one of many types, and a value. I believe this is enough to be able to build execution pipelines with easy error handling.
The limitation of the simple expected is that we have to write code like this:
auto res1 = f();
if ( !res1 )
{
...
}
auto res2 = g( res1 );
if ( !res2 )
{
...
}
auto res3 = t( res2 );
This looks like code bloat, especially if all the errors should be processed in a some common way.
I suggest the way to overcome this limitation by allowing expected to store many types of errors (therefore it is composite expected). Then it'd be possible to write pipeline and process errors like this:
auto res = f() >> g >> t;
if ( !res )
{
...
}
there is also a possibility to invoke functions taking many arguments, with use of then member function:
auto res = f().then( args_before, g, args_after ).then( t );
Link to the implementation.
P.S. Please do not pay too much attention to the implementation details. I'm most interested in the presented concept, not in the specific implementation. However, any notes are very welcomed.
#include <concepts>
#include <variant>
#include <functional>
#include <stdexcept>
class make_variant_index_error : public std::runtime_error
{
public:
enum Reason
{
BadIndex,
BadArgs
};
explicit make_variant_index_error( Reason reason ):
std::runtime_error( reason == BadIndex ? "Specified index is greater than number of variant alternatives" : "Specified index is not constructable from specified args" )
{}
};
namespace details
{
template <typename T>
struct is_variant
{
static constexpr bool value = false;
};
template <typename ...Ts>
struct is_variant<std::variant<Ts...>>
{
static constexpr bool value = true;
};
template <typename T>
constexpr bool is_variant_v = is_variant<T>::value; | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
template <typename T>
constexpr bool is_variant_v = is_variant<T>::value;
template <size_t rIndex, typename ...Ts, typename ...Args>
constexpr std::variant<Ts...> make_variant_index_impl_from_args( size_t index, Args&& ...args )
{
if ( index == rIndex )
{
if constexpr ( std::is_constructible_v<std::variant<Ts...>, std::in_place_index_t<rIndex>, Args...> )
return std::variant<Ts...>( std::in_place_index<rIndex>, std::forward<Args>( args )... );
else
throw make_variant_index_error( make_variant_index_error::BadArgs );
} else if constexpr ( rIndex == sizeof...( Ts ) - 1 )
throw make_variant_index_error( make_variant_index_error::BadIndex );
else
return make_variant_index_impl_from_args<rIndex + 1, Ts...>( index, std::forward<Args>( args )... );
} | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
template <size_t rIndexNew, size_t rIndexOld, typename ...Ts, typename OtherVariant>
requires is_variant_v<std::remove_cvref_t<OtherVariant>>
constexpr std::variant<Ts...> make_variant_index_impl_from_other( size_t indexNew, size_t indexOld, OtherVariant&& other )
{
using OtherVariantNoCvRef = std::remove_cvref_t<OtherVariant>;
if ( indexNew == rIndexNew )
{
if ( indexOld == rIndexOld )
{
if constexpr ( std::is_constructible_v<std::variant<Ts...>, std::in_place_index_t<rIndexNew>, std::variant_alternative_t<rIndexOld, OtherVariantNoCvRef>> )
return std::variant<Ts...>( std::in_place_index<rIndexNew>,
std::get<rIndexOld>( std::forward<OtherVariant>( other ) ) );
else
throw make_variant_index_error( make_variant_index_error::BadArgs );
} else if constexpr ( rIndexOld == std::variant_size_v<OtherVariantNoCvRef> - 1 )
throw make_variant_index_error( make_variant_index_error::BadIndex );
else
return make_variant_index_impl_from_other<rIndexNew, rIndexOld + 1, Ts...>( indexNew, indexOld,
std::forward<OtherVariant>(
other ));
} else if constexpr ( rIndexNew == sizeof...( Ts ) - 1 )
throw make_variant_index_error( make_variant_index_error::BadIndex );
else
return make_variant_index_impl_from_other<rIndexNew + 1, rIndexOld, Ts...>( indexNew, indexOld,
std::forward<OtherVariant>(
other ));
}
template <typename T>
struct make_variant_index_t; | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
template <typename T>
struct make_variant_index_t;
template <typename ...Ts>
struct make_variant_index_t<std::variant<Ts...>>
{
template <typename OtherVariant>
requires is_variant_v<std::remove_cvref_t<OtherVariant>>
constexpr static std::variant<Ts...> fromOther( size_t indexNew, size_t indexOld, OtherVariant&& other )
{
if ( indexNew >= sizeof...( Ts ) || indexOld >= std::variant_size_v<std::remove_cvref_t<OtherVariant>> )
throw make_variant_index_error( make_variant_index_error::BadIndex );
else
return make_variant_index_impl_from_other<0, 0, Ts...>( indexNew, indexOld,
std::forward<OtherVariant>( other ));
}
template <typename ...Args>
constexpr static std::variant<Ts...> fromArgs( size_t index, Args&& ...args )
{
if ( index >= sizeof...( Ts ))
throw make_variant_index_error( make_variant_index_error::BadIndex );
else
return make_variant_index_impl_from_args<0, Ts...>( index, std::forward<Args>( args )... );
}
};
template <typename T, typename J>
struct variant_add
{
};
template <typename T, typename J> requires ( !is_variant_v<T> && !is_variant_v<J> )
struct variant_add<T, J>
{
using type = std::variant<T, J>;
};
template <typename T, typename ...Ts> requires ( !is_variant_v<T> )
struct variant_add<T, std::variant<Ts...>>
{
using type = std::variant<T, Ts...>;
};
template <typename T, typename ...Ts> requires ( !is_variant_v<T> )
struct variant_add<std::variant<Ts...>, T>
{
using type = std::variant<Ts..., T>;
};
template <typename ...Ts, typename ...Js>
struct variant_add<std::variant<Ts...>, std::variant<Js...>>
{
using type = std::variant<Ts..., Js...>;
};
template <typename T>
struct variant_slice_first;
template <typename T, typename ...Ts>
struct variant_slice_first<std::variant<T, Ts...>>
{
using type = std::variant<Ts...>;
}; | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
template <typename T>
using variant_slice_first_t = typename variant_slice_first<T>::type;
}
template <typename T, typename ...Errs>
class composite_expected
{
public:
using variant_t = std::variant<T, Errs...>;
private:
variant_t variant_;
template <typename Other>
requires details::is_variant_v<typename Other::variant_t>
using united_t =
typename details::variant_add<
typename details::variant_add<
std::variant_alternative_t<0, typename Other::variant_t>,
details::variant_slice_first_t<variant_t>
>::type,
details::variant_slice_first_t<typename Other::variant_t>>::type;
template <typename Ret, typename Other>
requires details::is_variant_v<std::remove_cvref_t<Other>>
static auto united( Other&& other )
{
return other.index() == 0
? from_variant_t<Ret>( details::make_variant_index_t<Ret>::fromOther( 0, 0, std::forward<Other>( other ) ) )
: from_variant_t<Ret>(
details::make_variant_index_t<Ret>::fromOther( sizeof...( Errs ) + other.index(), other.index(), std::forward<Other>( other ) )
);
}
public:
template <typename J>
struct from_variant;
template <typename ...Ts>
struct from_variant<std::variant<Ts...>>
{
using type = composite_expected<Ts...>;
};
template <typename ...Ts>
using from_variant_t = typename from_variant<Ts...>::type;
using value_type = T;
template <typename ...Args>
static composite_expected<T, Errs...> fromErr( size_t errIndex, Args&& ...args )
{
return composite_expected( details::make_variant_index_t<decltype( variant_ )>::fromArgs( errIndex + 1, std::forward<Args>( args )... ) );
} | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
template <typename ...Args>
static composite_expected<T, Errs...> fromVal( Args&& ...args )
{
return composite_expected( std::in_place_index<0>, std::forward<Args>( args )... );
}
template <typename ...Args>
explicit composite_expected( Args&& ...args ):
variant_( std::forward<Args>( args )... )
{}
template <typename TFwd>
requires std::convertible_to<std::remove_cvref_t<TFwd>, T>
composite_expected( TFwd&& val ):
variant_( std::in_place_index<0>, std::forward<TFwd>( val ) )
{}
[[nodiscard]] const variant_t& variant() const
{
return variant_;
}
variant_t&& variant()
{
return std::move( variant_ );
}
explicit operator bool() const
{
return variant_.index() == 0;
}
[[nodiscard]] const T& value() const
{
return std::get<0>( variant_ );
}
T&& value()
{
return std::get<0>( std::move( variant_ ) );
}
[[nodiscard]] std::variant<Errs...> error() const
{
return details::make_variant_index_t<std::variant<Errs...>>::fromOther( variant_.index() - 1, variant_.index(), variant_ );
}
std::variant<Errs...> error()
{
return details::make_variant_index_t<std::variant<Errs...>>::fromOther( variant_.index() - 1, variant_.index(), std::move( variant_ ) );
}
[[nodiscard]] size_t errorIndex() const
{
return variant_.index() - 1;
} | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
[[nodiscard]] size_t errorIndex() const
{
return variant_.index() - 1;
}
template <typename ...Args1, typename Functor, typename ...Args2>
requires details::is_variant_v<typename std::invoke_result_t<Functor, Args1..., T, Args2...>::variant_t>
auto then( Args1&& ...args1, Functor f, Args2&& ...args2 )
{
using Ret = united_t<std::invoke_result_t<Functor, Args1..., T, Args2...>>;
return *this ? united<Ret>( std::invoke( f, std::forward<Args1>( args1 )..., std::move( value() ), std::forward<Args2>( args2 )... ).variant() )
: from_variant_t<Ret>( details::make_variant_index_t<Ret>::fromOther( variant_.index(), variant_.index(), std::move( variant_ ) ) );
}
template <typename ...Args1, typename Functor, typename ...Args2>
requires details::is_variant_v<typename std::invoke_result_t<Functor, Args1..., T, Args2...>::variant_t>
auto then( Args1&& ...args1, Functor f, Args2&& ...args2 ) const
{
using Ret = united_t<std::invoke_result_t<Functor, Args1..., T, Args2...>>;
return *this ? united<Ret>( std::invoke( f, std::forward<Args1>( args1 )..., value(), std::forward<Args2>( args2 )... ).variant() )
: from_variant_t<Ret>( details::make_variant_index_t<Ret>::fromOther( variant_.index(), variant_.index(), variant_ ) );
} | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
template <typename ...Args1, typename Functor, typename ...Args2>
requires ( std::invocable<Functor, Args1..., T, Args2...>
&& !requires { typename std::invoke_result_t<Functor, Args1..., T, Args2...>::variant_t; } )
auto then( Args1&& ...args1, Functor f, Args2&& ...args2 )
{
using Ret = std::variant<std::invoke_result_t<Functor, Args1..., T, Args2...>, Errs...>;
return *this ? from_variant_t<Ret>::fromVal( std::invoke( f, std::forward<Args1>( args1 )..., std::move( value() ), std::forward<Args1>( args2 )... ) )
: from_variant_t<Ret>( details::make_variant_index_t<Ret>::fromOther( variant_.index(), variant_.index(), std::move( variant_ ) ) );
}
template <typename ...Args1, typename Functor, typename ...Args2>
requires ( std::invocable<Functor, Args1..., T, Args2...>
&& !requires { typename std::invoke_result_t<Functor, Args1..., T, Args2...>::variant_t; } )
auto then( Args1&& ...args1, Functor f, Args2&& ...args2 ) const
{
using Ret = std::variant<std::invoke_result_t<Functor, Args1..., T, Args2...>, Errs...>;
return *this ? from_variant_t<Ret>::fromVal( std::invoke( f, std::forward<Args1>( args1 )..., value(), std::forward<Args2>( args2 )... ) )
: from_variant_t<Ret>( details::make_variant_index_t<Ret>::fromOther( variant_.index(), variant_.index(), variant_ ) );
}
template <std::invocable<T> Functor>
auto operator >>( Functor f )
{
return then( f );
}
template <std::invocable<T> Functor>
auto operator >>( Functor f ) const
{
return then( f );
}
};
And some use cases from tests.
template <typename T>
composite_expected<T, const char*> sqrt( T x )
{
if ( x >= 0 )
// implicit constructor from value
return std::sqrt( x );
else
return composite_expected<T, const char*>::fromErr( 0, "Could not take sqr-root of negative number" );
} | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
TEST( composite_expected, logic )
{
const auto x = composite_expected<int, int>::fromVal( 100 );
ASSERT_TRUE( x );
ASSERT_EQ( x.value(), 100 );
// calling with multiple arguments
const auto y = x.then( std::multiplies(), -2 );
static_assert( std::same_as<decltype( y ), const composite_expected<int, int>> );
ASSERT_TRUE( y );
ASSERT_EQ( y.value(), -200 );
auto z = x >> sqrt<int>;
static_assert( std::same_as<decltype( z ), composite_expected<int, int, const char*>> );
ASSERT_TRUE( z );
ASSERT_EQ( z.value(), 10 );
z = y >> sqrt<int>;
ASSERT_FALSE( z );
ASSERT_EQ( z.errorIndex(), 1 );
ASSERT_EQ( strcmp( std::get<1>( z.error() ), "Could not take sqr-root of negative number" ), 0 );
} | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
Answer: Design review
I’m skeptical of the idea that anyone would ever need a type that returns a value or one of multiple error types. That seems a bit excessive. I mean, imagine a square root function that returns a value if successful… or a std::error_code on failure, or a std::string describing the problem, or a std::complex with the result if a complex result is possible, or a std::vector with a bunch of a suggested alternative arguments that wouldn’t fail… or… or… or….
I mean, okay, there are situations where std::expected may be insufficient. The best example illustrating that, in my opinion, is Niall Douglas’s outcome. (Here’s a link to the Boost version.) Ignoring the policy argument, outcome has two error types, but those error types mean two very different things: the first one is for recoverable errors, while the second is for unrecoverable errors. Very basically, an error of the first type means “I couldn’t do what you wanted with the arguments you gave… but you could change your request in some way and try again, and it will work”, while the second means “nothing you could have done would have prevented this error, and it’s likely nothing you can do will prevent it happening again, so there’s no point retrying”. An example of where the difference might matter might be when you are loading configuration data: if the configuration simply isn’t there, that’s a problem, but one that you can solve by either using defaults, or pausing to query the user for what they want… but if you tried to read the configuration and the file was corrupt, or the disk had a read error, well that’s also a problem, but one that should never, ever happen in normal operation, and there’s nothing you can do (in the program) to fix it.
So I’m on board with an extended expected. Just… not quite as extended as you’re imagining. | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
So I’m on board with an extended expected. Just… not quite as extended as you’re imagining.
I would say that all anyone would ever need is outcome. I think that covers literally any possibility that anyone could ever want. You have your value, you have a space for errors that that calling code can potentially recover from, and you have a space for anything else that could ever happen but never should (unless something is really, really wrong). Using the square root example, you have your return value, you have a space for “there is no (real) result for the argument you gave (but you could give me a different argument, or you could use complex numbers)”, and you have a space for “the math co-processor is literally on fire”. And of course, expected (or result, to use Douglas’s terminology) is the simpler case where there isn’t a reason to distinguish between types of errors.
Okay, but what if you really do want multiple error types? What if you really do want to return a error_code, a string, or a complex from sqrt()? Well, for that strange and rare case, you just need expected<double, variant<error_code, string, complex<double>>. In other words, you don’t need expected<ValueType, ErrorTypes...>. You just need the standard expected<ValueType, ErrorType>, and you can use a variant<ErrorTypes...>. (Or, of course, something like outcome<ValueType, RecoverableErrorType, UnrecoverableErrorType>, where the latter two types could be variants.)
Or, even better, a custom type to hold multiple error types. So sqrt() could return a expected<double, sqrt_error_t>, where sqrt_error_t is a struct holds a complex<double> and an error_code, and throws an exception by default, so you could use it like this:
auto better_sqrt(double) -> std::expected<double, sqrt_error_t>; | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
// Simple use
auto res = better_sqrt(arg).value(); // throws on error
// Advanced use (not all of this is required, of course; use as much of it as
// you need for a given use case)
try
{
if (auto res = better_sqrt(arg); res.has_value())
{
auto val = res.value(); // this is a double
// do real calculations...
}
else
{
auto val = res.error().complex_value(); // either a complex<double>,
// or throws if even that could
// not be calculated
// do complex calculations...
}
}
// sqrt_error_t inherits from std::exception, so this works:
catch (std::exception const& x)
{
// Could not calculate a real *OR* complex square root, so report error.
}
// Alternate form, to avoid non-deterministic exception costs
if (auto res = better_sqrt(arg); res.has_value())
{
auto val = res.value(); // this is a double
// do real calculations...
}
else if (res.has_complex_value())
{
auto val = res.error().complex_value(); // this is a complex<double>
// do complex calculations...
}
else
{
// Could not calculate a real *OR* complex square root, so report error.
}
How would that compare to the composite_expected interface?
auto better_sqrt(double) -> std::composite_expected<double, std::complex<double>, std::error_code>;
// Simple use
auto res = better_sqrt(arg).value(); // throws on error | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
// Simple use
auto res = better_sqrt(arg).value(); // throws on error
// Advanced use
try
{
if (auto res = better_sqrt(arg); res)
{
auto val = res.value(); // this is a double
// WARNING: This is the one and only time you
// can call res.value(). If you accidentally
// call it a second time... UB.
// do real calculations...
}
else if (res.errorIndex() == 1)
// WARNING: Do not do:
// if (std::holds_alternative<complex<double>>(res.error()))
// because you can only call `res.error()` once, and if you do it here,
// you can’t do it below.
{
// WARNING: error index is 1, but we have to use index 0.
auto val = std::get<0>(res.error()); // this is a complex<double>
// or:
// auto val = std::get<std::complex<double>>(res.error());
// do complex calculations...
}
else
{
throw std::system_error{std::get<1>(res.error())};
// or:
// throw std::system_error{std::get<std::error_code>(res.error())};
}
}
catch (std::exception const& x)
{
// Could not calculate a real *OR* complex square root, so report error.
} | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
It’s basically the same (though there are some gotchas that I will go into later). So you don’t really gain much by the extra error types in composite_expected. (Note that in cases where you’re using the monadic interface, there will be no difference, so there’s no point comparing them.)
So, in summary, I don’t see the need for an extended expected to handle the case of multiple error types. In those very, very rare cases where you actually want multiple error types, it’s just as easy to put those error types in a variant or a custom struct… and, in doing so, you make the different error type cases more meaningful and ergonmic. Even outcome’s multiple error types seem a bit… much… for most use cases, but at least with outcome, there is a meaningful semantic to the two (and only two) error types.
Code review
Since the OP’s concern is only with the composite_expected class, I will ignore all the other code, regardless of problems, and assume it all works… well, not as described, because nothing is described—there is literally not a single comment anywhere in the code—but I will assume it works as I hope it works, given the names. More likely than not, my assumptions will be wrong, but… what can one do? There are no comments explaining anything.
Comment your code! The more the better! Obviously don’t make stupid comments like the classic “++i; // increments i”, but any high-level points or logical implications should be explained.
Nothing in your code is obvious to anyone else. It may be obvious to you what variant_add<variant<A, B>, variant<C, D>> does… but everyone else is wondering whether this gives variant<A, B, C, D> or variant<A, B, variant<C, D>>. A single line comment would remove the confusion.
Anywho, I’ll start the review with just the definition of composite_expected.
template <typename Other>
requires details::is_variant_v<typename Other::variant_t>
using united_t =
typename details::variant_add< | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
using united_t =
typename details::variant_add<
typename details::variant_add<
std::variant_alternative_t<0, typename Other::variant_t>,
details::variant_slice_first_t<variant_t>
>::type,
details::variant_slice_first_t<typename Other::variant_t>>::type; | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
template <typename Ret, typename Other>
requires details::is_variant_v<std::remove_cvref_t<Other>>
static auto united( Other&& other )
{
return other.index() == 0
? from_variant_t<Ret>( details::make_variant_index_t<Ret>::fromOther( 0, 0, std::forward<Other>( other ) ) )
: from_variant_t<Ret>(
details::make_variant_index_t<Ret>::fromOther( sizeof...( Errs ) + other.index(), other.index(), std::forward<Other>( other ) )
);
}
I literally have no idea what any of this is supposed to do. Like, not even the faintest notion. Nothing is explained. Not a single comment.
It’s not even possible to deduce what’s going on from the names. What does united mean?
The only way I could suss out what any of this does would be to dig into templates of templates of templates of templates… and… no. Just… no.
template <typename J>
struct from_variant;
template <typename ...Ts>
struct from_variant<std::variant<Ts...>>
{
using type = composite_expected<Ts...>;
};
template <typename ...Ts>
using from_variant_t = typename from_variant<Ts...>::type;
Why is this part of the public interface?
template <typename ...Args>
static composite_expected<T, Errs...> fromErr( size_t errIndex, Args&& ...args )
{
return composite_expected( details::make_variant_index_t<decltype( variant_ )>::fromArgs( errIndex + 1, std::forward<Args>( args )... ) );
}
My first problem with this function is that the index is a run-time argument, and not a compile-time, template argument.
See, if the index was a compile-time arguments, I could write:
composite_expected<T, const char*>::fromErr<0>("Could not take sqr-root of negative number"); | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
… and that index would be compile-time checked. As in, if I wrote a 1 by accident, it wouldn’t even compile. With the current code, it looks like it will throw a make_variant_index_error… which is weird, for a couple of reasons. But we’ll get back to that.
Also, if the index were a compile-time template argument, all of the machinery you need to make runtime indices works goes away. No more need for make_variant_index_t, make_variant_index_impl_from_other, etc..
And if you think about it… in what use case, ever, would you ever need to construct an error-ed composite_expected, and not know, at compile-time, which error you’re constructing? That will never happen. So why go through all the gymnastics to make it possible?
But my main problem with this function is how un-ergonomic it is. This is literally the only way to construct an error-ed composite_index, and the example given shows how ugly it is to actually do:
template <typename T>
composite_expected<T, const char*> sqrt( T x )
{
/* ... */
return composite_expected<T, const char*>::fromErr( 0, /* args */ );
}
In order to create an error state, one has to repeat the entire type… like, all of it, with the expected value type, and all of the error types (here there is just one, but the whole point of composite_expected is that there can be several). If you imagine this function could return one of several error types, then it would look like this:
auto func(/* ... */) -> composite_expected<T, ErrT1, ErrT2, ErrT3>
{
/* ... */
else if (/* error type 1 */)
return composite_expected<T, ErrT1, ErrT2, ErrT3>::fromErr(0, /* args */);
else if (/* error type 2 */)
return composite_expected<T, ErrT1, ErrT2, ErrT3>::fromErr(1, /* args */);
else if (/* error type 3 */)
return composite_expected<T, ErrT1, ErrT2, ErrT3>::fromErr(2, /* args */);
} | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
Now imagine we want to change ErrT2 to ErrT2b.
Yeah, sure, you can “fix” this problem with type aliases, but… well, take a look at what std::expected looks like (obviously only with a single error type):
auto func(/* ... */) -> std::expected<T, ErrT>
{
/* ... */
else if (/* error */)
return std::unexpected{/* args */};
// or, if this is not a simple, implicit conversion:
// return std::unexpected<ErrT>{std::inplace_t, /* args */};
}
If we imagine extending that to multiple types:
auto func(/* ... */) -> hypothetical::expected<T, ErrT1, ErrT2, ErrT3>
{
/* ... */
else if (/* error type 1 */)
return std::unexpected<ErrT1>{std::inplace_t, /* args */};
else if (/* error type 2 */)
return std::unexpected<ErrT2>{std::inplace_t, /* args */};
else if (/* error type 3 */)
return std::unexpected<ErrT3>{std::inplace_t, /* args */};
}
This, of course, assumes that the ErrT’s are completely distinct—you can’t implicitly construct an ErrT2 from an ErrT1, for example. If they’re not, then you’d need to specify the index. So:
auto func(/* ... */) -> hypothetical::expected<T, ErrT1, ErrT2, ErrT3>
{
/* ... */
else if (/* error type 1 */)
return hypothetical::unexpected<0, ErrT1>{std::inplace_t, /* args */};
else if (/* error type 2 */)
return hypothetical::unexpected<1, ErrT2>{std::inplace_t, /* args */};
else if (/* error type 3 */)
return hypothetical::unexpected<2, ErrT3>{std::inplace_t, /* args */};
}
And it might be possible (I’d need to sit down and think it through to be sure) to do:
auto func(/* ... */) -> hypothetical::expected<T, ErrT1, ErrT2, ErrT3>
{
/* ... */ | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
else if (/* error type 1 */)
return hypothetical::unexpected<0>{std::inplace_t, /* args */};
else if (/* error type 2 */)
return hypothetical::unexpected<1>{std::inplace_t, /* args */};
else if (/* error type 3 */)
return hypothetical::unexpected<2>{std::inplace_t, /* args */};
}
It would be nice if you were able to either specify just the type (in cases where the types are distinct) or the index or both (for safety). But even in the worst case, where you have to specify both the index and the type, that’s still better than the case of fromErr(), where you have to specify all the types—value and error—and the index.
Back to make_variant_index_error: it seems strange to throw a custom error for this because we already have a bunch of standard errors that would make more sense: std::out_of_range is probably the best choice. But even if you were going to make a custom error, it would make more sense to inherit from logic_error rather than runtime_error; after all, if someone gives a bad index, that’s on them; that’s a problem they could have avoided if they’d cared to.
template <typename ...Args>
static composite_expected<T, Errs...> fromVal( Args&& ...args )
{
return composite_expected( std::in_place_index<0>, std::forward<Args>( args )... );
}
This function seems superfluous, from an API point of view. auto v = composite_expected<T, E1 /*, E2,... */>(/* args */); is shorter, and more intuitive than auto v = composite_expected<T, E1 /*, E2,... */>::fromVal(/* args */);.
The problem is, of course, they don’t do the same thing… but we’ll get to that next.
template <typename ...Args>
explicit composite_expected( Args&& ...args ):
variant_( std::forward<Args>( args )... )
{}
template <typename TFwd>
requires std::convertible_to<std::remove_cvref_t<TFwd>, T>
composite_expected( TFwd&& val ):
variant_( std::in_place_index<0>, std::forward<TFwd>( val ) )
{} | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
There is something very weird going on here.
When I do auto v = composite_expected<T, E1 /*, E2, ...*/>(U{/*args*/});, then if U is implicitly convertible to T, the second constructor will be selected, and I’ll get a non-error value in v. Good. That’s what I expected. If I do auto v = composite_expected<std::string, std::error_code>("foo");, I get a non-error-ed v that holds a string. Great.
But if U is not implicitly convertible to T, the second constructor will be selected. And the weirdness here comes from the fact that that constructor does not use in_place_index to construct the value type… but instead uses variant’s converting constructor.
The reason why that’s weird is that the converting constructor won’t necessarily choose the first alternative if another alternative is a better match. Which means the argument given may be silently shunted to an error type.
For example, suppose you have a composite_expected<string, string_view>, and you do auto s = ""s; auto v = composite_expected<string, string_view>{s};. That will do the obvious, and you end up with v in the non-error-ed state, holding an empty string. All good. But then, at some later point, that first line becomes auto s = ""sv;. Such a minor change, and one that seems highly plausible—no need to construct a string here, right? It’s a compile-time string literal; we can use a string view. But… now v constructs in the error state, holding an empty string view. No warnings. No indications whatsoever of why v… which may be far away from s… is suddenly not what it was before.
I’m guessing the reason you did things this way is because you wanted the following to compile only when U is implicitly convertible to T:
auto f() -> composite_expected<T, E>
{
return U{};
} | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
Okay, fine, but… this is not the way to go about this. We have conditional explicit these days, so you could write those two constructors as:
template <typename U>
explicit(std::convertible_to<U, T>) composite_expected(U&& u)
: variant_{std::in_place_index<0>, std::forward<U>(u)}
{}
And the function above won’t compile if U is not implicitly convertible to T, but it will compile if U is explicitly convertible to T. And none of the error types will ever be considered (even if they’re a better match).
(If you want to also allow construction from multiple arguments, you would need another, non-conversion constructor to handle that. Or, you could use what you have now, but with std::in_place_index<0> in the unconstrained case as well.)
[[nodiscard]] const variant_t& variant() const
{
return variant_;
}
variant_t&& variant()
{
return std::move( variant_ );
}
These functions make no sense in the public interface, and expose the inner workings of the class. What if you decide to re-implement it in terms of boost::variant instead of std::variant? Or manually with a discriminated union?
explicit operator bool() const
{
return variant_.index() == 0;
}
This function is fine, but I wanted to point out that there’s a general lack of decoration that applies all throughout. For example, this function could be noexcept and constexpr.
[[nodiscard]] const T& value() const
{
return std::get<0>( variant_ );
}
T&& value()
{
return std::get<0>( std::move( variant_ ) );
} | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
T&& value()
{
return std::get<0>( std::move( variant_ ) );
}
There are some serious problems here.
The first function is (mostly) fine… although, I don’t really see the point of the [[nodiscard]]. You’re just returning a reference. There’s no cost if the user disregards it. There’s no point in calling the function if you’re just going to disregard the return, sure… but it’t not going to be a problem. I suppose this is a style thing, so if you really feel strongly about [[nodiscard]], then fine, go ahead… but in that case, you really should be using it everywhere.
The real problem is the second function. Suppose I do this:
auto v = composite_expected<T, ...>{...};
auto v1 = v.value(); // this is fine (assuming v has a value)
auto v2 = v.value(); // boom
What happens on that boom line? Could be anything. Depends on T. The value in v was moved from in the first call to value(), and the only things you should safely expect to do with a moved-from object is either reassign it, or destroy it. Using it is a no-no.
And note that the value gets moved from any time you call it with a non-const object. The previous code is dangerous, but the following code is fine:
auto const v = composite_expected<T, ...>{...};
auto v1 = v.value(); // this is fine (assuming v has a value)
auto v2 = v.value(); // fine | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
auto v1 = v.value(); // this is fine (assuming v has a value)
auto v2 = v.value(); // fine
Note that there is no indication in that first code block that the value has been moved from.
Moving a value silently out from under a user is a terrible idea. If something is going to be moved, it should be explicit. Or, at least, it should happen implicitly only in situations where anything other than a move would make no sense.
If you want the same “smart-moving” behaviour that std::optional or std::expected have, then in C++20, you have to write four functions, and use reference qualifiers:
auto value() & -> T& { return std::get<0>(variant_); }
auto value() const& -> T const& { return std::get<0>(variant_); }
auto value() && -> T&& { return std::get<0>(std::move(variant_)); }
auto value() const&& -> T const&& { return std::get<0>(std::move(variant_)); }
And, technically, this doesn’t take volatile into account (but nobody does anyway).
As of C++23, you can use deducing this to simplify this to a single function.
But the bottom line is that silently moving the internal value in a member function that isn’t r-value reference qualified is asking for disaster.
[[nodiscard]] std::variant<Errs...> error() const
{
return details::make_variant_index_t<std::variant<Errs...>>::fromOther( variant_.index() - 1, variant_.index(), variant_ );
}
std::variant<Errs...> error()
{
return details::make_variant_index_t<std::variant<Errs...>>::fromOther( variant_.index() - 1, variant_.index(), std::move( variant_ ) );
} | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
Do these functions really make sense? Will there ever be a need to get the whole tuple of potential errors? (Assuming that’s what’s really going on here. Again, I don’t want to dig into the morass of make_variant_index_t.)
You’d like a function that just returns the error, sure, but that seems impossible, because which error is active (if any) can’t be known at compile time. The only alternative, then, seems to be to return a variant of all possibilities. So, pragmatically, this would seem to be the only option.
I would say this is a point where you should step back and think about practical usage of the design. The only things anyone is probably ever going to want to do with the error (if any) are:
ask which of the error types is active; and
use the active error value to do something (most likely report).
You already have a function that does 1: errorIndex(). (Though, I would add some form of holds_alternative(), so you can query by type.) So all you need is 2.
So how does std::variant handle the case of wanting to the use the active value to do something? It uses the visitor pattern.
So what if instead of querying for all potential errors, then having to dig through that to figure out which error is active, then doing what they want with the one true error, you let users skip the first two steps by also using the visitor pattern. Something like:
template <typename F>
auto visit_error(F&& f) -> decltype(auto)
{
return std::visit(std::forward<F>(f), _variant);
}
(You’d need to quadruplicate the above to handle const and l-value/r-value references, or use deducing this.)
Usage:
composite_expected<T, E1, E2, E3> v = /* initialize to some error */;
struct error_handler_t
{
auto operator()(E1 const&) { /* ... */ }
auto operator()(E2 const&) { /* ... */ }
auto operator()(E3 const&) { /* ... */ }
};
if (v)
// use v
else
v.visit_error(error_handler_t{}); | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
if (v)
// use v
else
v.visit_error(error_handler_t{});
// Or:
template <typename... Ts> struct overloaded : Ts... { using Ts::operator()...; };
if (v)
// use v
else
v.visit_error(overloaded{
[](E1 const&) { /* ... */ },
[](E2 const&) { /* ... */ },
[](E3 const&) { /* ... */ },
});
This idea maps very nicely to a monadic interface:
auto wanted_value = v
.and_then(do_something)
.or_else(overloaded{
[](E1 const&) { /* ... */ },
[](E2 const&) { /* ... */ },
[](E3 const&) { /* ... */ },
});
For an actual, practical case:
auto wrap(T&& value) -> composite_expected<T>; // no errors, no error types
auto square_root(T&&) ->
composite_expected<T,
std::invalid_argument // if the arg is NaN (or some other invalid)
std::domain_error // if the arg is negative
>;
auto to_string(T&&) ->
composite_expected<std::string,
std::bad_alloc // if we ran out of memory
>;
std::string result = my_wrap(input)
.and_then(square_root)
.and_then(to_string)
.or_else(overloaded{
// Note how the possible errors are all combined.
[](std::invalid_argument const&) { return "not a number"s; },
[](std::domain_error const&) { return "negative number"s; },
[](std::domain_error const&) { return "ran out of memory"s; },
});
// So:
// input == 144; result == "12";
// input == -1; result == "negative number";
// input == <anything valid, but no mem left>; result == "out of memory"; | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
errorIndex() is fine. (Though it could use constexpr, and some better documentation: like, what happens if there is no error? Is the return value supposed to be std::variant_npos? Or is that just not specified?)
template <typename ...Args1, typename Functor, typename ...Args2>
requires details::is_variant_v<typename std::invoke_result_t<Functor, Args1..., T, Args2...>::variant_t>
auto then( Args1&& ...args1, Functor f, Args2&& ...args2 )
{
using Ret = united_t<std::invoke_result_t<Functor, Args1..., T, Args2...>>;
return *this ? united<Ret>( std::invoke( f, std::forward<Args1>( args1 )..., std::move( value() ), std::forward<Args2>( args2 )... ).variant() )
: from_variant_t<Ret>( details::make_variant_index_t<Ret>::fromOther( variant_.index(), variant_.index(), std::move( variant_ ) ) );
}
template <typename ...Args1, typename Functor, typename ...Args2>
requires details::is_variant_v<typename std::invoke_result_t<Functor, Args1..., T, Args2...>::variant_t>
auto then( Args1&& ...args1, Functor f, Args2&& ...args2 ) const
{
using Ret = united_t<std::invoke_result_t<Functor, Args1..., T, Args2...>>;
return *this ? united<Ret>( std::invoke( f, std::forward<Args1>( args1 )..., value(), std::forward<Args2>( args2 )... ).variant() )
: from_variant_t<Ret>( details::make_variant_index_t<Ret>::fromOther( variant_.index(), variant_.index(), variant_ ) );
} | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
template <typename ...Args1, typename Functor, typename ...Args2>
requires ( std::invocable<Functor, Args1..., T, Args2...>
&& !requires { typename std::invoke_result_t<Functor, Args1..., T, Args2...>::variant_t; } )
auto then( Args1&& ...args1, Functor f, Args2&& ...args2 )
{
using Ret = std::variant<std::invoke_result_t<Functor, Args1..., T, Args2...>, Errs...>;
return *this ? from_variant_t<Ret>::fromVal( std::invoke( f, std::forward<Args1>( args1 )..., std::move( value() ), std::forward<Args1>( args2 )... ) )
: from_variant_t<Ret>( details::make_variant_index_t<Ret>::fromOther( variant_.index(), variant_.index(), std::move( variant_ ) ) );
}
template <typename ...Args1, typename Functor, typename ...Args2>
requires ( std::invocable<Functor, Args1..., T, Args2...>
&& !requires { typename std::invoke_result_t<Functor, Args1..., T, Args2...>::variant_t; } )
auto then( Args1&& ...args1, Functor f, Args2&& ...args2 ) const
{
using Ret = std::variant<std::invoke_result_t<Functor, Args1..., T, Args2...>, Errs...>;
return *this ? from_variant_t<Ret>::fromVal( std::invoke( f, std::forward<Args1>( args1 )..., value(), std::forward<Args2>( args2 )... ) )
: from_variant_t<Ret>( details::make_variant_index_t<Ret>::fromOther( variant_.index(), variant_.index(), variant_ ) );
} | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
Okay, figuring out what’s going on here with no comments is going to be slog, so I’ll have to make some assumptions. It looks like you have 4 variations, but with const, non-const we can boil that down to 2. It looks like the first 2 deal with functions that return wrapped objects, while the latter two deal with functions that deal with unwrapped objects. So, basically, the first two are “bind”, and the last two are “map” (this may or may not match “standard” monadic terminology; I’ve never cared enough to really research this, because I just use the C++ terms “then” and “transform”).
Okay, so if you are trying to do both bind and map with the same name, you already have a problem. There’s a reason those two operations have different names in pretty much every implementation of monads. When the function object returns a wrapped object, sometimes you want it wrapped again, and sometimes not.
In C++, the first two functions are generally named “and_then”, and the second two “transform”.
By disambiguating them with different names, you avoid a whole host of usability headaches, and simplify the understanding of what’s going on. Now it’s no longer a mystery when a function returns composite_expected<T, Errs...>, whether the actual application in then() will return composite_expected<T, Errs...> or composite_expected<composite_expected<T, Errs...>, Errs...> or who knows what else.
Okay, so now that I have sussed out what’s really going on here (I would have been spared a lot of this work with some comments!!!), I can guess that maybe united_t is somehow collecting together the error types in Errs, and the error types returned by the function. How exactly is still a mystery. Are duplicate types coalesced? Are the types from the function placed before or after the types from the class?
Anyway, I assume they’re all collected somehow, in some order. | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
Anyway, I assume they’re all collected somehow, in some order.
Now, the same bug that exists in value() exists here: you are very silently moving the object’s value out from under the user, with no warning, and the only way the user can possibly know is if they take the time to sit down and parse apart this very long and very complicated function definition and spot the hidden std::move… and realize what it means.
As with value(), the way this should be fixed is by quadruplicating the function (or, in C++23, using deducing this). This is how it’s actually done in std::optional.
I would also suggest that you should be taking the function by forwarding-reference, rather than by-value. It may be non-copyable, or expensive to copy, and you don’t need to copy in any case.
But the main issue I have with these functions is that they’re wildly over-complicated, for no real benefits. You want to be able to work with functions that take multiple arguments, where the key argument is in any position. Fine. But we already have tools for that.
Consider this:
auto result = f(input)
.then(a, b, c, d, e); | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
Now, tell me which of a, b, c, d, e is the function.
Compare that to this:
auto result = f(input)
.then(std::bind(b, a, _1, c, d, e));
Now it’s clear: b is the function.
std::bind is not only clearer, it’s more powerful. What if you want to use the value twice in the argument list? You can’t do it with your way, but with std::bind it’s easy:
auto result = f(input)
// basically calls g(f(input), f(input)) (but without calling f twice)
.then(std::bind(g, _1, _1));
So I would say don’t bother with all the complexity of supporting before/after arguments. It makes your code more complex, and user code harder to read. And there’s a superior, standard solution.
template <std::invocable<T> Functor>
auto operator >>( Functor f )
{
return then( f );
}
template <std::invocable<T> Functor>
auto operator >>( Functor f ) const
{
return then( f );
}
I am really not a fan of appropriating operators for non-standard behaviours. I get that it sucks that C++ doesn’t have Haskell’s >>=… but you shouldn’t try to shoehorn it in.
It’s especially problematic when it creates ambiguity. For example, consider this line from your test code: auto z = x >> sqrt<int>; Without looking up the type of x, this could be a shift operation, or a stream read. (Yes, using << and >> for streaming was also a bad idea, one that has been expensive and miserable, and recent standards have starting moving away from that to function calls (cf std::format()).) Now it can also be a function chain. Not great.
And it doesn’t seem to add much:
auto z = x >> sqrt<int>;
auto z = x
.and_then(sqrt<int>);
The latter seems much more readable to me. It gets even more so as the chains get more complicated, and you starting adding transforms and or_elses and other stuff. For example:
auto z = (x >> sqrt<int>).value_or(0);
auto z = x
.and_then(sqrt<int>)
.value_or(0); | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
c++, monads
auto z = x
.and_then(sqrt<int>)
.value_or(0);
Also, keep in mind that there may be actual monadic chaining operators in the future. Proposals in flight include |> and ??. (The |> paper actually illustrates the hazard of what you’re doing. The ranges library co-opted | for pipelining. Because of that, if we ever get |>, the ranges library will have to truck around unnecessary and expensive support for | for many years to come… possibly forever.)
I’d toss these operators, split then() into and_then() and transform() (and remove support for prefix and postfix args), and that way your type will play well with other monadic types in the standard, past, present, and future. | {
"domain": "codereview.stackexchange",
"id": 43668,
"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++, monads",
"url": null
} |
python, performance, strings, numpy
Title: Improving the speed of one-hot encoding a list of strings
Question: I've recently developed two functions to functions to essentially convert a list of strings that look something like this (these strings are 101 characters long in my case):
['AGT', 'AAT']
To a numpy array:
array([[[[1],
[0],
[0],
[0]],
[[0],
[1],
[0],
[0]],
[[0],
[0],
[0],
[1]]],
[[[1],
[0],
[0],
[0]],
[[1],
[0],
[0],
[0]],
[[0],
[0],
[1],
[0]]]])
The shape of which is [2, 3, 4, 1] in this case
At the moment, my code essentially defines one function, in which I define a dictionary, which is then mapped to a single input string, like so:
def sequence_one_hot_encoder(seq):
import numpy as np
mapping = {
"A": [[1], [0], [0], [0]],
"G": [[0], [1], [0], [0]],
"C": [[0], [0], [1], [0]],
"T": [[0], [0], [0], [1]],
"X": [[0], [0], [0], [0]],
"N": [[1], [1], [1], [1]]
}
encoded_seq = np.array([mapping[i] for i in str(seq)])
return(encoded_seq)
Following from this, I then create another function to map this function to my list of strings:
def sequence_list_encoder(sequence_file):
import numpy as np
one_hot_encoded_array = np.asarray(list(map(sequence_one_hot_encoder, sequence_file)))
print(one_hot_encoded_array.shape)
return(one_hot_encoded_array)
At the moment, for a list containing 1,688,119 strings of 101 characters, it's taking around 7-8 minutes. I was curious if there was a better way of rewriting my two functions to reduce runtime? | {
"domain": "codereview.stackexchange",
"id": 43669,
"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, strings, numpy",
"url": null
} |
python, performance, strings, numpy
Answer: sequence_one_hot_encoder(seq) builds an array of shape (len(seq), 4, 1). sequence_list_encoder() puts all these into a python list and then coverts the list into an array with shape (number_of_sequences, len(seq), 4, 1). It looks like there is a lot of overhead doing that. It is much faster to treat the one_hot_encoded_array as 1-D and then set the shape at the end.
def sequence_list_encoder(sequence_file):
mapping = {
"A": (1, 0, 0, 0),
"G": (0, 1, 0, 0),
"C": (0, 0, 1, 0),
"T": (0, 0, 0, 1),
"X": (0, 0, 0, 0),
"N": (1, 1, 1, 1)
}
sequences = sequence_file.read().splitlines()
bits = [b for seq in sequences for ch in seq for b in mapping[ch]]
one_hot_encoded_array = np.fromiter(bits, dtype=np.uint8)
one_hot_encoded_array.shape = (len(sequences), len(sequences[0]), 4, 1)
return one_hot_encoded_array
This runs in about 1/5 the time as your code. | {
"domain": "codereview.stackexchange",
"id": 43669,
"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, strings, numpy",
"url": null
} |
c++, linked-list, queue
Title: Queue Linked List based implementation in C++
Question: I wrote my implementation to Queue Linked List based. And I need a review for it to improve it and improve my coding skill. I also will put this implementation on my GitHub account.
//======================================================
// Author : Omar_Hafez
// Created : 30 July 2022 (Saturday) 8:02:31 AM
//======================================================
#include <iostream>
#include <memory>
template <class T>
class Queue {
private:
struct Node {
T value;
std::shared_ptr<Node> next;
Node (T data, std::shared_ptr<Node> ptr) : value(data), next(ptr) {}
};
int size_value = 0;
std::shared_ptr<Node> back;
std::shared_ptr<Node> front;
public:
enum QueueOpStatus { FailedQueueEmpty = -1, FailedQueueFull = -2, OK = 1 };
// this constructor is to keep the consistency with the array based implementation
Queue(int MAX_SIZE = 1000000) {}
QueueOpStatus push(T const& t) {
if(full()) return FailedQueueFull;
if(front) {
back->next = std::make_shared<Node>(t, nullptr);
back = back->next;
} else {
front = std::make_shared<Node>(t, nullptr);
back = front;
}
size_value++;
return OK;
}
QueueOpStatus pop() {
if (empty()) return FailedQueueEmpty;
front = front->next;
size_value--;
return OK;
}
bool empty() const { return size_value == 0; }
bool full() const { return 0; }
int size() const { return size_value; }
T top() const {
if(empty()) {
throw "Queue is empty";
}
return front->value;
} | {
"domain": "codereview.stackexchange",
"id": 43670,
"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++, linked-list, queue",
"url": null
} |
c++, linked-list, queue
void clear() {
while(!empty()) {
pop();
}
}
};
Answer:
push could be streamlined: back will always point to the new node no matter what:
auto new_node = make_shared<Node>(t, nullptr);
if (front) {
back->next = new_node;
} else {
front = new_node;
}
back = new_node;
The emptiness of the queue is tested differently in push (which tests if (front)) versus pop/top (which tests empty() aka size_value == 0). Technically nothing is wrong, but it gives an uneasy feeling. Better use an uniform test.
top throwing an exception could be an overkill. Consider returning a std::pair<bool, T>, or std::optional<T>.
size_value shall be size_t.
To repeat another review, enqueue/dequeue are far better than push/pop. | {
"domain": "codereview.stackexchange",
"id": 43670,
"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++, linked-list, queue",
"url": null
} |
c++, math-expression-eval
Title: Polish Notation in C++
Question: This is my homemade Polish Notation implementation in C++.
I need a review for it to improve it and improve my coding skill. I also will put this implementation on my GitHub account
//======================================================
// Author : Omar_Hafez
// Created : 28 July 2022 (Thursday) 6:10:44 AM
//======================================================
#include <math.h>
#include <iostream>
#include <stack>
#include <vector>
class PolishNotation {
private:
std::string operations[5] = {"+", "-", "*", "/", "^"};
bool isDigit(char &ch) const { return ch >= '0' && ch <= '9'; }
bool isOperation(std::string str) const {
for (std::string x : operations) {
if (str == x) return 1;
}
return 0;
}
bool isNumber(std::string str) const {
bool floatingPoint = 0;
if (str.length() == 1) {
return isDigit(str[0]);
}
for (int i = (str[0] == '-'); i < str.length(); i++) {
if (!floatingPoint && str[i] == '.') {
floatingPoint = 1;
continue;
}
if (!isDigit(str[i])) return 0;
}
return 1;
}
bool isHigher(std::string a, std::string b) const {
int cnt1 = 0, cnt2 = 0;
cnt1 = (a == "+" || a == "-" ? 1 : a == "*" || a == "/" ? 2 : 3);
cnt2 = (b == "+" || b == "-" ? 1 : b == "*" || b == "/" ? 2 : 3);
return cnt1 > cnt2;
} | {
"domain": "codereview.stackexchange",
"id": 43671,
"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++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
std::string calculate(std::string a, std::string b, std::string operation) const {
long double x = stold(a);
long double y = stold(b);
if (operation == "+") return std::to_string(x + y);
if (operation == "-") return std::to_string(x - y);
if (operation == "*") return std::to_string(x * y);
if (operation == "/") return std::to_string(x / y);
if (operation == "^") return std::to_string(pow(x, y));
return a;
}
std::vector<std::string> cutter(std::string str) const {
std::vector<std::string> ope;
std::string tmp = "";
int ind = 0;
while (ind < str.length()) {
while (ind < str.length() &&
(isDigit(str[ind]) || str[ind] == '.')) {
tmp += str[ind++];
}
if (tmp != "") {
ope.push_back(tmp);
tmp = "";
}
while (ind < str.length() && !isDigit(str[ind])) {
tmp += str[ind++];
}
if (tmp.length() > 1 && tmp.back() == '-') {
tmp.pop_back();
ope.back() = "-" + ope.back();
}
if (tmp != "") {
ope.push_back(tmp);
tmp = "";
}
}
return ope;
} | {
"domain": "codereview.stackexchange",
"id": 43671,
"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++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
std::vector<std::string> convertToPolishNotation(std::vector<std::string> ope) const {
if (ope.size() == 1) return {ope[0]};
std::vector<std::string> a;
a.push_back(ope[0]);
std::stack<std::string> st;
for (int i = 1; i < ope.size(); i += 2) {
if (st.empty()) {
st.push(ope[i]);
} else {
while (!st.empty() && !isHigher(ope[i], st.top())) {
a.push_back(st.top());
st.pop();
}
st.push(ope[i]);
}
a.push_back(ope[i + 1]);
}
while (!st.empty()) {
a.push_back(st.top());
st.pop();
}
return a;
}
public:
std::vector<std::string> convertToPolishNotation(std::string str) const {
return convertToPolishNotation(cutter(str));
}
long double calculateThePolishNotation(std::vector<std::string> a) const {
int ind = 0;
std::stack<std::string> st;
while (ind < a.size()) {
while (st.empty() || isNumber(st.top())) {
st.push(a[ind++]);
}
std::string operation = st.top();
st.pop();
std::string x = st.top();
st.pop();
std::string y = st.top();
st.pop();
st.push(calculate(y, x, operation));
}
return stold(st.top());
}
};
int main() {
std::string str;
std::cin >> str;
PolishNotation p = PolishNotation();
std::cout << std::fixed << p.calculateThePolishNotation(p.convertToPolishNotation(str));
} | {
"domain": "codereview.stackexchange",
"id": 43671,
"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++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
Answer: Include All Necessary Include Files
The code does not contain the necessary include for std::string, it does not compile on my computer (Windows 10, Visual Studio 2019 Professional) without this.
Don't Reinvent the Wheel
The C programming language has ctype.h which includes the function isdigit() there is no need to write your own, you can include cctype to get access this function. You might also want to try the first answer in this stack overflow question.
Alternate Implementation of the calculate() Function
One problem with the current implementation of the calculate() function is that there is no error checking, what happens if someone inputs an operator that you don't check for such as %, ^ or $.
A second problem with this function is that it is difficult to add a new operator/operation.
An alternate implementation that could solve both these problems would be to use std::map or std::unordered_map that uses a character or string as a Key and has a pointer to a function as the mapped return type. | {
"domain": "codereview.stackexchange",
"id": 43671,
"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++, math-expression-eval",
"url": null
} |
java, programming-challenge, linked-list, interview-questions, cache
Title: Leetcode #146. LRUCache solution in Java (Doubly Linked List + HashMap)
Question: Problem Statement
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
Solution
This problem can be solved by implementing the Cache as a doubly linked list with head and tail pointers. This gives us constant time access to the head and tail of the Cache. For constant time access to all other nodes we can create a hashmap processMap which maps a key to its corresponding node in the Cache. Now, we can access any node in the linkedlist in constant time.
public void put(int key, int value) - First we check if there already exists an entry with the same key in the Cache. If it does then we remove this old entry from the processMap and the linked list. After this we insert the new entry at the end of the linked list.
public int get(int key) - We lookup the processMap and if there's an entry for the given key, we output the value of the node, remove the node from its current position and insert it at the end of the list. Otherwise, we return -1.
class ProcessNode {
private int key, value;
private ProcessNode previous, next; | {
"domain": "codereview.stackexchange",
"id": 43672,
"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, programming-challenge, linked-list, interview-questions, cache",
"url": null
} |
java, programming-challenge, linked-list, interview-questions, cache
public ProcessNode(int key, int value) {
this.key = key;
this.value = value;
}
public int getKey() {
return key;
}
public int getValue() {
return value;
}
public void setNext(ProcessNode next) {
this.next = next;
}
public ProcessNode getNext() {
return next;
}
public void setPrevious(ProcessNode previous) {
this.previous = previous;
}
public ProcessNode getPrevious() {
return previous;
}
}
class LRUCache {
private int size = 0;
private int capacity;
private ProcessNode head = null;
private ProcessNode tail = null;
private Map<Integer, ProcessNode> processMap = new HashMap<>();
public LRUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
ProcessNode processNode = processMap.get(key);
if (processNode == null) {
return -1;
}
remove(processNode);
addLast(processNode);
return processNode.getValue();
}
private void remove(ProcessNode processNode) {
if (processNode == null) {
return;
}
if ((processNode != head) && (processNode != tail)) {
processNode.getPrevious().setNext(processNode.getNext());
processNode.getNext().setPrevious(processNode.getPrevious());
} else {
if (processNode == head) {
head = processNode.getNext();
if (head != null) {
head.setPrevious(null);
}
}
if (processNode == tail) {
tail = processNode.getPrevious();
if (tail != null) {
tail.setNext(null);
}
}
}
size--;
processMap.remove(processNode.getKey());
}
private void removeFirst() {
remove(head);
} | {
"domain": "codereview.stackexchange",
"id": 43672,
"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, programming-challenge, linked-list, interview-questions, cache",
"url": null
} |
java, programming-challenge, linked-list, interview-questions, cache
private void removeFirst() {
remove(head);
}
private void addLast(ProcessNode processNode) {
if (size == capacity) {
removeFirst();
}
if (tail != null) {
tail.setNext(processNode);
processNode.setPrevious(tail);
tail = processNode;
} else {
head = processNode;
tail = processNode;
}
size++;
processMap.put(processNode.getKey(), processNode);
}
public void put(int key, int value) {
ProcessNode existingNode = processMap.get(key);
if (existingNode != null) {
remove(existingNode);
}
ProcessNode newProcessNode = new ProcessNode(key, value);
addLast(newProcessNode);
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
Please review my code and let me know if there's room for improvement.
Answer: Information hiding
If ProcessNode is only used by LRUCache,
then it's an implementation detail that's best hidden from other classes.
Instead of a local class, it would be better as a private static inner class.
Encapsulation and separation of concerns
LRUCache does multiple things:
Enforce a maximum number of key value pairs
Linked list operations
The linked list operations could be delegated to a dedicated class with remove(ListNode), removeFirst(ListNode), add(ListNode) methods.
With this reorganization, the implementation of LRUCache's main methods can focus on enforcing the bound on the number of entries, and be overall more clear and easier to understand, without having to follow through multiple methods the state changes of nodes, the map, and the size:
public int get(int key) {
ListNode node = nodeMap.get(key);
if (node == null) {
return -1;
}
list.remove(node);
list.add(node); | {
"domain": "codereview.stackexchange",
"id": 43672,
"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, programming-challenge, linked-list, interview-questions, cache",
"url": null
} |
java, programming-challenge, linked-list, interview-questions, cache
if (node == null) {
return -1;
}
list.remove(node);
list.add(node);
return node.getValue();
}
public void put(int key, int value) {
ListNode newNode = new ListNode(key, value);
list.add(newNode);
ListNode oldNode = nodeMap.put(key, newNode);
if (oldNode != null) {
list.remove(oldNode);
} else if (nodeMap.size() > capacity) {
ListNode eldest = list.removeFirst();
nodeMap.remove(eldest.getKey());
}
}
Naming
ProcessNode is just a node in a linked list.
I find name "Process" a bit confusing.
I recommend renaming to ListNode.
Minor technical improvements
There's no need to manage size manually, the map of nodes already has that information.
Some values are only assigned once, so they can be final,
such as capacity, key, value.
The getters and setters are overkill for the node class without plans of future extensions. Especially when moved inside an inner LinkedList class. There's no real need here for such verbose boilerplate code. | {
"domain": "codereview.stackexchange",
"id": 43672,
"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, programming-challenge, linked-list, interview-questions, cache",
"url": null
} |
c#, .net, file, file-system, portability
Title: File Abstraction Library
Question: This library is a layer of abstraction over file operations in C#. It aims to provide easy file IO syntax, and implicit error handling behaviors, to ensure robustness in scenarios including, but not limited to:
No file name supplied
Incorrect path supplied
File name is supplied without the path
But not only for error handling, it is written to make it more convenient for quick programs, like prototyping or demoing with C#. And to make file IO, and simple managing of state, easier.
This can be used for text files, and well as binary objects. And can run on multiple operating systems.
Here is the source code: Github
This is the demo project, that further illustrates the purpose, and syntax:
public class Demo
{
public static void Main()
{
//Simple operation with easy syntax. This can be done with any object.
4096.ToFile();
FileAbstraction.DisplayFile();
//Library will search for this file, as the location is not given.
8192.ToFile(@"..\Bas3 tw0 numb3r5.txt");
FileAbstraction.DisplayFile("Bas3 tw0 numb3r5.txt");
//A more complex search
"This was found in my user folder".ToFile(@$"C:\Users\{Environment.UserName}\Downloads\\" + "myFile.txt");
FileAbstraction.DisplayFile("myFile.txt");
//An even more complex search, here the caller supplied an incorrect path. (Drive does not exist)
"You found me, event though an incorrect path was given!"
.ToFile("X:\\I hide here.txt");
FileAbstraction.DisplayFile("I hide here.txt"); | {
"domain": "codereview.stackexchange",
"id": 43673,
"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, file, file-system, portability",
"url": null
} |
c#, .net, file, file-system, portability
//Also a search here. In this case, the file the caller wants, is on another drive (than what the app is running on).
//NOTE: This will only work, if you computer has another drive.
"You found me on another drive!".ToFile(@"E:\And I hide here.txt");
FileAbstraction.DisplayFile("And I hide here.txt");
//Serialization/De-Serialization of objects.
var c = new Computer();
c.ToFile();
var savedC = FileAbstraction.ReadBinFile<Computer>();
Console.WriteLine(savedC.Name);
}
}
internal class Computer
{
public Computer()
{
Name = Environment.MachineName;
_description = RuntimeInformation.ProcessArchitecture;
}
public string Name { get; set; }
private Architecture _description;
}
This the "main" part of the library, in the sense that it contains the methods called by the client code:
/// <summary>
/// For File => Object
/// </summary>
public static class FileAbstraction
{
public static T ReadBinFile<T>() where T : new()
{
var allFiles = Directory.GetFiles(Directory.GetCurrentDirectory());
var latestFile = allFiles.Max(x => File.GetLastWriteTime(x));
var path = new FilePath(allFiles.Where(x => (File.GetLastWriteTime(x) == latestFile)).Single()); | {
"domain": "codereview.stackexchange",
"id": 43673,
"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, file, file-system, portability",
"url": null
} |
c#, .net, file, file-system, portability
try
{
TextReader reader = new StreamReader(path.FileName);
var fileContents = reader.ReadToEnd();
var payload = JsonConvert.DeserializeObject<T>(fileContents);
return payload is null ? new T() : payload;
}
catch
{
return new T();
}
}
public static string ReadFile()
{
var allFiles = Directory.GetFiles(Directory.GetCurrentDirectory());
var latestFile = allFiles.Max(x => File.GetLastWriteTime(x));
var fileName = allFiles.Where(x => (File.GetLastWriteTime(x) == latestFile)).Single();
var file = new FileObject(fileName);
return File.ReadAllText(file.FileName);
}
public static string ReadFile(string input)
{
//name or path
if (Validation.IsDirectory(input))
{
var path = new FilePath(input);
try
{
return File.ReadAllText(path.FileName);
}
catch
{
return path.SearchRead();
}
}
else
{
var name = new FileName(input);
var allFiles = Directory.GetFiles(Directory.GetCurrentDirectory());
var match = allFiles.FirstOrDefault(x => x.Contains(name.FileName)); | {
"domain": "codereview.stackexchange",
"id": 43673,
"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, file, file-system, portability",
"url": null
} |
c#, .net, file, file-system, portability
return match is null ? name.SearchRead() : File.ReadAllText(match);
}
}
public static void DisplayFile() => Console.WriteLine(ReadFile());
public static void DisplayFile(string input) => Console.WriteLine(ReadFile(input));
}
/// <summary>
/// For Object => File
/// </summary>
public static class FileExtensions
{
private static void WriteToFile<T>(T o, FilePath path)
{
if (o is not null)
{
if (o.GetType() == typeof(string))
{
if (path.FileName.Contains(".txt"))
{
try
{
File.WriteAllText(path.FileName, o.ToString());
}
catch(DirectoryNotFoundException)
{
File.WriteAllText(Directory.GetCurrentDirectory() + Validation.SlashChar + Path.GetFileName(path.FileName), o.ToString());
}
}
else
{
File.WriteAllText(path.FileName + ".txt", o.ToString());
}
}
else
{
File.WriteAllBytes(path.FileName, o.ObjectToByteArray());
}
}
}
public static void ToFile<T>(this T o)
{
FilePath filePath = new FilePath(AppDomain.CurrentDomain.BaseDirectory + @$"{Validation.SlashChar}{Environment.UserName}");
WriteToFile(o, filePath); | {
"domain": "codereview.stackexchange",
"id": 43673,
"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, file, file-system, portability",
"url": null
} |
c#, .net, file, file-system, portability
}
public static void ToFile<T>(this T o, string input)
{
if (Validation.IsDirectory(input))
{
var path = new FilePath(input);
WriteToFile(o, path);
}
else
{
var fileName = new FileName(input);
var path = new FilePath(AppDomain.CurrentDomain.BaseDirectory + @$"{fileName.FileName}");
WriteToFile(o, path);
}
}
}
This Data class, contains logic for special data types, and operations related to file IO:
abstract internal class DirectoryItem
{
public string FileName => _fileName is null ? "" : _fileName;
protected string? _fileName;
protected string CorrectedFileName(string fileName)
{
if (Validation.IsWindows() && (fileName.IndexOfAny(Validation.InvalidWindowsChars) != -1))
{
foreach (char c in fileName)
{
if (Validation.InvalidWindowsChars.Contains(c)) { fileName.Replace(c.ToString(), ""); }
}
}
return fileName;
}
protected string TrimmedFileName(string fileName)
{
return fileName.Length > Validation.MaxFileNameLength ? fileName.Substring((fileName.Length - 1) - Validation.MaxFileNameLength, Validation.MaxFileNameLength) : fileName; //Trim file if too long, avoiding file system error
}
}
internal class FileName : DirectoryItem
{
public FileName(string name)
{
name = Validation.IsDirectory(name) ? Path.GetFileName(name) : name;
name = CorrectedFileName(name);
name = TrimmedFileName(name);
_fileName = name;
}
}
internal class FilePath : DirectoryItem
{
public FilePath(string filePath)
{
filePath = CorrectedFileName(filePath); | {
"domain": "codereview.stackexchange",
"id": 43673,
"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, file, file-system, portability",
"url": null
} |
c#, .net, file, file-system, portability
if(filePath.Length > Validation.MaxDirectoryLength)
{
FileName name = new FileName(Path.GetFileName(filePath).Substring(0,Validation.MaxDirectoryLength));
var dir = Path.GetDirectoryName(filePath);
_fileName = dir + Validation.SlashChar + name.FileName;
}
else
{
_fileName = filePath;
}
}
}
internal class FileObject : DirectoryItem
{
private string _fileExtensionText;
private FileType _type;
public FileObject(string fileName)
{
_fileName = fileName;
if (fileName.Length > 3)
{
_type = fileName.Substring(fileName.Length - 4, 4) == ".txt" ? FileType.text : FileType.binary;
}
else
{
_type = FileType.binary;
}
_fileExtensionText = fileName.Contains('.') ? fileName.Substring(fileName.LastIndexOf('.')) : "";
}
public FileType Type => _type;
}
enum FileType
{
text,
binary
}
internal static class DataOperationExensions
{
public static byte[] ObjectToByteArray<T>(this T o)
{
if (o == null)
return new byte[] { }; | {
"domain": "codereview.stackexchange",
"id": 43673,
"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, file, file-system, portability",
"url": null
} |
c#, .net, file, file-system, portability
return Encoding.UTF8.GetBytes(System.Text.Json.JsonSerializer.Serialize(o, GetJsonSerializerOptions()));
}
private static JsonSerializerOptions GetJsonSerializerOptions()
{
return new JsonSerializerOptions()
{
PropertyNamingPolicy = null,
WriteIndented = true,
AllowTrailingCommas = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
}
internal static string SearchRead(this DirectoryItem directoryItem)
{
var fileName = Validation.IsDirectory(directoryItem.FileName)
? directoryItem.FileName.Substring(directoryItem.FileName.LastIndexOf(Validation.SlashChar) + 1, (directoryItem.FileName.Length - 1) - (directoryItem.FileName.LastIndexOf(Validation.SlashChar) + 1))
: directoryItem.FileName;
var startDir = Directory.GetCurrentDirectory();
//Search deeper
var subDirectories = Directory.GetDirectories(startDir, "*", SearchOption.AllDirectories);
foreach (var subDirectory in subDirectories)
{
foreach (var filePath in Directory.GetFiles(subDirectory))
{
var name = new FileName(filePath);
if (name.FileName == fileName) return File.ReadAllText(filePath);
}
}
var drives = DriveInfo.GetDrives();
var thisDrive = drives.Where(x => x.Name == startDir.Substring(0, 3)).Single();
//Search back
var currentDir = startDir;
do
{
currentDir = Path.GetFullPath(Path.Combine(currentDir, ".."));
foreach (var filePath in Directory.GetFiles(currentDir))
{
var name = new FileName(filePath);
if (name.FileName == fileName) return File.ReadAllText(filePath);
}
} while (currentDir != thisDrive.Name); | {
"domain": "codereview.stackexchange",
"id": 43673,
"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, file, file-system, portability",
"url": null
} |
c#, .net, file, file-system, portability
} while (currentDir != thisDrive.Name);
//Search all drives
foreach (var drive in drives)
{
if (drive.IsReady)
{
var resultOnDrive = WalkDirectoryTree(new DirectoryInfo(drive.Name), fileName);
if (resultOnDrive.Length > 0)
return resultOnDrive;
}
}
return ""; //File not found
}
private static string WalkDirectoryTree(System.IO.DirectoryInfo root, string fileName)
{
System.IO.FileInfo[] files = null;
System.IO.DirectoryInfo[] subDirs = null;
// First, process all the files directly under this folder
try
{
files = root.GetFiles("*.*");
}
catch (UnauthorizedAccessException)
{
}
catch (System.IO.DirectoryNotFoundException)
{
}
if (files != null)
{
foreach (System.IO.FileInfo fi in files)
{
if (fi.Name == fileName) return File.ReadAllText(fi.FullName);
}
subDirs = root.GetDirectories();
foreach (System.IO.DirectoryInfo dirInfo in subDirs)
{
// Resursive call for each subdirectory.
if (!(dirInfo.Name == "Windows" || dirInfo.Name == "Program Files(x86)" || dirInfo.Name == "Program Files")) //Skip system folders, they are large and the user file is probably not here.
{
WalkDirectoryTree(dirInfo, fileName);
}
}
}
return "";
}
} | {
"domain": "codereview.stackexchange",
"id": 43673,
"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, file, file-system, portability",
"url": null
} |
c#, .net, file, file-system, portability
This validation class, is primarily used by the Data class:
internal class Validation
{
internal static bool IsDirectory(string s) => s.Contains(SlashChar);
internal static int MaxFileNameLength => IsWindows() ? ((IsLongPathsEnabled()) ? 32767 : 255) : 255;
internal static int MaxDirectoryLength => IsLinux() ? 4096 : 260;
internal static char SlashChar => IsWindows() ? '\\' : '/';
internal static char[] InvalidWindowsChars => new char[] { '<', '>', ':', '"', '/', '|', '?', '*' };
internal static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
internal static bool IsLinux() => RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
internal static bool IsLongPathsEnabled()
{
var key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\FileSystem");
if (key is null)
{
return false;
}
var regVal = key.GetValue("LongPathsEnabled");
if (regVal is null)
{
return false;
}
return (int)regVal > 0;
}
}
Answer: Okay, here are some quick random thoughts:
in the places where there is stuff.Where(something).Single() (or .First(), etc.), just remove the .Where(something) and put something in the parameter of the Single(): stuff.Single(something).
there are a couple places where you have a string as @$"stuff{other_stuff}" where there's no need for the @ because the code doesn't escape any characters or embed literal cr/lfs. Just remove it. The $ is necessary though as they are templated strings.
if o.GetType() == typeof(string) - simply replace with if o is string. In fact, then the previous line if o is not null is not needed at all.
The using statement: a number of types, specifically I/O types, implement the IDisposable interface and therefore must be wrapped in a using construct. For example: | {
"domain": "codereview.stackexchange",
"id": 43673,
"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, file, file-system, portability",
"url": null
} |
c#, .net, file, file-system, portability
TextReader reader = new StreamReader(path.FileName);
var fileContents = reader.ReadToEnd();
var payload = JsonConvert.DeserializeObject<T>(fileContents);
return payload is null ? new T() : payload;
should be
string fileContents;
using (TextReader reader = new StreamReader(path.FileName))
{
fileContents = reader.ReadToEnd();
}
var payload = JsonConvert.DeserializeObject<T>(fileContents);
return payload is null ? new T() : payload;
Minor, but improves readability: when you have a construct such as something.Max(x => Method(x)), it can be simplified as a "method group" to something.Max(Method).
in FileObject, get rid of the class member variable _type and make the property Type an "automatic property": public FileType Type { get; } and just assign directly to the property in the constructor.
the enum FileType should follow standard naming conventions and be PascalCased: Text, Binary. Further, you may want to prepend Unknown just to be able to code against that scenario if your code receives a 0 (zero) accidentally.
Always add braces {} around the body of an if or else, even if it is one single statement. This future-proofs a whole class of mistakes when needing to add to that body.
In class Computer, I don't see a need for the Name property to have a setter since the constructor fills it out. In fact, make both members automatic read-only properties:
public string Name { get; }
public Architecture Description { get; }
I know the Main program is just an example, but consider Path.Combine() rather than hard-coding backslashes like C:\\users\\ etc. Similarly, in class Validation, the SlashChar property is already implemented in .NET as Path.DirectorySeparatorChar.
This may change in the future, but I don't believe the operating system will change while the program is running, so the two methods | {
"domain": "codereview.stackexchange",
"id": 43673,
"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, file, file-system, portability",
"url": null
} |
c#, .net, file, file-system, portability
internal static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
internal static bool IsLinux() => RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
could be rewritten as properties
internal static bool IsWindows { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
internal static bool IsLinux { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
and forego calling the runtime information methods repeatedly.
Empty catch blocks are generally a cause of heartache. I like to add something in there, even if it's just for my own debugging purposes:
catch (SomeKindOfException ex)
{
System.Diagnostics.Debug.WriteLine($"Swallowed exception: {ex}");
}
Method WalkDirectoryTree is very Windows-specific as it doesn't skip Linux "system" folders and will erroneously skip Linux folders with those names. .NET helps you with this, and I'd rewrite part of that method slightly to remove the hard-coding:
var specialFolders = Enum.GetValues(typeof(Environment.SpecialFolder)).Cast<Environment.SpecialFolder>().Select(Environment.GetFolderPath).ToList();
foreach (System.IO.DirectoryInfo dirInfo in subDirs)
{
// Recursive call for each subdirectory.
if (!specialFolders.Contains(dirInfo.FullName))
{
WalkDirectoryTree(dirInfo, fileName);
}
}
new byte[] { } can be replaced with Array.Empty<byte>(); which won't create a new object that will get GC'd later.
var x = something is null ? blah : something (or something == null) can be replaced with "null coalescing operator": var x = something ?? blah.
This loop, as written, in CorrectedFileName does nothing:
foreach (char c in fileName)
{
if (Validation.InvalidWindowsChars.Contains(c))
{
fileName.Replace(c.ToString(), "");
}
} | {
"domain": "codereview.stackexchange",
"id": 43673,
"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, file, file-system, portability",
"url": null
} |
c#, .net, file, file-system, portability
because strings are immutable and String.Replace() returns a string. Flip the loop around:
foreach (char c in Validation.InvalidWindowsChars)
{
if (fileName.Contains(c))
{
fileName = fileName.Replace(c.ToString(), string.Empty);
}
}
better yet, use LINQ:
foreach (var c in Validation.InvalidWindowsChars.Where(c => fileName.Contains(c)))
{
fileName = fileName.Replace(c.ToString(), string.Empty);
}
There's probably a bit more if I dig deeper, but this seems like a good start. | {
"domain": "codereview.stackexchange",
"id": 43673,
"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, file, file-system, portability",
"url": null
} |
beginner, php, html, image
Title: Generating responsive image html with php? | {
"domain": "codereview.stackexchange",
"id": 43674,
"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": "beginner, php, html, image",
"url": null
} |
beginner, php, html, image
Question: As a beginner in php, I welcome you feedback on improving or simplifying the following php code that generates this responsive image html (image sizes and formats are auto-generated using Gulp). For example, is having three nested foreach loops bad practice?
Generated HTML:
<figure>
<picture>
<source media="(orientation: portrait)" type="image/avif"
srcset="assets/img/faith/faith-3x4-xs.avif 576w, assets/img/faith/faith-3x4-sm.avif 768w, assets/img/faith/faith-3x4-md.avif 992w, assets/img/faith/faith-3x4-lg.avif 1200w, assets/img/faith/faith-3x4-xl.avif 1400w, assets/img/faith/faith-3x4-xxl.avif 2048w">
<source media="(orientation: portrait)" type="image/webp"
srcset="assets/img/faith/faith-3x4-xs.webp 576w, assets/img/faith/faith-3x4-sm.webp 768w, assets/img/faith/faith-3x4-md.webp 992w, assets/img/faith/faith-3x4-lg.webp 1200w, assets/img/faith/faith-3x4-xl.webp 1400w, assets/img/faith/faith-3x4-xxl.webp 2048w">
<source media="(orientation: portrait)" type="image/jpg"
srcset="assets/img/faith/faith-3x4-xs.jpg 576w, assets/img/faith/faith-3x4-sm.jpg 768w, assets/img/faith/faith-3x4-md.jpg 992w, assets/img/faith/faith-3x4-lg.jpg 1200w, assets/img/faith/faith-3x4-xl.jpg 1400w, assets/img/faith/faith-3x4-xxl.jpg 2048w">
<source media="(orientation: landscape)" type="image/avif"
srcset="assets/img/faith/faith-3x2-xs.avif 576w, assets/img/faith/faith-3x2-sm.avif 768w, assets/img/faith/faith-3x2-md.avif 992w, assets/img/faith/faith-3x2-lg.avif 1200w, assets/img/faith/faith-3x2-xl.avif 1400w, assets/img/faith/faith-3x2-xxl.avif 2048w">
<source media="(orientation: landscape)" type="image/webp"
srcset="assets/img/faith/faith-3x2-xs.webp 576w, assets/img/faith/faith-3x2-sm.webp 768w, assets/img/faith/faith-3x2-md.webp 992w, assets/img/faith/faith-3x2-lg.webp 1200w, assets/img/faith/faith-3x2-xl.webp 1400w, assets/img/faith/faith-3x2-xxl.webp 2048w"> | {
"domain": "codereview.stackexchange",
"id": 43674,
"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": "beginner, php, html, image",
"url": null
} |
beginner, php, html, image
<source media="(orientation: landscape)" type="image/jpg"
srcset="assets/img/faith/faith-3x2-xs.jpg 576w, assets/img/faith/faith-3x2-sm.jpg 768w, assets/img/faith/faith-3x2-md.jpg 992w, assets/img/faith/faith-3x2-lg.jpg 1200w, assets/img/faith/faith-3x2-xl.jpg 1400w, assets/img/faith/faith-3x2-xxl.jpg 2048w">
<img src="assets/img/faith/faith-3x2-lg.jpg" width="1200" height="800" alt="Earth Day, Victoria, BC">
</picture>
</figure> | {
"domain": "codereview.stackexchange",
"id": 43674,
"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": "beginner, php, html, image",
"url": null
} |
beginner, php, html, image
Php code:
<?
$image= [
'name' => 'faith',
'srcset' =>
[
'sizes' =>
[
'size' => ['xs','sm','md','lg','xl','xxl'],
'vw' => [ 576, 768, 992, 1200, 1400, 2048 ]
],
'ratio' => ['portrait' => '3x4','landscape' => '3x2' ],
'format' => ['avif', 'webp','jpg']
],
'caption' => 'Earth Day, Victoria, BC',
];
$sizes = array_combine($image['srcset']['sizes']['size'], $image['srcset']['sizes']['vw']);
?>
<figure>
<picture>
<?
foreach ($image['srcset']['ratio'] as $orientation => $ratio):
$basePath = "assets/img/{$image['name']}/{$image['name']}-{$ratio}";
foreach($image['srcset']['format'] as $format): $comma = '';
$source = "<source media=\"(orientation: ${orientation})\" type = \"image/{$format}\" srcset=\"";
foreach($sizes as $size => $vw):
$source .= "{$comma}{$basePath}-{$size}.{$format} {$vw}w"; $comma=', ';
endforeach;
echo $source .= '">';
endforeach;
endforeach;
?>
<img src="<?=$basePath?>-lg.jpg" width="1200" height="800" alt="<?=$image['caption']?>">
</picture>
</figure>
Answer: Personally, I don't like that much logic in the template. Even hate it. The code becomes unreadable. In such a case I would rather move all this intricate logic into the PHP part, doing some preprocessing that will result in the plain array, so the end code would be like this
<figure>
<picture>
<?php foreach ($image['srcset'] as $row): ?>
<source media="(orientation: <?=$row['orientation']?>)" type="image/<?=$row['format']?>" srcset="<?=$row['srcset'] ?>">
<?php endforeach ?>
<img src="<?=$imagePath?>lg.jpg" width="1200" height="800" alt="<?=$image['caption']?>">
</picture>
</figure> | {
"domain": "codereview.stackexchange",
"id": 43674,
"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": "beginner, php, html, image",
"url": null
} |
beginner, php, html, image
The preprocessing PHP code should be exactly like your current code, just collecting the data into array instead of echoing it
$new = [];
foreach ($image['srcset']['ratio'] as $orientation => $ratio) {
$basePath = "assets/img/{$image['name']}/{$image['name']}-{$ratio}";
foreach($image['srcset']['format'] as $format) {
$srcset = '';
foreach($sizes as $size => $vw) {
$srcset .= $srcset ? ",":"";
$srcset .= "{$basePath}-{$size}.{$format} {$vw}w";
}
$new[] = [
'orientation' => $orientation,
'format' => $format,
'srcset' => $srcset,
];
}
}
another possibility is to write sort of a helper function
<figure>
<picture>
<?php foreach ($image['srcset']['ratio'] as $orientation => $ratio): ?>
<?php foreach($image['srcset']['format'] as $format): ?>
<source media="(orientation: <?=$orientation?>)" type="image/<?=$format?>" srcset="<?=getsrcset($image, $ratio, $format, $key)">
<?php endforeach ?>
<? endforeach ?>
<img src="<?=$imagePath?>lg.jpg" width="1200" height="800" alt="<?=$image['caption']?>">
</picture>
</figure>
And two generic suggestions:
short open tag is forbidden, always use <?php instead of <?
do not neglect the code indentation. The proper formatting is very important, it helps to understand what does the code do | {
"domain": "codereview.stackexchange",
"id": 43674,
"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": "beginner, php, html, image",
"url": null
} |
c++, linked-list, library
Title: Linked List implementation in c++ with all functions
Question: I wrote my implementation to Linked List. And I tried to implement all the functions in the standard library list in CPP! I need a review for it to improve it and improve my coding skill. I also will put this implementation on my GitHub account.
Thanks in advance.
//======================================================
// Author : Omar_Hafez
// Created : 31 July 2022 (Sunday) 5:19:10 AM
//======================================================
#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>
template <typename T>
class List {
public:
struct Node {
T value;
std::shared_ptr<Node> front, back;
Node (T data, std::shared_ptr<Node> ptr, std::shared_ptr<Node> ptr2)
: value(data), front(ptr), back(ptr2) {}
};
private:
int elementsCount = 0;
std::shared_ptr<Node> begin_ptr, end_ptr, itr, tmp_ptr, header, teller;
public:
List() :
header(std::make_shared<Node>((T)NULL, nullptr, nullptr)),
teller(std::make_shared<Node>((T)NULL, nullptr, nullptr)) {}
struct Iterator {
std::shared_ptr<Node> operator*() const { return m_ptr; }
Iterator operator++(int) {
if(!m_ptr) return *this;
if(!(m_ptr->front) || indxOfPtr < 0) {
indxOfPtr++;
return *this;
}
Iterator tmp = *this;
(*this) = m_ptr->front;
return tmp;
}
Iterator operator--(int) {
if(!m_ptr) return *this;
if(!(m_ptr->back) || indxOfPtr > 0) {
indxOfPtr--;
return *this;
}
Iterator tmp = *this;
(*this) = m_ptr->back;
return tmp;
} | {
"domain": "codereview.stackexchange",
"id": 43675,
"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++, linked-list, library",
"url": null
} |
c++, linked-list, library
friend bool operator== (const Iterator& a, const Iterator& b) { return a.m_ptr == b.m_ptr; };
friend bool operator!= (const Iterator& a, const Iterator& b) { return a.m_ptr != b.m_ptr; };
std::shared_ptr<Node> m_ptr;
int indxOfPtr;
Iterator(std::shared_ptr<Node> ptr) : m_ptr(ptr), indxOfPtr(0) {}
};
struct RIterator {
std::shared_ptr<Node> operator*() const { return m_ptr; }
RIterator operator++(int) {
if(!m_ptr) return *this;
if(!(m_ptr->back) || indxOfPtr > 0) {
indxOfPtr--;
return *this;
}
RIterator tmp = *this;
(*this) = m_ptr->back;
return tmp;
}
RIterator operator--(int) {
if(!m_ptr) return *this;
if(!(m_ptr->front) || indxOfPtr < 0) {
indxOfPtr++;
return *this;
}
RIterator tmp = *this;
(*this) = m_ptr->front;
return tmp;
}
Iterator to_Iterator() {
return Iterator(m_ptr->front);
}
friend bool operator== (const RIterator& a, const RIterator& b) { return a.m_ptr == b.m_ptr; };
friend bool operator!= (const RIterator& a, const RIterator& b) { return a.m_ptr != b.m_ptr; };
std::shared_ptr<Node> m_ptr;
int indxOfPtr;
RIterator(std::shared_ptr<Node> ptr) : m_ptr(ptr), indxOfPtr(0) {}
};
void advance(List<T>::Iterator &it, int val) {
while(*it && it != end() && val > 0) {
it++;
val--;
}
} | {
"domain": "codereview.stackexchange",
"id": 43675,
"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++, linked-list, library",
"url": null
} |
c++, linked-list, library
void createFirstNode(T t) {
begin_ptr = std::make_shared<Node>(t, nullptr, nullptr);
end_ptr = begin_ptr;
header->front = begin_ptr;
begin_ptr->back = header;
teller->back = end_ptr;
end_ptr->front = teller;
elementsCount++;
}
Iterator begin() { return Iterator(begin_ptr); }
Iterator end() {
if(!end_ptr) return Iterator(end_ptr);
return Iterator(end_ptr->front);
}
RIterator rbegin() {
return RIterator(end_ptr);
}
RIterator rend() {
if(!begin_ptr) return RIterator(begin_ptr);
return RIterator(begin_ptr->back);
}
enum ListOpStatus { FailedListEmpty = -1, FailedListFull = -2, FailedInvalidIterator = -3, OK = 1 };
ListOpStatus assign(T t, int count) {
if(count == 0) return OK;
begin_ptr = std::make_shared<Node>(t, nullptr, nullptr);
header->front = begin_ptr;
begin_ptr->back = header;
itr = begin_ptr;
for(int i = 1; i < count; i++) {
itr->front = std::make_shared<Node>(t, nullptr, nullptr);
tmp_ptr = itr;
itr = itr->front;
itr->back = tmp_ptr;
}
end_ptr = itr;
teller->back = end_ptr;
end_ptr->front = teller;
elementsCount = count;
end_ptr = itr;
return OK;
}
// assigning from another list
ListOpStatus assign(List<T>::Iterator it1, List<T>::Iterator it2) {
if(!(*it1) || !(*it2)) return FailedInvalidIterator;
begin_ptr = std::make_shared<Node> ((*it1)->value, nullptr, nullptr);
header->front = begin_ptr;
begin_ptr->back = header; | {
"domain": "codereview.stackexchange",
"id": 43675,
"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++, linked-list, library",
"url": null
} |
c++, linked-list, library
header->front = begin_ptr;
begin_ptr->back = header;
elementsCount = 1;
itr = begin_ptr;
it1++;
while(it1 != it2) {
itr->front = std::make_shared<Node>((*it1)->value, nullptr, nullptr);
tmp_ptr = itr;
itr = itr->front;
itr->back = tmp_ptr;
it1++;
elementsCount++;
}
end_ptr = itr;
teller->back = end_ptr;
end_ptr->front = teller;
return OK;
}
// assigning from another reversed list
ListOpStatus assign(List<T>::RIterator it1, List<T>::RIterator it2) {
if(!(*it1) || !(*it2)) return FailedInvalidIterator;
begin_ptr = std::make_shared<Node> ((*it1)->value, nullptr, nullptr);
header->front = begin_ptr;
begin_ptr->back = header;
elementsCount = 1;
itr = begin_ptr;
it1++;
while(it1 != it2) {
itr->front = std::make_shared<Node>((*it1)->value, nullptr, nullptr);
tmp_ptr = itr;
itr = itr->front;
itr->back = tmp_ptr;
it1++;
elementsCount++;
}
end_ptr = itr;
teller->back = end_ptr;
end_ptr->front = teller;
return OK;
}
// assigning from vector
ListOpStatus assign(typename std::vector<T>::iterator it1, typename std::vector<T>::iterator it2) {
if(!(*it1) || !(*it2)) return FailedInvalidIterator;
begin_ptr = std::make_shared<Node> (*it1, nullptr, nullptr);
header->front = begin_ptr;
begin_ptr->back = header; | {
"domain": "codereview.stackexchange",
"id": 43675,
"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++, linked-list, library",
"url": null
} |
c++, linked-list, library
header->front = begin_ptr;
begin_ptr->back = header;
elementsCount = 1;
itr = begin_ptr;
it1++;
while(it1 != it2) {
itr->front = std::make_shared<Node>(*it1, nullptr, nullptr);
tmp_ptr = itr;
itr = itr->front;
itr->back = tmp_ptr;
it1++;
elementsCount++;
}
end_ptr = itr;
teller->back = end_ptr;
end_ptr->front = teller;
return OK;
}
// assigning from reversed vector
ListOpStatus assign(typename std::vector<T>::reverse_iterator it1, typename std::vector<T>::reverse_iterator it2) {
if(!(*it1) || !(*it2)) return FailedInvalidIterator;
begin_ptr = std::make_shared<Node> (*it1, nullptr, nullptr);
header->front = begin_ptr;
begin_ptr->back = header;
elementsCount = 1;
itr = begin_ptr;
it1++;
while(it1 != it2) {
itr->front = std::make_shared<Node>(*it1, nullptr, nullptr);
tmp_ptr = itr;
itr = itr->front;
itr->back = tmp_ptr;
it1++;
elementsCount++;
}
end_ptr = itr;
teller->back = end_ptr;
end_ptr->front = teller;
return OK;
}
ListOpStatus push_back(T t) {
if(empty()) {
createFirstNode(t);
return OK;
}
tmp_ptr = end_ptr;
end_ptr->front = std::make_shared<Node>(t, nullptr, nullptr);
end_ptr = end_ptr->front;
end_ptr->back = tmp_ptr;
teller->back = end_ptr;
end_ptr->front = teller;
elementsCount++;
return OK;
} | {
"domain": "codereview.stackexchange",
"id": 43675,
"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++, linked-list, library",
"url": null
} |
c++, linked-list, library
elementsCount++;
return OK;
}
ListOpStatus push_front(T t) {
if(empty()) {
createFirstNode(t);
return OK;
}
tmp_ptr = begin_ptr;
begin_ptr->back = std::make_shared<Node>(t, nullptr, nullptr);
begin_ptr = begin_ptr->back;
begin_ptr->front = tmp_ptr;
header->front = begin_ptr;
begin_ptr->back = header;
elementsCount++;
return OK;
}
ListOpStatus pop_back() {
if(elementsCount == 1) {
clear();
return OK;
}
if(empty()) {
return FailedListEmpty;
}
end_ptr = end_ptr->back;
end_ptr->front = nullptr;
teller->back = end_ptr;
end_ptr->front = teller;
elementsCount--;
return OK;
}
ListOpStatus pop_front() {
if(elementsCount == 1) {
clear();
return OK;
}
if(empty()) {
return FailedListEmpty;
}
begin_ptr = begin_ptr->front;
begin_ptr->back = nullptr;
header->front = begin_ptr;
begin_ptr->back = header;
elementsCount--;
return OK;
}
ListOpStatus swap(List<T>::Iterator it1, List<T>::Iterator it2) {
if(!(*it1) || !(*it2)) return FailedInvalidIterator;
T tmp = (*it1)->value;
(*it1)->value = (*it2)->value;
(*it2)->value = tmp;
return OK;
}
ListOpStatus swap(List<T>::RIterator it1, List<T>::RIterator it2) {
if(!(*it1) || !(*it2)) return FailedInvalidIterator;
return swap(it1.to_Iterator(), it2.to_Iterator());
} | {
"domain": "codereview.stackexchange",
"id": 43675,
"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++, linked-list, library",
"url": null
} |
c++, linked-list, library
ListOpStatus insert(List<T>::Iterator it, T t) {
if(empty()) {
createFirstNode(t);
return OK;;
}
if(*it == begin_ptr) {
push_front(t);
return OK;
}
if(*it == end()) {
push_back(t);
return OK;
}
if(!(*it)) return FailedInvalidIterator;
tmp_ptr = std::make_shared<Node>(t, (*it), (*it)->back);
tmp_ptr->back->front = tmp_ptr;
(*it)->back = tmp_ptr;
elementsCount++;
return OK;
}
ListOpStatus insert(List<T>::RIterator it, T t) {
return insert(it.to_Iterator(), t);
}
ListOpStatus sort() {
T a[elementsCount];
int ind = 0;
for(auto it = begin(); it != end(); it++) {
a[ind++] = (*it)->value;
}
std::sort(a, a+elementsCount);
clear();
for(int x : a) {
push_back(x);
}
return OK;
}
ListOpStatus unique() {
if(empty()) return OK;
T a[elementsCount];
int ind = 0;
for(auto it = begin(); it != end(); it++) {
a[ind++] = (*it)->value;
}
std::sort(a, a+elementsCount);
int sz = elementsCount;
clear();
push_back(a[0]);
for(int i = 1; i < sz; i++) {
if(a[i] == a[i-1]) continue;
push_back(a[i]);
}
return OK;
} | {
"domain": "codereview.stackexchange",
"id": 43675,
"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++, linked-list, library",
"url": null
} |
c++, linked-list, library
ListOpStatus erase(List<T>::Iterator it) {
if(!(*it) || it == end()) return FailedInvalidIterator;
if(empty()) return OK;
if(*it == header || *it == teller) return FailedInvalidIterator;
if(elementsCount == 1) {
clear();
return OK;
}
itr = *it;
if(itr == begin_ptr) {
pop_front();
return OK;
}
if(itr == end_ptr) {
pop_back();
return OK;
}
tmp_ptr = itr->front;
auto tmp = itr->back;
tmp->front = tmp_ptr;
tmp_ptr->back = tmp;
elementsCount--;
return OK;
}
ListOpStatus erase(List<T>::RIterator it) {
return erase(List<T>::Iterator((*it)->front));
}
ListOpStatus erase(List<T>::Iterator it1, List<T>::Iterator it2) {
while(it1 != it2) {
erase(it1);
it1++;
}
return OK;
}
ListOpStatus erase(List<T>::RIterator it1, List<T>::RIterator it2) {
return(erase(it2.to_Iterator(), it1.to_Iterator()));
}
ListOpStatus remove_if(bool (*function) (T& t)) {
for(itr = begin_ptr; itr; itr = itr->front) {
if((*function) (itr->value)) {
erase(List<T>::Iterator(itr));
if(empty()) return OK;
}
}
return OK;
}
ListOpStatus remove(T t) {
for(itr = begin_ptr; itr; itr = itr->front) {
if(itr->value == t) {
erase(List<T>::Iterator(itr));
if(empty()) return OK;
}
}
return OK;
} | {
"domain": "codereview.stackexchange",
"id": 43675,
"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++, linked-list, library",
"url": null
} |
c++, linked-list, library
void clear() {
begin_ptr = nullptr;
end_ptr = nullptr;
itr = nullptr;
tmp_ptr = nullptr;
teller->back = nullptr;
header->front = nullptr;
elementsCount = 0;
}
bool empty() const {
return elementsCount == 0;
}
bool full() const {
return 0;
}
int size() const {
return elementsCount;
}
void traverseList(void (*function) (T& t)) {
for(itr = begin_ptr; itr; itr = itr->front) {
(*function)(itr->value);
}
}
};
Answer:
Using std::shared_ptr to manage your nodes is very heavyweight.
I would expect a container to look for efficiency, or provide seriously extended service.
std::size_t is the designated index-type. int can be too small.
De-referencing an iterator is expected to result in an element-reference, at worst a proxy-object. A pointer to the element, or even worse the containing node, defies all expectations.
If you change your nodes and list to have a single member containing both links, you can remove many irregularities from your code.
Consider whether you really want to write your own reverse-iterator, instead of just adapting a normal iterator with std::make_reverse_iterator(). The semantics are slightly but significantly different.
You don't support emplacing, nor move-semantics. That makes your list very inefficient or unusable for many element-types.
Dropping the start- and end-pointers, as you do in .clear() and the implicit .~List() leaves all nodes still interconnected with shared pointers. Thus, you have a memory-leak.
I'm not a fan of your error-codes. They mostly seem to cover operator failure, which should really either abort the program or be full UB. Thus I expect code using it will mostly fail to check.
Also, allocation/construction can still throw anyway. | {
"domain": "codereview.stackexchange",
"id": 43675,
"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++, linked-list, library",
"url": null
} |
c++, linked-list, library
Handling those points leads to a major rewrite, so I end it here. | {
"domain": "codereview.stackexchange",
"id": 43675,
"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++, linked-list, library",
"url": null
} |
c, library, socket, wrapper, client
Title: The receive function for telnet client
Question: This is a follow up question to Send and receive functions for telnet client.
I am designing a simple wrapper around the telnet client using libtelnet for text-based communication to a telnet server. Please see my implementation below:
#include <arpa/inet.h>
#include <ctype.h>
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>
#ifdef HAVE_ZLIB
#include "zlib.h"
#endif
#include "libtelnet.h"
#define BUFFER_SIZE 512
// following typedefs should be a part of header file
typedef struct addrinfo Addrinfo;
typedef struct sockaddr_in Sockaddr;
typedef struct timeval Timeval;
static telnet_t *telnet;
static const telnet_telopt_t telopts[] = {
{TELNET_TELOPT_ECHO, TELNET_WONT, TELNET_DO},
{TELNET_TELOPT_TTYPE, TELNET_WILL, TELNET_DONT},
{TELNET_TELOPT_COMPRESS2, TELNET_WONT, TELNET_DO},
{TELNET_TELOPT_MSSP, TELNET_WONT, TELNET_DO},
{-1, 0, 0}};
static int send_all(int sock_fd, char *buffer, size_t size) {
int ret_val = -1; // default value
// send data
while (size > 0) {
if ((ret_val = send(sock_fd, buffer, size, 0)) == -1) {
fprintf(stderr, "send() failed: %s\n", strerror(errno));
exit(-1);
} else if (ret_val == 0) {
fprintf(stderr, "send() unexpectedly returned 0\n");
exit(-1);
}
// update pointer and size to see if we've got more to send
buffer += ret_val;
size -= ret_val;
}
return ret_val;
}
static void event_handler(telnet_t *telnet, telnet_event_t *event,
void *user_data) {
int sock_fd = *(int *)user_data;
char msg[event->data.size + 1]; | {
"domain": "codereview.stackexchange",
"id": 43676,
"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, library, socket, wrapper, client",
"url": null
} |
c, library, socket, wrapper, client
switch (event->type) {
// data received
case TELNET_EV_DATA:
strncpy(msg, event->data.buffer, event->data.size);
msg[event->data.size] = '\0';
printf("Response: [%s]\n", msg);
break;
// data must be sent
case TELNET_EV_SEND:
send_all(sock_fd, event->data.buffer, event->data.size);
break;
// request to enable local feature (or receipt)
case TELNET_EV_DO:
break;
// demand to disable local feature (or receipt)
case TELNET_EV_DONT:
break;
// respond to TTYPE commands
case TELNET_EV_TTYPE:
// respond with our terminal type, if requested
if (event->ttype.cmd == TELNET_TTYPE_SEND) {
telnet_ttype_is(telnet, getenv("TERM"));
}
break;
// respond to particular subnegotiations
case TELNET_EV_SUBNEGOTIATION:
break;
// error
case TELNET_EV_ERROR:
fprintf(stderr, "ERROR: %s\n", event->error.msg);
exit(EXIT_FAILURE);
default:
// ignore
break;
}
}
static Timeval configure_timeout() {
// timeout 1 sec
Timeval time;
time.tv_sec = 1;
time.tv_usec = 0;
return time;
}
static void try_send(int sock_fd, char *cmd, size_t cmd_len) {
fd_set write_fd;
// clear the set ahead of time
FD_ZERO(&write_fd);
// add our descriptors to the set
FD_SET(sock_fd, &write_fd);
Timeval tv = configure_timeout();
int ret_val = select(sock_fd + 1, NULL, &write_fd, NULL, &tv);
if (ret_val == -1) {
// error occurred in select()
perror("select");
} else if (ret_val == 0) {
fprintf(stderr, "Timeout occurred!\n");
} else {
// send the request
if (FD_ISSET(sock_fd, &write_fd)) {
// print only for debugging
char msg[cmd_len + 1];
strncpy(msg, cmd, cmd_len);
msg[cmd_len] = '\0';
printf("Request: [%s]\n", msg);
telnet_send(telnet, cmd, cmd_len);
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43676,
"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, library, socket, wrapper, client",
"url": null
} |
c, library, socket, wrapper, client
static int try_recv(int sock_fd, char *buffer) {
int ret_val = -1; // default value
fd_set read_fd;
// clear the set ahead of time
FD_ZERO(&read_fd);
// add our descriptors to the set
FD_SET(sock_fd, &read_fd);
Timeval tv = configure_timeout();
ret_val = select(sock_fd + 1, &read_fd, NULL, NULL, &tv);
if (ret_val == -1) {
// error occurred in select()
perror("select");
} else if (ret_val == 0) {
fprintf(stderr, "Timeout occurred!\n");
} else {
// receive the response
if (FD_ISSET(sock_fd, &read_fd)) {
if ((ret_val = recv(sock_fd, buffer, BUFFER_SIZE, 0)) > 0) {
telnet_recv(telnet, buffer, ret_val);
} else if (ret_val == 0) {
fprintf(stderr, "connection has been closed.\n");
exit(-1);
} else {
fprintf(stderr, "recv() failed: %s\n", strerror(errno));
exit(-1);
}
}
}
return ret_val;
}
static int make_connection() {
int ret_val;
int sock_fd;
Sockaddr socket_addr;
Addrinfo *addr_info;
Addrinfo addr_hints;
const char *servname = "50000";
const char *hostname = "192.168.102.85";
// look up server host
memset(&addr_hints, 0, sizeof(addr_hints));
addr_hints.ai_family = AF_UNSPEC;
addr_hints.ai_socktype = SOCK_STREAM;
if ((ret_val = getaddrinfo(hostname, servname, &addr_hints, &addr_info)) != 0) {
fprintf(stderr, "getaddrinfo() failed for %s: %s\n", hostname, gai_strerror(ret_val));
return -1;
}
// create server socket
if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
fprintf(stderr, "socket() failed: %s\n", strerror(errno));
return -1;
}
// bind server socket
memset(&socket_addr, 0, sizeof(socket_addr));
socket_addr.sin_family = AF_INET;
if (bind(sock_fd, (struct sockaddr *)&socket_addr, sizeof(socket_addr)) == -1) {
fprintf(stderr, "bind() failed: %s\n", strerror(errno));
close(sock_fd);
return -1;
} | {
"domain": "codereview.stackexchange",
"id": 43676,
"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, library, socket, wrapper, client",
"url": null
} |
c, library, socket, wrapper, client
// connect
if (connect(sock_fd, addr_info->ai_addr, addr_info->ai_addrlen) == -1) {
fprintf(stderr, "connect() failed: %s\n", strerror(errno));
close(sock_fd);
return -1;
}
// free address lookup info
freeaddrinfo(addr_info);
return sock_fd;
}
int main() {
int num_bytes;
char buffer[BUFFER_SIZE];
int sock_fd = make_connection();
if (sock_fd < 0) {
return EXIT_FAILURE;
}
// initialize telnet box
telnet = telnet_init(telopts, event_handler, 0, &sock_fd);
// our server returns "Welcome\r\n" upon a successful connection
num_bytes = try_recv(sock_fd, buffer);
printf("Bytes: [%d]\n", num_bytes); // print bytes only for debugging
// the second recv is needed
num_bytes = try_recv(sock_fd, buffer);
printf("Bytes: [%d]\n", num_bytes); // print bytes only for debugging
// define our commands
const char *commands[] = {"INIT\r\n",
"READ PT3\r\n",
"READ PT4\r\n",
"REM PT3\r\n"};
size_t commands_count = sizeof(commands) / sizeof(*commands);
size_t i;
for (i = 0; i < commands_count; i++) {
try_send(sock_fd, commands[i], strlen(commands[i]));
num_bytes = try_recv(sock_fd, buffer);
printf("Bytes: [%d]\n", num_bytes); // print bytes only for debugging
}
// clean up
telnet_free(telnet);
close(sock_fd);
return EXIT_SUCCESS;
}
Output
I added a few print statements for debugging purposes. Please see below the complete log displayed on the terminal.
ravi@dell:~/telnet$ ./my_client
Response: [Welcome
]
Bytes: [8]
Response: [
]
Bytes: [2]
Request: [INIT
]
Response: [OK
]
Bytes: [4]
Request: [READ PT3
]
Response: [OK
]
Bytes: [4]
Request: [READ PT4
]
Response: [OK
]
Bytes: [4]
Request: [REM PT3
]
Response: [OK
]
Bytes: [4]
ravi@dell:~/telnet$
Problems
Most of the issues are related to how the response is received. Below are the problems I am facing: | {
"domain": "codereview.stackexchange",
"id": 43676,
"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, library, socket, wrapper, client",
"url": null
} |
c, library, socket, wrapper, client
The server returns "Welcome\r\n" upon a successful connection. Unfortunately, to grab the welcome message, the receive function, i.e., try_recv, is called twice, which does not look so nice. I think that the receive function should be able to collect the complete response in one call.
After every send command, the receive function is called. If I do not call receive function, the program prints "connection has been closed.". In this situation, I have to restart the telnet server forcefully. Can a client ignore the response from a telnet server, or is it compulsory to receive? If it is mandatory, then I think that send function should call receive.
The receive function prints the response on the terminal. Instead, I would like to return it as a string. | {
"domain": "codereview.stackexchange",
"id": 43676,
"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, library, socket, wrapper, client",
"url": null
} |
c, library, socket, wrapper, client
Answer: Error handling
You are already doing a lot of error handling, which is good, but you need to pay a little bit more attention to what kind of errors functions can return, and how to respond to them.
For example, send() can return -1 in situations that are recoverable. You should check errno, and if that is set to EINTR, you should retry sending the same data. Also, if send() returns zero, that is technically not an error, and you should just treat that as a short send, see also this StackOverflow question.
Also note that for many socket functions, only -1 is an error, and other negative numbers might be valid. So in main(), check for sock_fd == -1 instead of sock_fd < 0.
Exit codes
The proper exit code to signal an error is usually 1, not -1. Even better is to use EXIT_SUCCESS and EXIT_FAILURE instead of numeric codes.
Consider removing the typedefs
A typedef can be nice to reduce the amount of typing you have to do. If you use it for your own structs, it is usually fine. But consider not making typedefs for types from the system headers. The reason is that if someone else reads your code, and sees Timeval, they will wonder: "is this some custom made type, or just a typedef for struct timeval?" And then they have to search through the code to get an answer. If you just keep using struct timeval consistently, it's one less thing to think about.
Also, what is Sockaddr? Given the other two typedefs, one might assume it is equal to struct sockaddr, but in fact it's struct sockaddr_in. It would have been better to name it Sockaddr_in, but not making the typedef would have avoided this issue.
Call recv() in a loop
Just like you had to use a loop in send_all() because send() might not send all data in one go, recv() might not receive everything the peer sent in one go, thus you must implement a loop and keep receiving until you got all the data you want. | {
"domain": "codereview.stackexchange",
"id": 43676,
"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, library, socket, wrapper, client",
"url": null
} |
c, library, socket, wrapper, client
You might think, if the server calls send() once, shouldn't the client be able to call recv() once and receive everything that was sent? The issue though is that whatever you send() has to go on the network in packets. If you use a SOCK_STREAM socket with an IPv4 or IPv6 address, the connection will use the TCP protocol. This will treat all data that is being sent as one contiguous stream, and it will chop that stream up in to packets in a way that makes it efficient to traverse the network, but it does not have to correspond to how much you send() at a time. Furthermore, for IPv4 even routers between the sender and receiver can chop up the packets even more, called packet fragmentation. On the receiving side, there is also no guarantee how much you will recv() in one go; maybe it is however much there was in one network packet, but the kernel can buffer more or less than one packet.
So you have to treat the incoming data as a stream of bytes, and be able to handle recv() returning a random amount of bytes from that stream at a time. The only guarantee you have is that the bytes are received in the same order as they were sent.
Thus, if you want to receive a complete line, you need to write a loop that will call recv() and each time checks if you received a newline character. But you also be prepared to receive more than a single line.
Instead of doing all this yourself, you can use the POSIX function fdopen() to create a FILE * from a file descriptor, and then use fgets() or getline() to read a line at a time. The drawback is that those functions don't handle timeouts. | {
"domain": "codereview.stackexchange",
"id": 43676,
"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, library, socket, wrapper, client",
"url": null
} |
c, library, socket, wrapper, client
Unfortunately, to grab the welcome message, the receive function, i.e., try_recv, is called twice, which does not look so nice. I think that the receive function should be able to collect the complete response in one call.
The problem is how to determine that you got the "complete response". If you know that the initial response is two lines, you can just try receiving until you have gotten at least two newline characters.
Don't assume getaddrinfo() will return an IPv4 address
If you call getaddrinfo() with AF_UNSPEC, it can return IPv6 addresses. Don't make assumptions about the address family, and instead create the socket with the right address family like so:
if ((sock_fd = socket(addr_info->ai_family, addr_info->ai_socktype, addr_info->ai_protocol) == -1) {
...
}
Don't bind() outgoing sockets
You don't need to bind() outgoing sockets. If you call connect() and the local end is not bound yet, the kernel will do it for you automatically. You then also don't have to worry about providing a socket_addr. | {
"domain": "codereview.stackexchange",
"id": 43676,
"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, library, socket, wrapper, client",
"url": null
} |
c++, c++17
Title: A toy application of pub/sub using C++ for self-learning
Question: Firstly, I apologize for the lengthy post. I was not sure which code I should include.
In practice of c++, I am writing a toy application for pub/sub using c++17. To keep things simple, both the publisher and subscriber are on the same OS Process, and thus only a deque is needed to store messages.
I don't use a Singleton, but rather I create a shared_ptr and std::move it across constructors.
I attempt to use c++17 idioms where ever they are known to me; for example in std::scoped_lock vs std::lock_guard, and lambda over std::bind. If there are any other places in the code that can be upgraded, please note it.
One of my main struggles with c++ is the lack of clarity on which techniques are c++11 and which are more modern.
Along these lines, is any aware why the Google C++ style guide prohibits the use of c++20? Especially since c++23 is fast approaching.
The first class acts as the Queue, with call back mechanism.
#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <memory>
#include <mutex>
#include <deque>
#include <thread>
#include <functional>
namespace tareeqav {
namespace messaging {
class QueueBase {
public:
virtual ~QueueBase() {};
};
template<class T>
class Queue : public QueueBase {
public:
Queue() {
std::thread t = std::thread([this]() {
this->RunCallbacks();
});
t.detach();
};
void EnqueueMessage(std::shared_ptr<T const> message);
const int length() { return messages_.size(); };
template<typename CallbackT>
void RegisterCallback(CallbackT &&callback);
void RunCallbacks(); | {
"domain": "codereview.stackexchange",
"id": 43677,
"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++, c++17",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.