text stringlengths 1 2.12k | source dict |
|---|---|
c, parsing, file
return 0;
}
void getDigits(char* src, int* dest) {
int len = strlen(src);
// Get first digit
for (int i = 0; i < len; i++) {
if (!strncmp("zero", src+i, 4)) {
dest[0] = 0;
break;
}
if (!strncmp("one", src+i, 3)) {
dest[0] = 1;
break;
}
if (!strncmp("two", src+i, 3)) {
dest[0] = 2;
break;
}
if (!strncmp("three", src+i, 5)) {
dest[0] = 3;
break;
}
if (!strncmp("four", src+i, 4)) {
dest[0] = 4;
break;
}
if (!strncmp("five", src+i, 4)) {
dest[0] = 5;
break;
}
if (!strncmp("six", src+i, 3)) {
dest[0] = 6;
break;
}
if (!strncmp("seven", src+i, 5)) {
dest[0] = 7;
break;
}
if (!strncmp("eight", src+i, 5)) {
dest[0] = 8;
break;
}
if (!strncmp("nine", src+i, 4)) {
dest[0] = 9;
break;
}
if (src[i] > 47 && src[i] < 58) { // 48 -> 57 ASCII => number
dest[0] = src[i] - 48;
break;
}
} | {
"domain": "codereview.stackexchange",
"id": 45464,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, file",
"url": null
} |
c, parsing, file
// Get second digit
for (int i = len-1; i >= 0; i--) {
if (!strncmp("zero", src+i-3, 4)) {
dest[1] = 0;
break;
}
if (!strncmp("one", src+i-2, 3)) {
dest[1] = 1;
break;
}
if (!strncmp("two", src+i-2, 3)) {
dest[1] = 2;
break;
}
if (!strncmp("three", src+i-4, 5)) {
dest[1] = 3;
break;
}
if (!strncmp("four", src+i-3, 4)) {
dest[1] = 4;
break;
}
if (!strncmp("five", src+i-3, 4)) {
dest[1] = 5;
break;
}
if (!strncmp("six", src+i-2, 3)) {
dest[1] = 6;
break;
}
if (!strncmp("seven", src+i-4, 5)) {
dest[1] = 7;
break;
}
if (!strncmp("eight", src+i-4, 5)) {
dest[1] = 8;
break;
}
if (!strncmp("nine", src+i-3, 4)) {
dest[1] = 9;
break;
}
if (src[i] > 47 && src[i] < 58) {
dest[1] = src[i] - 48;
break;
}
}
}
Is there any way to optimize the "spelled out numbers" checking?
Answer: It's normal to write main() as the last function, so there's no need to forward-declare getDigts(). We would normally make that function static unless there's a good reason to share it with other translation units.
getline() isn't a portable (standard C) function. Assuming that you're using the function specified by POSIX, then the memory it allocates ought to be released using free(). Not doing that causes Valgrind warnings - it's easier to fix real problems if we clean up properly.
Risky conversion here:
int len = strlen(src);
strlen() returns a size_t, not int.
There's an assumption about character coding here:
if (src[i] > 47 && src[i] < 58) { // 48 -> 57 ASCII => number
dest[0] = src[i] - 48;
break;
} | {
"domain": "codereview.stackexchange",
"id": 45464,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, file",
"url": null
} |
c, parsing, file
We don't need to assume we're running in an ASCII environment, because we can use isdigit() (from <ctype.h>) and the abstract character '0' instead of a numeric code-point.
You correctly identified the repetition in getDigits as a problem. Other problems in this repetitious section include having to write out the length of each string in strncmp and matching each string with a digit value.
These problems can all be solved if we create an array of the digit names:
const char *const names[10] =
{ "zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine" };
We can then use a loop over this array to replace the repeated code, using strlen() to decide how many characters to compare, and the loop index for the numeric value. Like this:
static int find_first_digit(const char *src)
{
const size_t len = strlen(src);
for (size_t i = 0; i < len; ++i) {
if (isdigit((unsigned char)src[i])) {
return src[i] - '0';
}
for (int d = 0; d < 10; ++d) {
if (!strncmp(names[d], src+i, strlen(names[d]))) {
return d;
}
}
}
return -1; // or perhaps 0?
}
I'll leave the corresponding find_last_digit() as an exercise. | {
"domain": "codereview.stackexchange",
"id": 45464,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, parsing, file",
"url": null
} |
c, programming-challenge, string-processing
Title: Advent of Code 2023 day 1: Trebuchet (Part 1 and 2) Follow-up
Question: This is a follow-up to the question asked here: Advent of Code 2023 day 1:
Trebuchet (Part 1 and 2)
Changes made:
The code no longer assumes that all lines will fit into a fixed-size buffer. Although a fixed-size buffer is used, the code now checks whether a partial line was read. It continues processing and updating the first and last digits until the End of Line (EOL) is encountered. In case a partial line was read, the last 5 characters of the buffer are copied to the front (5 because the length of the longest digit name, such as eight or seven, is 5). The next read then starts 5 characters past the beginning of the buffer.
Error handling has been added.
Proper sizes have been utilized (attempted).
There was a memory leak in the code because the FILE * was not passed to fclose(). This issue has been fixed.
Another member has been added to the digit_map structure that keeps track of the number of bytes that can be skipped after a digit name has been matched in part 2 of the problem. This improvement saves us multiple unnecessary iterations.
For every non-numeric character, around 9 calls to strncmp() were being made. Whilst a prefix tree or similar structure hasn't been implemented or used, a check has been added to verify if the non-numeric character begins any digit before making all the comparisons.
Review request:
Are there any flaws or bugs in what I have implemented so far? Have I missed any cases? Do you see any off-by-one errors?
Any general suggestions, style improvements, or potential undefined behavior et cetera.
Part 1:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>
#include <stdint.h>
#define BUFSIZE 256
struct digit_pair {
unsigned int first;
unsigned int last;
};
static struct digit_pair first_last_digits(const char *buf)
{
unsigned int first = 0;
unsigned int last = 0; | {
"domain": "codereview.stackexchange",
"id": 45465,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, programming-challenge, string-processing",
"url": null
} |
c, programming-challenge, string-processing
/* Note: This would return true for 0, but 0 is not part of the
* problem specification, or the input, so we don't need to check
* for it.
*/
for (size_t i = 0; buf[i]; ++i) {
if (isdigit((unsigned char) buf[i])) {
first = !first ? buf[i] - '0' : first;
last = buf[i] - '0';
}
}
return (struct digit_pair) { first, last };
}
static uintmax_t calibration_total(FILE *stream)
{
char buf[BUFSIZE];
uintmax_t total = 0;
unsigned int first = 0;
unsigned int last = 0;
while (fgets(buf, sizeof buf, stream)) {
/* If EOL was seen, parse it normally.
* Else keep the intermediate first value, and continue updating last
* until the EOL is actually seen.
*/
struct digit_pair new = first_last_digits(buf);
if (!first) {
first = new.first;
}
if (new.last) {
last = new.last;
}
const size_t len = strlen(buf);
if (len > 0 && buf[len - 1] != '\n') {
continue;
}
total += first * 10 + last;
first = last = 0;
}
return total;
}
int main(int argc, char **argv)
{
if (!argv[0]) {
fputs("Fatal - A null argv[0] was passed in.", stderr);
return EXIT_FAILURE;
}
if (argc != 2) {
fprintf(stderr, "Error - No file provided.\n"
"Usage: %s <FILE>\n", argv[0]);
return EXIT_FAILURE;
}
errno = 0;
FILE *const file = fopen(argv[1], "r");
if (!file) {
if (errno) {
perror(argv[1]);
} else {
fputs("Error - Failed to open file.fputs\n", stderr);
}
return EXIT_FAILURE;
}
const uintmax_t total = calibration_total(file);
if (ferror(file) || !feof(file)) {
fclose(file);
fputs("Error - Failed to read file.\n", stderr);
return EXIT_FAILURE;
} | {
"domain": "codereview.stackexchange",
"id": 45465,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, programming-challenge, string-processing",
"url": null
} |
c, programming-challenge, string-processing
printf("%ju\n", total);
fclose(file);
return EXIT_SUCCESS;
}
Part 2:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>
#include <stdint.h>
#define BUFSIZE 256
struct digit_pair {
unsigned int first;
unsigned int last;
};
struct digit_map {
const char *const dname;
const unsigned int val;
const unsigned int bytes_skippable; /* On a match, we can skip this amount. */
} digits[] = {
{ "one", 1, 1 },
{ "two", 2, 1 },
{ "three", 3, 3 },
{ "four", 4, 3 },
{ "five", 5, 2 },
{ "six", 6, 2 },
{ "seven", 7, 3 },
{ "eight", 8, 4 },
{ "nine", 9, 2 }
};
/* The author was not ready to part with this piece of code, so this has been commented out. */
/*static size_t get_next_pos(const char *buf) */
/*{ */
/* /1* */
/* * "one" --- Skip 1 char, as 'e' might start "eight". */
/* * "two" --- Skip 1 char, as 'o' might start "one". */
/* * "three" --- Skip 3 chars, as 'e' might start "eight". */
/* * "four" --- Skip the remaining chars. */
/* * "five" --- Skip 2 chars, as 'e' might start "eight". */
/* * "six" --- Skip the remaining chars. */
/* * "seven" --- Skip 3 chars, as 'n' might start "nine". */
/* * "eight" --- Skip the remaining chars. */
/* * "nine" --- Skips 2 chars, as 'e' might start "eight". */
/* *1/ */
/* switch (buf[0]) { */
/* case 'o': return 1; */
/* case 't': return buf[1] == 'w' ? 1 : 3; */
/* case 'f': return buf[1] == 'o' ? 3 : 2; */
/* case 's': return buf[1] == 'i' ? 2 : 3; */
/* case 'e': return 4; */
/* case 'n': return 2; */
/* } */
/* /1* Now that I think of it, none of this was necessary. */
/* * Simply add another member to the digit_map struct. */
/* *1/ */
/* return 0; */
/* } */
static struct digit_pair first_last_digits(const char *buf)
{
unsigned int first = 0;
unsigned int last = 0; | {
"domain": "codereview.stackexchange",
"id": 45465,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, programming-challenge, string-processing",
"url": null
} |
c, programming-challenge, string-processing
/* Note: This would return true for 0, but 0 is not part of the
* problem specification, or the input, so we don't need to check
* for it.
*/
for (size_t i = 0; buf[i]; ++i) {
if (isdigit((unsigned char) buf[i])) {
first = !first ? buf[i] - '0' : first;
last = buf[i] - '0';
} else if (strchr("otfsen", buf[i])) { /* Check if buf[i] begins any digit. */
for (size_t j = 0; j < sizeof digits / sizeof *digits; ++j) {
if (!strncmp(buf + i, digits[j].dname, strlen(digits[j].dname))) {
first = !first ? digits[j].val : first;
last = digits[j].val;
i += digits[j].bytes_skippable - 1;
break;
}
}
}
}
return (struct digit_pair) { first, last };
}
static uintmax_t calibration_total(FILE *stream)
{
char buf[BUFSIZE];
uintmax_t total = 0;
unsigned int first = 0;
unsigned int last = 0;
size_t size = sizeof buf;
char *tmp = buf;
while (fgets(tmp, size, stream)) {
/* If EOL was seen, parse it normally.
* Else keep the intermediate first value, and continue updating last
* until the EOL is actually seen.
*/
struct digit_pair new = first_last_digits(buf);
if (!first) {
first = new.first;
}
if (new.last) {
last = new.last;
}
const size_t len = strlen(buf);
if (len > 0 && buf[len - 1] != '\n') {
/* Move the last 5 characters to the start of the buffer,
* as we'd not detect it if a digit is split into two lines,
* 5, because the length of the longest digit is 5.
*/
memmove(buf, buf + len - 5, 5);
tmp = buf + 5; | {
"domain": "codereview.stackexchange",
"id": 45465,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, programming-challenge, string-processing",
"url": null
} |
c, programming-challenge, string-processing
/* Adjust the buffer size. The check is required because each
* subsequent read without an EOL would otherwise decrease size
* by 5.
*/
size = sizeof buf - 5 == size ? size : size - 5;
continue;
}
total += first * 10 + last;
first = last = 0;
tmp = buf;
size = sizeof buf;
}
return total;
}
int main(int argc, char **argv)
{
if (!argv[0]) {
fputs("Fatal - A null argv[0] was passed in.", stderr);
return EXIT_FAILURE;
}
if (argc != 2) {
fprintf(stderr, "Error - No file provided.\n"
"Usage: %s <FILE>\n", argv[0]);
return EXIT_FAILURE;
}
errno = 0;
FILE *const file = fopen(argv[1], "r");
if (!file) {
if (errno) {
perror(argv[1]);
} else {
fputs("Error - Failed to open file.\n", stderr);
}
return EXIT_FAILURE;
}
const uintmax_t total = calibration_total(file);
if (ferror(file) || !feof(file)) {
fclose(file);
fputs("Error - Failed to read file.\n", stderr);
return EXIT_FAILURE;
}
fclose(file);
printf("%ju\n", total);
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 45465,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, programming-challenge, string-processing",
"url": null
} |
c, programming-challenge, string-processing
fclose(file);
printf("%ju\n", total);
return EXIT_SUCCESS;
}
Answer: Since Part 2 is mostly a superset of Part 1, I'll just review that.
288373.c:28:30: warning: operand of ‘?:’ changes signedness from ‘int’ to ‘unsigned int’ due to unsignedness of other operand [-Wsign-compare]
28 | first = !first ? buf[i] - '0' : first;
| ^~~~~~~~~~~~
288373.c:28:43: warning: conversion to ‘unsigned int’ from ‘int’ may change the sign of the result [-Wsign-conversion]
28 | first = !first ? buf[i] - '0' : first;
| ^
288373.c:29:20: warning: conversion to ‘unsigned int’ from ‘int’ may change the sign of the result [-Wsign-conversion]
29 | last = buf[i] - '0';
| ^~~
We could eliminate these with a small digit_value() function, or perhaps use unsigned char for our buffer.
struct digit_map {
const char *const dname;
const unsigned int val;
const unsigned int bytes_skippable; /* On a match, we can skip this amount. */
} digits[] = {
Is it really necessary to store val here, given it can be derived from the index into this array?
Even with the comment, it's not clear how bytes_skippable is computed. For example, why can we skip only 3 bytes of "three", when no digit name begins "ee"? It's harmless, of course (unlike over-skipping), but makes me question whether this optimisation is premature. It also creates more work if we were to localise to a different input language (though we could automate that, I guess).
Here's another case where the input language is baked-in:
} else if (strchr("otfsen", buf[i])) { /* Check if buf[i] begins any digit. */
We could derive that string automatically from the list of digit names, but again it's not clear that this really is an optimisation. If you have benchmark results justifying it, then it's worth including at least summary evidence in comments. | {
"domain": "codereview.stackexchange",
"id": 45465,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, programming-challenge, string-processing",
"url": null
} |
c, programming-challenge, string-processing
I wonder whether a series of strstr() might be a more efficient search method? Of course, the most efficient method would be to construct a finite-state automaton from the digit names (and actual digits, of course). That would simplify the line-handling code, as we wouldn't need to read more than one character at a time.
unsigned int first = 0;
unsigned int last = 0;
These variables wouldn't be necessary if we owned a struct digit_pair and passed it by reference to first_last_digits to populate.
char *tmp = buf;
That's a very poor name for the read insert position.
Here's another language dependency, involving a magic number that appears several times:
/* Move the last 5 characters to the start of the buffer,
* as we'd not detect it if a digit is split into two lines,
* 5, because the length of the longest digit is 5.
*/
memmove(buf, buf + len - 5, 5);
tmp = buf + 5;
Since the longest digit name is five characters, surely we only need to preserve the last four from the buffer? That's the largest amount that could be an incomplete digit name.
size = sizeof buf - 5 == size ? size : size - 5;
This is weird. At this point, we're either on the first iteration, and size is sizeof buf, or else we're on a subsequent iteration and it's sizeof buf - 5. In both cases the result is the same: sizeof buf - 5.
if (argc != 2) {
fprintf(stderr, "Error - No file provided.\n"
"Usage: %s <FILE>\n", argv[0]);
return EXIT_FAILURE;
}
The program would be much more ergonomic if it could read from standard input when a file name isn't specified. | {
"domain": "codereview.stackexchange",
"id": 45465,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, programming-challenge, string-processing",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
Title: A collection based on a bitset to store a set of unique integers from a given range (rev. 3)
Question: All right, let's do this one last time.
This is continuation of this review.
I applied most of the proposed changes, making interface of my container very close to that of std::set.
(I also added a few things that weren't explicitly mentioned but I found them on cppreference.com. For example, some type definitions like key_compare and value_compare which to be honest I don't know if I need.)
Description of the code:
This is an implementation of a set data structure.
It is optimized to efficiently store a huge amount of unsigned integers (even billions) from a range specified at construction (it always starts at 0).
It it used in very expensive computations so the main goal of this implementation (beside the memory efficiency) is performance.
The most important (for my goals) properties of this set are random read/write access in O(1) time, checking its size in O(1) time and an iterator that can continue iteration after changes in the set are made.
Additionally, the set is kept sorted because of how it is implemented.
This collection is not intended for storing small number of integers from a huge possible range. In such case the memory optimization is terrible and iteration takes too long.
(This is not the case in my program where on average half of the integers from the range is in the set.)
The goal of the review:
In my opinion the code is pretty good and it may need a few finishing touches at the most.
However, that's what I was thinking the last time and you guys proved me very wrong.
Actually, I'm not sure if declaring a goal is all that productive. If I can think it before the review, I can probably find the problem without help. Tell me about things I didn't think about. Go nuts.
However, changes that sacrifice performance for clean code are still off limits.
The code:
CompactSet.hh:
#pragma once | {
"domain": "codereview.stackexchange",
"id": 45466,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
#include <algorithm>
#include <cassert>
#include <concepts>
#include <functional>
#include <iterator>
#include <limits>
#include <utility>
#include <vector> | {
"domain": "codereview.stackexchange",
"id": 45466,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
// This container can store unique numbers in range 0..capacity-1 using only about capacity/CHAR_BIT bytes of memory.
// (The memory usage is the same regardles of how many numbers are stored.)
template<std::unsigned_integral T>
class CompactSet
{
public:
using key_type = T;
using value_type = T;
using size_type = std::vector<bool>::size_type;
using difference_type = std::vector<bool>::difference_type;
using key_compare = std::less<key_type>;
using value_compare = std::less<value_type>;
using pointer = T*;
using reference = T&;
private:
std::vector<bool> bits;
size_type size_ = 0;
public:
class iterator
{
const std::vector<bool> *bits = nullptr;
size_type i;
iterator(const std::vector<bool> &bits, const size_type i) : bits(&bits), i(i) { }
friend class CompactSet<T>;
public:
using value_type = T;
using pointer = T*;
using reference = T&;
using difference_type = std::ptrdiff_t;
using iterator_category = std::bidirectional_iterator_tag;
iterator() = default;
[[nodiscard]] bool operator==(const iterator &other) const { return this->i == other.i; }
[[nodiscard]] bool operator!=(const iterator &other) const { return this->i != other.i; }
[[nodiscard]] bool operator<(const iterator &other) const { return this->i < other.i; }
[[nodiscard]] bool operator<=(const iterator &other) const { return this->i <= other.i; }
[[nodiscard]] bool operator>(const iterator &other) const { return this->i > other.i; }
[[nodiscard]] bool operator>=(const iterator &other) const { return this->i >= other.i; }
[[nodiscard]] auto operator<=>(const iterator &other) const { return this->i <=> other.i; }
inline iterator& operator++();
[[nodiscard]] iterator operator++(int) const { iterator copy = *this; ++copy; return copy; } | {
"domain": "codereview.stackexchange",
"id": 45466,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
[[nodiscard]] iterator operator++(int) const { iterator copy = *this; ++copy; return copy; }
inline iterator& operator--();
[[nodiscard]] iterator operator--(int) const { iterator copy = *this; --copy; return copy; }
[[nodiscard]] value_type operator*() const { return static_cast<value_type>(i); }
};
static_assert(std::bidirectional_iterator<iterator>);
using const_iterator = iterator;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = reverse_iterator;
explicit inline CompactSet(const size_type capacity);
[[nodiscard]] bool operator==(const CompactSet &other) const { return this->size_ == other.size_ && this->bits == other.bits; }
[[nodiscard]] bool operator!=(const CompactSet &other) const { return !(*this == other); }
[[nodiscard]] bool empty() const { return size_ == 0; }
[[nodiscard]] bool full() const { return size_ == bits.size(); }
[[nodiscard]] size_type size() const { return size_; }
[[nodiscard]] size_type max_size() const { return bits.size(); }
void clear() { std::fill(bits.begin(), bits.end(), false); size_ = 0; }
inline std::pair<iterator, bool> insert(const value_type value);
iterator insert(const const_iterator, const value_type value) { return insert(value).first; }
template<class InputIt>
inline void insert(const InputIt first, const InputIt last);
void insert(std::initializer_list<value_type> ilist) { return insert(ilist.begin(), ilist.end()); }
inline void unsafe_insert(const CompactSet &other, const size_type overlappingCount); // This is needed to cut off a few seconds at max input size.
template<class... Args>
std::pair<iterator, bool> emplace(Args&&... args) { return insert(value_type(std::forward<Args>(args)...)); }
template<class... Args> | {
"domain": "codereview.stackexchange",
"id": 45466,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
template<class... Args>
iterator emplace_hint(const const_iterator, Args&&... args) { return insert(value_type(std::forward<Args>(args)...)).first; }
inline iterator erase(const_iterator pos);
inline iterator erase(const const_iterator first, const const_iterator last);
inline size_type erase(const value_type value);
void swap(CompactSet &other) { std::ranges::swap(this->bits, other.bits); std::ranges::swap(this->size_, other.size_); }
[[nodiscard]] size_type count(const value_type value) const { return bits[value] ? 1 : 0; }
[[nodiscard]] const_iterator find(const value_type value) const { return bits[value] ? iterator(bits, value) : end(); }
[[nodiscard]] bool contains(const value_type value) const { return bits[value]; }
[[nodiscard]] inline std::pair<const_iterator, const_iterator> equal_range(const value_type value) const;
[[nodiscard]] inline const_iterator lower_bound(const value_type value) const;
[[nodiscard]] const_iterator upper_bound(const value_type value) const;
[[nodiscard]] inline const_iterator begin() const;
[[nodiscard]] const_iterator end() const { return {this->bits, bits.size()}; }
[[nodiscard]] const_iterator cbegin() const { return begin(); }
[[nodiscard]] const_iterator cend() const { return end(); }
[[nodiscard]] reverse_iterator rbegin() const { return std::make_reverse_iterator(end()); }
[[nodiscard]] reverse_iterator rend() const { return std::make_reverse_iterator(begin()); }
[[nodiscard]] const_reverse_iterator crbegin() const { return rbegin(); }
[[nodiscard]] const_reverse_iterator crend() const { return rend(); }
#ifndef NDEBUG
void validate() const;
#endif
}; | {
"domain": "codereview.stackexchange",
"id": 45466,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
template<std::unsigned_integral T>
typename CompactSet<T>::iterator& CompactSet<T>::iterator::operator++()
{
for (++i; i != bits->size() && !(*bits)[i]; ++i) { }
return *this;
}
template<std::unsigned_integral T>
typename CompactSet<T>::iterator& CompactSet<T>::iterator::operator--()
{
for (--i; !(*bits)[i]; --i) { }
return *this;
}
template<std::unsigned_integral T>
CompactSet<T>::CompactSet(const size_type capacity) :
bits(capacity, false)
{
assert(capacity == 0 || capacity - 1 <= std::numeric_limits<T>::max());
assert(capacity <= std::numeric_limits<size_type>::max()); // Otherwise, iterators won't work.
}
template<std::unsigned_integral T>
std::pair<typename CompactSet<T>::iterator, bool> CompactSet<T>::insert(const value_type value)
{
const bool previous = bits[value];
if (!previous)
{
bits[value] = true;
++size_;
}
return {{this->bits, value}, !previous};
}
template<std::unsigned_integral T>
template<class InputIt>
void CompactSet<T>::insert(const InputIt first, const InputIt last)
{
for (InputIt current = first; current != last; ++current)
insert(*current);
}
template<std::unsigned_integral T>
void CompactSet<T>::unsafe_insert(const CompactSet &other, const size_type overlappingCount)
{
std::transform(
other.bits.cbegin(), other.bits.cend(),
this->bits.begin(), this->bits.begin(),
std::logical_or<bool>());
this->size_ += other.size_ - overlappingCount;
}
template<std::unsigned_integral T>
typename CompactSet<T>::iterator CompactSet<T>::erase(const_iterator pos)
{
bits[*pos] = false;
--size_;
++pos;
return pos;
}
template<std::unsigned_integral T>
typename CompactSet<T>::iterator CompactSet<T>::erase(const const_iterator first, const const_iterator last)
{
for (const_iterator current = first; current != last; ++current)
{
bits[*current] = false;
--size_;
}
return last;
} | {
"domain": "codereview.stackexchange",
"id": 45466,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
template<std::unsigned_integral T>
typename CompactSet<T>::size_type CompactSet<T>::erase(const value_type value)
{
const bool previous = bits[value];
if (previous)
{
bits[value] = false;
--size_;
}
return previous ? 1 : 0;
}
template<std::unsigned_integral T>
std::pair<typename CompactSet<T>::iterator, typename CompactSet<T>::iterator> CompactSet<T>::equal_range(const value_type value) const
{
iterator iter(bits, value);
if (bits[value])
return {iter, std::ranges::next(iter)};
++iter;
return {iter, iter};
}
template<std::unsigned_integral T>
typename CompactSet<T>::iterator CompactSet<T>::lower_bound(const value_type value) const
{
iterator iter(bits, value);
if (!bits[value])
++iter;
return iter;
}
template<std::unsigned_integral T>
typename CompactSet<T>::iterator CompactSet<T>::upper_bound(const value_type value) const
{
iterator iter(bits, value);
return ++iter;
}
template<std::unsigned_integral T>
typename CompactSet<T>::iterator CompactSet<T>::begin() const
{
iterator iter{this->bits, 0};
if (!bits.empty() && !bits[0])
++iter;
return iter;
}
CompactSet.cc:
#include "./CompactSet.hh"
#ifndef NDEBUG
template<std::unsigned_integral T>
void CompactSet<T>::validate() const
{
const std::size_t actualCount = std::ranges::count(bits, true);
assert(size_ == actualCount);
}
#endif
#include "Minterm.hh"
template class CompactSet<Minterm>;
The function validate() is called (in development build only) to make sure mostly that the unsafe_insert() was correctly used and in lesser degree to also check if normal insert() and erase() are working correctly.
Minterm (an alias for std::uint_fast32_t) is the only type for which this class is used in my code. | {
"domain": "codereview.stackexchange",
"id": 45466,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
Answer: First impressions are very good. You've taken advice from previous reviews and applied it well. The code layout is clear and readable, and my comments are generally going to be very minor concerns.
I would have liked to see some tests with this. Or even just a demonstration program that uses the class.
When we default-initialise an iterator, its i member is undefined:
const std::vector<bool> *bits = nullptr;
size_type i;
iterator() = default;
I don't think we need all of these iterator comparisons:
[[nodiscard]] bool operator==(const iterator &other) const { return this->i == other.i; }
[[nodiscard]] bool operator!=(const iterator &other) const { return this->i != other.i; }
[[nodiscard]] bool operator<(const iterator &other) const { return this->i < other.i; }
[[nodiscard]] bool operator<=(const iterator &other) const { return this->i <= other.i; }
[[nodiscard]] bool operator>(const iterator &other) const { return this->i > other.i; }
[[nodiscard]] bool operator>=(const iterator &other) const { return this->i >= other.i; }
[[nodiscard]] auto operator<=>(const iterator &other) const { return this->i <=> other.i; }
The idea of <=> is that we just implement that one and the compiler can synthesize all the others as necessary.
Slight simplification of post-increment and post-decrement: replace ++copy; return copy; with return ++copy;. It's arguable whether that's an improvement (some style guides discourage side-effects in such expressions).
You could even go with { return ++iterator{*this}; } but I'd argue that's too obscure.
I think that i needs to be able to represent a value that's one greater than the set size, in order to create an end iterator, so we can't just use value_type. Or we could disallow creating containers that could include a maximum value. On balance, I think I'm comfortable with the choice you made to always use the vector's size type for this. | {
"domain": "codereview.stackexchange",
"id": 45466,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
I like that we test we actually have a bidirectional iterator using static_assert(). I didn't think of that, though I probably would have if writing unit tests.
The set's operator!=() should by synthesizable from ==. I can't remember whether that's automatic or whether we actually need to write bool operator!=(const CompactSet&) const = default.
We could be more compatible with standard set if we implement the insert() overloads that accept a "hint" iterator (we can just ignore the hint, of course).
I like the name change for unsafe_insert(). It's a good balance between safety and optimisation now.
I wonder how much it would hurt to make a safe version, that computes the overlap size as it adds. It would look something like this:
template<std::unsigned_integral T>
void CompactSet<T>::insert(const CompactSet &other)
{
size_type intersection_size = 0;
auto combine = [&intersection_size](auto a, auto b){
intersection_size += a & b;
return a | b;
};
std::ranges::transform(bits, other.bits, bits.begin(), combine);
size_ += other.size_ - intersection_size;
}
We might want to reject insertion of sets containing elements beyond our max_size(), rather than simply dropping those values?
Of course, if we had access to the bit vector's underlying representation, we could use bitwise operations (and std::popcount() or std::bitset::count() for counting the intersection size of each block of bits).
emplace(Args&&... args) might be overkill. The only valid Args... is a single integer, so I think that could just be emplace(value_type). Similarly for emplace_hint().
It may be useful to declare swap() (in particular) with noexcept. This can help generic functions provide the strong exception guarantee.
These asserts in the constructor perhaps ought always to be executed and throw an exception (rather than being absent when NDEBUG is defined): | {
"domain": "codereview.stackexchange",
"id": 45466,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
assert(capacity == 0 || capacity - 1 <= std::numeric_limits<T>::max());
assert(capacity <= std::numeric_limits<size_type>::max()); // Otherwise, iterators won't work.
(Even though this is a template, it's possible for instantiations of it to be compiled separately from client code.) | {
"domain": "codereview.stackexchange",
"id": 45466,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
python, pandas, machine-learning
Title: Machine learning training, hyperparameter tuning and testing with 3 different models
Question: I am trying to solve a multi-class classification involving prediction the outcome of a football match (target variable = Win, Lose or Draw). With a dataset of 2280 rows, which is 6 seasons of football data.
I have features with both numerical and categorical values (which I have encoded using one encoding). The data is split into a train and test set, in a way so the test set is only the most recent season of data.
I wanted to understand as this is my first machine learning project if this overall process looks correct and if there is anything I should be doing better/more optimal.
Splitting data into train test split
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import classification_report, accuracy_score
from sklearn.naive_bayes import MultinomialNB
# Assign our target variable to label
label = match_df['FTR']
# Flatten the label array
y = np.ravel(label)
# Assign all columns expect the FTR column to the features variable
X = match_df.loc[:, match_df.columns != 'FTR']
# Split our data into training and testing sets
# We set shuffle to false as we want to keep the order of the matches in the data frame so we can use the 2022/2023 season as our test set
# Use a test size of 0.1665 as this will give us 380 test samples which is the same as the number of matches in a season
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1665, random_state=0, shuffle=False)
Testing our base model, then performing hyper parameter tuning
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import GridSearchCV, StratifiedKFold | {
"domain": "codereview.stackexchange",
"id": 45467,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, pandas, machine-learning",
"url": null
} |
python, pandas, machine-learning
# Try without normalization also try min max scaler
# Normalize the data set as we have a several features with different data scales
scaler = MinMaxScaler()
# Fit the scaler to the training set and transform the training set
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# Create SVM model
svm_model = SVC(random_state=0)
# Create KNN model
knn_model = KNeighborsClassifier()
# Create Naive Bayes model
nb_model = GaussianNB()
# Create a dictionary of the models
models = {'KNN':knn_model, 'SVM':svm_model, 'Naive_Bayes':nb_model}
# Create the StratifiedKFold object
skf = StratifiedKFold(n_splits=10)
# Train the base models and evaluate them using cross validation
for model_name, model in models.items():
model.fit(X_train, y_train)
scores = cross_val_score(model, X_train, y_train, cv=skf)
print(f"Accuracy during cross validation for BASE {model_name}: {scores.mean()}")
# Perform hyper parameter tuning on each model using grid search
# Create a dictionary of hyper parameters for each model we want to tune
svm_parameters = {'kernel':['poly', 'rbf', 'linear'], 'C':[0.1, 1, 10, 100], 'gamma':['scale', 'auto', 0.1, 1], 'degree':list(range(1, 10))}
# For knn neighbor param, we make sure it is odd to prevent ties
knn_parameters = {'n_neighbors':[i for i in range(2, 31) if i % 2 != 0], 'weights':['uniform', 'distance'], 'algorithm':['auto', 'ball_tree', 'kd_tree', 'brute'],
'leaf_size':[i for i in range(1, 40)], 'p':[1, 2], 'metric':['minkowski', 'euclidean', 'manhattan']}
nb_parameters = {'var_smoothing':[1e-09, 1e-08, 1e-07, 1e-06, 1e-05]}
# Create a dictionary of the parameters
parameters = {'SVM':svm_parameters, 'KNN':knn_parameters, 'Naive_Bayes':nb_parameters} | {
"domain": "codereview.stackexchange",
"id": 45467,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, pandas, machine-learning",
"url": null
} |
python, pandas, machine-learning
# import scoring metrics
from sklearn.metrics import accuracy_score, balanced_accuracy_score, precision_score, recall_score, f1_score, roc_auc_score
from sklearn.metrics import make_scorer
scoring = {
'accuracy': make_scorer(accuracy_score),
'balanced_accuracy': make_scorer(balanced_accuracy_score),
'precision': make_scorer(precision_score, average='macro'),
'recall': make_scorer(recall_score, average='macro'),
'f1': make_scorer(f1_score, average='macro')
}
# Loop through each model and perform hyper parameter tuning
for model_name, model in models.items():
print(f"Performing hyper parameter tuning on {model_name}...")
# Create a grid search object and fit it to the data to perform hyper parameter tuning
search = GridSearchCV(estimator=model, param_grid=parameters[model_name], scoring=scoring, refit='accuracy', cv=skf, n_jobs=-1)
# Fit the grid search object to the train data
searchResults = search.fit(X_train, y_train)
# Get the optimal hyper parameters and corresponding accuracy score
print(f"Best parameters: {search.best_params_}, Best Score: {search.best_score_}")
print("Evaluating the model on the test data...")
bestModel = searchResults.best_estimator_
print(bestModel)
print(f"Test Score: {bestModel.score(X_test, y_test)}\n\n")
# Fit the best parameters to the model
models[model_name] = bestModel
Final test of our hyper parameter tuning models and display their confusion matrix
for model_name, model in models.items():
# Produce a confusion matrix for the final model
conf_matrix = confusion_matrix(y_test, model.predict(X_test))
# Plot the confusion matrix
sns.heatmap(conf_matrix, annot=True, cmap='Blues')
# Set our x, y labels and title
plt.xlabel('Predicted labels')
plt.ylabel('True labels')
plt.title(f'Confusion Matrix for {model_name}')
# Display the plot
plt.show() | {
"domain": "codereview.stackexchange",
"id": 45467,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, pandas, machine-learning",
"url": null
} |
python, pandas, machine-learning
# Display the plot
plt.show()
Answer: missing review context
label = match_df['FTR']
This line makes no sense,
as it will produce "NameError: name 'match_df' is not defined";
we didn't define it in previous code such as imports.
extra temp var
Maybe do it all in one go?
Since we do not later refer to label.
y = np.ravel(match_df['FTR'])
I do thank you for the helpful reminder that ravel() means "flatten".
(Some other comments, like "fit scaler ... transform",
just say what the code says and could be elided.)
nit, typo: "expect" --> "except"
comment could be code
# Use a test size of 0.1665 as this will give us 380 test samples which is the same as the number of matches in a season
This is a helpful comment and I thank you for it.
(Oddly, final digit is 5 rather than 7.)
It makes an assertion about how our data relates to the real world.
Assertions are more believable when they are code instead of prose.
Usually comments start out being true, but then they bit-rot
as the code changes and the comments don't keep up.
Consider rephrasing this as
matches_per_season = 380
test_size = matches_per_season / len(y)
assert round(test_size, 4) == 0.1667
But wait!
Perhaps confusingly, perhaps conveniently,
train_test_split behaves differently according to
whether the parameter is in the unit interval or is a large integer.
We could more clearly convey Author's Intent by simply saying
matches_per_season = 380
assert len(y) == 6 * matches_per_season # dataset covers six seasons
..., ..., ..., ... = train_test_split(X, y, test_size=matches_per_season, ... )
magic number
skf = StratifiedKFold(n_splits=10) | {
"domain": "codereview.stackexchange",
"id": 45467,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, pandas, machine-learning",
"url": null
} |
python, pandas, machine-learning
magic number
skf = StratifiedKFold(n_splits=10)
Number of splits would have defaulted to 5,
a natural fit for the number of seasons you're testing on.
Splitting into {first, second} half of each season seems arbitrary,
and worth a # comment.
On the bright side, at least we're using a multiple of five.
My maintenance concern is that someone may change this to, say, 8,
and then observe bigger effect than anticipated, puzzling them.
Had you shuffled the time series of scores up top,
none of these concerns would be relevant here.
But having decided to preserve the time series,
that colors how we look at these subsequent pipeline stages.
step parameter
# For knn neighbor param, we make sure it is odd to prevent ties
knn_parameters = {'n_neighbors':[i for i in range(2, 31) if i % 2 != 0]
The "tie breaking" comment is helpful.
Ending the range at odd 31 is unusual, given that the final i
tested will be even 30 which is rejected.
Starting at 2 is similarly unusual, and does not aid human cognition.
range takes a 3rd parameter. Prefer:
[i for i in range(3, 30, 2)] which of course is simply
list(range(3, 30, 2))
The grid searching could be better motivated.
As stated it looks like "throw stuff at the wall to see what sticks".
extract helpers
Each time you write a helpful comment like this:
# Loop through each model and perform hyper parameter tuning | {
"domain": "codereview.stackexchange",
"id": 45467,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, pandas, machine-learning",
"url": null
} |
python, pandas, machine-learning
it suggests that you might have written something
like def tune_hyperparameters():
The biggest advantage of extracting such helpers is that all their
local variables go out-of-scope when they return, thereby reducing
coupling
and the cognitive load that comes from juggling all those global variables.
Clearly showing what is fed into a function, and what it produces,
is helpful for future maintenance engineers.
It will also give you a place to add a """docstring""".
And when a function morphs into doing something a little
different, a function name that "lies" is more likely
to be updated to tell the truth, compared with
prose trying to tell the same story.
It also admits of
unit testing.
choosing identifiers
searchResults = ...
bestModel = ...
Pep-8
asks that you spell these search_results and best_model.
We preserved causal (chronological) order among example rows,
but it's not clear that any of the models benefit from that.
Kudos for labeling your axes!
This ML exercise hews pretty closely to standard textbook formats,
and achieves its design goals.
I would be willing to delegate or assign maintenance tasks on this code. | {
"domain": "codereview.stackexchange",
"id": 45467,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, pandas, machine-learning",
"url": null
} |
c++, array, reinventing-the-wheel, memory-management, c++17
Title: A fixed-size dynamic array
Question: Background
I implemented the historic std::dynarray according to the specification under the name dynamic_array in C++17. dynamic_array doesn't attempt to get allocated on stack storage.
The most interesting part is the allocator support. Unlike other containers, dynamic_array does not take an allocator as a template parameter. But it supports construction from an arbitrary allocator, and it has to call the appropriate allocator on destruction. As such, the allocator has to be stored with the help of type erasure.
At first I thought of using std::any to hold the allocator. However, there is a problem: std::any does not have a visit functionality, we can't get the type of the allocator back, thus unable to call std::allocator_traits<A>::destroy.
As such, my approach is to use a std::function. A lambda is generated for each construction from an allocator, which captures the allocator by copy and calls the correct destroy function. Admittedly, this is one of the few times I find a meaningful usage for mutable lambdas.
Code
Here's the header dynamic_array.hpp:
// C++17 fixed-size dynamic array
#ifndef INC_DYNAMIC_ARRAY_HPP_akMQiHuI0M
#define INC_DYNAMIC_ARRAY_HPP_akMQiHuI0M
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <initializer_list>
#include <iterator>
#include <memory>
#include <type_traits>
namespace LF_lib {
template <class T>
class dynamic_array {
public:
using value_type = T;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using reference = T&;
using const_reference = const T&;
using pointer = T*;
using const_pointer = const T*;
using iterator = T*;
using const_iterator = const T*;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>; | {
"domain": "codereview.stackexchange",
"id": 45468,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, reinventing-the-wheel, memory-management, c++17",
"url": null
} |
c++, array, reinventing-the-wheel, memory-management, c++17
// default-initializes the elements
explicit dynamic_array(std::size_t n)
:dynamic_array{n, std::allocator<T>{}}
{
}
template <class A>
dynamic_array(std::size_t n, const A& a)
:count{n}
{
if (count == 0) {
register_empty_cleanup();
return;
}
A alloc = a;
elems = std::allocator_traits<A>::allocate(alloc, count);
T* p = begin();
try {
register_cleanup(alloc);
for (; p != end(); ++p)
std::allocator_traits<A>::construct(alloc, p);
} catch (...) {
for (T* q = begin(); q != p; ++q)
std::allocator_traits<A>::destroy(alloc, q);
std::allocator_traits<A>::deallocate(alloc, elems, count);
throw;
}
}
dynamic_array(std::size_t n, const T& value)
:dynamic_array{n, value, std::allocator<T>{}}
{
}
template <class A>
dynamic_array(std::size_t n, const T& value, const A& a)
:count{n}
{
if (count == 0) {
register_empty_cleanup();
return;
}
A alloc = a;
elems = std::allocator_traits<A>::allocate(alloc, count);
T* p = begin();
try {
register_cleanup(alloc);
for (; p != end(); ++p)
std::allocator_traits<A>::construct(alloc, p, value);
} catch (...) {
for (T* q = begin(); q != p; ++q)
std::allocator_traits<A>::destroy(alloc, q);
std::allocator_traits<A>::deallocate(alloc, elems, count);
throw;
}
}
dynamic_array(const dynamic_array& other)
:dynamic_array{other, std::allocator<T>{}}
{
}
template <class A>
dynamic_array(const dynamic_array& other, const A& a)
:count{other.size()}
{
if (count == 0) {
register_empty_cleanup();
return;
} | {
"domain": "codereview.stackexchange",
"id": 45468,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, reinventing-the-wheel, memory-management, c++17",
"url": null
} |
c++, array, reinventing-the-wheel, memory-management, c++17
A alloc = a;
elems = std::allocator_traits<A>::allocate(alloc, count);
T* p = begin();
try {
register_cleanup(alloc);
for (const T* q = other.cbegin(); p != cend(); ++p, ++q)
std::allocator_traits<A>::construct(alloc, p, *q);
} catch (...) {
for (T* q = begin(); q != p; ++q)
std::allocator_traits<A>::destroy(alloc, q);
std::allocator_traits<A>::deallocate(alloc, elems, count);
throw;
}
}
dynamic_array(std::initializer_list<T> init)
:dynamic_array{init, std::allocator<T>{}}
{
}
template <class A>
dynamic_array(std::initializer_list<T> init, const A& a)
:count{init.size()}
{
if (count == 0) {
register_empty_cleanup();
return;
}
A alloc = a;
elems = std::allocator_traits<A>::allocate(alloc, count);
T* p = begin();
try {
register_cleanup(alloc);
for (const T* q = init.begin(); p != end(); ++p, ++q)
std::allocator_traits<A>::construct(alloc, p, *q);
} catch (...) {
for (T* q = begin(); q != p; ++q)
std::allocator_traits<A>::destroy(alloc, q);
std::allocator_traits<A>::deallocate(alloc, elems, count);
throw;
}
}
~dynamic_array()
{
cleanup(elems, count);
}
dynamic_array& operator=(const dynamic_array&) = delete;
dynamic_array& operator=(dynamic_array&&) = delete;
T& at(std::size_t index) { check(index); return elems[index]; }
const T& at(std::size_t index) const { check(index); return elems[index]; }
T& operator[](std::size_t index) { return elems[index]; }
const T& operator[](std::size_t index) const { return elems[index]; }
T& front() { return elems[0]; }
const T& front() const { return elems[0]; }
T& back() { return elems[count - 1]; }
const T& back() const { return elems[count - 1]; } | {
"domain": "codereview.stackexchange",
"id": 45468,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, reinventing-the-wheel, memory-management, c++17",
"url": null
} |
c++, array, reinventing-the-wheel, memory-management, c++17
T* data() noexcept { return elems; }
const T* data() const noexcept { return elems; }
iterator begin() noexcept { return elems; }
const_iterator begin() const noexcept { return elems; }
const_iterator cbegin() const noexcept { return begin(); }
iterator end() noexcept { return elems + count; }
const_iterator end() const noexcept { return elems + count; }
const_iterator cend() const noexcept { return end(); }
reverse_iterator rbegin() noexcept { return end(); }
const_reverse_iterator rbegin() const noexcept { return end(); }
const_reverse_iterator crbegin() const noexcept { return rbegin(); }
reverse_iterator rend() noexcept { return begin(); }
const_reverse_iterator rend() const noexcept { return begin(); }
const_reverse_iterator crend() const noexcept { return rend(); }
bool empty() const noexcept { return size != 0; }
std::size_t size() const noexcept { return count; }
std::size_t max_size() const noexcept
{
return SIZE_MAX / sizeof(T);
}
void fill(const T& value)
{
std::fill(begin(), end(), value);
}
private:
T* elems = nullptr;
std::size_t count;
std::function<void(T*, std::size_t)> cleanup;
void register_empty_cleanup()
{
cleanup = [](T*, std::size_t) {};
}
template <class A>
void register_cleanup(A& alloc)
{
cleanup = [alloc](T* elems, std::size_t count) mutable {
T* it = elems;
for (std::size_t i = 0; i < count; ++i)
std::allocator_traits<A>::destroy(alloc, it++);
std::allocator_traits<A>::deallocate(alloc, elems, count);
};
}
void check(std::size_t index) const
{
if (index >= count)
throw std::out_of_range{"LF_lib::dynamic_array out of range"};
}
}; | {
"domain": "codereview.stackexchange",
"id": 45468,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, reinventing-the-wheel, memory-management, c++17",
"url": null
} |
c++, array, reinventing-the-wheel, memory-management, c++17
template <class T>
bool operator==(const dynamic_array<T>& lhs, const dynamic_array<T>& rhs)
{
return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}
template <class T>
bool operator!=(const dynamic_array<T>& lhs, const dynamic_array<T>& rhs)
{
return !(lhs == rhs);
}
template <class T>
bool operator< (const dynamic_array<T>& lhs, const dynamic_array<T>& rhs)
{
return std::lexicographical_compare(lhs.begin(), lhs.end(),
rhs.begin(), rhs.end());
}
template <class T>
bool operator<=(const dynamic_array<T>& lhs, const dynamic_array<T>& rhs)
{
return !(rhs < lhs);
}
template <class T>
bool operator> (const dynamic_array<T>& lhs, const dynamic_array<T>& rhs)
{
return rhs < lhs;
}
template <class T>
bool operator>=(const dynamic_array<T>& lhs, const dynamic_array<T>& rhs)
{
return !(lhs < rhs);
}
}
namespace std {
template <class T, class A>
struct uses_allocator<LF_lib::dynamic_array<T>, A>
:std::true_type { };
}
#endif
And here's an example on its usage, showing how the allocators work under the hood:
#include <iomanip>
#include <iostream>
#include <numeric>
#include <string>
#include <type_traits>
#include "dynamic_array.hpp"
using LF_lib::dynamic_array;
template <typename T>
class Tracing_alloc :private std::allocator<T> {
using Base = std::allocator<T>;
public:
using value_type = T;
T* allocate(std::size_t n)
{
std::cerr << "allocate(" << n << ")\n";
return Base::allocate(n);
}
void deallocate(T* ptr, std::size_t n)
{
std::cerr << "deallocate(" << static_cast<void*>(ptr) << ", "
<< n << ")\n";
Base::deallocate(ptr, n);
}
template <typename... Args>
void construct(T* ptr, Args&&... args)
{
std::cerr << "construct(" << ptr << ", args...)\n";
std::allocator_traits<Base>::construct(*this, ptr, args...);
} | {
"domain": "codereview.stackexchange",
"id": 45468,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, reinventing-the-wheel, memory-management, c++17",
"url": null
} |
c++, array, reinventing-the-wheel, memory-management, c++17
void destroy(T* ptr)
{
std::cerr << "destroy(" << ptr << ")\n";
std::allocator_traits<Base>::destroy(*this, ptr);
}
};
template <typename T>
bool operator==(const Tracing_alloc<T>&, const Tracing_alloc<T>&)
{
return true;
}
template <typename T>
bool operator!=(const Tracing_alloc<T>&, const Tracing_alloc<T>&)
{
return false;
}
class Construct_throw {
public:
Construct_throw()
{
static int i = 0;
if (i++ > 3)
throw std::exception{};
}
};
void test(std::size_t n)
{
dynamic_array<std::string> arr{n, Tracing_alloc<std::string>{}};
for (auto& x : arr)
x = "a";
std::inclusive_scan(arr.begin(), arr.end(), arr.begin(), std::plus<>{});
for (const auto& x : arr)
std::cout << std::quoted(x) << " ";
std::cout << "\n";
dynamic_array<std::string> arr2{arr, Tracing_alloc<std::string>{}};
for (const auto& x : arr2)
std::cout << std::quoted(x) << " ";
std::cout << "\n";
dynamic_array<std::string> arr3{{"foo", "bar", "baz"},
Tracing_alloc<std::string>{}};
for (const auto& x : arr3)
std::cout << std::quoted(x) << " ";
std::cout << "\n";
dynamic_array<Construct_throw> arr4{n, Tracing_alloc<Construct_throw>{}};
}
int main()
try {
test(0);
test(10);
} catch (...) {
return 1;
}
Here's the output I got: (the initial empty lines are intentional) | {
"domain": "codereview.stackexchange",
"id": 45468,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, reinventing-the-wheel, memory-management, c++17",
"url": null
} |
c++, array, reinventing-the-wheel, memory-management, c++17
allocate(3)
construct(000001CE3ADE8F60, args...)
construct(000001CE3ADE8F80, args...)
construct(000001CE3ADE8FA0, args...)
"foo" "bar" "baz"
destroy(000001CE3ADE8F60)
destroy(000001CE3ADE8F80)
destroy(000001CE3ADE8FA0)
deallocate(000001CE3ADE8F60, 3)
allocate(10)
construct(000001CE3ADEC130, args...)
construct(000001CE3ADEC150, args...)
construct(000001CE3ADEC170, args...)
construct(000001CE3ADEC190, args...)
construct(000001CE3ADEC1B0, args...)
construct(000001CE3ADEC1D0, args...)
construct(000001CE3ADEC1F0, args...)
construct(000001CE3ADEC210, args...)
construct(000001CE3ADEC230, args...)
construct(000001CE3ADEC250, args...)
"a" "aa" "aaa" "aaaa" "aaaaa" "aaaaaa" "aaaaaaa" "aaaaaaaa" "aaaaaaaaa" "aaaaaaaaaa"
allocate(10)
construct(000001CE3ADEDED0, args...)
construct(000001CE3ADEDEF0, args...)
construct(000001CE3ADEDF10, args...)
construct(000001CE3ADEDF30, args...)
construct(000001CE3ADEDF50, args...)
construct(000001CE3ADEDF70, args...)
construct(000001CE3ADEDF90, args...)
construct(000001CE3ADEDFB0, args...)
construct(000001CE3ADEDFD0, args...)
construct(000001CE3ADEDFF0, args...)
"a" "aa" "aaa" "aaaa" "aaaaa" "aaaaaa" "aaaaaaa" "aaaaaaaa" "aaaaaaaaa" "aaaaaaaaaa"
allocate(3)
construct(000001CE3ADE8F60, args...)
construct(000001CE3ADE8F80, args...)
construct(000001CE3ADE8FA0, args...)
"foo" "bar" "baz"
allocate(10)
construct(000001CE3ADE8CC0, args...)
construct(000001CE3ADE8CC1, args...)
construct(000001CE3ADE8CC2, args...)
construct(000001CE3ADE8CC3, args...)
construct(000001CE3ADE8CC4, args...)
destroy(000001CE3ADE8CC0)
destroy(000001CE3ADE8CC1)
destroy(000001CE3ADE8CC2)
destroy(000001CE3ADE8CC3)
deallocate(000001CE3ADE8CC0, 10)
destroy(000001CE3ADE8F60)
destroy(000001CE3ADE8F80)
destroy(000001CE3ADE8FA0)
deallocate(000001CE3ADE8F60, 3)
destroy(000001CE3ADEDED0)
destroy(000001CE3ADEDEF0)
destroy(000001CE3ADEDF10)
destroy(000001CE3ADEDF30)
destroy(000001CE3ADEDF50)
destroy(000001CE3ADEDF70)
destroy(000001CE3ADEDF90)
destroy(000001CE3ADEDFB0) | {
"domain": "codereview.stackexchange",
"id": 45468,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, reinventing-the-wheel, memory-management, c++17",
"url": null
} |
c++, array, reinventing-the-wheel, memory-management, c++17
destroy(000001CE3ADEDF70)
destroy(000001CE3ADEDF90)
destroy(000001CE3ADEDFB0)
destroy(000001CE3ADEDFD0)
destroy(000001CE3ADEDFF0)
deallocate(000001CE3ADEDED0, 10)
destroy(000001CE3ADEC130)
destroy(000001CE3ADEC150)
destroy(000001CE3ADEC170)
destroy(000001CE3ADEC190)
destroy(000001CE3ADEC1B0)
destroy(000001CE3ADEC1D0)
destroy(000001CE3ADEC1F0)
destroy(000001CE3ADEC210)
destroy(000001CE3ADEC230)
destroy(000001CE3ADEC250)
deallocate(000001CE3ADEC130, 10) | {
"domain": "codereview.stackexchange",
"id": 45468,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, reinventing-the-wheel, memory-management, c++17",
"url": null
} |
c++, array, reinventing-the-wheel, memory-management, c++17
Of course, you may get completely different addresses.
Answer: Note: although the question is tagged C++17, I'm going to use some C++20 or later features in my review, as this simplifies the code. Many of my suggestions can be written in C++17, but at the expense of clarity. | {
"domain": "codereview.stackexchange",
"id": 45468,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, reinventing-the-wheel, memory-management, c++17",
"url": null
} |
c++, array, reinventing-the-wheel, memory-management, c++17
I get some compilation warnings:
g++-14 -std=c++23 -fPIC -gdwarf-4 -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wmissing-braces -Wconversion -Wuseless-cast -Weffc++ 221719.cpp -o 221719
221719.cpp: In instantiation of ‘LF_lib::dynamic_array<T>::dynamic_array(std::size_t, const A&) [with A = Tracing_alloc<std::__cxx11::basic_string<char> >; T = std::__cxx11::basic_string<char>; std::size_t = long unsigned int]’:
221719.cpp:349:65: required from here
349 | dynamic_array<std::string> arr{n, Tracing_alloc<std::string>{}};
| ^
221719.cpp:41:5: warning: ‘LF_lib::dynamic_array<std::__cxx11::basic_string<char> >::cleanup’ should be initialized in the member initialization list [-Weffc++]
41 | dynamic_array(std::size_t n, const A& a)
| ^~~~~~~~~~~~~
221719.cpp: In instantiation of ‘LF_lib::dynamic_array<T>::dynamic_array(const LF_lib::dynamic_array<T>&, const A&) [with A = Tracing_alloc<std::__cxx11::basic_string<char> >; T = std::__cxx11::basic_string<char>]’:
221719.cpp:357:68: required from here
221719.cpp:41:5: warning: 357 | dynamic_array<std::string> arr2{arr, Tracing_alloc<std::string>{}};
221719.cpp:41:5: warning: | ^
221719.cpp:99:5: warning: ‘LF_lib::dynamic_array<std::__cxx11::basic_string<char> >::cleanup’ should be initialized in the member initialization list [-Weffc++]
99 | dynamic_array(const dynamic_array& other, const A& a)
| ^~~~~~~~~~~~~
221719.cpp: In instantiation of ‘LF_lib::dynamic_array<T>::dynamic_array(std::initializer_list<_Tp>, const A&) [with A = Tracing_alloc<std::__cxx11::basic_string<char> >; T = std::__cxx11::basic_string<char>]’:
221719.cpp:363:35: required from here
221719.cpp:99:5: warning: 363 | Tracing_alloc<std::string>{}};
221719.cpp:99:5: warning: | ^ | {
"domain": "codereview.stackexchange",
"id": 45468,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, reinventing-the-wheel, memory-management, c++17",
"url": null
} |
c++, array, reinventing-the-wheel, memory-management, c++17
221719.cpp:99:5: warning: | ^
221719.cpp:128:5: warning: ‘LF_lib::dynamic_array<std::__cxx11::basic_string<char> >::cleanup’ should be initialized in the member initialization list [-Weffc++]
128 | dynamic_array(std::initializer_list<T> init, const A& a)
| ^~~~~~~~~~~~~
221719.cpp: In instantiation of ‘LF_lib::dynamic_array<T>::dynamic_array(std::size_t, const A&) [with A = Tracing_alloc<Construct_throw>; T = Construct_throw; std::size_t = long unsigned int]’:
221719.cpp:368:74: required from here
221719.cpp:128:5: warning: 368 | dynamic_array<Construct_throw> arr4{n, Tracing_alloc<Construct_throw>{}};
221719.cpp:128:5: warning: | ^
221719.cpp:41:5: warning: ‘LF_lib::dynamic_array<Construct_throw>::cleanup’ should be initialized in the member initialization list [-Weffc++]
41 | dynamic_array(std::size_t n, const A& a)
| ^~~~~~~~~~~~~ | {
"domain": "codereview.stackexchange",
"id": 45468,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, reinventing-the-wheel, memory-management, c++17",
"url": null
} |
c++, array, reinventing-the-wheel, memory-management, c++17
These are easily suppressed with std::function<⋯> cleanup = {};, making the default-initialisation explicit.
The test program is Valgrind-clean, but does exit with failure status:
==1410317== HEAP SUMMARY:
==1410317== in use at exit: 0 bytes in 0 blocks
==1410317== total heap usage: 13 allocs, 13 frees, 75,735 bytes allocated
==1410317==
==1410317== All heap blocks were freed -- no leaks are possible
==1410317==
==1410317== For lists of detected and suppressed errors, rerun with: -s
==1410317== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
make[1]: *** [Makefile:74: 221719.run] Error 1
Adding a bit of diagnostic, we see that this is due to catching the exception from Construct_throw(), and it seems that the test program should expect this, and simply has its return statuses the wrong way around (i.e. the test should fail if we don't get the exception):
Construct_throw()
{
static int i = 0;
if (i++ > 3)
throw std::runtime_error("Construct_throw");
}
#include <cstdlib>
#include <stdexcept>
int main()
try {
test(0);
test(10);
return EXIT_FAILURE;
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
return EXIT_SUCCESS;
}
The first two constructors can easily be combined into a single one by defaulting the allocator. And since we just copy it to alloc, we can accept it by value:
template <class A = std::allocator<T>>
explicit dynamic_array(std::size_t n, A alloc = {})
Similarly:
template <class A = std::allocator<T>>
dynamic_array(std::size_t n, const T& value, A alloc = {})
and
template <class A = std::allocator<T>>
dynamic_array(std::initializer_list<T> init, A alloc a = {})
But not
template <class A = std::allocator<T>>
dynamic_array(const dynamic_array& other, A alloc = {})
because this is no longer a copy constructor. | {
"domain": "codereview.stackexchange",
"id": 45468,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, reinventing-the-wheel, memory-management, c++17",
"url": null
} |
c++, array, reinventing-the-wheel, memory-management, c++17
because this is no longer a copy constructor.
When constructing contents throws an exception, I think we're supposed to destroy in reverse order of construction:
} catch (...) {
while (p-- != begin())
std::allocator_traits<A>::destroy(alloc, p);
std::allocator_traits<A>::deallocate(alloc, elems, count);
throw;
A similar change is required in register_cleanup():
cleanup = [alloc](T* elems, std::size_t count) mutable {
T* it = elems + count;
while (it-- > elems)
std::allocator_traits<A>::destroy(alloc, it);
std::allocator_traits<A>::deallocate(alloc, elems, count);
};
As far as I can make out, there's nothing to stop allocator traits' destroy() or deallocate() from throwing, so perhaps we ought to handle any exceptions, especially in register_cleanup()'s stored function which is called from within noexcept context (specifically, in a destructor).
Also in register_cleanup(), we could eliminate the need to store the allocator in the common case of a stateless allocator. If the traits tells us that all instances are equivalent, we may be able to create a new one for cleanup rather than capturing this one:
using traits = std::allocator_traits<A>;
if constexpr (traits::is_always_equal::value &&
std::is_default_constructible_v<A>) {
cleanup = [](T* elems, std::size_t count) {
A alloc;
for (T* it = elems + count; it-- > elems; )
traits::destroy(alloc, it);
traits::deallocate(alloc, elems, count);
};
} else {
cleanup = [alloc](T* elems, std::size_t count) {
for (T* it = elems + count; it-- > elems; )
traits::destroy(alloc, it);
traits::deallocate(alloc, elems, count);
};
} | {
"domain": "codereview.stackexchange",
"id": 45468,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, reinventing-the-wheel, memory-management, c++17",
"url": null
} |
c++, array, reinventing-the-wheel, memory-management, c++17
There's a lot of commonality among the different constructors. I think we can refactor that out into a private utility method.
// allocate and populate content (for constructors)
template<class A>
void copy_content(std::ranges::input_range auto&& other, A alloc)
{
if (count == 0) {
register_empty_cleanup();
return;
}
using traits = std::allocator_traits<A>;
elems = traits::allocate(alloc, count);
T* p = begin();
try {
for (auto q = other.begin(); p != end(); ++p, ++q)
traits::construct(alloc, p, *q);
} catch (...) {
while (p-- != begin())
traits::destroy(alloc, p);
traits::deallocate(alloc, elems, count);
throw;
}
}
We can then use that for most of the constructors:
template <class A = std::allocator<T>>
dynamic_array(std::size_t n, const T& value, A alloc = {})
:count{n}
{
copy_content(std::views::repeat(value), alloc);
}
dynamic_array(const dynamic_array& other)
:dynamic_array{other, std::allocator<T>{}}
{
}
template <class A = std::allocator<T>>
dynamic_array(const dynamic_array& other, A alloc)
:count{other.size()}
{
copy_content(other, alloc);
}
template <class A = std::allocator<T>>
dynamic_array(std::initializer_list<T> init, A alloc = {})
:count{init.size()}
{
copy_content(init, alloc);
}
We can't as easily use it for the first constructor (which default-constructs elements) because in that case T might be non-copyable.
The helper function prompts a possibility of one or two additional constructors - we could accept a sized_range (possibly of rvalues, thanks to std::views::as_rvalue, helping us move values from other containers). | {
"domain": "codereview.stackexchange",
"id": 45468,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, reinventing-the-wheel, memory-management, c++17",
"url": null
} |
c++, array, reinventing-the-wheel, memory-management, c++17
We can get rid of register_empty_cleanup(), just by declining to call an unassigned std::function:
~dynamic_array()
{
if (cleanup) // or, "if (elems)"
cleanup(elems, count);
}
I don't see any reason to disable move-assignment or move-construction. We could use copy-and-swap idiom for the latter.
The rbegin() and rend() look wrong to me:
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
reverse_iterator rbegin() noexcept { return end(); }
const_reverse_iterator rbegin() const noexcept { return end(); }
reverse_iterator rend() noexcept { return begin(); }
const_reverse_iterator rend() const noexcept { return begin(); }
I'm not sure how we're getting away with this, since the std::reverse_iterator constructor here is explicit - I don't see any exception that applies to bare pointers.
The set of relational operators can be replaced with <=> and std::lexicographical_compare_three_way() (there's no ranges version of this algorithm, likely due to it appearing after the ranges algorithms were written).
In the test program's allocator, we have
template <typename... Args>
void construct(T* ptr, Args&&... args)
{
std::cerr << "construct(" << ptr << ", args...)\n";
std::allocator_traits<Base>::construct(*this, ptr, args...);
}
We ought to std::forward() the arguments there.
We could improve the Construct_throw test with a constructor that only throws every n invocations. That could help us ensure that we destruct the correct elements, in the correct order. | {
"domain": "codereview.stackexchange",
"id": 45468,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, reinventing-the-wheel, memory-management, c++17",
"url": null
} |
c#, performance, array
Title: "stray" point correction in 2D array
Question: I have a code which does the following:
For each value v in a 2D array, look at neighboring positions - how far to look is specified by distThreshold. If the count of values identical to v in the neighborhood is lower or equal to countThreshold, change v to a value which is most prevalent in the neighborhood.
For example:
input:
[5, 2, 1, 0, 5]
[1, 5, 5, 0, 4]
[0, 2, 0, 0, 5]
[1, 3, 2, 4, 0]
[3, 3, 4, 3, 0]
output for distThreshold = 1, countThreshold = 0:
[5, 5, 5, 0, 0]
[2, 5, 5, 0, 0]
[1, 2, 0, 0, 0]
[3, 3, 2, 4, 0]
[3, 3, 4, 0, 0] | {
"domain": "codereview.stackexchange",
"id": 45469,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, array",
"url": null
} |
c#, performance, array
Functions that are important:
public static int[][] correctedArray(int distThreshold, int countThreshold, int[][] arr)
{
int[][] newArray = arrCopy(arr);
for (int j = 0; j < arr.Length; j++)
{
for (int i = 0; i < arr[0].Length; i++)
{
int[] dcfac = dupeCountForAutoCorrect(i, j, distThreshold, countThreshold, arr);
int dupeCount = dcfac[0];
int replacementIndex = dcfac[1];
if (dupeCount <= countThreshold)
{
newArray[j][i] = replacementIndex;
}
}
}
return newArray;
}
private static int[] dupeCountForAutoCorrect(int x, int y, int distThreshold, int countThreshold, int[][] arr)
{
int testedIndex = arr[y][x];
int[] result = new int[2];
Dictionary < int, int > colorCounts = new Dictionary < int, int > ();
for (int j = y - distThreshold; j <= y + distThreshold; j++)
{
for (int i = x - distThreshold; i <= x + distThreshold; i++)
{
if (!(i == x && j == y))
{
try
{
int currentIndex = arr[j][i];
if (currentIndex == testedIndex) result[0]++;
if (result[0] > countThreshold) return result;
if (colorCounts.TryGetValue(currentIndex, out int value))
{
value++;
colorCounts[currentIndex] = value;
}
else
{
colorCounts.Add(currentIndex, 1);
}
}
catch (IndexOutOfRangeException)
{
//do nothing and continue
}
}
}
}
//returns the index with highest count. I don't understand this at all, ripped from Stack Overflow
result[1] = colorCounts.Aggregate((xx, yy) => xx.Value > yy.Value ? xx : yy).Key; | {
"domain": "codereview.stackexchange",
"id": 45469,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, array",
"url": null
} |
c#, performance, array
result[1] = colorCounts.Aggregate((xx, yy) => xx.Value > yy.Value ? xx : yy).Key;
return result;
} | {
"domain": "codereview.stackexchange",
"id": 45469,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, array",
"url": null
} |
c#, performance, array
Helper functions and testing:
public static void testArr()
{
int maxIndex = 5;
int arrWidth = 5;
int arrHeight = 5;
int distThreshold = 1;
int countThreshold = 0;
int[][] originalArray = new int[arrHeight][];
Random rnd = new Random();
for (int j = 0; j < arrHeight; j++)
{
int[] r = new int[arrWidth];
for (int i = 0; i < arrWidth; i++)
{
int rndn = rnd.Next(maxIndex + 1);;
r[i] = rndn;
}
originalArray[j] = r;
}
DateTime nao = DateTime.Now;
int[][] newArr = correctedArray(distThreshold, countThreshold, originalArray);
Console.WriteLine((DateTime.Now - nao).TotalSeconds.ToString() + "seconds");
string origArrString = arrToString(originalArray);
string newArrString = arrToString(newArr);
Console.Write(origArrString + System.Environment.NewLine + newArrString);
}
public static string arrToString(int[][] arr)
{
string result = "";
for (int j = 0; j < arr.Length; j++)
{
result += "[";
for (int i = 0; i < arr[0].Length; i++)
{
int val = arr[j][i];
result += val + (i == arr[0].Length - 1 ? "]" + System.Environment.NewLine : ", ");
}
}
return result;
}
public static int[][] arrCopy(int[][] arr)
{
int[][] result = new int[arr.Length][];
for (int j = 0; j < arr.Length; j++)
{
result[j] = new int[arr[0].Length];
for (int i = 0; i < arr[0].Length; i++)
{
result[j][i] = arr[j][i];
}
}
return result;
}
100*100 array is processed in a little over 3 seconds on my machine which seems a little slow to me. I am very new to C#, so pardon my naming and other convention violations :X
Answer: This submission is about performance.
It does not include any profiler measurements.
robust testing
public static void testArr()
...
int arrWidth = 5;
int arrHeight = 5; | {
"domain": "codereview.stackexchange",
"id": 45469,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, array",
"url": null
} |
c#, performance, array
Prefer a 5 × 6 matrix,
or other non-square shape.
Why?
Sometimes target code will accidentally
invert (x, y) into (y, x),
and we wish to provoke and fix such bugs.
Consider using a distance threshold greater than 1 in your testing,
if you wish to expose performance hotspots.
variant spelling
DateTime nao = DateTime.Now;
You knao perfectly well how to spell that word.
Prefer its standard spelling.
names
In many identifiers you describe something
as an "index" where my understanding is
it's more like a pixel "color" or "value".
if (colorCounts.TryGetValue(currentIndex, out int value))
{
value++;
colorCounts[currentIndex] = value; | {
"domain": "codereview.stackexchange",
"id": 45469,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, array",
"url": null
} |
c#, performance, array
Here value is too vague; prefer count.
common exceptions
For a square matrix of side N, your test code throws
about 12 × N IndexOutOfRangeExceptions,
which seems like perhaps more than you'd prefer
since doing so takes time.
Consider expanding the array with borders,
so we have (N + 2 × distThreshold)² cells in total.
Fill the border with unique serial numbers,
or with periodic pattern of period
at least 1 + 2 * distThreshold.
That way a border value won't be the most popular.
common operations
Each point requests the allocation and deallocation of a Dictionary,
causing GC work.
Maybe hang onto a single Dictionary, and .Clear() it
when starting on a new cell?
Or maybe turn the dictionary into a vector of size C,
the number of colors?
When scanning a raster we re-compute
the same old partial sums several times.
For low values of distThreshold,
such as what your test code uses,
I'm skeptical that one can do much better.
For moderate or large thresholds, consider an alternate approach.
Initialize by making a single scan to find number of distinct
pixel colors, C, in the input matrix.
Depending on size of threshold, allocate either a byte or a UInt16
count matrix, with shape arrWidth × arrHeight × C,
or slightly larger if we have tacked on border cells.
When computing window sums for a moving average,
we can efficiently add a figure from the leading edge
and subtract another figure from the trailing edge.
Similarly, in this situation, we can efficiently compute
"count of certain pixel color in this cell's neighborhood"
by copying the counts we had just finished computing,
increment based on leading edge, and decrement based on trailing edge.
It is perfectly OK to have some garbage counts in the border,
as we won't actually consult them.
Area of neighborhood is quadratic with distThreshold.
For this approach to work well,
number of distinct colors C should be smallish relative to
neighborhood area.
Sometimes result[1] must be set to the majority color, | {
"domain": "codereview.stackexchange",
"id": 45469,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, array",
"url": null
} |
c#, performance, array
neighborhood area.
Sometimes result[1] must be set to the majority color,
and computing this will have O(C) cost.
(It could have O(log N) cost,
but that sounds like a lot of
pqueues.)
simplify the input
Initially computing a color histogram,
the population count of each distinct pixel color,
is fairly cheap.
We might find there's a handful of very popular colors
plus small numbers of rare color values.
It might be acceptable to perform a lossy input transform,
which lumps all unpopular colors together as
a single designated value, or uses a randomly chosen mapping
to turn them into just a few distinct colors.
We could even put our thumb on the scale, so the function
will never return an unpopular color.
This would give us an attractively small C,
at the cost of slightly changing the output.
You wouldn't want to use this technique
in an adversarial setting.
median
The
majority
filter you propose appears to be intended
to cope with salt-and-pepper noise.
It seems like it lies on this neighborhood filtering continuum: | {
"domain": "codereview.stackexchange",
"id": 45469,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, array",
"url": null
} |
c#, performance, array
mean
median
majority
In image regions that are somewhat distant from an edge,
you may be able to get away with dynamically switching
to one of those other filters, taking advantage of
a rapid, mature implementation.
Sampling every Nth pixel neighborhood to support such
a decision may be sufficient to give acceptable results.
Consider relying on the scikit-image implementation of this or
related
filters. | {
"domain": "codereview.stackexchange",
"id": 45469,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, array",
"url": null
} |
rust, iterator
Title: Odometer in Rust
Question: I am trying to implement an odometer in Rust. This should a be an iterator that yields items of type [u16; N] and it should be generic over const N.
Configuration Parameters
The iterator should be configurable with a starting state of type [u16; N] which should be the value yielded on the first iteration, and a limit which should dictate when each element "rolls over" as described in the following section.
Behavior description
On each iteration of the iterator, the rightmost element of the yielded item should be increased by 1 until it reaches limit - 1 at which time it should roll over back to zero and the next leftmost element should be incremented. This process should continue until all elements are limit - 1, after which the iterator is exhausted and should no longer yield any elements.
This behavior is the same as that exhibited by a typical mechanical car odometer when limit == 10.
It can also be thought of as an N-digit counter with radix limit which adds with integer overflow.
Example Outputs
An odometer iterator with initial state [1,2,3] and limit = 4 should yield the following sequence:
[1, 2, 3] // First element yielded is the initial state
[1, 3, 0] // least significant digit rolls over here at `limit - 1 = 4`
[1, 3, 1]
[1, 3, 2]
[1, 3, 3]
[2, 0, 0] // digit 1 and 2 both roll over here
[2, 0, 1]
[2, 0, 2]
[2, 0, 3]
[2, 1, 0]
[2, 1, 1]
[2, 1, 2]
[2, 1, 3]
[2, 2, 0]
[2, 2, 1]
[2, 2, 2]
[2, 2, 3]
[2, 3, 0]
[2, 3, 1]
[2, 3, 2]
[2, 3, 3]
[3, 0, 0] // digit 1 and 2 both roll over here again
[3, 0, 1]
[3, 0, 2]
[3, 0, 3]
[3, 1, 0]
[3, 1, 1]
[3, 1, 2]
[3, 1, 3]
[3, 2, 0]
[3, 2, 1]
[3, 2, 2]
[3, 2, 3]
[3, 3, 0]
[3, 3, 1]
[3, 3, 2]
[3, 3, 3] // All three digits roll over after this element so iteration stops.
Naïve implementation
Here is a naïve implementation with design thought process documented as comments
#[derive(Debug, Clone, Copy)]
struct Odometer<const N: usize> {
state: Option<[u16; N]>,
limit: u16,
} | {
"domain": "codereview.stackexchange",
"id": 45470,
"lm_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, iterator",
"url": null
} |
rust, iterator
impl<const N: usize> Odometer<N> {
/// Increment the odometer's internal state according to the iteration rules. When the
/// odometer is completely exhausted, this should leave the state as None so that iteration
/// halts on the next call to Iterator::next
#[inline]
fn increment(&mut self) {
// Keep track of the number of digits that roll over during this incrementation
let mut rollovers = 0;
// SAFETY: Odometer::increment is only called after verifying that `self.state.is_some()`
// so the unwrap() here is safe.
for digit in self.state.as_mut().unwrap().iter_mut().rev() {
// Increment this digit by 1 with modular arithmetic to implement the digit rollover
// behavior
*digit = (*digit + 1) % self.limit;
if *digit != 0 {
// If the digit is not zero after the increment it did not roll over so the state
// is now final. return immediately
return;
}
// If this line is reached a rollover has occurred on this digit, so increment the
// rollover counter.
rollovers += 1;
}
// If the number of rollovers is N, the iterator is exhausted
if rollovers == N {
self.state = None;
}
}
}
impl<const N: usize> Iterator for Odometer<N> {
type Item = [u16; N];
fn next(&mut self) -> Option<Self::Item> {
// Save a copy of the initial state to return if there is one, otherwise return None early
let initial_state = self.state?;
// Increment the internal state according to the iteration rules
self.increment();
// Return the copy of the initial state saved before the call to Self::increment
Some(initial_state)
}
}
Playground link | {
"domain": "codereview.stackexchange",
"id": 45470,
"lm_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, iterator",
"url": null
} |
rust, iterator
Playground link
Answer: The code is easy to follow. It is structured well and well formatted. Also variables are named sensibly.
A few possible improvements below:
Don't assume valid state
In increment() don't assume valid state. Check for it!
Use comments sparingly
Currently you have a lot of comments. The only really useful comment being the one that hints on the assumption of valid state in increment(). You may remove the other comments as they don't clarify anything.
Get rid of unnecessary state
Currently you track rollovers (usually called carry on additions), which is not necessary.
Make the code more generic
You can generalize the type of stored variables using a generic type and restricting it via num_traits:
[package]
name = "odometer"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
num-traits = "0.2.18"
lib.rs:
use num_traits::{One, Zero};
use std::ops::Rem;
pub struct Odometer<const DIGITS: usize, T>
where
T: Copy + Eq + Rem<Output = T> + One + Zero,
{
digits: Option<[T; DIGITS]>,
modulo: T,
}
impl<const DIGITS: usize, T> Odometer<DIGITS, T>
where
T: Copy + Eq + Rem<Output = T> + One + Zero,
{
pub const fn new(modulo: T) -> Self {
Self {
digits: None,
modulo,
}
}
/// Increment the odometer.
///
/// # Errors
/// Returns [`T::one()`] as carry on overflow.
fn increment(&mut self) -> Result<(), T> {
if let Some(digits) = &mut self.digits {
increment(digits, self.modulo)
} else {
self.digits.replace([T::zero(); DIGITS]);
Ok(())
}
}
}
impl<const DIGITS: usize, T> Iterator for Odometer<DIGITS, T>
where
T: Copy + Eq + Rem<Output = T> + One + Zero,
{
type Item = [T; DIGITS];
fn next(&mut self) -> Option<Self::Item> {
self.increment().ok()?;
self.digits
}
} | {
"domain": "codereview.stackexchange",
"id": 45470,
"lm_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, iterator",
"url": null
} |
rust, iterator
fn increment<const DIGITS: usize, T>(digits: &mut [T; DIGITS], modulo: T) -> Result<(), T>
where
T: Copy + Eq + Rem<Output = T> + One + Zero,
{
for digit in digits.iter_mut().rev() {
*digit = (*digit + T::one()) % modulo;
if *digit != T::zero() {
return Ok(());
}
}
Err(T::one())
}
main.rs:
use odometer::Odometer;
fn main() {
for step in Odometer::<3, u16>::new(4) {
println!("{step:?}");
}
} | {
"domain": "codereview.stackexchange",
"id": 45470,
"lm_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, iterator",
"url": null
} |
c#, strings, .net, user-interface, string-processing
Title: Truncating/abbreviating strings in the middle with an ellipsis (…) (or other) separators with a fixed character limit | {
"domain": "codereview.stackexchange",
"id": 45471,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, strings, .net, user-interface, string-processing",
"url": null
} |
c#, strings, .net, user-interface, string-processing
Question: Problem
For some user-facing string, I want to truncate it to some given maximum length (also useful for file name/path lengths on Windows etc.). However, I want to do it a little more elaborately than just appending ... or … or so at the end, as I want to place that character in the middle.
I.e. I want both the start and the end of the string be visible, if truncated.
Of course, if the string is shorter, it does not need truncation and should be ignored.
Actually, I later saw in Java you have a great method StringUtils.abbrevate in Apache Commons that goes much further, where abbreviateMiddle may actually be, what I want to do here.
For my case, I choose to value the last side/end more, i.e. you may get 12…def instead of 123…ef if truncating 1234567890abcdef to 6 characters. But that is an implementation detail, IMHO.
Solution
I started with ChatGPT making the basics/an idea and then some tests. I iterated on that and found out about the nice StringBuilder, which I first passed to ChatGPT to adjust. Later I manually needed to adjust the code, as ChatGPT really has problems with counting and such applied maths (note I did use the GPT 3.5 version).
Also the tests (and somewhat TDD) really had helped me to get fix the issue, with odd maximum length numbers, as these resulted in strings being one character too short.
The last thing I changed, implementation-wise, was to adjust it to have a configurable separator (aka "just" a Resharper refactor -> Introduce parameter and some test adjustments), because it was previously hardcoded to .... Thus, I also changed the default to …, which is a much nicer Unicode character for an ellipsis.
I finished it by converting it to an extension method and documenting it, as that may be generally useful. | {
"domain": "codereview.stackexchange",
"id": 45471,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, strings, .net, user-interface, string-processing",
"url": null
} |
c#, strings, .net, user-interface, string-processing
Obviously I tried following clean code and write as few commends as necessary. Also, the project I am working with, has a test pattern/coding guideline, where I should put tests for a method in a subclass named after that method, so tests get more tidy (similar to describe blocks in jasmine).
I also thought of using/switching to uint for parameters that can never be < 0. However, even .NET's StringBuilder just uses a "usual" ArgumentOutOfRangeException and uses int. As such, using uint here would just require casting and the benefit is unclear, IMHO, if even .NET itself does not uses uint here. (Though I am open for discussion, also about the fact why Microsoft implemented it that way in StringBuilder.)
Implementation
using System;
using System.Diagnostics;
using System.Text; | {
"domain": "codereview.stackexchange",
"id": 45471,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, strings, .net, user-interface, string-processing",
"url": null
} |
c#, strings, .net, user-interface, string-processing
/// <summary>
/// Common extensions for manipulating strings.
/// </summary>
public static class StringExtensions
{
/// <summary>
/// This truncates/abbreviates the string and places the separator as a user-facing indicator <i>in the middle</i> of that string.
/// </summary>
/// <remarks>For example "1234567890abcdef" gets truncated as "12…def" if you have a limit of 6 characters.</remarks>
/// <param name="input">the string to truncate</param>
/// <param name="lengthLimit">the maximum length of the resulting string</param>
/// <param name="separator">optionally, the separator to use, by default the ellipsis …</param>
/// <returns>The truncated string, if necessary.</returns>
/// <exception cref="ArgumentException">if the input parameters are invalid</exception>
public static string TruncateInMiddle(this string input, int lengthLimit, string separator = "…")
{
var middleIndex = lengthLimit / 2;
if (input.Length <= lengthLimit)
return input;
if (separator.Length > lengthLimit)
throw new ArgumentOutOfRangeException(nameof(separator),
$"Separator \"{separator}\" (length: {separator.Length}) must be _NOT_ be larger than the lengthLimit {lengthLimit}."
);
if (middleIndex < separator.Length)
throw new ArgumentOutOfRangeException(nameof(lengthLimit),
$"Length limit {lengthLimit} must be larger than double of length of the separation string \"{separator}\" (length: {separator.Length})x2 for proper display."
);
var result = new StringBuilder(lengthLimit, lengthLimit);
result.Append(input, 0, middleIndex - separator.Length);
result.Append(separator);
var remainingLength = result.Length;
Debug.Assert(remainingLength == middleIndex, "result.Length == middleIndex");
if (lengthLimit % 2 != 0)
remainingLength++; | {
"domain": "codereview.stackexchange",
"id": 45471,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, strings, .net, user-interface, string-processing",
"url": null
} |
c#, strings, .net, user-interface, string-processing
if (lengthLimit % 2 != 0)
remainingLength++;
result.Append(input, input.Length - remainingLength, remainingLength);
return result.ToString();
}
}
Tests
Using NUnit and FluentAssertions.
[TestOf(typeof(StringExtensions))]
public class StringExtensionsTest
{
public class TruncateInMiddle : StringExtensionsTest
{
[TestCase(0, 1)]
[TestCase(1, 2)]
[TestCase(2, 3)]
[TestCase(3, 4)]
[TestCase(4, 5)]
[TestCase(1, 5)]
public void ThrowsIfSeparatorIsTooLong(int lengthLimit, int separatorLength)
{
// Arrange
var separator = TestContext.CurrentContext.Random.GetString(separatorLength);
// Act
var action = () => "doesNotMatter".TruncateInMiddle(lengthLimit, separator);
// Assert
action.Should().ThrowExactly<ArgumentOutOfRangeException>()
.WithMessage("*(Parameter 'separator')")
.WithMessage("*Separator * must be _NOT_ be larger than * lengthLimit*")
.WithMessage($"*{lengthLimit}*")
.WithMessage($"*\"{separator}\"*")
.WithMessage($"*(length: {separatorLength}*");
}
[Test]
public void ThrowsForTooSmallLengthLimits([Range(4, 5)] int lengthLimit)
{
// Act
var action = () => "doesNotMatter".TruncateInMiddle(lengthLimit, "...");
// Assert
action.Should().ThrowExactly<ArgumentOutOfRangeException>()
.WithMessage("*(Parameter 'lengthLimit')")
.WithMessage("*Length limit * must be larger than double of length of the separation string*")
.WithMessage($"*{lengthLimit}*")
.WithMessage("*\"...\"*")
.WithMessage("*(length: 3)x2*");
} | {
"domain": "codereview.stackexchange",
"id": 45471,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, strings, .net, user-interface, string-processing",
"url": null
} |
c#, strings, .net, user-interface, string-processing
[TestCase("abcde", 4, "..", ExpectedResult = "..de")]
[TestCase("123456789", 5, "..", ExpectedResult = "..789")]
[TestCase("1234567890abcdef", 6, "...", ExpectedResult = "...def")]
[TestCase("1234567890abcdef", 6, "…", ExpectedResult = "12…def")]
public string TruncatesMinimalExamplesCorrectly(string inputString, int lengthLimit, string separator)
{
// Act
var outputString = inputString.TruncateInMiddle(lengthLimit, separator);
Debug.WriteLine(outputString);
// Assert
outputString.Should().HaveLength(lengthLimit)
.And.Contain(separator);
return outputString;
}
[Test]
public void AppliesLengthLimit([Random(100, 150, 5)] int randomLength, [Random(2, 100, 5)] int lengthLimit)
{
// Arrange
var inputString = TestContext.CurrentContext.Random.GetString(randomLength);
Debug.WriteLine(inputString);
// Act
var outputString = inputString.TruncateInMiddle(lengthLimit);
Debug.WriteLine(outputString);
// Assert
outputString.Should().HaveLength(lengthLimit)
.And.Contain("…");
}
[Test]
public void ReturnsStringsSmallerThanLimitUnchanged([Random(2, 100, 5)] int randomLength,
[Random(100, 150, 5)] int lengthLimit)
{
// Arrange
var inputString = TestContext.CurrentContext.Random.GetString(randomLength);
Debug.WriteLine(inputString);
// Act
var outputString = inputString.TruncateInMiddle(lengthLimit);
Debug.WriteLine(outputString);
// Assert
outputString.Should().Be(inputString);
}
}
}
.NET 6.0 | {
"domain": "codereview.stackexchange",
"id": 45471,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, strings, .net, user-interface, string-processing",
"url": null
} |
c#, strings, .net, user-interface, string-processing
// Assert
outputString.Should().Be(inputString);
}
}
}
.NET 6.0
Answer: Let me present you an alternative version of your TruncateInMiddle which utilizes ReadOnlySpans. The core logic can be rewritten like this
ReadOnlySpan<char> inputSpan = input.AsSpan();
var prefixEnd = middleIndex - separator.Length;
ReadOnlySpan<char> prefix = inputSpan[..prefixEnd];
var remainingLength = lengthLimit % 2 == 0 ? middleIndex : middleIndex + 1;
var suffixStart = input.Length - remainingLength;
ReadOnlySpan<char> suffix = inputSpan[suffixStart..];
return string.Concat(prefix, separator, suffix);
prefix points to the beginning of the input for a given length
suffix points to the end of the input from a calculated index
the end result is a simple string concatenation
I've run a simple benchmark to measure my implementation
BenchmarkRunner.Run<TruncateExperiment>();
[HtmlExporter]
[MemoryDiagnoser]
[SimpleJob(BenchmarkDotNet.Engines.RunStrategy.ColdStart, launchCount: 20)]
public class TruncateExperiment
{
List<string> inputs = new();
[GlobalSetup]
public void Setup()
{
for(int i = 1; i < 100; i++)
{
inputs.Add(string.Join("",
Enumerable.Repeat(0, Random.Shared.Next(100))
.Select(n => (char)Random.Shared.Next(127))));
}
}
[Benchmark(Baseline = true)]
public void RunBaseLine()
{
foreach(var input in inputs)
input.TruncateInMiddle(6);
}
[Benchmark]
public void RunNew()
{
foreach(var input in inputs)
input.TruncateInMiddleNew(6);
}
} | {
"domain": "codereview.stackexchange",
"id": 45471,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, strings, .net, user-interface, string-processing",
"url": null
} |
c#, strings, .net, user-interface, string-processing
The results on my machine
| Method | Mean | Error | StdDev | Median | Ratio | RatioSD | Allocated | Alloc Ratio |
|------------ |---------:|---------:|----------:|---------:|------:|--------:|----------:|------------:|
| RunBaseLine | 8.502 us | 2.885 us | 39.154 us | 4.333 us | 1.00 | 0.00 | 11.97 KB | 1.00 |
| RunNew | 7.384 us | 2.783 us | 37.761 us | 3.375 us | 0.80 | 0.18 | 4.31 KB | 0.36 |
It's a bit faster and uses less memory. | {
"domain": "codereview.stackexchange",
"id": 45471,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, strings, .net, user-interface, string-processing",
"url": null
} |
javascript, logging
Title: Manage repetitive/similar structures (logging & try/catch blocks)
Question: I'm writing a web bot using puppeteer and I'm logging (using winston) every action the bots does and running it inside try/catch blocks.
For automating these processes and avoid code repetition I created this function:
module.exports = {
webAction: async function (logger, msg, func, ...args)
{
return new Promise(async (resolve) => {
let actionMessage, actionLevel;
try
{
await func(...args);
actionMessage = msg;
actionLevel = 'info';
}
catch (error)
{
actionMessage = "Error while executing (" + msg + ") function.\n---\n" + error.message + "\n---";
actionLevel = 'error';
}
finally
{
logger.log({
level: actionLevel,
message: actionMessage
})
}
resolve('Fullfilment value of Promise');
})
},
I use the previous function with arrow functions and normal/regular functions as arguments for making it as dynamic as it can be:
const htmlCode = await page.evaluate(() => document.querySelector('*').outerHTML);
await utils.webAction(
logger, 'Save web code as html file',
(() => (utils.saveStrAsFile('htmlCodeMP_NewItem.html', htmlCode)))
);
let titleID, priceID;
await utils.webAction(
logger, 'Find Ids',
(() => ([titleID, priceID] = utils.findDynamicIdsMP(htmlCode)))
);
await utils.webAction(
logger, 'Enter item title', utils.webType,
page, 'FooTitle', `input[id="${titleID}"]` // Arguments of `webType`
);
await utils.webAction(
logger, 'Enter item price', utils.webType,
page, '1234', `input[id="${priceID}"]` // Arguments of `webType`
);
await utils.webAction(
logger, 'Click item category dropdown menu',
(() => (page.click(constants.cssMpCreateItemCategory))),
); | {
"domain": "codereview.stackexchange",
"id": 45472,
"lm_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, logging",
"url": null
} |
javascript, logging
Is this a good practice?
I honestly thinks it avoids a lot repetition of code (at least the try/catch blocks & the logger block).
But on the other part I'm thinking that there must be a better approach or professional way of doing this.
I'm no professional nor skilled in Javascript, I'm an amateur in Javascript.
Any advice is highly appreciated/
Thanks in advanced ;)
Answer: Passing in arguments as a list of arguments into webAction becomes hard to read. My suggestion would be as follows
Make the arguments an object
Make the func a callback that is invoked with no arguments. Don't have webAction know anything about what function it is running
return the func's return value in webAction.
const utils = {
webAction: async ({ logger, msg, func }) => {
return new Promise(async (resolve) => {
let res
let actionMessage, actionLevel
try {
res = await func()
actionMessage = msg
actionLevel = 'info'
}
catch (error) {
actionMessage = "Error while executing (" + msg + ") function.\n---\n" + error.message + "\n---"
actionLevel = 'error'
}
finally {
logger.log({
level: actionLevel,
message: actionMessage,
})
}
resolve(res)
})
},
}
Notice how func is invoked with no arguments. Then in its usage:
const htmlCode = await page.evaluate(() => document.querySelector('*').outerHTML);
await utils.webAction({
logger,
msg: 'Save web code as html file',
func: () => utils.saveStrAsFile('htmlCodeMP_NewItem.html', htmlCode)
})
const [titleID, priceID] = await utils.webAction({
func: () => utils.findDynamicIdsMP('htmlCode'),
logger,
msg: 'Find Ids',
}) | {
"domain": "codereview.stackexchange",
"id": 45472,
"lm_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, logging",
"url": null
} |
javascript, logging
await utils.webAction({
func: () => utils.webType(page, 'FooTitle', `input[id="${titleID}"]`),
logger,
msg: 'Enter item title',
}) | {
"domain": "codereview.stackexchange",
"id": 45472,
"lm_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, logging",
"url": null
} |
python, unit-testing, binary-search
Title: Testing binary search module, based on bisect
Question: The bisect module can only find the index to insert an element. I created a simple class based on the bisect module for precise searching and covered all the edge cases that came to mind with tests.
Could you please check the correctness of the tests for the binary search extension module? I want to make sure that the tests match the function documentation (docstrings). Well, maybe more you could review the code, or suggest optimizations?
My code:
from bisect import bisect_left, bisect_right
class BisectFinder:
''' This class contains some convenient binary search functions for an element in a list '''
@staticmethod
def find_left_lt(a, x, lo=0, hi=None, key=None):
'''Finds the index of the leftmost (among duplicates) element that is strictly less than X.
A[index] < X
A[index] == a2
[
a1{<x}, a1{<x}, A[index], a2{<x}, a2{<x},
a3{<=x}, a3{<=x}, a4{<=x}, a4{<=x},
a5{==x}, a5{==x},
a7{>=x}, a7{>=x}, a8{>=x}, a8{>=x},
a9{>x}, a9{>x}, a10{>x}, a10{>x}
]
'''
index = bisect_left(a, x, lo=lo, hi=hi, key=key)
if len(a) > 0 and index < len(a) + 1 and a[index - 1] < x:
return bisect_left(a, a[index - 1], lo=lo, hi=index-1, key=key)
raise ValueError("No elements less than x found.") | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
@staticmethod
def find_left_le(a, x, lo=0, hi=None, key=None):
'''Finds the index of the leftmost (among duplicates) element that is less than or equal to X.
A[index] <= X
A[index] == a4
[
a1{<x}, a1{<x}, a2{<x}, a2{<x},
a3{<=x}, a3{<=x}, A[index], a4{<=x}, a4{<=x},
a5{==x}, a5{==x},
a7{>=x}, a7{>=x}, a8{>=x}, a8{>=x},
a9{>x}, a9{>x}, a10{>x}, a10{>x}
]
'''
index = bisect_right(a, x, lo=lo, hi=hi, key=key)
if len(a) > 0 and index < len(a) + 1 and a[index - 1] <= x:
return bisect_left(a, a[index - 1], lo=lo, hi=index-1, key=key)
raise ValueError("No elements less than or equal to x found.")
@staticmethod
def find_left_eq(a, x, lo=0, hi=None, key=None):
'''Finds the index of the leftmost (among duplicates) element that is equal to X.
A[index] == X
A[index] == a5
[
a1{<x}, a1{<x}, a2{<x}, a2{<x},
a3{<=x}, a3{<=x}, a4{<=x}, a4{<=x},
A[index], a5{==x}, a5{==x},
a7{>=x}, a7{>=x}, a8{>=x}, a8{>=x},
a9{>x}, a9{>x}, a10{>x}, a10{>x}
]
'''
index = bisect_left(a, x, lo=lo, hi=hi, key=key)
if index != len(a) and a[index] == x:
return index
raise ValueError("No elements equal to x found.") | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
@staticmethod
def find_left_ge(a, x, lo=0, hi=None, key=None):
'''Finds the index of the leftmost (among duplicates) element that is greater than or equal to X.
A[index] >= X
A[index] == a7
[
a1{<x}, a1{<x}, a2{<x}, a2{<x},
a3{<=x}, a3{<=x}, a4{<=x}, a4{<=x},
a5{==x}, a5{==x},
A[index], a7{>=x}, a7{>=x}, a8{>=x}, a8{>=x},
a9{>x}, a9{>x}, a10{>x}, a10{>x}
]
'''
index = bisect_left(a, x, lo=lo, hi=hi, key=key)
if index != len(a):
return index
raise ValueError("No elements greater than or equal to x found.")
@staticmethod
def find_left_gt(a, x, lo=0, hi=None, key=None):
'''Finds the index of the leftmost (among duplicates) element that is strictly greater than X.
A[index] > X
A[index] == a9
[
a1{<x}, a1{<x}, a2{<x}, a2{<x},
a3{<=x}, a3{<=x}, a4{<=x}, a4{<=x},
a5{==x}, a5{==x},
a7{>=x}, a7{>=x}, a8{>=x}, a8{>=x},
A[index], a9{>x}, a9{>x}, a10{>x}, a10{>x}
]
'''
index = bisect_right(a, x, lo=lo, hi=hi, key=key)
if index != len(a):
return index
raise ValueError("No elements greater than x found.") | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
@staticmethod
def find_right_lt(a, x, lo=0, hi=None, key=None):
'''Finds the index of the rightmost (among duplicates) element that is strictly less than X.
A[index] < X
A[index] == a2
[
a1{<x}, a1{<x}, a2{<x}, a2{<x}, A[index],
a3{<=x}, a3{<=x}, a4{<=x}, a4{<=x},
a5{==x}, a5{==x},
a7{>=x}, a7{>=x}, a8{>=x}, a8{>=x},
a9{>x}, a9{>x}, a10{>x}, a10{>x}
]
'''
index = bisect_left(a, x, lo=lo, hi=hi, key=key)
if index:
return index-1
raise ValueError("No elements less than x found.")
@staticmethod
def find_right_le(a, x, lo=0, hi=None, key=None):
'''Finds the index of the rightmost (among duplicates) element that is less than or equal to X.
A[index] <= X
A[index] == a4
[
a1{<x}, a1{<x}, a2{<x}, a2{<x},
a3{<=x}, a3{<=x}, a4{<=x}, a4{<=x}, A[index],
a5{==x}, a5{==x},
a7{>=x}, a7{>=x}, a8{>=x}, a8{>=x},
a9{>x}, a9{>x}, a10{>x}, a10{>x}
]
'''
index = bisect_right(a, x, lo=lo, hi=hi, key=key)
if index:
return index-1
raise ValueError("No elements less than or equal to x found.") | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
@staticmethod
def find_right_eq(a, x, lo=0, hi=None, key=None):
'''Finds the index of the rightmost (among duplicates) element that is equal to X.
A[index] == X
A[index] == a5
[
a1{<x}, a1{<x}, a2{<x}, a2{<x},
a3{<=x}, a3{<=x}, a4{<=x}, a4{<=x},
a5{==x}, a5{==x}, A[index],
a7{>=x}, a7{>=x}, a8{>=x}, a8{>=x},
a9{>x}, a9{>x}, a10{>x}, a10{>x}
]
'''
index = bisect_left(a, x, lo=lo, hi=hi, key=key)
if index != len(a) and a[index] == x:
return bisect_right(a, a[index], lo=index, hi=hi, key=key) - 1
raise ValueError("No elements equal to x found.")
@staticmethod
def find_right_ge(a, x, lo=0, hi=None, key=None):
'''Finds the index of the rightmost (among duplicates) element that is greater than or equal to X.
A[index] >= X
A[index] == a7
[
a1{<x}, a1{<x}, a2{<x}, a2{<x},
a3{<=x}, a3{<=x}, a4{<=x}, a4{<=x},
a5{==x}, a5{==x},
a7{>=x}, a7{>=x}, A[index], a8{>=x}, a8{>=x},
a9{>x}, a9{>x}, a10{>x}, a10{>x}
]
'''
index = bisect_left(a, x, lo=lo, hi=hi, key=key)
if index != len(a):
return bisect_right(a, a[index], lo=index, hi=hi, key=key) - 1
raise ValueError("No elements greater than or equal to x found.") | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
@staticmethod
def find_right_gt(a, x, lo=0, hi=None, key=None):
'''Finds the index of the rightmost (among duplicates) element that is strictly greater than X.
A[index] > X
A[index] == a9
[
a1{<x}, a1{<x}, a2{<x}, a2{<x},
a3{<=x}, a3{<=x}, a4{<=x}, a4{<=x},
a5{==x}, a5{==x},
a7{>=x}, a7{>=x}, a8{>=x}, a8{>=x},
a9{>x}, a9{>x}, A[index], a10{>x}, a10{>x}
]
'''
index = bisect_right(a, x, lo=lo, hi=hi, key=key)
if index != len(a):
return bisect_right(a, a[index], lo=index, hi=hi, key=key) - 1
raise ValueError("No elements greater than x found.")
My tests:
import unittest
from unittest import TestCase
from implements import BisectFinder
class TestBisectFinder(TestCase):
def setUp(self):
self.empty_list = [] # 10
self.one_element_list = [5] # 2, 5, 7
self.two_element_list = [3, 8] # 2, 3, 6, 8, 9
self.three_element_list = [2, 7, 7] # 1, 2, 4, 7, 8
self.four_element_list = [2, 2, 2, 5] # 1, 2, 4, 5, 6
self.five_element_list = [1, 5, 5, 5, 9] # 0, 1, 2, 5, 7, 9, 10
# Tests for the find_left_lt function
def test_find_left_lt_empty_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_lt, self.empty_list, 10)
def test_find_left_lt_one_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_lt, self.one_element_list, 2)
self.assertRaises(ValueError, BisectFinder.find_left_lt, self.one_element_list, 5)
self.assertEqual(BisectFinder.find_left_lt(self.one_element_list, 7), 0) | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
def test_find_left_lt_two_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_lt, self.two_element_list, 2)
self.assertRaises(ValueError, BisectFinder.find_left_lt, self.two_element_list, 3)
self.assertEqual(BisectFinder.find_left_lt(self.two_element_list, 6), 0)
self.assertEqual(BisectFinder.find_left_lt(self.two_element_list, 8), 0)
self.assertEqual(BisectFinder.find_left_lt(self.two_element_list, 9), 1)
def test_find_left_lt_three_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_lt, self.three_element_list, 1)
self.assertRaises(ValueError, BisectFinder.find_left_lt, self.three_element_list, 2)
self.assertEqual(BisectFinder.find_left_lt(self.three_element_list, 4), 0)
self.assertEqual(BisectFinder.find_left_lt(self.three_element_list, 7), 0)
self.assertEqual(BisectFinder.find_left_lt(self.three_element_list, 8), 1)
def test_find_left_lt_four_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_lt, self.four_element_list, 1)
self.assertRaises(ValueError, BisectFinder.find_left_lt, self.four_element_list, 2)
self.assertEqual(BisectFinder.find_left_lt(self.four_element_list, 4), 0)
self.assertEqual(BisectFinder.find_left_lt(self.four_element_list, 5), 0)
self.assertEqual(BisectFinder.find_left_lt(self.four_element_list, 6), 3) | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
def test_find_left_lt_five_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_lt, self.five_element_list, 0)
self.assertRaises(ValueError, BisectFinder.find_left_lt, self.five_element_list, 1)
self.assertEqual(BisectFinder.find_left_lt(self.five_element_list, 2), 0)
self.assertEqual(BisectFinder.find_left_lt(self.five_element_list, 5), 0)
self.assertEqual(BisectFinder.find_left_lt(self.five_element_list, 7), 1)
self.assertEqual(BisectFinder.find_left_lt(self.five_element_list, 9), 1)
self.assertEqual(BisectFinder.find_left_lt(self.five_element_list, 10), 4)
# Tests for the find_left_le function
def test_find_left_le_empty_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_le, self.empty_list, 10)
def test_find_left_le_one_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_le, self.one_element_list, 2)
self.assertEqual(BisectFinder.find_left_le(self.one_element_list, 5), 0)
self.assertEqual(BisectFinder.find_left_le(self.one_element_list, 7), 0) | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
def test_find_left_le_two_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_le, self.two_element_list, 2)
self.assertEqual(BisectFinder.find_left_le(self.two_element_list, 3), 0)
self.assertEqual(BisectFinder.find_left_le(self.two_element_list, 6), 0)
self.assertEqual(BisectFinder.find_left_le(self.two_element_list, 8), 1)
self.assertEqual(BisectFinder.find_left_le(self.two_element_list, 9), 1)
def test_find_left_le_three_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_le, self.three_element_list, 1)
self.assertEqual(BisectFinder.find_left_le(self.three_element_list, 2), 0)
self.assertEqual(BisectFinder.find_left_le(self.three_element_list, 4), 0)
self.assertEqual(BisectFinder.find_left_le(self.three_element_list, 7), 1)
self.assertEqual(BisectFinder.find_left_le(self.three_element_list, 8), 1)
def test_find_left_le_four_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_le, self.four_element_list, 1)
self.assertEqual(BisectFinder.find_left_le(self.four_element_list, 2), 0)
self.assertEqual(BisectFinder.find_left_le(self.four_element_list, 4), 0)
self.assertEqual(BisectFinder.find_left_le(self.four_element_list, 5), 3)
self.assertEqual(BisectFinder.find_left_le(self.four_element_list, 6), 3) | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
def test_find_left_le_five_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_le, self.five_element_list, 0)
self.assertEqual(BisectFinder.find_left_le(self.five_element_list, 1), 0)
self.assertEqual(BisectFinder.find_left_le(self.five_element_list, 2), 0)
self.assertEqual(BisectFinder.find_left_le(self.five_element_list, 5), 1)
self.assertEqual(BisectFinder.find_left_le(self.five_element_list, 7), 1)
self.assertEqual(BisectFinder.find_left_le(self.five_element_list, 9), 4)
self.assertEqual(BisectFinder.find_left_le(self.five_element_list, 10), 4)
# Tests for the find_left_eq function
def test_find_left_eq_empty_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_eq, self.empty_list, 10)
def test_find_left_eq_one_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_eq, self.one_element_list, 2)
self.assertEqual(BisectFinder.find_left_eq(self.one_element_list, 5), 0)
self.assertRaises(ValueError, BisectFinder.find_left_eq, self.one_element_list, 7) | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
def test_find_left_eq_two_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_eq, self.two_element_list, 2)
self.assertEqual(BisectFinder.find_left_eq(self.two_element_list, 3), 0)
self.assertRaises(ValueError, BisectFinder.find_left_eq, self.two_element_list, 6)
self.assertEqual(BisectFinder.find_left_eq(self.two_element_list, 8), 1)
self.assertRaises(ValueError, BisectFinder.find_left_eq, self.two_element_list, 9)
def test_find_left_eq_three_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_eq, self.three_element_list, 1)
self.assertEqual(BisectFinder.find_left_eq(self.three_element_list, 2), 0)
self.assertRaises(ValueError, BisectFinder.find_left_eq, self.three_element_list, 4)
self.assertEqual(BisectFinder.find_left_eq(self.three_element_list, 7), 1)
self.assertRaises(ValueError, BisectFinder.find_left_eq, self.three_element_list, 8)
def test_find_left_eq_four_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_eq, self.four_element_list, 1)
self.assertEqual(BisectFinder.find_left_eq(self.four_element_list, 2), 0)
self.assertRaises(ValueError, BisectFinder.find_left_eq, self.four_element_list, 4)
self.assertEqual(BisectFinder.find_left_eq(self.four_element_list, 5), 3)
self.assertRaises(ValueError, BisectFinder.find_left_eq, self.four_element_list, 6) | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
def test_find_left_eq_five_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_eq, self.five_element_list, 0)
self.assertEqual(BisectFinder.find_left_eq(self.five_element_list, 1), 0)
self.assertRaises(ValueError, BisectFinder.find_left_eq, self.five_element_list, 2)
self.assertEqual(BisectFinder.find_left_eq(self.five_element_list, 5), 1)
self.assertRaises(ValueError, BisectFinder.find_left_eq, self.five_element_list, 7)
self.assertEqual(BisectFinder.find_left_eq(self.five_element_list, 9), 4)
self.assertRaises(ValueError, BisectFinder.find_left_eq, self.five_element_list, 10)
# Tests for the find_left_ge function
def test_find_left_ge_empty_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_ge, self.empty_list, 10)
def test_find_left_ge_one_element_list(self):
self.assertEqual(BisectFinder.find_left_ge(self.one_element_list, 2), 0)
self.assertEqual(BisectFinder.find_left_ge(self.one_element_list, 5), 0)
self.assertRaises(ValueError, BisectFinder.find_left_ge, self.one_element_list, 7)
def test_find_left_ge_two_element_list(self):
self.assertEqual(BisectFinder.find_left_ge(self.two_element_list, 2), 0)
self.assertEqual(BisectFinder.find_left_ge(self.two_element_list, 3), 0)
self.assertEqual(BisectFinder.find_left_ge(self.two_element_list, 6), 1)
self.assertEqual(BisectFinder.find_left_ge(self.two_element_list, 8), 1)
self.assertRaises(ValueError, BisectFinder.find_left_ge, self.two_element_list, 9) | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
def test_find_left_ge_three_element_list(self):
self.assertEqual(BisectFinder.find_left_ge(self.three_element_list, 1), 0)
self.assertEqual(BisectFinder.find_left_ge(self.three_element_list, 2), 0)
self.assertEqual(BisectFinder.find_left_ge(self.three_element_list, 4), 1)
self.assertEqual(BisectFinder.find_left_ge(self.three_element_list, 7), 1)
self.assertRaises(ValueError, BisectFinder.find_left_ge, self.three_element_list, 8)
def test_find_left_ge_four_element_list(self):
self.assertEqual(BisectFinder.find_left_ge(self.four_element_list, 1), 0)
self.assertEqual(BisectFinder.find_left_ge(self.four_element_list, 2), 0)
self.assertEqual(BisectFinder.find_left_ge(self.four_element_list, 4), 3)
self.assertEqual(BisectFinder.find_left_ge(self.four_element_list, 5), 3)
self.assertRaises(ValueError, BisectFinder.find_left_ge, self.four_element_list, 6)
def test_find_left_ge_five_element_list(self):
self.assertEqual(BisectFinder.find_left_ge(self.five_element_list, 0), 0)
self.assertEqual(BisectFinder.find_left_ge(self.five_element_list, 1), 0)
self.assertEqual(BisectFinder.find_left_ge(self.five_element_list, 2), 1)
self.assertEqual(BisectFinder.find_left_ge(self.five_element_list, 5), 1)
self.assertEqual(BisectFinder.find_left_ge(self.five_element_list, 7), 4)
self.assertEqual(BisectFinder.find_left_ge(self.five_element_list, 9), 4)
self.assertRaises(ValueError, BisectFinder.find_left_ge, self.five_element_list, 10)
# Tests for the find_left_gt function
def test_find_left_gt_empty_list(self):
self.assertRaises(ValueError, BisectFinder.find_left_gt, self.empty_list, 10) | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
def test_find_left_gt_one_element_list(self):
self.assertEqual(BisectFinder.find_left_gt(self.one_element_list, 2), 0)
self.assertRaises(ValueError, BisectFinder.find_left_gt, self.one_element_list, 5)
self.assertRaises(ValueError, BisectFinder.find_left_gt, self.one_element_list, 7)
def test_find_left_gt_two_element_list(self):
self.assertEqual(BisectFinder.find_left_gt(self.two_element_list, 2), 0)
self.assertEqual(BisectFinder.find_left_gt(self.two_element_list, 3), 1)
self.assertEqual(BisectFinder.find_left_gt(self.two_element_list, 6), 1)
self.assertRaises(ValueError, BisectFinder.find_left_gt, self.two_element_list, 8)
self.assertRaises(ValueError, BisectFinder.find_left_gt, self.two_element_list, 9) | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
def test_find_left_gt_three_element_list(self):
self.assertEqual(BisectFinder.find_left_gt(self.three_element_list, 1), 0)
self.assertEqual(BisectFinder.find_left_gt(self.three_element_list, 2), 1)
self.assertEqual(BisectFinder.find_left_gt(self.three_element_list, 4), 1)
self.assertRaises(ValueError, BisectFinder.find_left_gt, self.three_element_list, 7)
self.assertRaises(ValueError, BisectFinder.find_left_gt, self.three_element_list, 8)
def test_find_left_gt_four_element_list(self):
self.assertEqual(BisectFinder.find_left_gt(self.four_element_list, 1), 0)
self.assertEqual(BisectFinder.find_left_gt(self.four_element_list, 2), 3)
self.assertEqual(BisectFinder.find_left_gt(self.four_element_list, 4), 3)
self.assertRaises(ValueError, BisectFinder.find_left_gt, self.four_element_list, 5)
self.assertRaises(ValueError, BisectFinder.find_left_gt, self.four_element_list, 6)
def test_find_left_gt_five_element_list(self):
self.assertEqual(BisectFinder.find_left_gt(self.five_element_list, 0), 0)
self.assertEqual(BisectFinder.find_left_gt(self.five_element_list, 1), 1)
self.assertEqual(BisectFinder.find_left_gt(self.five_element_list, 2), 1)
self.assertEqual(BisectFinder.find_left_gt(self.five_element_list, 5), 4)
self.assertEqual(BisectFinder.find_left_gt(self.five_element_list, 7), 4)
self.assertRaises(ValueError, BisectFinder.find_left_gt, self.five_element_list, 9)
self.assertRaises(ValueError, BisectFinder.find_left_gt, self.five_element_list, 10)
# Tests for the find_right_lt function
def test_find_right_lt_empty_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_lt, self.empty_list, 10) | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
def test_find_right_lt_one_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_lt, self.one_element_list, 2)
self.assertRaises(ValueError, BisectFinder.find_right_lt, self.one_element_list, 5)
self.assertEqual(BisectFinder.find_right_lt(self.one_element_list, 7), 0)
def test_find_right_lt_two_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_lt, self.two_element_list, 2)
self.assertRaises(ValueError, BisectFinder.find_right_lt, self.two_element_list, 3)
self.assertEqual(BisectFinder.find_right_lt(self.two_element_list, 6), 0)
self.assertEqual(BisectFinder.find_right_lt(self.two_element_list, 8), 0)
self.assertEqual(BisectFinder.find_right_lt(self.two_element_list, 9), 1)
def test_find_right_lt_three_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_lt, self.three_element_list, 1)
self.assertRaises(ValueError, BisectFinder.find_right_lt, self.three_element_list, 2)
self.assertEqual(BisectFinder.find_right_lt(self.three_element_list, 4), 0)
self.assertEqual(BisectFinder.find_right_lt(self.three_element_list, 7), 0)
self.assertEqual(BisectFinder.find_right_lt(self.three_element_list, 8), 2)
def test_find_right_lt_four_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_lt, self.four_element_list, 1)
self.assertRaises(ValueError, BisectFinder.find_right_lt, self.four_element_list, 2)
self.assertEqual(BisectFinder.find_right_lt(self.four_element_list, 4), 2)
self.assertEqual(BisectFinder.find_right_lt(self.four_element_list, 5), 2)
self.assertEqual(BisectFinder.find_right_lt(self.four_element_list, 6), 3) | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
def test_find_right_lt_five_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_lt, self.five_element_list, 0)
self.assertRaises(ValueError, BisectFinder.find_right_lt, self.five_element_list, 1)
self.assertEqual(BisectFinder.find_right_lt(self.five_element_list, 2), 0)
self.assertEqual(BisectFinder.find_right_lt(self.five_element_list, 5), 0)
self.assertEqual(BisectFinder.find_right_lt(self.five_element_list, 7), 3)
self.assertEqual(BisectFinder.find_right_lt(self.five_element_list, 9), 3)
self.assertEqual(BisectFinder.find_right_lt(self.five_element_list, 10), 4)
# Tests for the find_right_le function
def test_find_right_le_empty_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_le, self.empty_list, 10)
def test_find_right_le_one_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_le, self.one_element_list, 2)
self.assertEqual(BisectFinder.find_right_le(self.one_element_list, 5), 0)
self.assertEqual(BisectFinder.find_right_le(self.one_element_list, 7), 0) | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
def test_find_right_le_two_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_le, self.two_element_list, 2)
self.assertEqual(BisectFinder.find_right_le(self.two_element_list, 3), 0)
self.assertEqual(BisectFinder.find_right_le(self.two_element_list, 6), 0)
self.assertEqual(BisectFinder.find_right_le(self.two_element_list, 8), 1)
self.assertEqual(BisectFinder.find_right_le(self.two_element_list, 9), 1)
def test_find_right_le_three_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_le, self.three_element_list, 1)
self.assertEqual(BisectFinder.find_right_le(self.three_element_list, 2), 0)
self.assertEqual(BisectFinder.find_right_le(self.three_element_list, 4), 0)
self.assertEqual(BisectFinder.find_right_le(self.three_element_list, 7), 2)
self.assertEqual(BisectFinder.find_right_le(self.three_element_list, 8), 2)
def test_find_right_le_four_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_le, self.four_element_list, 1)
self.assertEqual(BisectFinder.find_right_le(self.four_element_list, 2), 2)
self.assertEqual(BisectFinder.find_right_le(self.four_element_list, 4), 2)
self.assertEqual(BisectFinder.find_right_le(self.four_element_list, 5), 3)
self.assertEqual(BisectFinder.find_right_le(self.four_element_list, 6), 3) | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
def test_find_right_le_five_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_le, self.five_element_list, 0)
self.assertEqual(BisectFinder.find_right_le(self.five_element_list, 1), 0)
self.assertEqual(BisectFinder.find_right_le(self.five_element_list, 2), 0)
self.assertEqual(BisectFinder.find_right_le(self.five_element_list, 5), 3)
self.assertEqual(BisectFinder.find_right_le(self.five_element_list, 7), 3)
self.assertEqual(BisectFinder.find_right_le(self.five_element_list, 9), 4)
self.assertEqual(BisectFinder.find_right_le(self.five_element_list, 10), 4)
# Tests for the find_right_eq function
def test_find_right_eq_empty_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_eq, self.empty_list, 10)
def test_find_right_eq_one_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_eq, self.one_element_list, 2)
self.assertEqual(BisectFinder.find_right_eq(self.one_element_list, 5), 0)
self.assertRaises(ValueError, BisectFinder.find_right_eq, self.one_element_list, 7) | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
def test_find_right_eq_two_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_eq, self.two_element_list, 2)
self.assertEqual(BisectFinder.find_right_eq(self.two_element_list, 3), 0)
self.assertRaises(ValueError, BisectFinder.find_right_eq, self.two_element_list, 6)
self.assertEqual(BisectFinder.find_right_eq(self.two_element_list, 8), 1)
self.assertRaises(ValueError, BisectFinder.find_right_eq, self.two_element_list, 9)
def test_find_right_eq_three_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_eq, self.three_element_list, 1)
self.assertEqual(BisectFinder.find_right_eq(self.three_element_list, 2), 0)
self.assertRaises(ValueError, BisectFinder.find_right_eq, self.three_element_list, 4)
self.assertEqual(BisectFinder.find_right_eq(self.three_element_list, 7), 2)
self.assertRaises(ValueError, BisectFinder.find_right_eq, self.three_element_list, 8)
def test_find_right_eq_four_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_eq, self.four_element_list, 1)
self.assertEqual(BisectFinder.find_right_eq(self.four_element_list, 2), 2)
self.assertRaises(ValueError, BisectFinder.find_right_eq, self.four_element_list, 4)
self.assertEqual(BisectFinder.find_right_eq(self.four_element_list, 5), 3)
self.assertRaises(ValueError, BisectFinder.find_right_eq, self.four_element_list, 6) | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
def test_find_right_eq_five_element_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_eq, self.five_element_list, 0)
self.assertEqual(BisectFinder.find_right_eq(self.five_element_list, 1), 0)
self.assertRaises(ValueError, BisectFinder.find_right_eq, self.five_element_list, 2)
self.assertEqual(BisectFinder.find_right_eq(self.five_element_list, 5), 3)
self.assertRaises(ValueError, BisectFinder.find_right_eq, self.five_element_list, 7)
self.assertEqual(BisectFinder.find_right_eq(self.five_element_list, 9), 4)
self.assertRaises(ValueError, BisectFinder.find_right_eq, self.five_element_list, 10)
# Tests for the find_right_ge function
def test_find_right_ge_empty_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_ge, self.empty_list, 10)
def test_find_right_ge_one_element_list(self):
self.assertEqual(BisectFinder.find_right_ge(self.one_element_list, 2), 0)
self.assertEqual(BisectFinder.find_right_ge(self.one_element_list, 5), 0)
self.assertRaises(ValueError, BisectFinder.find_right_ge, self.one_element_list, 7)
def test_find_right_ge_two_element_list(self):
self.assertEqual(BisectFinder.find_right_ge(self.two_element_list, 2), 0)
self.assertEqual(BisectFinder.find_right_ge(self.two_element_list, 3), 0)
self.assertEqual(BisectFinder.find_right_ge(self.two_element_list, 6), 1)
self.assertEqual(BisectFinder.find_right_ge(self.two_element_list, 8), 1)
self.assertRaises(ValueError, BisectFinder.find_right_ge, self.two_element_list, 9) | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
def test_find_right_ge_three_element_list(self):
self.assertEqual(BisectFinder.find_right_ge(self.three_element_list, 1), 0)
self.assertEqual(BisectFinder.find_right_ge(self.three_element_list, 2), 0)
self.assertEqual(BisectFinder.find_right_ge(self.three_element_list, 4), 2)
self.assertEqual(BisectFinder.find_right_ge(self.three_element_list, 7), 2)
self.assertRaises(ValueError, BisectFinder.find_right_ge, self.three_element_list, 8)
def test_find_right_ge_four_element_list(self):
self.assertEqual(BisectFinder.find_right_ge(self.four_element_list, 1), 2)
self.assertEqual(BisectFinder.find_right_ge(self.four_element_list, 2), 2)
self.assertEqual(BisectFinder.find_right_ge(self.four_element_list, 4), 3)
self.assertEqual(BisectFinder.find_right_ge(self.four_element_list, 5), 3)
self.assertRaises(ValueError, BisectFinder.find_right_ge, self.four_element_list, 6)
def test_find_right_ge_five_element_list(self):
self.assertEqual(BisectFinder.find_right_ge(self.five_element_list, 0), 0)
self.assertEqual(BisectFinder.find_right_ge(self.five_element_list, 1), 0)
self.assertEqual(BisectFinder.find_right_ge(self.five_element_list, 2), 3)
self.assertEqual(BisectFinder.find_right_ge(self.five_element_list, 5), 3)
self.assertEqual(BisectFinder.find_right_ge(self.five_element_list, 7), 4)
self.assertEqual(BisectFinder.find_right_ge(self.five_element_list, 9), 4)
self.assertRaises(ValueError, BisectFinder.find_right_ge, self.five_element_list, 10)
# Tests for the find_right_gt function
def test_find_right_gt_empty_list(self):
self.assertRaises(ValueError, BisectFinder.find_right_gt, self.empty_list, 10) | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
def test_find_right_gt_one_element_list(self):
self.assertEqual(BisectFinder.find_right_gt(self.one_element_list, 2), 0)
self.assertRaises(ValueError, BisectFinder.find_right_gt, self.one_element_list, 5)
self.assertRaises(ValueError, BisectFinder.find_right_gt, self.one_element_list, 7)
def test_find_right_gt_two_element_list(self):
self.assertEqual(BisectFinder.find_right_gt(self.two_element_list, 2), 0)
self.assertEqual(BisectFinder.find_right_gt(self.two_element_list, 3), 1)
self.assertEqual(BisectFinder.find_right_gt(self.two_element_list, 6), 1)
self.assertRaises(ValueError, BisectFinder.find_right_gt, self.two_element_list, 8)
self.assertRaises(ValueError, BisectFinder.find_right_gt, self.two_element_list, 9)
def test_find_right_gt_three_element_list(self):
self.assertEqual(BisectFinder.find_right_gt(self.three_element_list, 1), 0)
self.assertEqual(BisectFinder.find_right_gt(self.three_element_list, 2), 2)
self.assertEqual(BisectFinder.find_right_gt(self.three_element_list, 4), 2)
self.assertRaises(ValueError, BisectFinder.find_right_gt, self.three_element_list, 7)
self.assertRaises(ValueError, BisectFinder.find_right_gt, self.three_element_list, 8)
def test_find_right_gt_four_element_list(self):
self.assertEqual(BisectFinder.find_right_gt(self.four_element_list, 1), 2)
self.assertEqual(BisectFinder.find_right_gt(self.four_element_list, 2), 3)
self.assertEqual(BisectFinder.find_right_gt(self.four_element_list, 4), 3)
self.assertRaises(ValueError, BisectFinder.find_right_gt, self.four_element_list, 5)
self.assertRaises(ValueError, BisectFinder.find_right_gt, self.four_element_list, 6) | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
def test_find_right_gt_five_element_list(self):
self.assertEqual(BisectFinder.find_right_gt(self.five_element_list, 0), 0)
self.assertEqual(BisectFinder.find_right_gt(self.five_element_list, 1), 3)
self.assertEqual(BisectFinder.find_right_gt(self.five_element_list, 2), 3)
self.assertEqual(BisectFinder.find_right_gt(self.five_element_list, 5), 4)
self.assertEqual(BisectFinder.find_right_gt(self.five_element_list, 7), 4)
self.assertRaises(ValueError, BisectFinder.find_right_gt, self.five_element_list, 9)
self.assertRaises(ValueError, BisectFinder.find_right_gt, self.five_element_list, 10)
if __name__ == '__main__':
unittest.main()
Answer: testing approach
from unittest import TestCase | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
Good!
You may wish to consider using
hypothesis,
as well. It does an amazing job of thinking up
random test cases that you never would have,
and then tries to distill them down to
"simplest input which still produces Red bar".
BTW, implements seems an odd module name,
which the Review Context never mentions.
AAA
The "arrange" part has been moved out to setUp,
and the tests focus on "act, assert".
This can be good, if arranging is "hard" or tediously long,
and especially if we arrange a common data structure
which is used by multiple independent tests.
But here the separation is slightly distracting.
I have a weak preference for seeing the one-line "arrange"
setting a local variable which we use on the next line.
edge cases
I will focus on just one test; others follow a similar pattern.
In test_find_left_lt_one_element_list the element to be
found is 5, and we systematically test {2, 5, 7}.
I would rather have seen {4, 5, 6} being tested.
When we wrote the target code we tried to correctly
use < vs <= operators.
The point of test code is to verify the right thing happened.
verbose tests
Oh my goodness, the tests just go on,
cycling through {left, right} × {<, <=, ==, >=, >}.
Humans aren't great at going through such enumerations.
My eyes glaze over.
OK, you win, I guess factoring out all the "arrange" into setUp
was the right call, for these particular tests.
Yes, test code should be "very simple", and
we embrace copy-n-paste for it.
But after ten stanzas, I'm not sure these are exactly "simple",
in the sense that I'm not doing a good job of eye-balling
each one and deciding "oh yeah, this is the right answer"
before reading what the assertion says.
Instead of these, or in addition to these,
I would like to see some test logic that constructs a list
so it knows the right answer, then verifies that the right
answer is returned.
It would accept list_length as a parameter.
And then add some
hypothesis
testing on top of that. | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
It would accept list_length as a parameter.
And then add some
hypothesis
testing on top of that.
I'm starting to wish there was a (possibly _private) method
that accepts a comparison operator.
It would simplify cycling through the variants.
@staticmethod
There's nothing exactly wrong with using that decorator.
But introducing a "container" class to organize the namespace
is unnecessary, a module can certainly do that.
Consider using simple defs in a bisectfinder module.
signature
def find_left_lt(a, x, lo=0, hi=None, key=None): | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
Leaving a and x as type Any is fine,
and caller will soon figure out that the Sequence a
should contain elements of x's type,
and the elements should support comparison.
Neglecting to point out that we return def ... ) -> int:
seems like a missed opportunity.
Plus, it makes mypy linting slightly harder for callers.
docstring
'''Finds the index of the leftmost (among duplicates) element that is strictly less than X.
A[index] < X
A[index] == a2
I appreciate the pithiness of that sentence.
The < X postcondition could clarify that it's a contract,
it shall be true upon return.
The notation upcases a and x where that doesn't seem necessary.
I don't know where a2 came from,
and if the intent is to promise some postcondition,
I'm afraid I'm not quite getting it.
The [ list ] which follows I found entirely obscure.
I was a little surprised to see no mention of the familiar
bisect_left,
for example to contrast their behavior.
Plus, the meaning of key here matches its behavior in every way.
That familiar function is a
total
function.
The docstring makes no mention that find_left_lt
is a partial function which could very well raise.
This is a serious omission and should be remedied.
custom exception
I'm not entirely comfortable with using ValueError for failures.
It feels more like an IndexError happened -- "bad index",
no matching index exists.
Consider defining your own exception,
and have it inherit from IndexError.
Then a caller a few levels up the call stack
can focus on your specific exception if desired,
or can choose to catch just IndexError or Exception
if that's sufficient for caller's need.
raise ValueError("No elements less than or equal to x found.")
This is less informative than it could be.
Put yourself in the shoes of some maintenance engineer who is staring at this message.
First question is going to be "what was x?", right?
Consider using an f-string to put the value of x in there. | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
python, unit-testing, binary-search
I find it interesting that only the message changes
between e.g. `find_right_ge` and `find_right_gt`.
Perhaps the message template
might become a keyword parameter.
simple comparisons
if len(a) > 0 and index < len(a) + 1 and a[index - 1] < x:
I find those three conjuncts harder to read than necessary.
And I believe you do, too.
Let's tackle the middle one.
It's a guard, but it's more obscure than needed.
It could be:
if ... and index - 1 < len(a) and a[index - 1] < x:
which makes it transparently obvious that we're avoiding
running off the end.
But bisect_left() is perfectly happy to return an index of 0.
Don't we want to verify that index - 1 hasn't walked
off the other end of the array?!?
I confess it is not completely clear to me how lo and hi
figure into this.
The test suite did not consider them, but it should.
The underlying bisect_left uses lo and hi,
so there's a good case for keeping them as-is.
Let me float a radical proposal.
Consider accepting a single range argument,
and then you pass .start and .stop to bisect_left.
Or not, whatever.
It slightly simplifies the promises
and is perhaps a little easier to reason about
in the presence of potential
OBOBs.
postcondition
I really liked how the one sentence ("Finds the index...") states a
contract.
I would like it even more if it was believable,
if I knew for certain it was always true after my call.
There's an easy way to do that: use assert before returning. | {
"domain": "codereview.stackexchange",
"id": 45473,
"lm_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, unit-testing, binary-search",
"url": null
} |
array, node.js, json, api, classes
Title: Updating class method to use data from new weather API endpoint while keeping same return value object structure as with old endpoint
Question: I needed to update a class in Node.js that parses the response from a new weather API endpoint but still preserves the same object structure and key values from having been using the old weather API endpoint. The return value from the class' main method should be an array of eight objects, each representing data from a given day of the week, including hi and low temps, and a day and night object.
The data from the new API response is structured as follows with arrays of lengths 8 and 16:
const apiResponse = {
dayOfWeek: ['Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
calendarDayTemperatureMax: [57, 59, 53, 47, 42, 44, 42, 43],
calendarDayTemperatureMin: [39, 40, 40, 37, 33, 31, 31, 30]
validTimeLocal: ['2024-02-09T07:00:00-0500', '2024-02-10T07:00:00-0500', '2024-02-11T07:00:00-0500', '2024-02-12T07:00:00-0500', '2024-02-13T07:00:00-0500', '2024-02-14T07:00:00-0500', '2024-02-15T07:00:00-0500', '2024-02-16T07:00:00-0500'],
daypart:[{
dayOrNight: ['D', 'N', 'D', 'N', 'D', 'N', 'D', 'N', 'D', 'N', 'D', 'N', 'D', 'N', 'D', 'N'],
daypartName: ['Today', 'Tonight', 'Tomorrow', 'Tomorrow night', 'Sunday', 'Sunday night', 'Monday', 'Monday night', 'Tuesday', 'Tuesday night', 'Wednesday', 'Wednesday night', 'Thursday', 'Thursday night', 'Friday', 'Friday night']
temperature: [57, 40, 59, 45, 51, 37, 47, 35, 41, 31, 44, 31, 42, 30, 43, 29],
iconCode: [32, 29, 26, 27, 26, 27, 39, 5, 16, 29, 30, 29, 30, 29, 30, 29]
}]
} | {
"domain": "codereview.stackexchange",
"id": 45474,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, node.js, json, api, classes",
"url": null
} |
array, node.js, json, api, classes
The old weekly weather forecast class:
module.exports = class Weekly extends Feed {
constructor () {
super()
this.desiredFields = ['daypart_name', 'temp', 'icon_code', 'fcst_valid_local']
this.fieldMap = {
'fcst_valid_local': 'date',
'daypart_name': 'day_part'
}
}
/**
* Accepts Api results and request; formats feed for API output
*
* @param {Api} apiResponse
* @param {Request} request
*/
getDayPartFields (obj) {
let fields = _.pick(obj, this.desiredFields)
return Feed.mapFields(this.fieldMap, fields)
}
generateFeed (apiResponse, request) {
let formattedResponse = apiResponse.forecasts.map( obj => {
let { day, night, max_temp, min_temp} = obj
let dayObject = this.getDayPartFields(day)
let nightObject = this.getDayPartFields(night)
return { hi: max_temp, lo: min_temp, day: dayObject, night: nightObject }
})
let feed = this.getBaseFeed(request, formattedResponse)
this.setFeed(feed)
}
}
My updated weekly weather forecast class looks like this:
module.exports = class Weekly extends Feed {
constructor () {
super()
this.desiredFields = ['daypartName', 'temp', 'icon_code', 'validTimeLocal']
this.fieldMap = {
'validTimeLocal': 'date',
'daypartName': 'day_part'
}
}
/**
* Accepts Api results and request; formats feed for API output
*
* @param {Api} apiResponse
* @param {Request} request
*/ | {
"domain": "codereview.stackexchange",
"id": 45474,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, node.js, json, api, classes",
"url": null
} |
array, node.js, json, api, classes
generateFeed (apiResponse, request) {
let formattedResponse = apiResponse.dayOfWeek.map((_, idx) => {
const dayIndex = idx * 2;
return {
'hi': apiResponse.calendarDayTemperatureMax[idx],
'lo': apiResponse.calendarDayTemperatureMin[idx],
'day': {
'daypart': apiResponse.daypart[0].daypartName[dayIndex],
'temp': apiResponse.daypart[0].temperature[dayIndex],
'icon_code': apiResponse.daypart[0].iconCode[dayIndex],
'date': apiResponse.validTimeLocal[idx]
},
'night': {
'daypart': apiResponse.daypart[0].daypartName[dayIndex + 1],
'temp': apiResponse.daypart[0].temperature[dayIndex + 1],
'icon_code': apiResponse.daypart[0].iconCode[dayIndex + 1],
'date': apiResponse.validTimeLocal[idx]
}
};
});
let feed = this.getBaseFeed(request, formattedResponse)
this.setFeed(feed)
}
}
The properties in the constructor method were left over from the previous implementation, but I updated a couple of the values to correlate with the new API response. There were also a couple of helper methods with I deleted, each for populating the values in the day and night objects in the formattedResponse.
Would it be better to have a couple of helper methods here? Also, do I need to keep what's inside the constructor method? This was actually quite a bit of fun to solve, but I would welcome any suggestions for optimization, thanks!
Answer: This submission is about refactoring code so it will
return a same-format response.
Yet it did not include an automated test suite
which shows Green bar on "old" code
and again Green on this "new" code.
ctor
daypartName: ['Today', 'Tonight', 'Tomorrow', 'Tomorrow night', 'Sunday', ... ]
temperature: [57, ... ],
iconCode: [32, ... ]
...
this.desiredFields = ['daypartName', 'temp', 'icon_code', 'validTimeLocal'] | {
"domain": "codereview.stackexchange",
"id": 45474,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, node.js, json, api, classes",
"url": null
} |
array, node.js, json, api, classes
I started to object to the names temp and icon_code,
until I saw the fieldMap.
It was initially unclear to me which were "old" and which were "new"
field names.
It would be helpful to put version numbers, dates, or vendor names
on "old" and "new", for unambiguous reference in source comments.
(Some European cities have had trouble with versioning
their place names, leading to statements like
"Let's meet for lunch near the Old New Bridge!")
It appears we're transitioning from a conventional camelCase endpoint
to a snake_case endpoint.
A comment in the source to that effect would be welcome.
Then maintenance engineers will better understand
why certain spelling variants were chosen,
and how they should choose names when adding new features.
In particular, if the project architect has decided that
code interacting with this should continue using camelCase,
we should see a statement to that effect.
Otherwise maintainers might figure "oh, we're transitioning
everything to snake_case", and introduce undesired refactors.
do I need to keep what's inside the constructor method?
What you wrote looks good to me, modulo my remarks.
Not sure what you would get rid of;
it seems sensible from where I'm sitting.
day vs hour-within-day
validTimeLocal: ['2024-02-09T07:00:00-0500',
'2024-02-10T07:00:00-0500', ... ],
...
'day': { ...
'date': apiResponse.validTimeLocal[idx]
},
'night': { ...
'date': apiResponse.validTimeLocal[idx] | {
"domain": "codereview.stackexchange",
"id": 45474,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, node.js, json, api, classes",
"url": null
} |
array, node.js, json, api, classes
I found those two lines of code confusing,
in the sense that I simply don't know what date means here.
It appears to refer to a calendar day, e.g. 2024-02-09.
Yet 6:30am on the ninth would correspond to 2024-02-08 ?!?
And combining the 5 hour offset
of EST (presumably from America/New_York)
with 7 hours past midnight (start of day?) muddies the waters.
It's unclear what edge cases a unit test author should look for,
even for days that don't involve a Daylight Saving transition.
Summary: use the one-second resolution of HH:MM:SS when a
detailed timestamp is intended, and prefer one-day granularity
when an entire day is being modeled.
anonymous intermediate expression
let feed = this.getBaseFeed(request, formattedResponse)
this.setFeed(feed)
The code is perfectly eloquent here.
No need to explain that a "feed" is what we got.
Prefer a simple one-line assignment for this.
Would it be better to have a couple of helper methods here?
Nah.
I'm usually pretty vocal about "too long!" or "DRY!",
and I didn't notice any such issues here.
If a unit test author comes along and wishes
to expose formattedResponse, that will be straightforward,
so we'll worry about crossing that bridge when we come to it. | {
"domain": "codereview.stackexchange",
"id": 45474,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, node.js, json, api, classes",
"url": null
} |
python, python-3.x, error-handling, exception
Title: Python exception for handling invalid argument types
Question: Greetings
One small problem that anyone have to tackle with in Python is handling invalid argument types ( without an automatic static type checking tool like
Mypy )
One of the best methods for handling the invalid argument is raising an exception which would easily inform the code client with the required steps to fix, ( I.E ):
"Expected argument type passed for the parameter ( im_a_parameter ): ( int ) | Not: ( str )"
in this case, raising a ValueError would get the job done.
While attending this method, as my project was growing larger, I found out that repeating this idiom would deny the DRY principle, so I rolled up my sleeves, and came up with a fixture:
unexpected_argument_type.py
"""
# The holder module for the UnexpectedArgumentTypeError exception class
"""
class UnexpectedArgumentTypeError(ValueError):
def __init__(self, parameter: str, expected_argument_types: object | list[object]) -> None:
"""
# Args:
1. ( parameter ): The expected parameter of the current function signature.
2. ( expected_argument_types ): The types that were expected to be passed to the function parameter.
"""
self.passed_argument = parameter
self.passed_argument_type = parameter
self.expected_argument_types = expected_argument_types
self._generate_error_message()
super().__init__(self._error_message)
def _generate_error_message(self):
if isinstance(self.expected_argument_type, object) and not self._arguments_are_list:
self._error_message = (
f"Expected argument type passed for the parameter \
( {self.passed_argument} ): ( {self.expected_argument_type} ) | Not ( {self.passed_argument_type} )."
)
return | {
"domain": "codereview.stackexchange",
"id": 45475,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, error-handling, exception",
"url": null
} |
python, python-3.x, error-handling, exception
if isinstance(self.expected_argument_type, list):
expected_argument_types_str = ', '.join(self.expected_argument_type)
self._error_message = (
f"Expected argument type passed for the parameter \
( {self.passed_argument} ): ( {expected_argument_types_str} ) | Not ( {self.passed_argument_type} )"
)
@property
def passed_argument_type(self):
return self._passed_argument_type
@passed_argument_type.setter
def passed_argument_type(self, argument_type):
self._passed_argument_type = type(argument_type).__name__
@property
def expected_argument_types(self):
return self._expected_argument_type
@expected_argument_types.setter
def expected_argument_type(self, arguments):
if not isinstance(arguments, (list, object)):
raise ValueError("The ( expected_argument_type ) argument must be object| e.x: ( str, tuple... )")
if isinstance(arguments, list):
self._arguments_are_list = True
arguments = [str(argument) for argument in arguments]
if isinstance(arguments, object) and not self._arguments_are_list:
arguments = arguments.__name__
self._expected_argument_type = arguments
After all of this, one question remains:
Does handling this problem worth the complexity that this piece of code adds?
( Writing unit tests, maintaining documentations ).
Answer: missing review context
This submission of a utility class is off-topic, as it
does not offer any examples of caller code
that relies on the utility.
We can't see how caller's life is made better by
existence of the utility,
there's no "with" vs "without" contrast offered.
comparison with the competition
mypy
... handling invalid argument types ( without an automatic static type checking tool like Mypy ) | {
"domain": "codereview.stackexchange",
"id": 45475,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, error-handling, exception",
"url": null
} |
python, python-3.x, error-handling, exception
... handling invalid argument types ( without an automatic static type checking tool like Mypy )
There exist reasons why a project may be reluctant to
adopt mypy or may choose to reject such linters.
But this submission does not mention any of those reasons,
so we cannot evaluate its fitness for purpose.
In short, we don't know the intended use case.
beartype
Sometimes I do want strict runtime checking.
I have been pretty happy with
@beartype decorators.
>>> from beartype import beartype
>>>
>>> @beartype
... def increment(n: int) -> int:
... return n + 1
...
>>>
>>> increment(2)
3
>>> increment(2.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<@beartype(__main__.increment) at 0x1057c4360>", line 28, in increment
beartype.roar.BeartypeCallHintParamViolation: Function __main__.increment() parameter n=2.0 violates type hint <class 'int'>, as float 2.0 not instance of int.
This submission makes no attempt to explain how
it offers a solution competitive with mypy or @beartype.
Is handling this problem worth the complexity that this piece of code adds?
No. | {
"domain": "codereview.stackexchange",
"id": 45475,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, error-handling, exception",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.