text
stringlengths
1
2.12k
source
dict
programming-challenge, haskell Visited is used like a Bool, so let it be a Bool. (You can wrap it up various different ways for clarity though!) At the same time, your use of Int to represent the land/water distinction isn't great. What if a 3 snuck in by mistake? Again, wrap up a bool! Use record types to name data fields. I suggest using type applications for things like read instead of an inline type hint. There's probably a better way to write getCellValue using lenses, but in this case I'd leverage the Maybe monad. In general, learning more abstractions will be good. For example, if I introduce a Coordinates type to wrap up (Int, Int), I can make it an instance of Semigroup and Monoid. getCellValue returns a lot of redundant data; simplify it down to just get the new stuff. This will push a little extra complexity up into the places where it's used, but the complexity belongs there (and can be resolved there). With respect to the algorithm: Instead of checking if each element is already in the list, consider always adding everything and then using nub at the end. This relies on the specific behavior of nubBy (it keeps the first match). So the code does get a little more fragile, but it enables substantial simplification! Also, in your list of ±1 offsets, there's no reason to be searching backward; you already checked those cells! I've been a bit lazy documenting my process, but the above got me to import Data.Function (on) import Data.List (nubBy) import Data.Maybe import qualified Data.Vector as V newtype Terrain = Terrain{isLand :: Bool} data Coordinates = Coord{row :: Int, column :: Int} deriving (Eq, Ord, Show) instance Semigroup Coordinates where (Coord r1 c1) <> (Coord r2 c2) = Coord (r1 + r2) (c1 + c2) instance Monoid Coordinates where mempty = Coord 0 0 incementColumn :: Coordinates -> Coordinates incementColumn (Coord r c) = Coord r (c + 1) data Cell = Cell { coordinates :: Coordinates, isNew :: Bool } deriving (Show)
{ "domain": "codereview.stackexchange", "id": 44510, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "programming-challenge, haskell", "url": null }
programming-challenge, haskell data Cell = Cell { coordinates :: Coordinates, isNew :: Bool } deriving (Show) islands :: V.Vector (V.Vector Terrain) -> Int islands oceanscape = length . filter isNew . nubBy ((==) `on` coordinates) . reverse $ islandhelper1 mempty [] where islandhelper1 :: Coordinates -> [Cell] -> [Cell] islandhelper1 coord cells = case oceanscape V.!? row coord of Just rowVector -> islandhelper2 rowVector coord cells _ -> cells islandhelper2 :: V.Vector Terrain -> Coordinates -> [Cell] -> [Cell] islandhelper2 rowVector coord cells = case rowVector V.!? column coord of Just (Terrain True) -> islandhelper2 rowVector (incementColumn coord) (getNeighbors oceanscape coord ++ Cell coord True : cells) Just (Terrain False) -> islandhelper2 rowVector (incementColumn coord) cells _ -> islandhelper1 (Coord{row = row coord + 1, column = 0}) cells getNeighbors:: V.Vector (V.Vector Terrain) -> Coordinates -> [Cell] getNeighbors oceanscape coord = mapMaybe (clfilter . (coord <>) . uncurry Coord) [(0,1), (1,0)] where clfilter :: Coordinates -> Maybe Cell clfilter coord' = do -- The Maybe Monad! Terrain True <- oceanscape !? coord' -- pattern match failure will yield Nothing. return $ Cell coord' False -- get the cell value (!?) :: V.Vector (V.Vector a) -> Coordinates -> Maybe a oceanscape !? coord = do -- The Maybe Monad! x <- oceanscape V.!? row coord x V.!? column coord
{ "domain": "codereview.stackexchange", "id": 44510, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "programming-challenge, haskell", "url": null }
programming-challenge, haskell At this point we can see that the entire recursive structure of islands is just generating 0-5 items for each step of an iteration, so let's use fmap. (Even if we did need to be examining the accumulator, we could still use a fold.) Here's my final version. I'm pretty sure there's a better way to build locations, but I gotta go do actual work :) There are probably even better ways of thinking about the whole problem, but at that point we'd be changing your fundamental algorithm, so that's out of scope. module Main where import Data.Function (on) import Data.List (nubBy) import Data.Maybe import qualified Data.Vector as V newtype Terrain = Terrain{isLand :: Bool} data Coordinates = Coord{row :: Int, column :: Int} deriving (Eq, Ord, Show) instance Semigroup Coordinates where (Coord r1 c1) <> (Coord r2 c2) = Coord (r1 + r2) (c1 + c2) data Cell = Cell { coordinates :: Coordinates, isNew :: Bool } deriving (Show) islands :: V.Vector (V.Vector Terrain) -> Int islands oceanscape = length . filter isNew . nubBy ((==) `on` coordinates) $ islandHelper `concatMap` locations where islandHelper :: (Coordinates, Terrain) -> [Cell] islandHelper (coord, Terrain True) = Cell coord True : getNeighbors oceanscape coord islandHelper (_, Terrain False) = [] locations :: V.Vector (Coordinates, Terrain) locations = do -- The Vector Monad! (rowIndex, rowVector) <- V.generate (length oceanscape) id `V.zip` oceanscape (columnIndex, value) <- V.generate (length rowVector) id `V.zip` rowVector return (Coord{row=rowIndex, column=columnIndex}, value)
{ "domain": "codereview.stackexchange", "id": 44510, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "programming-challenge, haskell", "url": null }
programming-challenge, haskell getNeighbors:: V.Vector (V.Vector Terrain) -> Coordinates -> [Cell] getNeighbors oceanscape coord = mapMaybe (clfilter . (coord <>) . uncurry Coord) [(0,1), (1,0)] where clfilter :: Coordinates -> Maybe Cell clfilter coord' = do -- The Maybe Monad! Terrain True <- oceanscape !? coord' -- pattern match failure will yield Nothing. return $ Cell coord' False -- get the cell value (!?) :: V.Vector (V.Vector a) -> Coordinates -> Maybe a oceanscape !? coord = do -- The Maybe Monad! x <- oceanscape V.!? row coord x V.!? column coord main::IO() main = do content1 <- parse <$> readFile "code_review_283543_1.test" print $ islands content1 content2 <- parse <$> readFile "code_review_283543_2.test" print $ islands content2 content3 <- parse <$> readFile "code_review_283543_3.test" print $ islands content3 content4 <- parse <$> readFile "code_review_283543_4.test" print $ islands content4 content8 <- parse <$> readFile "code_review_283543_8.test" print $ islands content8 where parse :: String -> V.Vector (V.Vector Terrain) parse = V.fromList . map (V.fromList . map parseCell . words) . lines parseCell = Terrain . (/= 0) . (read @Int)
{ "domain": "codereview.stackexchange", "id": 44510, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "programming-challenge, haskell", "url": null }
c++, iteration, c++20 Title: std::ranges zip view to iterate over two equal size ranges at the same time Question: Since c++20 std::ranges doesn't have a zip view like range-v3 does, I am working on implementing a basic version of such a zip view to iterate over two ranges at the same time. The ranges should be equal in size. If they are not equal in size, the view should iterate over both ranges and stop as soon as one range has reached the end. I would like feedback on whether this implementation is correct (iterator implementation, references, forwarding) and if it could be improved in any way. Demo on Compiler Explorer: https://godbolt.org/z/r7Y8hfcd8 My Implementation: #include <concepts> #include <ranges> #include <vector> template<std::ranges::input_range Rng1, std::ranges::input_range Rng2> requires std::ranges::view<Rng1> && std::ranges::view<Rng2> struct zip_view : std::ranges::view_interface<zip_view<Rng1, Rng2>> { using reference = std::pair< std::ranges::range_reference_t<Rng1>, std::ranges::range_reference_t<Rng2>>; using const_reference = std::pair< std::ranges::range_reference_t<Rng1>, std::ranges::range_reference_t<Rng2>>; using value_type = std::pair< std::remove_cv_t< std::remove_reference_t<std::ranges::range_reference_t<Rng1>>>, std::remove_cv_t< std::remove_reference_t<std::ranges::range_reference_t<Rng2>>>>; struct iterator; using const_iterator = iterator; private: std::ranges::iterator_t<Rng1> m_rng1_begin, m_rng1_end; std::ranges::iterator_t<Rng2> m_rng2_begin, m_rng2_end; public: zip_view() = default; zip_view(Rng1&& rng1, Rng2&& rng2) : m_rng1_begin(std::begin(rng1)), m_rng1_end(std::end(rng1)), m_rng2_begin(std::begin(rng2)), m_rng2_end(std::end(rng2)) { }
{ "domain": "codereview.stackexchange", "id": 44511, "lm_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++, iteration, c++20", "url": null }
c++, iteration, c++20 zip_view(Rng1 const& rng1, Rng2 const& rng2) : m_rng1_begin(std::begin(rng1)), m_rng1_end(std::end(rng1)), m_rng2_begin(std::begin(rng2)), m_rng2_end(std::end(rng2)) { } iterator begin() const { return iterator(m_rng1_begin, m_rng2_begin); } iterator end() const { return iterator(m_rng1_end, m_rng2_end); } const_iterator cbegin() const { return const_iterator(m_rng1_begin, m_rng2_begin); } const_iterator cend() const { return const_iterator(m_rng1_end, m_rng2_end); } }; template<typename Rng1, typename Rng2> zip_view( Rng1&& rng1, Rng2&& rng2 ) -> zip_view<std::ranges::views::all_t<Rng1>, std::ranges::views::all_t<Rng2>>; template<std::ranges::input_range Rng1, std::ranges::input_range Rng2> requires std::ranges::view<Rng1> && std::ranges::view<Rng2> struct zip_view<Rng1, Rng2>::iterator { using difference_type = ptrdiff_t; using value_type = zip_view<Rng1, Rng2>::value_type; private: std::ranges::iterator_t<Rng1> m_it1; std::ranges::iterator_t<Rng2> m_it2; public: iterator() = default; iterator( std::ranges::iterator_t<Rng1> it1, std::ranges::iterator_t<Rng2> it2 ) : m_it1(std::move(it1)), m_it2(std::move(it2)) { } iterator& operator++() { ++m_it1, ++m_it2; return (*this); } iterator operator++(int) { return ++iterator(m_it1, m_it2); } bool operator==(iterator const& other) const { // check if one of the iterators is equal so we don't iterate past the // end in case (m_it1 == end) and (m_it2 != end) or (m_it1 != end) and // (m_it2 == end) return (m_it1 == other.m_it1) || (m_it2 == other.m_it2); }
{ "domain": "codereview.stackexchange", "id": 44511, "lm_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++, iteration, c++20", "url": null }
c++, iteration, c++20 bool operator!=(iterator const& other) const { // check if both of the iterators are unqequal so we don't iterate past // the end in case (m_it1 == end) and (m_it2 != end) or (m_it1 != end) // and (m_it2 == end) return (m_it1 != other.m_it1) && (m_it2 != other.m_it2); } reference operator*() { return reference(*m_it1, *m_it2); } const_reference operator*() const { return const_reference(*m_it1, *m_it2); } reference operator->() { return reference(*m_it1, *m_it2); } const_reference operator->() const { return reference(*m_it1, *m_it2); } }; static_assert((bool)std::input_iterator<zip_view< std::views::all_t<std::vector<int>>, std::views::all_t<std::vector<int>>>::iterator>); static_assert((bool)std::ranges::input_range<zip_view< std::views::all_t<std::vector<int>>, std::views::all_t<std::vector<int>>>>); static_assert((bool)std::ranges::view<zip_view< std::views::all_t<std::vector<int>>, std::views::all_t<std::vector<int>>>>); Example Usage: #include <vector> #include <iostream> #include <string> int main() { std::vector<int> v1({ 1, 2, 3, 4 }); std::vector<std::string> v2({ "a", "b", "c", "d" }); for (auto&& [a, b] : zip_view(v1, v2)) std::cout << a << " : " << b << "\n"; } Answer: The problem with returning a pair of references It looks like you have a const_iterator which when dereferenced returns a const_reference, which sounds like it should be a pair of const references, but it isn't. And even if const pair of references is deduced somewhere, that is not the same as a pair of const references. So you can write this code: const auto const_zipped_view = zip_view(v1, v2); for (const auto& [a, b] : const_zipped_view) { a = -1; b = "oops!"; } for (auto&& [a, b] : zip_view(v1, v2)) std::cout << a << " : " << b << "\n";
{ "domain": "codereview.stackexchange", "id": 44511, "lm_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++, iteration, c++20", "url": null }
c++, iteration, c++20 for (auto&& [a, b] : zip_view(v1, v2)) std::cout << a << " : " << b << "\n"; And it will compile without any warnings and print "-1 : oops!" a few times. Only if v1 and/or v2 themselves are const will a pair of const references be deduced. C++23 introduces std::ranges::range_const_reference_t, which might help create your const_reference, or you have to do it yourself somehow. This also makes it clear you need a lot more unit tests to verify that all the assumptions you might have about your zipped view are actually correct. Implement a real const_iterator Your const_iterator is just the same as iterator, so if someone is explicitly calling cbegin() and cend() on a zip_view, they will still get a regular iterator that can potentially mutate the contents of the view. About the constructor I am uncertain what the proper way would be to write the constructor for a zip_view classes. However, I fail to see why you have one overload take rvalue-references, when you are not going to std::move() them. Just take them by lvalue-reference. You can omit operator!=() If you omit operator!=(), the compiler will generate a defaulted one that just calls operator==() and negates it, which is exactly what you want. Make the iterator more flexible Your iterator only implements the bare minimum to be an input iterator. So it can only iterator over the view once, cannot iterate backwards, and cannot be used to have random access to the view, even if the two ranges do support all that. One use case for allowing random access would be to be able to sort one array based on the contents of another, by writing something like: std::vector<Key> keys = {…}; std::vector<Value> values = {…}; std::ranges:sort(zip_view(keys, values), {}, [](auto& kvp){return kvp.first;});
{ "domain": "codereview.stackexchange", "id": 44511, "lm_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++, iteration, c++20", "url": null }
c++, iteration, c++20 Of course, this will require a lot more effort to implement. Allow zipping more than two ranges at a time It would be a nice exercise to create a zip_view that can handle three or more ranges at a time. This requires making it a variadic template, using std::tuple instead of std::pair, and parameter pack expansions. However, it will not require more lines of code than you already have.
{ "domain": "codereview.stackexchange", "id": 44511, "lm_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++, iteration, c++20", "url": null }
performance, algorithm, c, combinatorics Title: Brute Force Algorithm in C Question: This is a simple brute force algorithm that I have programmed in C. All the program does is print out every possible combination of the given alphabet for the given length. I would prefer suggestions on how to improve the algorithm, or decrease run-time. Any other suggestions are acceptable though. #include <stdio.h> #include <string.h> #include <stdlib.h> static const char alphabet[] = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789"; static const int alphabetSize = sizeof(alphabet) - 1; void bruteImpl(char* str, int index, int maxDepth) { for (int i = 0; i < alphabetSize; ++i) { str[index] = alphabet[i]; if (index == maxDepth - 1) printf("%s\n", str); else bruteImpl(str, index + 1, maxDepth); } } void bruteSequential(int maxLen) { char* buf = malloc(maxLen + 1); for (int i = 1; i <= maxLen; ++i) { memset(buf, 0, maxLen + 1); bruteImpl(buf, 0, i); } free(buf); } int main(void) { bruteSequential(3); return 0; } Answer: I'm going to skip reviewing the OP's code, which has already been reviewed quite nicely by others. Instead I'm just going to show a much faster version and explain it. What is the algorithm? Basically the way the algorithm works is that a buffer is created that holds alphaLen^2 patterns, where alphaLen is the length of the alphabet. A pattern is one combination, such as "aaaaa\n". The reason that alphaLen^2 patterns are used is because the buffer is prepopulated with the last 2 letters already set to all possible combinations. So for example, the buffer initially looks like (for length 5 patterns): "aaaaa\naaaab\naaaac\n ... aaa99\n" (62*62 patterns, 23064 bytes in length)
{ "domain": "codereview.stackexchange", "id": 44512, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, algorithm, c, combinatorics", "url": null }
performance, algorithm, c, combinatorics On every iteration, the function uses write() to output the buffer, and then increments the third to last letter. This involves writing that letter alphaLen^2 times (once per pattern). So the first iteration goes like: "aabaa\naabab\naabac\n ... aab99\n" ^ ^ ^ ^ | | | | +------+------+-----------+----- Characters written to buffer (62*62 changes) Whenever the third to last character wraps around, then we also need to update the fourth to last letter. If that wraps around, the fifth to last letter is also updated, etc. This continues until the first letter wraps around, at which point we are done. How fast is it? For all testing, I outputted to /dev/null so that my hard drive speed would not be the limiting factor. I tried the OP's program for 5 letter patterns but for me it took way too long (203 seconds). So I'll use Edward's estimate of 18 seconds for the OP's program instead. I also tested Edward's program on my machine, as well as a second program I wrote where I extended the algorithm to hardcode the last 3 characters instead of 2. I am using Cygwin gcc (32-bit) with -O4 on a Windows desktop. Here are the results: Time (secs) Length Program ----------- ------ ------- 18.0 5 syb0rg 9.6 5 Edward 0.4 5 JS1 (2 characters) 0.4 5 JS1 (3 characters) 665.0 6 Edward 26.0 6 JS1 (2 characters) 24.2 6 JS1 (3 characters) 1513.7 7 JS1 (3 characters) As you can see, this algorithm is very fast. The code Both programs are available here on GitHub. I'll show the 2 character variation below: static void generate(int maxlen) { int alphaLen = strlen(alphabet); int len = 0; char *buffer = malloc((maxlen + 1) * alphaLen * alphaLen); int *letters = malloc(maxlen * sizeof(int));
{ "domain": "codereview.stackexchange", "id": 44512, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, algorithm, c, combinatorics", "url": null }
performance, algorithm, c, combinatorics if (buffer == NULL || letters == NULL) { fprintf(stderr, "Not enough memory.\n"); exit(1); } // This for loop generates all 1 letter patterns, then 2 letters, etc, // up to the given maxlen. for (len=1;len<=maxlen;len++) { // The stride is one larger than len because each line has a '\n'. int i; int stride = len+1; int bufLen = stride * alphaLen * alphaLen; if (len == 1) { // Special case. The main algorithm hardcodes the last two // letters, so this case needs to be handled separately. int j = 0; bufLen = (len + 1) * alphaLen; for (i=0;i<alphaLen;i++) { buffer[j++] = alphabet[i]; buffer[j++] = '\n'; } write(STDOUT_FILENO, buffer, bufLen); continue; } // Initialize buffer to contain all first letters. memset(buffer, alphabet[0], bufLen); // Now in buffer, write all the last 2 letters and newlines, which // will after this not change during the main algorithm. { // Let0 is the 2nd to last letter. Let1 is the last letter. int let0 = 0; int let1 = 0; for (i=len-2;i<bufLen;i+=stride) { buffer[i] = alphabet[let0]; buffer[i+1] = alphabet[let1++]; buffer[i+2] = '\n'; if (let1 == alphaLen) { let1 = 0; let0++; if (let0 == alphaLen) let0 = 0; } } } // Write the first sequence out. write(STDOUT_FILENO, buffer, bufLen); // Special case for length 2, we're already done. if (len == 2) continue; // Set all the letters to 0. for (i=0;i<len;i++) letters[i] = 0;
{ "domain": "codereview.stackexchange", "id": 44512, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, algorithm, c, combinatorics", "url": null }
performance, algorithm, c, combinatorics // Set all the letters to 0. for (i=0;i<len;i++) letters[i] = 0; // Now on each iteration, increment the the third to last letter. i = len-3; do { char c; int j; // Increment this letter. letters[i]++; // Handle wraparound. if (letters[i] >= alphaLen) letters[i] = 0; // Set this letter in the proper places in the buffer. c = alphabet[letters[i]]; for (j=i;j<bufLen;j+=stride) buffer[j] = c; if (letters[i] != 0) { // No wraparound, so we finally finished incrementing. // Write out this set. Reset i back to third to last letter. write(STDOUT_FILENO, buffer, bufLen); i = len - 3; continue; } // The letter wrapped around ("carried"). Set up to increment // the next letter on the left. i--; // If we carried past last letter, we're done with this // whole length. if (i < 0) break; } while(1); } // Clean up. free(letters); free(buffer); }
{ "domain": "codereview.stackexchange", "id": 44512, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, algorithm, c, combinatorics", "url": null }
javascript Title: Create an array which contains one object per objectid Question: Is there a better or simplified approach to create an array which contains one object per objectid with an array of contacts that matches globalLkupRemoveContactReviewer by userid and then send each array which contains one object to the database in the form of [ { objectid: '222', contacts: [ { isdelete: '1', contactid: '1', associationid: '1968398' }, { isdelete: '1', contactid: '2', associationid: '1968399' }, ], }, ]; I get a dynamic string in the form of values separated by , and each value is separated by * in the format of objectid, userid, associationid const globalLkupRemoveContactReviewer = [ { objectid: 555, userid: '1', associationid: '1948874' }, { objectid: 555, userid: '2', associationid: '1950833' }, ]; //My Code: var myStr = '111*1*1968397,222*1*1968398,222*2*1968399,333*2*1968401,333*4*1968402,333*1*19684034'; Object.values( myStr .split(',') .map((item) => item.split('*')) .map(([objectid, userid, associationid]) => ({ objectid, userid, associationid, })) .filter( (item1) => !!globalLkupRemoveContactReviewer.find( (item2) => item2.userid === item1.userid ) ) .reduce((acc, { objectid, userid, associationid }) => { (acc[objectid] ??= { objectid, contacts: [] }).contacts.push({ isdelete: '1', contactid: userid, associationid, }); return acc; }, {}) ).forEach((item) => { console.log([item]); });
{ "domain": "codereview.stackexchange", "id": 44513, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript // Need result in this format to send to the database // [ { "objectid": "111", "contacts": [ { "isdelete": "1", "contactid": "1", "associationid": "1968397" } ] } ] // [ { "objectid": "222", "contacts": [ { "isdelete": "1", "contactid": "1", "associationid": "1968398" }, { "isdelete": "1", "contactid": "2", "associationid": "1968399" } ] } ] // [ { "objectid": "333", "contacts": [ { "isdelete": "1", "contactid": "2", "associationid": "1968401" }, { "isdelete": "1", "contactid": "1", "associationid": "19684034" } ] } ] Answer: If I understand everything correctly, then this can be done easier. The code can be formatted in different ways. But the main thing is that there is less action. So: we split the data into parts then through reduce we form a common array of objects parse data for object (including objectid) check globalLkupRemoveContactReviewer if we should add something to save space, we form a child object once if we have an object with this objectid - update it otherwise create it const globalLkupRemoveContactReviewer = [ { objectid: 555, userid: '1', associationid: '1948874' }, { objectid: 555, userid: '2', associationid: '1950833' }, ]; const myStr = '111*1*1968397,222*1*1968398,222*2*1968399,333*2*1968401,333*4*1968402,333*1*19684034'; const data = myStr.split(',') .reduce((acc, e) => { const [objectid, contactid, associationid] = e.split('*') if (!globalLkupRemoveContactReviewer.find((item2) => item2.userid === contactid)) return acc // skip const parent = acc.find(e => e.objectid === objectid) const child = { isdelete: "1", contactid, associationid } if (parent) { parent.contacts.push(child) // append contact } else { acc.push({objectid,contacts: [child]}) // new object } return acc }, []) console.log(JSON.stringify(data, null, 2))
{ "domain": "codereview.stackexchange", "id": 44513, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript As a result, we do not have unnecessary actions and operations. UPDATE Another great example of how to improve performance with reduce. The morbusg's answer has a use of Set, but you can create it in different ways. I suggest creating it in reduce - we will have one loop. In the case of new Set(x.map(...)) we have a map loop and an inner loop in the Set constructor. const globalLkupRemoveContactReviewer = [ { objectid: 555, userid: '1', associationid: '1948874' }, { objectid: 555, userid: '2', associationid: '1950833' }, ]; console.time('1') for (let i=0; i<100; i++) new Set(globalLkupRemoveContactReviewer.map(({userid}) => userid)) console.timeEnd('1') console.time('2') for (let i=0; i<100; i++) globalLkupRemoveContactReviewer.reduce((acc, {userid}) => acc.has(userid) ? acc : acc.add(userid), new Set) console.timeEnd('2') The final version might look like this: const globalLkupRemoveContactReviewer = [ { objectid: 555, userid: '1', associationid: '1948874' }, { objectid: 555, userid: '2', associationid: '1950833' }, ]; const globalRemoveContactId = globalLkupRemoveContactReviewer .reduce((acc, {userid}) => acc.has(userid) ? acc : acc.add(userid), new Set) const myStr = '111*1*1968397,222*1*1968398,222*2*1968399,333*2*1968401,333*4*1968402,333*1*19684034'; const data = myStr.split(',') .reduce((acc, e) => { const [objectid, contactid, associationid] = e.split('*') if (!globalRemoveContactId.has(contactid)) return acc // skip const parent = acc.find(e => e.objectid === objectid) const child = { isdelete: "1", contactid, associationid } if (parent) { parent.contacts.push(child) // append contact } else { acc.push({objectid,contacts: [child]}) // new object } return acc }, []) console.log(JSON.stringify(data, null, 2))
{ "domain": "codereview.stackexchange", "id": 44513, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
c, parsing, calculator, math-expression-eval, portability Title: Command line calculator in C
{ "domain": "codereview.stackexchange", "id": 44514, "lm_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, parsing, calculator, math-expression-eval, portability", "url": null }
c, parsing, calculator, math-expression-eval, portability Question: This code is an arithmetic parser as is the code in a previous question of mine. However this parser handles floating point arguments and mathematical functions, and handles them without needing to define a new function for every precedence level. The component to parse function names is the topic of a different previous question of mine. The code uses a recursive approach to parse strings of mathematical expressions. u is short for unary, which handles individual terms, such as individual numbers, functions, or parenthesized expressions. b is short for binary, which handles the binary operators. Associativity and precedence is respected. The first term is evaluated. Then, any operators operating on it are checked. If they are found, the right operand of the operator is recursively evaluated by passing the precedence operator to the function. The function only evaluates until an operator of precedence lower or equal (for right-to-left associativity) or lower (for left-to-right associativity) precedence is encountered. As such, the recursion ends, and the previous recursion level handles the rest. The workings are complicated but I am trying my best to explain them. As always, if my code is needlessly non-portable, or could use general improvement advice, corrections or comments would be appreciated. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> static size_t l; static int c(const void *const restrict a, const void *const restrict b) { const unsigned char *const sa = *(const unsigned char *const *)a, *const sb = *(const unsigned char *const *)b; const int cmp = memcmp(sa, sb, l = strlen((const char *)sb)); return cmp ? cmp : isalpha(sa[l]) ? sa[l]-sb[l] : 0; } static double (*func(const char **const str))(double) {
{ "domain": "codereview.stackexchange", "id": 44514, "lm_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, parsing, calculator, math-expression-eval, portability", "url": null }
c, parsing, calculator, math-expression-eval, portability } static double (*func(const char **const str))(double) { static const char *const s[] = {"abs", "acos", "acosh", "asin", "asinh", "atan", "atanh", "cbrt", "ceil", "cos", "cosh", "erf", "erfc", "exp", "expb", "floor", "gamma", "lgamma", "lb", "ln", "log", "round", "sin", "sinh", "sqrt", "tan", "tanh", "trunc"}; static double (*const f[])(double) = {fabs, acos, acosh, asin, asinh, atan, atanh, cbrt, ceil, cos, cosh, erf, erfc, exp, exp2, floor, tgamma, lgamma, log2, log, log10, round, sin, sinh, sqrt, tan, tanh, trunc}; const char *const *const r = bsearch(str, s, sizeof(s)/sizeof(*s), sizeof(*s), c); if (r) { *str += l; return f[r-s]; } return NULL; } static double u(const char **); static double b(const char **const str, const unsigned l) { *str += l != 0; // `l` will only be nonzero if recursively called by `b`, in which case there is an operator character to skip over for (double r = u(str);;) { while (isspace(**str)) ++*str; switch (**str) { case '^': if (l <= 3) // Using `<=` instead of `<` gives `^` right-to-left associativity r = pow(r, b(str, 3)); else break; continue; case '*': if (l < 2) r *= b(str, 2); else break; continue; case '/': if (l < 2) r /= b(str, 2); else break; continue; case '%': if (l < 2) r = fmod(r, b(str, 2)); else break; continue; case '+': if (l < 1) r += b(str, 1); else break; continue; case '-': if (l < 1) r -= b(str, 1);
{ "domain": "codereview.stackexchange", "id": 44514, "lm_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, parsing, calculator, math-expression-eval, portability", "url": null }
c, parsing, calculator, math-expression-eval, portability case '-': if (l < 1) r -= b(str, 1); else break; continue; } return r; } } static double u(const char **const str) { while (isspace(**str)) ++*str; if (isdigit(**str) || **str == '.') return strtod(*str, (char **)str); if (isalpha(**str)) { double (*f)(double) = func(str); if (f) return f(u(str)); } else switch (*(*str)++) { case '+': return +u(str); case '-': return -u(str); case '(': { register const double r = b(str, 0); if (*(*str)++ == ')') return r; } } return NAN; } #include <errno.h> int main(const int argc, const char *const *argv) { while (*++argv) if (printf("%g\n", b(&(const char *){*argv}, 0)) < 0) return EXIT_FAILURE; return EXIT_SUCCESS; }
{ "domain": "codereview.stackexchange", "id": 44514, "lm_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, parsing, calculator, math-expression-eval, portability", "url": null }
c, parsing, calculator, math-expression-eval, portability Answer: Avoid global variables for this task The key problem, in this case, is the added difficultly in proving code correctness. Alternative: In func(), instead of *str += l;, use *str += strlen(r); Note: use of l as a global and l as a local variable decreases code clarity. I'd re-write it further: #define SL(s) (s), sizeof (s) - 1 struct { const char *name; unsigned len; double (*const func)(double); } pairs[] = { { SL("abs"), abs}, { SL("acosh"), acosh}, ... }; #undef SL ... and then `bsearch()` on `pairs` and avoid all `strlen()` calls. Formatting First, use an auto-formatter. Target your audience. On this site, the width of your code is about 310% the width of the window. Adjust your auto formatting to stay within 120%, or even 100%. Plan for the future Move the parsing code to another file, say dparse.c. Form dparse.h and main.c. That way your good work can now readily get used on larger applications. Detect no conversion Do not assume a convertible string must begin with a digit/'.'. Other possibilities include , (other locale), i, I, n, N, .... strtod() also has "In other than the "C" locale, additional locale-specific subject sequence forms may be accepted." The only side effect of that is . is parsed as 0 is not wholly correct. Better to let strtod() determine what is convertible. // if (isdigit(**str) || **str == '.') // return strtod(*str, (char **)str); char *endptr; double val = strtod(*str, &endptr); if (*str == endptr) { // Handle no conversion } else { *str = endptr; return val; } Code then likely needs to test for +, - first.
{ "domain": "codereview.stackexchange", "id": 44514, "lm_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, parsing, calculator, math-expression-eval, portability", "url": null }
php, object-oriented, classes Title: GPG class for AJAX calls Question: I want to know if this GPG class in PHP is up to snuff as a professional-level class. I did my best to include everything and make it easy to use. I'm calling the object by invoke(). If anyone can figure anything I've missed, or how I can do better then, I'd really appreciate it. This is a very simple codebase I made to interact with the GPG installation. I'm creating Filters for a JS package I created. The Filters are PHP and the direct codebase is JS. <?PHP class GPG { private $id; function __invoke(string $command, $param1 = "", $param2 = "", $param3 = "") { if (!isset($this->id)) $this->id = gnupg_init(); $tempFuncCall = 'gnupg_'.$command; $one_string = ["addencryptkey","decrypt","encrypt","encryptsign", "export","gettrustlist","import","keyinfo","listsignatures","setarmor","seterrormode","setsignmode","sign"]; $two_strings = ["adddecryptkey","addsignkey","decryptverify"]; $three_strings = ["verify"]; if (in_array($command,$one_string)) { return $tempFuncCall($this->id, $param1); } else if (in_array($command,$two_strings)) { return $tempFuncCall($this->id, $param1, $param2); } else if (in_array($command,$three_strings)) { return $tempFuncCall($this->id, $param1, $param2, $param3); } else if ($command != "init") { try { return $tempFuncCall($this->id); } catch (e) { echo "Command does not exist"; } } } } ?> Here's an Example: $gpg = new GPG(); $gpg('addencryptkey', "credentials"); $r = $gpg('encrypt',"this is just some text."); $gpg('adddecryptkey',"credentials",""); echo $gpg('decrypt', $r); // $r = $gpg('') echo $r;
{ "domain": "codereview.stackexchange", "id": 44515, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, object-oriented, classes", "url": null }
php, object-oriented, classes Answer: My opinion is that variable variables and variable function/method names should be avoided as much as possible (I nearly want to say: "NEVER use them"). These features often have a negative impact on the developer experience in IDEs. I think you would benefit from reading PSR-12 coding guidelines. Things that stand out to me are: missing __invoke() method visibility declaration https://www.php.net/manual/en/language.oop5.magic.php if without curly braces type declarations on all __invoke() arguments missing spaces after commas inside array declarations placement of opening curly brace on if blocks there should not be a space between else if -- it is one word in PHP Beyond that, here are few other thoughts: $one_string, $two_string, and $three_string variable names are NOT awesome/intuitive/meaningful. I see that these are whitelists and I don't really have an alternative to offer, but it doesn't strike me as "professional". Should these even be variables at all? Would they be better as constants? Why are there three arguments after command anyhow? Can the variable length parameters be simplified using the spread operator in the signature? What about: public function __invoke(string $command, string ...$params): mixed { //... return $tempFuncCall($this->id, ...$params); //... } I recommend strict comparisons unless logical to do otherwise. $command !== "init"
{ "domain": "codereview.stackexchange", "id": 44515, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, object-oriented, classes", "url": null }
shell, posix Title: Printing script intro by typing Y/y or just by pressing Enter in a POSIX shell script Question: Say, I have my POSIX script introduction stored in variable: script_intro=\ '------------------------------------------------------------ -- Safe system files editing as root -- -- Code language: POSIX shell script -- -- Copyright: 2020-2023 Vlastimil Burian -- -- Email: info@vlastimilburian.cz -- -- GitHub: https://git.io/Jvnzq -- -- License: The Unlicense -- -- Version 5.0 (stable) -- -- Released: 2023-Feb-13 -- ------------------------------------------------------------' This was actually made by boxes (boxes -d ada-box -a c -s 60). And now say we have a function to ask if the user wants to display that intro and I want that done by default (y*/Enter), where the interesting part is the Enter key which was mostly attributed to this answer. sudoedit_help () { printf '%s' 'sudoedit-enhanced: Do you wish to print intro? [Y/Enter] / ? ' IFS= read -r print_intro case "$print_intro" in ([Yy]*|'') printf '%s\n' "$script_intro" esac cat << EOF Main useful info like usage... Usage example: suvim /path/to/file1 /path/to/file2 EOF } Answer: Problem #1 sudoedit_help or generally sudoedit_whatever functions will populate the shell and be messing with the standard sudoedit command in shell command completion for the user. There is a simple solution to it, the best I came up with is prefixing the functions with an underscore like this: _sudoedit_help () { ... } Problem #2 Before asking any additional question(s), help should be displayed. Like this: _sudoedit_help () { cat <<EOF sudoedit-enhanced: Usage Example: suvi /path/to/file1 /path/to/file2 EOF ... }
{ "domain": "codereview.stackexchange", "id": 44516, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "shell, posix", "url": null }
shell, posix ... } Problem #3 (cosmetic) Sentence sudoedit-enhanced: Do you wish to print intro? [Y/Enter] / ? can be better phrased like this: sudoedit-enhanced: Do you wish to print intro? [y/Enter/?] Problem #4 The function name could be named better, e.g. to contain a verb. Like this: _sudoedit_show_help () { ... } Problem #5 sudoedit-enhanced: Usage could really be better phrased. Like this: Usage of sudoedit-enhanced shell extension. And since we are showing one single example of use, then vim shall be replaced by the basic vi to be more generic. Refactored code _sudoedit_show_help () { cat <<EOF Usage of sudoedit-enhanced shell extension: Example: suvi /path/to/file1 /path/to/file2 EOF printf '\n%s' 'sudoedit-enhanced: Do you wish to print intro? [y/Enter/?] ' IFS= read -r print_intro case "$print_intro" in ([Yy]*|'') printf '%s\n' "$script_intro" esac }
{ "domain": "codereview.stackexchange", "id": 44516, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "shell, posix", "url": null }
ruby, ruby-on-rails Title: Ruby SFTP client Question: I'm on Ruby for three weeks and now I want to learn more. Please review this SFTP client and suggest any necessary changes. # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # What is Net::SFTP? # Net::SFTP is a pure-Ruby implementation of the SFTP protocol. # That’s “SFTP” as in “Secure File Transfer Protocol”, as defined as an adjuct to the SSH specification. # Not “SFTP” as in “Secure FTP” (a completely different beast). # Nor is it an implementation of the “Simple File Transfer Protocol” (which is in no way secure). require 'net/sftp' require 'ostruct' require 'optparse' class Christina Script = "Script => (christina.rb)" Version = "Version => (0.0.1)" def run(arguments) parse(arguments) connect(arguments) end private def parse(arguments) ARGV << "-h" if ARGV.empty? @options = OpenStruct.new args = OptionParser.new do |args| args.banner = "Usage: #{__FILE__} [options]" args.on("-s", "--set-host=HOST", String, "The Host To Connect To") do |set_host| @options.set_host = set_host end args.on("-u", "--username=USERNAME", String, "Authenticate With A Username") do |username| @options.username = username end
{ "domain": "codereview.stackexchange", "id": 44517, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "ruby, ruby-on-rails", "url": null }
ruby, ruby-on-rails args.on("-p", "--password=PASSWORD", String, "Authenticate With A Password") do |password| @options.password = password end args.on("-w", "--wharf=WHARF", Integer, "Specify The Wharf (Port) The Service Is Running") do |wharf| @options.wharf = wharf end args.on("-t", "--transfer=FILE", String, "Upload An Entire File On Disk") do |transfer| @options.transfer = transfer end args.on("-d", "--destination=FILE", String, "Destination For The Uploaded File") do |destination| @options.destination = destination end args.on("-m", "--mkdir=CREATE DIRECTORY", String, "Create A Directory") do |mkdir| @options.mkdir = mkdir end args.on("-r", "--rmdir=REMOVE DIRECTORY", String, "Remove A Directory") do |rmdir| @options.rmdir = rmdir end args.on("-q", "--query=FILE", String, "Query A File’s Permissions") do |query| @options.query = query end args.on("-e", "--erase=FILE", String, "Delete A File") do |erase| @options.erase = erase end args.on("-c", "--change=FILE", String, "Change A File’s Permissions") do |change| @options.change = change end args.on("-a", "--authorization=INTEGER", Integer, "Combine With The Above Command To Change A File's Permissions") do |authorization| @options.authorization = authorization end args.on("-b", "--brand=FILE", String, "Brand (Rename) A File") do |name| @options.name = name end args.on("-n", "--new=FILE", String, "The Name Off The Renamed File") do |new| @options.new = new end args.on("-l", "--list=DIRECTORY", String, "Query The Contents Of A Directory") do |list| @options.list = list end
{ "domain": "codereview.stackexchange", "id": 44517, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "ruby, ruby-on-rails", "url": null }
ruby, ruby-on-rails args.on("-g", "--grab=FILE", String, "Grab Data Off The Remote Host Directly To A Buffer") do |grab| @options.grab = grab end args.on("-f", "--file=FILE", String, "Download Directly To A Local File") do |file| @options.file = file end args.on("-o", "--output=FILE", String, "Destination Off The Downloaded File") do |output| @options.output = output end args.on("-h", "--help", "Show Help And Exit") do puts args exit end args.on("-V", "--version", "Show Version And Exit") do puts Script puts Version exit end begin args.parse!(arguments) rescue OptionParser::MissingArgument => error puts "[!] => #{error.message}" exit rescue OptionParser::InvalidOption => error puts "[!] => #{error.message}" exit end end end def connect(arguments) output("----------------------------------------------------------") output("[*] Starting at => #{Time.now}") output("[*] Operating System => #{RUBY_PLATFORM}") output("----------------------------------------------------------") output("[i] Connecting to Secure SHell") output("\t-- Host => #{@options.set_host}") output("\t-- Username => #{@options.username}") output("\t-- Password => #{@options.password}") output("\t-- Wharf => #{@options.wharf}") output("----------------------------------------------------------")
{ "domain": "codereview.stackexchange", "id": 44517, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "ruby, ruby-on-rails", "url": null }
ruby, ruby-on-rails Net::SFTP.start(@options.set_host, @options.username, :password => @options.password, :port => @options.wharf) do |sftp| mkdir(sftp) if @options.mkdir rmdir(sftp) if @options.rmdir remove(sftp) if @options.erase query(sftp) if @options.query list(sftp) if @options.list grab(sftp) if @options.grab rename(sftp) if @options.name || @options.new change(sftp) if @options.change || @options.authorization upload(sftp) if @options.transfer || @options.destination download(sftp) if @options.file || @options.output end output("----------------------------------------------------------") output("[*] Exiting at => #{Time.now}") output("----------------------------------------------------------") end def mkdir(sftp) sftp.mkdir!(@options.mkdir) output("[i] Creating Directory => #{@options.mkdir}") end def rmdir(sftp) sftp.rmdir!(@options.rmdir) output("[i] Removing Directory => #{@options.rmdir}") end def remove(sftp) sftp.remove!(@options.erase) output("[i] Removing File => #{@options.erase}") end def query(sftp) output("[i] Checking Permissions => #{sftp.stat!(@options.query).permissions}") end def grab(sftp) sftp.download!(@options.grab) output("[i] Grabing File => #{@options.grab}") end def rename(sftp) sftp.rename!(@options.name, @options.new) output("[i] Renaming File => #{@options.name}") output("[i] New File => #{@options.new}") end def change(sftp) sftp.setstat!(@options.change, :permissions => @options.authorization) output("[i] Setting Permissions To => #{@options.change}") output("[i] Permissions Set To => #{@options.authorization}") end
{ "domain": "codereview.stackexchange", "id": 44517, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "ruby, ruby-on-rails", "url": null }
ruby, ruby-on-rails def upload(sftp) sftp.upload!(@options.transfer, @options.destination) output("[i] Uploading File To => #{@options.set_host}") output("\t-- Local File => #{@options.transfer}") output("\t-- File Destination => #{@options.destination}") end def download(sftp) sftp.download!(@options.file, @options.output) output("[i] Downloading File From => #{@options.set_host}") output("\t-- Remote File => #{@options.file}") output("\t-- File Destination => #{@options.output}") end def list(sftp) output("[i] Listing Contents Of => #{@options.list}") output("----------------------------------------------------------") sftp.dir.foreach(@options.list) do |entry| output(entry.longname) end end def output(string) puts "#{string}" end end sftp = Christina.new sftp.run(ARGV) Answer: ... under the terms of the GNU General Public License ... IANAL, TINLA. As copyright holder you chose to license the code in your posting under the terms of CC-BY-SA, which is incompatible with GPLv3 as it does not allow authors to ... legally restrict others from doing anything the [CC] license permits. It's possible you would find the (more permissive) MIT or 2-clause BSD licenses to your liking. tl;dr: These lines do not appear to have their intended effect, in the review context. The CC folks have this to say about porting code between licenses, which apparently would go somewhat smoothly had you tried to do it in the opposite direction: People may not adapt a GPLv3-licensed work and use BY-SA to license their contributions. This is not allowed by GPLv3. Thus, this compatibility determination only allows movement one way, from BY-SA 4.0 to GPLv3. A concise "RFC913" citation for that third protocol wouldn't hurt. For the first and second protocols, I think that you are respectively referring to these? https://en.wikipedia.org/wiki/SSH_File_Transfer_Protocol https://en.wikipedia.org/wiki/Secure_FTP_(software)
{ "domain": "codereview.stackexchange", "id": 44517, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "ruby, ruby-on-rails", "url": null }
ruby, ruby-on-rails But documentation shouldn't be a guessing game. Spell it out for us. Cite your references. The "public" run vs "private" implementation is a nice touch. Thank you. @options.set_host = set_host I don't understand why the UI doesn't offer a --host option, but whatever. Even if that remains unchanged, consider assigning just @options.host. args.on("-w", "--wharf=WHARF", Integer, This term doesn't appear in section 4 of rfc1192. Recommend that you Explicitly identify the target audience you're addressing, whichever community would customarily use "wharf" as a 16-bit socket identifier, and Add a --port synonym which has the same effect. nit: Consider Using Fewer Capital Letters In The Help Text. args.on("-p", "--password=PASSWORD", String, This is a tricky one. What you have there is fine, don't change it. But some folks will look for the ability to have a non-echoing interactive prompt. And a more common practice is to pull such credentials from an exported environment variable. There's also config files like ~/.netrc args.on("-t", "--transfer=FILE", String, Honestly, these are starting to sound less like "options" and more like "commands". You have a bunch of them. And I can envision a caller wanting to execute several of them once they've spent some time setting up an SSH connection. If caller specifies -t A.txt -t B.txt it's pretty clear they'll only get the second file. Consider supporting a list of commands? Or reading commands from a file, such as stdin? typo ("of"): "The Name Off The Renamed File") do |new| rescue OptionParser::MissingArgument => error ... rescue OptionParser::InvalidOption => error DRY. Maybe we can combine the puts behavior, here? Also, think about the diagnostic value of the message. Maybe the person viewing it would benefit from a reminder that --help is available? output("[*] Operating System => #{RUBY_PLATFORM}")
{ "domain": "codereview.stackexchange", "id": 44517, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "ruby, ruby-on-rails", "url": null }
ruby, ruby-on-rails output("[*] Operating System => #{RUBY_PLATFORM}") Consider clarifying that this is the local OS. remove(sftp) if @options.erase query(sftp) if @options.query Hmmm, that seems undesirable. If I was reading the --help output, I might believe that query happens before erase, but it turns out that is not so. And we also see such inconsistencies in "list" and others. There is a design choice to be made, here. Consider adopting either Args validation limits the caller to just a single verb, or Args support a list of verbs to execute in sequence. rename(sftp) if @options.name || @options.new change(sftp) if @options.change || @options.authorization upload(sftp) if @options.transfer || @options.destination download(sftp) if @options.file || @options.output Sorry, I don't find those obvious. Oh, wait, I just viewed the docs. At least some of those require that both args be specified, right? And we've not done any local validation along those lines, yet. IDK, maybe the rename method being called gives an appropriate diagnostic message to the user when only a single arg appeared on the command line? output("[*] Exiting at => #{Time.now}") This is lovely. Maybe displaying the elapsed time is also of interest to caller? sftp.mkdir!(@options.mkdir) output("[i] Creating Directory => #{@options.mkdir}") In each of these methods, the order seems backwards. Consider telling the user before executing the verb, in case something goes wrong and it blows up. Alternatively, announce the fait accompli in the past tense, with "Created". Also, ruby offers a lovely logger. Consider using it, so callers can reliably parse your output. And, oh yeah. Everything that @papirtiger said!
{ "domain": "codereview.stackexchange", "id": 44517, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "ruby, ruby-on-rails", "url": null }
docker, nginx, dockerfile Title: Nginx Docker image with built from source with modules Question: I needed Nginx Docker image with additional modules (Lua and headers more) and Lua Prometheus lib. I did not want to use Openresty for that because its Alpine docker image weighs ~110MB, when Nginx Alpine image weighs 22MB. So I decided to create my own Nginx image with modules I need. My image weighs 38MB and I think it's pretty good. But I am not really familiar with compiling Nginx from source, adding some modules, using Lua with Nginx, etc. Technically, it was my 1 time to compile Nginx from source and not using package manager to install it. So tell me please if there is something you think may be done a better way or completely redone. FROM alpine:3.15.4 ARG NGINX_VERSION=1.21.6 ARG HEADERS_MORE_VERSION=0.34 ARG LUA_NGINX_VERSION=0.10.23 ARG LUA_PROMETHEUS_VERSION=0.20221218 ARG LUAJIT_VERSION=2.1-20230119 ARG NGX_DEVEL_VERSION=0.3.2 ARG RESTY_CORE_VERSION=0.1.25 ARG RESTY_LRUCACHE_VERSION=0.13 WORKDIR /tmp/build/nginx
{ "domain": "codereview.stackexchange", "id": 44518, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "docker, nginx, dockerfile", "url": null }
docker, nginx, dockerfile # install dependencies and dev-dependencies RUN apk add --no-cache gzip \ pcre \ zlib \ openssl \ curl \ libaio \ libgcc && \ apk add --no-cache \ --virtual .build \ linux-headers \ gnupg \ wget \ g++ \ pcre-dev \ zlib-dev \ make \ openssl-dev \ libaio-dev && \ # create nginx user and group addgroup -g 101 -S nginx && \ adduser -S -D -H -u 101 -s /sbin/nologin -G nginx -g nginx nginx && \ # get nginx, luajit and required modules and libs wget https://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz && \ wget https://github.com/openresty/luajit2/archive/v${LUAJIT_VERSION}.tar.gz \ -O luajit2-${LUAJIT_VERSION}.tar.gz && \ wget https://github.com/knyar/nginx-lua-prometheus/archive/${LUA_PROMETHEUS_VERSION}.tar.gz \ -O nginx-lua-prometheus-${LUA_PROMETHEUS_VERSION}.tar.gz && \ wget https://github.com/openresty/lua-nginx-module/archive/v${LUA_NGINX_VERSION}.tar.gz \ -O lua-nginx-module-${LUA_NGINX_VERSION}.tar.gz && \ wget https://github.com/openresty/headers-more-nginx-module/archive/refs/tags/v${HEADERS_MORE_VERSION}.tar.gz \ -O headers-more-nginx-module-${HEADERS_MORE_VERSION}.tar.gz && \ wget https://github.com/vision5/ngx_devel_kit/archive/v${NGX_DEVEL_VERSION}.tar.gz \ -O ngx_devel_kit-${NGX_DEVEL_VERSION}.tar.gz && \ wget https://github.com/openresty/lua-resty-core/archive/v${RESTY_CORE_VERSION}.tar.gz \ -O lua-resty-core-${RESTY_CORE_VERSION}.tar.gz && \ wget https://github.com/openresty/lua-resty-lrucache/archive/v${RESTY_LRUCACHE_VERSION}.tar.gz \ -O lua-resty-lrucache-${RESTY_LRUCACHE_VERSION}.tar.gz && \
{ "domain": "codereview.stackexchange", "id": 44518, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "docker, nginx, dockerfile", "url": null }
docker, nginx, dockerfile -O lua-resty-lrucache-${RESTY_LRUCACHE_VERSION}.tar.gz && \ # unpack them all tar -xvf nginx-${NGINX_VERSION}.tar.gz && \ tar -xvf luajit2-${LUAJIT_VERSION}.tar.gz && \ tar -xvf nginx-lua-prometheus-${LUA_PROMETHEUS_VERSION}.tar.gz && \ tar -xvf lua-nginx-module-${LUA_NGINX_VERSION}.tar.gz && \ tar -xvf headers-more-nginx-module-${HEADERS_MORE_VERSION}.tar.gz && \ tar -xvf ngx_devel_kit-${NGX_DEVEL_VERSION}.tar.gz && \ tar -xvf lua-resty-core-${RESTY_CORE_VERSION}.tar.gz && \ tar -xvf lua-resty-lrucache-${RESTY_LRUCACHE_VERSION}.tar.gz && \ # install luajit cd luajit2-${LUAJIT_VERSION} && make install && cd .. && \ # install nginx with modules cd nginx-${NGINX_VERSION} && \ LUAJIT_LIB=/usr/local/lib LUAJIT_INC=/usr/local/include/luajit-2.1 \ ./configure \ --prefix=/etc/nginx \ --sbin-path=/usr/sbin/nginx \ --modules-path=/usr/lib/nginx/modules \ --conf-path=/etc/nginx/nginx.conf \ --error-log-path=/dev/stdout \ --http-log-path=/dev/stdout \ --pid-path=/var/run/nginx.pid \ --lock-path=/var/run/nginx.lock \ --http-client-body-temp-path=/var/cache/nginx/client_temp \ --http-proxy-temp-path=/var/cache/nginx/proxy_temp \ --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp \ --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp \ --http-scgi-temp-path=/var/cache/nginx/scgi_temp \ --user=nginx \ --group=nginx \ --with-compat \ --with-file-aio \ --with-threads \ --with-http_addition_module \ --with-http_auth_request_module \ --with-http_dav_module \ --with-http_flv_module \ --with-http_gunzip_module \ --with-http_gzip_static_module \ --with-http_mp4_module \ --with-http_random_index_module \ --with-http_realip_module \ --with-http_secure_link_module \ --with-http_slice_module \
{ "domain": "codereview.stackexchange", "id": 44518, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "docker, nginx, dockerfile", "url": null }
docker, nginx, dockerfile --with-http_secure_link_module \ --with-http_slice_module \ --with-http_ssl_module \ --with-http_stub_status_module \ --with-http_sub_module \ --with-http_v2_module \ --with-cc-opt='-Os -fomit-frame-pointer -g' \ --with-ld-opt=-Wl,--as-needed,-O1,--sort-common \ --add-module=$(cd .. && pwd)/ngx_devel_kit-${NGX_DEVEL_VERSION} \ --add-module=$(cd .. && pwd)/lua-nginx-module-${LUA_NGINX_VERSION} \ --add-module=$(cd .. && pwd)/headers-more-nginx-module-${HEADERS_MORE_VERSION} && \ make && make install && cd .. && \ # install lua resty core lib cd lua-resty-core-${RESTY_CORE_VERSION} && \ make install PREFIX=/etc/nginx && cd .. && \ # install lua resty lrucache lib cd lua-resty-lrucache-${RESTY_LRUCACHE_VERSION} && \ make install PREFIX=/etc/nginx && cd .. && \ # add lua prometheus files to nginx lua libs directory rm nginx-lua-prometheus-${LUA_PROMETHEUS_VERSION}/prometheus_test.lua && \ cp nginx-lua-prometheus-${LUA_PROMETHEUS_VERSION}/prometheus*.lua /etc/nginx/lib/lua/ && \ # clean build files apk del --no-cache .build && \ rm -rf /tmp/build/nginx && \ # set correct permissions mkdir -p /usr/share/nginx /var/log/nginx /var/cache/nginx /usr/lib/nginx/modules && \ ln -s /usr/lib/nginx/modules /etc/nginx/modules && \ touch /var/run/nginx.pid && \ chown -R nginx:nginx /usr/share/nginx /etc/nginx /var/run/nginx.pid /var/cache/nginx /var/log/nginx /usr/lib/nginx && \ chmod -R 744 /usr/share/nginx /var/log/nginx /var/cache/nginx /var/run/nginx.pid
{ "domain": "codereview.stackexchange", "id": 44518, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "docker, nginx, dockerfile", "url": null }
docker, nginx, dockerfile ENV LUA_PATH=/etc/nginx/lib/lua/?.lua;; USER nginx WORKDIR /etc/nginx STOPSIGNAL SIGQUIT CMD ["nginx", "-g", "daemon off;"] Answer: That's a very long RUN command - it might be better to write that as a shell script which you ADD and then RUN. That has advantages such as using a shell-syntax-aware editor or being able to run shellcheck or other tools on it. In any case, I recommend set -u to catch misspelt variable names. Quite a few commands in the script are wget commands. It might be better to use Dockerfile's ADD for these rather than having the shell fetch them. Downside of that is that we end up with bigger layers, so consider what size impact they have. Repeated use of $(cd .. && pwd) suggests that a variable could be used there - or, since you know the working directory, just use absolute pathnames. Did you check whether relative paths work (i.e. just ..)? Or perhaps (with Bash as interpreter) we could make a relative path using ~+/... Also related to directory changing - we could use Make's -C option to reduce the number of cd invocations, and make it easier for the reader to keep track of working directory. For example, cd luajit2-${LUAJIT_VERSION} && make install && cd .. becomes make -C luajit2-${LUAJIT_VERSION} install If there were other temporary changes of directory, we could consider using a subshell to isolate the directory change: (cd workdir && command) It's good that you have rm -rf /tmp/build/nginx after using the sources to build - that can make a big difference to the size of the layer.
{ "domain": "codereview.stackexchange", "id": 44518, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "docker, nginx, dockerfile", "url": null }
c#, selenium Title: Waits for one of two xpaths to be present, one inside of an iframe, one outside of it Question: I'm using selenium for testing, and I've written code that waits for one of two locations before it continues. This is really easy when both locations are within the same frame, because then I can just use a WebDriverWait, which is the obvious solution. That's not the case for this situation though. This is the basic idea of the elements I'm trying to find <div>Location outside of IFrame</div> <iframe> #document <html> <div>Location inside of IFrame</div> Here's the working code I currently have ChromeDriver driver; bool isPresent = false; // This resets the start time for a timer. StartTimer(); // HasMinutesPassed is a method that returns false until x minutes have passed. while (!HasMinutesPassed(2) && !isPresent) { if (driver.FindElements(iFrameLocation).Any()) { //This is an extension method in my project that makes IFrame handling a bit easier. I'll include the method just in case it's what's stopping this from being better driver.ExecuteInFrame(iFrameLocation, () => { // insideLocation is the XPath for the element I'm looking for inside of the iFrame if (driver.FindElements(insideLocation).Any()) { isPresent = true; } }); } // outsideLocation is the XPath for the element I'm looking for outside of the iFrame if (driver.FindElements(outsideLocation).Any()) { isPresent = true; } } // Iframe handling method public void ExecuteInFrame(this Driver driver, By frameLocator, Action action) { driver.Instance.SwitchTo().DefaultContent(); driver.Wait.Until(ExpectedConditions.FrameToBeAvailableAndSwitchToIt(frameLocator)); action(); driver.Instance.SwitchTo().DefaultContent(); }
{ "domain": "codereview.stackexchange", "id": 44519, "lm_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#, selenium", "url": null }
c#, selenium I know it's probably inefficient, and it almost definitely could be cleaner. Any suggestions on how to improve this will be greatly appreciated. Answer: By reducing the number of if blocks you can greatly simplify your code. This guarded assignment if (driver.FindElements(outsideLocation).Any()) { isPresent = true; } is equal to this isPresent = driver.FindElements(outsideLocation).Any(); So, if you apply this change and use do - while loop instead of while then your main logic could be written like this do { if (driver.FindElements(iFrameLocation).Any()) driver.ExecuteInFrame(iFrameLocation, () => isPresent = driver.FindElements(insideLocation).Any()); isPresent = driver.FindElements(outsideLocation).Any(); } while (!HasMinutesPassed(2) && !isPresent) By introducing the following helper method bool IsElementPresent(By by) => driver.FindElements(by).Any(); you can make your code even more concise do { if (IsElementPresent(iFrameLocation)) driver.ExecuteInFrame(iFrameLocation, () => isPresent = IsElementPresent(insideLocation)); isPresent = IsElementPresent(outsideLocation); } while (!HasMinutesPassed(2) && !isPresent)
{ "domain": "codereview.stackexchange", "id": 44519, "lm_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#, selenium", "url": null }
algorithm, c, binary-search-tree Title: Binary Search Tree implementation in C [1] Question: I have tried to implement my Binary Search Tree in C. The following are the 18 operations defined: create a bst is_empty insert delete clear find find_min find_max height size depth level order traversal preorder traversal inorder traversal postorder traversal inorder successor is_bst (is the tree a binary search tree) is_bst_balanced (is the binary search tree balanced) This was an important phase in my coding skills to understand what recursion really is. I usually have a table of returns and a recursive call stack both drawn to track the running of recursion, and that helped immensely to grasp the background work of recursion. If you find any improvement to be said about some recursive functions in this BST implementation, I would be grateful to read them through. This is the entire code. I have included my Queue because I needed for the level_order function. #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #define max(x, y) (((x) > (y)) ? (x) : (y)) typedef struct Node { int data; struct Node* left; struct Node* right; } Node; //---------------Queue----------------- typedef struct QNode { Node* data; struct QNode* next; } QNode; typedef struct Queue { int size; QNode* head; QNode* tail; } Queue; const Queue queue_init = { .size = 0, .head = NULL, .tail = NULL }; QNode* create_node(Node* elm) { QNode* node = malloc(sizeof * node); if (!node) return node; node->data = elm; node->next = NULL; return node; } int is_empty_q(Queue *q) { return q->tail == NULL; } QNode* tail_prev(Queue *q) { QNode* node = q->head, *prev = NULL; while (node->next) { prev = node; node = node->next; } return prev; }
{ "domain": "codereview.stackexchange", "id": 44520, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, binary-search-tree", "url": null }
algorithm, c, binary-search-tree void enqueue(Queue *q, Node* elm) { QNode* updated_head = create_node(elm); if (!q->head) { q->head = updated_head; q->tail = q->head; } else { updated_head->next = q->head; q->head = updated_head; } q->size++; } Node* dequeue(Queue *q) { if (!is_empty_q(q)) { QNode* node = q->tail; Node* elm = q->tail->data; q->tail = tail_prev(q); if (q->tail) { q->tail->next = NULL; } else { q->head = NULL; } free(node); q->size--; return elm; } return NULL; } Node* front(Queue *q) { Node* front; if (q->tail) front = q->tail->data; else front = NULL; return front; } void clear_q(Queue *q) { while (q->tail) dequeue(q); printf("Queue Cleared"); } //---------------BST------------------ typedef struct BST { Node* root; } BST; const BST bst_init = { .root = NULL }; Node* create_node_bst(int elm) { Node* node = malloc(sizeof * node); if (!node) return node; node->data = elm; node->left = node->right = NULL; return node; } BST* create_bst() { BST* bst = malloc(sizeof * bst); if (!bst) return bst; bst->root = NULL; return bst; } int is_empty(Node* root) { return root == NULL; } Node* insert(Node* root, int elm) { // -V if (!root) { root = create_node_bst(elm); } else if (elm <= root->data) { root->left = insert(root->left, elm); } else { root->right = insert(root->right, elm); } return root; }
{ "domain": "codereview.stackexchange", "id": 44520, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, binary-search-tree", "url": null }
algorithm, c, binary-search-tree Node* find(Node* root, int elm) { // -V if (!is_empty(root)) { if (!root) { root = NULL; } else if (root->data == elm) { root = root; } else if (elm <= root->data) { root = find(root->left, elm); } else { root = find(root->right, elm); } return root; } else return root; } Node* find_max(Node* root) { //-V if (!is_empty(root)) { if (root->right == NULL) return root; else { return find_max(root->right); } } else return root; } Node* find_min(Node* root) { //-V if (!is_empty(root)) { if (!root->left) return root; else { return find_min(root->left); } } else return root; } int height(Node* root) { if (root == NULL) { return -1; // 0 if heighe is number of edges, or -1 if height=number of edges } int left_height = height(root->left); int right_height = height(root->right); return max(left_height, right_height) + 1; } int depth(Node* root, int elm) { if (root->data == elm) { return 0; } else if (elm < root->data) { return depth(root->left, elm) + 1; } else { return depth(root->right, elm) + 1; } }
{ "domain": "codereview.stackexchange", "id": 44520, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, binary-search-tree", "url": null }
algorithm, c, binary-search-tree Node* delete(Node* root, int elm) { if (root == NULL) return root; else if (elm > root->data) root->right = delete(root->right, elm); else if (elm < root->data) root->left = delete(root->left, elm); else { // elm found if (root->left == NULL && root->right == NULL) { free(root); root = NULL; } else if (root->left == NULL) { Node* temp = root; root = root->right; free(temp); } else if (root->right == NULL) { Node* temp = root; root = root->left; free(temp); } else { //this case is done until it is reduced to one of the previous three cases Node* temp = find_min(root->right); root->data = temp->data; root->right = delete(root->right, elm); } } return root; } int is_bst(Node* root, int min, int max) { // solution 1 if (root == NULL) { return 1; } else if (root->data < max && root->data > min && is_bst(root->left, min, root->data) && is_bst(root->right, root->data, max)) return 1; else return 0; } // solution 2, traverse inorder and check if the list is sorted int is_bst_balanced(Node* root) { int is_balanced = 1; int left_height = height(root->left); int right_height = height(root->right); if (abs(right_height - left_height) > 1) is_balanced = 0; return is_balanced; } int size(Node* root) { if (!root) return 0; int left_size = size(root->left); int right_size = size(root->right); return left_size + right_size + 1; // + 1 is for the ancesstor }
{ "domain": "codereview.stackexchange", "id": 44520, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, binary-search-tree", "url": null }
algorithm, c, binary-search-tree void level_order(Node* root) { // visit all children before grand children if (!is_empty(root)) { Queue *q = malloc(sizeof *q); if (q) { *q = queue_init; enqueue(q, root); while (!is_empty_q(q)) { Node* cur = front(q); printf("%d ", cur->data); if (cur->left != NULL) enqueue(q, cur->left); if (cur->right != NULL) enqueue(q, cur->right); dequeue(q); } } } } void pre_order(Node* root) { //D<root>L<left>R<right> -- preorder (of root) if (root) { printf("%d ", root->data); pre_order(root->left); pre_order(root->right); } } void in_order(Node* root) { //L<left>D<root>R<right> -- inorder -- gives sorted list if (root) { in_order(root->left); printf("%d ", root->data); in_order(root->right); } } Node* in_order_suc(Node* root, int data) { Node* cur = find(root, data); if (!cur) return cur; if (cur->right != NULL) { //case 1: node has sub tree return find_min(cur->right); } else { //case 2: no right sub tree Node* suc = NULL, *prev = root; while (prev != cur) { if (cur->data < prev->data) { suc = prev; prev = prev->left; } else { prev = prev->right; } } return suc; } } void post_order(Node* root) { //L<left>R<right>R<root> -- postorder if (root) { post_order(root->left); post_order(root->right); printf("%d ", root->data); } } Node* clear(Node* root) { while (root) { root = delete(root, root->data); } return root; }
{ "domain": "codereview.stackexchange", "id": 44520, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, binary-search-tree", "url": null }
algorithm, c, binary-search-tree int main() { #define MAX 8 int n = MAX; BST bst1 = bst_init; Node* bst1_root = bst1.root; int arr[MAX] = {15, 10, 20, 9, 13, 19, 22, 18}; if (!arr) return 0; for (int i = 0; i < n; i++) bst1_root = insert(bst1_root, arr[i]); printf("height: %d \n", height(bst1_root)); printf("size: %d \n", size(bst1_root)); printf("depth of 13: %d \n", depth(bst1_root, 18)); printf("is_bst: %d \n", is_bst(bst1_root, -1000, 1000)); //assuming -1000 < data(bst) < 1000 printf("is_bst_balanced: %d \n", is_bst_balanced(bst1_root)); printf("min: %d \n", find_min(bst1_root)->data); printf("max: %d \n", find_max(bst1_root)->data); printf("element: %d found \n", find(bst1_root, 19)->data); printf("level order "); level_order(bst1_root); printf("\n"); printf("preorder order "); pre_order(bst1_root); printf("\n"); printf("inorder order "); in_order(bst1_root); printf("\n"); printf("postorder order "); post_order(bst1_root); printf("\n"); printf("inorder successor of 9 is %d \n", in_order_suc(bst1_root, 9)->data); bst1_root = delete(bst1_root, 18); printf("in order "); in_order(bst1_root); printf("\n"); bst1_root = insert(bst1_root, 18); printf("in order "); in_order(bst1_root); bst1_root = clear(bst1_root); printf("\n"); if (!bst1_root) printf("BST Cleared!"); return 0; } Answer: Fix compilation warnings If your compiler isn't telling you about these, you haven't enabled enough warnings: BST* create_bst(void) { /**/ int main(void) { /**/ int arr[MAX] = {15, 10, 20, 9, 13, 19, 22, 18}; //if (!arr) return 0; assert(arr); /* local array cannot be a null pointer */
{ "domain": "codereview.stackexchange", "id": 44520, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, binary-search-tree", "url": null }
algorithm, c, binary-search-tree Fix the leak Valgrind identifies memory we haven't freed: ==3037411== HEAP SUMMARY: ==3037411== in use at exit: 24 bytes in 1 blocks ==3037411== total heap usage: 19 allocs, 18 frees, 1,392 bytes allocated ==3037411== ==3037411== 24 bytes in 1 blocks are definitely lost in loss record 1 of 1 ==3037411== at 0x48407B4: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==3037411== by 0x109903: level_order (283676.c:258) ==3037411== by 0x109D81: main (283676.c:347) Prefer functions to macros #define max(x, y) (((x) > (y)) ? (x) : (y)) This is a dangerous macro, as it expands arguments multiple times, causing doubled side-effects. Prefer to write a function for each type it's used with, or simply inline it since it's used exactly once in this program. Clients shouldn't need to know about nodes Node and QNode are implementation details that shouldn't be in the public (non-static) interface. They should be created and deleted automatically by the public function. We'd find it much easier to follow if the code at least foresaw separate compilation and put the "header" content ahead of implementation. Handle memory failure gracefully We have a good check in create_node(): QNode* node = malloc(sizeof * node); if (!node) return node; However, when we call it, we fail to account for the fact it can return a null pointer: QNode* updated_head = create_node(elm); /* possibly null */ if (!q->head) { ⋮ } else { updated_head->next = q->head; /* BANG! */ ⋮ } This is something you have been told about in a previous review, but seem not to have learnt from. Similarly, the example code in main() doesn't show us using the return value from insert() to determine whether the operation was successful.
{ "domain": "codereview.stackexchange", "id": 44520, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, binary-search-tree", "url": null }
algorithm, c, binary-search-tree The queue seems backwards It's naturally quite easy to add elements to the tail of a singly-linked list, and to remove them from the head. Doing it the other way around means that every dequeue() calls tail->prev to walk the entire length of the list. That's obviously much less efficient. Tree operations don't have to be recursive We seem to have the beginnings of iterative operation (assigning to root rather than just performing a tail-call) in insert() and find(), but have failed to follow up on that. Traversal functions are inflexible level_order(), pre_order(), in_order() and post_order() just print the values encountered. Traversal functions should take a function pointer to permit other actions. We usually also accept a void* which the function can use as state while it operates: void in_order(Node* root, void(*func)(Node*,void*), void *func_data); Think about modifiability Functions that I'd expect to accept a const tree, such as find(), have mutable arguments. A good interface is much more explicit about which operations will modify the tree and which will not. Tests should be self-checking The demo program is interesting, but it would be much more useful if it actually tested the functionality and returned appropriate exit status for success or failure.
{ "domain": "codereview.stackexchange", "id": 44520, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, binary-search-tree", "url": null }
c, linked-list, stack Title: Stack using doubly linked list Question: I have implemented my stack based on a doubly linked list. The code is tested and works; however, I am interested in any improvement ideas. #include <stdio.h> #include <stdlib.h> typedef struct Node { int data; struct Node* prev; struct Node* next; } Node; //---------------------Stack--------------------- typedef struct Stack { int size; Node* head; Node* tail; int top; } Stack; const Stack stack_init = { .size = 0, .head = NULL, .tail = NULL, .top = -1 }; Node* create_node(int elm) { Node* node = malloc(sizeof * node); if (!node) return node; node->data = elm; node->prev = NULL; node->next = NULL; return node; } int is_empty_s(Stack *s) { return s->tail == NULL; } void push(Stack *s, int elm) { Node* updated_head = create_node(elm); if (!s->head) { s->head = updated_head; s->tail = s->head; } else { updated_head->next = s->head; s->head->prev = updated_head; s->head = updated_head; } s->size++; s->top = s->head->data; } int pop(Stack *s) { if (!is_empty_s(s)) { Node* node = s->head; int elm = node->data; s->head = s->head->next; if (s->head) { s->head->prev = NULL; s->top = s->head->data; } else { s->tail = NULL; s->top = -1; } s->size--; free(node); return elm; } return -111; //assuming it -111 won't be in the stack } int top(Stack *s) { return s->top; } void clear_s(Stack *s) { while (s->tail) pop(s); } void reverse_s(Stack *s) { //iterative Stack *s2 = malloc(sizeof *s2); *s2 = stack_init; while (s->tail) push(s2, pop(s)); s->head = s2->head; }
{ "domain": "codereview.stackexchange", "id": 44521, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list, stack", "url": null }
c, linked-list, stack while (s->tail) push(s2, pop(s)); s->head = s2->head; } void print_s(Stack *s) { for(Node* trav = s->head; trav != NULL; trav = trav->next) printf("%d ", trav->data); printf("\n"); } int main() { Stack s1 = stack_init; push(&s1, 5); push(&s1, 4); print_s(&s1); reverse_s(&s1); print_s(&s1); return 0; } Answer: Why use a doubly-linked list? All the work of a stack is at one end, so a singly-linked list will save you space and time (both coding time and execution time). We're failing to account for null pointer return here: Node* updated_head = create_node(elm); if (!s->head) { ⋮ } else { updated_head->next = s->head; And here: Stack *s2 = malloc(sizeof *s2); *s2 = stack_init; Compiling with gcc -fanalyzer reveals these, and running under Valgrind shows failure to free the latter. I've never, ever, needed to reverse the elements in a stack. Unless you have a compelling use case, drop that function. If you do have such a use, document why it's needed in a comment, so that when it's no longer needed it can be removed. It's good practice to make all function declarations declare the acceptable arguments: int main(void) Please use braces consistent for all control structures (if, for, while, do). It makes your code clearer and more resilient to editing.
{ "domain": "codereview.stackexchange", "id": 44521, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list, stack", "url": null }
c++, performance, template, c++20, constrained-templates Title: A recursive_transform Template Function with Calling reserve for Performance Improvement Question: This is a follow-up question for A recursive_transform Template Function with Unwrap Level for std::array Implementation in C++. Following the suggestion mentioned in G. Sliepen's answer, the function recursive_transform implementation is updated. The constraint using requires clause is performed instead of using static_assert(). The is_iterable concept is replaced by std::ranges::input_range in STL. Moreover, std::ranges::transform() is used in the overload that handles std::array. For the part of performance acceleration, another overload is added for those containers with reserve() member function. To separate the version for dealing with containers with / without reserve member function, additional concept is_reservable is added in this post. The experimental implementation The experimental implementations of recursive_transform function and the used is_reservable concept are as follows. recursive_transform function implementation: // recursive_transform implementation (the version with unwrap_level) template<std::size_t unwrap_level = 1, class T, class F> requires (unwrap_level <= recursive_depth<T>()&& // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235 !is_reservable<T>) // constexpr auto recursive_transform(const T& input, const F& f) { if constexpr (unwrap_level > 0) { recursive_invoke_result_t<F, T> output{}; std::ranges::transform( input, // passing a range to std::ranges::transform() std::inserter(output, std::ranges::end(output)), [&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); } ); return output; } else { return std::invoke(f, input); // use std::invoke() } }
{ "domain": "codereview.stackexchange", "id": 44522, "lm_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, template, c++20, constrained-templates", "url": null }
c++, performance, template, c++20, constrained-templates // recursive_transform implementation (the version with unwrap_level, reserve space) template<std::size_t unwrap_level = 1, class T, class F> requires ( unwrap_level <= recursive_depth<T>()&& // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235 is_reservable<T>) constexpr auto recursive_transform(const T& input, const F& f) { if constexpr (unwrap_level > 0) { recursive_invoke_result_t<F, T> output{}; output.reserve(input.size()); // Call reserve() if possible, https://codereview.stackexchange.com/a/283563/231235 std::ranges::transform( input, // passing a range to std::ranges::transform() std::inserter(output, std::ranges::end(output)), [&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); } ); return output; } else { return std::invoke(f, input); // use std::invoke() } } /* This overload of recursive_transform is to support std::array */ template< std::size_t unwrap_level = 1, template<class, std::size_t> class Container, typename T, std::size_t N, typename F > requires std::ranges::input_range<Container<T, N>> constexpr auto recursive_transform(const Container<T, N>& input, const F& f) { Container<recursive_invoke_result_t<F, T>, N> output; std::ranges::transform( // Use std::ranges::transform() for std::arrays as well input, std::begin(output), [&f](auto&& element){ return recursive_transform<unwrap_level - 1>(element, f); } ); return output; } is_reservable concept implementation: template<class T> concept is_reservable = requires(T input) { input.reserve(1); };
{ "domain": "codereview.stackexchange", "id": 44522, "lm_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, template, c++20, constrained-templates", "url": null }
c++, performance, template, c++20, constrained-templates Full Testing Code The full testing code: // A recursive_transform Template Function with Calling reserve for Performance Improvement #include <algorithm> #include <array> #include <cassert> #include <chrono> #include <complex> #include <concepts> #include <deque> #include <execution> #include <exception> #include <functional> #include <iostream> #include <iterator> #include <list> #include <map> #include <mutex> #include <numeric> #include <optional> #include <ranges> #include <stdexcept> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <variant> #include <vector> template<class T> concept is_reservable = requires(T input) { input.reserve(1); }; // recursive_depth function implementation template<typename T> constexpr std::size_t recursive_depth() { return 0; } template<std::ranges::input_range Range> constexpr std::size_t recursive_depth() { return recursive_depth<std::ranges::range_value_t<Range>>() + 1; } // recursive_invoke_result_t implementation template<typename, typename> struct recursive_invoke_result { }; template<typename T, std::invocable<T> F> struct recursive_invoke_result<F, T> { using type = std::invoke_result_t<F, T>; }; template<typename F, template<typename...> typename Container, typename... Ts> requires ( !std::invocable<F, Container<Ts...>>&& // F cannot be invoked to Container<Ts...> directly std::ranges::input_range<Container<Ts...>>&& requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type; }) struct recursive_invoke_result<F, Container<Ts...>> { using type = Container< typename recursive_invoke_result< F, std::ranges::range_value_t<Container<Ts...>> >::type >; };
{ "domain": "codereview.stackexchange", "id": 44522, "lm_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, template, c++20, constrained-templates", "url": null }
c++, performance, template, c++20, constrained-templates template<template<typename, std::size_t> typename Container, typename T, std::size_t N, std::invocable<Container<T, N>> F> struct recursive_invoke_result<F, Container<T, N>> { using type = std::invoke_result_t<F, Container<T, N>>; }; template<template<typename, std::size_t> typename Container, typename T, std::size_t N, typename F> requires ( !std::invocable<F, Container<T, N>>&& // F cannot be invoked to Container<Ts...> directly requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<T, N>>>::type; }) struct recursive_invoke_result<F, Container<T, N>> { using type = Container< typename recursive_invoke_result< F, std::ranges::range_value_t<Container<T, N>> >::type , N>; }; template<typename F, typename T> using recursive_invoke_result_t = typename recursive_invoke_result<F, T>::type; // recursive_transform implementation (the version with unwrap_level) template<std::size_t unwrap_level = 1, class T, class F> requires (unwrap_level <= recursive_depth<T>()&& // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235 !is_reservable<T>) // constexpr auto recursive_transform(const T& input, const F& f) { if constexpr (unwrap_level > 0) { recursive_invoke_result_t<F, T> output{}; std::ranges::transform( input, // passing a range to std::ranges::transform() std::inserter(output, std::ranges::end(output)), [&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); } ); return output; } else { return std::invoke(f, input); // use std::invoke() } }
{ "domain": "codereview.stackexchange", "id": 44522, "lm_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, template, c++20, constrained-templates", "url": null }
c++, performance, template, c++20, constrained-templates // recursive_transform implementation (the version with unwrap_level, reserve space) template<std::size_t unwrap_level = 1, class T, class F> requires ( unwrap_level <= recursive_depth<T>()&& // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235 is_reservable<T>) constexpr auto recursive_transform(const T& input, const F& f) { if constexpr (unwrap_level > 0) { recursive_invoke_result_t<F, T> output{}; output.reserve(input.size()); // Call reserve() if possible, https://codereview.stackexchange.com/a/283563/231235 std::ranges::transform( input, // passing a range to std::ranges::transform() std::inserter(output, std::ranges::end(output)), [&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); } ); return output; } else { return std::invoke(f, input); // use std::invoke() } } /* This overload of recursive_transform is to support std::array */ template< std::size_t unwrap_level = 1, template<class, std::size_t> class Container, typename T, std::size_t N, typename F > requires std::ranges::input_range<Container<T, N>> constexpr auto recursive_transform(const Container<T, N>& input, const F& f) { Container<recursive_invoke_result_t<F, T>, N> output; std::ranges::transform( // Use std::ranges::transform() for std::arrays as well input, std::begin(output), [&f](auto&& element){ return recursive_transform<unwrap_level - 1>(element, f); } ); return output; }
{ "domain": "codereview.stackexchange", "id": 44522, "lm_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, template, c++20, constrained-templates", "url": null }
c++, performance, template, c++20, constrained-templates return output; } int main() { // non-nested input test, lambda function applied on input directly int test_number = 3; std::cout << "non-nested input test, lambda function applied on input directly: \n" << recursive_transform<0>(test_number, [](auto&& element) { return element + 1; }) << '\n'; // test with non-nested std::array container static constexpr std::size_t D = 3; auto test_array = std::array< double, D >{1, 2, 3}; std::cout << "test with non-nested std::array container: \n" << recursive_transform<1>(test_array, [](auto&& element) { return element + 1; })[0] << '\n'; // test with nested std::arrays auto test_nested_array = std::array< decltype(test_array), D >{test_array, test_array, test_array}; //std::cout << "test with nested std::arrays: \n" // << recursive_transform<2>(test_nested_array, [](auto&& element) { return element + 1; })[0][0] << '\n'; // nested input test, lambda function applied on input directly std::vector<int> test_vector = { 1, 2, 3 }; std::cout << recursive_transform<0>(test_vector, [](auto element) { element.push_back(4); element.push_back(5); return element; }).size() << '\n'; // std::vector<int> -> std::vector<std::string> auto recursive_transform_result = recursive_transform<1>( test_vector, [](int x)->std::string { return std::to_string(x); } ); // For testing
{ "domain": "codereview.stackexchange", "id": 44522, "lm_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, template, c++20, constrained-templates", "url": null }
c++, performance, template, c++20, constrained-templates std::cout << "std::vector<int> -> std::vector<std::string>: " + recursive_transform_result.at(0) << '\n'; // recursive_transform_result.at(0) is a std::string // std::vector<string> -> std::vector<int> std::cout << "std::vector<string> -> std::vector<int>: " << recursive_transform<1>( recursive_transform_result, [](std::string x) { return std::atoi(x.c_str()); }).at(0) + 1 << '\n'; // std::string element to int // std::vector<std::vector<int>> -> std::vector<std::vector<std::string>> std::vector<decltype(test_vector)> test_vector2 = { test_vector, test_vector, test_vector }; auto recursive_transform_result2 = recursive_transform<2>( test_vector2, [](int x)->std::string { return std::to_string(x); } ); // For testing std::cout << "string: " + recursive_transform_result2.at(0).at(0) << '\n'; // recursive_transform_result.at(0).at(0) is also a std::string // std::deque<int> -> std::deque<std::string> std::deque<int> test_deque; test_deque.push_back(1); test_deque.push_back(1); test_deque.push_back(1); auto recursive_transform_result3 = recursive_transform<1>( test_deque, [](int x)->std::string { return std::to_string(x); }); // For testing std::cout << "string: " + recursive_transform_result3.at(0) << '\n'; // std::deque<std::deque<int>> -> std::deque<std::deque<std::string>> std::deque<decltype(test_deque)> test_deque2; test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); auto recursive_transform_result4 = recursive_transform<2>( test_deque2, [](int x)->std::string { return std::to_string(x); }); // For testing
{ "domain": "codereview.stackexchange", "id": 44522, "lm_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, template, c++20, constrained-templates", "url": null }
c++, performance, template, c++20, constrained-templates std::cout << "string: " + recursive_transform_result4.at(0).at(0) << '\n'; // std::list<int> -> std::list<std::string> std::list<int> test_list = { 1, 2, 3, 4 }; auto recursive_transform_result5 = recursive_transform<1>( test_list, [](int x)->std::string { return std::to_string(x); }); // For testing std::cout << "string: " + recursive_transform_result5.front() << '\n'; // std::list<std::list<int>> -> std::list<std::list<std::string>> std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list }; auto recursive_transform_result6 = recursive_transform<2>( test_list2, [](int x)->std::string { return std::to_string(x); }); // For testing std::cout << "string: " + recursive_transform_result6.front().front() << '\n'; return 0; } The output of the test code above: non-nested input test, lambda function applied on input directly: 4 test with non-nested std::array container: 2 5 std::vector<int> -> std::vector<std::string>: 1 std::vector<string> -> std::vector<int>: 2 string: 1 string: 1 string: 1 string: 1 string: 1 Godbolt link All suggestions are welcome. The summary information: Which question it is a follow-up to? A recursive_transform Template Function with Unwrap Level for std::array Implementation in C++ What changes has been made in the code since last question? The constraint using requires clause is performed instead of using static_assert(). New concept is_reservable is proposed and another overload calling reserve() member function is added. Why a new review is being asked for? Please review the updated version recursive_transform template function. I am not sure there is any other better way to deal with containers with / without reserve member function for performance improvement. Any other further suggestion is welcome, certainly.
{ "domain": "codereview.stackexchange", "id": 44522, "lm_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, template, c++20, constrained-templates", "url": null }
c++, performance, template, c++20, constrained-templates Answer: Avoid code duplication You have two versions of recursive_transform() that look very similar, and only differ in whether reserve() is called. I would avoid the code duplication here by making use of if constexpr: template<std::size_t unwrap_level = 1, class T, class F> requires (unwrap_level <= recursive_depth<T>()) constexpr auto recursive_transform(const T& input, const F& f) { … recursive_invoke_result_t<F, T> output{}; if constexpr (is_reservable<decltype(output)>) { output.reserve(); } … }
{ "domain": "codereview.stackexchange", "id": 44522, "lm_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, template, c++20, constrained-templates", "url": null }
c, networking, socket Title: Follow Up: struct sockaddr storage initialization by network format-string Question: This is a follow up to: struct sockaddr_storage initialization by network format string First of all thanks to @Haris, @Toby Speight, @G. Sliepen and @chux - Reinstate for their help. I learned a lot and try to use it for future projects. I removed the Addr type for this code to keep it clean and based on the basic structures used in network programming. I've split the code into miscellaneous code in misc.c and each function returning a socket in this case has its own file. There is an internal header file netstring_internal.h containing definitions for misc.c and the user header file netstring.h. Hope I did realize your suggestions as good as possible. If you think I missed something you can let me know. netstring_internal.h: I put the macro for getting the size of an array in it. Very useful and simple solution defining a constant for the host buffer size #ifndef _INTERNAL_NETSTRING_H /* BEGIN INCLUDE GUARD */ #define _INTERNAL_NETSTRING_H #if(_POSIX_C_SOURCE != 200112L) #undef _POSIX_C_SOURCE #define _POSIX_C_SOURCE 200112L #endif #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #define DOMAIN_BUFSIZ 256 /* used vor netstring parser */ #define ARRAYSIZE(x) (sizeof(x) / sizeof(x[0])) /* make protocl_table defined in misc.c visible to other files */ extern const char *protocol_table[]; /* numerical identifiert for the protocol table */ enum netstr_protocols {tcp, tcp4, tcp6, udp, udp4, udp6}; /* error number returned by all functions beginning with -2...-n because functions will return and socket and socket return -1 on error otherwise will be > 0 */ enum netstr_error { NETSTR_PROTO = -2, NETSTR_HOST = -3, NETSTR_PORT = -4, NETSTR_INET_PTON = -5, };
{ "domain": "codereview.stackexchange", "id": 44523, "lm_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, networking, socket", "url": null }
c, networking, socket /* netstring internal */ /*! @function @param str1 null terminated first string to compare @param str2 null terminated first string to compare @param delim charcter until compare happens */ bool netstr_compare_until_delim(const char *str1, const char *str2, char delim); /*! @function @abstract internal function to compare beginning of string to a lookup table containing predefined protocol formats @param str const char pointer to string @return int: index of to be used with protocol_table */ int netstr_check_protocol(const char **str); /*! @function @abstract parsing string for host as (ipv6 format, ipv4 dotted notation or domain name), writing everything valid to buffer @param host_start: double char pointer with starting location for the host part @param dest: pointer to host buffer @return index of to be used with protocol_table */ int netstring_write_domain(const char **host_start, char *dest); /*! @function @abstract interal function that takes the assumed string location of port and translating it to int if valid @param str double char pointer to char array (used to update it to the address behind end of string number) @return port if port > 0 and port < 65536 and -1 on error */ int netstr_check_port(const char **str); /*! @function @abstract internal function used to check for domain lookup and overwriting if any @param host pointer to the buffer containing the host @param sz size of host buffer @return 0 on succes or NETSTR_HOST error value */ int netstr_resolve_host(char *host, int sz); /*! @function @abstract internal function used to get the appropriate socket type for the socket @param proto: internal defined protocol value @return socket type defined by <sys/socket.h> */ int netstr_get_proto(int proto);
{ "domain": "codereview.stackexchange", "id": 44523, "lm_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, networking, socket", "url": null }
c, networking, socket /*! @function @abstract internal function to setup struct sockaddr_storage by ipv6 flag, host and port @param *sockaddr_storage pointer to struct sockaddr_storage @param ipv6 bool to check if use ipv6 or ipv4 structure @param host null terminated host buffer @param port port number @return 0 on success, -1 if error */ int netstr_setup_sockaddr(void *sockaddr_storage, bool ipv6, const char*host, int port); #endif /* END INCLUDE GUARD */ misc.c: using simplified compare_until_delim by Toby Speight split down into some functions S can use for this format I use braces around every if/else if/else I use strtol with checking for errno for error I removed the need of stncpy_s because netstring_write_domain will write host/domain into buffer while parsing #include "netstring_internal.h" #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <errno.h> #include <netdb.h> #include <arpa/inet.h> /* protocol table containing supported protocol for socket configuration */ const char *protocol_table[] = { "tcp:", "tcp4:", "tcp6:", "udp:", "udp4:", "upd6:", }; /*! @function @param str1 null terminated first string to compare @param str2 null terminated first string to compare @param delim charcter until compare happens */ bool netstr_compare_until_delim(const char *str1, const char *str2, char delim) { const char end[] = "\0\0"; while (*str1 || *str2) { if (*str1 == delim) str1 = end; if (*str2 == delim) str2 = end; if (*str1++ != *str2++) return false; } return true; } /*! @function @abstract internal function to compare beginning of string to a lookup table containing predefined protocol formats @param str const char pointer to string @return int: index of to be used with protocol_table */ int netstr_check_protocol(const char **str) { int i; int table_size = sizeof(protocol_table) / sizeof(*protocol_table);
{ "domain": "codereview.stackexchange", "id": 44523, "lm_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, networking, socket", "url": null }
c, networking, socket for(i = 0; i < table_size ; i++) { if(netstr_compare_until_delim(protocol_table[i], *str, ':')) { *str = *str + strlen(protocol_table[i]); return i; } } return -1; /* not found */ } /*! @function @abstract parsing string for host as (ipv6 format, ipv4 dotted notation or domain name), writing everything valid to buffer @param host_start: double char pointer with starting location for the host part @param dest: pointer to host buffer @return index of to be used with protocol_table */ int netstring_write_domain(const char **host_start, char *dest) { bool ipv6 = false; const char *start = *host_start; *dest = '\0'; /* if first char after protocol is [ check for ] to say it is an ipv6 address */ if(*start == '[') { /* go latest until null byte */ start++; /* go behind '[' */ while(*start != '\0') { /* if enclosure bracket ] was found set ipv6 true and increment service_start */ if(*start == ']') { *dest = '\0'; ipv6 = true; start++; break; } *dest++ = *start++; } /* service_start should point to ':' in format string right before service/port */ } /* ip not ipv6 assume ipv4 or domain name */ if(ipv6 == false) { /* go latest until null byte */ while(*start != '\0') { /* service_start points to seperator ':', increment domain_p first and set to null byte */ if(*start == ':') { *dest = '\0'; break; } /* write a copy to domain_buffer */ *dest++ = *start++; } /* service_start should point to ':' in format string right before service/port too */ } if(*start != ':') { return NETSTR_HOST; /* return position in host string */ }
{ "domain": "codereview.stackexchange", "id": 44523, "lm_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, networking, socket", "url": null }
c, networking, socket if(*start != ':') { return NETSTR_HOST; /* return position in host string */ } *host_start = ++start; /* overwrite external string with ne location */ return ipv6; } /*! @function @abstract interal function that takes the assumed string location of port and translating it to int if valid @param str double char pointer to char array (used to update it to the address behind end of string number) @return port if port > 0 and port < 65536 and -1 on error */ int netstr_check_port(const char **str) { long port; port = strtol(*str, (char **) str, 10); if (errno == EINVAL || errno == ERANGE) return -1; if (port < 1 && port > 65535) return -1; return (int) port; } /*! @function @abstract internal function used to check for domain lookup and overwriting if any @param host pointer to the buffer containing the host @param sz size of host buffer @return 0 on succes or NETSTR_HOST error value */ int netstr_resolve_host(char *host, int sz) { struct hostent *entry = gethostbyname(host); if (entry == NULL) return NETSTR_HOST; strncpy(host, inet_ntoa(*(struct in_addr*)entry->h_addr_list[0]), sz); return 0; } /*! @function @abstract internal function used to get the appropriate socket type for the socket @param proto: internal defined protocol value @return socket type defined by <sys/socket.h> */ int netstr_get_proto(int proto) { switch(proto) { case tcp: case tcp4: case tcp6: proto = SOCK_STREAM; break; case udp: case udp4: case udp6: proto = SOCK_DGRAM; break; default: /* this should never happen */ return proto = -1; } return proto; }
{ "domain": "codereview.stackexchange", "id": 44523, "lm_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, networking, socket", "url": null }
c, networking, socket return proto; } /*! @function @abstract internal function to setup struct sockaddr_storage by ipv6 flag, host and port @param *sockaddr_storage pointer to struct sockaddr_storage @param ipv6 bool to check if use ipv6 or ipv4 structure @param host null terminated host buffer @param port port number @return 0 on success, -1 if error */ int netstr_setup_sockaddr(void *sockaddr_storage, bool ipv6, const char *host, int port) { void *in_addr = NULL; if (ipv6 == true) { ((struct sockaddr_in6 *) sockaddr_storage)->sin6_family = AF_INET6; ((struct sockaddr_in6 *) sockaddr_storage)->sin6_port = htons(port); in_addr = &((struct sockaddr_in6 *) sockaddr_storage)->sin6_addr; } else { /* ipv4 */ ((struct sockaddr_in *) sockaddr_storage)->sin_family = AF_INET; ((struct sockaddr_in *) sockaddr_storage)->sin_port = htons(port); in_addr = &((struct sockaddr_in *) sockaddr_storage)->sin_addr; } if (inet_pton(((struct sockaddr*)sockaddr_storage)->sa_family, host, in_addr) != 1) { return -1; } return 0; } netstring_to_addrinfo.c I implemented one function that uses struct addrinfo //#include <stdnet.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <errno.h> #include <assert.h> #include <unistd.h> #include <time.h> #include "netstring_internal.h" #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h>
{ "domain": "codereview.stackexchange", "id": 44523, "lm_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, networking, socket", "url": null }
c, networking, socket /*! @function @abstract returns a configured socket for given network format string and setup of struct addrinfo (freeing struct addrinfo is for user) @param netstr network format string like 'proto:host:port' e.g. tcp:www.google.de:443 or udp:8.8.8.8:dns @param storage: pointer to stuct sockaddr_storage @return configured socket */ int netstring_to_addrinfo(const char *netstr, struct addrinfo **info) { int proto = -1, ipv6 = 0, err = 0; char host[DOMAIN_BUFSIZ]; struct addrinfo hint; memset(&hint, 0, sizeof hint); /* get protocol if any otherwise return with error */ proto = netstr_check_protocol(&netstr); if(proto < 0) { err = NETSTR_PROTO; goto CLEANUP_ERROR; } /* write host (domain, ip or ipv6) to host buffer and return on error */ ipv6 = netstring_write_domain(&netstr, host); if (ipv6 == NETSTR_HOST) { err = ipv6; goto CLEANUP_ERROR; } /* set hint based on ipv6 or ipv4 */ if (ipv6 == true) { hint.ai_family = AF_INET6; } else { hint.ai_family = AF_INET; } /* get the correct socket type from protocl found in netstr */ proto = netstr_get_socktype(proto); if(proto == -1) { err = NETSTR_PROTO; goto CLEANUP_ERROR; } hint.ai_socktype = proto; /* lookup domain if any and return on error */ err = getaddrinfo(host, netstr, &hint, info); if (err) { err = errno; goto CLEANUP_ERROR; } /* setup socket with infos from getaddrinfo */ int sock; sock = socket((*info)->ai_family, (*info)->ai_socktype, (*info)->ai_protocol); if (sock == -1) { err = errno; freeaddrinfo((*info)); goto CLEANUP_ERROR; } return sock; CLEANUP_ERROR: return err; } netstring_to_socket.c: I kept the version with struct sockaddr_storage anyway #include "netstring_internal.h"
{ "domain": "codereview.stackexchange", "id": 44523, "lm_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, networking, socket", "url": null }
c, networking, socket I kept the version with struct sockaddr_storage anyway #include "netstring_internal.h" /*! @function @abstract returns a configured socket for given network format string and setup of struct sockaddr_storage @param netstr network format string like 'proto:host:port' @param storage: pointer to stuct sockaddr_storage @return configured socket */ int netstring_to_socket(const char *ipstr, struct sockaddr_storage *storage) { int proto = -1, port = -1, err = 0; bool ipv6 = 0; char host[DOMAIN_BUFSIZ]; /* get protocol if any otherwise return with error */ proto = netstr_check_protocol(&ipstr); if (proto == -1) { err = NETSTR_PROTO; goto CLEANUP_ERROR; } /* write host (domain, ip or ipv6) to host buffer and return on error */ ipv6 = netstring_write_domain(&ipstr, host); if (ipv6 == NETSTR_HOST) { err = NETSTR_HOST; goto CLEANUP_ERROR; } /* check if port is a valid port */ if ((port = netstr_check_port(&ipstr)) < 0) { err = NETSTR_PORT; goto CLEANUP_ERROR; } /* if not ipv6 expecting hostname or ip address so resolve hostname and overwrite current host */ if(ipv6 == false) { if(netstr_resolve_host(host, sizeof host)) { err = NETSTR_HOST; goto CLEANUP_ERROR; } } /* setting up sockaddr_storage and return on error if any */ err = netstr_setup_sockaddr(storage, ipv6, host, port); if (err) { err = NETSTR_INET_PTON; goto CLEANUP_ERROR; } /* get the correct socket type from protocol found in netstr */ proto = netstr_get_socktype(proto); if (proto == -1) { err = NETSTR_PROTO; goto CLEANUP_ERROR; } /* setup socket and return it */ return socket(((struct sockaddr_in *) storage)->sin_family, proto, 0); CLEANUP_ERROR: return err; } Answer: Why not always use getaddrinfo()?
{ "domain": "codereview.stackexchange", "id": 44523, "lm_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, networking, socket", "url": null }
c, networking, socket Answer: Why not always use getaddrinfo()? I kept the version with struct sockaddr_storage anyway Why? It is inferior in every possible way, except that it might work on some very old/rare systems that do have struct sockaddr_in6 and inet_pton() but not getaddrinfo(). Unless you really need to support those, I would not bother with it. Make sure names are precise Your netstring_to_addrinfo() does more than convert a string to "an" addrinfo, it also creates a socket. Either I would put that in the name as well (netstring_to_socket_and_addrinfo()), or I would have it not create a socket to begin with. An addrinfo has all the information needed to create a proper socket for the address it holds. But more importantly, getaddrinfo() returns a pointer to a list of addrinfos, since more than one address can be associated with a hostname. You cannot just create a socket for the first addrinfo in the list, as the next one might be for a different address family.
{ "domain": "codereview.stackexchange", "id": 44523, "lm_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, networking, socket", "url": null }
python-3.x, object-oriented, mathematics, api, generics Title: Python Module for representation, calculus and rich comparisons between temperature scale instances Question: ToTemp is a temperature conversion package with Celsius, Delisle, Fahrenheit, Kelvin, Rankine, Réaumur, Newton and Rømer scales. With a documentation and already in PyPI. The source code for the main implementation here, since is too long to be completely shown, it is basically a ABC for Abstract Temperature Scales, which all scales inhehit from. Here's a snippet of it (ommited most methods and docs for brevity, besides for __init_subclass__, __init__, __repr__, __str__, __add__, convert_to and to_fahrenheit): from __future__ import annotations from abc import ABCMeta, abstractmethod from typing import Any, ClassVar, TypeVar T = TypeVar('T', bound='AbstractTemperature') class AbstractTemperature(metaclass=ABCMeta): """ ... """ _symbol: ClassVar[str] _value: float @classmethod def __init_subclass__(cls, **kwargs: object) -> None: """Ensures subclasses set the `_symbol` attribute.""" super().__init_subclass__(**kwargs) try: _ = cls._symbol except AttributeError: raise AttributeError( 'Temperature subclasses must set the `_symbol` class attribute' ) from None def __init__(self, value: float) -> None: self._value = value def __str__(self) -> str: """ ... """ return f'{self._value} {self._symbol}' def __repr__(self) -> str: """ ... """ return f'{self.__class__.__name__}({self._value})' def __add__(self: T, other: Any) -> T: """ Returns a new instance of the same class with the sum of the values. If `other` is a temperature instance, it is first converted to the calling class, then the values are added. Otherwise, an attempt is made to add `other` to the value directly.
{ "domain": "codereview.stackexchange", "id": 44524, "lm_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-3.x, object-oriented, mathematics, api, generics", "url": null }
python-3.x, object-oriented, mathematics, api, generics Notes ----- If `other` is not a temperature instance, atempts to return: cls(self._value + other) Returns ------- self.__add__(other) : T cls(self._value + other.convert_to(cls).value) """ cls = self.__class__ try: if isinstance(other, AbstractTemperature): return cls(self._value + other.convert_to(cls).value) return cls(self._value + other) except TypeError: return NotImplemented def to_fahrenheit(self) -> Fahrenheit: """ Returns a Fahrenheit object which contains the class attribute "value" with the result from the conversion typed the same as the attribute. Returns ------- convert_to(Fahrenheit) : Fahrenheit """ return self.convert_to(Fahrenheit) @abstractmethod def convert_to(self, temp_cls: type[T]) -> T: """ Returns an instance of `temp_cls` containing the converted value. If no conversion to `temp_cls` is possible, `TypeError` is raised. """ ... This package aims to bring the simple and straight to the point, but precise, Object Oriented experience of working with temperature scale data types. First of all, install the package: pip install totemp The instances: from totemp import Celsius, Fahrenheit if __name__ == '__main__': temps: list = [Celsius(12), Celsius(25), Celsius(50)] print(temps[0]) # '12 ºC' print(temps) # [Celsius(12), Celsius(25), Celsius(50)] temps = list(map(Celsius.to_fahrenheit, temps)) print(temps[0]) # '53.6 ºF' print(temps) # [Fahrenheit(53.6), Fahrenheit(77.0), Fahrenheit(122.0)] It's representations and properties: Property symbol is read-only. from totemp import Fahrenheit
{ "domain": "codereview.stackexchange", "id": 44524, "lm_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-3.x, object-oriented, mathematics, api, generics", "url": null }
python-3.x, object-oriented, mathematics, api, generics It's representations and properties: Property symbol is read-only. from totemp import Fahrenheit if __name__ == '__main__': temp0 = Fahrenheit(53.6) print(temp0.__repr__()) # 'Fahrenheit(53.6)' print(temp0.__str__()) # '53.6 ºF' print(temp0.symbol) # 'ºF' print(temp0.value) # 53.6 Comparision operations ('==', '!=', '>', '>=', '<',...): The comparision/arithmetic implementation attempts to convert the value of other (if it is a temperature instance) and then evaluate the expression. import totemp as tp if __name__ == '__main__': temp0, temp1 = tp.Celsius(0), tp.Fahrenheit(32) print(f'temp0: {repr(temp0)}') # Celsius(0) print(f'temp1: {repr(temp1.to_celsius())}') # Celsius(0.0) print(temp0 != temp1) # False print(temp0 > temp1) # False print(temp0 < temp1) # False print(temp0 >= temp1) # True print(temp0 <= temp1) # True print(temp0 == temp1) # True Arithmetic operations ('+', '-', '*', '**', '/', '//', '%', ...): from totemp import Newton, Rankine if __name__ == '__main__': temp0 = Newton(33) temp1 = Rankine(671.67) temp2 = temp0 + temp1 print('temp2:', temp2) # temp2: 65.99999999999999 ºN print('temp2:', repr(temp2)) # temp2: Newton(65.99999999999999) print('temp2:', temp2.value, temp2.symbol) # temp2: 65.99999999999999 ºN print((temp0 + temp1).rounded()) # 66 ºN print(repr((temp0 + temp1).rounded())) # Newton(66) print(temp2 + 12.55) # 78.54999999999998 ºN print((12 + temp2.rounded())) # 78 ºN ToTemp classes can work with many built-in Python functions: from math import floor, ceil, trunc from totemp import Reaumur if __name__ == '__main__': temp = Reaumur(100.4)
{ "domain": "codereview.stackexchange", "id": 44524, "lm_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-3.x, object-oriented, mathematics, api, generics", "url": null }
python-3.x, object-oriented, mathematics, api, generics from totemp import Reaumur if __name__ == '__main__': temp = Reaumur(100.4) float(temp) # 100.4 int(temp) # 100 round(temp) # Reaumur(100) abs(temp) # Reaumur(100) floor(temp) # Reaumur(100) ceil(temp) # Reaumur(101) trunc(temp) # Reaumur(100) divmod(temp, temp0 := Reaumur(25.1)) # (Reaumur(4.0), Reaumur(0.0)) Temperature Instance Conversions: import totemp if __name__ == '__main__': temp = totemp.Fahrenheit(32) print(temp.to_celsius()) # 0.0 ºC print(temp.to_fahrenheit()) # 32 ºF print(temp.to_delisle()) # 150.0 ºDe print(temp.to_kelvin()) # 273.15 K print(temp.to_newton()) # 0.0 ºN print(temp.to_rankine()) # 491.67 ºR print(temp.to_reaumur()) # 0.0 ºRé print(temp.to_romer()) # 7.5 ºRø And that's it, that's my first ever project, some feedback or collaborations would be wonderfull! Proud of doing this, always gratefull for the friends and other programmer dudes of the internet that helped me make this project happen.
{ "domain": "codereview.stackexchange", "id": 44524, "lm_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-3.x, object-oriented, mathematics, api, generics", "url": null }
python-3.x, object-oriented, mathematics, api, generics Answer: Tests You test that a value in corresponds to an expected value out, but where did you get the calculated value out? Was it from your code? If so, it's only testing regression. I'd prefer to see some tests based on the scales' definitions themselves (i.e. freezing/boiling pt of water) are in agreement, along with some other known quantities (e.g. 0K to check nothing reasonably goes below 0K on conversion [though this is possible in limited contexts unlikely to occur here], human body temp, other melting/boiling points) as well as some arbitrary points on the scale for regression testing. You should also probably do conversion there and back i.e. degC -> degF -> degC to check that both formulae are implemented correctly with tolerable accuracy. You also only test coversions, not any of your comparisons or arithmetic ops. Your test function takes a strange input of a 4-tuple, which is really two 2-tuples to be compared. This would make much more sense to me as a map (dict) of input->output, this also makes them iterable as pairs e.g. def func_to_test_precise_rounded_results(mapping): for inp, outp in mapping.items(): if inp != outp: # Rather than `not inp == outp` errors.append(f'{inp} != {outp} -> should be equal') This could then be called as: temps = { Romer(25).to_newton(): Newton(11.0), Romer(25).to_newton().rounded(): Newton(11), } func_to_test_precise_rounded_results(temps)
{ "domain": "codereview.stackexchange", "id": 44524, "lm_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-3.x, object-oriented, mathematics, api, generics", "url": null }
python-3.x, object-oriented, mathematics, api, generics Which, to me, makes the intent more clear and also allows testing as many comparisons as you'd like. Also, to me, the name func_to_test_precise_rounded_results is overly verbose with no extra detail. We know it's a func because we give it a verb name. It doesn't test precise vs rounded results, because those are manually provided. It compares the first 2 and last 2 elements of a 4-tuple. Implementation A common way to do lots of conversions is to have an internal value which serves as your standard format, say you picked K. You would then convert any value stored to K and then back out to unit. This means instead of having to implement new converters for every unit to every other: C -> F, F -> C, C -> K, K -> C, F -> K, K -> F [combinatoric growth] You just need: C -> K, F -> K, K -> C, K -> F [2N-1] Then C -> F is implemented as C -> K -> F. This does mean you can lose some accuracy over repeated operations, but in general this doesn't cause too much of a problem. Arithmetic operations You have implemented arithmetic operations, but what does an arithmetic operation mean on a physical quantity? 3m * 3m != 9m! It's 9m^2. Likewise for division and who knows what a mod (%) does to the units. Misc You have slightly inconsistent renderings of some of your formulae which made me have to double check whether they were right class Celsius(AbstractTemperature): ... def convert_to(self, temp_cls: type[T]) -> T: ... if temp_cls is Newton: return temp_cls(self._value * 33 / 100) class Newton(AbstractTemperature): ... def convert_to(self, temp_cls: type[T]) -> T: if temp_cls is Celsius: return temp_cls(self._value / 0.33) Consistency of style can be very helpful. Converting to Newton scale is unlikely to be consistent across the board as it's a relatively simple scale with 2 different metrics. Some points
{ "domain": "codereview.stackexchange", "id": 44524, "lm_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-3.x, object-oriented, mathematics, api, generics", "url": null }
python-3.x, object-oriented, mathematics, api, generics 0degC = 0degN 100degC = 33degN (where you get 1/3) 271degC = 81degN (81*3 = 243) - Melting pt of bismuth 327degC = 96degN (96*3 = 288) - Melting pt of lead
{ "domain": "codereview.stackexchange", "id": 44524, "lm_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-3.x, object-oriented, mathematics, api, generics", "url": null }
javascript Title: Separate a list in two lists using JavaScript Question: I have a list of events. They are html elements. The premium events have a data attribute in their parent element: data-premium-event. I need to separate the events in two lists: a list of premium events a list of regular (non-premium) events I then show oder hide them using the logic in handleVisibleEvents. The method works correctly but I would like to refactor it while it has a high cognitive complexity. this.nrOfRegularEventsDisplayed = 0; this.nrOfPremiumEventsDisplayed = 0; this.regularEventsToShow = []; this.premiumEventsToShow = []; this.refreshActiveCategoryTags(); const events = toArray(this.elements['event']); if (events) { if (this.loadEventsButton) { show(this.loadEventsButton); } events.forEach((event) => { if (event.dataset.eventTags.includes(this.activeCategory.dataset.categoryTag)) { if (event.parentElement.getAttribute('data-premium-event') !== null) { this.premiumEventsToShow.push(event); } else { this.regularEventsToShow.push(event); } } else { hide(event.parentElement); } }); this.handleVisibleEvents(TagsFilteringOverview.VISIBLE_EVENTS, false); } Answer: A common name for such operation is partition. An implementation of it might look something like const fold = to => fun => iterable => Array.prototype.reduce.call(iterable, fun, to) const partition = pred => fold ([[], []]) ((acc, x) => (acc[pred(x) ? 0 : 1].push(x), acc)) so that given a predicate const hasPremium = el => el.parentElement.dataset?.premiumEvent
{ "domain": "codereview.stackexchange", "id": 44525, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript so that given a predicate const hasPremium = el => el.parentElement.dataset?.premiumEvent and example data const data = [ {parentElement: {dataset: {premiumEvent: true}}} , {parentElement: {}} , {parentElement: {}} , {parentElement: {}} , {parentElement: {dataset: {premiumEvent: true}}} , {parentElement: {}} , {parentElement: {}} , {parentElement: {dataset: {premiumEvent: true}}} , {parentElement: {dataset: {premiumEvent: true}}} ] the usage becomes console.log(partition (hasPremium) (data))
{ "domain": "codereview.stackexchange", "id": 44525, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
c++, atomic Title: Mutually exclusive execution using std::atomic? Question: I am currently learning more about lock free programming and wondered how I could implement mutual exclusion using std::atomics. I implemented the following code to realize a pipe class for passing values between threads. pipe_t uses the exclusive_executor_t to provide mutual exclusion for its critical sections. exclusive_executor_t uses a std::atomic<bool> flag and compare and swap to prevent access to the critical section. Unfortunately, I am not sure this implementation is correct. On my system the expected sum is correct, but of course that doesn't mean much. I am currently looking into formal methods for verifying it (https://www.intel.com/content/www/us/en/developer/tools/oneapi/inspector.html#gs.rlur9y), but I thought maybe the community could offer advice and guidance before I go to far down that rabbit hole. So, is it possible to implement mutual exclusion using std::atomics and is this implementation successfully accomplishing it? #include <atomic> #include <cstddef> #include <iostream> #include <memory> #include <queue> #include <thread> #include <type_traits> template <typename value_t> class pipe_t { std::atomic<bool> is_empty{true}; std::queue<value_t> q; class exclusive_executor_t { using flag_t = std::atomic<bool>; flag_t flag; /** * @breif locks this->flag * @note blocks until this->flag is false */ void lock() { bool expected{false}; while (!flag.compare_exchange_weak(expected, true, std::memory_order_acquire, std::memory_order_relaxed)) { expected = false; } }
{ "domain": "codereview.stackexchange", "id": 44526, "lm_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++, atomic", "url": null }
c++, atomic /** * @breif releases this->flag * @note blocks until this->flag is true */ void release() { bool expected{true}; while (!flag.compare_exchange_weak(expected, false, std::memory_order_release, std::memory_order_relaxed)) { expected = true; } } public: template <typename func_t> void exec(func_t fun) { static_assert(std::is_nothrow_invocable<func_t>::value); lock(); fun(); release(); } }; exclusive_executor_t executor; public: bool empty() const { return is_empty.load(); } value_t read() { is_empty.wait(true); value_t ret; executor.exec([&]() noexcept { ret = q.front(); q.pop(); is_empty.store(q.empty()); }); return ret; } void write(value_t const val) { executor.exec([&]() noexcept { q.emplace(val); is_empty.store(false); }); } }; long long n{1'000'000}; void f(std::shared_ptr<pipe_t<int>> p) { p->write(n); for (int i{1}; i <= n; ++i) { p->write(i); } } void g(std::shared_ptr<pipe_t<int>> p) { long long sum{0}; int count{p->read()}; for (int i{1}; i <= count; ++i) { sum += p->read(); } long long const expected_sum{(n * (n + 1)) / 2}; if (sum == expected_sum) { std::cout << "pass : "; } else { std::cout << " fail : "; } std::cout << sum << " =?= " << expected_sum << std::endl; } int main() { std::shared_ptr<pipe_t<int>> p{std::make_shared<pipe_t<int>>()}; std::thread t1(f, p); std::thread t2(g, p); t1.join(); t2.join(); return 0; } ```
{ "domain": "codereview.stackexchange", "id": 44526, "lm_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++, atomic", "url": null }
c++, atomic ``` Answer: Race condition in the read() method The read() function waits for the queue to be nonempty with is_empty.wait(true);. Then it takes the lock and retrieves q.front(). However, it is possible that in between the queue becoming nonempty, and the lock being taken, some other thread takes the lock and empties the queue. So when your original thread gets the lock, it will call q.front() on an empty queue, causing undefined behavior. At the least, you need to recheck is_empty or q.empty() after taking the lock. If it is empty, release the lock and wait again. release() shouldn't have a loop Your release() method spins until this->flag is true. That might seem reasonable by symmetry with what lock() does, but it's not correct. A thread must only release a lock that it currently holds (i.e. that it previously locked and has not released since then); lock and unlock calls must strictly alternate within each thread. If release() is called with this->flag == false, this invariant has been violated, and your code has a bug somewhere. Reasonable ways to handle this are: Abort the program, as this is effectively a failed assert Log a warning and return from release() without doing anything to the flag Don't check at all - assume that the rest of your program will always call this function correctly, i.e. with the lock held, and have release() simply do an unconditional flag.store(false, std::memory_order_release); with no compare-exchange or looping. This is not very good defensive programming, but it does shave off a few clock cycles; and it's in the spirit of std::mutex, for which an attempt to unlock a mutex that isn't owned simply causes undefined behavior. But it means that if your thread A releases a lock it doesn't hold, at a time when some other thread B actually does hold it and is in a critical section, then a third thread C could take the lock and also enter the critical section, violating mutual exclusion.
{ "domain": "codereview.stackexchange", "id": 44526, "lm_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++, atomic", "url": null }
c++, atomic As it stands, what would happen is that the buggy thread (A) would spin in its loop, consuming CPU and energy as it goes, until some other thread (B) calls lock(). Then A will exit its loop and store false to the flag. This violates mutual exclusion as mentioned above. Or, maybe no other thread ever needs to lock the resource, in which case A will simply spin forever. If you choose to go to the trouble of testing the state of the lock on entry to release(), then you should handle what you observe in a sensible fashion. Don't confuse "blocking" with "spinning" "Blocking" usually means having the operating system put your thread to sleep, in such a way that it will be promptly reawakened when whatever you are waiting for happens. Like "blocking I/O". What you are doing is polling in that you just test and retest the lock until you discover it is available. Moreover you do this in a busy-loop, without any useful work or yield taking place in the meantime, so this is a spinlock. The immediate implication for your code is that the @note comments on lock() and release() are misleading. But more broadly, although spinlocks do correctly achieve mutual exclusion, they are problematic in other ways and are usually best avoided. Wasting CPU cycles is one thing, but you might think it's not such a big deal if threads will only hold the lock for very short periods (a handful of instructions, say tens of nanoseconds). The problem is that, on a non-realtime operating system, a thread holding the lock might get scheduled out, and then the lock may stay held for several milliseconds, which is roughly eternity on this scale. In the meantime, every other thread that attempts to take the lock will be spinning, and your CPU load becomes very high. Which in turn makes it take longer before the owning thread can be scheduled back in, so it's a vicious cycle.
{ "domain": "codereview.stackexchange", "id": 44526, "lm_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++, atomic", "url": null }
c++, atomic So you really do want to yield the CPU back to the OS if you need to wait for the lock. One compromise approach is that you spin for a bounded number of iterations, for the common case when the lock will be available soon, but if you don't take it within that time, you then std::this_thread::yield() or similar before trying again. This is still not ideal because your thread will have to keep waking up to test the lock. Implementations of std::mutex usually get assistance from the kernel, which keeps a "wait list" of threads currently blocked on this mutex. When the owning thread unlocks it, it notifies the kernel, which selects exactly one thread from the wait list and wakes it up, while the others remain asleep. This way there is no polling at all. Unfortunately, you cannot duplicate this in portable C++, because the standard does not expose those kernel features other than through std::mutex; you'd have to write OS-specific code. Spinlocks are mostly useful in bare-metal, kernel, or realtime code, where you can ensure that your thread won't be scheduled out because you control the scheduler, or because you have not implemented scheduling or preemption at all. If you are already running under a proper OS then you normally would not use them. Prefer std::atomic_flag The std::atomic_flag class has more useful methods than std::atomic<bool> does, most notably test_and_set (mentioned by Davislor) which is likely to be more efficient, and more readable, than the compare-exchange loop in lock(). Alternatively, if you use an integer type such as std::atomic<unsigned char>, you can use fetch_or to get this effect. Unfortunately the standard does not include these methods for std::atomic<bool>.
{ "domain": "codereview.stackexchange", "id": 44526, "lm_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++, atomic", "url": null }
c++, atomic In general, be familiar with the full stable of atomic read-modify-write operations at your disposal, including compound assignment operators which are atomic for std::atomic types (though they don't let you choose anything but the strongest std::memory_order_seq_cst ordering). Use a compare-exchange loop only when you need to do something more complex. The mutual exclusion is done correctly Your use of acquire-release ordering in the lock() and release() methods is correct, and properly achieves the desired mutual exclusion, so your code is free of data races as far as I can see. (The race condition mentioned in the first paragraph is a bug, but is not a data race in the sense of involving unsynchronized concurrent access to non-atomic objects.) The load which verifies that the lock was available is acquire, as it must be, and it is done atomically with the store that makes the lock unavailable to other threads. (The store side of this read-modify-write does not need stronger ordering in this case.) The store which releases the lock is release as it must be. Thus a release of the lock by thread A synchronizes with the load when thread B locks it, ensuring that the end of A's critical section happens-before the beginning of B's, in terms of the formal happens-before ordering. This is the simplest and most classical use of acquire-release ordering.
{ "domain": "codereview.stackexchange", "id": 44526, "lm_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++, atomic", "url": null }
c++, serialization Title: Serialization and deserialization a doubly-linked list with a pointer to a random node in C++ Question: I tried to serialize a doubly linked list. Can you rate it, and what could be improved? I open the file with fopen(path, "wb") and write all data in binary mode. #include <string> #include <unordered_map> #include <vector> #include <random> #include <iostream> struct ListNode { ListNode* prev = nullptr; ListNode* next = nullptr; ListNode* rand = nullptr; std::string data; }; class List { public: void Serialize(FILE* file) { std::unordered_map<ListNode*, int> uMap; auto cur = head; for (int i = 1; i <= count; i++) { uMap.insert(std::make_pair(cur, i)); cur = cur->next; } std::vector <std::pair<std::string, int>> vNode; vNode.reserve(count); cur = head; while (cur) { int randEl{ 0 }; if (cur->rand != nullptr) { auto search = uMap.find(cur->rand); randEl = search->second; } vNode.push_back(std::make_pair(cur->data, randEl)); cur = cur->next; } fwrite(&count, sizeof(count), 1, file); for (auto& a: vNode) { fwrite(&a.second, sizeof(a.second), 1, file); int size = a.first.size(); fwrite(&size, sizeof(size), 1, file); fwrite(a.first.c_str(), 1, size, file); } } void Deserialize(FILE* file) { std::unordered_map<int, ListNode*> uMap; std::vector<int> vRandNode; int rCount{ 0 }; fread(&rCount, sizeof(rCount), 1, file); vRandNode.reserve(rCount); rCount = 1; for (; rCount <= vRandNode.capacity(); rCount++) { int randNode{ 0 }; fread(&randNode, sizeof(randNode), 1, file);
{ "domain": "codereview.stackexchange", "id": 44527, "lm_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++, serialization", "url": null }
c++, serialization int len{ 0 }; fread(&len, sizeof(len), 1, file); std::string temp{ "" }; while (len > 0) { char ch ; fread(&ch, sizeof(ch), 1, file); temp += ch; len--; } Add(temp); vRandNode.push_back(randNode); uMap.insert(std::make_pair(rCount, tail)); } auto cur = head; for(auto a: vRandNode) { if (a != 0) cur->rand = uMap.find(a)->second; else cur->rand = nullptr; cur = cur->next; } } void Add(std::string str) { ListNode* node = new ListNode; node->data = std::move(str); count++; if (head == nullptr) { head = node; } else { tail->next = node; node->prev = tail; } tail = node; } List(){} List(std::string str) { Add(std::move(str)); } ~List() { while (head) { auto temp = head->next; delete head; head = temp; } } void ShufleRandom() { std::random_device rd; std::mt19937 gen(rd()); auto cur = head; while (cur) { auto randNode = head; int randNum = gen() % (count + 1); for (int i = 1; i < randNum; i++) { randNode = randNode->next; } if (randNum == 0) cur->rand = nullptr; else cur->rand = randNode; cur = cur->next; } }
{ "domain": "codereview.stackexchange", "id": 44527, "lm_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++, serialization", "url": null }
c++, serialization cur = cur->next; } } void PrintListAndRand() const { auto cur = head; while (cur) { std::cout << "===Data->" << cur->data; if (cur->rand) std::cout << " | RandData->" << cur->rand->data << "===" << std::endl; else std::cout << " | RandData->nullptr===" << std::endl; cur = cur->next; } std::cout << "_______________________________________________________________" << std::endl; } private: ListNode* head = nullptr; ListNode* tail = nullptr; int count = 0; }; Answer: Thanks for posting your code and not being afraid of feedback. The indentation of your code is nice and you're already using a lot of stuff present in the C++ standard library. That's great. Unclear application I don't understand how the structure would be beneficial for me. What would I use a linked list pointing to random nodes for? And while I can add something to the list, it seems there's no way of accessing the elements of the list except saving and printing. Your list does not act like a C++ container and thus its use is limited. We can't use it with any algorithms of the standard library. Use of FILE and fopen() These probably come from <cstdio>, which you should include, following the "include what you use" (IWYU) principle. And, as the name of the library suggests, they are C functions. For C++ you might want to #include <fstream> and use std::ifstream and std::ofstream instead. Rule of 5 You have implemented a custom destructor, which means that you should think about a copy constructor, copy assignment operator, move constructor and move assignment operator as well. See: The rule of three/five/zero Long function Serialize The function is 30 lines long and from its structure, it looks like this could be split into 3 smaller private functions:
{ "domain": "codereview.stackexchange", "id": 44527, "lm_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++, serialization", "url": null }
c++, serialization conversion of the list into a Hashmap. conversion of the Hashmap into a flat list writing the flat list Use emplace_back The line vNode.push_back(std::make_pair(cur->data, randEl)); can be replaced by the shorter and more efficient vNode.emplace_back(cur->data, randEl);. Long method Deserialize I expected to see the 3 operations of Serialize() in reverse order, but somehow they are interleaved. At the moment, I can't judge whether that makes your implementation more efficient, but at least it hurts readability. Try 3 private methods in the reverse order of Serialize. count not set when deserializing In Deserialize, why is the variable called rCount instead of count? At first sight, it seemed to me that count is never set - until I find that Add() is called which increases the counter. Wrong use of capacity The loop for (; rCount <= vRandNode.capacity(); rCount++) is incorrect. After vRandNode.reserve(rCount);, the capacity of that vector may be larger than the original requested size. As a consequence, you may read more items than available in the file. [...] to a value that's greater or equal to new_cap.
{ "domain": "codereview.stackexchange", "id": 44527, "lm_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++, serialization", "url": null }
c++, serialization [...] to a value that's greater or equal to new_cap. Source: https://en.cppreference.com/w/cpp/container/vector/reserve This brings me to an important topic: Missing tests It seems that there are no unit tests for your class. Although I find unit tests quite hard to do in C++ (compared to other languages), I still think they are useful and you should look into that. Using C++ streams (as suggested before) will actually help you with testing, since you can use a string stream instead of a file stream during the test. Uniform initialization std::string temp{ "" }; can just be std::string temp;. int randNode{ 0 }; can be int randNode{}; and similar. You can also do that for ListNode: ListNode* prev{}; will use a nullptr. Missing error checks / basic exception guarantee The return value of fread() is never checked. Your code assumes that the file always has correct content. If you implement a unit test, also implement one for partial / broken files. Try to achieve at least Basic exception guarantee level. Make the loop complete Instead of rCount = 1; for (; rCount <= vRandNode.capacity(); rCount++) write for (rCount = 1; rCount <= vRandNode.capacity(); rCount++)
{ "domain": "codereview.stackexchange", "id": 44527, "lm_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++, serialization", "url": null }
c++, serialization write for (rCount = 1; rCount <= vRandNode.capacity(); rCount++) so that the for loop looks like a normal for loop. Except for capacity(), as discussed before. Use auto You already use auto a lot. This applies to the principle "almost always auto" (AAA). But you can use it more, e.g. auto node = new ListNode; instead of ListNode* node = new ListNode; ShufleRandom Shuffle is written with 2 Fs. ShuffleRandom() seems to be duplicate words for the same thing. Shuffle() is enough. Random number generation I don't know about your requirements on the distribution of the random numbers. Nor did I fully understand why that list has random pointers in the first place. The modulo approach typically doesn't give you a uniform distribution. Have a look at this Stack Overflow question to find out how to generate random numbers in a better way. gen() gives you an unsigned integer, but randNum? is a signed integer. randNum should be the same type: auto const randNum = gen() % (count + 1); I'd also like to see if (randNum == 0) { cur->rand = nullptr; } else { cur->rand = nthNode(randNum); } Const correctness The PrintListAndRand() function is const, so it seems that you're at least a bit familiar with const correctness. Seeing that, I would consider that Serialize() should also be const.
{ "domain": "codereview.stackexchange", "id": 44527, "lm_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++, serialization", "url": null }
c, event-handling, networking, unix, posix Title: Follow up: A chat server using the select() API Question: This is a follow up to my last question: Multiperson chat server using the select() API Changes: After much fine critique, I made the following changes to the code: Removed redundant casts and initializations. Moved the contents of selectserver.h to selectserver.c. Rewrote the read_line() function (Added checks for buffer overflow / DOS attack). Enabled line-buffering for the file stream instead of flushing logs each time. Replaced the FSYNC macro with a function, and moved it to log.c. Removed the exit_cleanup() function registered with atexit(). Simplified main(). Moved all the socket opening and file opening logic in separate functions. Added error-handling for time.h functions. Added a check for a file descriptor > 1024, silently closing it to guard against undefined behaviour. Review goals: Some more questions: Could any of these syscalls block? Is using blocking sockets defeating (at least partially) the point of select()? Is the overhead of continuously malloc()ing and free()ing comparable in contrast to the overhead of syscalls? Do you see a potential buffer overflow / memory leak? (Other than the FILE * valgrind reports about, though that should be eliminated as well) Does any part of my code exhibit undefined behaviour? Is there a better strategy with handling file descriptors above 1024, other than gracefully exiting or silently closing any new connections? (Eliminating the possibility of using poll() and the like) Does any part of my code require a comment? How do I avoid mixed messages? For instance: Jack (typing): hel... John (typing): nig... Jack's screen: hellnight Would it suffice to call fsync() before closing the file descriptor once, instead of calling it after every write()? How can I further improve my code? Code: log.h: #ifndef LOG_H #define LOG_H #include <stdio.h> #include <unistd.h> #include <time.h>
{ "domain": "codereview.stackexchange", "id": 44528, "lm_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, event-handling, networking, unix, posix", "url": null }
c, event-handling, networking, unix, posix Code: log.h: #ifndef LOG_H #define LOG_H #include <stdio.h> #include <unistd.h> #include <time.h> #define LOG_TIME 0x01 /* 0b00000001 */ #define LOG_DATE 0x02 /* 0b00000010 */ #define LOG_USER 0x04 /* 0b00000100 */ #define LOG_COUNT 0x08 /* 0b00001000 */ #define LOG_ALL 0xFF /* 0b11111111 */ #define LOG_FULLTIME 0x03 /* 0b00000011 */ void flush_cache (int fd); void log_msg (FILE * fp, const char *msg, unsigned int options); #endif log.c: #include "log.h" #define TS_BUF_LENGTH 30 void flush_cache (int fd) { if (fsync (fd) == -1) { perror ("fsync()"); } } void log_msg (FILE * fp, const char *msg, unsigned int flags) { static long long log_count = 0; char time_stamp[TS_BUF_LENGTH]; char date_stamp[TS_BUF_LENGTH]; time_t time_val = flags & LOG_FULLTIME ? time (0) : 0; struct tm *tm_info = flags & LOG_FULLTIME ? localtime (&time_val) : 0; if (flags & LOG_COUNT) { fprintf (fp, "%lld\n, ", ++log_count); } if (flags & LOG_DATE && strftime (date_stamp, TS_BUF_LENGTH, "%F (%a)", tm_info)) { fprintf (fp, "%s, ", date_stamp); } if (flags & LOG_TIME && strftime (time_stamp, TS_BUF_LENGTH, "%H:%M:%S", tm_info)) { fprintf (fp, "%s, ", time_stamp); } fprintf (fp, "%s\n", msg); } selectserver.c /* * selectserver.c -- a multiperson chat server */ #define _POSIX_C_SOURCE 200809L #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <errno.h> #include <signal.h> #include <unistd.h> #include <sys/time.h> #include <netdb.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/ioctl.h> #include <arpa/inet.h> #include "log.h" #define PROGRAM_NAME "selectserver" #define PORT "9808" /* Port we are listening on */ #define MAX_LOG_TEXT 2048 /* Max text lenght for logging */
{ "domain": "codereview.stackexchange", "id": 44528, "lm_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, event-handling, networking, unix, posix", "url": null }
c, event-handling, networking, unix, posix #ifdef BUFSIZ /* Max text lenght */ #define BUFSIZE BUFSIZ #else #define BUFSIZE 4096 #endif #define LOG_FILE "server.log" #define ARRAY_CARDINALITY(x) (sizeof(x) / sizeof (x)[0]) #define NI_MAXHOST 1024 #define NI_MAXSERV 35 FILE *log_fp = 0; int log_fd = 0; static void sigint_handler (int sig) { close (log_fd); signal (sig, SIG_DFL); raise (sig); } static int init_addr (struct addrinfo **servinfo) { struct addrinfo hints; memset (&hints, 0x00, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; if (getaddrinfo (0, PORT, &hints, servinfo) != 0) { perror ("getaddrinfo()"); return -1; } return 0; } static void configure_tcp (int master_fd) { int yes = 1; socklen_t size_yes = sizeof yes; if (setsockopt (master_fd, SOL_SOCKET, SO_REUSEADDR, (void *) &yes, size_yes) == -1) { perror ("setsockopt()"); } if (setsockopt (master_fd, SOL_SOCKET, SO_KEEPALIVE, (void *) &yes, size_yes) == -1) { perror ("setsockopt()"); } int keep_cnt = 9; socklen_t size_cnt = sizeof keep_cnt; if (setsockopt (master_fd, IPPROTO_TCP, TCP_KEEPCNT, (void *) &keep_cnt, size_cnt) == -1) { perror ("setsockopt()"); } int keep_idle = 25; socklen_t size_idle = sizeof keep_idle; if (setsockopt (master_fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *) &keep_idle, size_idle) == -1) { perror ("setsockopt()"); } int keep_intvl = 25; socklen_t size_intvl = sizeof keep_intvl; if (setsockopt (master_fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *) &keep_intvl, size_intvl) == -1) { perror ("setsockopt()"); } } /* Returns: -1 on failure, a listening socket descriptor otherwise. */ static int open_tcp_socket (struct addrinfo **servinfo) { int master_fd = 0; struct addrinfo *p = 0;
{ "domain": "codereview.stackexchange", "id": 44528, "lm_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, event-handling, networking, unix, posix", "url": null }
c, event-handling, networking, unix, posix for (p = *servinfo; p; p = p->ai_next) { master_fd = socket (p->ai_family, p->ai_socktype, p->ai_protocol); if (master_fd == -1) { perror ("socket()"); continue; } configure_tcp (master_fd); if (bind (master_fd, p->ai_addr, p->ai_addrlen) == -1) { close (master_fd); perror ("bind()"); continue; } break; } if (!p) { fprintf (stderr, "%s: Failed to setup a socket.\n", PROGRAM_NAME); return -1; } if (listen (master_fd, SOMAXCONN) == -1) { perror ("listen()"); close (master_fd); return -1; } return master_fd; } static void get_slave_addr (int slave_fd, char *ip_str, int *port) { struct sockaddr_storage addr; socklen_t addr_len = sizeof addr; if ((getpeername (slave_fd, (struct sockaddr *) &addr, &addr_len)) == -1) { perror ("getpeername"); } /* Deal with both IPv4 and IPv6 */ if (addr.ss_family == AF_INET) { struct sockaddr_in *s = (struct sockaddr_in *) &addr; *port = ntohs (s->sin_port); if (!inet_ntop (AF_INET, &s->sin_addr, ip_str, INET_ADDRSTRLEN)) { perror ("inet_ntop()"); } } else { struct sockaddr_in6 *s = (struct sockaddr_in6 *) &addr; *port = ntohs (s->sin6_port); if (!inet_ntop (AF_INET6, &s->sin6_addr, ip_str, INET6_ADDRSTRLEN)) { perror ("inet_ntop()"); } } } static void write_slave_info (int slave_fd) { struct sockaddr_in slave_addr; socklen_t addr_len = sizeof slave_addr; char slave_ip[INET6_ADDRSTRLEN] = { 0 }; char local_ip[INET6_ADDRSTRLEN] = { 0 }; int port = 0; get_slave_addr (slave_fd, slave_ip, &port); if (getsockname (slave_fd, (struct sockaddr *) &slave_addr, &addr_len) == -1) { perror ("getsockname()"); }
{ "domain": "codereview.stackexchange", "id": 44528, "lm_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, event-handling, networking, unix, posix", "url": null }
c, event-handling, networking, unix, posix if (!inet_ntop (AF_INET, (const void *) &slave_addr, local_ip, sizeof local_ip)) { perror ("inet_ntop()"); } char host[NI_MAXHOST] = { 0 }; char service[NI_MAXSERV] = { 0 }; int ret_val = 0; if ((ret_val = getnameinfo ((struct sockaddr *) &slave_addr, addr_len, host, sizeof host, service, sizeof service, 0)) != 0) { fprintf (stderr, "%s: getnameinfo: %s\n", PROGRAM_NAME, gai_strerror (ret_val)); } char log_txt[MAX_LOG_TEXT] = { 0 }; snprintf (log_txt, sizeof log_txt, "INFO: New connection from FOREIGN IP ADDRESS:%s, HOST:%s, SERVICE:%s,\n\t\t\t\t LOCAL IP ADDRESS:%s, PORT:%d on socket %d.", slave_ip, host, service, local_ip, port, slave_fd); log_msg (stderr, log_txt, LOG_FULLTIME); log_msg (log_fp, log_txt, LOG_FULLTIME); flush_cache (log_fd); } /* Returns: The slave file descriptor on success, -1 otherwise. */ static int accept_new_connection (int master_fd) { int slave_fd = 0; struct sockaddr slave_addr = { 0 }; socklen_t addr_len = sizeof slave_addr; do { slave_fd = accept (master_fd, &slave_addr, &addr_len); } while ((slave_fd == -1) && (errno == EINTR)); if (slave_fd == -1) { perror ("accept()"); return -1; } write_slave_info (slave_fd); return slave_fd; } static void write_farewell (int slave_fd) { char log_txt[MAX_LOG_TEXT] = { 0 }; snprintf (log_txt, sizeof log_txt, "INFO: Socket %d hung up.\n", slave_fd); log_msg (stderr, log_txt, LOG_FULLTIME); log_msg (log_fp, log_txt, LOG_FULLTIME); flush_cache (log_fd); } /* Synopsis: Get the number of bytes that are immediately available for * reading. * Returns: -1 on failure, number of bytes available elsewise. */ static int get_bytes (int slave_fd) { int flag = 0;
{ "domain": "codereview.stackexchange", "id": 44528, "lm_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, event-handling, networking, unix, posix", "url": null }
c, event-handling, networking, unix, posix if (ioctl (slave_fd, FIONREAD, &flag) == -1) { perror ("ioctl()"); return -1; } return flag; } /* Synopsis: Calls recv() in a loop to read as much as available. * * Returns: 0 on allocation failure, storing 0 in status, a pointer to the line elsewise. * Stores -1 in status in case of a closed connection * or a recv() error. * * Remarks: The caller is responsible for freeing the returned * memory (in case of success), else we risk exhaustion. */ static char *get_response (size_t *nbytes, int slave_fd, int *status) { static const size_t page_size = BUFSIZE; char *buf = 0; int flag = 0; ssize_t ret_val = 0; size_t total = 0; do { if (total > (BUFSIZE * 10)) { /* Likely a DOS attack */ free (buf); *status = -1; return 0; } char *new = realloc (buf, total + page_size); if (!new) { perror ("realloc()"); status = 0; return 0; } buf = new; new = 0; ret_val = recv (slave_fd, buf + total, page_size - 1, 0); if (ret_val > 0) { total += (size_t) ret_val; buf[ret_val] = '\0'; flag = get_bytes (slave_fd); if (flag == -1) { free (buf); *status = -1; return 0; } } else { flag = 0; } } while (flag > 0); if (ret_val <= 0) { if (ret_val == 0) { write_farewell (slave_fd); } free (buf); *status = -1; return 0; } *nbytes = total; return buf; }
{ "domain": "codereview.stackexchange", "id": 44528, "lm_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, event-handling, networking, unix, posix", "url": null }
c, event-handling, networking, unix, posix /* Synopsis: Calls send() in a loop to ensure that all data is sent. * Stores the number of bytes sent in len. * Returns: 0 on success, -1 otherwise. */ static int send_all (int slave_fd, const char *line, size_t *len) { size_t total = 0; size_t bytes_left = *len; ssize_t status = 0; while (total < *len) { status = send (slave_fd, line + total, bytes_left, MSG_NOSIGNAL); if ((status == -1) && (errno == EINTR)) { /* A send() error */ continue; } if (status == -1) { break; } total += (size_t) status; bytes_left -= (size_t) status; } *len = total; return status == -1 ? -1 : 0; } static void send_msg (size_t nbytes, const char *line, int sender_fd, int master_fd, fd_set master, int fd_max) { for (int i = 0; i <= fd_max; i++) { /* Send it to everyone */ if (FD_ISSET (i, &master)) { /* Excluding the master and sender */ if (i != master_fd && i != sender_fd) { size_t len = nbytes; int status = send_all (i, line, &len); if (status == -1) { perror ("send()"); } else if (len != nbytes) { fprintf (stderr, "%s: We only sent %ld bytes because of a send() error.\n", PROGRAM_NAME, len); } } } } } /* Synopsis: Calls select and handles new connections. * Returns: -1 on failure to init select or ENOMEM, 0 otherwise. */ static int handle_connections (int master_fd) { fd_set master; /* Master file descriptor list */ fd_set read_fds; /* Temp file descriptor list for select() */ int fd_max = 0; /* Max descriptor seen so far */ FD_ZERO (&master); FD_ZERO (&read_fds); FD_SET (master_fd, &master); fd_max = master_fd;
{ "domain": "codereview.stackexchange", "id": 44528, "lm_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, event-handling, networking, unix, posix", "url": null }
c, event-handling, networking, unix, posix FD_SET (master_fd, &master); fd_max = master_fd; for (;;) { /* Because select is destructive */ read_fds = master; if (select (fd_max + 1, &read_fds, 0, 0, 0) == -1) { if (errno == EINTR) { continue; } perror ("select()"); return -1; } /* Iterate through the existing connections looking for data to read */ for (int i = 0; i <= fd_max; i++) { /* We have a connection */ if (FD_ISSET (i, &read_fds)) { /* It's the master */ if (i == master_fd) { int slave_fd = 0; if ((slave_fd = accept_new_connection (master_fd)) != -1) { if (slave_fd < 1023) { FD_SET (slave_fd, &master); } else { close (slave_fd); continue; } } if (slave_fd > fd_max) { fd_max = slave_fd; } } /* We have data to read */ else { size_t nbytes = 0; int status = 0; char *line = get_response (&nbytes, i, &status); /* A read error, or the slave closed connection */ if (!line && !status) { return -1; /* ENOMEM */ } else if (status == -1) { FD_CLR (i, &master); close (i); } else { send_msg (nbytes, line, i, master_fd, master, fd_max); free (line); } } } } } return 0; }
{ "domain": "codereview.stackexchange", "id": 44528, "lm_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, event-handling, networking, unix, posix", "url": null }
c, event-handling, networking, unix, posix /* Returns: the master_fd on success, -1 otherwise. */ static int setup_server (void) { struct addrinfo *servinfo; int master_fd = 0; if (init_addr (&servinfo) == -1) { return -1; } if ((master_fd = open_tcp_socket (&servinfo)) == -1) { freeaddrinfo (servinfo); return -1; } freeaddrinfo (servinfo); return master_fd; } /* Returns: -1 on failure, 0 elsewise. */ static int open_logfile (void) { log_fp = fopen (LOG_FILE, "a"); if (!log_fp) { perror ("fopen()"); return -1; } /* Be less efficient here, to solve a problem more important * than mere efficiency */ if (setvbuf (log_fp, 0, _IOLBF, 0)) { perror ("setvbuf()"); fclose (log_fp); return -1; } log_fd = fileno (log_fp); if (log_fd == -1) { perror ("fileno()"); fclose (log_fp); return -1; } return 0; } int main (void) { static sigset_t caught_signals; sigemptyset (&caught_signals); static int const sig[] = { SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM, }; const size_t nsigs = ARRAY_CARDINALITY (sig); struct sigaction act; for (size_t i = 0; i < nsigs; i++) { if (sigaction (sig[i], 0, &act) == -1) { perror ("sigaction()"); return EXIT_FAILURE; } if (act.sa_handler != SIG_IGN) { sigaddset (&caught_signals, sig[i]); } } act.sa_handler = sigint_handler; act.sa_mask = caught_signals; act.sa_flags = 0; for (size_t i = 0; i < nsigs; i++) { if (sigismember (&caught_signals, sig[i])) { if (sigaction (sig[i], &act, 0) == -1) { perror ("sigaction()"); return EXIT_FAILURE; } } } if (open_logfile () == -1) { return EXIT_FAILURE; } int master_fd = 0;
{ "domain": "codereview.stackexchange", "id": 44528, "lm_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, event-handling, networking, unix, posix", "url": null }
c, event-handling, networking, unix, posix if ((master_fd = setup_server ()) == -1) { return EXIT_FAILURE; } /* Wait for and eventually handle a new connection */ printf ("\nListening for connections on port %s.\n", PORT); if (handle_connections (master_fd) == -1) { close (master_fd); return EXIT_FAILURE; } close (master_fd); return EXIT_SUCCESS; } Dynamic analysis: ==387== Memcheck, a memory error detector ==387== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al. ==387== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info ==387== Command: ./selectserver ==387== Parent PID: 325 ==387== ==387== error calling PR_SET_PTRACER, vgdb might block ==387== ==387== Process terminating with default action of signal 2 (SIGINT) ==387== at 0x497FF7A: select (select.c:41) ==387== by 0x10A4FE: handle_connections (selectserver.c:372) ==387== by 0x10AB96: main (selectserver.c:504) ==387== ==387== HEAP SUMMARY: ==387== in use at exit: 472 bytes in 1 blocks ==387== total heap usage: 111 allocs, 110 frees, 56,793 bytes allocated ==387== ==387== 472 bytes in 1 blocks are still reachable in loss record 1 of 1 ==387== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so) ==387== by 0x48ED92D: __fopen_internal (iofopen.c:65) ==387== by 0x48ED92D: fopen@@GLIBC_2.2.5 (iofopen.c:86) ==387== by 0x10A884: open_logfile (selectserver.c:444) ==387== by 0x10AB40: main (selectserver.c:494) ==387== ==387== LEAK SUMMARY: ==387== definitely lost: 0 bytes in 0 blocks ==387== indirectly lost: 0 bytes in 0 blocks ==387== possibly lost: 0 bytes in 0 blocks ==387== still reachable: 472 bytes in 1 blocks ==387== suppressed: 0 bytes in 0 blocks ==387== ==387== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) Edit: fixed typo. Answer: Answers to the remaining 8 questions Could any of these syscalls block?
{ "domain": "codereview.stackexchange", "id": 44528, "lm_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, event-handling, networking, unix, posix", "url": null }
c, event-handling, networking, unix, posix Edit: fixed typo. Answer: Answers to the remaining 8 questions Could any of these syscalls block? That's an excellent question to ask for a program like this. There are lots of system calls in your code that can block, apart from select() of course which is intended to block. To name a few: printf(), fprintf() and perror(): even output to stdio or stderr can block. You might consider ignoring that though, by the time this blocks you might have bigger problems. fsync(): this actually does more than just flushing the stream buffer, it also waits until the data is guaranteed to be on the disk. This might take a significant amount of time, especially on a mechanical hard drive. getnameinfo(): this will do a DNS lookup which can take an arbitrary amount of time. Consider whether you need to have a symbolic hostname at all, or whether just the address in numeric form is good enough. You can get the latter by passing AI_NUMERICHOST | AI_NUMERICSERV for the last parameter. send(): this can easily block, consider for example that one of the peers might not be responding (maybe their network is down, someone paused the chat program, or any other number of reasons). Do you want to wait for that one peer and hold up passing the message to the remaining peers? To make this non-blocking, either set O_NONBLOCK on the socket, or pass MSG_DONTWAIT as a flag to send(). recv(): obviously this blocks by default. But you might think you are safe, because you are using select(). However, if you read the manpage for select(), you'll notice it mentions that it can spuriously report that a filedescriptor is ready for reading, when in fact it isn't. It is safer to set the O_NONBLOCK flag on the socket, or pass MSG_DONTWAIT to recv(). Is using blocking sockets defeating (at least partially) the point of select()?
{ "domain": "codereview.stackexchange", "id": 44528, "lm_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, event-handling, networking, unix, posix", "url": null }
c, event-handling, networking, unix, posix Is using blocking sockets defeating (at least partially) the point of select()? There might be reasons why you want the sockets to be blocking. For example, in a congested network, you might just want to let things wait and slow down until messages can be sent, instead of returning an error early. Is the overhead of continuously malloc()ing and free()ing comparable in contrast to the overhead of syscalls? malloc() and free() can cause system calls to happen as well. However, I would not worry about it too much: even if it does, you have at least as many calls to recv() as you have to realloc(), so you were paying for system calls anyway. If you believe it is a problem, consider using a profiling tool to find out where your program spends most of its CPU cycles. If it is in realloc(), you can consider finding ways to avoid allocating memory all the time, for example by keeping a pool of allocated memory around, and returning buf to that pool when it's no longer being used. Do you see a potential buffer overflow / memory leak? (Other than the FILE * valgrind reports about, though that should be eliminated as well) Yes. If realloc() fails after the first iteration of the do…while loop, you forget to free(buf). In handle_connections(), I also see two potential paths where line isn't freed: if !line but status != 0, and if status == -1. As you can see, Valgrind doesn't catch those errors if those error paths are never exercised when running the program. Consider using static analysis tools like cppcheck, Clang's static analyzer and/or GCC's static analyzer. These can find bugs by analyzing all the possible paths through a program without having to actually run it. Note that even those cannot guarantee they find every possible bug. Is there a better strategy with handling file descriptors above 1024, other than gracefully exiting or silently closing any new connections? (Eliminating the possibility of using poll() and the like)
{ "domain": "codereview.stackexchange", "id": 44528, "lm_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, event-handling, networking, unix, posix", "url": null }