text
stringlengths
1
2.12k
source
dict
c#, winforms drAddItem = dtTemp.NewRow(); //Populating the retrieved values into the related cells of the DataRow drAddItem["Party"] = col1Value.ToString(); drAddItem["Bill No."] = col2Value.ToString(); drAddItem["Bill Date"] = col3Value.ToString(); drAddItem["Amount"] = col4Value.ToString(); drAddItem["Due Date"] = col5Value.ToString(); drAddItem["Remarks"] = col6Value.ToString(); drAddItem["Payment Released on"] = col8Value.ToString(); dtTemp.Rows.Add(drAddItem); The retrieving logic can be simplified really easily by using a loop for(int column = 1; column < 9; column++) { if (column == 7) continue; object columnValue = workSheet.Cells[row, column].Text; } The mapping logic can be simplified by utilizing an array to preserve the ordering var columnMapping = new [] { "Party", "Bill No.", "Bill Date", "Amount", "Due Date", "Remarks", "Payment Released on" }; Now you need to combine these together var columnMapping = new[] { "Party", "Bill No.", "Bill Date", "Amount", "Due Date", "Remarks", "Payment Released on" }; drAddItem = dtTemp.NewRow(); dtTemp.Rows.Add(drAddItem); var columnIterator = columnMapping.GetEnumerator(); for (int column = 1; column < 9; column++) { if (column == 7) continue; columnIterator.MoveNext(); object columnValue = workSheet.Cells[row, column].Text; drAddItem[columnIterator.Current.ToString()] = columnValue.ToString(); } I would like to warn you that this code is fragile since the column indexer and the column mapping are living separately. It means if you modify one of them you have to remember to modify the other one as well. There will be no compile error that you have modified one but you did not update the other.
{ "domain": "codereview.stackexchange", "id": 42766, "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#, winforms", "url": null }
c#, winforms UPDATE Populating columnMapping from dtTemp's Columns You can retrieve the column names from the DataTable and use that to populate the mappings in the following way: var dtTemp = new DataTable(); dtTemp.Columns.AddRange(new[] { new DataColumn("Party"), new DataColumn("Bill No."), new DataColumn("Bill Date"), new DataColumn("Amount"), new DataColumn("Due Date"), new DataColumn("Remarks"), new DataColumn("Payment Released on"), }); var columnMapping = dtTemp.Columns .Cast<DataColumn>() .Select(col => col.ColumnName); Because Columns is a DataColumnCollection you can't issue Linq queries directly against it you need to Cast it first.
{ "domain": "codereview.stackexchange", "id": 42766, "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#, winforms", "url": null }
c++, performance, strings, c++14, classes Title: TString - An implementation of std::string Question: I wanted to make a feature rich string in C++. Similar to one in python. I am using C++14. I have not added much yet, I just want to get my code reviewed to ensure I am going the right way. Features: Negative indexing.(.at(-i)) (Slices coming soon) Mutable string, no fixed length. Can delete according to index.(.pop(i)) Justify text. (.rjust, .ljust, center) Questions Am I using new and delete properly? Is my class structure correct? Is my TString optimized well? Am I missing any optimized library functions, but instead implementing myself? tstring.h #pragma once #include <iostream> #include <stdexcept> char char_lower(const char); char char_upper(const char); class TString { private: char* __list; unsigned int __len; public: TString(); TString(const char); TString(const char*, unsigned int); TString(unsigned int, const char); TString(const TString&); ~TString(); friend std::ostream& operator<<(std::ostream&, const TString&); char& operator[](unsigned int) const; bool operator==(const TString&) const; bool operator!=(const TString&) const; TString& operator=(const TString&); TString& operator+=(const TString&); TString& operator*=(unsigned int); TString operator+(const TString&) const; TString operator*(unsigned int) const; friend TString operator+(const char, const TString&); friend TString operator*(unsigned int, const TString&); unsigned int length() const; char& at(int) const; char& begin() const; char& end() const; void pop(int index); bool is_empty() const; TString lower() const; TString upper() const; TString reverse() const; TString ljust(unsigned int, const char) const; TString center(unsigned int, const char) const; TString rjust(unsigned int, const char) const; bool contains(const char) const; bool contains(const TString&) const;
{ "domain": "codereview.stackexchange", "id": 42767, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++14, classes", "url": null }
c++, performance, strings, c++14, classes bool contains(const char) const; bool contains(const TString&) const; int index(const char) const; int index(const TString&) const; unsigned int count(const char) const; unsigned int count(const TString&) const; }; str.cpp #include "tstring.h" char char_lower(const char char_) { switch (char_) { case 'A': return 'a'; case 'B': return 'b'; case 'C': return 'c'; case 'D': return 'd'; case 'E': return 'e'; case 'F': return 'f'; case 'G': return 'g'; case 'H': return 'h'; case 'I': return 'i'; case 'J': return 'j'; case 'K': return 'k'; case 'L': return 'l'; case 'M': return 'm'; case 'N': return 'n'; case 'O': return 'o'; case 'P': return 'p'; case 'Q': return 'q'; case 'R': return 'r'; case 'S': return 's'; case 'T': return 't'; case 'U': return 'u'; case 'V': return 'v'; case 'W': return 'w'; case 'X': return 'x'; case 'Y': return 'y'; case 'Z': return 'z'; default: return char_; } }
{ "domain": "codereview.stackexchange", "id": 42767, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++14, classes", "url": null }
c++, performance, strings, c++14, classes char char_upper(const char char_) { switch (char_) { case 'a': return 'A'; case 'b': return 'B'; case 'c': return 'C'; case 'd': return 'D'; case 'e': return 'E'; case 'f': return 'F'; case 'g': return 'G'; case 'h': return 'H'; case 'i': return 'I'; case 'j': return 'J'; case 'k': return 'K'; case 'l': return 'L'; case 'm': return 'M'; case 'n': return 'N'; case 'o': return 'O'; case 'p': return 'P'; case 'q': return 'Q'; case 'r': return 'R'; case 's': return 'S'; case 't': return 'T'; case 'u': return 'U'; case 'v': return 'V'; case 'w': return 'W'; case 'x': return 'X'; case 'y': return 'Y'; case 'z': return 'Z'; default: return char_; } } TString::TString(): __list{new char[0]}, __len{0} {}; TString::TString(const char char_): __list{new char[1]}, __len{1} { __list[0] = char_; } TString::TString(const char* char_array, unsigned int len): __list{new char[len]}, __len{len} { for (int i = 0; i < len; ++i) { __list[i] = char_array[i]; } } TString::TString(unsigned int len, const char char_): __list{new char[len]}, __len{len} { for (int i = 0; i < len; ++i) { __list[i] = char_; } } TString::TString(const TString& str): __list{new char[str.length()]}, __len{str.length()} { for (int i = 0; i < str.length(); ++i) { __list[i] = str[i]; } } TString::~TString() { delete[] __list; delete &__len; } std::ostream& operator<<(std::ostream& os, const TString& str) { for (int i = 0; i < str.length(); ++i) { os << str.__list[i]; } return os; } char& TString::operator[](unsigned int index) const { return __list[index]; }
{ "domain": "codereview.stackexchange", "id": 42767, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++14, classes", "url": null }
c++, performance, strings, c++14, classes char& TString::operator[](unsigned int index) const { return __list[index]; } bool TString::operator==(const TString& str) const { if (__len != str.length()) { return false; } for (int i = 0; i < str.length(); ++i) { if (__list[i] != str[i]) { return false; } } return true; } bool TString::operator!=(const TString& str) const { if (__len != str.length()) { return true; } for (int i = 0; i < str.length(); ++i) { if (__list[i] != str[i]) { return true; } } return false; } TString& TString::operator=(const TString& str) { delete[] __list; __len = str.length(); __list = new char[__len]; for (int i = 0; i < __len; ++i) { __list[i] = str[i]; } return *this; } TString& TString::operator+=(const TString& str) { if (__len == 0) { *this = str; } else { char copy_list[__len]; int copy_len = __len; for (int i = 0; i < copy_len; ++i) { copy_list[i] = __list[i]; } delete[] __list; __len += str.length(); __list = new char[__len]; for (int i = 0; i < copy_len; ++i) { __list[i] = copy_list[i]; } for (int i = 0; i < str.length(); ++i) { __list[copy_len + i] = str[i]; } } return *this; } TString& TString::operator*=(unsigned int x) { TString result(*this); if (__len == 0) { return *this; } for (int i = 1; i < x; ++i) { *this += *this; } return *this; } TString TString::operator+(const TString& str) const { TString result(*this); result += str; return result; } TString TString::operator*(unsigned int x) const { TString result(*this); result *= x; return result; }
{ "domain": "codereview.stackexchange", "id": 42767, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++14, classes", "url": null }
c++, performance, strings, c++14, classes TString operator+(const char char_, const TString& str) { TString result(char_); result += str; return result; } TString operator*(unsigned int x, const TString& str) { return (str * x); } TString operator""_t(const char array[], unsigned int len) { return TString(array, len); } TString operator""_t(const char char_) { return TString(char_); } unsigned int TString::length() const { return __len; } char& TString::at(int index) const { if (index >= 0 && index < __len) { return (*this)[index]; } else if (index < 0 && index >= -__len) { return (*this)[index + __len]; } throw std::out_of_range("Index out of range!"); } char& TString::begin() const { if (__len == 0) { throw std::domain_error("String is empty!"); } return (*this)[0]; } char& TString::end() const { if (__len == 0) { throw std::domain_error("String is empty!"); } return (*this)[__len - 1]; } void TString::pop(int index) { if (index < 0) { index += __len; } char* new_list = new char[__len - 1]; for (int i = 0; i < index; ++i) { new_list[i] = __list[i]; } for (int i = index + 1; i < __len; ++i) { new_list[i - 1] = __list[i]; } delete[] __list; __list = new_list; } bool TString::is_empty() const { return (__len == 0); } TString TString::upper() const { TString result(*this); for (int i = 0; i < __len; ++i) { result[i] = char_upper(__list[i]); } return result; } TString TString::lower() const { TString result(*this); for (int i = 0; i < __len; ++i) { result[i] = char_lower(__list[i]); } return result; } TString TString::reverse() const { TString result; for (int i = __len - 1; i >= 0; --i) { result += __list[i]; } return result; }
{ "domain": "codereview.stackexchange", "id": 42767, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++14, classes", "url": null }
c++, performance, strings, c++14, classes TString TString::ljust(unsigned int width, const char char_) const { if (width <= __len) { return *this; } int padding = width - __len; return *this + TString(padding, char_); } TString TString::center(unsigned int width, const char char_) const { if (width <= __len) return *this; int total_padding = width - __len; int rpad = total_padding / 2; int lpad = total_padding - rpad; return TString(rpad, char_) + *this + TString(lpad, char_); } TString TString::rjust(unsigned int width, const char char_) const { if (width <= __len) return *this; int padding = width - __len; return TString(padding, char_) + *this; } bool TString::contains(const char char_) const { for (int i = 0; i < __len; ++i) { if (__list[i] == char_) { return true; } } return false; } bool TString::contains(const TString& str) const { if (*this == str) { return true; } for (int i = 0; i < __len - str.length(); ++i) { for (int j = 0; j < str.length(); ++j) { if (__list[j + i] != str[j]) { break; } else if (j == str.length() - 1) { return true; } } } return false; } int TString::index(const char char_) const { for (int i = 0; i < __len; ++i) { if (__list[i] == char_) { return i; } } return -1; } int TString::index(const TString& str) const { if (*this == str) { return 0; } for (int i = 0; i < __len - str.length(); ++i) { for (int j = 0; j < str.length(); ++j) { if (__list[j + i] != str[j]) { break; } else if (j == str.length() - 1) { return i; } } } return -1; }
{ "domain": "codereview.stackexchange", "id": 42767, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++14, classes", "url": null }
c++, performance, strings, c++14, classes unsigned int TString::count(const char char_) const { unsigned int count = 0; for (int i = 0; i < __len; ++i) { if (__list[i] == char_) { ++count; } } return count; } unsigned int TString::count(const TString& str) const { unsigned int count = 0; if (*this == str) { ++count; return count; } for (int i = 0; i < __len - str.length(); ++i) { for (int j = 0; j < str.length(); ++j) { if (__list[j + i] != str[j]) { break; } else if (j == str.length() - 1) { ++count; } } } return count; } Basic use int main() { TString hello = "Hello, World!"_t; std::cout << hello << '\n'; } Thanks! Answer: Justify text. (.rjust, .ljust, center) That is becoming a "fat interface". These functions should be generic algorithms that can work with any string class, including yours, std::string, std::string_view, and even vectors, arrays, and C-style strings. They should not be members of this class. Am I using new and delete properly? Probably not. See ⧺C.149 — no naked new or delete. You ought to use std::vector for your underlying storage. Then you need only to implement the members that make it "string like" that are not available already in vector. char char_lower(const char); A top-level const on the parameter has no effect in this declaration. It has its normal meaning in the definition, but it's not part of the calling signature and should be omitted in the declaration. case 'A': return 'a'; case 'B': return 'b';
{ "domain": "codereview.stackexchange", "id": 42767, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++14, classes", "url": null }
c++, performance, strings, c++14, classes Holy cow! Are you expecting to compile and run with a bizarre character set like EBCDIC? Even EBCDIC (famous for having non-contiguous letters) has a constant offset between the corresponding upper and lowercase letters. char to_upper (char inchar) { if (!std::isalpha(static_cast<unsigned char>(inchar)) return inchar; // unchanged constexpr auto offset = 'a'-'A'; return char(inchar + offset); } Of course, this only works for ASCII characters. The constructors don't seem to match the meanings of the constructors on std::string. You should make them match, for drop-in compatibility and to avoid confusing people reading (or modifying) your code. Of course, you can have more constructors that std::string doesn't have. But the ones with the same meaning should be the same to call. You want to include others: convert from std::string and std::string_view, and a pair of iterators. char& operator[](unsigned int) const; No, that should not work. The const-ness of the container means that the elements are const. You are returning a mutable reference. You should have char operator[](unsigned int) const; // read-only if const char& operator[](unsigned int) &; // reference only on non-const lvalue char operator[](unsigned int) &&; // read-only for rvalue (temporary) too. Rather than unsigned int you should define an index type as a type alias inside your class. I suggest matching that of the underlying vector. TString operator+(const TString&) const; friend TString operator+(const char, const TString&);
{ "domain": "codereview.stackexchange", "id": 42767, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++14, classes", "url": null }
c++, performance, strings, c++14, classes TString operator+(const TString&) const; friend TString operator+(const char, const TString&); You should not need that second one. By making the operator+ a member, you get asymmetric behavior. The left argument must be of that class, and will not be found via implicit conversions. You normally should write these operators as non-members so both arguments are treated the same way. A non-member operator+ will have no trouble accepting both s+'c' and 'c'+s equally well. Normally, you implement operator+= as a member, then implement + very simply to call +=. char& begin() const; char& end() const; Huh? A char& doesn't work as an iterator. Your code compiles, right? Try using your class in a range-based for loop and see that it chokes rather than working as expected. for (char c : mystring) { ... } I think count is another candidate for not making it a member function. It should be a generic algorithm that works with any string-like type. for (int i = 0; i < len; ++i) { __list[i] = char_array[i]; } Don't write loops when standard algorithms already exist. As Stroustrup says, "Don't write code; use algorithms". This is just copy. But, if you use vector as the backing memory, you can just defer this to the corresponding constructor of vector. I see you only have a pointer and a length. There's no separate length for capacity. That means you'll have to re-allocate and copy every time the string changes. Using a vector will use a more performant memory management and automatically take care of the recopying when that is necessary. You can't convert given a C-style string alone. You should default the length to use strlen automatically. TString::TString(const TString& str): __list{new char[str.length()]}, __len{str.length()} { for (int i = 0; i < str.length(); ++i) { __list[i] = str[i]; } }
{ "domain": "codereview.stackexchange", "id": 42767, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++14, classes", "url": null }
c++, performance, strings, c++14, classes Again, outch. This is just copy. But, the work can be deferred to the underlying vector. You ask about optimal implementation: Besides the lack of a separate capacity measure, you should have a move constructor and move assignment operator, and a swap function. bool TString::operator==(const TString& str) const { if (__len != str.length()) { return false; } for (int i = 0; i < str.length(); ++i) { if (__list[i] != str[i]) { return false; } } return true; } <sigh> how about return __len==str.length() && std::equals(list,list+__len,str.list); Lesson: Know what's in the Library. Read through https://en.cppreference.com/w/cpp/algorithm bool TString::operator!=(const TString& str) const { if (__len != str.length()) { return true; } for (int i = 0; i < str.length(); ++i) { if (__list[i] != str[i]) { return true; } } return false; } Oh come on!! return !(*this==str); You should never do it any other way. (In C++20, this is automatic) TString& TString::operator+=(const TString& str) { if (__len == 0) { *this = str; } else { char copy_list[__len]; // Not Legal! int copy_len = __len; for (int i = 0; i < copy_len; ++i) { copy_list[i] = __list[i]; } delete[] __list; __len += str.length(); __list = new char[__len]; for (int i = 0; i < copy_len; ++i) { __list[i] = copy_list[i]; } for (int i = 0; i < str.length(); ++i) { __list[copy_len + i] = str[i]; } } return *this; }
{ "domain": "codereview.stackexchange", "id": 42767, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++14, classes", "url": null }
c++, performance, strings, c++14, classes First of all, the line char copy_list[__len]; is not even legal C++. A C-style VLA is a gcc extension supported in the C++ compiler. But why are you copying twice? You copy to copy_list and then copy it again into the allocated memory. I think you are confused about the __list memory only living in that member data, rather than being a pointer you can do anything with. Create a local variable for the new data. Copy into that. Then delete __list and assign __list = new_list;. You are also doing the copy loop again.... sure, you didn't know that there's a copy in the library already, but you already did this in your own code. Why can't you call a common place for copying the string contents? You should naturally think about making common code and not duplicating code. Maybe you've heard DRY: Don't Repeat Yourself. TString& TString::operator*=(unsigned int x) { TString result(*this); if (__len == 0) { return *this; } for (int i = 1; i < x; ++i) { *this += *this; } return *this; } Hmm, you duplicate the original string into result but then never use it! Do you have compiler warnings disabled, or are not paying attention to them? Reverse that situation: warnings are useful and informative. I would have thought this function repeats the original string x times. But it actually doubles the original string x times. That's an odd thing to do, IMO. And you're doing it inefficiently, allocating and deallocating and re-copying x times. You should figure out the size of the result, allocate that, and copy the original 2x times into it using a loop. char& TString::at(int index) const { if (index >= 0 && index < __len) { return (*this)[index]; } else if (index < 0 && index >= -__len) { return (*this)[index + __len]; } throw std::out_of_range("Index out of range!"); } Put your preconditions at the top. E.g. if (index > __len || index < -__len) throw...
{ "domain": "codereview.stackexchange", "id": 42767, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++14, classes", "url": null }
c++, performance, strings, c++14, classes Put your preconditions at the top. E.g. if (index > __len || index < -__len) throw... I can see how the "whatever's left" logic is handy in this particular case, but it's generally better to put preconditions at the top so it's worth going to a small amount of effort to arrange it that way. You're repeating the entire indexing operation when you only changed the value of the index. Put the condition around the smallest amount of code possible rather than repeating entire calls when only one argument changed. if (index<0) index += __len; return __list[index]; bool TString::is_empty() const Match the member names from the std::string class. In this case, put the implementation inline inside the class definition rather than in a separate CPP file. TString TString::reverse() const You don't even need that! std::reverse should work on your class. It doesn't right now because your begin/end are wonky, but when written properly you will be able to use all the library algorithms and other reusable code. Hmm, your function returns a new reversed string, rather than reversing in-place. That's confusing, as I expected a member function to reverse in-place. Anyway, it can be implemented as follows: TString TString::reverse() const { Tstring result (*this); std::reverse (result.__list,result.__list+result.__len); return result; } But you can see that morally we're implementing an in-place reverse, but artificially forcing it to be called on a copy. I'd say this is inefficient, copying twice. But it blows away your original code, which re-allocates and re-copies for every character in the string! You ask whether your code is optimal?? This is what you would call the opposite of that. contains functions, count functions: see Lesson above.
{ "domain": "codereview.stackexchange", "id": 42767, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++14, classes", "url": null }
c++, performance, strings, c++14, classes Lesson 2 You seem to be writing every function as if it's the only code that exists in this body of work. That is, it operates on the most primitive things directly. You should write code in hierarchical manner. Start with primitive routines that need to be implemented directly, but then other function can call the more primitive ones to do their work. This is commonly known as top-down design but when you're writing code it might be bottom-up implementation. Functions should be expressed in terms that are one level of detail deeper; not go all the way back down to the most primitive in every function. Even if you don't know the available library functions, or are writing something where library functions don't help you, you should be doing that with your own functions! Think hierarchy, not every function stands alone. Lesson 3 When writing a novel class that's like a common or standard class, but different in some way that warrants your own implementation, start by looking at the standard class. Look over all the members and use that as a starting point for your own. Edit it to change the things you are intentionally changing, remove the things that don't apply, and make notes where the behavior is different. Don't just make up everything from scratch. It should be easy and familiar to programmers, because they know the standard classes already. In your case, you should understand how C++ containers work, and make sure your implementation is a valid container. Lesson 4 "Feature Rich" might be misguided. I think you are actually meaning "fat interface", which is the antithesis of current best practices. A truly feature-rich string would refer to fundamental features of the string itself, not more functions that operate on strings.
{ "domain": "codereview.stackexchange", "id": 42767, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++14, classes", "url": null }
c++, performance, strings, c++14, classes Many of the things you want are already available, just not as members of the string class. Many are not so easy to call on a string (pre C++20). You might instead want to write a library of generic algorithms that take any string-like type as an argument, and call the standard algorithm where available and implement things where necessary. For example, you might write: template <typename Str> auto ljust (const Str& s, char pad, size_t width) { using RetType = ret_for<Str>::type; ⋮ }
{ "domain": "codereview.stackexchange", "id": 42767, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++14, classes", "url": null }
c++, performance, strings, c++14, classes The RetType line is a bit of template metaprogramming that lets you map the input type to a possibly different return type. This is to allow accepting a string_view and having that return a string. You might also have a second optional template argument to allow the user to specify the return type, optionally. If you want to be simpler and stick with standard string only, the functions that don't modify the argument but return a new string with the result should just return std::string and should accept a string_view (by value). std::string ljust (std::string_view s, char pad, size_t width) { std::string retval; const auto padding = s.size() >= width ? 0 : width - s.size(); retval.reserve (s.size()+padding); retval.resize (padding. pad); retval += s; return s; } For example look at Boost.StringAlgo, though that predates string_view and even C++11, so it does not show current best practices. Point is, making a separate library of non-member functions means you can use them with existing code, and have code that uses these functions be able to call other library functions and otherwise interoperate with other modules, since it still uses standard types! Fat interfaces are bad. A string class should have only what it needs to expose its feature set efficiently. Anything else can be written as a non-member that uses that string class, and additional functions like what you want will be just the same — you're not limited to what the class designer provided. final words Keep it up! Be ambitious in your projects, and keep learning. I look forward to your next effort.
{ "domain": "codereview.stackexchange", "id": 42767, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++14, classes", "url": null }
java Title: Reduce Optionals to throw an error once Question: I have the following response coming from a rest call and performing some logic based on what is returned. This is what I want. If the overall status code is NOT 200 OR If within the list of SimpleResponse, none of the SimpleResponse objects has a 200 httpCode, throw an error. Too much going on there, having an optional within another optional. And then throwing the same error at 2 different places. Is there a cleaner way to write this? These are the 2 related objects @Getter @Setter public class SimpleResponses { private List<SimpleResponse> simpleResponsesList; } @Getter @Setter public class SimpleResponse { private String httpCode; // ... other fields } Method calling rest call and throwing error if needed. public ResponseEntity<SimpleResponses> get() { HttpEntity<Object> httpEntity = this.getEntity(); // restTemplate is from Spring ResponseEntity<SimpleResponses> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, SimpleResponses.class); // START // This is the logic to throw error depending on output as mentioned above. // looking for a better way to write this. // if none of the object inside the list has 200 code, throw error Optional.ofNullable(responseEntity.getBody()) .map(SimpleResponses::getSimpleResponses) .ifPresent(response -> { Optional<SimpleResponse> simpleResponse = response.stream() .filter(responseStream -> responseStream.getHttpCode().equals("200")) .findAny(); if (!simpleResponse.isPresent()) { throw new CustomRuntimeException("Failed ..... "); // repetitive same error being thrown again below. } }); // if overall code is not 200, throw error too if (!responseEntity.getStatusCode().is2xxSuccessful()) { throw new CustomRuntimeException("Failed ..... "); }
{ "domain": "codereview.stackexchange", "id": 42768, "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", "url": null }
java // END return responseEntity; } Answer: I'm not really addressing your main concerns, but a few things stood out to me about your code. It seems upside down. I haven't used restTemplate, however since the http status code is in the header, I'd assume that you can check it before trying to process the response body. Since the status code check is the most straightforward and a lot of codes would indicate that there is no body, I would tend to check this first, then go on to validate the body. When you're processing the body, you only throw if there is a list of responses, none of which are status "200". This matches your description of the requirements, but is it really true? How come "null response body", and "null simpleResponsesList" are acceptable? Why is this different to an "empty simpleResponsesList"? Throwing the same error from different locations in a method isn't necessarily bad, if it is the cleanest way to achieve your desired outcome. If I had a method with three parameters that needed validated, I might throw InvalidParameterException three times, once for each parameter, probably with the message tailored to that parameter. In your code it seems like a failure in the high level call may indicate something completely different (such as a network/server error) and a non 200 code from one of the nested responses. You don't include CustomRuntimeException, or all of SimpleResponse, but I can certainly picture a scenario where I might want to include different information such as something to identify the request which a failed SimpleResponse is associated with.
{ "domain": "codereview.stackexchange", "id": 42768, "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", "url": null }
python, performance, python-3.x, multiprocessing Title: My code creates a soundboard that can assign a sound to a key on a keyboard while listening to keyboard strokes in parallel Question: My code works but I am looking for an efficient way to implement the idea with out having to repeat the same code block inside the function Recin() (record Input function is stated in the code) in order to assign a new key. I'm using windows for this project. here is the code: import playsound as ps import keyboard as kb import concurrent.futures def recin(): #record input and return a string based on each key it is a while loop because I want it to listen in parallel and the return key value. Return ,based on my research ,initiates the break function so the function will not continue after returning a value k0 = "." #example keys k1 = "e" x=0 while True: #in order to assign a key I need to create a code block that looks like the ones here if kb.is_pressed(k0): return k0 if kb.is_pressed(k1): return k1 #here is the part that plays sounds and assigns them to keys: def sp(file,key): #play a sound after receiving a string as an input then reinitiates the recin func in hopes of changing the f1.result value to avoid endless loop over the same sound global f1 #f1 is a processes that will start in parallel and will return the user input user_input = f1.result() if user_input == key: ps.playsound(file,False) user_input = "" with concurrent.futures.ProcessPoolExecutor() as executor: # rerun the parallel process after shutting down because once the code returns a value it will break the while loop by default f1 = executor.submit(recin) #here is how the code will look like while using the functions stated above: if __name__ == '__main__': with concurrent.futures.ProcessPoolExecutor() as executor: #intiates recin in parallel just to get the code working f1 = executor.submit(recin)
{ "domain": "codereview.stackexchange", "id": 42769, "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, python-3.x, multiprocessing", "url": null }
python, performance, python-3.x, multiprocessing while True: #sp() example sp("sound file","e") sp("another sound file",".") Answer: Here, I shall work with the assumption that the "playing sound" part works fine. Firstly, congratulations! The concept you came up with to resume the execution of the recin function is known as a continuation, and it is available in Python natively through generators and the yield keyword. Rewriting your code to use generators and still polling the keyboard: from time import sleep import keyboard as kb def recin(keys): while True: sleep(0.1) key_status = {key: kb.is_pressed(key) for key in keys} if any(key_status.values()): yield key_status def soundboard(keymap): for key_status in recin(keymap): for key, is_pressed in key_status.items(): if is_pressed: # kb.release(key) print(f"\n{key}: {keymap[key]}") if __name__ == "__main__": example_keymap = { 'e': "sound file", '.': "another sound file" } soundboard(example_keymap)
{ "domain": "codereview.stackexchange", "id": 42769, "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, python-3.x, multiprocessing", "url": null }
python, performance, python-3.x, multiprocessing Note that for purposes of testing I have replaced you ps.playsound(file, False) with a simple print statement with some debugging info. Also note the time.sleep(0.1) call, I found that while testing on Mac the keyboard package maybe somewhat buggy and was not clearing the is_pressed status fast enough, so I was getting repeat events. I guess initializing the ProcessPoolExecutors in your code is sufficiently slow that this doesn't become a problem. Note another design choice here: instead of creating separate key handlers running concurrently, I choose to poll the pressed status of all keys we are interested in and store it in a dictionary. However, this remains a sort-of wasteful approach, as the CPU has better things to do than sit around polling the keyboard. Thankfully, the keyboard package allows us to register event handlers, which are functions that can be made to run when a particular key is pressed. The scheduling of these handlers can now be left up to the module, and is no longer our problem! See this approach: from time import sleep import keyboard as kb def soundboard(keymap): for key in keymap: kb.on_press_key(key, lambda key_event: print(f"\n{key_event.name}: {keymap[key_event.name]}")) while True: try: sleep(0.05) except KeyboardInterrupt: break if __name__ == "__main__": example_keymap = { 'e': "sound file", '.': "another sound file" } soundboard(example_keymap)
{ "domain": "codereview.stackexchange", "id": 42769, "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, python-3.x, multiprocessing", "url": null }
python, performance, python-3.x, multiprocessing Now, you should agree that this is very simple! But it has a problem - as far as I can find out, this only allows handling a single keypress at a time (the backend is not capable of processing all the key events concurrently). You need the sleep call here too, otherwise since there is no background thread spawned for the keyboard event handlers, the program will quit immediately. Now, we have a case to use the ProcessPoolExecutor you had reached for earlier: from time import sleep from concurrent.futures import ProcessPoolExecutor as PoolExecutor import keyboard as kb def do_for_key(keymap, key): kb.on_press_key(key, lambda key_event: print(f"\n{key_event.name}: {keymap[key_event.name]}")) while True: sleep(0.005) def soundboard(keymap): with PoolExecutor() as pool: for key in keymap: pool.submit(do_for_key, keymap, key) if __name__ == "__main__": example_keymap = { 'e': "sound file", '.': "another sound file" } soundboard(example_keymap) However, now we have come full-circle to your original implementation - the sleep call excepted, this is almost fully equivalent to your original implementation. This, however, still doesn't solve the problem that multiple keys pressed together are not all considered (only the key pressed first will work, the other pressed keys won't do anything). With a ProcessPoolExecutor, I don't know why multiple pressed keys don't trigger events - I haven't studied the keyboard package in any depth. So to fix that, we come back to a combination of Solution 1 and Solution 2: from time import sleep import keyboard as kb keymap_count = None def do_for_key(pressed_key, keymap): global keymap_count if keymap_count is None: keymap_count = dict(zip(keymap, [0]*len(keymap))) for key in keymap: if kb.is_pressed(key): keymap_count[key] += 1 print(f"\n{key}: {keymap[key]}; {keymap_count[key]}")
{ "domain": "codereview.stackexchange", "id": 42769, "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, python-3.x, multiprocessing", "url": null }
python, performance, python-3.x, multiprocessing def soundboard(keymap): for key in keymap: kb.on_press_key(key, lambda key_event: do_for_key(key_event.name, keymap)) while True: try: sleep(0.05) except KeyboardInterrupt: break if __name__ == "__main__": example_keymap = { 'e': "sound file", '.': "another sound file" } soundboard(example_keymap) So, whenever we receive an event that any key we are interested in has been pressed, we check if any other keys of our interest are also pressed, and process them all together! keymap_count is a debugging variable for letting me know how many times a key has been pressed. The 2nd and 3rd examples may work for you on Windows, but macOS support by the keyboard library is experimental and the problems I have may not be ones you face. However, I do believe that the final solution is the most robust one for multiplatform support, and does not rely on something as heavyweight as ProcessPoolExecutors. An other minor note: You have comments explaining what recin does. Maybe put them in a docstring? I'm not going to make other comments around style and readability, there are other, more qualified contributors here who can help.
{ "domain": "codereview.stackexchange", "id": 42769, "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, python-3.x, multiprocessing", "url": null }
c#, .net, cryptography, openssl, ssl Title: .Net BouncyCastle - PKCS#3, PKCS#8 & PKCS#10 Generation as base64 Question: Reaserching BouncyCastle for C# is not for the faint of heart. After navigating an ocean of Java dead ends, I have arrived at the following code. I believe it's very useful for someone who wants to create these files in C# to use it anywhere. It basically generates the 3 files every webdev who uses NGINX http server would need to configure SSL certificates. I wanted to make sure some of this BouncyCastle code isn't outdated and if it could be streamlined and improved. There's no need for class implementations. Just pure, openssl equivalent, output. Take a look: // .NET Imports using System.Collections; using System.Text.RegularExpressions; // BouncyCastle for .NET Imports using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Pkcs; using Org.BouncyCastle.Security; class Program { static void Main(string[] args) { // RootLenght.RootLength1024 for testing only! // It's faster to visualize. Recommended is RootLenght.RootLength2048 GeneratePkcs3(RootLenght.RootLength1024); GeneratePkcs8Pkcs10("US", "Utah", "Salt Lake City", "XYZ Inc.", "IT Subdivision", "www.example.com", "admin@example.com", RootLenght.RootLength2048); }
{ "domain": "codereview.stackexchange", "id": 42770, "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, cryptography, openssl, ssl", "url": null }
c#, .net, cryptography, openssl, ssl } /// <summary> /// Generates dhparam in PKCS#3 format as defined by RFC 2631. /// /// OpenSSL equivalent command: /// $ openssl dhparam -out dhparam.pem 2048 /// /// The minimum root length recommended for NGINX dhparam is 2048bit /// /// ******************************************* /// Notes / Handy references: /// http://www.keylength.com/en/compare/ /// /// </summary> static void GeneratePkcs3(RootLenght rootLength) { string dhparam = null; try { Console.WriteLine($"Generating {(int)rootLength}bit DH parameter..."); Console.WriteLine(""); Console.WriteLine("Choosing a Root Length > 1024bit may take a while."); Console.WriteLine(""); const int DefaultPrimeProbability = 30; DHParametersGenerator generator = new DHParametersGenerator(); generator.Init((int)rootLength, DefaultPrimeProbability, new SecureRandom()); DHParameters parameters = generator.GenerateParameters(); DHParameters realParams = new DHParameters(parameters.P, BigInteger.ValueOf(2)); Asn1EncodableVector seq = new Asn1EncodableVector(); seq.Add(new DerInteger(realParams.P)); seq.Add(new DerInteger(realParams.G)); byte[] derEncoded = new DerSequence(seq).GetDerEncoded(); dhparam = Convert.ToBase64String(derEncoded); Console.WriteLine("-----BEGIN DH PARAMETERS-----"); Console.WriteLine(SpliceText(dhparam, 64)); Console.WriteLine("-----END DH PARAMETERS-----"); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine($"{(int)rootLength}bit DH parameter succesfully generated."); Console.WriteLine(""); Console.WriteLine("");
{ "domain": "codereview.stackexchange", "id": 42770, "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, cryptography, openssl, ssl", "url": null }
c#, .net, cryptography, openssl, ssl Console.WriteLine(""); Console.WriteLine(""); } catch (Exception ex) { // Note: handles errors on the page. Redirect to error page. //ErrorHandler(ex); Console.WriteLine(ex.Message); } } /// <summary> /// Generates RSA private key in PKCS#8 format as defined by RFC 5208. /// Generates Certificate Signing Reuqest in PKCS#10 format as defined by RFC 2986. /// /// OpenSSL equivalent command: /// $ openssl req -new -newkey rsa:2048 -nodes -keyout www_example_com.key -out www_example_com.csr -subj "/C=US/ST=UT/L=Salt Lak City/O=XYZ Inc./OU=IT Division/CN=www.example.com/emailAddress=admin@example.com" /// /// The minimum root length recommended for NGINX dhparam is 2048bit /// /// ******************************************* /// Notes / Handy references: /// http://www.keylength.com/en/compare/ /// /// </summary> static void GeneratePkcs8Pkcs10(string countryIso2Characters, string state, string city, string companyName, string division, string domainName, string email, RootLenght rootLength) { string csr = null; string privateKey = null; try { var rsaKeyPairGenerator = new RsaKeyPairGenerator(); // Note: the numbers {3, 5, 17, 257 or 65537} as Fermat primes. // NIST doesn't allow a public exponent smaller than 65537, since smaller exponents are a problem if they aren't properly padded. // Note: the default in openssl is '65537', i.e. 0x10001. var genParam = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), new SecureRandom(), (int)rootLength, 128); rsaKeyPairGenerator.Init(genParam); AsymmetricCipherKeyPair pair = rsaKeyPairGenerator.GenerateKeyPair(); IDictionary attrs = new Hashtable();
{ "domain": "codereview.stackexchange", "id": 42770, "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, cryptography, openssl, ssl", "url": null }
c#, .net, cryptography, openssl, ssl IDictionary attrs = new Hashtable(); attrs.Add(X509Name.C, countryIso2Characters); attrs.Add(X509Name.L, city); attrs.Add(X509Name.ST, state); attrs.Add(X509Name.O, companyName); if (division != null) { attrs.Add(X509Name.OU, division); } attrs.Add(X509Name.CN, domainName); if (email != null) { attrs.Add(X509Name.EmailAddress, email); } var subject = new X509Name(new ArrayList(attrs.Keys), attrs); var pkcs10CertificationRequest = new Pkcs10CertificationRequest(PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id, subject, pair.Public, null, pair.Private); csr = Convert.ToBase64String(pkcs10CertificationRequest.GetEncoded()); var pkInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(pair.Private); privateKey = Convert.ToBase64String(pkInfo.GetDerEncoded()); Console.WriteLine("-----BEGIN PRIVATE KEY-----"); Console.WriteLine(SpliceText(privateKey, 64)); Console.WriteLine("-----END PRIVATE KEY-----"); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine($"{(int)rootLength}bit Private key succesfully generated."); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("-----BEGIN CERTIFICATE REQUEST-----"); Console.WriteLine(SpliceText(csr, 64)); Console.WriteLine("-----END CERTIFICATE REQUEST-----"); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine($"Certificate Signing Request succesfully generated."); Console.ReadKey();
{ "domain": "codereview.stackexchange", "id": 42770, "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, cryptography, openssl, ssl", "url": null }
c#, .net, cryptography, openssl, ssl Console.ReadKey(); } catch (Exception ex) { // Note: handles errors on the page. Redirect to error page. //ErrorHandler(ex); Console.WriteLine(ex.Message); } } private enum RootLenght { RootLength1024 = 1024, // Test ONLY! RootLength2048 = 2048, RootLength3072 = 3072, RootLength4096 = 4096, } public static string SpliceText(string text, int lineLength) { return Regex.Replace(text, "(.{" + lineLength + "})", "$1" + Environment.NewLine); } } Here's the output: Generating 1024bit DH parameter... Choosing a Root Length > 1024bit may take a while. -----BEGIN DH PARAMETERS----- MIGHAoGBAMP7G34Trw22TCnfYzIpkv/4hJKGGbEYalW4okSq2Zkxvk8Oeikel3k4 M+2b6KbBUMETpKqMhm18M3bCVE8ENFRGyTtrhYGXfPrWAF+cbhZVttgnpnyGOpcp 7rsuI3/NHkhp8n/Fuxy+9CDzh6mva4nCNSwvbzzkzhh0tOhtkMezAgEC -----END DH PARAMETERS----- 1024bit DH parameter succesfully generated.
{ "domain": "codereview.stackexchange", "id": 42770, "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, cryptography, openssl, ssl", "url": null }
c#, .net, cryptography, openssl, ssl 1024bit DH parameter succesfully generated. -----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDQMMj7KQMzVc7x oDXF5mqvuJS/7LH7hJEWQnpbsYH5oIu1/dfL9+xd0yBZ25xcA4NFSlWf34otTnBj qrRLzq/86PZNHJn239odbM+1XRqPnC6XLyHBmOcQAa4eIQL3zHL6JQcCKWVcOBy4 HvY+OTwE2IksvEBgybj6HdSbdJnGLkyCpiG9F9tjcc3OUmflev554Vpwb6Pdxt0d 2zQt3UHHoNKRJYnhZMAGVm2X0c1s5QGx33sDQxBEZp7dhO4Wq9gnU8DVzJzXmvN6 9eJykIN42TEHdQr/MycQP0B5M92BDLuIy4mf/gCj9eIarJlDFnkKBu5QAF3wVtHt 13imkCEXAgMBAAECggEAVm+iyhBNiV87c7tCCB+xtLIsZAC4JoZ0HGtOVMp+fa8n wlAZa9BLvOqemGAi61r0Ae0qXp2XR1c1N1QU1hKCo7zvIbXZwJNRAf1+wTxd/jjo aRGC8Nd0O4OPEGhBTLOAGxYLclzQffi4B8OnFc96eUKTtVSVX/nwiDuhXUeMXqhz AZynm9CqhDN4fVJhMlUCVokKmaPD5Y/toUTQ1hkrsb72HYX1tcAnp9j02UwUobZW /GJKC9d0WVkUw1Rb0cWhPlyz1vV/l4nlif1mQVa9pSWFcGyjmi34ERGqGah+iCJe H6br82dng8VvWcSJrjD+iloa5LmwFMQbLBax1sX+ZQKBgQD6AvKQZ0jq1AGwAwXj Hv10zaW4RhiW3RI6Qnk4w+WxuR6tqHq8ONsyK6a97k9MSp00TglNo8udiBOdBcIK F3WjhZX2i6qMIedIWwEg1ZEYHikTCsAcx/JyQP3YqMqTMBLJEfHVZURNkS/NUiDx xCzF+5yQfA5MhnRWznwoMglcUwKBgQDVLWUBPWtDXZZWJyLkArxS28s/dstrUdYp Vc+jDOEmIwWoPfCzkkTLCtGpveh0k1Z1dzTC5pAcWBngvDeB3rXrvCf7VtOd7Q1R AIhHaLSYCA5yG93tf28WeCBICK/taAhkNAMcGcOfG106LOvB9t/B19q3LoxoEiJ/ L2PWy2CvrQKBgEiPxHDu2TX2tEquhe3mV6+n5Bo4lfhrT1gDZQV5rdfIH8RNKtoo Mk48Zxem6/L7kObWY1LaYEVncjHXsvqU1nrQUbcN0ED9sg/JAenSslrqngc9zoZL 7e0FOefBDZJsmHctMyA5VPqiUdpopNEmm8wWe9lfeBLzzx5GrbhI1XirAoGBAJGs +LX1M8SQQrjS+7vWxrzUqDrRQkcvYGtU0ZR5q641Bpum4ELGNK6P0SDuvthTCyUw deSuTFKiPeTemgvslmLmbGgMOIZWROBSvc4WljrCXqTJuEmg6Nfw9RZkoVxZ2Eop ZOqiDJVAzN+BbQZaXyQHDtZZP+eqZNqHFvHkf0jtAoGAEggGixhY79ZoSpRejlHS oTCWqtsjB9xLPNC6JLD1TP7UhHNXhpnvBRpxanqeUKwvfnMLZKR5ZH2mE+aA3hij oiU87X9iDf7H9oQ91dzvsoDh3WbEFvTFo88kBUxb7Q2lIqWG0OjhKDrj/3TGWzpQ XznRAR43mzbkukKE39ddYns= -----END PRIVATE KEY----- 2048bit Private key succesfully generated.
{ "domain": "codereview.stackexchange", "id": 42770, "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, cryptography, openssl, ssl", "url": null }
c#, .net, cryptography, openssl, ssl 2048bit Private key succesfully generated. -----BEGIN CERTIFICATE REQUEST----- MIIC4TCCAckCAQAwgZ0xFzAVBgNVBAsMDklUIFN1YmRpdmlzaW9uMRcwFQYDVQQH DA5TYWx0IExha2UgQ2l0eTEgMB4GCSqGSIb3DQEJARYRYWRtaW5AZXhhbXBsZS5j b20xGDAWBgNVBAMMD3d3dy5leGFtcGxlLmNvbTENMAsGA1UECAwEVXRhaDELMAkG A1UEBhMCVVMxETAPBgNVBAoMCFhZWiBJbmMuMIIBIjANBgkqhkiG9w0BAQEFAAOC AQ8AMIIBCgKCAQEA0DDI+ykDM1XO8aA1xeZqr7iUv+yx+4SRFkJ6W7GB+aCLtf3X y/fsXdMgWducXAODRUpVn9+KLU5wY6q0S86v/Oj2TRyZ9t/aHWzPtV0aj5wuly8h wZjnEAGuHiEC98xy+iUHAillXDgcuB72Pjk8BNiJLLxAYMm4+h3Um3SZxi5MgqYh vRfbY3HNzlJn5Xr+eeFacG+j3cbdHds0Ld1Bx6DSkSWJ4WTABlZtl9HNbOUBsd97 A0MQRGae3YTuFqvYJ1PA1cyc15rzevXicpCDeNkxB3UK/zMnED9AeTPdgQy7iMuJ n/4Ao/XiGqyZQxZ5CgbuUABd8FbR7dd4ppAhFwIDAQABMA0GCSqGSIb3DQEBCwUA A4IBAQCwaMkLKKioFy1XUSRjkjDupuvsSXT070oov3F5Vwr0TT5rxki16PeXaLFf lFzhaiwMx88ql2vHLeq6WADrvRtW/dB2OPTbceMC+CuRb7Mk0WKI+SMfrDbSYc4I oXdDE8NfdMWV2ntWbKptVjJUfU0OmNnsh2W9973JpiRVMl+UJv/eMXMjKhH4Trzf sW+voJLNajjVTJwYIQktOpGM7rmfjb9rVtZ1f5ZlgCCJUeTttdFSqSPG/yRh+9yJ HKBeBFKptJ0HsZTLMhcRWc8rEiqTmag2QmL9jJHP4krwLf5aYQVUZAABJJ2LNyR8 8yYUVt5KsHKYksMu3yOnOq5BOHNu -----END CERTIFICATE REQUEST----- Certificate Signing Request succesfully generated. Answer: Security remarks: generally a 3072 bit RSA key and DH domain parameters would be preferred; 2048 bit keys don't even reach 128 bits of security commonly named parameters are used, so there is no need to generate DH domain parameters (and it is questionable if they should be linked to the lifetime of the private key / certificate) dumping private keys on the console is a very bad idea; instead a PKCS#12 or an password encrypted PKCS#8 should be generated generally we use the faster / more secure ECDH instead of DH nowadays, although it is less secure against quantum computers - once they become available Other remarks:
{ "domain": "codereview.stackexchange", "id": 42770, "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, cryptography, openssl, ssl", "url": null }
c#, .net, cryptography, openssl, ssl Other remarks: generally you'd use a line size of 76 (ASCII) characters within PEM encoded files, not 64 the message is printed to standard out instead of standard error the "success" messages are entirely spurious and may harm code that tries to read out the PEM parts from the printout it seems that a space between the bit size and the word "bit" would make your output more readable the text "Choosing a Root Length > 1024bit may take a while." does not need to be printed for 1024 bit keys it is strange that code edits are required to generate the output parameter documentation is missing and it is unclear from the method definition which parameters may be set to null Coding remarks:
{ "domain": "codereview.stackexchange", "id": 42770, "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, cryptography, openssl, ssl", "url": null }
c#, .net, cryptography, openssl, ssl Coding remarks: input parameters such as country code size are not tested csr and privateKey are never returned, so they don't need to be defined before the try loop, and assigning null is never needed all exceptions are caught and printed, but you don't return any error code from your Main method commented out code is present for the exception handling, without TODO or anything like that the generation and DER encoding / printout of the generated parameter / key / certificate should be placed in separate methods more functions should be used, e.g. Bouncy Castle has code to perform PEM encoding and probably has functions to perform DH parameter encoding as well the enum is generally placed on top of the class definition, not at the bottom there doesn't seem to be any need to make the SpliceText method public; you would not use this class as utility class in other applications for that it's probably more performant and more readable to use a StringBuilder class for SpliceText than a regular expression Replace; you could simply use Substring after all the entire SpliceText could be avoided if you had taken a look at the base 64 encoder provided with C# it is unclear why the size of the private key is called rootLength 8 method parameters is a lot, and it makes it easy to e.g. swap parameters, a builder / class could be used instead - especially since you may want to increase them later on
{ "domain": "codereview.stackexchange", "id": 42770, "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, cryptography, openssl, ssl", "url": null }
c++, algorithm, c++20 Title: Nelder-Mead optimization in C++ Question: I've implemented the Nelder-Mead optimization algorithm in C++. I found this document to be a very good explanation of how the algorithm works, but I'll try my best to explain it (with an example) here so it's clear for everyone. The problem I'm trying to optimize is very simple : I'm trying to find the best a,b,c coefficients for a quadratic function to fit points on a quadratic function of form f(x) = 1.5*x^2 + 3.2*x + 7. So, of course, the optimal parameters I'm looking for are a=1.5, b=3.2, c=7. In order to compute the error between the coefficients that I have and the expected coefficients, I use the following function : #include "Eigen/Dense" static double quadraticEquationError(Array<double, 1, 3> parameters) { double searchedParamters[] = {1.5, 3.2, 7}; auto x = Array<double, 100, 1>().setLinSpaced(100, 0, 90); auto expected = searchedParamters[0] * x*x + searchedParamters[1] * x + searchedParamters[2]; auto result = parameters(0, 0) * x * x + parameters(0, 1) * x + parameters(0, 2); auto diff = result.matrix() - expected.matrix(); return diff.norm(); } It's very simple, but it's also a way for me to check if my algorithm works. The goal of this error function is to return 0, where I would have found my optimal parameters. The Nelder-Mead algorithm takes as input an error function and some initial parameters (in my case, a=0, b=0, c=0). Then, it generates a simplex of N+1 dimensions (here, N = 3 since we are looking for 3 parameters) where each vertex of the simplex represents a new parameters set. After that, depending on the values of the worst, second worst and best sets, it replaces the worst point by a new value. There are five operations that can be used : reflection, expansion, inside contraction, outside contraction and shrinking. The following figure shows the result of these operations for a 2D simplex (of 3 points).
{ "domain": "codereview.stackexchange", "id": 42771, "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++, algorithm, c++20", "url": null }
c++, algorithm, c++20 In order to figure out which operation to use, we can look at the following diagram : Progressively, the error will go down until a convergence criterion is reached. In my case, I decided to stop when the best error is under a certain value. So, I hope this is pretty clear as to how the algorithm works, here's my code : main.cpp #include "library.h" #include <iostream> #include "Eigen/Dense" #include "optimization/NelderMead.h" using namespace Optimization; static double quadraticEquationError(Array<double, 1, 3> parameters) { double searchedParamters[] = {1.5, 3.2, 7}; auto x = Array<double, 100, 1>().setLinSpaced(100, 0, 90); auto expected = searchedParamters[0] * x*x + searchedParamters[1] * x + searchedParamters[2]; auto result = parameters(0, 0) * x * x + parameters(0, 1) * x + parameters(0, 2); auto diff = result.matrix() - expected.matrix(); return diff.norm(); } int main() { Array<double, 1, 3> initialParameters; initialParameters.row(0) << 0.0, 0.0, 0.0; auto nelderMead = NelderMead<3>(quadraticEquationError, initialParameters, 1, 2); nelderMead.optimize(); return 0; } optimization/NelderMead.h #include "Eigen/Dense" #include <vector> #include <limits> #include <cstring> #include <iostream> using namespace Eigen; namespace Optimization { template<int nDims> class NelderMead { public: typedef Array<double, 1, nDims> FunctionParameters; typedef std::function<double(FunctionParameters)> ErrorFunction;
{ "domain": "codereview.stackexchange", "id": 42771, "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++, algorithm, c++20", "url": null }
c++, algorithm, c++20 NelderMead(ErrorFunction errorFunction, FunctionParameters initial, double minError, double initialEdgeLength, double shrinkCoeff = 1, double contractionCoeff = 0.5, double reflectionCoeff = 1, double expansionCoeff = 1) : errorFunction(errorFunction), minError(minError), shrinkCoeff(shrinkCoeff), contractionCoeff(contractionCoeff), reflectionCoeff(reflectionCoeff), expansionCoeff(expansionCoeff), worstValueId(-1), secondWorstValueId(-1), bestValueId(-1) { this->errors = std::vector(nDims + 1, std::numeric_limits<double>::max()); const double b = initialEdgeLength / (nDims * SQRT2) * (sqrt(nDims + 1) - 1); const double a = initialEdgeLength / SQRT2; this->values = initial.replicate(nDims + 1, 1); for (int i = 0; i < nDims; i++) { FunctionParameters simplexRow; simplexRow.setConstant(b); simplexRow(0, i) = a; simplexRow += initial; this->values.row(i+1) = simplexRow; } } void optimize() { for (int i = 0; i < nDims+1; i++) { this->errors.at(i) = this->errorFunction(this->values.row(i)); } this->invalidateIdsCache(); while (this->errors.at(this->bestValueId) > this->minError) { step(); auto bestError = this->errorFunction(this->best()); auto worstError = this->errorFunction(this->worst()); std::cout << "Best error " << std::to_string(bestError) << " with : " << this->best(); std::cout << " Worst error " << std::to_string(worstError) << " with : " << this->worst(); std::cout << '\n'; } }
{ "domain": "codereview.stackexchange", "id": 42771, "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++, algorithm, c++20", "url": null }
c++, algorithm, c++20 void step() { auto meanWithoutWorst = this->getMeanWithoutWorst(); auto reflectionOfWorst = this->getReflectionOfWorst(meanWithoutWorst); auto reflectionError = this->errorFunction(reflectionOfWorst); FunctionParameters newValue = reflectionOfWorst; double newError = reflectionError; bool shrink = false; if (reflectionError < this->errors.at(this->bestValueId)) { auto expansionValue = this->expansion(meanWithoutWorst, reflectionOfWorst); double expansionError = this->errorFunction(expansionValue); if (expansionError < this->errors.at(this->bestValueId)) { newValue = expansionValue; newError = expansionError; } } else if (reflectionError > this->errors.at(this->worstValueId)) { newValue = this->insideContraction(meanWithoutWorst); newError = this->errorFunction(newValue); if (newError > this->errors.at(this->worstValueId)) { shrink = true; } } else if (reflectionError > this->errors.at(this->secondWorstValueId)) { newValue = this->outsideContraction(meanWithoutWorst); newError = this->errorFunction(newValue); if (newError > reflectionError) { shrink = true; } } else { newValue = reflectionOfWorst; newError = reflectionError; } if (shrink) { this->shrink(); this->invalidateIdsCache(); return; } this->values.row(this->worstValueId) = newValue; this->errors.at(this->worstValueId) = newError; this->invalidateIdsCache(); }
{ "domain": "codereview.stackexchange", "id": 42771, "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++, algorithm, c++20", "url": null }
c++, algorithm, c++20 inline FunctionParameters worst() { return this->values.row(this->worstValueId); } inline FunctionParameters best() { return this->values.row(this->bestValueId); } private: void shrink() { auto bestVertex = this->values.row(this->bestValueId); for (int i = 0; i < nDims + 1; i++) { if (i == this->bestValueId) { continue; } this->values.row(i) = bestVertex + this->shrinkCoeff * (this->values.row(i) - bestVertex); this->errors.at(i) = this->errorFunction(this->values.row(i)); } } inline FunctionParameters expansion(FunctionParameters meanWithoutWorst, FunctionParameters reflection) { return reflection + this->expansionCoeff * (reflection - meanWithoutWorst); } inline FunctionParameters insideContraction(FunctionParameters meanWithoutWorst) { return meanWithoutWorst - this->contractionCoeff * (meanWithoutWorst - this->worst()); } inline FunctionParameters outsideContraction(FunctionParameters meanWithoutWorst) { return meanWithoutWorst + this->contractionCoeff * (meanWithoutWorst - this->worst()); } FunctionParameters getReflectionOfWorst(FunctionParameters meanWithoutWorst) { return meanWithoutWorst + this->reflectionCoeff * (meanWithoutWorst - this->worst()); } FunctionParameters getMeanWithoutWorst() { FunctionParameters mean(0); for (int i = 0; i < nDims + 1; i++) { if (i == this->worstValueId) { continue; } mean += this->values.row(i); } // Not divided by nDims+1 because there's one ignored value. mean /= nDims; return mean; }
{ "domain": "codereview.stackexchange", "id": 42771, "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++, algorithm, c++20", "url": null }
c++, algorithm, c++20 return mean; } void invalidateIdsCache() { double worstError = std::numeric_limits<double>::min(); int worstId = -1; double secondWorstError = std::numeric_limits<double>::max(); int secondWorstId = -1; double bestError = std::numeric_limits<double>::max(); int bestId = -1; for (int i = 0; i < nDims + 1; i++) { auto error = this->errors.at(i); if (error > worstError) { secondWorstError = worstError; secondWorstId = worstId; worstError = error; worstId = i; } else if (error > secondWorstError) { secondWorstError = error; secondWorstId = i; } if (error < bestError) { bestError = error; bestId = i; } } // If we deal with a problem in 1D, it won't be set. if (secondWorstId == -1) { secondWorstId = worstId; } this->bestValueId = bestId; this->worstValueId = worstId; this->secondWorstValueId = secondWorstId; } ErrorFunction errorFunction; Array<double, nDims + 1, nDims> values; std::vector<double> errors; int worstValueId; int secondWorstValueId; int bestValueId; double minError; double shrinkCoeff; double expansionCoeff; double contractionCoeff; double reflectionCoeff; const double SQRT2 = sqrt(2); }; }
{ "domain": "codereview.stackexchange", "id": 42771, "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++, algorithm, c++20", "url": null }
c++, algorithm, c++20 const double SQRT2 = sqrt(2); }; } Now, the thing is I don't know much about C++, but I know a lot about C# so I think my code structure is fine. I tried to use templates and typedefs to make code more readable/generic, but I'd like my C++ skills to improve a lot since I'm starting a new job soon that will require me to write C++ (my employer knows I'm not super strong in C++ but I'd like to get up to speed). I'm looking for parts of my code that aren't using the full potential of C++, although I'm open to any part of the code reviewed. Answer: Usage Documentation I'll consider the text contents of the post as documentation and it looks good. Consumers It is important to have a straightforward consumption process. Usually it is having a CMakeLists script that searches for required dependencies and sets up required (!) compilation flags. The stuff like optimization levels and warnings can go into toolchain file. Usage flow At the moment it looks like a toy program. What is the usecase for the current implementation? I would expect something like the following: template <typename T, std::size_t Dimensions> using coefficients_t = Array<T, 1, Dimensions>; template <typename T, std::size_t Dimensions> struct optimization_state_t { coefficients_t<T, Dimensions> coefficients; std::function<double(coefficients_t<T, Dimensions>)> error_function; /*errors and what other internal state is needed */ }; template <typename T, std::size_t Dimensions> optimization_state_t make_starting_state(coefficients_t<T, Dimensions> start = {}, std::function<double(coefficients_t<T, Dimensions>)> error_function = default_error_function); template <typename T, std::size_t Dimensions> void perform_step(optimization_state_t<T, Dimensions>& state); template <typename T, std::size_t Dimensions> optimization_state_t<T, Dimensions> optimize_until(coefficients_t<T, Dimensions> coefficients);
{ "domain": "codereview.stackexchange", "id": 42771, "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++, algorithm, c++20", "url": null }
c++, algorithm, c++20 This way, my flow will be decide on initial parameters -> optimize one step and see if the convergence speed is good -> try again or abort -> feed results somewhere else or decide on initial parameters -> optimize until some condition -> feed results somewhere else I believe interfaces should support desired usage flow instead of just providing bits and pieces that together form a crooked road. Note that error function is part of the optimization state, as the error values will lose meaning in incompatible error functions. As Scott Meyers said, interfaces should be "easy to use correctly and hard to use incorrectly".
{ "domain": "codereview.stackexchange", "id": 42771, "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++, algorithm, c++20", "url": null }
c++, algorithm, c++20 Details Proper types I'm not an experienced user of Eigen, I believe Vector3d is a better fit due to the conversion into matrix in the error function and generally solving a system of equations. There is also a library called Blaze, which from what I remember makes better use of intel MKL (needless to say that on AMD CPUs performance will be subpar). Use standard constants There are well defined constants since C++20. Computing it from scratch using library features might change the value from release to release. Consider the cost of accepting by value To accept by value, a new instance of the type has to be made. If the type does dynamic memory allocation (new, malloc, etc) and there is no real need to copy/move/construct a new object, then it is better to avoid paying the performance cost of additional memory allocation by accepting by reference. On the other hand, if Array<double, 1, 3> does not do dynamic memory allocation, it is better to accept it by value since it is small and will not cause stackoverflow Do not use checking version of subscripts Subscript operators that do bounds checking prevent SIMD instruction generation for compilers. It is better to just do plain assert and call non-checking version. Do not import names into current scope without the need using namespace something is usually a bad idea inside a header. Aside from obvious name clashes, there is ADL. The bottom line is that if Eigen decides to add similar function to yours and the call is not qualified with a namespace, two erroneous outcomes will happen. First and the best one is that ambigious call error will be issued because both functions are at equal rank in overload resolution. The worst case is that the compiler will silently select unintended function because the programmer didn't know about this (and most people don't know about ADL).
{ "domain": "codereview.stackexchange", "id": 42771, "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++, algorithm, c++20", "url": null }
c++, algorithm, c++20 Style Usage of this this is usually frowned upon unless there are some clever mixin tricks need to be done. I do not really know a strong reason why it is frowned upon, but arguments thrown around are that it makes it easy to confuse argument with member variable, that this can be a bit weird with lambdas and so on. Naming The standard uses snake_case for almost everything except template parameter names which are Pascal case. There is also Google style guide, MISRA and the others. I believe it is important to just pick a well-known one and stick with it, because clang-format configs are already written for them.
{ "domain": "codereview.stackexchange", "id": 42771, "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++, algorithm, c++20", "url": null }
c#, .net, networking, ado.net Title: IPAddress Range access Question: I want to make this code better and easier to read. It works now but I think it can be better. When there is an Inbound request I check to see if that accessKey is setup for IP address Range that will return a bool flag. If its true I then need to get the IPStartAddress and IPEndAddress from the database. With that data and the inbound IP Address I can see if its in Range. Would be great if anyone can help me with this. public static bool IsAuthenticated(string accessKey, string ipAddress) { bool IsRangeEnable = false; IsRangeEnable = IsAccessKeyRangeEnable(accessKey); if (IsRangeEnable == false) { bool canAccess = false; string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; SQLHelper sql = new SQLHelper(conn); SqlParameter[] parms = new SqlParameter[] { new SqlParameter("@AccessKey", SqlDbType.VarChar,36), new SqlParameter("@IPAddress",SqlDbType.VarChar,15) }; parms[0].Value = accessKey; parms[1].Value = ipAddress; SqlDataReader dr = sql.ExecuteReaderStoreProcedure("dbo.[usp_Select_LoginAPI_AccessKey_IPAddress]", parms); while (dr.Read()) { canAccess = Convert.ToBoolean(dr["IsValid"]); } dr.Close(); return canAccess; } else { return CheckIPRange(accessKey, ipAddress); } }
{ "domain": "codereview.stackexchange", "id": 42772, "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, networking, ado.net", "url": null }
c#, .net, networking, ado.net } public static bool IsAccessKeyRangeEnable(string accessKey) { bool IsRangeEnable = false; string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; SQLHelper sql = new SQLHelper(conn); SqlParameter[] parms = new SqlParameter[] { new SqlParameter("@AccessKey", SqlDbType.VarChar,36), }; parms[0].Value = accessKey; SqlDataReader dr = sql.ExecuteReaderStoreProcedure("dbo.[usp_Admin_Select_AccessKeyRangeEnable]", parms); while (dr.Read()) { IsRangeEnable = Convert.ToBoolean(dr["ReturnValue"]); } dr.Close(); return IsRangeEnable; } public static bool CheckIPRange(string accessKey, string ipAddress) { bool InRange = false; string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; SQLHelper sql = new SQLHelper(conn); SqlParameter[] parms = new SqlParameter[] { new SqlParameter("@AccessKey", SqlDbType.VarChar,36), }; parms[0].Value = accessKey; SqlDataReader dr = sql.ExecuteReaderStoreProcedure("dbo.[usp_Admin_Select_IPRange]", parms); while (dr.Read()) { InRange = IsInRange(Convert.ToString(dr["IPStartAddress"]), Convert.ToString(dr["IPEndAddress"]), ipAddress); } dr.Close(); return InRange; } public static bool IsInRange(string startIpAddr, string endIpAddr, string address) { long ipStart = BitConverter.ToInt32(IPAddress.Parse(startIpAddr).GetAddressBytes().Reverse().ToArray(), 0); long ipEnd = BitConverter.ToInt32(IPAddress.Parse(endIpAddr).GetAddressBytes().Reverse().ToArray(), 0);
{ "domain": "codereview.stackexchange", "id": 42772, "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, networking, ado.net", "url": null }
c#, .net, networking, ado.net long ip = BitConverter.ToInt32(IPAddress.Parse(address).GetAddressBytes().Reverse().ToArray(), 0); return ip >= ipStart && ip <= ipEnd; } Answer: Quick remarks: There is no point in defining a variable and assigning it a value, only to override that value in the next line (IsRangeEnable in IsAuthenticated). Follow the Microsoft naming guidelines. Variable names should be camelCase (InRange, IsRangeEnable, ...). Don't use ADO.NET. Use something like Dapper. Using it would have made your code significantly shorter and easier to read. (I don't know what SQLHelper is; a Google search seems to suggest some ancient class that you definitely should not use.) Looking at your code you don't seem to properly dispose of your database connection. Don't pointlessly abbreviate. Look at conn: I'd expect a connection, instead it is a connection string. I also never would have guess that sql is a SQLHelper from its name. Why is the code inside if (IsRangeEnable == false) not in a method of its own?
{ "domain": "codereview.stackexchange", "id": 42772, "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, networking, ado.net", "url": null }
python, python-3.x, algorithm Title: Cleaning a game logs list to find the frequent action triplets and the busy user Question: I have these game logs which I need to clean, process and find the frequency of game actions. These game actions should be a triplet. In the below given list, "1|123|/jump", "2|123|/flip", "3|123|/crouch" is a triplet and also "2|123|/flip", "3|123|/crouch", "8|123|/dance". Similarly, "4|999|/jump", "5|999|/flip", "6|999|/crouch", "5|999|/flip", "6|999|/crouch", "7|999|/stroll", and "6|999|/crouch", "7|999|/stroll", "9|999|/jump". And finally, "10|639|/flip", "11|639|/crouch","12|639|/stroll". The output should be a dictionary of action triplets with keys as action triplets and value is the frequency of the action triplets. {'/jump,/flip,/crouch': 2, '/flip,/crouch,/dance': 1, '/flip,/crouch,/stroll': 2, '/crouch,/stroll,/jump': 1} and the user_id which has the highest number of action triplets. In this case it is user_id: 999 The following is my approach: I split the string on | and create a list of tuples (user_id, action). I ignore the sequence id (first part of the log). I sort the list of tuples by user_id. I create triplets by comparing the three consecutive user_ids and create a 2-d list. Create a dictionary with key (append each user_action together with a comma) from each list of action triplets and value being the count of these same set of user_actions. Create another dictionary with key (user_id) - I took the very first value of the tuple from each list as each triplet list can only have one user_id. Then, I return the max value key i.e., user_id at the end.
{ "domain": "codereview.stackexchange", "id": 42773, "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, python-3.x, algorithm", "url": null }
python, python-3.x, algorithm game_logs = ["1|123|/jump", "2|123|/flip", "3|123|/crouch", "4|999|/jump", "5|999|/flip", "6|999|/crouch", "7|999|/stroll", "8|123|/dance", "9|999|/jump", "10|639|/flip", "11|639|/crouch","12|639|/stroll"] def clean(game_logs): size = len(game_logs) user_id_actions = [] for game_log in game_logs: id, user_id, action = extract(game_log) user_id_actions.append((user_id, action)) user_id_actions.sort(key = lambda x:x[0]) # print(user_id_actions) action_triplets = [] for i in range(size - 2): if user_id_actions[i][0] == user_id_actions[i+1][0] and user_id_actions[i+1][0] == user_id_actions[i+2][0]: action_triplets.append([user_id_actions[i], user_id_actions[i+1], user_id_actions[i+2]]) # print(action_triplets) triplet_hash = {} max_actions_user_id_hash = {} for triplet in action_triplets: page_string = [] for val in triplet: user_id, page = val page_string.append(page) fin_string = ','.join(page_string) if fin_string not in triplet_hash: triplet_hash[fin_string] = 1 else: triplet_hash[fin_string] += 1 # print(triplet_hash) print(f"Action action_triplets: {triplet_hash}") for triplet in action_triplets: user_id = triplet[0][0] if user_id not in max_actions_user_id_hash: max_actions_user_id_hash[user_id] = 1 else: max_actions_user_id_hash[user_id] += 1 # print(max_actions_user_id_hash) print(f"Highest number of action_triplets are for the user_id :{max(max_actions_user_id_hash, key=max_actions_user_id_hash.get)}") def extract(game_log): extract_info = tuple(game_log.split('|'))
{ "domain": "codereview.stackexchange", "id": 42773, "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, python-3.x, algorithm", "url": null }
python, python-3.x, algorithm def extract(game_log): extract_info = tuple(game_log.split('|')) return extract_info clean(game_logs)
{ "domain": "codereview.stackexchange", "id": 42773, "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, python-3.x, algorithm", "url": null }
python, python-3.x, algorithm It feels like I over complicated the whole logic here. Creating nested lists, creating multiple dictionaries. Could anyone share feedback. Thank you Answer: Your code is reasonable. The primary advice I have focuses not on anything particularly wrong with your current implementation but on simpler ways to complete the task using the standard library. The first part of your function assembles the data into triples, and you're on the right track in the sense that you are sorting the data by user ID. But you can simplify further by taking advantage of itertools.groupby. Here's a function that takes the game logs and returns a dict mapping user ID to all of that user's action tuples. from operator import itemgetter from itertools import groupby from collections import Counter def parse_game_logs(game_logs): # Parse logs into tuples. No need to abandon the sequence ID. actions = [glog.split('|') for glog in game_logs] # Prepare the grouping generator. uidkey = itemgetter(1) grouping_gen = groupby(sorted(actions, key = uidkey), key = uidkey) # Return dict mapping user ID to its actions. return { uid : list(acts) for uid, acts in grouping_gen } Once you have that dict, finding the user with the most actions involves finding the minimum (key, value) tuple, where minimum computation is based on length of the value. def get_most_active_user(actions): len_key = lambda tup: len(tup[1]) return max(actions.items(), key = len_key)[0] And the same dict of actions can be used to assemble the tally of action triples. A Counter is a good data structure to use: def get_triple_frequencies(actions): return Counter( ','.join(a for sid, uid, a in acts[i : i + 3]) for uid, acts in actions.items() for i in range(len(acts) - 2) )
{ "domain": "codereview.stackexchange", "id": 42773, "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, python-3.x, algorithm", "url": null }
python, python-3.x, algorithm Putting all of the pieces together: def clean(game_logs): actions = parse_game_logs(game_logs) return ( get_most_active_user(actions), get_triple_frequencies(actions), )
{ "domain": "codereview.stackexchange", "id": 42773, "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, python-3.x, algorithm", "url": null }
python, python-3.x Title: Clean up Python function with too many if/else statements Question: I have a working function with too many if/else statements (pylint). The code works but it's not good. I try to improve it but I have some tunnelvision. Can someone help me to improve the code? So depending on a list of stacks, an environment (prod, nonprod or all) and a list of account IDs there can be filtered on which stacks need to be updated. This is an example of a stack dict: {'AccountId': '123456789101', 'StackName': 'test-nonprod'} function: def filter_stacks(stacks, environment, account_ids): """todo""" non_prod_regex = re.compile("(nonprod|non-prod)") stacks_to_update = [] if non_prod_regex.match(environment) and account_ids: for stack in stacks: if ( non_prod_regex.search(stack["StackName"]) and stack["AccountId"] in account_ids ): stacks_to_update.append(stack) elif non_prod_regex.match(environment) and not account_ids: for stack in stacks: if non_prod_regex.search(stack["StackName"]): stacks_to_update.append(stack) elif re.compile("all").match(environment) and account_ids: for stack in stacks: if stack["AccountId"] in account_ids: stacks_to_update.append(stack) elif re.compile("all").match(environment) and not account_ids: stacks_to_update = stacks elif not non_prod_regex.match(environment) and account_ids: for stack in stacks: if ( not non_prod_regex.search(stack["StackName"]) and stack["AccountId"] in account_ids ): stacks_to_update.append(stack) elif not non_prod_regex.match(environment) and not account_ids: for stack in stacks: if not non_prod_regex.search(stack["StackName"]): stacks_to_update.append(stack) else: print("No match found.")
{ "domain": "codereview.stackexchange", "id": 42774, "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, python-3.x", "url": null }
python, python-3.x return stacks_to_update Answer: Simplifications re.compile("(nonprod|non-prod)") is just a complicated way to write a badly performing regex for re.compile("non-?prod"), which does the same, but better. extract re.compile("all") into a variable like you did with non_prod_regex, or better yet, do a string comparison: if environment == "all"... Achieves the same effect, but is quicker (because no regex involved). A different design An alterative to having that for-loop inside of the if-statements would be to have the if-statements inside of your loop. That can be made much cleaner by converting it to a list comprehension: is_nonprod = bool(non_prod_regex.match(environment)) has_accounts = bool(account_ids) stacks_to_update = [stack for stack in stacks if ( (environment == "all" or (is_nonprod == bool(non_prod_regex.match(stack["StackName"])))) and (not has_accounts or stack["AccountId"] in account_ids) )] This design makes an interesting simplification: You have two dimensions of things you want to check: The environment of the stack and the account of the stack. Both of these dimensions impact the result set, but are independent of one another. This allows us to simplify things a bit by noticing the repeating pattern: if there are account_ids, the account needs to be checked, otherwise we don't care The environment must either be "all" or the 'nonprod-status' of the stack must match the environment. These two conditions must be fulfilled to include a stack in the result set. The first one is easier, it's just an implication \$A \Rightarrow s.aid \in A\$, which is equivalent to \$\neg A \lor s.aid \in A\$ (not account_ids or ...) The second condition is equally simple to implement and combining the two conditions with and gets all the results filtered the way we need them to.
{ "domain": "codereview.stackexchange", "id": 42774, "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, python-3.x", "url": null }
python, api Title: A Python-program that makes successive API-calls Question: I wrote some code to make calls to a public API. The code is correct as required as usual. My goal is to make the code as self-explanatory, maintainable and robust as possible. I also tried to make the code extendable, such that it would be easy to add different API calls in the future. Execution speed or memory-efficiency are not really a big issue. I would appreciate any comments on my overall approach or implementation details. With my goals in mind: what could be improved? The following code generates info about releases published on discogs.com. Every instance of ReleaseGenerator takes wantlist_url as a parameter, which is just the URL to a user generated list of releases. Release info can be retrieved like this: url = 'https://api.discogs.com/users/damonrthomas/wants?page=1&per_page=500' releases = ReleaseGenerator(url) for release in releases: print(release)
{ "domain": "codereview.stackexchange", "id": 42775, "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, api", "url": null }
python, api Running the program outputs release info for all releases contained on the specified wantlist, e.g.: Release(id=3010992, title='DJ-Kicks', artists=['Motor City Drum Ensemble'], genres=['Electronic', 'Jazz', 'Funk / Soul', 'Stage & Screen'], styles=['House', 'Fusion', 'Disco', 'Neo Soul', 'Deep House', 'Soundtrack', 'Minimal', 'Free Jazz'], labels=['!K7 Records'], year=2011, mediums=[{'medium': 'Vinyl', 'description': ['LP', 'Compilation'], 'qty': '2'}]) Release(id=8108236, title='DJ-Kicks', artists=['Moodymann'], genres=['Electronic', 'Hip Hop', 'Funk / Soul'], styles=['Soul', 'Downtempo', 'Deep House', 'House'], labels=['!K7 Records', '!K7 Records'], year=2016, mediums=[{'medium': 'Vinyl', 'description': ['LP', 'Compilation'], 'qty': '3'}]) Release(id=14917657, title='Sounds & Reasons', artists=['The Mighty Zaf', 'Phil Asher'], genres=['Funk / Soul'], styles=['Disco', 'Boogie'], labels=["'80s"], year=2020, mediums=[{'medium': 'Vinyl', 'description': ['12"', '33 ⅓ RPM', 'Test Pressing'], 'qty': '1'}]) Release(id=11771040, title='Genie', artists=['The Mighty Zaf', 'Phil Asher'], genres=['Funk / Soul'], styles=['Disco'], labels=["'80s"], year=2018, mediums=[{'medium': 'Vinyl', 'description': ['12"', '33 ⅓ RPM', 'Test Pressing'], 'qty': '1'}]) Release(id=12009859, title='Genie', artists=['The Mighty Zaf', 'Phil Asher'], genres=['Funk / Soul'], styles=['Disco'], labels=["'80s"], year=2018, mediums=[{'medium': 'Vinyl', 'description': ['12"', '33 ⅓ RPM'], 'qty': '1'}]) Release(id=16157292, title='Sounds & Reasons', artists=['The Mighty Zaf', 'Phil Asher'], genres=['Funk / Soul'], styles=['Disco', 'Boogie'], labels=["'80s"], year=2020, mediums=[{'medium': 'Vinyl', 'description': ['12"', '33 ⅓ RPM'], 'qty': '1'}]) ... The class ReleaseGenerator makes use of the public API of discogs.com and implements the retrieval of data: import requests from src.utils import verify import time from collections import namedtuple
{ "domain": "codereview.stackexchange", "id": 42775, "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, api", "url": null }
python, api class ReleaseGenerator: """Class for generating information about releases on the specified wantlist url""" def __init__(self, wantlist_url): self.wantlist_url = wantlist_url self.release_url = 'https://api.discogs.com/releases' self.want_key = 'wants' self.page_key = 'pagination' self.url_key = 'urls' self.id_key = 'id' self.next_key = 'next' @verify def _get_response(self, url): """Makes a request to the specified url.""" request = requests.get(url) json = request.json() return json def _generate_pages(self): """Generates all pages of the paginated API response. Throttles requests automatically if needed.""" url = self.wantlist_url while True: res = self._get_response(url) try: url = res[self.page_key][self.url_key][self.next_key] except KeyError: if 'message' in res.keys() and res['message'] == "You are making requests too quickly.": time.sleep(60) else: print('Warning: Unknown KeyError in parsing API response') else: if res[self.page_key]['page'] != res[self.page_key]['pages']: yield res else: break
{ "domain": "codereview.stackexchange", "id": 42775, "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, api", "url": null }
python, api def _generate_releases_on_page(self, page): """Extracts needed information from API response page and returns it as a namedtuple.""" Release = namedtuple('Release', 'id title artists genres styles labels year mediums') items = page[self.want_key] for item in items: release = Release(item[self.id_key], item['basic_information']['title'], [artist['name'] for artist in item['basic_information']['artists']], [genre for genre in item['basic_information']['genres']], [style for style in item['basic_information']['styles']], [label['name'] for label in item['basic_information']['labels']], item['basic_information']['year'], [{'medium': medium['name'], 'description': medium['descriptions'], 'qty': medium['qty']} for medium in item['basic_information']['formats']]) yield release def __iter__(self): """Generates release info for the specified wantlist url.""" for page in self._generate_pages(): for rid in self._generate_releases_on_page(page): yield rid Finally, this is how the @verify decorator is implemented: import requests import sys import time
{ "domain": "codereview.stackexchange", "id": 42775, "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, api", "url": null }
python, api Finally, this is how the @verify decorator is implemented: import requests import sys import time def verify(fn): """ Attempts to execute the function at most 10 times. If execution is successful, the function returns. If execution throws a Connection Error, try again after 10 seconds. If execution is not successful after 10 times, the program terminates. """ def wrapper(*args, **kwargs): for attempt in range(10): try: json = fn(*args, **kwargs) break except requests.exceptions.ConnectionError: time.sleep(10) else: sys.exit() return json return wrapper Answer: Sessions When you are making repeated requests against a host, you should use requests.Session(). Sessions make it easy to persist cookies, headers etc and improve performance by reusing TCP connections. They should probably be the preferred way of using requests. API The API doc provides some useful information. For instance: Your application must provide a User-Agent string that identifies itself – preferably something that follows RFC 1945... But you are not doing that. So your user agent is a default value like: python-requests/2.26.0. Strike one. They also write in the FAQ: Why am I getting an empty response from the server? This generally happens when you forget to add a User-Agent header to your requests. Regarding rate limiting: they provide some headers in their responses, like this one: X-Discogs-Ratelimit-Remaining: The number of remaining requests you are able to make in the existing rate limit window.
{ "domain": "codereview.stackexchange", "id": 42775, "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, api", "url": null }
python, api So you should be using those headers to track your own consumption and adjust your rate accordingly. Strike two. Status code: you are not checking the status code for your requests. If you get anything else than 200 (or at least in the 200 range), than quite likely an error has occurred and you should log the response and investigate. The point is to make your bot aware, and not shoot blindly in the dark, spamming a server with requests that may not even succeed. Strike three. If you get a non-200 response, then your code will crash anyway because you are attempting to fetch a JSON response that isn't there. It's easy to anticipate errors if you systematically inspect the status code. You have a number of JSON keys like self.want_key = 'wants' or self.page_key = 'pagination' but I am not sure they provide much benefit because they are used in one function. They make the code slightly less transparent. instead of writing: url = res[self.page_key][self.url_key][self.next_key] I think you could simply write: url = res['pagination']['urls']['next'] Basically, just like you did in function _generate_releases_on_page. The API specifications may change at some point, but in either case you would have to perform search and replace across your code. I can't see how those variables improve the situation. But you can protect yourself against unexpected changes in the format of the responses: Currently, our API only supports one version: v2. However, you can specify a version in your requests to future-proof your application. By adding an Accept header with the version and media type, you can guarantee your requests will receive data from the correct version you develop your app on. A standard Accept header may look like this: application/vnd.discogs.v2.html+json Simplification This function can be reduced a bit: def _get_response(self, url): """Makes a request to the specified url.""" request = requests.get(url) json = request.json() return json
{ "domain": "codereview.stackexchange", "id": 42775, "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, api", "url": null }
python, api Why not simply do: def _get_response(self, url): """Makes a request to the specified url.""" request = requests.get(url) return request.json() You're not doing anything with the JSON, so the variable assignment is unneeded. This function is extremely short and it's very obvious what it does, so the comment does not teach me anything. But _get_response is very generic, I would perhaps rename the function to _get_json_response to be more explicit. Note that the user agent and some other useful requests headers can be set once in your session, and then you no longer have to worry about them. They will be added automatically to your requests. Moreover, you can still pass additional headers on a per-request basis if needed. while True is a code smell here: def _generate_pages(self): """Generates all pages of the paginated API response. Throttles requests automatically if needed.""" url = self.wantlist_url while True: res = self._get_response(url) try: url = res[self.page_key][self.url_key][self.next_key] except KeyError: if 'message' in res.keys() and res['message'] == "You are making requests too quickly.": time.sleep(60) else: print('Warning: Unknown KeyError in parsing API response') else: if res[self.page_key]['page'] != res[self.page_key]['pages']: yield res else: break Since you expect a response like this: { "pagination": { "page": 1, "pages": 17, "per_page": 500, "items": 8022, "urls": { "last": "https://api.discogs.com/users/damonrthomas/wants?page=17&per_page=500", "next": "https://api.discogs.com/users/damonrthomas/wants?page=2&per_page=500" } }, "wants": [ ...
{ "domain": "codereview.stackexchange", "id": 42775, "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, api", "url": null }
python, api you know how many pages to fetch. So you either do a regular for ... in range statement, or while current_page < pages. The other problem is the timing, you are pounding the server with a lot of requests without pause - until you get blocked - and then you wait 60s to reset your window. It is a crude way of doing it. I would either get rid of the verify decorator, or rewrite it to take full advantage of the response headers at your disposal. Then the function can be used to perform sensible throttling on your end, not just wait 60 seconds but a more flexible rate that is in line with the permitted usage. You already have an indication here: Requests are throttled by the server by source IP to 60 per minute for authenticated requests, and 25 per minute for unauthenticated requests, with some exceptions. Get a token, then add a systematic delay of about 1s after every request + some margin and you should be fine. You may not experience any blocking if you play nice, and your code will perform better and more reliably. But do check the response headers to verify that you are always within limits. And do check the status code, always.
{ "domain": "codereview.stackexchange", "id": 42775, "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, api", "url": null }
c++, image, template, classes, c++20 Title: Checking image size in C++ Question: This is a follow-up question for 3D Inverse Discrete Cosine Transformation Implementation in C++. After checking G. Sliepen's answer, I am trying to update the part of width and height checking of Image class. Instead using macros, there are several template functions is_width_same, is_height_same, is_size_same, assert_width_same, assert_height_same, assert_size_same and check_size_same proposed in this post. The experimental implementation is_width_same template functions implementation: template<typename ElementT> constexpr bool is_width_same(const Image<ElementT>& x, const Image<ElementT>& y) { return x.getWidth() == y.getWidth(); } template<typename ElementT> constexpr bool is_width_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z) { return is_width_same(x, y) && is_width_same(y, z) && is_width_same(x, z); } is_height_same template functions implementation: template<typename ElementT> constexpr bool is_height_same(const Image<ElementT>& x, const Image<ElementT>& y) { return x.getHeight() == y.getHeight(); } template<typename ElementT> constexpr bool is_height_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z) { return is_height_same(x, y) && is_height_same(y, z) && is_height_same(x, z); } is_size_same template functions implementation: template<typename ElementT> constexpr bool is_size_same(const Image<ElementT>& x, const Image<ElementT>& y) { return is_width_same(x, y) && is_height_same(x, y); } template<typename ElementT> constexpr bool is_size_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z) { return is_size_same(x, y) && is_size_same(y, z) && is_size_same(x, z); }
{ "domain": "codereview.stackexchange", "id": 42776, "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++, image, template, classes, c++20", "url": null }
c++, image, template, classes, c++20 assert_width_same template functions implementation: wrap is_width_same function with assert. template<typename ElementT> constexpr void assert_width_same(const Image<ElementT>& x, const Image<ElementT>& y) { assert(is_width_same(x, y)); } template<typename ElementT> constexpr void assert_width_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z) { assert(is_width_same(x, y, z)); } assert_height_same template function implementation: wrap is_height_same function with assert. template<typename ElementT> constexpr void assert_height_same(const Image<ElementT>& x, const Image<ElementT>& y) { assert(is_height_same(x, y)); } template<typename ElementT> constexpr void assert_height_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z) { assert(is_height_same(x, y, z)); } assert_size_same template function implementation: template<typename ElementT> constexpr void assert_size_same(const Image<ElementT>& x, const Image<ElementT>& y) { assert_width_same(x, y); assert_height_same(x, y); } template<typename ElementT> constexpr void assert_size_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z) { assert_size_same(x, y); assert_size_same(y, z); assert_size_same(x, z); } check_size_same template function implementation: template<typename ElementT> constexpr void check_size_same(const Image<ElementT>& x, const Image<ElementT>& y) { if (!is_width_same(x, y)) throw std::runtime_error("Width mismatched!"); if (!is_height_same(x, y)) throw std::runtime_error("Height mismatched!"); } the updated version Image class: operator<< overloading updated. checkBoundary function implementation updated. I am trying to add a constructor with rvalue reference Image(std::vector<ElementT>&& input, std::size_t newWidth, std::size_t newHeight). Please also take a look about this part.
{ "domain": "codereview.stackexchange", "id": 42776, "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++, image, template, classes, c++20", "url": null }
c++, image, template, classes, c++20 template <typename ElementT> class Image { public: Image() = default; Image(const std::size_t width, const std::size_t height): width(width), height(height), image_data(width * height) { } Image(const std::size_t width, const std::size_t height, const ElementT initVal): width(width), height(height), image_data(width * height, initVal) {} Image(const std::vector<ElementT>& input, std::size_t newWidth, std::size_t newHeight): width(newWidth), height(newHeight) { if (input.size() != newWidth * newHeight) { throw std::runtime_error("Image data input and the given size are mismatched!"); } image_data = input; } Image(std::vector<ElementT>&& input, std::size_t newWidth, std::size_t newHeight): width(newWidth), height(newHeight) { if (input.size() != newWidth * newHeight) { throw std::runtime_error("Image data input and the given size are mismatched!"); } image_data = std::move(input); } constexpr ElementT& at(const unsigned int x, const unsigned int y) { checkBoundary(x, y); return image_data[y * width + x]; } constexpr ElementT const& at(const unsigned int x, const unsigned int y) const { checkBoundary(x, y); return image_data[y * width + x]; } constexpr std::size_t getWidth() const { return width; } constexpr std::size_t getHeight() const noexcept { return height; } constexpr auto getSize() noexcept { return std::make_tuple(width, height); } std::vector<ElementT> const& getImageData() const noexcept { return image_data; } // expose the internal data
{ "domain": "codereview.stackexchange", "id": 42776, "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++, image, template, classes, c++20", "url": null }
c++, image, template, classes, c++20 void print(std::string separator = "\t", std::ostream& os = std::cout) const { for (std::size_t y = 0; y < height; ++y) { for (std::size_t x = 0; x < width; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y) << separator; } os << "\n"; } os << "\n"; return; } // Enable this function if ElementT = RGB void print(std::string separator = "\t", std::ostream& os = std::cout) const requires(std::same_as<ElementT, RGB>) { for (std::size_t y = 0; y < height; ++y) { for (std::size_t x = 0; x < width; ++x) { os << "( "; for (std::size_t channel_index = 0; channel_index < 3; ++channel_index) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y).channels[channel_index] << separator; } os << ")" << separator; } os << "\n"; } os << "\n"; return; } friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs) { const std::string separator = "\t"; rhs.print(separator, os); return os; } Image<ElementT>& operator+=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::plus<>{}); return *this; }
{ "domain": "codereview.stackexchange", "id": 42776, "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++, image, template, classes, c++20", "url": null }
c++, image, template, classes, c++20 Image<ElementT>& operator-=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::minus<>{}); return *this; } Image<ElementT>& operator*=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::multiplies<>{}); return *this; } Image<ElementT>& operator/=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::divides<>{}); return *this; } friend bool operator==(Image<ElementT> const&, Image<ElementT> const&) = default; friend bool operator!=(Image<ElementT> const&, Image<ElementT> const&) = default; friend Image<ElementT> operator+(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 += input2; } friend Image<ElementT> operator-(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 -= input2; } Image<ElementT>& operator=(Image<ElementT> const& input) = default; // Copy Assign Image<ElementT>& operator=(Image<ElementT>&& other) = default; // Move Assign Image(const Image<ElementT> &input) = default; // Copy Constructor Image(Image<ElementT> &&input) = default; // Move Constructor
{ "domain": "codereview.stackexchange", "id": 42776, "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++, image, template, classes, c++20", "url": null }
c++, image, template, classes, c++20 Image(Image<ElementT> &&input) = default; // Move Constructor private: std::size_t width; std::size_t height; std::vector<ElementT> image_data; void checkBoundary(const size_t x, const size_t y) const { if (x >= width) throw std::out_of_range("Given x out of range!"); if (y >= height) throw std::out_of_range("Given y out of range!"); } }; Full Testing Code #include <algorithm> #include <cassert> #include <chrono> #include <cmath> #include <concepts> #include <cstdint> #include <exception> #include <fstream> #include <functional> #include <iostream> #include <iterator> #include <numbers> #include <numeric> #include <ranges> #include <string> #include <type_traits> #include <utility> #include <vector> struct RGB { std::uint8_t channels[3]; }; using GrayScale = std::uint8_t; namespace TinyDIP { template <typename ElementT> class Image { public: Image() = default; Image(const std::size_t width, const std::size_t height): width(width), height(height), image_data(width * height) { } Image(const std::size_t width, const std::size_t height, const ElementT initVal): width(width), height(height), image_data(width * height, initVal) {} Image(const std::vector<ElementT>& input, std::size_t newWidth, std::size_t newHeight): width(newWidth), height(newHeight) { if (input.size() != newWidth * newHeight) { throw std::runtime_error("Image data input and the given size are mismatched!"); } image_data = input; }
{ "domain": "codereview.stackexchange", "id": 42776, "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++, image, template, classes, c++20", "url": null }
c++, image, template, classes, c++20 Image(std::vector<ElementT>&& input, std::size_t newWidth, std::size_t newHeight): width(newWidth), height(newHeight) { if (input.size() != newWidth * newHeight) { throw std::runtime_error("Image data input and the given size are mismatched!"); } image_data = std::move(input); } constexpr ElementT& at(const unsigned int x, const unsigned int y) { checkBoundary(x, y); return image_data[y * width + x]; } constexpr ElementT const& at(const unsigned int x, const unsigned int y) const { checkBoundary(x, y); return image_data[y * width + x]; } constexpr std::size_t getWidth() const { return width; } constexpr std::size_t getHeight() const noexcept { return height; } constexpr auto getSize() noexcept { return std::make_tuple(width, height); } std::vector<ElementT> const& getImageData() const noexcept { return image_data; } // expose the internal data void print(std::string separator = "\t", std::ostream& os = std::cout) const { for (std::size_t y = 0; y < height; ++y) { for (std::size_t x = 0; x < width; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y) << separator; } os << "\n"; } os << "\n"; return; }
{ "domain": "codereview.stackexchange", "id": 42776, "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++, image, template, classes, c++20", "url": null }
c++, image, template, classes, c++20 // Enable this function if ElementT = RGB void print(std::string separator = "\t", std::ostream& os = std::cout) const requires(std::same_as<ElementT, RGB>) { for (std::size_t y = 0; y < height; ++y) { for (std::size_t x = 0; x < width; ++x) { os << "( "; for (std::size_t channel_index = 0; channel_index < 3; ++channel_index) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y).channels[channel_index] << separator; } os << ")" << separator; } os << "\n"; } os << "\n"; return; } friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs) { const std::string separator = "\t"; rhs.print(separator, os); return os; } Image<ElementT>& operator+=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::plus<>{}); return *this; } Image<ElementT>& operator-=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::minus<>{}); return *this; }
{ "domain": "codereview.stackexchange", "id": 42776, "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++, image, template, classes, c++20", "url": null }
c++, image, template, classes, c++20 Image<ElementT>& operator*=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::multiplies<>{}); return *this; } Image<ElementT>& operator/=(const Image<ElementT>& rhs) { assert(rhs.width == this->width); assert(rhs.height == this->height); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::divides<>{}); return *this; } friend bool operator==(Image<ElementT> const&, Image<ElementT> const&) = default; friend bool operator!=(Image<ElementT> const&, Image<ElementT> const&) = default; friend Image<ElementT> operator+(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 += input2; } friend Image<ElementT> operator-(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 -= input2; } Image<ElementT>& operator=(Image<ElementT> const& input) = default; // Copy Assign Image<ElementT>& operator=(Image<ElementT>&& other) = default; // Move Assign Image(const Image<ElementT> &input) = default; // Copy Constructor Image(Image<ElementT> &&input) = default; // Move Constructor private: std::size_t width; std::size_t height; std::vector<ElementT> image_data;
{ "domain": "codereview.stackexchange", "id": 42776, "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++, image, template, classes, c++20", "url": null }
c++, image, template, classes, c++20 void checkBoundary(const size_t x, const size_t y) const { if (x >= width) throw std::out_of_range("Given x out of range!"); if (y >= height) throw std::out_of_range("Given y out of range!"); } }; template<typename ElementT> constexpr bool is_width_same(const Image<ElementT>& x, const Image<ElementT>& y) { return x.getWidth() == y.getWidth(); } template<typename ElementT> constexpr bool is_width_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z) { return is_width_same(x, y) && is_width_same(y, z) && is_width_same(x, z); } template<typename ElementT> constexpr bool is_height_same(const Image<ElementT>& x, const Image<ElementT>& y) { return x.getHeight() == y.getHeight(); } template<typename ElementT> constexpr bool is_height_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z) { return is_height_same(x, y) && is_height_same(y, z) && is_height_same(x, z); } template<typename ElementT> constexpr bool is_size_same(const Image<ElementT>& x, const Image<ElementT>& y) { return is_width_same(x, y) && is_height_same(x, y); } template<typename ElementT> constexpr bool is_size_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z) { return is_size_same(x, y) && is_size_same(y, z) && is_size_same(x, z); } template<typename ElementT> constexpr void assert_width_same(const Image<ElementT>& x, const Image<ElementT>& y) { assert(is_width_same(x, y)); } template<typename ElementT> constexpr void assert_width_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z) { assert(is_width_same(x, y, z)); }
{ "domain": "codereview.stackexchange", "id": 42776, "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++, image, template, classes, c++20", "url": null }
c++, image, template, classes, c++20 template<typename ElementT> constexpr void assert_height_same(const Image<ElementT>& x, const Image<ElementT>& y) { assert(is_height_same(x, y)); } template<typename ElementT> constexpr void assert_height_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z) { assert(is_height_same(x, y, z)); } template<typename ElementT> constexpr void assert_size_same(const Image<ElementT>& x, const Image<ElementT>& y) { assert_width_same(x, y); assert_height_same(x, y); } template<typename ElementT> constexpr void assert_size_same(const Image<ElementT>& x, const Image<ElementT>& y, const Image<ElementT>& z) { assert_size_same(x, y); assert_size_same(y, z); assert_size_same(x, z); } template<typename ElementT> constexpr void check_size_same(const Image<ElementT>& x, const Image<ElementT>& y) { if (!is_width_same(x, y)) throw std::runtime_error("Width mismatched!"); if (!is_height_same(x, y)) throw std::runtime_error("Height mismatched!"); } } void checkSizeTest(const std::size_t xsize, const std::size_t ysize) { auto image1 = TinyDIP::Image<std::uint8_t>(xsize, ysize); auto image2 = TinyDIP::Image<std::uint8_t>(xsize + 1, ysize); auto image3 = TinyDIP::Image<std::uint8_t>(xsize, ysize + 1); auto image4 = TinyDIP::Image<std::uint8_t>(xsize + 1, ysize + 1); check_size_same(image1, image1); return; } int main() { auto start = std::chrono::system_clock::now(); checkSizeTest(8, 8); auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n'; return 0; }
{ "domain": "codereview.stackexchange", "id": 42776, "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++, image, template, classes, c++20", "url": null }
c++, image, template, classes, c++20 A Godbolt link is here. TinyDIP on GitHub All suggestions are welcome. The summary information: Which question it is a follow-up to? 3D Inverse Discrete Cosine Transformation Implementation in C++ What changes has been made in the code since last question? There are several template functions is_width_same, is_height_same, is_size_same, assert_width_same, assert_height_same, assert_size_same and check_size_same proposed in this post. Why a new review is being asked for? If there is any possible improvement, please let me know. Answer: Make it work for any number of images I see you have overloads for comparing two and for comparing three images. But that immediately makes me think: why not compare four? Or more? You can make a variadic function that uses a fold expression to check the dimensions of an arbitrary number of images with each other: template<typename T, typename... Ts> constexpr bool is_width_same(const Image<T>& x, const Image<Ts>&... y) { return ((x.getWidth() == y.getWidth()) && ...); } As a bonus, this will also allow you to check that the dimensions of two images using a different value type are the same. If you really don't want that, you can add a requires clause to force them to all be the same: requires (std::same_as<T, Ts> && ...) Consider removing the assert_*_same() helpers You are not saving much typing with these helper functions, compare: assert(is_width_same(x, y)); assert_width_same(x, y); It saves only 4 characters, but the drawback is that when the assert triggers, the second one will show a line number inside assert_width_same() instead of the line number of the call site. It is different for check_size_same(); at least on Linux, if an unhandled exception is thrown, it prints the what() but no line number, so nothing is lost by putting the throw statements in a function.
{ "domain": "codereview.stackexchange", "id": 42776, "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++, image, template, classes, c++20", "url": null }
vba, rubberduck Title: Produce date range string from a database table Question: My project creates a report based on test results which are stored in database table associated with a JobNumber. The test results for a particular JobNumber may be all be from the same date or from a range of dates. I create a report to display results for a single JobNumber and this report contains a string to display this date or range in a readable way. The following code would produce the date range string from the two classes outlined below and the two interfaces implied below: With ReportRepository.Create("1234") Debug.print .MonitoringDates End With The desired output of IReportRepository.MonitoringDates: "01 January 2022" - single date "01 - 02 January 2022" - date range in same month "01 January - 01 February 2022" - date range across different months "01 January 2022 - 01 January 2023" - date range across different years The project uses Rubberduck SecureADODB - https://github.com/rubberduck-vba/examples/tree/master/SecureADODB SecureDatabase class, Implements IDataAccessObject: '@Folder "ProjectWriter.DataAccessObject" Option Explicit Implements IDataAccessObject Private Type TSecureDatabase SecureConnetion As IDbConnection Command As IDbCommand End Type Private this As TSecureDatabase Const ConnectionString As String = "<connection string here>" Private Sub Class_Initialize() Dim Mappings As ITypeMap Set Mappings = AdoTypeMappings.Default Dim Provider As IParameterProvider Set Provider = AdoParameterProvider.Create(Mappings) Dim BaseCommand As IDbCommandBase Set BaseCommand = DbCommandBase.Create(Provider) With DbConnection.Create(ConnectionString) Set this.Command = DefaultDbCommand.Create(.Self, BaseCommand) End With End Sub
{ "domain": "codereview.stackexchange", "id": 42777, "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": "vba, rubberduck", "url": null }
vba, rubberduck Private Function IDataAccessObject_MonitoringStartDate(ByVal JobNumber As String) As Date AllErrors.GuardEmptyString JobNumber IDataAccessObject_MonitoringStartDate = this.Command.GetSingleValue("SELECT MIN(SampleDate) FROM Results JOIN Jobs ON Results.JobID = Jobs.ID WHERE Jobs.JobNumber = ? LIMIT 1", JobNumber) End Function Private Function IDataAccessObject_MonitoringEndDate(ByVal JobNumber As String) As Date AllErrors.GuardEmptyString JobNumber IDataAccessObject_MonitoringEndDate = this.Command.GetSingleValue("SELECT MAX(SampleDate) FROM Results JOIN Jobs ON Results.JobID = Jobs.ID WHERE Jobs.JobNumber = ? LIMIT 1", JobNumber) End Function 'other functions ReportRepository class, Implements IReportRepository '@Folder("ProjectWriter.Repository") '@PredeclaredId Option Explicit Implements IReportRepository Private Type TReportRepository DataAccessObject As IDataAccessObject MonitoringDates As String 'other members End Type Private this As TReportRepository Public Property Get Self() As ReportRepository Set Self = Me End Property Public Function Create(ByVal JobNumber As String) As IReportRepository AllErrors.GuardEmptyString JobNumber With New ReportRepository .Initialise JobNumber Set Create = .Self End With End Function Public Sub Initialise(ByVal JobNumber As String) this.JobNumber = JobNumber Set this.DataAccessObject = New SecureDatabase With this.DataAccessObject this.MonitoringDates = MonitoringDates(.MonitoringStartDate(JobNumber), .MonitoringEndDate(JobNumber)) 'initialisation of other members End With End Sub
{ "domain": "codereview.stackexchange", "id": 42777, "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": "vba, rubberduck", "url": null }
vba, rubberduck Private Function MonitoringDates(ByVal StartDate As Date, ByVal EndDate As Date) As String Dim StartMonth As String StartMonth = VBA.Format$(StartDate, "mmmm") Dim EndMonth As String EndMonth = VBA.Format$(EndDate, "mmmm") Dim StartYear As String StartYear = VBA.Format$(StartDate, "yyyy") Dim EndYear As String EndYear = VBA.Format$(EndDate, "yyyy") Dim Dates As String Select Case True Case EndDate = StartDate: Dates = VBA.Format$(StartDate, "dd mmmm yyyy") Case StartMonth = EndMonth And StartYear = EndYear Dates = VBA.Format$(StartDate, "dd") & " - " & VBA.Format$(EndDate, "dd mmmm yyyy") Case StartYear = EndYear Dates = VBA.Format$(StartDate, "dd mmmm") & " - " & VBA.Format$(EndDate, "dd mmmm yyyy") Case Else: Dates = VBA.Format$(StartDate, "dd mmmm yyyy") & " - " & VBA.Format$(EndDate, "dd mmmm yyyy") End Select MonitoringDates = Dates End Function Private Property Get IReportRepository_MonitoringDates() As String IReportRepository_MonitoringDates = this.MonitoringDates End Property 'other properties I invite your comments, particularly on: If I am using the SecureADODB correctly - I was thinking there may be a way to refactor what I am doing to include both the start and end date in a single transaction or query and whether this would be worthwhile. If there is a more efficient way of producing the date range string compared to the VBA select case. Any comments on the structure of the classes for what I appear to be doing. Or any other comments on how I can improve the way this code is written. Sorry if I have missed anything that I should have included, this is my first code review post. Thanks in advance! Answer: Regarding the points of interest you identified:
{ "domain": "codereview.stackexchange", "id": 42777, "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": "vba, rubberduck", "url": null }
vba, rubberduck Answer: Regarding the points of interest you identified: Using either one or two queries to get your data can be acceptable so long as it meets your performance criteria in actual use. However, I am going to suggest that you package the two results (Start and End dates) within a data object so that the rest of your code can operate on a single context of data from the database. More efficient way to produce the date range string: Using Select Case can become a problem if the number of possible cases can continue to grow over time. It would seem there is only a finite number of ways that the range string will be represented...So, using Select Case looks OK here. On the other hand, the order of the Case statements matter here because they do not specify entirely independent cases. Because of this, I would use If-ElseIf-Else instead because it makes this overlapping condition more obvious. Also, there are some opportunities to apply the Don't Repeat Yourself (DRY) principle within the date range string code. Structure: There are some structural changes that I am suggesting for you to consider. Instantiating a SecureDatabase instance inside the ReportRepository object would be considered inconsistent with SOLID coding practices (in particular, the letters "L" and "D"). In the code below, the ReportRepository is rewritten to consume an IDataAccessObject reference and a JobNumber in its Create function input parameters.
{ "domain": "codereview.stackexchange", "id": 42777, "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": "vba, rubberduck", "url": null }
vba, rubberduck (Testing) A consequence of creating the SecureDatabase instance within the ReportRepository object is that it is impossible to test the code without the existence of a database. And, accordingly, I noticed a Sample database identifier within the SQL statements of the provided code. Passing in an IDataAccessObject facilitates testing free of a database (Sample or otherwise) and is more consistent with SOLID coding practices. Further, in the spirit of easy testing, the MonitoringDates function was made Public to allow testing without having to call ReportRepository.Create or have a database. The code below is a revised version incorporating the points described above. ReportRepository '@PredeclaredId '@Folder("ProjectWriter.Repository") Option Explicit Implements IReportRepository Private Type TReportRepository MonitoringDates As String JobNumber As String StartDate As Date EndDate As Date SecureDatabase As IDataAccessObject End Type Private this As TReportRepository Public Property Get Self() As ReportRepository Set Self = Me End Property Public Function Create(ByVal dDB As IDataAccessObject, ByVal JobNumber As String) As IReportRepository With New ReportRepository .Initialise dDB, JobNumber Set Create = .Self End With End Function Public Sub Initialise(ByVal dDB As IDataAccessObject, ByVal JobNumber As String) Set this.SecureDatabase = dDB this.JobNumber = JobNumber Dim dataObject As DateRangeDTO Set dataObject = this.SecureDatabase.RetrieveDateRangeDTO(JobNumber) this.StartDate = dataObject.StartDate this.EndDate = dataObject.EndDate this.MonitoringDates = MonitoringDates(dataObject.StartDate, dataObject.EndDate) End Sub Public Function MonitoringDates(ByVal vbaStartDate As Date, ByVal vbaEndDate As Date) As String
{ "domain": "codereview.stackexchange", "id": 42777, "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": "vba, rubberduck", "url": null }
vba, rubberduck Public Function MonitoringDates(ByVal vbaStartDate As Date, ByVal vbaEndDate As Date) As String Dim dStartDateFormat As String dStartDateFormat = "dd mmmm yyyy" Dim endDateExpression As String endDateExpression = VBA.Format$(vbaEndDate, dStartDateFormat) Dim toEndDateExpression As String toEndDateExpression = " - " & endDateExpression If vbaStartDate = vbaEndDate Then MonitoringDates = endDateExpression ElseIf VBA.Year(vbaStartDate) = VBA.Year(vbaEndDate) Then dStartDateFormat = IIf(VBA.Month(vbaStartDate) = VBA.Month(vbaEndDate), "dd", "dd mmmm") MonitoringDates = VBA.Format$(vbaStartDate, dStartDateFormat) & toEndDateExpression Else MonitoringDates = VBA.Format$(vbaStartDate, dStartDateFormat) & toEndDateExpression End If End Function Private Property Get IReportRepository_MonitoringDates() As String IReportRepository_MonitoringDates = this.MonitoringDates End Property 'other properties IDataAccessObject IDataAccessObject was modified to return a simple data object Public Function RetrieveDateRangeDTO(ByVal JobNumber As String) As DateRangeDTO End Function DateRangeDTO DateRangeDTO keeps the Job number, start and end dates as a single context. Option Explicit Private Type TDateRangeDTO JobNumber As String StartDate As Date EndDate As Date End Type Private this As TDateRangeDTO Public Property Get JobNumber() As String JobNumber = this.JobNumber End Property Public Property Let JobNumber(ByVal RHS As String) this.JobNumber = RHS End Property Public Property Get StartDate() As Date StartDate = this.StartDate End Property Public Property Let StartDate(ByVal RHS As Date) this.StartDate = RHS End Property Public Property Get EndDate() As Date EndDate = this.EndDate End Property Public Property Let EndDate(ByVal RHS As Date) this.EndDate = RHS End Property
{ "domain": "codereview.stackexchange", "id": 42777, "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": "vba, rubberduck", "url": null }
vba, rubberduck An example of testing without a database using a Fake object SecureDatabaseFake Implements IDataAccessObject Private Type TSecureDatabaseFake TestDTO As DateRangeDTO End Type Private this As TSecureDatabaseFake Const ConnectionString As String = "<connection string here>" Private Function IDataAccessObject_RetrieveDateRangeDTO(ByVal testJobNumber As String) As DateRangeDTO this.TestDTO.JobNumber = testJobNumber Set IDataAccessObject_RetrieveDateRangeDTOO = this.TestDTO End Function Public Sub LoadDateRangeDTO(ByVal testDataDTO As DateRangeDTO) Set this.TestDTO = testDataDTO End Sub A couple tests made possible by using the database Fake and other changes: Option Explicit Sub Test() 'Arrange Dim dDBFake As SecureDatabaseFake Set dDBFake = New SecureDatabaseFake Dim dDB As IDataAccessObject Set dDB = dDBFake Dim dDTO As DateRangeDTO Set dDTO = New DateRangeDTO dDTO.StartDate = DateValue("January 3, 2022") dDTO.EndDate = DateValue("August 4, 2045") 'Specify the results that the fake database should return dDBFake.LoadDateRangeDTO dDTO 'Act Dim dRep As IReportRepository Set dRep = ReportRepository.Create(dDB, "1234") 'Assert If dRep.MonitoringDates <> "03 January 2022 - 04 August 2045" Then MsgBox "Test Failed" Exit Sub End If MsgBox "TestPassed" End Sub Sub TestMonitoringDatesDirectly() Dim dTestResult As String dTestResult = ReportRepository.MonitoringDates(DateValue("January 3, 2022"), DateValue("January 14, 2022")) If dTestResult <> "03 - 14 January 2022" Then MsgBox "Test Failed" Exit Sub End If MsgBox "TestPassed" End Sub
{ "domain": "codereview.stackexchange", "id": 42777, "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": "vba, rubberduck", "url": null }
python, python-3.x, matrix Title: Rotating a matrix clockwise by one element without any libraries (Python 3.9) Question: The question is as follows: Rotate an NxN matrix clockwise by one element and display the new matrix. For example, if A = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10,11,12], [13,14,15,16]] Then the rotated matrix obtained from A will be [[5, 1, 2, 3], [9, 10, 6, 4], [13, 11, 7, 8], [14, 15, 16, 12]] You may think of it as rotating each of the "rings" clockwise by one element. So, that was the question given to us and we were told to absolutely not use Numpy or any other library that can handle matrices. Here's what I did: def get_previous_pos(i, j, matrix_size): ring_no = min(j, matrix_size-1-j, i, matrix_size-1-i) max_no = matrix_size - 1 - ring_no x = i + (j==ring_no) - (j==max_no) - (i==max_no and j==ring_no) + (j==max_no and i==ring_no) y = j + (i==max_no) - (i==ring_no) - (i==max_no and j==max_no) + (i==ring_no and j==ring_no) return x,y def get_rotated_matrix(matrix): n = len(matrix) rotated_matrix = [matrix[row_no][:] for row_no in range(n)] for i in range(n): for j in range(n): prev = get_previous_pos(i, j, n) rotated_matrix[i][j] = matrix[prev[0]][prev[1]] return rotated_matrix n = int(input("Enter size of the square matrix: ")) matrix = [[int(input()) for j in range(n)] for i in range(n)] print("original matrix --> ", matrix) print("rotated matrix --> ", get_rotated_matrix(matrix))
{ "domain": "codereview.stackexchange", "id": 42778, "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, python-3.x, matrix", "url": null }
python, python-3.x, matrix The function, get_rotated_matrix(matrix) takes any 2D NxN list and returns the rotated 2D list. The get_previous_pos(i,j,matrix_size) function takes a matrix position as its (i,j) value, the matrix size(N), and returns the position of the element that will occupy (i,j) after the clockwise rotation. I have tested this code for matrix sizes ranging from 1X1 up to 5x5. It did produce the desired output. So, I suppose its safe to say that it works. However, I'm sure there's a much better way to go about this and was wondering if you can help me out. Edit: I've added a bit of driver code to the original so it can be tested without further modification. I've also attached a sample input/output below for a 4x4 matrix: Enter size of the square matrix: 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 original matrix --> [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] rotated matrix --> [[5, 1, 2, 3], [9, 10, 6, 4], [13, 11, 7, 8], [14, 15, 16, 12]] Answer: When possible, iterate directly over collections. Most of the time, you don't need indexes when iterating over Python collections. As an example, here's an easier way to initialize an independent copy of the matrix. (Or just use deepcopy). rotated_matrix = [list(row) for row in matrix] Put all code inside of functions or methods. Some will say it's alright to put a little bit of logic, including defining variables, after the __main__ guard. Don't do it. Just adopt the discipline of never doing more than calling a function and you'll avoid time wasted on silly bugs caused by the unexpected presence of global variables that you had forgotten about during the heat of code writing. Here's the template I use for scripts like this: # Only imports, functions, classes, and constants at top level. import sys def main(args): ... if __name__ == '__main__': main(sys.argv[1:])
{ "domain": "codereview.stackexchange", "id": 42778, "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, python-3.x, matrix", "url": null }
python, python-3.x, matrix import sys def main(args): ... if __name__ == '__main__': main(sys.argv[1:]) Don't make humans enter a matrix one cell at a time. Python is powerful. You can easily parse a variety of simple input formats for a matrix (e.g., "1,2,3,4 5,6,7,8 9,10,11,12 13,14,15,16"). Even better, since this is mostly a learning project, just define a matrix or two in your code (as constants) and let the user pick one via a short name. I'm not endorsing any particular strategy, but the current usage implementation too painful, too much work. Part of becoming a better software engineer is developing a deep loathing for that kind of tedium -- in other words, cultivating your laziness. An opaque algorithm that is probably fine but isn't easy to understand. You've done a good job posing a clear question, and I can understand the general outlines of your code and strategy easily enough. However, the logic in get_previous_pos() -- in many ways, the heart of the program -- is opaque. It's the kind of math-heavy logic that one has to dig into deeply to understand. I assume it works but it's neither intuitive nor self-evidently correct. An alternative to consider. I don't know if this will be valuable to you, but here's how I worked when trying to solve this interesting problem. I started in fantasy land, with a top level function that is easy to understand only because it hand-waves away the complexity to a not-yet-written utility function: def get_rotated_matrix(matrix): rotated = [list(row) for row in matrix] for (r1, c1), (r2, c2) in get_index_rings(len(matrix)): rotated[r2][c2] = matrix[r1][c1] return rotated
{ "domain": "codereview.stackexchange", "id": 42778, "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, python-3.x, matrix", "url": null }
python, python-3.x, matrix And then I tried to write the utility function in an intuitive way. I envisioned each of the matrix "rings" as a starting position on the diagonal (eg, (0, 0)) plus a sequence of movements (right, down, left, up). To the extent that I have succeeded in writing a more intuitive version, here are some of the key points that I would emphasize: (1) declarative names when helpful (eg, the direction constants); (2) comments to guide the reader by providing context and information about purpose or strategy; (3) the use of blank lines plus those comments to group the code into meaningful sub-units; and (4) an algorithm backed by a simple narrative (we drive around the ring, making turns). def get_index_rings(n): # Movement directions. RIGHT, DOWN, LEFT, UP = [(0, 1), (1, 0), (0, -1), (-1, 0)] # The starting positions for each of the rings are the points # on the diagonal: (0,0), (1,1), etc until we reach the middle. # When n is odd, the innermost ring is a single cell and can be ignored. for start in range(n // 2): # Inital position. r, c = (start, start) # The movements around the current ring. times = n - start - start - 1 moves = [RIGHT] * times + [DOWN] * times + [LEFT] * times + [UP] * times # Yield position pairs as we move around the ring: (CURRENT, NEXT). for dr, dc in moves: p1 = (r, c) r += dr c += dc yield (p1, (r, c))
{ "domain": "codereview.stackexchange", "id": 42778, "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, python-3.x, matrix", "url": null }
c++, algorithm, graph Title: Implementing graph for pathfinding Question: I need a graph for multiple pathfinding algorithms,so I wanted to ask whether my new graph implementation is ok. Would someone who works as a developer in related fields(Graphs, Pathfinding, Algorithms) do things similarly. Node class: #include "Coordinates.hpp" #include <stdint.h> namespace Pathfinding::Datastructures { struct Node { Node() = delete; constexpr explicit Node(uint32_t i_ ) : id(i_) {}; uint32_t id; }; [[nodiscard]] bool operator<(const Node & lhs, const Node & rhs); [[nodiscard]] bool operator==(const Node & lhs, const Node & rhs); } Here is my graph.hpp: #include <map> #include <vector> #include "Node.hpp" #include "Connection.hpp" namespace Pathfinding::Datastructures { class Graph { public: Graph() = default; void addConnection(Node start, Node goal, double weight); [[nodiscard]] auto begin() { return data.begin(); } [[nodiscard]] auto end() { return data.end(); } [[nodiscard]] const auto begin() const { return data.begin(); } [[nodiscard]] const auto end() const { return data.end(); } [[nodiscard]] std::size_t size() const { return data.size(); } [[nodiscard]] bool contains(Node node) const { return data.contains(node); } [[nodiscard]] std::vector<Connection> operator[](Node node) const; protected: std::map<Node, std::vector<Connection>> data; }; } Graph.cpp: #include "Graph.hpp" #include <vector> #include <exception> #include "Connection.hpp" #include "Node.hpp" #include <iostream>
{ "domain": "codereview.stackexchange", "id": 42779, "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++, algorithm, graph", "url": null }
c++, algorithm, graph #include "Connection.hpp" #include "Node.hpp" #include <iostream> namespace Pathfinding::Datastructures { namespace { [[nodiscard]] bool nodeContainsConnection(const Graph & graph, const Node & start, const Node & end) { for(const auto neighbor : graph[start]) { if(neighbor.node == end) { return true; } } return false; } } void Graph::addConnection(Node start, Node goal, double weight) { if(data.contains(start)) { if(!nodeContainsConnection(*this, start, goal)) { data[start].push_back(Connection(goal, weight)); data[goal].push_back(Connection(start, weight)); } } else { data[start] = {Connection(goal, weight)}; data[goal] = {Connection(start, weight)}; } } std::vector<Connection> Graph::operator[](Node node) const { const auto it = data.find(node); if(it == data.end()) { throw std::exception("Node not present in graph"); } return it->second; } } Here is connection: namespace Pathfinding::Datastructures { struct Connection { Connection() = delete; Connection(Node node_, double weight_) : node(node_), weight(weight_) {} Node node; double weight; }; [[nodiscard]] bool operator==(const Connection & lhs, const Connection & rhs); } Connection.cpp: #include "Connection.hpp" namespace Pathfinding::Datastructures { bool operator==(const Connection & lhs, const Connection & rhs) { return lhs.weight == rhs.weight && lhs.node == rhs.node; } }
{ "domain": "codereview.stackexchange", "id": 42779, "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++, algorithm, graph", "url": null }
c++, algorithm, graph Answer: No need to delete or default the default constructors If you add a user-declared constructor to a class, the compiler will not generate an implicit default constructor. So there is no need to = delete it. Conversely, if you didn't add any user-declared constructors, it will generate an implicit default constructor, so there is no need to explicitly add one using = default. Consider using a std::unordered_map Graph algorithms don't care about the order of nodes, so consider using a std::unordered_map instead of a std::map to hold the nodes and their adjacency lists. Looking up nodes in a std::unordered_map is \$O(1)\$, compared to \$O(\log N)\$ for std::map. You can still iterate over it using begin() and end(). Return the adjacency list by reference Graph::operator[]() returns a std::vector<Connection> by value. This causes a copy to be made every time it is called, which can be expensive, especially in large, dense graphs. Return it by (const) reference, just like data.operator[]() does. Use the same semantics as the STL containers You already use the same names for member functions as STL containers, like begin() and size(). That's great, it means it is easier for someone to use your Graph class if they already know how to use STL containers. But also make sure the behavior of these functions matches that of the STL. In particular, operator[] does not throw exceptions, so yours should not either. STL containers provide the member function at() that does throw if the key you provided is not found. Consider adding an at() member function to your own class if you want this functionality. If you don't like that operator[] might insert a node that didn't exist yet, consider not adding that member function to Graph. Make nodeContainsConnection() a member function of Graph It is strange that nodeContainsConnection() is not a member function, unlike other functions like addConnection(). I would also rename it to containsConnection(). Simplify addConnection()
{ "domain": "codereview.stackexchange", "id": 42779, "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++, algorithm, graph", "url": null }
c++, algorithm, graph Simplify addConnection() Make use of the fact that operator[] will access an element or insert it if it didn't exist yet. If it inserts one, a std::vector<Connection> will be default constructed, so you can immediately push_back() on it, or even better, use emplace_back(): void Graph::addConnection(Node start, Node goal, double weight) { if (containsConnection(start, goal)) return;
{ "domain": "codereview.stackexchange", "id": 42779, "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++, algorithm, graph", "url": null }
c++, algorithm, graph data[start].emplace_back(goal, weight); data[goal].emplace_back(start, weight); }
{ "domain": "codereview.stackexchange", "id": 42779, "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++, algorithm, graph", "url": null }
c, makefile Title: C Makefile boilerplate Question: This is the current Makefile that I use with my C projects. Here is what I would like to be reviewed: Reusability - is this Makefile easy to use for multiple separate projects with minimal modification? Organization - is this Makefile organized in a logical and readable way? Dynamics - are there Make features (or compiler options/warnings) that I am not taking advantage of that could make my Makefile more powerful? Miscellaneous - what other things could I improve? CXX = g++-4.9 CC = gcc-4.9 DOXYGEN = doxygen CFLAGS = -fdiagnostics-color=always -std=gnu11 -s -c -g3 -O3 -time WARNINGS = -Werror -Wall -Wextra -pedantic-errors -Wformat=2 -Wno-import -Wimplicit -Wmain -Wchar-subscripts -Wsequence-point -Wmissing-braces -Wparentheses -Winit-self -Wswitch-enum -Wstrict-aliasing=2 -Wundef -Wshadow -Wpointer-arith -Wbad-function-cast -Wcast-qual -Wcast-align -Wwrite-strings -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Wredundant-decls -Wnested-externs -Winline -Wdisabled-optimization -Wunused-macros -Wno-unused LDFLAGS = LIBRARIES = -lcurl SOURCES = main.c test.c OBJECTS = $(SOURCES:.c=.o) EXECUTABLE = test all: $(SOURCES) $(EXECUTABLE) $(EXECUTABLE): $(OBJECTS) $(CC) $(LDFLAGS) $(OBJECTS) -o $@ $(LIBRARIES) debug: CFLAGS += -DDEBUG -g debug: $(SOURCES) $(EXECUTABLE) .c.o: $(CC) $< -o $@ $(CFLAGS) $(WARNINGS) .PHONY: doc clean doc: $(DOXYGEN) doxygen.config clean: rm -rf $(EXECUTABLE) $(OBJECTS) Answer: I would make source file discovery dynamic: SOURCES = $(wildcard *.c) In addition to all I usually add debug and release versions. CFLAGS = -fdiagnostics-color=always -std=gnu11 -s -c -time all: CFLAGS += -DTYPE=ALL debug: CFLAGS += -DTYPE=DEBUG -g3 release: CFLAGS += -DTYPE=RELEASE -O3
{ "domain": "codereview.stackexchange", "id": 42780, "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, makefile", "url": null }
c, makefile I have a generic build file that I have all my rules built-into. https://github.com/Loki-Astari/ThorMaker https://github.com/Loki-Astari/ThorMaker/blob/master/tools/Makefile Note: It is not perfect or great (but does what I need). But have a look and pull anything you need. This allows my actual makefiles to be very simple: # The Target I want to build # My generic Makefile build apps and lib based # on the extension extension of the target. TARGET = myLib.slib # Then include the Generic Makefile # In uses THORSANVIL_ROOT as the root of where you are THORSANVIL_ROOT = $(realpath ../) include ${THORSANVIL_ROOT}/build/tools/Makefile
{ "domain": "codereview.stackexchange", "id": 42780, "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, makefile", "url": null }
java, algorithm, linked-list, interview-questions Title: Reverse a sublist of a singly-linked master list in constant space and maximum of one pass (Java) Question: So I found this funky programming challenge somewhere on Quora. The idea is to take the head of a singly-linked list, and reverse a specific sublist. The requirements are: runs in constant space, makes only one pass over the master list. After hours of hard work, I came with the following solution: com.quora.algo.list.ReverseLinkedList.java: package com.quora.algo.list; import java.util.ArrayDeque; import java.util.Deque; /** * This class provides methods for reversing sublists in singly-linked lists. * * @author Rodion "rodde" Efremov * @version 1.6 (Jan 15, 2022) */ public final class ReverseLinkedList {
{ "domain": "codereview.stackexchange", "id": 42781, "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, algorithm, linked-list, interview-questions", "url": null }
java, algorithm, linked-list, interview-questions /** * Reverses the sublist {@code [fromIndex, toIndex]} in a single pass over * the singly-linked master list. Runs in {@code O(toIndex)} time. Indices * start from 1, not 0. * * @param head the head node of the list. * @param fromIndex the index of the leftmost node of the target sublist. * @param toIndex the index of the rightmost node of the target sublist. * @return the head of the resulting list. (May change, if {@code fromIndex} * is 1.) */ public static Node reverse(Node head, int fromIndex, int toIndex) { if (head == null) { return null; } checkIndices(fromIndex, toIndex); // Easy case. Nothing to reverse: if (fromIndex == toIndex) { return head; } Node prefixTail, sublistPtr, sublistHead, sublistTail = null, suffixHead = null, previouslyProcessedNode = null; if (fromIndex == 1) { prefixTail = null; sublistHead = head; } else { prefixTail = head; sublistHead = head.next; // Go to the fromIndex'th node: for (int i = 1; i <= fromIndex - 2; ++i) { if (prefixTail == null) { throw new IllegalArgumentException( "fromIndex(" + fromIndex + ") is too large. Must be at most " + (i + 1) + "."); } prefixTail = prefixTail.next; sublistHead = sublistHead.next; } } sublistPtr = prefixTail == null ? head : sublistHead; int numberOfNodesToProcess = toIndex - fromIndex + 2; // March through the nodes comprising the sublist to reverse. Also, we
{ "domain": "codereview.stackexchange", "id": 42781, "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, algorithm, linked-list, interview-questions", "url": null }
java, algorithm, linked-list, interview-questions // March through the nodes comprising the sublist to reverse. Also, we // need to find the suffix head node in order to link the tail of the // reversed sublist to the suffix head: for (int i = 0; i < numberOfNodesToProcess; ++i) { Node nodeToProcess = sublistPtr; if (nodeToProcess == null) { if (i == numberOfNodesToProcess - 1) { // Once here, the toIndex points to the tail node of the // entire list: suffixHead = null; } else { // Oops! toIndex is too large: throw new IllegalArgumentException( "toIndex is too large: " + toIndex + ". Must be at most " + (i + 1) + "."); } } else if (i < numberOfNodesToProcess - 1) { // Relink: sublistPtr = sublistPtr.next; suffixHead = sublistPtr; sublistTail = nodeToProcess; nodeToProcess.next = previouslyProcessedNode; } previouslyProcessedNode = nodeToProcess; } if (prefixTail == null) { sublistHead.next = suffixHead; return sublistTail; } else { prefixTail.next = sublistTail; sublistHead.next = suffixHead; return head; } } public static void main(String[] args) { Node head = null; Node tail = null; int m = Integer.valueOf(args[0]); int n = Integer.valueOf(args[1]); for (int i = 2; i < args.length; i++) { int value = Integer.valueOf(args[i]); if (head == null) { head = tail = new Node(value, null); } else { tail = (tail.next = new Node(value, null)); } }
{ "domain": "codereview.stackexchange", "id": 42781, "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, algorithm, linked-list, interview-questions", "url": null }
java, algorithm, linked-list, interview-questions tail = (tail.next = new Node(value, null)); } } head = reverse(head, m, n); for (Node node = head; node != null; node = node.next) { System.out.print(node.value + " "); } System.out.println(); } public static Node safeReverse(Node head, int fromIndex, int toIndex) { checkIndices(fromIndex, toIndex); // Easy case. Nothing to reverse: if (fromIndex == toIndex) { return head; } Pair<Node> sublistNodePair = getSublist(head, fromIndex, toIndex); Node prefixTail = getPrefixTail(head, fromIndex - 1); Node suffixHead = getSuffixHead(head, toIndex + 1); reverseRelink(sublistNodePair); sublistNodePair.first.next = suffixHead; if (prefixTail == null) { return sublistNodePair.second; } prefixTail.next = sublistNodePair.second; return head; } private static void reverseRelink(Pair<Node> sublist) { Deque<Node> stack = new ArrayDeque<>(); for (Node node = sublist.first; node != sublist.second.next; node = node.next) { stack.addLast(node); } Node previousNode = stack.removeFirst(); while (!stack.isEmpty()) { Node node = stack.removeFirst(); node.next = previousNode; previousNode = node; } } private static Node getPrefixTail(Node head, int fromIndex) { if (fromIndex == 0) { return null; } Node node = head; for (int i = 1; i < fromIndex; ++i) { node = node.next; } return node; } private static Node getSuffixHead(Node head, int toIndex) { Node node = head;
{ "domain": "codereview.stackexchange", "id": 42781, "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, algorithm, linked-list, interview-questions", "url": null }
java, algorithm, linked-list, interview-questions private static Node getSuffixHead(Node head, int toIndex) { Node node = head; for (int i = 1; i < toIndex; ++i) { node = node.next; } return node; } public static final class Pair<T> { public final T first; public final T second; public Pair(T first, T second) { this.first = first; this.second = second; } } private static Pair<Node> getSublist(Node head, int fromIndex, int toIndex) { Node start = null, end = null; int counter = 0; for (Node node = head; node != null; node = node.next) { ++counter; if (counter == fromIndex) { start = node; } else if (counter == toIndex) { end = node; return new Pair<>(start, end); } } throw new IllegalArgumentException("Bad indices!"); } public static void checkContainsNoCycles(Node head) { Node ptr1 = head; Node ptr2 = head; while (ptr1 != null && ptr2 != null) { ptr1 = ptr1.next; ptr2 = ptr2.next; if (ptr2 != null && ptr2.next != null) { ptr2 = ptr2.next; } if (ptr1 == ptr2) { throw new IllegalStateException( "The input list contains a cycle!"); } } } private static void checkIndices(int fromIndex, int toIndex) { if (fromIndex < 1 || toIndex < 1 || fromIndex > toIndex) { throw new IllegalArgumentException( "fromIndex(" + fromIndex + "), toIndex(" + toIndex + ")"); } } }
{ "domain": "codereview.stackexchange", "id": 42781, "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, algorithm, linked-list, interview-questions", "url": null }
java, algorithm, linked-list, interview-questions com.quora.algo.list.Node.java: package com.quora.algo.list; public final class Node { public final int value; public Node next; public Node(int value, Node next) { this.value = value; this.next = next; } // For debugging: @Override public String toString() { return "[" + value + "]"; } } com.quora.algo.list.ReverseLinkedListTest.java: package com.quora.algo.list; import static com.quora.algo.list.TestUtils.createList; import static com.quora.algo.list.TestUtils.eq; import static com.quora.algo.list.TestUtils.getList; import java.util.Random; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test;
{ "domain": "codereview.stackexchange", "id": 42781, "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, algorithm, linked-list, interview-questions", "url": null }
java, algorithm, linked-list, interview-questions public class ReverseLinkedListTest { private static final int BRUTE_FORCE_ITERATIONS = 100; private static Node list1; private static Node list2; private static Node list3; private static Node list4; private static Node list5; @Before public void before() { list1 = getList(1); list2 = getList(2); list3 = getList(3); list4 = getList(4); list5 = getList(5); } @Test(expected = IllegalArgumentException.class) public void throwsOnTooSmallFromIndex() { ReverseLinkedList.reverse(list1, 0, 1); } @Test(expected = IllegalArgumentException.class) public void throwsOnIndicesBackwards() { ReverseLinkedList.reverse(list2, 2, 1); } @Test(expected = IllegalArgumentException.class) public void throwsOnTooLargeToIndex() { ReverseLinkedList.reverse(list5, 2, 6); } @Test public void list1TrivialReverse() { ReverseLinkedList.reverse(list1, 1, 1); } @Test public void listAll2() { Node result = ReverseLinkedList.reverse(list2, 1, 2); Node expected = createList(2, 1); assertTrue(eq(result, expected)); } @Test public void listAll3() { Node result = ReverseLinkedList.reverse(list3, 1, 3); Node expected = createList(3, 2, 1); assertTrue(eq(result, expected)); } @Test public void bruteForceComparisonTest() { Random random = new Random(123L); for (int iteration = 0; iteration < BRUTE_FORCE_ITERATIONS; iteration++) { int length = random.nextInt(10) + 1; Node head1 = getList(length); Node head2 = getList(length); int index1 = random.nextInt(length) + 1; int index2 = random.nextInt(length) + 1; int fromIndex = Math.min(index1, index2);
{ "domain": "codereview.stackexchange", "id": 42781, "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, algorithm, linked-list, interview-questions", "url": null }
java, algorithm, linked-list, interview-questions int fromIndex = Math.min(index1, index2); int toIndex = Math.max(index1, index2); head1 = ReverseLinkedList.reverse(head1, fromIndex, toIndex); head2 = ReverseLinkedList.safeReverse(head2, fromIndex, toIndex); assertTrue(eq(head1, head2)); } } }
{ "domain": "codereview.stackexchange", "id": 42781, "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, algorithm, linked-list, interview-questions", "url": null }
java, algorithm, linked-list, interview-questions com.quora.algo.list.SafeReverseLinkedListTest.java: package com.quora.algo.list; import static com.quora.algo.list.TestUtils.createList; import static com.quora.algo.list.TestUtils.eq; import static com.quora.algo.list.TestUtils.getList; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; public class SafeReverseLinkedListTest { private Node list1; private Node list2; private Node list3; private Node list4; private Node list5; @Before public void before() { list1 = getList(1); list2 = getList(2); list3 = getList(3); list4 = getList(4); list5 = getList(5); } @Test(expected = IllegalArgumentException.class) public void throwsOnTooSmallFromIndex() { ReverseLinkedList.safeReverse(list1, 0, 1); } @Test(expected = IllegalArgumentException.class) public void throwsOnIndicesBackwards() { ReverseLinkedList.safeReverse(list2, 2, 1); } @Test(expected = IllegalArgumentException.class) public void throwsOnTooLargeToIndex() { ReverseLinkedList.safeReverse(list5, 2, 6); } @Test public void list1TrivialReverse() { ReverseLinkedList.safeReverse(list1, 1, 1); } @Test public void listAll2() { Node result = ReverseLinkedList.safeReverse(list2, 1, 2); Node expected = createList(2, 1); assertTrue(eq(result, expected)); } @Test public void listAll3() { Node result = ReverseLinkedList.safeReverse(list3, 1, 3); Node expected = createList(3, 2, 1); assertTrue(eq(result, expected)); } } com.quora.algo.list.TestUtils.java: package com.quora.algo.list;
{ "domain": "codereview.stackexchange", "id": 42781, "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, algorithm, linked-list, interview-questions", "url": null }