text
stringlengths
1
2.12k
source
dict
c++, collections, c++17, circular-list, constant-expression template <class InputIterator> void insert_back(InputIterator first, InputIterator last) { size_t num = static_cast<size_t>(std::distance(first, last)); if (will_remain_linearized(num)) { std::uninitialized_copy(first, last, &write_ptr()); write_pos += num; } else std::copy(first, last, std::back_inserter(*this)); } /* add at the front of the buffer */ void push_front_without_checks(const value_type& value) { emplace_front_without_checks(value); } void push_front_without_checks(value_type&& value) { emplace_front_without_checks(value); } bool try_push_front(const value_type& value) { return try_emplace_front(value); } bool try_push_front(value_type&& value) { return try_emplace_front(value); } void push_front(const value_type& value) { emplace_front(value); } void push_front(value_type&& value) { emplace_front(value); } template <class ... Args> void emplace_front_without_checks(Args&& ... args) { --read_pos; new (&read_ptr()) T(std::forward<Args>(args)...); } template <class ... Args> bool try_emplace_front(Args&& ... args) { if (full()) return false; emplace_front_without_checks(std::forward<Args>(args)...); } template <class ... Args> void emplace_front(Args&& ... args) { if (full()) pop_back(); emplace_front_without_checks(std::forward<Args>(args)...); }
{ "domain": "codereview.stackexchange", "id": 45239, "lm_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++, collections, c++17, circular-list, constant-expression", "url": null }
c++, collections, c++17, circular-list, constant-expression template <class InputIterator> void insert_front(InputIterator first, InputIterator last) { std::copy(first, last, std::front_inserter(*this)); } /* extraction methods */ /* extract from the front of the buffer used with back insertion to make a FIFO queue */ void pop_front(value_type& value) { auto& elem = read_ptr(); value = std::move(elem); elem.~T(); ++read_pos; } bool try_pop_front(value_type& value) { if (empty()) return false; pop_front(value); return true; } void pop_front() { read_ptr().~T(); ++read_pos; } bool try_pop_front() { if (empty()) return false; pop_front(); return true; } // dumps num of first elements into dest where dest points to initialized memory template <class OutputIterator> void pop_front(OutputIterator dest, size_t num) { move_from_front(dest, num); if constexpr (std::is_pod_v<value_type>) read_pos += num; else { while (num--) pop_front(); } } // dumps num of first elements into dest where dest points to uninitialized memory template <class OutputIterator> void pop_front(OutputIterator dest, size_t num, no_init_t) { move_from_front(dest, num, no_init); if constexpr (std::is_pod_v<value_type>) read_pos += num; else { while (num--) pop_front(); } }
{ "domain": "codereview.stackexchange", "id": 45239, "lm_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++, collections, c++17, circular-list, constant-expression", "url": null }
c++, collections, c++17, circular-list, constant-expression template <class OutputIterator> bool try_pop_front(OutputIterator dest, size_t num) { if (num > size()) return false; pop_front(dest, num); return true; } template <class OutputIterator> bool try_pop_front(OutputIterator dest, size_t num, no_init_t) { if (num > size()) return false; pop_front(dest, num, no_init); return true; } /* extract from the back of the buffer used with back insertion to make a LIFO queue */ void pop_back(value_type& value) { --write_pos; auto& elem = write_ptr(); value = std::move(elem); elem.~T(); } bool try_pop_back(value_type& value) { if (empty()) return false; pop_back(value); return true; } void pop_back() { --write_pos; write_ptr().~T(); } bool try_pop_back() { if (empty()) return false; pop_back(); return true; } template <class OutputIterator> void pop_back(OutputIterator dest, size_t num) { move_from_back(dest, num); if constexpr (std::is_pod_v<value_type>) write_pos -= num; else { while (num--) pop_back(); } } template <class OutputIterator> void pop_back(OutputIterator dest, size_t num, no_init_t) { move_from_back(dest, num, no_init); if constexpr (std::is_pod_v<value_type>) write_pos -= num; else { while (num--) pop_back(); } }
{ "domain": "codereview.stackexchange", "id": 45239, "lm_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++, collections, c++17, circular-list, constant-expression", "url": null }
c++, collections, c++17, circular-list, constant-expression template <class OutputIterator> bool try_pop_back(OutputIterator dest, size_t num) { if (size() < num) return false; pop_back(dest, num); return true; } template <class OutputIterator> bool try_pop_back(OutputIterator dest, size_t num, no_init_t) { if (size() < num) return false; pop_back(dest, num, no_init); return true; } /* accesors */ reference front() { return read_ptr(); } reference back() { auto pos = write_pos; --pos; return raw_buffer[pos.as_index(N)]; } const_reference front() const { return read_ptr(); } const_reference back() const { auto pos = write_pos; --pos; return raw_buffer[pos.as_index(N)]; } reference operator[](size_type pos) noexcept { auto index = read_pos + pos; return raw_buffer[index.as_index(N)]; } const_reference operator[](size_type pos) const noexcept { auto index = read_pos + pos; return raw_buffer[index.as_index(N)]; } /* ^ ==> read pointer > ==> write pointer data starts from read pointer to write pointer 1 - linearized (from empty to full) : there is one array starting from read pointer to write pointer -------------------------------------------------------------------------- | ^ | 1 | 2 | 3 | 4 | 5 | > | | | | | | | | | | | | | | | | --------------------------------------------------------------------------
{ "domain": "codereview.stackexchange", "id": 45239, "lm_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++, collections, c++17, circular-list, constant-expression", "url": null }
c++, collections, c++17, circular-list, constant-expression 2 - not linearized : the first array is from read pointer until the end of the buffer (last index N-1) the second array is from the start of the buffer until the write pointer -------------------------------------------------------------------------------------- | 6 | 7 | 8 | > | | | | | | | | | | | | | | | | ^ | 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------------- */ std::span<value_type> array_one() noexcept { pointer read_pointer = &read_ptr(); if (is_linearized()) // or empty return std::span<value_type>{read_pointer, read_pointer + size()}; else return std::span<value_type>{read_pointer, raw_buffer.ptr() - read_pointer + size()}; } std::span<const value_type> array_one() const noexcept { pointer read_pointer = &read_ptr(); if (is_linearized()) // or empty return std::span<const value_type>{read_pointer, read_pointer + size()}; else return std::span<const value_type>{read_pointer, raw_buffer.ptr() - read_pointer + size()}; } std::span<value_type> array_two() noexcept { if (is_linearized()) return {}; else { return std::span<value_type>{raw_buffer.ptr(), &write_ptr()}; } } std::span<const value_type> array_two() const noexcept { if (is_linearized()) return {}; else { return std::span<const value_type>{raw_buffer.ptr(), &write_ptr()}; } } void copy_from_front(value_type& value) const { value = front(); }
{ "domain": "codereview.stackexchange", "id": 45239, "lm_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++, collections, c++17, circular-list, constant-expression", "url": null }
c++, collections, c++17, circular-list, constant-expression value_type copy_from_front() const { value_type value; copy_from_front(value); return value; } void move_from_front(value_type& value) { value = std::move(front()); } value_type move_from_front() { value_type value; move_from_front(value); return value; } template <class OutputIterator> void copy_from_front(OutputIterator dest, size_t num) const { if (is_linearized()) { pointer begin_iter = &read_ptr(); pointer end_iter = begin_iter + num; std::copy(begin_iter, end_iter, dest); } else { auto begin_iter = begin(); auto end_iter = begin_iter + num; std::copy(begin_iter, end_iter, dest); } } template <class OutputIterator> void copy_from_front(OutputIterator dest, size_t num, no_init_t) const { if (is_linearized()) { pointer begin_iter = &read_ptr(); pointer end_iter = begin_iter + num; std::uninitialized_copy(begin_iter, end_iter, dest); } else { auto begin_iter = begin(); auto end_iter = begin_iter + num; std::uninitialized_copy(begin_iter, end_iter, dest); } }
{ "domain": "codereview.stackexchange", "id": 45239, "lm_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++, collections, c++17, circular-list, constant-expression", "url": null }
c++, collections, c++17, circular-list, constant-expression template <class OutputIterator> void move_from_front(OutputIterator dest, size_t num) { if (is_linearized()) { pointer begin_iter = &read_ptr(); pointer end_iter = begin_iter + num; std::copy(std::make_move_iterator(begin_iter), std::make_move_iterator(end_iter), dest); } else { auto begin_iter = begin(); auto end_iter = begin_iter + num; std::copy(std::make_move_iterator(begin_iter), std::make_move_iterator(end_iter), dest); } } template <class OutputIterator> void move_from_front(OutputIterator dest, size_t num, no_init_t) { if (is_linearized()) { pointer begin_iter = &read_ptr(); pointer end_iter = begin_iter + num; std::uninitialized_move(begin_iter, end_iter, dest); } else { auto begin_iter = begin(); auto end_iter = begin_iter + num; std::uninitialized_move(begin_iter, end_iter, dest); } } void copy_from_back(value_type& value) const { value = back(); } value_type copy_from_back() const { value_type value; copy_from_back(value); return value; } void move_from_back(value_type& value) { value = std::move(back()); } value_type move_from_back() { value_type value; move_from_back(value); return value; }
{ "domain": "codereview.stackexchange", "id": 45239, "lm_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++, collections, c++17, circular-list, constant-expression", "url": null }
c++, collections, c++17, circular-list, constant-expression template <class OutputIterator> void copy_from_back(OutputIterator dest, size_t num) const { if (is_linearized()) { pointer end_iter = &write_ptr(); pointer first = end_iter - num; std::copy(first, end_iter, dest); } else { auto end_iter = end(); auto first = end_iter - num; std::copy(first, end_iter, dest); } } template <class OutputIterator> void copy_from_back(OutputIterator dest, size_t num, no_init_t) const { if (is_linearized()) { pointer end_iter = &write_ptr(); pointer first = end_iter - num; std::uninitialized_copy(first, end_iter, dest); } else { auto end_iter = end(); auto first = end_iter - num; std::uninitialized_copy(first, end_iter, dest); } } template <class OutputIterator> void move_from_back(OutputIterator dest, size_t num) { if (is_linearized()) { pointer end_iter = &write_ptr(); pointer first = end_iter - num; std::copy(std::make_move_iterator(first), std::make_move_iterator(end_iter), dest); } else { auto end_iter = end(); auto first = end_iter - num; std::copy(std::make_move_iterator(first), std::make_move_iterator(end_iter), dest); } }
{ "domain": "codereview.stackexchange", "id": 45239, "lm_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++, collections, c++17, circular-list, constant-expression", "url": null }
c++, collections, c++17, circular-list, constant-expression template <class OutputIterator> void move_from_back(OutputIterator dest, size_t num, no_init_t) { if (is_linearized()) { pointer end_iter = &write_ptr(); pointer first = end_iter - num; std::uninitialized_move(first, end_iter, dest); } else { auto end_iter = end(); auto first = end_iter - num; std::uninitialized_move(first, end_iter, dest); } } /* range methods */ iterator begin() noexcept { return iterator{raw_buffer.ptr(), read_pos, N}; } iterator end() noexcept { return iterator{raw_buffer.ptr(), write_pos, N}; } const_iterator begin() const noexcept { return const_iterator{raw_buffer.ptr(), read_pos, N}; } const_iterator end() const noexcept { return const_iterator{raw_buffer.ptr(), write_pos, N}; } const_iterator cbegin() const noexcept { return begin(); } const_iterator cend() const noexcept { return end(); } reverse_iterator rbegin() noexcept { return reverse_iterator{ raw_buffer.ptr(), write_pos - 1, N }; } reverse_iterator rend() noexcept { return reverse_iterator{ raw_buffer.ptr(), read_pos - 1, N }; } const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator{ raw_buffer.ptr(), write_pos - 1, N }; } const_reverse_iterator rend() const noexcept { return const_reverse_iterator{ raw_buffer.ptr(), read_pos - 1, N }; } const_reverse_iterator crbegin() const noexcept { return rbegin(); } const_reverse_iterator crend() const noexcept { return rend(); } /* eraser, linearization, resize and some info */
{ "domain": "codereview.stackexchange", "id": 45239, "lm_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++, collections, c++17, circular-list, constant-expression", "url": null }
c++, collections, c++17, circular-list, constant-expression /* eraser, linearization, resize and some info */ void clear() { if constexpr (std::is_pod_v<value_type>) { read_pos.reset(); write_pos.reset(); } else { while (!empty()) pop_front(); } } pointer linearize() { ring_buffer rbf(N); auto first_array = array_one(); rbf.insert_back(std::make_move_iterator(first_array.begin()), std::make_move_iterator(first_array.end())); auto second_array = array_two(); rbf.insert_back(std::make_move_iterator(second_array.begin()), std::make_move_iterator(second_array.end())); this->operator=(std::move(rbf)); return raw_buffer.ptr(); } template <class OutputIterator> void linearize(OutputIterator dest) const { auto first_array = array_one(); std::copy(first_array.begin(), first_array.end(), dest); auto second_array = array_two(); std::copy(second_array.begin(), second_array.end(), dest + first_array.size()); } void set_capacity(size_type Num) { clear(); N = Num; raw_buffer.resize(Num); } size_t capacity() const noexcept { return N; } size_t size() const noexcept { return write_pos - read_pos; } size_t available_size() const noexcept { return capacity() - size(); } size_t reserve() const noexcept { return available_size(); } bool full() const noexcept { return size() == capacity(); } bool empty() const noexcept { return !size(); } bool is_linearized() const noexcept { ring_buffer_index last_pos = write_pos - 1; return last_pos.as_index(N) >= read_pos.as_index(N); }
{ "domain": "codereview.stackexchange", "id": 45239, "lm_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++, collections, c++17, circular-list, constant-expression", "url": null }
c++, collections, c++17, circular-list, constant-expression /* aliases to use the ring buffer as FIFO */ template <class ...Args> void emplace(Args&& ... args) { emplace_back(std::forward<Args>(args)...); } void push(const value_type& value) { push_back(value); } void push(value_type&& value) { push_back(std::move(value)); } template <class InputIterator> void insert(InputIterator first, InputIterator last) { insert_back(first, last); } void pop(value_type& value) { pop_front(value); } bool try_pop(value_type& value) { return try_pop_front(value); } void pop() { pop_front(); } bool try_pop() { return try_pop_front(); } template <class OutputIt> void pop(OutputIt dest, size_t num) { pop_front(dest, num); } template <class OutputIt> void pop(OutputIt dest, size_t num, no_init_t) { pop_front(dest, num, no_init); } template <class OutputIt> bool try_pop(OutputIt dest, size_t num) { return try_pop_front(dest, num); } template <class OutputIt> bool try_pop(OutputIt dest, size_t num, no_init_t) { return try_pop_front(dest, num, no_init); } }; The span.h header can be found here. I found it somewhere on the internet since some months ago, but I can't recall where did I get it from and as said in the title it's an implementation for the new C++ 20 span which represents a view for a range of contiguous memory, like string_view, but it enables to non const access the values if it isn't const. I want to know:
{ "domain": "codereview.stackexchange", "id": 45239, "lm_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++, collections, c++17, circular-list, constant-expression", "url": null }
c++, collections, c++17, circular-list, constant-expression Does the implementation misuse the concept of ring buffer? Do the iterators satisfy the C++ concept of iterators? Is there any drawbacks of using the indexes as counters and obtaining the real indexes with modulus especially for bigger values? Answer: After some searching I found that my ring buffer is broken if its capacity isn't power of 2, because once the counter reaches its maximum (on 64-bit : 2^64 - 1) it will begin from zero the next increment so if the modulus of the counter by n isn't n-1 when it reaches the maximum unsigned integer of the architecture then the counter will misbehave because at the next step the remainder (index) will be 0 while the previous remainder (index) isn't n - 1 this illustrates the problem : constexpr uint64_t rem1 = std::numeric_limits<uint64_t>::max() % 13; cout << "rem1 = " << rem1 << endl; // rem1 = 2 constexpr uint64_t rem2 = (std::numeric_limits<uint64_t>::max() + 1) % 13; // std::numeric_limits<uint64_t>::max() + 1 = 0 cout << "rem2 = " << rem2 << endl; // rem2 = 0 not 3 ! but for number n equals power of two the remainder will be n -1 at maximum value so no problem here
{ "domain": "codereview.stackexchange", "id": 45239, "lm_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++, collections, c++17, circular-list, constant-expression", "url": null }
python Title: Clock markings refactoring for enhancement opportunities Question: The given Python code snippet is for drawing clock markings. from waffle_oak_clock import markings_number, markings_radius, markings_hours_size, markings_hours_color, markings_minutes_size, markings_minutes_color, clock def draw_markings() -> None: ''' Draws the markings of the clock ''' for i in range(markings_number): angle = radians(i * 360 / markings_number) x = markings_radius * sin(angle) y = -markings_radius * cos(angle) if i % 5 == 0: # Larger dot for hours clock.penup() clock.goto(x, y) clock.dot(markings_hours_size, markings_hours_color) elif i % 1 == 0: # Smaller dot for minutes clock.penup() clock.goto(x, y) clock.dot(markings_minutes_size, markings_minutes_color) Are there opportunities for refactoring draw_markings() to enhance code readability and function? This is the current, updated code: from math import sin, cos def main( markings_radius: int = 220, markings_number: int = 60, markings_hours_color: str = "blue", markings_hours_size: int = 10, markings_minutes_color: str = "green", markings_minutes_size: int = 5, ): # Create a turtle to draw the markings clock = RawTurtle(screen) clock.speed(100) def draw_markings() -> None: """Draws the markings of the clock.""" for minute in range(markings_number): angle = radians(minute * 360 / markings_number) x = markings_radius * sin(angle) y = -markings_radius * cos(angle) clock.penup() clock.goto(x, y) if minute % 5 == 0: clock.dot(markings_hours_size, markings_hours_color) else: clock.dot(markings_minutes_size, markings_minutes_color) This is the main app
{ "domain": "codereview.stackexchange", "id": 45240, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python This is the main app Answer: Wow, that's a lot of imported symbols at the module level. I guess it works for you. You might consider defining a class, so these become self.foo object attributes plus some class constants. The clock, in particular, worries me. draw_markings() side effects it. Good manners suggests we should list it in the signature as an input parameter, so the Gentle Reader has a heads up that it will be pretty important during this function call. Lots of module-level symbols can be a good thing, but I worry that with too many it starts to encounter the coupling issues of global variables. if i % 5 == 0: Either this runs exactly once, or there was an indentation copy-n-paste error when submitting the source text to Code Review. elif i % 1 == 0: No, please don't say elif True:, prefer the simpler else: Note that every single integer is congruent to zero mod one. We see some repeated penup + goto code, hardly the end of the world. Consider defaulting size, color to the "minutes" settings, conditionally changing them to "hours" if we're on a multiple of five, and then you're set up for a single dot call. Often for i ... is the appropriate loop index identifier. But here it's really representing the minute, so that would have been a better name to choose.
{ "domain": "codereview.stackexchange", "id": 45240, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
c, image, signal-processing Title: Image Processing Application in C Question: I'm making a image processing application in c from scratch using P6 ppm images, I want some input on my code before I start adding more features to prevent it from falling apart if it's not well structured sample output improc.h #ifndef IMPROC_H #define IMPROC_H #include <stdint.h> typedef struct { int size; double *weights; } Kernel; typedef struct { uint8_t r; uint8_t g; uint8_t b; } Pixel; typedef struct { double r; double g; double b; } Accumulator; typedef struct { int height; int width; Pixel *pixels; } Image; typedef struct { double re; double im; } Complex; Image *create_image(int width, int height); void free_image(Image *image); Image *load_image(char *filename); int save_image(char *filename, Image image); Image *grayscale(Image image); Image *perceptual_grayscale(Image image); double kernel_min(Kernel kernel); double kernel_max(Kernel kernel); Accumulator convolve(Image image, Kernel kernel, int row, int col); Image *apply_kernel(Image image, Kernel kernel); Image *sobel(Image image); Kernel sobel_y(int n); Kernel sobel_x(int n); unsigned modulo(int value, unsigned m); #endif
{ "domain": "codereview.stackexchange", "id": 45241, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, image, signal-processing", "url": null }
c, image, signal-processing improc.c #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <math.h> #include <unistd.h> #include <errno.h> #include "improc.h" Image *create_image(int width, int height) { Image *image = malloc(sizeof(Image)); if (image == NULL) { fprintf(stderr, "Could not allocate memory to Image: %s\n", strerror(errno)); return NULL; } image->width = width; image->height = height; image->pixels = malloc(width*height*sizeof(Pixel)); if (image->pixels == NULL) { free(image); fprintf(stderr, "Could not allocate memory to pixels: %s\n", strerror(errno)); return NULL; } return image; } void free_image(Image *image) { if (image != NULL) { if (image->pixels != NULL) free(image->pixels); free(image); } } Image *load_image(char *filename) { char magic[3]; int maxval, width, height; FILE *fp = fopen(filename, "rb"); if (fp == NULL) { fprintf(stderr, "Error opening file: %s\n", strerror(errno)); return NULL; } fscanf(fp, "%2s", magic); if (magic[0] != 'P' || magic[1] != '6') { fprintf(stderr, "Not a valid P6 ppm file: %s\n", strerror(errno)); fclose(fp); return NULL; } fscanf(fp, "%d%d%*c", &width, &height); Image *image = create_image(width, height); fscanf(fp, "%d%*c", &maxval); fread(image->pixels, sizeof(Pixel),image->width*image->height, fp); fclose(fp); return image; } int save_image(char *filename, Image image) { FILE *fp = fopen(filename, "wb"); if (fp == NULL) { fprintf(stderr, "Error opening file: %s\n", strerror(errno)); return -1; } fprintf(fp, "P6\n%d %d\n255\n", image.width, image.height); fwrite(image.pixels, sizeof(Pixel), image.width*image.height, fp); fclose(fp); return 0; } Image *grayscale(Image image) { Image *gray = create_image(image.width, image.height); Pixel pix;
{ "domain": "codereview.stackexchange", "id": 45241, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, image, signal-processing", "url": null }
c, image, signal-processing { Image *gray = create_image(image.width, image.height); Pixel pix; int index; uint8_t avg; for (int row = 0; row < image.height; row++) { for (int col = 0; col < image.width; col++) { index = row*image.width + col; pix = image.pixels[index]; avg = (uint8_t) ((pix.r + pix.g + pix.b)/3.0); gray->pixels[index] = (Pixel) {avg, avg, avg}; } } return gray; } Image *perceptual_grayscale(Image image) { Image *gray = create_image(image.width, image.height); Pixel pix; uint8_t bt_601; int index; for (int row = 0; row < image.height; row++) { for (int col = 0; col < image.width; col++) { index = row*image.width + col; pix = image.pixels[index]; bt_601 = (uint8_t) (0.2126*pix.r + 0.7152*pix.g + 0.0722*pix.b); gray->pixels[index] = (Pixel) {bt_601, bt_601, bt_601}; } } return gray; }
{ "domain": "codereview.stackexchange", "id": 45241, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, image, signal-processing", "url": null }
c, image, signal-processing double kernel_min(Kernel kernel) { double min = 0; for (int index = 0; index < kernel.size*kernel.size; index++) { if (kernel.weights[index] < 0) min += kernel.weights[index]; } return min*255; } double kernel_max(Kernel kernel) { double max = 0; for (int index = 0; index < kernel.size*kernel.size; index++) { if (kernel.weights[index] > 0) max += kernel.weights[index]; } return max*255; } Accumulator convolve(Image image, Kernel kernel, int row, int col) { Accumulator accumulator = {0, 0, 0}; for (int r_off = -kernel.size/2; r_off <= kernel.size/2; r_off++) { for (int c_off = -kernel.size/2; c_off <= kernel.size/2; c_off++) { int ir = modulo(row + r_off, image.height); int ic = modulo(col + c_off, image.width); int kr = r_off + kernel.size/2; int kc = c_off + kernel.size/2; int index = ir*image.width + ic; Pixel pixel = image.pixels[index]; accumulator.r += pixel.r*kernel.weights[kr*kernel.size + kc]; accumulator.g += pixel.g*kernel.weights[kr*kernel.size + kc]; accumulator.b += pixel.b*kernel.weights[kr*kernel.size + kc]; } } return accumulator; } Image *apply_kernel(Image image, Kernel kernel) { Image *conv = create_image(image.width, image.height); double max = kernel_max(kernel); double min = kernel_min(kernel); double alpha = max - min; for (int row = 0; row < image.height; row++) { for (int col = 0; col < image.width; col++) { Accumulator accumulator = convolve(image, kernel, row, col); accumulator.r = 255*(accumulator.r - min)/alpha; accumulator.g = 255*(accumulator.g - min)/alpha; accumulator.b = 255*(accumulator.b - min)/alpha;
{ "domain": "codereview.stackexchange", "id": 45241, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, image, signal-processing", "url": null }
c, image, signal-processing conv->pixels[row*image.width + col].r = accumulator.r; conv->pixels[row*image.width + col].g = accumulator.g; conv->pixels[row*image.width + col].b = accumulator.b; } printf("%lf\r", 100.0*(1.0*row)/image.height); fflush(stdout); } return conv; } Kernel sobel_x(int n) { Kernel sx; sx.size = 3; sx.weights = malloc(sizeof(double)*sx.size*sx.size); sx.weights[0] = -1; sx.weights[1] = -2; sx.weights[2] = -1; sx.weights[3] = 0; sx.weights[4] = 0; sx.weights[5] = 0; sx.weights[6] = 1; sx.weights[7] = 2; sx.weights[8] = 1; return sx; } Kernel sobel_y(int n) { Kernel sy; sy.size = 3; sy.weights = malloc(sy.size*sy.size*sizeof(double)); sy.weights[0] = -1; sy.weights[1] = 0; sy.weights[2] = 1; sy.weights[3] = -2; sy.weights[4] = 0; sy.weights[5] = 2; sy.weights[6] = -1; sy.weights[7] = 0; sy.weights[8] = 1; return sy; } Image *sobel(Image image) { Image *conv = create_image(image.width, image.height); Image *sobx, *soby; Kernel sx = sobel_x(3); Kernel sy = sobel_y(3); sobx = apply_kernel(image, sx); soby = apply_kernel(image, sy); save_image("sobel_x.ppm", *sobx); save_image("sobel_y.ppm", *soby); double max = kernel_max(sx); double min = kernel_min(sx); double alpha = max - min; for (int row = 0; row < image.height; row++) { for (int col = 0; col < image.width; col++) { Accumulator x = convolve(image, sx, row, col); Accumulator y = convolve(image, sy, row, col); x.r = 255*(x.r)/alpha; x.g = 255*(x.g)/alpha; x.b = 255*(x.b)/alpha; y.r = 255*(y.r)/alpha; y.g = 255*(y.g)/alpha; y.b = 255*(y.b)/alpha;
{ "domain": "codereview.stackexchange", "id": 45241, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, image, signal-processing", "url": null }
c, image, signal-processing Accumulator gradient = { sqrt(x.r*x.r + y.r*y.r), sqrt(x.g*x.g + y.g*y.g), sqrt(x.b*x.b + y.b*y.b), }; gradient.r = (gradient.r > 255)? 255: gradient.r; gradient.g = (gradient.g > 255)? 255: gradient.g; gradient.b = (gradient.b > 255)? 255: gradient.b; conv->pixels[row*image.width + col].r = (uint8_t) gradient.r; conv->pixels[row*image.width + col].g = (uint8_t) gradient.g; conv->pixels[row*image.width + col].b = (uint8_t) gradient.b; } printf("%lf\r", 100.0*(1.0*row)/image.height); fflush(stdout); } return conv; } unsigned modulo(int value, unsigned m) { int mod = value % (int) m; if (mod < 0) mod += m; return mod; } main.c #include <stdio.h> #include <stdlib.h> #include <math.h> #include "improc.h" int main(int argc, char **argv) { (void) argc; Image *ema = load_image(argv[1]); save_image("identity.ppm", *ema); Image *sob = sobel(*ema); save_image("sobel.ppm", *sob); } build script #!/bin/bash gcc improc.c main.c -O3 -g -Wall -Wpedantic -lm -Wextra -o main Answer: Let's talk about the API. I've worked with multiple imaging libraries over the past ~25 years, and have significant experience designing them too. API: Let's start with the image container, the core of any imaging library. typedef struct { int height; int width; Pixel *pixels; } Image; //… Image *ema = load_image(argv[1]); Image *sob = sobel(*ema); free_image(ema); /* (missing from the code, but should be there.) //…
{ "domain": "codereview.stackexchange", "id": 45241, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, image, signal-processing", "url": null }
c, image, signal-processing Most of the times that you refer to an image, you use *name, except in a few places where it's just name. This is confusing, and unnecessarily complicated. First of all, passing a struct (even if it's small now) by value (i.e. its values are copied) is more expensive than passing its pointer. Second, when you create the image object you malloc it, and it's awkward to then copy its contents to the stack to call a function. Third, as the library grows, so will this struct (a flag for RGB vs grayscale, or maybe an int for the number of channels, maybe a flag for which color space it's in, maybe a flag for the data type, maybe a flag for whether the struct owns the pixel data or not, ...). At some point copying the struct will be prohibitive. So, let's enforce passing the struct by pointer, and let's make it easy to do so! typedef struct { int height; int width; Pixel *pixels; } *Image; //… Image ema = load_image(argv[1]); Image sob = sobel(ema); free_image(ema); //… Now Image is always a pointer to the struct. There's no type you can use to refer to the struct itself, you can only refer to the pointer. But it looks nice in the code, the user doesn't even need to know it's a pointer! For Kernel you're doing something totally different: when you create a kernel (e.g. sobel_x) you create the struct on the stack and return it by value. Why the distinction? A kernel is, after all, just an image with a different type for the pixels. Why is the kernel always square? This is an important limitation. At some point you'll be looking to use a 15x1 kernel, and you'll have to create a 15x15 kernel with lots of zeros, which will be 15 times as expensive to use.
{ "domain": "codereview.stackexchange", "id": 45241, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, image, signal-processing", "url": null }
c, image, signal-processing The function convolve doesn't convolve two images, it only computes the result of the convolution at one pixel. This is surprising. Your function apply_kernel should be called convolve (or maybe convolution). The single pixel sub-function should, IMO, be private. Likewise, Accumulator could be private until you have a reason to make it public. The fewer things you make public initially, the easier it will be to improve on the API. Making something public (i.e. putting it into improc.h) sort of fixes them in perpetuity. As soon as people start using that API, you can't change it any more*, but you can always add to it. * At least not without forcing users to update their code. And you're a user too. As soon as you start using this library to write programs, it will become hard to make changes to the API, you'll have to update all the programs that use it too. kernel_min and kernel_max have the wrong name. I was reading the code, and wondering why you were using addition and not max(). Later I came to realize that you use these functions to determine what the minimum and maximum possible values of the output image will be when you compute the convolution with that kernel. You could instead consider adding offset and scale arguments to your convolution function, and clip the result of the convolution before writing it to the uint8 output. This makes the function more flexible: the maximum and minimum possible values are not often obtained, so your scaling is a bit too drastic, the result is a very dim image, and a strongly quantized derivative. A user might want to pick a smaller scaling value.
{ "domain": "codereview.stackexchange", "id": 45241, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, image, signal-processing", "url": null }
c, image, signal-processing improc.h, which defines your API, should contain documentation for the functions and types it makes public. You can document in a separate file, but it's always easier to put the documentation directly in the header. You user will be able to easily find the documentation in their IDE, and many IDEs will even show this documentation in a tooltip when you hover over a function call with the mouse. I suggest you use the Doxygen style for documentation. Doxygen is a nice tool to generate HTML from the documentation in the header files, though it has some downsides as well (many people, including me, have written alternatives, but most of these will use the same style for the documentation source). Efficiency: The convolution tests, for each pixel, whether a neighbor is inside the image or not (you use modulo for this, a neat solution, but it still has a branch in it). It is actually (in my experience) faster to copy the image into a larger buffer, and pick some padding scheme to fill those values outside the original image. The convolution now doesn't need to do any tests at all. You can also consider reducing the amount of coordinate computation you do within the loop: Accumulator convolve(Image image, Kernel kernel, int row, int col) { Accumulator accumulator = {0, 0, 0}; r_offset = row - kernel.size / 2; c_offset = col - kernel.size / 2; int kindex = 0; for (int kr = 0; kr < kernel.size; kr++) { int ir = modulo(r_offset + kr, image.height); int iindex = ir * image.width; for (int kc = 0; kc <= kernel.size; kc++, kindex++) { int ic = modulo(c_offset + kc, image.width); Pixel pixel = image.pixels[iindex + ic]; accumulator.r += pixel.r * kernel.weights[kindex]; accumulator.g += pixel.g * kernel.weights[kindex]; accumulator.b += pixel.b * kernel.weights[kindex]; } } return accumulator; }
{ "domain": "codereview.stackexchange", "id": 45241, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, image, signal-processing", "url": null }
c, image, signal-processing kindex, the index into the kernel, increases by 1 every inner loop iteration, so just increment it, don't compute kr*kernel.size + kc (and certainly don't compute that 3 times, even though your compiler will likely optimize that out). ir doesn't change during the inner loop, so compute it outside that loop. And a lot of the remaining computation you did was because your loop goes from -size/2 to size/2, rather than from 0 to size, and so you needed to add an offset again to index into the kernel. (By the way, your code has a bug if kernel.size is even) Style: Please use an empty line in between functions. Vertical space is very important for readability.
{ "domain": "codereview.stackexchange", "id": 45241, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, image, signal-processing", "url": null }
python, yaml Title: Cleaning Yaml Data in Python Question: I'm working with a bunch of yaml files that are rather sloppy. This is outside of my control unfortunately, so I'm trying to clean up the data after the fact. My approach doesn't allow for nested structures yet, but I was wondering if this approach seems reasonable so far, if the code is readable, and if there are suggestions to improve the code. from dataclasses import dataclass, field, fields from enum import auto, Enum from pathlib import Path from typing import Any import yaml class HandleValidationError(Enum): """ An enumeration representing options for handling validation errors in the MappedYaml class. Enum Values: ignore: Ignore validation errors and proceed with the invalid data. reject: Reject the invalid data and exclude it from further processing. correct: Attempt to correct the invalid data and continue with the corrected values. """ ignore = auto() reject = auto() correct = auto() class StatusValidationError(Enum): """ An enumeration representing the status of validation errors in the MappedYaml class. Enum Values: ignored: The validation error was ignored. rejected: The validation error led to rejection of the invalid data. correct_fail: Attempted correction of the invalid data failed. correct_success: Attempted correction of the invalid data succeeded. """ ignored = auto() rejected = auto() correct_fail = auto() correct_success = auto() @dataclass class ValidationErrorLog: """ A class to store validation error logs for YAML data in the MappedYaml class. """ missing_key: list[str] = field(default_factory=list) without_value: list[str] = field(default_factory=list) incorrectly_formatted_value: list[tuple[str, StatusValidationError]] = field(default_factory=list) invalid_value_type: list[tuple[str, StatusValidationError]] = field(default_factory=list)
{ "domain": "codereview.stackexchange", "id": 45242, "lm_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, yaml", "url": null }
python, yaml def add_missing_key(self, missing_key: str) -> None: self.missing_key.append(missing_key) def add_key_without_value(self, key_without_value: str) -> None: self.without_value.append(key_without_value) def add_key_with_incorrectly_formatted_value(self, key_with_incorrectly_formatted_value: str, status: StatusValidationError) -> None: self.incorrectly_formatted_value.append((key_with_incorrectly_formatted_value, status)) def add_key_with_incorrect_value_type(self, key_with_invalid_value_type: str, status: StatusValidationError) -> None: self.invalid_value_type.append((key_with_invalid_value_type, status)) @dataclass(kw_only=True) class MappedYaml: """ A base class for mapping YAML data to Python objects with validation. """ validation_error_log: ValidationErrorLog = None @classmethod def init_with_validation( cls, path: Path, handle_type_errors: HandleValidationError = HandleValidationError.correct, handle_formatting_errors: HandleValidationError = HandleValidationError.correct ) -> 'MappedYaml': """ Initialize an instance of the class with validation. Args: path (Path): The path to the YAML file. handle_type_errors (HandleValidationError): How to handle errors related to invalid value types. handle_formatting_errors (HandleValidationError): How to handle errors related to invalid formatting. Returns: MappedYaml: An instance of the class with validated data. Raises: ValueError: If the file has an invalid suffix. TypeError: If the child class cannot be initialized. """ if not path.suffix == '.yaml': raise ValueError(f'File "{path.as_posix()}" has invalid suffix. Only .yaml files are supported.')
{ "domain": "codereview.stackexchange", "id": 45242, "lm_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, yaml", "url": null }
python, yaml log = cls._new_log() data = cls._get_data(path, log) cls._check_invalid_types(data, log, handle_type_errors) cls._check_invalid_formatting(data, log, handle_formatting_errors) try: return cls(validation_error_log=log, **data) except TypeError: raise TypeError('Could not initialize child class. Check if the child class has default values for ' 'every field.') @classmethod def _new_log(cls) -> ValidationErrorLog: """ Create a new instance of the validation error log. Override this method if you wish to use a custom version of ValidationErrorLog(). """ return ValidationErrorLog() @classmethod def _get_data( cls, path: Path, log: ValidationErrorLog ) -> dict[str, Any]: """ Attempt to retrieve the data from a YAML file, as defined in the fields of the child class. Logs missing keys and values from the Yaml file. """ with open(path) as file: all_data = yaml.safe_load(file) result = {} for f in fields(cls)[1:]: try: data_value = all_data[f.name] except KeyError: log.add_missing_key(f.name) else: if not data_value: log.add_key_without_value(f.name) result[f.name] = data_value return result @classmethod def _check_invalid_types( cls, data: dict[str, Any], log: ValidationErrorLog, handle_type_errors: HandleValidationError ) -> None: """ Checks if the value types of the yaml data aligns with the field types declared in the fields of the child class. """ required_types = {f.name: f.type for f in fields(cls)} keys_to_remove = []
{ "domain": "codereview.stackexchange", "id": 45242, "lm_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, yaml", "url": null }
python, yaml required_types = {f.name: f.type for f in fields(cls)} keys_to_remove = [] for data_key, data_value in data.items(): required_type = required_types.get(data_key) if data_value and not isinstance(data_value, required_type): status = cls._handle_invalid_type(data, data_key, required_type, handle_type_errors) log.add_key_with_incorrect_value_type(data_key, status) if status in {StatusValidationError.rejected, StatusValidationError.correct_fail}: keys_to_remove.append(data_key) for key in keys_to_remove: data.pop(key) @classmethod def _handle_invalid_type( cls, data: dict[str, Any], data_key: str, required_type: type, handle_type_errors: HandleValidationError ) -> StatusValidationError: """ Handle cases where a value has an invalid type. """ if handle_type_errors == HandleValidationError.ignore: return StatusValidationError.ignored elif handle_type_errors == HandleValidationError.reject: return StatusValidationError.rejected else: try: data[data_key] = required_type(data[data_key]) return StatusValidationError.correct_success except ValueError: return StatusValidationError.correct_fail @classmethod def _check_invalid_formatting( cls, data: dict[str, Any], log: ValidationErrorLog, handle_formatting_errors: HandleValidationError ) -> None: """ Check for invalid formatting in the data. Implement to add custom formatting checks for your data. """ pass
{ "domain": "codereview.stackexchange", "id": 45242, "lm_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, yaml", "url": null }
python, yaml # example of a child class: @dataclass(kw_only=True) class StudyYamlData(MappedYaml): study_id: str = '' year: int = None abstract: str = '' reference: str = '' keywords: str = '' domain_general: str = '' domain_specific: str = '' Answer: nouns and verbs We use nouns for class names and verbs for function (or method) names. class HandleValidationError(Enum): """ An enumeration representing options for handling validation errors in the MappedYaml class. That looks more like a ValidationAction to me (or perhaps a "recovery type"). Grammar in the docstring is perfect -- other code will be handling each error. But this code is not about "handling" errors and fixing them, it's about attaching a descriptive tag. nit: To "correct" horribly bad data is sometimes impossible. Consider using "impute" instead. Using an Enum here was very nice. I will just observe in passing that we don't necessarily need that level of indirection. We could choose to mention class names directly, so we're pointing directly at the code which implements the recovery strategy. errors are exceptions class StatusValidationError(Enum): Yikes! Up above I somehow knew the name was "wrong", but I didn't even realize exactly why I felt that so strongly. But now the pattern becomes clearer. Yeah, we have FooError which inherits from Enum rather than Exception -- that's pretty surprising! Please don't do that. I guess each of these is a ValidationErrorStatus ? And perhaps the previous class is ValidationErrorStrategy ? Sorry. It turns out that Naming is Hard. But it's really important, so we strive to get it (mostly) right. I worry that this class seems mostly redundant with the strategy class, except for a bool on whether imputation succeeded or not. Maybe failed imputation replaces input with a BAD_DATA sentinel and then we don't need these four enums? I will read further to see how that holds up.
{ "domain": "codereview.stackexchange", "id": 45242, "lm_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, yaml", "url": null }
python, yaml dataclass methods Yay, ValidationErrorLog is a @dataclass! Other name suffixes to consider would be ...Store and ...Repository, but ...Log is perfectly nice as-is. I really like the four fields, and their very clear signatures. The four methods seem on the verbose side, like I'm reading java rather than python. Maybe we need them? We'll see. But given that your Public API defines four public fields, it's unclear why caller shouldn't just do the .append() himself. Not seeing much value add in these methods yet. Well, certainly it's very clean! types in docstrings In MappedYaml init_with_validation, the optional type annotation is lovely, I thank you. The Args section of the docstring seems mostly redundant with the excellent parameter names you chose, especially the types which repeat types seen in the signature. Maybe some people find a list of known exceptions helpful? This isn't java. I figure lightning can strike at any moment, there's no knowing exactly what might happen during a call. As long as we have informative diagnostic error messages, which I'm seeing here, then we're good. Consider renaming the first param to be slightly more verbose: yaml_path docstring format Tiny nit: in _new_log, we see a very nice docstring. Pep-8 asks that you write the first sentence and then insert a blank line before going on with the helpful "override" advice. tricky code for f in fields(cls)[1:]:
{ "domain": "codereview.stackexchange", "id": 45242, "lm_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, yaml", "url": null }
python, yaml tricky code for f in fields(cls)[1:]: In _get_data it's not clear what's special about the zeroth field. Especially since MappedYaml doesn't have any fields at all. The helpful example class seems to indicate that an "...id" might be special. We should find a way to document this. Maybe it makes sense to filter() fields that match an "id" regex? Or maybe "optional field" is the concept we're going for here? Or "ignored field"? The if not data_value: test is maybe looser than desired, since many things can be falsey. Or maybe the current behavior is exactly what you want, and it just needs some better documentation. I'm concerned that someone could run a YAML file through this parser, be happy with it, then make a tiny edit and be surprised by the parse result. checking for valid types In _check_invalid_types, here's a small nit: if status in {StatusValidationError.rejected, StatusValidationError.correct_fail}: This is very nice as-is. I think you were going for speed -- usually we prefer to use the in operator on a set than a sequence. It's a micro-optimization. We're constructing a new set and then soon discarding it. I haven't viewed the python3.12 bytecode, but usually dis.dis reveals that in (a, b) does less work than if we construct a mutable sequence. It gets to put the immutable tuple into the bytecode, once, and then keep recycling it. No biggie. This is a nice method, very clear. Here's an algorithmic idea: maybe delete it? And let beartype worry about the heavy lifting? Then it's just a matter of catching any exceptions that it raises. Ok, maybe it's a bit late in the design process to contemplate merging in beartype. I just like how it consults type annotations.
{ "domain": "codereview.stackexchange", "id": 45242, "lm_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, yaml", "url": null }
python, yaml default behavior I found _check_invalid_formatting surprisingly short. Perhaps we'd like to offer some example behavior, like prohibiting values longer than a megabyte, as an example for future implementors? That brings me back to _check_invalid_types, which also is void (returns -> None:). I kind of wish that both docstrings were more explicit about "evaluate for side effects", and then spell out the kinds of side effects contemplated. If the Author's Intent is that both are likely to be overriden in a child class according to needs of a custom use case, perhaps we'd prefer public method names rather than _private? Anyway, overall I find these are well engineered classes that do a good job of describing the details. I've written a couple three things about them, but that's more a reflection on me being chatty than upon code quality. I would use this as-is. This codebase achieves its design goals. I would be willing to delegate or accept maintenance tasks on it.
{ "domain": "codereview.stackexchange", "id": 45242, "lm_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, yaml", "url": null }
react.js, memoization Title: Further memoize context value in react? Question: This is a contrived example of a question that came up in code review the other day about memoizing context values in React. Let's say I have a hook which returns a memoized value of an expensive operation like so import { useMemo } from 'react' const ONE_MILLION = 1_000_000 const ZERO_TO_ONE_MILLION = Array(ONE_MILLION).fill(0).map((_, i) => i) export type NumberSelector = (n: number) => boolean /** * This hook returns a memoized sequence of numbers from 0 to 1,000,00 * for which the given selector returns true. */ export function useSequence(selector: NumberSelector): number[] { return useMemo(() => ZERO_TO_ONE_MILLION.filter(selector), [selector]) } Then let's say we want a context which contains several sequences import { createContext, PropsWithChildren } from 'react' import { selectOddNumber, selectEvenNumber, selectPowerOfTwo } from './selectors' import { useSequence } from './useSequence' export type Numbers = { odds: number[] evens: number[] powersOfTwo: number[] } export const NumberContext = createContext<Numbers>({ odds: [], evens: [], powersOfTwo: [], }) export function NumberProvider({ children }: PropsWithChildren<{}>) { // compute expensive calculations const odds = useSequence(selectOddNumber) const evens = useSequence(selectEvenNumber) const powersOfTwo = useSequence(selectPowerOfTwo) return ( <NumberContext.Provider value={{ odds, evens, powersOfTwo }}> {children} </NumberContext.Provider> ) } My coworker mentioned in the code-review that I should also memoize the value passed to the provider, something like: const memoizedValue = useMemo(() => ({ odds, evens, powersOfTwo }), [odds, evens, powersOfTwo]) return ( <NumberContext.Provider value={memoizedValue}> {children} </NumberContext.Provider> )
{ "domain": "codereview.stackexchange", "id": 45243, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "react.js, memoization", "url": null }
react.js, memoization Otherwise this would cause the sub-tree to re-render unnecessarily. However, I am not so convinced since our application is mainly using functional components which will re-render even if the props stay the same. My main two questions are: Does React always re-render the subtree unless specified otherwise with memo, etc. Should we always memoized the value to a context provider? Just for a little more context we primarily interact with a hook import { useContext } from 'react' import { NumberContext, Numbers } from './index' export function useNumbers(): Numbers { return useContext(NumberContext) } Also here is an example of the code, thanks! Answer: So the way React contexts work can be basically boiled down to: if that context re-renders any component which useContext's that context will re-render. So in this instance, I think that additional useMemo your coworker is suggesting may actually cause another unnecessary additional render though I could be wrong on that point. B/c when one of thos useSequence values changes, your context is rerendering anyways. On that next render, your new useMemo's dependency list would have altered, causing another re-render as it computes the new memoized values which are the same. useMemo is pretty often misused. Your initial usage inside the hook is perfect though.
{ "domain": "codereview.stackexchange", "id": 45243, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "react.js, memoization", "url": null }
c++, embedded Title: How to interface a "pull" library with a "push" library using callbacks Question: I am using a driver that retrieves data from HW (Driver) and a display (Viewer) that will output data to the user. The user calls a trigger function to initiate the getting of data from the Driver. The Driver's constructor accepts a "publish" callback function to be called when data is ready. The Viewer receives a "get data" callback on construction, to be called when it wants data from my code. My code must integrate the "pull" for data from the viewer with the data "pushed" back from the Driver once I call its trigger function. Another block of code (that I do not have access to) initiates requests from the Viewer and acts upon the data it received back. This is represented by the main method in my example, below. Thanks in advance! #include <cstdint> #include <iostream> #include <functional> class Viewer { public: Viewer(std::function<void(int&)> get_data_cb) : m_get_data_cb(get_data_cb) { } void populate_view(int &data) { m_get_data_cb(data); } private: std::function<void(int&)> m_get_data_cb; }; class Driver { public: Driver(std::function<void(int&)> publish_data_cb) : m_publish_data_cb(publish_data_cb) { } void trigger_event() { // tells RTL to start collecting data ++rtl_int; // trigger_event does not call the IRQ - this is just for demo purposes event_IRQ_handler(); } void event_IRQ_handler() { // fires when RTL has finished collecting data m_publish_data_cb(rtl_int); } private: std::function<void(int&)> m_publish_data_cb; int rtl_int{ 0 }; }; /**********************************************************************/ // Code I have control of starts here volatile uint32_t publish_count{0}; int my_int{0}; // callback to send to Driver void my_publish_data_cb(int &i) { my_int = i; ++publish_count; }
{ "domain": "codereview.stackexchange", "id": 45244, "lm_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++, embedded", "url": null }
c++, embedded Driver my_driver = Driver{ my_publish_data_cb }; // callback to send to Viewer void my_get_data_cb(int &i) { uint32_t before = publish_count; my_driver.trigger_event(); // I need to give the driver's event_IRQ_handler() time // to get the data but is this the best way??? while (before == publish_count){}; i = my_int; //cout << "Viewer: i =" << i << endl; } Viewer my_viewer = Viewer{ my_get_data_cb }; // Code I have control of ends here /**********************************************************************/ int main() { my_viewer.populate_view(my_int); std::cout << "my_int = " << my_int << std::endl; my_viewer.populate_view(my_int); std::cout << "my_int = " << my_int << std::endl; my_viewer.populate_view(my_int); std::cout << "my_int = " << my_int << std::endl; return 0; }
{ "domain": "codereview.stackexchange", "id": 45244, "lm_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++, embedded", "url": null }
c++, embedded Answer: You are using a busy-loop to wait for publish_count to be incremented by the interrupt handler. In general, this is a bad way to wait for something to happen, as it keeps the processor busy, which wastes power and might increase its temperature unnecessarily. However, in an embedded device that is not battery-powered, it might be fine. If the device has a single CPU core, then some compilers will even detect what you are doing and insert a CPU instruction in the loop that will pause the processor until an interrupt occurs, thus avoiding wasting power. However, that will not work on multi-core processors. Since you mentioned the code is running on FreeRTOS, you can use its functions to suspend a task, and resume it from within the interrupt handler, for example using xTaskResumeFromISR(). Another option is to use a queue to send information from the ISR to a task. This decouples the task from the ISR, which might have some advantages. For example, in your code, my_get_data_cb() will always wait for the IRQ handler to generate a new value, but maybe there was already a new value available if the IRQ fired between two calls to my_get_data_cb(), in which case the latter could have returned it immediately. Furthermore, with queues you can send data larger than an int without having to worry about atomicity.
{ "domain": "codereview.stackexchange", "id": 45244, "lm_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++, embedded", "url": null }
c++, c++17, windows, winapi Title: ReadDirectoryChangesW Improvements Question: I'm currently using the ReadDirectoryChangesW Function from the Windows API to build a Directory Watcher. The Watcher should monitor a folder for newly added files. For this i use the following code: class DirectoryWatcher { public: using Callback = std::function<void(const std::string&)>; DirectoryWatcher(const std::filesystem::path& input_directory, std::vector<std::string> file_types, Callback callback); explicit operator bool() const { return is_valid_; } bool watch(); void stop(); size_t processedFilesCount() const { return processed_files_count; } size_t ignoredFilesCount() const { return ignored_files_count; } private: bool eventRecv(); bool eventSend(); void handleEvents(); bool hasEvent() const { return event_buf_len_ready_ != 0; } bool isProcessableFile(const std::filesystem::path& path) const; bool isValidAction(int action) const; std::filesystem::path input_directory_; std::vector<std::string> file_types_{}; Callback callback_; HANDLE path_handle_; HANDLE completion_token_{ INVALID_HANDLE_VALUE }; unsigned long event_buf_len_ready_{ 0 }; bool is_valid_{ false }; OVERLAPPED event_overlap_{}; std::vector<std::byte> event_buf_{ 64 * 1024 }; size_t processed_files_count{ 0 }; size_t ignored_files_count{ 0 }; }; DirectoryWatcher::DirectoryWatcher(const std::filesystem::path& input_directory, std::vector<std::string> file_types, Callback callback) : input_directory_{ input_directory }, file_types_{ file_types }, callback_{ std::move(callback) } { path_handle_ = CreateFileA(input_directory.string().c_str(), FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, nullptr); if (path_handle_ != INVALID_HANDLE_VALUE) { completion_token_ = CreateIoCompletionPort(INVALID_HANDLE_VALUE, nullptr, 0, 0); }
{ "domain": "codereview.stackexchange", "id": 45245, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, windows, winapi", "url": null }
c++, c++17, windows, winapi if (completion_token_ != INVALID_HANDLE_VALUE) { is_valid_ = CreateIoCompletionPort(path_handle_, completion_token_, (ULONG_PTR)path_handle_, 1); } } bool DirectoryWatcher::watch() { if (is_valid_) { eventRecv(); while (is_valid_ && hasEvent()) { eventSend(); } while (is_valid_) { ULONG_PTR completion_key{ 0 }; LPOVERLAPPED overlap{ nullptr }; bool complete = GetQueuedCompletionStatus(completion_token_, &event_buf_len_ready_, &completion_key, &overlap, 16); if (complete && overlap) { handleEvents(); } } return true; } else { return false; } } void DirectoryWatcher::handleEvents() { while (is_valid_ && hasEvent()) { eventSend(); eventRecv(); } } void DirectoryWatcher::stop() { is_valid_ = false; } bool DirectoryWatcher::eventRecv() { event_buf_len_ready_ = 0; DWORD bytes_returned = 0; memset(&event_overlap_, 0, sizeof(OVERLAPPED)); auto read_ok = ReadDirectoryChangesW(path_handle_, event_buf_.data(), event_buf_.size(), FALSE, FILE_NOTIFY_CHANGE_FILE_NAME, &bytes_returned, &event_overlap_, nullptr); if (!event_buf_.empty() && read_ok) { event_buf_len_ready_ = bytes_returned > 0 ? bytes_returned : 0; return true; } if (GetLastError() == ERROR_IO_PENDING) { event_buf_len_ready_ = 0; is_valid_ = false; } return false; } bool DirectoryWatcher::eventSend() { auto buf = reinterpret_cast<FILE_NOTIFY_INFORMATION*>(event_buf_.data()); if (is_valid_) { while (buf + sizeof(FILE_NOTIFY_INFORMATION) <= buf + event_buf_len_ready_) { auto filename = input_directory_ / std::wstring{ buf->FileName, buf->FileNameLength / 2 }; if (isValidAction(buf->Action) && isProcessableFile(filename)) { callback_({ filename.string() }); processed_files_count++; } else { ignored_files_count++; } if (buf->NextEntryOffset == 0) { break; }
{ "domain": "codereview.stackexchange", "id": 45245, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, windows, winapi", "url": null }
c++, c++17, windows, winapi buf = reinterpret_cast<FILE_NOTIFY_INFORMATION*>(reinterpret_cast<std::byte*>(buf) + buf->NextEntryOffset); } return true; } else { return false; } } bool DirectoryWatcher::isProcessableFile(const std::filesystem::path& path) const { // Get extension and erase first character (dot-character of extension) std::string extension = path.extension().string().erase(0, 1); std::transform(extension.begin(), extension.end(), extension.begin(), [](unsigned char c) { return std::tolower(c); }); return std::find(file_types_.begin(), file_types_.end(), extension) != file_types_.end(); } bool DirectoryWatcher::isValidAction(int action) const { return action == FILE_ACTION_ADDED || action == FILE_ACTION_RENAMED_NEW_NAME; } int main() { int counter{ 0 }; std::cout << "Hello World!\n"; DirectoryWatcher watcher{ "C:\\temp\\dummy", {"dat"}, [&counter](const std::string& filename) { counter++; std::cout << "counter: " << counter << '\n'; //processing std::filesystem::remove(filename); } }; std::thread th1{ &DirectoryWatcher::watch, &watcher }; std::this_thread::sleep_for(std::chrono::seconds(300)); watcher.stop(); th1.join(); } I think that i don't have the best way used to do such things so i'm happy for any improvements or suggestions on this. The code should be compilable with c++ 17 and Visual Studio.
{ "domain": "codereview.stackexchange", "id": 45245, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, windows, winapi", "url": null }
c++, c++17, windows, winapi Answer: Simplify the interface Do you really need all those public member functions? It looks like processedFilesCount() and ignoredFilesCount() is something you might want to use for debugging, but would an application really care about those numbers? If it really cared, you could make the callback update some counters, as you already do in your own example code in main(). If you always intend to run watch() in a separate thread, then you could consider removing watch() and stop() (or make them private), and instead let the constructor automatically start watching and the destructor stop it. Your main() would then look like: int main() { DirectoryWatcher watcher{…}; std::this_thread::sleep_for(std::chrono::seconds(300)); }
{ "domain": "codereview.stackexchange", "id": 45245, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, windows, winapi", "url": null }
c++, c++17, windows, winapi I also wonder if you should pass a list of extensions to watch for to DirectoryWatcher(). The callback could easily check for that itself. And only checking extensions is not very flexible; what if I want to check for files whose name starts with a digit? Thread safety When you want to stop a thread, you should use atomic variables or mutexes to coordinate between the thread running watch() and the thread calling stop(). Don't store unnecessary data in member variables You store lots if information in member variables. However, this then takes up memory even if you aren't actually watching anything. A lot of the member variables are only necessary for watch() itself. They could be made local member variables of that function, and passed down to functions it calls where necessary. Also, why do you need to store input_directory_? After you have opened path_handle_, your class doesn't actually need the name of the directory anymore; isProcessableFile() only cares about the extension, not the directory name. The user of your class can pass the directory name to the callback function if it is really necessary. Why is event_buf_ exactly 64 kilobytes? You hardcoded the size of event_buf_ to 64 kilobytes. But why? FILE_NOTIFY_INFORMATION is just a few integers and the filename, but on Windows, a filename cannot be larger than 255 characters. So the buffer would be hold about 244 FILE_NOTIFY_INFORMATION structs, which seems to be much larger than necessary. How often do you expect that many files to be added between calls to ReadDirectoryChangesW()? Dodgy pointer arithmetic In this line of code: while (buf + sizeof(FILE_NOTIFY_INFORMATION) <= buf + event_buf_len_ready_) {
{ "domain": "codereview.stackexchange", "id": 45245, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, windows, winapi", "url": null }
c++, c++17, windows, winapi buf is a pointer to a FILE_NOTIFY_INFORMATION. If you add 1 to buf, it will therefore add sizeof(FILE_NOTIFY_INFORMATION) to the address. You are lucky here because you made the same mistake on both sides of the inequality, which cancels it out. You should instead just write: while (sizeof(FILE_NOTIFY_INFORMATION) <= event_buf_len_ready_) { But I also recommend you keep one std::byte* pointer variable that you can update, and then cast that to a FILE_NOTIFY_INFORMATION* only right before you need it. So: auto ptr = event_buf_.data(); … while (sizeof(FILE_NOTIFY_INFORMATION) <= event_buf_len_ready_) { auto buf = reinterpret_cast<FILE_NOTIFY_INFORMATION*>(ptr); … ptr += buf->NextEntryOffset; } Possible infinite loop Near the start of watch() you have this loop: while (is_valid_ && hasEvent()) { eventSend(); } Since eventSend() never clears event_buf_len_ready_, if it ever enters this loop, it will be an infinite one. Alternatives to callbacks Callback functions are certainly one way to do something when a directory even occurs, however they have some drawbacks. Especially if they are run in their own thread and might need to interact with other parts of your code base, you then need to worry about thread safety. There are ways to avoid that. One rather elegant solution is to use a thread-safe queue. The watch() function just pushes filenames to the queue, another thread can pop from it in a loop.
{ "domain": "codereview.stackexchange", "id": 45245, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, windows, winapi", "url": null }
shell, posix Title: Script to prevent nested root shells (POSIX) Question: Script to prevent nested root shells shall do exactly as said, plus some niceties like an error message when someone runs it with some argument/option. #!/bin/sh set -o nounset; set -o errexit error() { printf >&2 '%b\n' "$@" exit 1 } is_root() { [ "$(id -u)" -eq 0 ] } start_root_shell() { exec sudo -s } if [ "$#" -gt 0 ]; then error "Usage of $(basename "$0") script:\n" \ 'Starts a root shell, no argument accepted.' fi if is_root; then error 'You are already superuser!' fi start_root_shell Answer: First, the things I like in this script: Good use of the shell options to find simple mistakes. That's the first thing I do in my shell scripts. Good error reporting - correctly using the error stream and exit status Good use of quoted strings. You didn't miss the tricky one in $(basename "$0"). Everything is laid out well - it's clear and easy to read. The observations I have are generally quite minor. I don't see why we have two separate commands here: set -o nounset; set -o errexit It's simpler to write set -o nounset -o errexit We're using an undefined conversion here: printf >&2 '%b\n' "$@" %b isn't among the conversions specified by POSIX. I think that %s should be fine here, if we change the single use of \n into a separate string argument (and this neatly fixes an obscure bug if the command file-name contains \): error "Usage of $(basename "$0") script:" \ '' \ 'Starts a root shell, no argument accepted.' is_root and start_root_shell each contain a single command and are used just once, so the benefit of using functions is debatable. I'd lean towards inlining them, perhaps with a comment. Modified version The only change I'd insist upon if accepting this code would be to use a specified, portable conversion in the printf. The rest is just style. #!/bin/sh set -o nounset -o errexit
{ "domain": "codereview.stackexchange", "id": 45246, "lm_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 set -o nounset -o errexit error() { printf >&2 '%s\n' "$@" exit 1 } if [ "$#" -gt 0 ] then error "Usage of $(basename "$0") script:" \ '' \ 'Starts a root shell, no argument accepted.' fi if [ "$(id -u)" -eq 0 ] then error 'You are already superuser!' fi # Start the root shell exec sudo -s
{ "domain": "codereview.stackexchange", "id": 45246, "lm_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 }
c, bitwise Title: C Bit Utility Functions: Popcount, Trailing Zeros Count, Reverse All Bits Question: Here are some utility bitwise functions for 64 bit integers. I have independently derived inv64 (inverse all bits) and pcnt64 (count bits set to 1) myself, though I am sure someone else has before, so this is nothing new. But ctz64 (count trailing zero bits) is a modified version of Count the consecutive zero bits (trailing) on the right in parallel (Bit Twiddling Hacks). uint64_t inv64(uint64_t n) { n = (n & 0x5555555555555555ULL) << 1 | n >> 1 & 0x5555555555555555ULL; n = (n & 0x3333333333333333ULL) << 2 | n >> 2 & 0x3333333333333333ULL; n = (n & 0xF0F0F0F0F0F0F0FULL) << 4 | n >> 4 & 0xF0F0F0F0F0F0F0FULL; n = (n & 0xFF00FF00FF00FFULL) << 8 | n >> 8 & 0xFF00FF00FF00FFULL; n = (n & 0xFFFF0000FFFFULL) << 16 | n >> 16 & 0xFFFF0000FFFFULL; return n << 32 | n >> 32; } uint8_t pcnt64(uint64_t n) { n = (n & 0x5555555555555555ULL) + (n >> 1 & 0x5555555555555555ULL); n = (n & 0x3333333333333333ULL) + (n >> 2 & 0x3333333333333333ULL); n = (n & 0xF0F0F0F0F0F0F0FULL) + (n >> 4 & 0xF0F0F0F0F0F0F0FULL); n = (n & 0xFF00FF00FF00FFULL) + (n >> 8 & 0xFF00FF00FF00FFULL); n = (n & 0xFFFF0000FFFFULL) + (n >> 16 & 0xFFFF0000FFFFULL); return (uint8_t)n + (uint8_t)(n >> 32); } uint64_t ctz64(uint64_t n) { n &= -(int64_t)n; return (!(n & 0xFFFFFFFFULL) << 5 | !(n & 0xFFFF0000FFFFULL) << 4 | !(n & 0xFF00FF00FF00FFULL) << 3 | !(n & 0xF0F0F0F0F0F0F0FULL) << 2 | !(n & 0x3333333333333333ULL) << 1 | !(n & 0x5555555555555555ULL)) + !n; }
{ "domain": "codereview.stackexchange", "id": 45247, "lm_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, bitwise", "url": null }
c, bitwise Answer: These look familiar to me, but they are apparently "different enough" that GCC and Clang fail to recognize them as idioms. Well, the bit-reversal comes out about as well as can be expected on x64 (GCC and Clang both managed to use bswap), but not the other two. If I make a couple of changes to pcnt64 then suddenly GCC and Clang recognize it: uint8_t pcnt64(uint64_t n) { n = n - ((n >> 1) & 0x5555555555555555ULL); n = (n & 0x3333333333333333ULL) + (n >> 2 & 0x3333333333333333ULL); n = (n + (n >> 4)) & 0xF0F0F0F0F0F0F0FULL; return (n * 0x0101010101010101ULL) >> 56; } Gets compiled into popcnt64: xor eax, eax popcnt rax, rdi ret
{ "domain": "codereview.stackexchange", "id": 45247, "lm_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, bitwise", "url": null }
c, bitwise Gets compiled into popcnt64: xor eax, eax popcnt rax, rdi ret Although when compiling with a different compiler and/or targeting a different platform, this can work out poorly - for example on an embedded platform that lacks both a built-in popcnt instruction and also a hardware multiplier. As is commonly the case, the same code is not the best for all platforms. You could do some #ifdef-based selection between alternative implementations, or just decide which platforms you care about the most. I don't know what portable code to write such that a tzcnt instruction comes out. If you don't care about portability so much, there's _tzcnt_u64 (from immintrin.h) which is at least "portable across compilers", though not across different CPUs. As a "dual" to that there is __builtin_ctzll which is a GCC/Clang builtin (maybe seen in some other random compilers, but not MSVC) but supported across different CPUs (note that it does not deal gracefully with the case where the input is zero). In n &= -(int64_t)n; you should not be casting to int64_t to do the negation. Paradoxically that creates the potential for UB, while negating an unsigned integer is completely safe (with no edge cases) and does exactly what you need it to do. Though to silence some incorrect warnings, you may need to subtract from zero instead of negate. There is an alternative trailing-zero-counting strategy that may be better in some cases (popcnt instructions are more widely available across different CPUs, and seem to be easier to get out of a compiler too): make a mask of the trailing zeroes and then popcnt that. For example: uint64_t ctz64(uint64_t n) { return pcnt64(~n & (n - 1)); } ~n & (n - 1) is a trailing-bit-manipulation idiom, see manipulating rightmost bits. Clang even managed to make a tzcnt from that; GCC's more literal interpretation is not bad either.
{ "domain": "codereview.stackexchange", "id": 45247, "lm_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, bitwise", "url": null }
javascript, performance, programming-challenge, array Title: Given an array, remove zero or more elements to maximize the reduction where you add odd values and subtract even values Question: Here's a code challenge I got. (I could not solve the challenge, I ran out of time. I rephrased the challenge language and I am trying the challenge again for personal growth & computer science knowledge) Consider an array A of N integers. You can delete zero or more of its elements. Then take the remaining elements and reduce to an integer S according to these rules: elements in even positions are added elements in odd positions are subtracted: e.g. S = A[0] − A[1] + A[2] − A[3] + ... Create a function to find the maximum value of S When A = [4, 1, 2, 3], then S = 6, because the function could delete the third value in A: A = [4, 1, 3]. Then S = 4 − 1 + 3 = 6. When A = [1, 2, 3, 3, 2, 1, 5], then S = 7, because for A = [3, 1, 5], then S is maximized S = 3 − 1 + 5 = 7. When A = [1000000000, 1, 2, 2, 1000000000, 1, 1000000000], then S = 999999998, because for A = [1000000000, 1, 1000000000, 1, 1000000000], then S is maximized, S = 1000000000 - 1 + 1000000000 -1 + 1000000000 = 2999999998 You can assume that the value for S will not overflow an integer, and the length of the array (N) is under 100,000. After giving it more thought, I tried solution function get_best. I wrote in Javascript, but I appreciate your advice in any language. function get_best(A) { // rather than modifying the original array `A`, I accumulate a new array `remaining` with only the items from `A` that I didn't "delete" var remaining = []; A.forEach((current_item, i) => { var is_would_add = remaining.length % 2 == 0; var last_taken_item = remaining[remaining.length - 1]; var next_item = A[i + 1];
{ "domain": "codereview.stackexchange", "id": 45248, "lm_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, performance, programming-challenge, array", "url": null }
javascript, performance, programming-challenge, array if (is_would_add) { console.log(`add: the current item ${current_item} will be added (net positive); taking the current item`); remaining.push(current_item); } else { if (last_taken_item < current_item) { console.log(`subtract: last item ${last_taken_item} added *less* than the current item ${current_item} would subtract (net negative); taking the current item instead`); remaining.pop(); remaining.push(current_item); } else if (next_item < current_item) { console.log(`subtract: the next item ${next_item} would be a smaller negative than the current item ${current_item}, ignoring the current item`); } else { console.log(`subtract: the current item ${current_item} wont contribute to net negative, nor would the next item be a smaller choice; taking the current item`); remaining.push(current_item); } } }); return { remaining, reduction: remaining.reduce((accumulator, cv, ci) => { return accumulator + ((ci % 2 == 0) ? cv : -cv); }, 0) } } [ { input: [4, 1, 2, 3], output: { remaining: [4, 1, 3], reduction: 6 } }, { input: [1, 2, 3, 3, 2, 1, 5], output: { remaining: [3, 1, 5], reduction: 7 } },
{ "domain": "codereview.stackexchange", "id": 45248, "lm_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, performance, programming-challenge, array", "url": null }
javascript, performance, programming-challenge, array { input: [1000000000, 1, 2, 2, 1000000000, 1, 1000000000], output: { remaining: [1000000000, 1, 1000000000, 1, 1000000000], reduction: 2999999998 } } ].forEach((example, example_index) => { var best_output = get_best(example.input); if (best_output.reduction !== example.output.reduction) { console.warn(`example ${example_index + 1} failed, expected reduction is ${example.output.reduction} with expected remaining ${example.output.remaining} -- actual reduction is ${best_output.reduction} with actual remaining ${best_output.remaining}`); } else { console.log(`example ${example_index + 1} produced the expected result`); } }); Some questions: With the three examples given, did they find? I can't find better results. Of course, in answering this question, I must think about how my function should work. But I just want to confirm the examples aren't misleading! The solution above solves the above examples, but I challenge myself to find an example that my solution does not solve. The solution above; what's its complexity? what time complexity? I think it's O(N) (size of the array A) what space complexity? I'm not sure how to measure this, I'll search for some resources on understanding space complexity (I will read more of my resource for learning about complexity) Are there any "tricks or techniques" you can suggest to approach this challenge even if you can't offer a solution outright? Is there another solution? How is the solution better; does it solve more examples, and/or perform better in terms of time complexity, or space complexity? I have an idea, but I'm not sure if it's a good idea, or a better solution... use some kind of binary search to find the maximum value, split into left and right parts, and recursively find the maximum value of each (with constraints, like the left part must have an even number of elements, etc)
{ "domain": "codereview.stackexchange", "id": 45248, "lm_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, performance, programming-challenge, array", "url": null }
javascript, performance, programming-challenge, array Answer: You could simply use this pattern: [greatest value, smallest value, greatest value, smallest value, ...] local maximum, local minimum, ... That means, go until you found a value which is greater than the next value and if found go until you found a value which smaller than the next value. And so on. With a special treatment for the last value. If searching for a greater value, take the last (finally add this value), if searching for a smaller value, omit this value (prevent having a value for subtraction). With values: [4, 1, 2, 3] 4 1 3 [1, 2, 3, 3, 2, 1, 5] 3 1 5 [1000, 1, 2, 2, 1000, 1, 1000] 1000 1 1000 1 1000 The solution contains two functions for getting greater or smaller values. If one value is the greatest or smallest toggle the function to get the opposite value. Big O Time complexity: a single loop with O(n) (size of the array A) Space complexity: another shorter array O(n), or O(1), if only the sum is used. function getMax(values) { const smaller = (a, b) => a < b, greater = (a, b) => a > b, find = fn => (v, i, a) => { if (i + 1 === a.length && fn === greater || fn(v, a[i + 1])) { fn = fn === smaller ? greater : smaller; return true; } }; return values.filter(find(greater)); } console.log(...getMax([4, 1, 2, 3])); console.log(...getMax([4, 1, 2, 3, 1])); console.log(...getMax([4, 1, 2, 3, 1, 1])); console.log(...getMax([1, 2, 3, 3, 2, 1, 5])); console.log(...getMax([1000, 1, 2, 2, 1000, 1, 1000]));
{ "domain": "codereview.stackexchange", "id": 45248, "lm_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, performance, programming-challenge, array", "url": null }
python Title: Theme Toggle switch refactoring Question: I built a theme toggle switch function, and refactored it following an awesome suggestion in a previous answer. Before the refactoring the function looked like this: def toggle_theme(): if state["theme"]["light_mode"] is False: # If it is dark mode at the moment, make light state["theme"]["light_mode"] = True state["theme"]["theme_bg"] = config["theme"]["light_bg"] screen.bgcolor(config["theme"]["light_bg"]) theme_button.config(text=config["buttons"]["theme"]["dark_text"]) # If it is light mode, make dark else: state["theme"]["light_mode"] = False state["theme"]["theme_bg"] = config["theme"]["dark_bg"] screen.bgcolor(config["theme"]["dark_bg"]) theme_button.config(text=config["buttons"]["theme"]["light_text"]) After the refactoring it looks like this: def toggle_theme() -> None: ''' If light mode is on, switch to dark and vice versa. ''' state["theme"]["theme_bg"] = state["theme"]["theme_bg"][::-1] This is the state that is being changed: state = "theme": { "theme_bg": ['dark_bg', 'light_bg'] } Is toggle_theme() an appropriately simple and readable solution? The function has the side effect of changing a variable in state in a non-local scope. Should this side-effect be indicated? After fiddling for a while I settled with theme_bg as an argument of def main() and switching it directly with command: theme_bg: List=["black", "white"] theme_button = Button( button_frame, text=buttons_theme_light_text, command=screen.bgcolor(not theme_bg) )
{ "domain": "codereview.stackexchange", "id": 45249, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python Answer: I am not sure your code is ready for review. I have some comments that you might wish to consider if you will be further updating your code. But these comments are too long and too many to be posted as actual comments. So think of this post as a pre-review for whatever it is worth. I will confine my remarks to the second code version you have: A Minimal, Complete Example It's okay to post minimal code that demonstrates what you are doing, but that code should be complete, i.e. it compiles and runs. You have many names in the code that are not defined, e.g. screen, List, Button, etc. How much bigger would the code be if you included some missing import statements and the statements required to create a minimal GUI? Not much - and we would be able to execute the code and see how it works. A More Complete Docstring It appears that you have two themes: The background color is black and the button text is "☀️", The background color is white and the button text is """.
{ "domain": "codereview.stackexchange", "id": 45249, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python Now I may have gotten that wrong and that is all the more reason why your theme_toggle docstring should give a more complete description of what it is you are trying to accomplish. Why is theme_toggle Encapsulated Within Function main? Some of the statements that implement your theme toggle are within function theme_toggle while others are within the enclosing main function. It would be preferable to have the definitions that are currently within main placed at global scope and function theme_toggle should also be at global scope. This would certainly make the function more widely accessible to other functions. If this code were implementing what I consider to be a theme, the implementation would be using classes (I will describe why below). What is a Theme? TL;DR Feel free to skip this wordy exposition and jump to the last paragraph in bold. The themes I have worked with apply specific styling to the various widgets in your GUI. You can generally switch from one theme to another and all you have changed is the "look and feel." So changing a button's font, for example, would be an example. But when you toggle your theme, you are actually changing the caption being displayed in a very specific button. Clearly, if you had multiple buttons on your window, you would only be changing one specific button and changing it in a way that to me seems non-standard for a theme. I would not call what you are doing "toggling a theme." Let me elaborate:
{ "domain": "codereview.stackexchange", "id": 45249, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python You are changing the presentation's state in a way that goes beyond styling: I consider the button's caption to be part of it's state. Whether the button is up or down would also be part of its state. Whether the button is enabled or disabled would be part of its state. But a button's color, unless it had some semantic value, would not be. A situation where the button color does represent state is if we display two different colors depending on whether the button is enabled or not. So whereas a change in theme might change the colors used to denote enabled and disabled, for any given theme currently in use a change in color represents a change in state. But changing the button's color just because you changed the theme, would not be a change in state (if it was enabled before it is still enabled). Anyway, that is the distinction I am making between state and styling that has nothing to do with state. If you had multiple buttons and changing themes meant changing the styling of the buttons, then you might implement code that can walk through all the widgets and update the buttons it finds. Alternatively, on button creation you can add that button to a the set of all buttons in the presentation. Then it becomes a simple matter to iterate the set. So to my way of thinking (others may disagree), you are not toggling a theme as I generally understand it. Or if you really mean to be toggling a theme, the code is not very versatile. Update I am sorry I gave such a verbose post, which may have been confusing. My main objection was that I normally would consider the text of a button to represent part of that button's state independent of how it is styled (font choice, color choices, etc.). So I think of a theme as changing the styling of widgets without changing its state.
{ "domain": "codereview.stackexchange", "id": 45249, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python But I clearly misunderstood your post and it is now clear to me that this button you are referring to is what is being used to toggle the theme. Somehow I missed that and for that I apologize. So when you toggle the theme, then it is appropriate that the button that is being used to do that and also to show what the current theme is should change its state as long as all the other widgets should only have their styling change. So it now appears to me that the only "widget" in the presentation whose style is changing due to the toggling is just the screen itself. But consider a potentially future situation where you have lots of other widgets whose styling should be changed. You either have to explicitly add code to toggle_theme for each widget in your presentation. Every time you change the presentation adding or removing a widget, you have to update toggle_theme. That could be a maintenance nightmare. That's why I would suggest somehow tracking all widgets that are being added to a presentation by widget type in some appropriate class instances. Then toggle theme can iterate through the list of widgets and according to type change its style appropriately. I hope that makes things clearer. But what you are still missing is a minimal, complete example that I could in principle copy and paste with no additions and run it. But given that limitation, the following is how I would encapsulate the theme toggler in a class ThemeToggler. This code is necessarily missing the needed import statements and definitions. # import class defintions for Screen and Button (not included)
{ "domain": "codereview.stackexchange", "id": 45249, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python class ThemeToggler(): """This class toggles the theme in a presentation simply by changing the screens color and the "text" of the button that when clicked triggers a call to the toggle_theme method below.""" # What is missing is a defintion of config _themes = ( {"theme_bg": config["theme"]["dark_bg"], "theme_button": ""}, # dark_mode {"theme_bg": config["theme"]["light_bg"], "theme_button": "☀️"} # light_mode ) def __init__(self, screen: Screen, theme_button: Button): self._light_mode = True self._screen = screen self._theme_button = theme_button self._set_theme() def _set_theme(self): """Update presentation according to the current mode.""" theme = self._themes[self._light_mode] self._screen.bgcolor(theme['theme_bg']) self._theme_button.bgcolor.config(text=theme["theme_button") def toggle_theme(self): """We must arrange to have this method called as part of event processing when the theme button has been clicked.""" self._light_mode = not self._light_mode self._set_theme() def main(): # Build presentation defining screen and theme_button: ... # Most of the code is omitted # Create theme toggle theme_button = Button( button_frame, text=buttons_theme_text[not light_mode_on], command=theme_toggle ) theme_button.pack() ... theme_toggler = ThemeToggler(screen, theme_button) # Now arrange for theme_toggler.togle_theme to be invoked when # theme_button is clicked: ... if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 45249, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
javascript, strings, regex Title: Convert camelCase and PascalCase to Title Case Question: I'm trying to take camelCase and PascalCase strings into a function and spit them out as Title Case. This function also needs to be able to handle odd PascalCase strings with capitalized abbreviations such as "CDReceiverBox" and return a readable string - "CD Receiver Box". My current working solution: function splitCamelCase(camelCaseString) { const result = camelCaseString .replace(/([A-Z][a-z])/g, " $1") .replace(/([A-Z]+)/g, " $1") .replace(/ +/g, " ") .replace(/^ +/g, ""); return result.charAt(0).toUpperCase() + result.slice(1); } I would like to condense the amount of replace statements I'm using by at least combining the first two replace statements and the last two together since they are semi similar. The more concise I can make this the better. CodePen: https://codepen.io/andrewgarrison/pen/dEQrMy Answer: I like your solution quite a bit. It's clear, easy to read and I don't see any bugs. There are many ways to condense the replace calls as you mention, but I think you're at a point where such changes can easily have a disproportionate impact on readability. That's good--it means the code is already pretty optimal from that standpoint. For example, here's a one-shot replace using alternation, but its merit is debatable: const splitCamelCase = s => s.replace( /^[a-z]|^([A-Z]+)(?=[A-Z]|$)|([A-Z])+(?=[A-Z]|$)|([A-Z])(?=[a-z]+)/g, m => " " + m.toUpperCase() ).trim() ; The idea here is to enumerate each scenario, join the patterns with |s, and provide an arrow function to handle the addition of a space and a capital letter for each match. With the two extremes in mind, I prefer a balanced approach such as: const splitCamelCase = s => s.replace(/([A-Z][a-z])/g, " $1") .replace(/\s*([A-Z]+)/g, " $1") .replace(/./, m => m.toUpperCase()) .trim() ;
{ "domain": "codereview.stackexchange", "id": 45250, "lm_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, strings, regex", "url": null }
javascript, strings, regex or perhaps const splitCamelCase = s => s.replace(/([A-Z][a-z]|[A-Z]+(?=[A-Z]|$))/g, " $1") .replace(/./, m => m.toUpperCase()) .trim() ; These should offer ideas as far as how far you want to go in making the succinctness versus readability tradeoff. But, failing the possibility of a shortcut I might have overlooked, keeping your code basically as-is seems like a fine option to me. If it's performance you're after in reducing replace calls, there's no guarantee that fewer calls will translate into better performance. Under the hood, the regex engine may make more passes to compensate; you can benchmark and tweak using a debugger like regex101. For performance, it's likely best to avoid regex entirely and write a single-pass loop by hand. Here's a test runner: const splitCamelCase = s => s.replace(/([A-Z][a-z]|[A-Z]+(?=[A-Z]|$))/g, " $1") .replace(/./, m => m.toUpperCase()) .trim() ; [ "AAABbbbbCcDddEEFffGGHhIiJ", "AaBbCcDDEeFGgHHHH", "CDBoomBoxAAAABbbbCCC", "CDBoomBox", "camelCase", "camel", "Camel", "c", "C", "Aa", "AA", "aa", "AAA", "aB", "aBC", "aBCc", "", ].forEach(test => console.log( splitCamelCaseOriginal(test) === splitCamelCase(test) ? `'${test}' -> '${splitCamelCase(test)}'` : "TEST FAILED" ) ); function splitCamelCaseOriginal(camelCaseString) { const result = camelCaseString .replace(/([A-Z][a-z])/g, " $1") .replace(/([A-Z]+)/g, " $1") .replace(/ +/g, " ") .replace(/^ +/g, ""); return result.charAt(0).toUpperCase() + result.slice(1); }
{ "domain": "codereview.stackexchange", "id": 45250, "lm_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, strings, regex", "url": null }
python, configuration, yaml Title: Settings and global variables in one place Question: I have a configuration (YAML) file used across related modules. I also have a few additional variables to be accessed globally in my modules. I want to have them at one place (an instance of a class in my implementation below but I am willing to change it). This implementation (based on recommendations from the web and ChatGPT) is working as intended. I like that I can define the basic dictionary needed across all modules and then add additional items to the dictionary based on the particular module I'm calling by their relevant methods. But there must be a better implementation. In particular, I don't like storing the database engine in a dictionary (as almost all other items have strings). And storing it as a separate instance variable seems to have one outlier. Another thing I don't like is the long name when using dictionary notation config['parameter1']['parameter2']. What is a better way to handle this? Any help is appreciated. """Module to setup configuration parameters (read from YAML + additional)""" import logging import os from pathlib import Path import dotenv import sqlalchemy import yaml from . import utils # project directory as basepath irrespective of Python script or Jupyter notebook BASEPATH = utils.agnostic_path(Path().resolve()) dotenv.load_dotenv() codify_env = os.getenv("CODIFY_ENV") codify_client = os.getenv("CODIFY_CLIENT") class CodifyConfig: """ CodifyConfig """ def __init__(self, path_config: Path = Path(BASEPATH, "config", "config.yml")): self.path_config = path_config self.config = self.load_config() self.setup_additional_params() def load_config(self): """Loads project wide YAML configuration file""" with open(self.path_config, "r", encoding="utf-8") as file: config = yaml.safe_load(file)["client"][codify_client][codify_env] return config
{ "domain": "codereview.stackexchange", "id": 45251, "lm_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, configuration, yaml", "url": null }
python, configuration, yaml def setup_additional_params(self): """ Adds parameters to config not in the YAML config file because initial YAML parameters are chosen based on some of these parameters """ self.config["basepath"] = BASEPATH self.config["client"] = codify_client self.config["env"] = codify_env def setup_database(self, db: str = ""): """Create database engine""" db = db or self.config.get("database_url") self.config["engine"] = sqlalchemy.create_engine(db) def setup_logging(self, fn_log: str = "default.log") -> None: """Defaults and file name for logging""" path_log = Path(self.config["basepath"], "logs", fn_log) logging.basicConfig( filename=path_log, filemode="a", format="%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s", datefmt="%H:%M:%S", level=logging.INFO, ) Answer: Another thing I don't like is the long name when using dictionary notation config['parameter1']['parameter2']. Consider using the glom library, which was designed to address exactly that concern. informative identifier # project directory as basepath irrespective of Python script or Jupyter notebook BASEPATH = utils.agnostic_path(Path().resolve()) Thank you for the comment, I find it helpful. But I'm sad that you felt you needed a comment. That is, agnostic_path seems to be an unhelpful identifier. Ideally we wouldn't need to write a comment at all. Maybe utils.script_folder() would be more self explanatory? I often will add a get_repo_top() helper to my projects, which does the equivalent of $ git rev-parse --show-toplevel. I feel your utility function should definitely return Path rather than str. It is more descriptive. And it is easier / less visually intrusive to convert to str, with f"{folder}", than the other way 'round. clean import dotenv.load_dotenv()
{ "domain": "codereview.stackexchange", "id": 45251, "lm_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, configuration, yaml", "url": null }
python, configuration, yaml clean import dotenv.load_dotenv() This is not terrible, but I'd rather see it protected by if __name__ == '__main__': or run within some function. I assume it will complain if the calling user lacks dot files. A $ python -m unittest run should import cleanly, without error, even if dot files are missing. An import on a CI/CD host or container should work smoothly, even if dot files are missing. From its section you're telling me pretty clearly that $ pip install dotenv is the way to obtain this library. But I don't see that method in the source. globals codify_env = os.getenv("CODIFY_ENV") codify_client = os.getenv("CODIFY_CLIENT") These are kind of OK as module level symbols. But maybe there's no need to clutter up that Public API namespace, maybe we could defer the lookup until we need it? Or do it within an __init__ ctor? As a followup to the "clean import" remarks above, I do thank you for accepting None when env var is undefined. Flip side of that is, when we actually use the value, maybe os.eviron["CODIFY_ENV"] would offer a clearer diagnostic in the event someone forgot to set it? unhelpful docstring """ CodifyConfig """ Please delete. Or write an English sentence describing the responsibility of this class. That will be an aid to future maintainers, who will pass up the temptation to add kitchen_sink to the class, based on your advice about what does and does not belong here. In contrast, you've written a bunch of nice method and module docstrings, thank you. If a linter "made" you insert a docstring, then consider using a linter that is less picky by default, or change your current linter's config. local variable vs object attribute self.path_config = path_config Consider deleting that, preferring a call to self.load_config(path_config). Consider renaming the parameter to config_path.
{ "domain": "codereview.stackexchange", "id": 45251, "lm_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, configuration, yaml", "url": null }
python, configuration, yaml extra helper Usually I encourage folks to break up functions using Extract Helper, and then break them up some more. But you already have nice bite-sized pieces here. Maybe setup_additional_params should be merged with load_config? Then the codify client and env wouldn't go out of scope, so we could create them as local variables, use them twice, and be done with them. Consider renaming setup_additional_params to setup_runtime_params, as an explanation of why those params can't come from a static text file. dict vs object attribute self.config["engine"] = sqlalchemy.create_engine(db) Yeah, I agree with you, that is not a "config" item, and it looks weird. Prefer: self.engine = sqlalchemy.create_engine(db) BTW, I like that db or ... defaulting idiom. However, I don't like the default empty string value, as it is useless, it won't give us e.g. a sqlite in-memory database. So I recommend eliding the default value. abbrev def setup_logging(self, fn_log: str = "default.log") -> None: It wouldn't hurt to spell out filename_log (or log_filename). path_log = Path(self.config["basepath"], "logs", fn_log) This is perfectly fine as-is. Usual way to phrase this would be with / slashes: path_log = self.config["basepath"] / "logs" / fn_log) This code achieves its design goals. I would be willing to delegate or accept maintenance tasks on it.
{ "domain": "codereview.stackexchange", "id": 45251, "lm_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, configuration, yaml", "url": null }
beginner, c Title: char* to integer implementation (atoi with saturation to INT_MIN or INT_MAX on overflow) Question: I am learning C. As a task, I need to write a get_int function that will convert a char* to int. What parts can I improve here? I'm especially interested in how I can improve/rewrite the overflow checking. #include <stdio.h> #include <ctype.h> #include <limits.h> #define MINIUNIT_MAIN // https://github.com/urin/miniunit/blob/master/miniunit.h #include "miniunit.h" int get_int(char *string) { int i = 0; while (isspace(string[i])) { i++; } char sign = string[i] == '-' ? '-' : '+'; if (string[i] == '-' || string[i] == '+') { i++; } int result = 0; while (string[i] != '\0' && isdigit(string[i])) { // Check for overflow if (INT_MIN / 10 > result || (INT_MIN / 10 == result && INT_MIN % 10 >= -(string[i] - '0'))) { return sign == '-' ? INT_MIN : INT_MAX; } result = result * 10 - (string[i] - '0'); i++; } return sign == '-' ? result : -result; } int main(void) { test_case("Simple numbers", { expect("0", get_int("0") == 0); expect("1", get_int("1") == 1); expect("12", get_int("12") == 12); expect("199", get_int("199") == 199); expect("1000", get_int("1000") == 1000); expect("214748364", get_int("214748364") == 214748364); expect("214748500", get_int("214748500") == 214748500); }); test_case("Invalid input", { expect("Empty string", get_int("") == 0); expect("Spaces", get_int(" ") == 0); expect("Spaces and numbers", get_int(" 123") == 123); expect("Plus sign", get_int("+") == 0); expect("Minus sign", get_int("-") == 0); expect("Letters", get_int("abc") == 0); expect("Letters and numbers", get_int("123abc") == 123); expect("Dot and numbers", get_int("123.4") == 123); }); test_case("Negative numbers", { expect("-0", get_int("-0") == 0); expect("-1", get_int("-1") == -1); expect("-5", get_int("-5") == -5);
{ "domain": "codereview.stackexchange", "id": 45252, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c", "url": null }
beginner, c expect("-1", get_int("-1") == -1); expect("-5", get_int("-5") == -5); expect("-12", get_int("-12") == -12); expect("-1000", get_int("-1000") == -1000); }); test_case("Overflows", { expect("INT_MAX", get_int("2147483647") == INT_MAX); expect("INT_MAX + 1", get_int("2147483648") == INT_MAX); expect("INT_MAX + 10", get_int("2147483657") == INT_MAX); expect("INT_MAX + 1000", get_int("2147484647") == INT_MAX); expect("INT_MIN", get_int("-2147483648") == INT_MIN); expect("INT_MIN - 1", get_int("-2147483649") == INT_MIN); expect("INT_MIN - 10", get_int("-2147483658") == INT_MIN); expect("INT_MIN - 1000", get_int("-2147484648") == INT_MIN); }); } Answer: Uncommon bug: is...() is...() expects to receive an int with a value in the unsigned char range or EOF. char values may be other negatives which results in undefined behavior (UB). // while (isspace(string[i])) { while (isspace(((unsigned char *)string)[i])) { Pedantic bug: Long strings int i = 0; better as size_t i = 0 for strings whose length exceeds INT_MAX as in pathological input "000...3 billion zeros... 123". Overflow checking correct. Test is good and works for int of various width and encodings. Consider a stronger && test. It may help performance as first test INT_MIN / 10 > result is commonly false. // if (INT_MIN / 10 > result || (INT_MIN / 10 == result && INT_MIN % 10 >= -(string[i] - '0'))) { if (INT_MIN / 10 >= result && (INT_MIN / 10 > result || INT_MIN % 10 >= -(string[i] - '0'))) { Misleading comment // Check for overflow also is the return path for valid input like get_int("-2147483648"). Name get_int() sounds incorrect as get...() is often an I/O function. Maybe my_atoi(). Consider assigning errno so caller can distinguish good from bad. On overflow and no conversion consider setting errno. Maybe also invalid arguments and/or trailing non-numeric non-white-space text. Sample tested alternative Use const.
{ "domain": "codereview.stackexchange", "id": 45252, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c", "url": null }
beginner, c Sample tested alternative Use const. Stronger first range test. && Add error indication when possible. Take advantage that isdigt('\0') is false. Stronger tests for argument validity. #include <errno.h> #include <stdlib.h> #include <stdbool.h> int atoint_alt(const char *string) { // Maybe check argument? if (string == NULL) { #ifdef EINVAL errno = EINVAL; #endif return 0; } bool digit_found = false; const unsigned char *ustring = (const unsigned char*) string; while (isspace(*ustring)) { ustring++; } bool isneg = *ustring == '-'; if (isneg || *ustring == '+') { ustring++; } int result = 0; while (isdigit(*ustring)) { int digit = *ustring - '0'; digit_found = true; // Check for overflow if (result <= INT_MIN / 10 && (result < INT_MIN / 10 || digit > -(INT_MIN % 10))) { errno = ERANGE; return isneg ? INT_MIN : INT_MAX; } // Accumulate the value on the negative side. result = result * 10 - digit; ustring++; } if (!digit_found) { #ifdef EINVAL errno = EINVAL; #endif return 0; } if (!isneg) { if (result < -INT_MAX) { errno = ERANGE; return INT_MAX; } result = -result; } // Maybe look for extra junk while (isspace(*ustring)) { ustring++; } if (*ustring) { #ifdef EINVAL errno = EINVAL; #endif return 0; // or maybe retval? } return result; } Note: INT_MIN / 10 and INT_MIN % 10 have some issues with pre-C99 code. Look to div() to fix.
{ "domain": "codereview.stackexchange", "id": 45252, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c", "url": null }
c#, multithreading, .net, console, .net-core Title: Thread-safe int wrapper in c# Question: My system is a .NET Core 7 console app, which starts some background threads. I need to pass some int values (counters, etc.) between the main and background threads, in a thread-safe manner. Although I can pass an int by reference (e.g. DoFoo(ref myInt)), I can't assign it in the background thread (e.g. I can't pass it into the background thread class' constructor and save it as a field). So I decided to wrap it in a reference type, which I can pass that way. The following class works, but I'd like to know if it is truly thread-safe (have I missed something?) and whether it can be improved. public sealed class ConcurrentInt { private int _value; public ConcurrentInt(int value) => _value = value; // update value atomically public void Add(int value) => Interlocked.Add(ref _value, value); // read freshest value private int Get() => Interlocked.CompareExchange(ref _value, 0, 0); // allow `ci = ci + 1` and `ci += 1` and `ci += 1234` public static ConcurrentInt operator + (ConcurrentInt concurrentInt, int x) { _ = concurrentInt ?? throw new ArgumentNullException(nameof(concurrentInt)); concurrentInt.Add(x); return concurrentInt; } // allow `int x = ci` instead of `int x = ci.Get()` public static implicit operator int(ConcurrentInt concurrentInt) { _ = concurrentInt ?? throw new ArgumentNullException(nameof(concurrentInt)); return concurrentInt.Get(); } // ci.ToString("N0") public string ToString(string? format = null) => Get().ToString(format); } Answer: Based on the discussion in the comments section I think the code can be greatly simplified: public sealed class Counters { private int intCounter = 0; public int IntCounter { get => Interlocked.CompareExchange(ref intCounter, 0, 0); set => Interlocked.Exchange(ref intCounter, value); } }
{ "domain": "codereview.stackexchange", "id": 45253, "lm_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#, multithreading, .net, console, .net-core", "url": null }
c#, multithreading, .net, console, .net-core This allows you to hide the usage of Interlocked while exposing the data as int. Here is a simple usage example: var c = new Counters(); var t = new List<Task>() { Task.Run(async () => { c.IntCounter += 100; await Task.Yield(); c.IntCounter++; }), Task.Run(async () => { ++c.IntCounter; await Task.Yield(); c.IntCounter = c.IntCounter + 20; }) }; await Task.WhenAll(t); Console.WriteLine(c.IntCounter); The main drawback of this design is that it allows c.IntCounter = -1 as well.
{ "domain": "codereview.stackexchange", "id": 45253, "lm_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#, multithreading, .net, console, .net-core", "url": null }
rust Title: Idiomatic way to filter a `Vec` of version identifiers to only include latest version for each minor release? Question: I have a Vec<String> of all available versions of a particular piece of software (Godot), named VERSIONS in code below, where each version can be either "major.minor" or "major.minor.patch". These are manually scraped from tuxfamily. I also have a Vec<&str> of versions that are considered "supported", named STABLES in code below, where each version is in form of "major.minor". These are fetched from a file on GitHub. The purpose of this snippet is to filter VERSIONS to only include latest versions for each minor release. For example, if i have VERSIONS = [2.1, 3.5, 3.5.1, 3.6] and STABLES = [3.5, 3.6], i want to disregard 2.1 (as it is not in STABLES) and 3.5 (as the latest 3.5 release is 3.5.1), ending up with VERSIONS = [3.5.1, 3.6]. I tried hard to figure out a clean and ideally fast way to do the above, but ended up with a solution that is explicit about everything it does, possibly sacrificing readability (opinionated) and speed (i did not measure it, but i think it could be faster). // Dependencies: `versions` (for the `Versioning` struct), `ahash` (for `AHashMap`). // A mapping of "major.minor" to a struct representing "major.minor[.patch]" let mut latest_versions: AHashMap<&str, Versioning> = AHashMap::new(); // For each Godot version fetched from tuxfamily for godot_version in VERSIONS { for stable_godot_version in &STABLES { // We check if it is one of the versions marked as stable in our // custom data set if godot_version.starts_with(stable_godot_version) { // If yes, we check if we already have a version set as // "latest" in our hashmap. let latest: Option<&Versioning> = latest_versions.get(stable_godot_version);
{ "domain": "codereview.stackexchange", "id": 45254, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust match latest { Some(latest) => { // If yes, we compare our currently-iterated-over version // with the one in the hashmap, and if it is greater, we // set it as the latest let godot_version = Versioning::new(godot_version.as_str()).unwrap(); if &godot_version > latest { latest_versions.insert(stable_godot_version, godot_version); } }, // If not, we simply set it as the latest. None => { latest_versions.insert(stable_godot_version, Versioning::new(godot_version.as_str()).unwrap()); }, } } } } VERSIONS = latest_versions.values().into_iter().map(|v| v.to_string()).collect(); Notably, version comparison is done by overloaded operators on versions::Versioning. I still am not very comfortable with this code in my codebase, so i wonder if there's a way to improve/refactor it? Answer: I would start by parsing all of the version strings into some sort of Version struct. I might define it something like: struct Version { major: u32, minor: u32, patch: Option<u32> } You already do use versions::Versioning which you could parse into, but looking at that crate it looks to be trying to support any kind of version format and consequently lacks functionality which would be more useful for a constrained version. for godot_version in VERSIONS { for stable_godot_version in &STABLES { // We check if it is one of the versions marked as stable in our // custom data set if godot_version.starts_with(stable_godot_version) {
{ "domain": "codereview.stackexchange", "id": 45254, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust This is going to be somewhat inefficient because you loop over all the STABLES looking for a match. It would be more efficient if you created a set of stable versions and then checked if the corresponding major.minor for a particular godot version was in there. What I'd do is sort all of the versions. (Actually, if you are scraping it, maybe they already come sorted). Then I'd group_by from itertools to group versions with the same major.minor version. Then you could filter by stable versions and then map to return the last item of the group.
{ "domain": "codereview.stackexchange", "id": 45254, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
c++, networking Title: Lazy/deferred OOP-based networking using the Epic EOS SDK Question: For gaming applications, networking looks strange from the point of view of traditional approaches. Much of the game logic is based on "ticks"; Most often this is a mandatory item of operation. There is also a limitation from the "Epic EOS SDK" in the absence of thread safety, all "C" calls can only be made from one thread. Additionally, there is no explicit separation between client and server; we are dealing with a "p2p" network (transport via UDP protocol, WebRTC). The main.cpp code provided simply sends and receives a text strings twice. Here is one key point that concern me: Have I taken the best approach in terms of performance? QueueCommands.h #pragma once namespace detail_ { template <typename F, typename... Ts> class Action; } // namespace detail_ // forward decl class QueueCommands { static constexpr std::chrono::seconds c_commandTO{ 30 }; static constexpr auto now = std::chrono::system_clock::now; EOS_HPlatform m_platformHandle; EOS_HP2P m_p2PHandle; struct AvoidPush { bool Yes; } m_avoidPush{ true }; public: enum class Direction { Outgoing, Incoming }; struct ICommand { virtual Networking::messageData_t act(const QueueCommands::AvoidPush&) = 0; virtual Direction getDirection() const = 0; virtual ~ICommand() {} }; private: typedef std::shared_ptr< ICommand > sptr_t; std::queue< sptr_t > m_fifo; explicit QueueCommands(EOS_HPlatform platformHandle) : m_platformHandle( platformHandle ) , m_p2PHandle( ::EOS_Platform_GetP2PInterface( platformHandle ) ) {} QueueCommands(const QueueCommands &) = delete; QueueCommands(QueueCommands &&) = delete; QueueCommands& operator=(const QueueCommands &) = delete; QueueCommands& operator=(QueueCommands &&) = delete;
{ "domain": "codereview.stackexchange", "id": 45255, "lm_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", "url": null }
c++, networking static QueueCommands& getInstanceImpl_(EOS_HPlatform platformHandle = nullptr) { static QueueCommands instance{ platformHandle }; return instance; } sptr_t pop_() { if ( m_fifo.empty( ) ) return nullptr; auto x = m_fifo.front( ); m_fifo.pop( ); return x; } template <typename, typename...> friend class detail_::Action; friend class Receiving; friend class Sending; void push(const sptr_t &p) { m_fifo.push( p ); } void tick_() { ::EOS_Platform_Tick( m_platformHandle ); } uint64_t outgoingPacketQueueCurrentSizeBytes_() { EOS_P2P_PacketQueueInfo queueInfo = { }; EOS_P2P_GetPacketQueueInfoOptions options = { EOS_P2P_GETPACKETQUEUEINFO_API_LATEST }; ::EOS_P2P_GetPacketQueueInfo( m_p2PHandle, &options, &queueInfo ); // error checking has been ommited for "codereview" return queueInfo.OutgoingPacketQueueCurrentSizeBytes; } public: static void init(EOS_HPlatform platformHandle) { getInstanceImpl_( platformHandle ); } static QueueCommands& instance() { return getInstanceImpl_( ); } auto ticksAll() { std::vector< Networking::messageData_t > allIncomingData; sptr_t command; while ( command = pop_( ) ) { if ( Direction::Outgoing == command ->getDirection( ) ) { command ->act( m_avoidPush ); do { tick_( ); } while ( outgoingPacketQueueCurrentSizeBytes_( ) ); }
{ "domain": "codereview.stackexchange", "id": 45255, "lm_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", "url": null }
c++, networking auto timeout = now( ) + c_commandTO; if ( Direction::Incoming == command ->getDirection( ) ) { Networking::messageData_t packet = { }; do { packet = command ->act( m_avoidPush ); if ( packet.size( ) ) break; tick_( ); } while ( now( ) < timeout ); allIncomingData.push_back( packet ); } } return allIncomingData; } }; Action.h #pragma once namespace detail_ { template <typename F, typename... Ts> class Action : public QueueCommands::ICommand , public std::enable_shared_from_this< Action< F, Ts... > > { static_assert( !( std::is_rvalue_reference_v<Ts> &&... ) ); const QueueCommands::Direction m_direction; const F m_function; const std::tuple<Ts...> m_args; public: template <typename FwdF, typename... FwdTs, typename = std::enable_if_t< ( std::is_convertible_v< FwdTs&&, Ts > &&... ) >> Action(QueueCommands::Direction direction, FwdF&& func, FwdTs&&... args) : m_direction( direction ) , m_function( std::forward<FwdF>( func ) ) , m_args{ std::forward<FwdTs>( args )... } {} virtual ~Action() {}
{ "domain": "codereview.stackexchange", "id": 45255, "lm_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", "url": null }
c++, networking [[nodiscard]] Networking::messageData_t act( const QueueCommands::AvoidPush& avoidPush = QueueCommands::AvoidPush{ } ) override { Networking::messageData_t messageData = std::apply( m_function, m_args ); if ( !avoidPush.Yes ) QueueCommands::instance( ).push( shared_from_this( ) ); return messageData; } QueueCommands::Direction getDirection() const override { return m_direction; } }; template <typename F, typename... Args> auto make_action(QueueCommands::Direction direction, F&& f, Args&&... args) { return std::make_shared < Action< std::decay_t< F >, std::remove_cv_t< std::remove_reference_t< Args > >...> > ( direction, std::forward< F >( f ), std::forward< Args >( args )... ) ; } } // namespace detail_ aux Ctx struct Ctx { const std::string m_SocketName; const EOS_ProductUserId m_LocalUserId; const EOS_HPlatform m_PlatformHandle; const EOS_ProductUserId m_FriendLocalUserId; }; Sender/SendText.h #pragma once namespace Sender { class SendText { const Ctx m_ctx; const EOS_HP2P m_p2PHandle; EOS_P2P_SocketId m_sendSocketId; EOS_P2P_SendPacketOptions m_options; template<typename T> void sendPacket_(const T &messageData) { const size_t maxDataLengthBytes = Networking::c_MaxDataSizeBytes; auto it = messageData.begin( ); while ( it != messageData.end( ) ) { const size_t distance = std::distance( it, messageData.end( ) ); const size_t dataLengthBytes = std::min( maxDataLengthBytes, distance ); m_options.DataLengthBytes = static_cast< uint32_t >( dataLengthBytes ); m_options.Data = std::addressof( *it ); ::EOS_P2P_SendPacket( m_p2PHandle, &m_options ); // error checking has been ommited for "codereview" it += dataLengthBytes; } }
{ "domain": "codereview.stackexchange", "id": 45255, "lm_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", "url": null }
c++, networking public: SendText(const Ctx &ctx, uint8_t channel) : m_ctx( ctx ) , m_p2PHandle( ::EOS_Platform_GetP2PInterface( ctx.m_PlatformHandle ) ) , m_sendSocketId{ EOS_P2P_SOCKETID_API_LATEST } , m_options{ EOS_P2P_SENDPACKET_API_LATEST } { strcpy_s( m_sendSocketId.SocketName , m_ctx.m_SocketName.c_str( ) ); m_options.LocalUserId = m_ctx.m_LocalUserId; m_options.RemoteUserId = m_ctx.m_FriendLocalUserId; m_options.SocketId = &m_sendSocketId; m_options.bAllowDelayedDelivery = EOS_TRUE; m_options.Channel = channel; m_options.Reliability = EOS_EPacketReliability::EOS_PR_ReliableOrdered; m_options.bDisableAutoAcceptConnection = EOS_FALSE; } void send(const std::string &value) { sendPacket_( value ); } }; } // namespace Sender Receiver/RecvText.h #pragma once namespace Receiver { class RecvText { const Ctx m_ctx; const EOS_HP2P m_p2PHandle; EOS_P2P_SocketId m_receiveSocketId; EOS_P2P_ReceivePacketOptions m_options; const uint8_t m_channel = 0; // If NULL, we're retrieving the size of the next packet on any channel const uint8_t* m_requestedChannel = &m_channel; public: RecvText(const Ctx &ctx, uint8_t channel) : m_ctx( ctx ) , m_p2PHandle( ::EOS_Platform_GetP2PInterface( ctx.m_PlatformHandle ) ) , m_receiveSocketId{ EOS_P2P_SOCKETID_API_LATEST } , m_options{ EOS_P2P_RECEIVEPACKET_API_LATEST } , m_channel( channel ) { strcpy_s( m_receiveSocketId.SocketName , m_ctx.m_SocketName.c_str( ) ); m_options.LocalUserId = m_ctx.m_LocalUserId; m_options.MaxDataSizeBytes = Networking::c_MaxDataSizeBytes; m_options.RequestedChannel = m_requestedChannel; }
{ "domain": "codereview.stackexchange", "id": 45255, "lm_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", "url": null }
c++, networking Networking::messageData_t receive(size_t len) { EOS_ProductUserId unused_; Networking::messageData_t messageData( m_options.MaxDataSizeBytes ); uint32_t bytesWritten = 0; uint8_t outChannel = 0; EOS_EResult result = ::EOS_P2P_ReceivePacket( m_p2PHandle, &m_options , &unused_, &m_receiveSocketId, &outChannel, messageData.data( ), &bytesWritten ); // error checking has been ommited for "codereview" if ( EOS_EResult::EOS_NotFound == result ) return { }; messageData.resize( bytesWritten ); return messageData; } }; } // namespace Receiver Sending.h #pragma once class Sending { Ctx m_ctx; uint8_t m_channel; public: Sending(const Ctx &ctx, uint8_t channel = 0) : m_ctx( ctx ) , m_channel( channel ) {} void text(const std::string &text) { auto executor = std::make_unique< Sender::SendText >( m_ctx, m_channel ); auto command = detail_::make_action( QueueCommands::Direction::Outgoing , [text] (const std::unique_ptr< Sender::SendText > &p) { p ->send( text ); return Networking::messageData_t{ }; } , std::move( executor ) ); QueueCommands::instance( ).push( command ); } // auto vector(const Networking::messageData_t &vector) { ... } }; Receiving.h #pragma once class Receiving { Ctx m_ctx; uint8_t m_channel;
{ "domain": "codereview.stackexchange", "id": 45255, "lm_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", "url": null }
c++, networking Receiving.h #pragma once class Receiving { Ctx m_ctx; uint8_t m_channel; public: Receiving(const Ctx &ctx, uint8_t channel = 0) : m_ctx( ctx ) , m_channel( channel ) {} void text(size_t len) { auto executor = std::make_unique< Receiver::RecvText >( m_ctx, m_channel ); auto accumulator = std::make_unique< Networking::messageData_t >( ); auto command = detail_::make_action( QueueCommands::Direction::Incoming , [len] ( const std::unique_ptr< Receiver::RecvText > &executor , const std::unique_ptr< Networking::messageData_t > &buf ) { Networking::messageData_t messageData = executor ->receive( len ); if ( !messageData.empty( ) && messageData.size( ) != len ) { // accumulate std::copy( messageData.begin( ), messageData.end( ), std::back_inserter( *buf ) ); // until requirement size if ( buf ->size( ) == len ) return *buf; return Networking::messageData_t{ }; } return messageData; } , std::move( executor ) , std::move( accumulator ) ); QueueCommands::instance( ).push( command ); } //auto vector(size_t len) { ... } }; demo main.cpp #include "pch.h" #include "Deferred/QueueCommands.h" #include "Deferred/Action.h" #include "Deferred/Sender/SendText.h" #include "Deferred/Receiver/RecvText.h" #include "Deferred/Sending.h" #include "Deferred/Receiving.h"
{ "domain": "codereview.stackexchange", "id": 45255, "lm_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", "url": null }
c++, networking int main(int argc, char *argv[]) { bool isServer = ( argc > 1 ); Ctx ctx = createContext( isServer ); QueueCommands::init( ctx.m_PlatformHandle ); ConnectionRequestListener::AcceptEveryone acceptEveryone( ctx ); const std::string text0 = "ping1", text1 = "ping2"; if ( isServer ) { Receiving receiving( ctx ); receiving.text( text0.length( ) ); receiving.text( text1.length( ) ); auto incoming = QueueCommands::instance( ).ticksAll( ); assert( ( text0 == std::string( incoming[ 0 ].begin( ), incoming[ 0 ].end( ) ) ) ); assert( ( text1 == std::string( incoming[ 1 ].begin( ), incoming[ 1 ].end( ) ) ) ); } else { Sending sending( ctx ); sending.text( text0 ); sending.text( text1 ); QueueCommands::instance( ).ticksAll( ); } return printf( "press [Enter] to exit" ), getchar( ); } Synchronization of access to methods is intentionally not implemented here; The topic of multithreading support will be discussed later. Intentionally omitted handling of critical call errors and UDP deficiencies. I know that using a template in the class Action (@insp SO) increases the size of the binary file, but willing to sacrifice that for the sake of the usability of the deducer detail_::make_action. I chose the deferred sending/receiving approach because of the need to cause "ticks" for the network to work, but we had to accumulate sending and receiving commands somewhere. Queue singleton to select to reduce the number of arguments passed between functions, besides, if there is only one tick, then the first thing that comes to mind is the queue in a single copy, although I am against global variables and this review could have been done without them (shared_ptr are passed between all participants...). Full code on GitHub repo Regards, Alex0vSky
{ "domain": "codereview.stackexchange", "id": 45255, "lm_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", "url": null }
c++, networking Answer: Separate concerns Try to separate concerns in your code where possible. For example, your QueueCommands deals with too many things at the same time: it is a queue, it knows about commands, and it deals with network I/O. It's better to have it just be a queue, all other functions can be handled outside the class. Avoid singletons While you might only need one command queue in your program, that does not mean it has to be a singleton class. You could just declare a single instance of the queue, either as a global variable, as a local variable of which you pass a reference to other objects and functions as necessary, or perhaps it's best part of another object. For example, in most places where you call QueueCommands::instance(), you also have a reference to a Ctx. Maybe you can make the queue part of Ctx? Avoid making everything a class There is no need in C++ to put everything into a class. In many cases, free functions are perfectly fine. For example, Sending and Receiving are classes with just one member function text(). Why not pass the context and channel to text()? In that case you don't need member variables anymore, and text() can be made a free function. For example: void sendText(const Ctx &ctx, uint8_t channel, const std::string &text) { … } void receiveText(const Ctx &ctx, uint8_t channel, std::size_t len) { … } Classes should not be used for actions, they should be for objects. If anything, you could make a class Channel, that represents a channel as an object, and then have send() and receive() member functions: class Channel { … public: Channel(const Ctx &ctx, uint8_t channel): … {} void send(const std::string &text) {…} void receive(std::size_t len) {…} };
{ "domain": "codereview.stackexchange", "id": 45255, "lm_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", "url": null }
c++, networking You are also needlessly complicating things by having SendText and ReceiveText classes. These might have some value if objects are constructed once, and send() and receive() called many times on them, but they seem just to be used for one-shot sends and receives. Again, why not make them free functions to do the low-level send and receive? Use std::function Apart from having a Direction, an Action is just a reimplementation of std::function. Just use std::function instead, and add whatever you need on top of that. Consider: struct Command { Direction m_direction; std::function<Networking::messageData_t(bool)> action; }; struct Ctx { … std::queue<Command> commandQueue; auto processAll() { std::vector<Networking::messageData_t> allIncomingData; while (!commandQueue.empty()) { auto& command = commandQueue.front(); if (Direction::Outgoing == command.direction) { command.action(m_avoidPush); … } else { … } } return allIncomingData; } … }; And to send something: class Channel { Ctx &m_ctx; … public: … void send(const std::string &text) { m_ctx.commandQueue.emplace_back(Direction::Outgoing, [&m_ctx, m_channel, text] { sendText(m_ctx, m_channel, text); } ); } }; And finally, the low-level send function itself can look like this: void sendText(const Ctx &ctx, uint8_t channel, const std::string &text) { EOS_P2P_SendPacketOptions m_options; m_options.LocalUserId = m_ctx.m_LocalUserId; … while (…) { … ::EOS_P2P_SendPacket(ctx.m_PlatformHandle, m_options); … } }
{ "domain": "codereview.stackexchange", "id": 45255, "lm_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", "url": null }
c++, networking Consider using std::packaged_task If you are receiving data, you collect the received data into the vector allIncomingData, which is returned from ticksAll(). It's easy if you only receive a few things when calling ticksAll(), but if your code gets more complicated and wants to receive lots of things between calls, or if it doesn't exactly know when ticksAll() gets called, it can become messy to get that data. Wouldn't it be much nicer if you could return the data somehow directly from the send call, but in such a way you get the results asynchronously? That's what std::future is made for. Your calling code could then look like this: Ctx ctx = …; … if (isServer) { result0 = ctx.receive(text0.length()); result1 = ctx.receive(text1.length()); ctx.processAll(); assert(text0 == result0.get()); assert(text1 == result1.get()); } Instead of storing std::functions in the queue, you should then store std::packaged_tasks instead. The drawback of this is that you can forget to call processAll() before trying to get the result, which would then cause get() to wait indefinitely for the future result to appear. If you had a separate thread processing commands, that would not be an issue.
{ "domain": "codereview.stackexchange", "id": 45255, "lm_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", "url": null }
python, ssh Title: Is it a correct way to read a file contents using paramiko (SSH, SFTP client)? Question: Is my implementation of _read_contents (3 lines) fine, or does it create a potential problem (e.g. passing part of an object that has to be destroyed, or a connection that cannot be closed, etc.)? I don't need the review of the general design, only these 3 lines. import paramiko ################################################################################# class StorageSFTP: def __init__(self, ssh_client_params): self.ssh_client_params = ssh_client_params ############################################################################### def __enter__(self): self.ssh_client = paramiko.SSHClient() # AutoAddPolicy explained in --> https://www.linode.com/docs/guides/use-paramiko-python-to-ssh-into-a-server/ self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh_client.connect(**self.ssh_client_params) self.sftp_client = self.ssh_client.open_sftp() return self def __exit__(self, type, value, traceback): self.sftp_client.close() self.ssh_client.close() ############################################################################### def _read_contents(self, my_filename): with self.sftp_client.open(my_filename) as sftp_file: contents = sftp_file.read() return contents Usage (dummy example): with StorageSFTP({...}) as my_stft: c = my_stft._read_contents("my_filename") print(c[:100]) Answer: There's a pair of high-level isssues with this design. declaring object attributes object (session) lifetimes
{ "domain": "codereview.stackexchange", "id": 45256, "lm_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, ssh", "url": null }
python, ssh declaring object attributes object (session) lifetimes You offered example usage; thank you. I'm going to pretend it was this slightly more complex example: def retrieve_files(ssh_client_params, filename1="my_filename", filename2="another_filename"): with StorageSFTP(ssh_client_params) as my_stftp: c = my_stftp._read_contents(filename1) d = my_stftp._read_contents(filename2) return c, d That is, I'm going to assume a design where we authenticate once then retrieve several files. Creating a connection and authenticating costs roughly half a second across a WAN. We wish to amortize that cost over the retrieval of several short files. If that's not a requirement for your use case, then there's other ways to design the Public API if you get to re-authenticate once per file. declare attributes in constructor def __init__(self, ...): self.ssh_client_params = ... ##### Uggh! Please elide this ASCII art. ####### def _open(self): self.ssh_client = ... self.sftp_client = ... There are three object attributes that a maintenance engineer has to keep in mind. One of them is declared up-front in the __init__ ctor where it should be, thank you. The other two are created later in the object's lifetime. Please don't do that. You don't have to, but it is polite to tell the Gentle Reader about them by initializing each one to None if you're not quite ready for them yet. Some linters will flag this issue. I recommend that you store an open self.sftp_client attribute in __init__, and let the other (local!) variables go out of scope, as you won't need them again.
{ "domain": "codereview.stackexchange", "id": 45256, "lm_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, ssh", "url": null }
python, ssh object lifetimes You have exactly the right idea that using a with context manager helps app developers prevent resource leaks. But the OP code does not appear to work correctly, since it doesn't implement methods required by the protocol. I tried this under cPython 3.11: >>> class StorageSFTP: ... def _open(self): ... print('open') ... def _close(self): ... print('close') ... def get(self): ... print('get') ... >>> with StorageSFTP() as s: ... s.get() ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'StorageSFTP' object does not support the context manager protocol Unsurprisingly it fails. A context manager must implement __enter__ and __exit__. Usually it is more convenient to use a @contextmanager decorator. The leading _ underscore to denote a _private() method can be helpful. But here we have ignored the mandatory method names, whose spelling cannot change from the protocol spec, and we have a private _read_contents() method which should actually be part of the Public API. Just rename it to read_contents(). You may find from contextlib import closing convenient. If you're looking for an easy-to-apply pattern, just stick to using the @closing decorator. App developers will always use with to obtain an instance, and your def close will always execute at the end, even if a fatal exception happened somewhere in the app code. When you write that close method, feel free to log "Closing...", so you can convince yourself that it's happening when you anticipated. This code does not achieve its design goals. I would not be willing to delegate or accept maintenance tasks on it. EDIT: It appears the OP has altered the code. The def _open method I reviewed has been renamed to __enter__. Similarly def _close became __exit__.
{ "domain": "codereview.stackexchange", "id": 45256, "lm_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, ssh", "url": null }
c++, algorithm Title: Gaussian elimination algorithm in C++ Question: Given: j-g-h-i=0 a+b-c-j=0 c+i-d-e=0 e+g-f=0 And known: a=10 b=7 d=3 e=2 f=3 j=14 I want to solve this (or similar equations) with the Gaussian elimination algorithm, and wrote the following C++ code: #include <string> #include <vector> #include <sstream> #include <iostream> using namespace std; const int my_magic1 = 999; const int my_magic2 = -999; void printMatrix1(vector<vector<int>> &matrix1) { printf("Matrix1: (%d x %d)\n", matrix1.size(), matrix1[0].size()); for (int i = 0; i < matrix1.size(); i++) { for (int j = 0; j < matrix1[i].size(); j++) { cout << matrix1[i][j] << " "; } cout << endl; } cout << endl; } void printMatrix2(vector<int> &matrix2) { printf("Matrix2: (%d)\n", matrix2.size()); for (int i = 0; i < matrix2.size(); i++) { cout << " " << (char)('a' + i) << " "; } cout << endl; for (int i = 0; i < matrix2.size(); i++) { printf("% 3d ", matrix2[i]); } cout << endl; cout << endl; } void solveAndPrint(vector<vector<int>> &matrix1, vector<int> &matrix2) { vector<vector<int>> result(matrix1); vector<int> result2(matrix2); for (int i = 0; i < result.size(); i++) { for (int j = 0; j < result[i].size(); j++) { if (result[i][j] != 0) { if (result2[j] != my_magic1) { result[i][j] = result[i][j] * result2[j]; } else if (result[i][j] < 0) { result[i][j] = my_magic2; } else { result[i][j] = my_magic1; } } } } printMatrix1(result); printMatrix2(result2);
{ "domain": "codereview.stackexchange", "id": 45257, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm", "url": null }
c++, algorithm printMatrix1(result); printMatrix2(result2); bool changed = true; while (changed) { changed = false; for (int i = 0; i < result.size(); i++) { int magic_n = 0; int magic_i = 0; bool isneg = false; for (int j = 0; j < result[i].size(); j++) { if (result[i][j] == my_magic1 || result[i][j] == my_magic2) { magic_n++; magic_i = j; isneg = result[i][j] == my_magic2; } } if (magic_n == 1) { int sum = 0; for (int j = 0; j < result[i].size(); j++) { if (j != magic_i) { sum += result[i][j]; } } for (int k = 0; k < result.size(); k++) { if (result[k][magic_i] == my_magic1) { result[k][magic_i] = isneg ? sum : -sum; } else if (result[k][magic_i] == my_magic2) { result[k][magic_i] = isneg ? -sum : sum; } } if (result2[magic_i] == my_magic1) { result2[magic_i] = isneg ? sum : -sum; } changed = true; break; } } } printMatrix1(result); printMatrix2(result2); }
{ "domain": "codereview.stackexchange", "id": 45257, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm", "url": null }
c++, algorithm printMatrix1(result); printMatrix2(result2); } int main(int argc, char const *argv[]) { vector<string> args({"0 0 0 0 0 0 -1 -1 -1 1", "1 1 -1 0 0 0 0 0 0 -1", "0 0 1 -1 -1 0 0 0 1 0", "0 0 0 0 1 -1 1 0 0 0", "0", "10 7 - 3 2 3 - - - 14"}); vector<vector<int>> matrix1; vector<int> matrix2; for (int i = 1;; i++) { printf("Coefficients %d. row, or 0:\n", i); string l; // getline(cin, l); l = args[i - 1]; cout << l << endl; if (l == "0") { break; } stringstream ss; ss << l; string segment; vector<int> v; while (getline(ss, segment, ' ')) { v.push_back(stoi(segment)); } matrix1.push_back(v); } { cout << "Known, or just - if unknown:" << endl; string l; // getline(cin, l); l = args[args.size() - 1]; cout << l << endl; stringstream ss; ss << l; string segment; while (getline(ss, segment, ' ')) { if (segment == "-") { matrix2.push_back(my_magic1); } else { matrix2.push_back(stoi(segment)); } } } solveAndPrint(matrix1, matrix2); return 0; } I would like to get a code review, and how I can avoid my_magic1 and my_magic2.
{ "domain": "codereview.stackexchange", "id": 45257, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm", "url": null }
c++, algorithm I would like to get a code review, and how I can avoid my_magic1 and my_magic2. Answer: Adding to pacmaninbw's answer: Naming things matrix2 is not a matrix, it's a vector. I would just call it a vector to avoid any confusion. Of course, since you used using namespace std, you can't name a variable vector anymore. Either don't use using namespace std, or rename matrix2 to vec, or instead of naming variables after its type, name it after what they represents. For example, matrix1 could be renamed to coefficients, and matrix2 to constant_terms (as that is how they are named in the system of linear equations). Another thing you can do is create new types or type aliases that represent matrices and vectors. For example: using Matrix = std::vector<std::vector<int>>; using Vector = std::vector<int>; That way you can write: void solveAndPrint(const Matrix& system, const Vector& constant_terms) { … } Group related data The coefficients and the constant terms together form the system of linear equations. You could group them into a struct: struct System { Matrix coefficients; Vector constant_terms; }; That way you only have to pass one variable to solveAndPrint(): void solveAndPrint(const System& system) { … } Alternatively, consider that in mathematics, a system of linear equations is often written as an augmented matrix. You could do the same in your code. Printing Instead of having to call a function to print a matrix, wouldn't it be nice if you could just write something like this? std::cout << matrix1; This is actually easy to do. You just need to create an overload for the <<-operator. You can reuse most of your printMatrix1() for this: std::ostream& operator<<(std::ostream& out, const Matrix& matrix) { out << "Matrix: (" << matrix.size() << " x " << matrix[0].size() << ")\n"; for (auto& row: matrix) { for (auto& value: row) { out << value << ' '; } out << '\n'; } return out << '\n'; }
{ "domain": "codereview.stackexchange", "id": 45257, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm", "url": null }
c++, algorithm Note that this function is no longer hardcoded to print to std::cout, so now you can also print to std::cerr, to a std::stringstream or to a file. Of course, you can also do the same for printMatrix2(). Return values from functions pacmaninbw already mentioned splitting up solveAndPrint(). Make a solve() function that returns the result. Of course, you can only return one thing from a function, but as shown above, you can always group things into a struct. If you reuse System, then you can write: System solve(const System& input) { System result = input; for (auto& row: result.coefficients) { … } … return result; } Also consider creating a function that reads the system of linear equations from the command line or standard input. Then your main() can be simplified to: int main(int argc, char* argv[]) { System input = readInput(…); System result = solve(input); std::cout << result.coefficients; std::cout << result.constant_terms; } Getting rid of the magic constants You are correct in wanting to avoid the magic constants my_magic1 and my_magic2. What if the input contained those numbers? The correct way to solve this is to create a new type that can store either a number or the state "unknown". If it's unknown, you also want to track if the sign was negative or positive during the algorithm. I see two ways to solve this: Use std::variant together with an enum class that indicates positive or negative unknown: enum class Unknown { POSITIVE, NEGATIVE, }; using Value = std::variant<int, Unknown>; using Matrix = std::vector<std::vector<Value>>; Variants are a bit cumbersome to work with in C++ though. The alternative is: Use a struct that combines both a number and a flag to indicate whether this is an unknown or not. If it is an unknown, you could keep the original value, or store 1 or -1 in the number to indicate positive/negative: struct Value { int value; bool unknown; };
{ "domain": "codereview.stackexchange", "id": 45257, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm", "url": null }
c++, algorithm using Matrix = std::vector<std::vector<Value>>; This way the code in solve() could look like: for (int i = 0; i < result.size(); i++) { for (int j = 0; j < result[i].size(); j++) { if (result[i][j].value != 0) { if (!result2[j].unknown) { result[i][j].value *= result2[j].value; } else { // keep original value, but mark it as unknown result[i][j].unknown = true; } } } } … Other minor issues Use const references where appropriate.
{ "domain": "codereview.stackexchange", "id": 45257, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm", "url": null }
python-3.x, excel, xml Title: Python script to read an XML file and write some information to an Excel file Question: I'm getting an XML file from an application, want to extract some information from that file and write it to an Excel file. The XML file contains data about vacations. I need data from the last month with an approval status 1, 5 or 6. The following function returns the month and year: def set_month(): year = time.localtime()[0] month = time.localtime()[1] if month == 1: month = 12 year -= 1 else: month -= 1 return (year, month) I assume there is a better way to do this. Below you'll find the complete script and an example XML file. I'd be happy about any ideas to improve the code. #!/usr/bin/env python3 # file: urlaub.py # desc: Reads a xml file created from another software. This file contains # vacation requests. This program search all vacation requests for the month # ago, grabs the relevant informations and write they into an excel file. # # possible exit status if the program does not crash: # 0: all clear # 1: you hav a double character in your wantedInfos directory # 2: failed to read the xml file or to get the tree root # 3: failed to write the excel file import time import logging from sys import exit import datetime as dt from openpyxl import Workbook as WB from openpyxl.styles import Font import xml.etree.ElementTree as ET # --- logging --- # def configure_logging(loglevel): ''' Configure logging settings. param 1: integer ''' formatstring = "%(levelname)-8s %(message)s" logging.basicConfig(format=formatstring, level=loglevel) logging.info("Loglevel set to {}".format(loglevel)) # --- misk --- #
{ "domain": "codereview.stackexchange", "id": 45258, "lm_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, excel, xml", "url": null }
python-3.x, excel, xml # --- misk --- # def check_doubles(): ''' Checks for double (column) characters in the wantedInfos dictionary. ''' char_list = [] logging.debug("Check for double cell characters") for dictionary in (wantedInfos, interestedAbsence): for key in dictionary.keys(): character = dictionary[key]["Col"] if character in char_list: logging.error("Double cell character found: {}".format(character)) exit(1) char_list.append(character) logging.debug("Character list {}".format(sorted(char_list))) # --- xml processing --- # def set_month(): ''' Searchs for the month ago. Returns year and month as string. returns: tuple of strings ''' year = time.localtime()[0] month = time.localtime()[1] if month == 1: month = 12 year -= 1 else: month -= 1 logging.info("Search for vacation requests in {} {}".format(month, year)) return (year, month) def absence_is_relevant(absence): ''' Checks if the given absence is relevant. This includes an check for time and also for approval status. param 1: xml element returns: boolean ''' start = absence.find(get_path(["Beginning"])) date = start.text.split("T") logging.debug("Test absence for {}".format(date)) year, month, day = date[0].split("-") if int(year) == wantedYear and int(month) == wantedMonth: logging.debug("Absence is relevant") status = absence.find(get_path(["ApprovalStatus"])) if int(status.text) in (0, 2, 4): logging.debug("Status is {} ... skip.".format(status.text)) return False return True logging.debug("Absence is not relevant") return False
{ "domain": "codereview.stackexchange", "id": 45258, "lm_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, excel, xml", "url": null }
python-3.x, excel, xml def request_is_relevant(request): ''' Checks if the given request is relevant. Walks through the absence list and calls absence_is_relevant for every absence found. param 1: xml tree element returns: boolean ''' guid_main = request.find(get_path(["GUID"])) name = request.find(get_path(["RequestorFullName"])) logging.debug("Test for relevanz: {}".format(guid_main.text)) for absence in request.findall(get_path(["AbsenceList", "Absence"])): if absence_is_relevant(absence) is True: logging.debug("Request is relevant") return True logging.debug("Request is not relevant") return False def get_path(part_list): ''' Because i cannot access the data only with the tag name, we add the namespace for every tree level. param 1: list returns: string ''' parts = [] for tag in part_list: parts.append(get_full_tag(tag)) path = "/".join(parts) return path def get_full_tag(tag): ''' Adds the namespace to an single xml tag. param 1: string returns: string ''' return "".join((ns, tag)) def crop_namespace(node): ''' param 1: string returns: string or none ''' if node is None: return None return node.tag.split("}")[1].strip() def process_request(request): ''' Processes the given request. We walk two times through all keys from the wantedInfos dictionary. First time we collect all data for keys flagged with "Abs" is false. Second time we walk through all branches from absence list. If the absence is relevant, we collect all data for keys flagged with true. These data will be stored in a subdictionary with absenceCounter as key. param 1: xml-tree object returns: dictionary ''' currentRequest: dict = {'AbsenceList': {}, } relevantCounter = 0 absenceCounter = 0
{ "domain": "codereview.stackexchange", "id": 45258, "lm_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, excel, xml", "url": null }
python-3.x, excel, xml guid_main = request.find(get_path(["GUID"])) name = request.find(get_path(["RequestorFullName"])) logging.debug("Processing {}: {}".format(guid_main.text, name.text)) # collect request level information for key in wantedInfos.keys(): if wantedInfos[key]['Abs'] is False: path = get_path(wantedInfos[key]["Path"]) logging.debug("Search for key '{}' '{}'".format(key, path)) node = request.find(path) logging.debug("Found node '{}'".format(crop_namespace(node))) if node is None: value = None else: value = node.text currentRequest[key] = value logging.debug("Store: key: {}, value: '{}'".format(key, value)) # walk through absence list and collect absence level informations for absence in request.findall(get_path(["AbsenceList", "Absence"])): absenceCounter += 1 guid_abs = absence.find(get_path(["VacationRequestGUID"])) logging.debug("{}. Abs: {}".format(absenceCounter, guid_abs.text)) if absence_is_relevant(absence) is False: logging.debug("Skip absence") continue logging.debug("Processing absence") relevantCounter += 1 currentRequest['AbsenceList'][relevantCounter] = {} for key in wantedInfos.keys(): if wantedInfos[key]['Abs'] is True: path = get_path(wantedInfos[key]['Path']) value = absence.find(path).text currentRequest['AbsenceList'][relevantCounter][key] = value logging.debug("Store: key: '{}', value: '{}'".format(value, key)) return currentRequest def xml_to_list(): ''' Collects the wanted informations from a xml tree and store these data in a list of dictionarys. returns: list of dictinaries ''' counter = 0 relevant = 0 allVacations = []
{ "domain": "codereview.stackexchange", "id": 45258, "lm_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, excel, xml", "url": null }
python-3.x, excel, xml # read the xml tree from file and grab tree root try: tree = ET.parse(xmlfile) logging.debug("Reading xml-file {} successful".format(xmlfile)) root = tree.getroot() except Exception as error: logging.error("Failed to get xml-tree root.") logging.error(error) exit(2) # iterate over all vacation requests and check if the request is # relevant. for request in root.findall(get_full_tag("VacationRequests")): counter += 1 logging.debug("* {}. New request found".format(counter)) guid = request.find(get_path(["GUID"])) name = request.find(get_path(["RequestorFullName"])) logging.debug("{}: {}".format(guid.text, name.text)) if request_is_relevant(request) is False: continue else: # if request is relevant call function to grab all needed data. relevant += 1 logging.debug("Relevant entry found: {}".format(relevant)) currentRequest = process_request(request) allVacations.append(currentRequest) logging.info("{} relevant requests found".format(len(allVacations))) return(allVacations) # --- excel --- # def get_cell_name(character, number): ''' Returns an string from column character and row number. param 1: string param 2: integer returns: string ''' return "".join((character.strip(), str(number).strip()))
{ "domain": "codereview.stackexchange", "id": 45258, "lm_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, excel, xml", "url": null }
python-3.x, excel, xml def write_sheet_header(worksheet): ''' Writes the first row in the worksheet. The cell text is the key from wantedInfos. The column character comes from the keys "col" flag. We use characters because worksheet.column_dimensions cannot work with integer. param 1: worksheet object ''' row = 1 boldFont = Font(name="Calibri", bold = True) for key in wantedInfos.keys(): width = wantedInfos[key]["Width"] column = wantedInfos[key]["Col"] worksheet.column_dimensions[column].width = width cell_name = get_cell_name(column, row) cell = worksheet[cell_name] cell.font = boldFont worksheet[cell_name] = key logging.debug("Column {} was set to width {}".format(key, width)) worksheet.freeze_panes = "ZZ2" logging.debug("First row pinned") def write_cell(worksheet, row, key, value): ''' Writes "value" into a cell. The cell name is build from the wantedInfos "Col" flag for "key" and row. param 1: sheet object param 2: integer param 3: string param 4: string ''' # any values needs to convert into an readable format if key == "Art": value = absenceKindDict[value] if key == "Tage": value = int(int(value) / 2) elif key in ("Freigabe1", "Freigabe2", "Freigabe"): value = approvalStatusDict[value] elif key in ("Start", "Ende", "Eingetr."): value = dt.date.fromisoformat(value.split("T")[0]) # write column = wantedInfos[key]['Col'] cell_name = get_cell_name(column, row) worksheet[cell_name] = value if key in ("Start", "Ende", "Eingetr."): worksheet[cell_name].number_format = "dd.mm.yyyy" logging.debug("{}: '{}' written".format(cell_name, value))
{ "domain": "codereview.stackexchange", "id": 45258, "lm_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, excel, xml", "url": null }
python-3.x, excel, xml def write_excel(vacationList): ''' Becomes the vacation requests list and writes there data into an excel file. param 1: list of dictionaries ''' year = str(wantedYear) if wantedMonth in range(1, 10): month = "".join(("0", str(wantedMonth))) else: month = str(wantedMonth) fileName = "material/urlaub-{}-{}.xls".format(year, month) sheetName = " ".join(("urlaub", year, month)) logging.info("Starting to write excel file {}".format(fileName)) workbook = WB() workbook.iso_dates = True worksheet = workbook.active worksheet.title = sheetName for i in hidden_column: worksheet.column_dimensions[i].hidden = True row = 1 # set width and write header write_sheet_header(worksheet) # process all requests for request in allVacations: row += 1 logging.debug("Write request into row {}: {} {}".format(row, \ request["GUID-R"], request["Name"])) # write the main request data for key in request.keys(): if key == "AbsenceList": continue else: write_cell(worksheet, row, key, request[key]) # then we write the absence data for absence_nr in request["AbsenceList"].keys(): if absence_nr > 1: row += 1 guida = request["AbsenceList"][absence_nr]["GUID-A"] logging.debug("Write absence into row {}: {} {}".format(row, \ absence_nr, guida)) for key in request["AbsenceList"][absence_nr].keys(): value = request["AbsenceList"][absence_nr][key] write_cell(worksheet, row, key, value) logging.info("{} absence request written.".format(row - 1)) try: workbook.save(fileName) logging.info("Excel file successful written") except Exception as error: logging.critical("Failed to write excel file") exit(3) # --- start program --- #
{ "domain": "codereview.stackexchange", "id": 45258, "lm_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, excel, xml", "url": null }
python-3.x, excel, xml xmlfile = "material/urlaubsantraege.xml" ns = "{urn:orkan-software.de:schema:ORKAN}" wantedInfos = { # "Eingetr.": {"Abs": False, "Col": "A", "Width": 12, "Path": ["DateAdd"]}, # "Kurzname": {"Abs": False, "Col": "B", "Width": 15, "Path": ["RequestorMaMatch"]}, "Name": {"Abs": False, "Col": "C", "Width": 25, "Path": ["RequestorFullName"]}, # "Tage": {"Abs": False, "Col": "D", "Width": 8, "Path": ["RequestedHalfDays"]}, #"Typ": {"Abs": True, "Col": "E", "Width": 8, "Path": ["AbsenceType"]}, # "Freigabe1": {"Abs": False, "Col": "E", "Width": 12, "Path": ["Approval1ApprovalStatus"]}, "Freigabe1-Name": {"Abs": False, "Col": "F", "Width": 16, "Path": ["Approval1MaMatch"]}, # "Freigabe2": {"Abs": False, "Col": "G", "Width": 12, "Path": ["Approval2ApprovalStatus"]}, "Freigabe2-Name": {"Abs": False, "Col": "H", "Width": 16, "Path": ["Approval2MaMatch"]}, "Freigabe": {"Abs": True, "Col": "I", "Width": 15, "Path": ["ApprovalStatus"]}, "Art": {"Abs": True, "Col": "J", "Width": 15, "Path": ["AbsenceKindGuid"]}, "Start": {"Abs": True, "Col": "K", "Width": 12, "Path": ["Beginning"]}, "Ende": {"Abs": True, "Col": "L", "Width": 12, "Path": ["Ending"]}, "GUID-A": {"Abs": True, "Col": "M", "Width": 45, "Path": ["VacationRequestGUID"]}, "GUID-R": {"Abs": False, "Col": "N", "Width": 45, "Path": ["GUID"]}, # "Grund": {"Abs": False, "Col": "O", "Width": 40, "Path": ["RejectionReason"]}, # "Kommentar": {"Abs": False, "Col": "P", "Width": 50, "Path": ["RequestorComment"]} } interestedAbsence: dict = { } absenceKindDict = { "{953D3EA0-CB6A-477F-83F1-C1B4939BA0FD}": "Bildungsurlaub", "{DECF84D7-ADD8-4785-AD55-662B8F70C158}": "Lehrgang HWK", "{945EB227-B3E2-4EFF-831E-8D7D1A08281D}": "Resturlaub", "{EFC603E1-5CAF-4153-ADF9-A035440E34CD}": "Sonderurlaub", "{3F43AC39-6132-4397-B236-7D45F9E43019}": "Jahresurlaub" } approvalStatusDict = {
{ "domain": "codereview.stackexchange", "id": 45258, "lm_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, excel, xml", "url": null }