text stringlengths 1 2.12k | source dict |
|---|---|
c++, c++17
ReservoirSamplerWeighted(const ReservoirSamplerWeighted& other)
: mSamplesCount(other.mSamplesCount)
, mWeightJumpOver(other.mWeightJumpOver)
, mRand(other.mRand)
, mUniformDist(other.mUniformDist)
, mAllocatedElementsCount(other.mAllocatedElementsCount)
{
if (other.mData)
{
allocateData();
for (size_t i = 0; i < mSamplesCount; ++i)
{
new (mQueuePrios + i) RandType(other.mQueuePrios[i]);
}
std::memcpy(mQueueIndexes, other.mQueueIndexes, sizeof(size_t)*mAllocatedElementsCount);
for (size_t i = 0; i < mAllocatedElementsCount; ++i)
{
new (mElements + i) T(other.mElements[i]);
}
}
}
ReservoirSamplerWeighted(ReservoirSamplerWeighted&& other)
: mSamplesCount(other.mSamplesCount)
, mWeightJumpOver(other.mWeightJumpOver)
, mRand(other.mRand)
, mUniformDist(other.mUniformDist)
, mAllocatedElementsCount(other.mAllocatedElementsCount)
, mData(other.mData)
, mQueuePrios(other.mQueuePrios)
, mQueueIndexes(other.mQueueIndexes)
, mElements(other.mElements)
{
other.mWeightJumpOver = {};
other.mAllocatedElementsCount = 0;
other.mData = nullptr;
other.mQueuePrios = nullptr;
other.mQueueIndexes = nullptr;
other.mElements = nullptr;
}
ReservoirSamplerWeighted& operator=(const ReservoirSamplerWeighted&) = delete;
ReservoirSamplerWeighted& operator=(ReservoirSamplerWeighted&&) = delete;
// if creation of an object to store is expensive you can check this before calling addElement
// and provide a "dummy" object in case this returns false, because it will be ignored in that case
bool willNextBeConsidered(WeightType weight) const
{
return (mWeightJumpOver - weight) <= 0;
} | {
"domain": "codereview.stackexchange",
"id": 44061,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, c++17
template<typename E, typename = std::enable_if_t<std::is_move_constructible_v<std::decay_t<E>> && std::is_move_assignable_v<std::decay_t<E>> && std::is_same_v<std::decay_t<E>, T>>>
void addElement(WeightType weight, E&& element)
{
emplaceElement(weight, std::move(element));
}
void addElement(WeightType weight, const T& element)
{
emplaceElement(weight, element);
}
template<typename... Args>
void emplaceElement(WeightType weight, Args&&... arguments)
{
if (mData == nullptr)
{
prepareData();
}
if (weight > WeightType(0.0))
{
if (mAllocatedElementsCount < mSamplesCount)
{
const RandType r = std::pow(mUniformDist(mRand), (static_cast<RandType>(1.0) / weight));
insertSorted(r, std::forward<Args>(arguments)...);
if (mAllocatedElementsCount == mSamplesCount)
{
mWeightJumpOver = log(mUniformDist(mRand)) / log(mQueuePrios[0]);
}
}
else
{
mWeightJumpOver -= weight;
if (mWeightJumpOver <= 0)
{
const RandType t = std::pow(mQueuePrios[0], weight);
const RandType r = std::pow(std::uniform_real_distribution<RandType>(t, static_cast<RandType>(1.0))(mRand), static_cast<RandType>(1.0) / weight);
insertSortedRemoveFirst(r, std::forward<Args>(arguments)...);
mWeightJumpOver = log(mUniformDist(mRand)) / log(mQueuePrios[0]);
}
}
}
}
const std::pair<const T*, size_t> getResult() const { return std::make_pair(mElements, mAllocatedElementsCount); }
private:
void prepareData()
{
allocateData();
for (size_t i = 0; i < mSamplesCount; ++i)
{
new (mQueuePrios + i) RandType();
}
} | {
"domain": "codereview.stackexchange",
"id": 44061,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, c++17
void allocateData()
{
assert(mData == nullptr);
constexpr size_t alignment = std::max(std::max(std::alignment_of_v<RandType>, std::alignment_of_v<size_t>), std::alignment_of_v<T>);
const size_t keysExtent = (sizeof(RandType)*mSamplesCount) % std::alignment_of_v<size_t>;
const size_t indexesAlignmentGap = keysExtent > 0 ? (std::alignment_of_v<size_t> - keysExtent) : 0;
const size_t indexesOffset = sizeof(RandType)*mSamplesCount + indexesAlignmentGap;
const size_t indexesExtent = (indexesOffset + sizeof(size_t)*mSamplesCount) % std::alignment_of_v<T>;
const size_t elementsAlignmentGap = indexesExtent > 0 ? (std::alignment_of_v<T> - indexesExtent) : 0;
const size_t elementsOffset = indexesOffset + sizeof(size_t)*mSamplesCount + elementsAlignmentGap;
const size_t alignedSize = elementsOffset + sizeof(T)*mSamplesCount;
mData = std::aligned_alloc(alignment, alignedSize);
mQueuePrios = reinterpret_cast<RandType*>(mData);
mQueueIndexes = reinterpret_cast<size_t*>(static_cast<char*>(mData) + indexesOffset);
mElements = reinterpret_cast<T*>(static_cast<char*>(mData) + elementsOffset);
}
template<typename... Args>
void insertSorted(RandType r, Args&&... arguments)
{
RandType* it = std::upper_bound(mQueuePrios, mQueuePrios + mAllocatedElementsCount, r);
const size_t firstMovedIdx = std::distance(mQueuePrios, it);
std::move_backward(it, mQueuePrios + mAllocatedElementsCount, mQueuePrios + mAllocatedElementsCount + 1);
std::move_backward(mQueueIndexes + firstMovedIdx, mQueueIndexes + mAllocatedElementsCount, mQueueIndexes + mAllocatedElementsCount + 1);
mQueuePrios[firstMovedIdx] = r;
mQueueIndexes[firstMovedIdx] = mAllocatedElementsCount;
new (mElements + mAllocatedElementsCount) T(std::forward<Args>(arguments)...);
++mAllocatedElementsCount;
} | {
"domain": "codereview.stackexchange",
"id": 44061,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, c++17
template<typename... Args>
void insertSortedRemoveFirst(RandType r, Args&&... arguments)
{
RandType* it = std::upper_bound(mQueuePrios + 1, mQueuePrios + mSamplesCount, r);
const size_t firstNotMovedIdx = std::distance(mQueuePrios, it);
const size_t oldElementIdx = mQueueIndexes[0];
std::move(mQueuePrios + 1, it, mQueuePrios);
std::move(mQueueIndexes + 1, mQueueIndexes + firstNotMovedIdx, mQueueIndexes);
mQueuePrios[firstNotMovedIdx - 1] = r;
mQueueIndexes[firstNotMovedIdx - 1] = oldElementIdx;
if constexpr (std::is_assignable_v<T, T> && sizeof...(Args) == 1 && std::is_same_v<std::decay_t<std::tuple_element_t<0, std::tuple<Args...>>>, T>)
{
mElements[oldElementIdx] = std::forward<Args...>(arguments...);
}
else if constexpr (std::is_move_assignable_v<T>)
{
mElements[oldElementIdx] = T(std::forward<Args>(arguments)...);
}
else
{
// support for non-moveable types
mElements[oldElementIdx].~T();
new (mElements + (oldElementIdx)) T(std::forward<Args>(arguments)...);
}
}
private:
const size_t mSamplesCount;
WeightType mWeightJumpOver {};
URBG mRand;
std::uniform_real_distribution<RandType> mUniformDist{static_cast<RandType>(0.0), static_cast<RandType>(1.0)};
size_t mAllocatedElementsCount = 0;
void* mData = nullptr;
RandType* mQueuePrios = nullptr;
size_t* mQueueIndexes = nullptr;
T* mElements = nullptr;
};
Examples with test code: https://wandbox.org/permlink/gvRzEKxibM9sv5A1
Answer: Avoid manual memory management
A great deal of complexity comes from the fact that you allocate memory manually. I assume this was done to satisfy this requirement you had:
should work with non-copyable and/or non-movable types | {
"domain": "codereview.stackexchange",
"id": 44061,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, c++17
should work with non-copyable and/or non-movable types
I cannot imagine a scenario where you would want to do reservoir sampling on non-copyable/movable types, but on the other hand it's always good to not make assumptions and to make your code work in as many situations as possible.
Instead of doing manual memory allocation, and then having to make your own destructors, copy and move constructors, I see three alternatives:
Use std::unique_ptr<T[]> to store the data. With C++20, you can use std::make_unique_for_overwrite() to allocate the memory, pre-C++20 you just have to manually new T[samplesCount] and store it in the std::unique_ptr. This uses default initialization, so for POD types it does what you want, but it might be less efficient for classes with default constructors. It also requires assignment operators to exist for T.
Use std::deque<T> to store the data. This is like a std::vector, but doesn't move elements when it is resized. You can emplace_back() new elements efficiently. One drawback is that it might still do multiple allocations, although since no moving of data in memory is involved it's much cheaper than std::vector.
Create your own class that acts like a fixed size std::vector but also allows non-copyable/movable types, and use that. This removes the complexity from class ReservoirSamplerWeighted. | {
"domain": "codereview.stackexchange",
"id": 44061,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, c++17
There are lots of subtle issues that you need to think about when doing this yourself, like whether alignof(T) > sizeof(T) is possible, object lifetimes, and whether your pointers are valid.
But you do require T to be copyable
In your copy constructor, you call placement-new and pass a reference to other.mElements[i]; this invokes the copy constructor of T.
Make use of std::priority_queue
You already require that RandType is movable, and std::size_t certainly is, so I don't think you need to put the queue priorities and indexes in the same allocated memory as the data elements. And in that case, I strongly recommend you use std::priority_queue; it does exactly what you want, and it's more efficient since it is implemented as a heap instead of a sorted list: both inserting an element and popping the minimum element are \$O(\log N)\$ instead of \$O(N)\$.
To do this in a nice way, create a struct that holds an index and a priority, and has an operator<() overload that compares two objects based on their priority.
Returning the data
Your getResult() works correctly, but instead of returning a std::pair, returning a struct {T* data; std::size_t size;} would be nicer, as the members are explicitly named. If you can use C++20, then I would recommend returning a std::span instead. And of course if you use an STL container to store the data, then you can just return a reference to that container.
Something to think about is whether you want the caller to move the data out of your class. For example, they might want to pass it around while not wanting to keep the ReservoirSamplerWeighted object alive all the time. Maybe an extract() function would be nice, but of course that would only work if the data is held in a proper container object (but that can be any of the three alternatives I mentioned above).
Allowing custom arithmetic types | {
"domain": "codereview.stackexchange",
"id": 44061,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, c++17
Allowing custom arithmetic types
It would indeed be nice to support custom WeightTypes and RandTypes, but make sure your code handles it correctly. One issue is that you need "0" and "1" values. You write WeightType(0.0) and RandType(1.0) in your code. But would a bigint class have a constructor that takes a double argument? I think WeightType{} would be a safer way to construct a zero, but how to make a one? You could perhaps make a one_v template like C++20's mathematical constants, which can then be overloaded for T outside of the definition of your class ReservoirSamplerWeighted. But also consider that you use std::log() (except you forgot the std::) and std::pow() in your code, so it doesn't really doesn't make sense to use anything other than float or double.
You also might want to think about constraining the allowed types to ones that your class can work with. You can use SFINAE or concepts for that. You want to check for something like std::floating_point. | {
"domain": "codereview.stackexchange",
"id": 44061,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17",
"url": null
} |
c++, beginner, reinventing-the-wheel, c++17
Title: Reimplementing Alias method in C++
Question: In the following I reimplement the Walker-Vose Alias method for sampling from nonuniform, discrete probability distributions.
I am well aware that there is https://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
which I would use for production code.
alias_lib.h contains the main logic.
main.cpp contains example usage.
CMakeLists.txt contains a minimal cmake file.
alias_lib.h
#include <random>
#include <vector>
#include <algorithm>
typedef double real;
template <typename T>
T pop(std::vector<T>& V)
// Remove and return the last element of a vector.
{
auto val = V.back();
V.pop_back();
return val;
}
template <typename RNE>
auto get_r(RNE& gen)
// Return a real number from [0, 1) using a Random Number Engine
{
static std::uniform_real_distribution<real> dist(0.0, 1.0);
return dist(gen);
};
class AliasSampler
// This class implements the Walker-Vose Alias Sampling method.
//
// The initializing weights do not have to be normalized.
// The algorithm is described
// [here](https://web.archive.org/web/20131029203736/http://web.eecs.utk.edu/~vose/Publications/random.pdf)
// The naming of variables follows the Wikipedia [article](https://en.wikipedia.org/wiki/Alias_method) (As of 2022-10-31).
{
public:
AliasSampler() = delete;
AliasSampler(const std::vector<real>& weights)
: K_(weights.size())
{
// [...] If Ui = 1, the corresponding value Ki will never be consulted and is unimportant,
// but a value of Ki = i is sensible. [...]
std::iota(K_.begin(), K_.end(), 0); | {
"domain": "codereview.stackexchange",
"id": 44062,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, reinventing-the-wheel, c++17",
"url": null
} |
c++, beginner, reinventing-the-wheel, c++17
std::iota(K_.begin(), K_.end(), 0);
p_.reserve(weights.size());
std::transform(
weights.begin(), weights.end(),
std::back_inserter(p_),
[result = std::reduce(weights.begin(), weights.end())]
(real w) -> real
{
return w / result;
}
);
U_.reserve(weights.size());
std::transform(
p_.begin(), p_.end(),
std::back_inserter(U_),
[&, this]
(real x) -> real
{
return p_.size() * x;
}
);
// [...] As the lookup procedure is slightly faster if y < Ui (because Ki does not need to be consulted),
// one goal during table generation is to maximize the sum of the Ui.
// Doing this optimally turns out to be NP hard, but a greedy algorithm comes reasonably close: rob from the richest and give to the poorest.
// That is, at each step choose the largest Ui and the smallest Uj.
// Because this requires sorting the Ui, it requires O(n log n) time. [...] (See the Wikipedia article)
// For this reason we partition into small and large indices and use them in a sorted fashion.
std::vector<std::size_t> indices_(U_.size());
std::iota(indices_.begin(), indices_.end(), 0);
std::sort(indices_.begin(), indices_.end(),
[&, this]
(int a, int b) -> bool
{
return U_[a] < U_[b];
}); | {
"domain": "codereview.stackexchange",
"id": 44062,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, reinventing-the-wheel, c++17",
"url": null
} |
c++, beginner, reinventing-the-wheel, c++17
// I could use std::partition for partitioning into smaller and larger, **but**
// AFAIK this would not make use of the fact that the array is already sorted.
std::vector<std::size_t> smaller, larger;
for (std::size_t i = 0; U_[indices_[i]] < 1; ++i) {
smaller.push_back(indices_[i]);
};
for (std::size_t i = U_.size() - 1; U_[indices_[i]] >= 1; --i) {
larger.push_back(indices_[i]);
};
while (smaller.size() && larger.size()) {
std::size_t s = pop(smaller);
std::size_t l = pop(larger);
K_[s] = l;
U_[l] = U_[l] - (1. - U_[s]);
if (U_[l] < 1) {
smaller.push_back(l);
} else {
larger.push_back(l);
};
};
// [...] If one category empties before the other, the remaining entries may
// have U_i set to 1 with negligible error. [...] (See the Wikipedia article)
while (smaller.size()) {
std::size_t s = pop(smaller);
U_[s] = 1.;
};
while (larger.size()) {
std::size_t l = pop(larger);
U_[l] = 1.;
};
};
const auto& probabilities() const
{
return p_;
};
template <typename RNE>
auto operator()(RNE& gen) const
// Return a random number according to the given probabilities
// at initialization using a Random Number Engine.
{
auto x = get_r(gen);
auto i = static_cast<size_t>(p_.size() * x);
auto y = p_.size() * x - i;
return y < U_[i] ? i : K_[i];
};
auto min() const
{
return 0;
};
auto max() const
{
return p_.size() - 1;
}; | {
"domain": "codereview.stackexchange",
"id": 44062,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, reinventing-the-wheel, c++17",
"url": null
} |
c++, beginner, reinventing-the-wheel, c++17
auto max() const
{
return p_.size() - 1;
};
private:
std::vector<real> p_{};
std::vector<std::size_t> K_{};
std::vector<real> U_{};
std::vector<std::size_t> indices_{};
};
main.cpp
#include <iostream>
#include <random>
#include <map>
#include <iomanip>
#include "alias_lib.h"
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
AliasSampler sampler({1., 2., 3., 1.5, 1., 1.5});
std::map<int, int> map;
for(int n=0; n<100000; ++n) {
++map[sampler(gen)];
}
for(const auto& [num, count] : map) {
std::cout << num << " generated " << std::setw(4) << count << " times\n";
}
return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(test_alias_sampling)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
add_library(alias_lib
INTERFACE
alias_lib.h
)
add_executable(main main.cpp)
target_compile_options(main PRIVATE -Wall -Wextra -Werror)
target_link_libraries(main alias_lib) | {
"domain": "codereview.stackexchange",
"id": 44062,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, reinventing-the-wheel, c++17",
"url": null
} |
c++, beginner, reinventing-the-wheel, c++17
Answer: Make it satify the RandomNumberDistribution requirement
Your sampler class basically implements a specific random number distribution. The random number distributions in the standard library all satisfy the RandomNumberDistribtion requirement. It seems your class already satisfies many of the requirements, but it's missing some features, like the result_type and param_type type aliases, param(), reset(), an operator() that also takes a set of weights, comparison operators and std::ostream and std::istream operator overloads.
By conforming exactly to this requirement, your class will be a true drop-in replacement for existing standard random number distributions.
Avoid out-of-class utility functions and type aliases
You defined real, pop(), get_r() outside class AliasSampler. This means these names will now live in the global namespace, and can potentially conflict with other code that wants to define those things. You can make pop() and get_r() private member functions, and you can even move the definition of real into the class.
Use of STL algorithms
STL algorithms are very helpful tools, but sometimes they are very unwieldy. You have examples of both cases in your code: using std::reduce() to sum a vector is very concise, but then std::transform() to fill a vector is looking like a monstrosity. Sometimes a good old for-loop is simpler and better than an algorithm. Consider:
p_.reserve(weights.size());
auto sum_weights = std::reduce(weights.begin(), weights.end());
for (auto weight: weights) {
p_.push_back(weight / sum_weights);
}
With C++20's ranges it might become a bit nicer to use algorithms:
p_.reserve(weights.size());
auto sum_weights = std::reduce(weights.begin(), weights.end());
std::ranges::copy(std::views::transform(weights, [&](auto weight){
return weight / sum_weights;
}, std::back_inserter(p_)); | {
"domain": "codereview.stackexchange",
"id": 44062,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, reinventing-the-wheel, c++17",
"url": null
} |
c++, beginner, reinventing-the-wheel, c++17
Or with C++23:
auto sum_weights = std::reduce(weights.begin(), weights.end());
p_ = std::ranges::transform(weights, [&](auto weight){
return weight / sum_weights;
}) | std::ranges::to<std::vector>();
Avoid unnecessary use of floating point
The Wikipedia article mentions that the algorithm requires you to generate a random number between 0 and 1. However, the only reason to do so is to select a random index into p_. Instead of literally doing what the article mentions and using a std::uniform_real_distribution<real> to generate that random number, consider using a std::uniform_int_distribution<size_t>(0, p_.size() - 1). This avoids the multiplication and static_cast back to size_t.
Don't store temporary data in member variables
The vector indices_ is only used in the constructor to build the tables. It should not be a member variable, but just be declared inside the constructor.
From the Wikipedia article it looks like you only need \$U_i\$ and \$K_i\$ to sample the distribution, \$p_i\$ is only mentiond in the table generation section. I'm not sure why you are using it in operator()?
Stray semicolon
There is an unnecessary semicolon after the definition of operator(). Make sure you turn on compiler warnings, and fix all the warnings the compiler reports.
Documentation
It's really good to see that you have linked to a paper and the Wikipedia article describing the algorithm, and mentioning that your are matching the naming conventions from one of those.
You could also consider using the Doxygen format to document your code; this also allows the Doxygen tools to produce cross-references HTML and PDF output of the documentation you wrote. | {
"domain": "codereview.stackexchange",
"id": 44062,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, reinventing-the-wheel, c++17",
"url": null
} |
c, sorting, reinventing-the-wheel, insertion-sort, c99
Title: Generic insertion sort
Question: I implemented a generic insertion sort routine that can sort an array of any type. It's similar to the qsort function from the standard library. My goal it to optimize the code for readability above everything else, so I would appreciate any feedback.
void isort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)) {
for (size_t i = 1; i < nmemb; i++) {
char *key = (char *)base + i * size;
char key_copy[size];
memcpy(key_copy, key, size);
char *curr = NULL;
for (curr = key; curr > base && compar(curr - size, key_copy) > 0; curr -= size) {
memcpy(curr, curr - size, size);
}
memcpy(curr, key_copy, size);
}
}
Example client code:
int cmp_int(const void *p, const void *q) {
return *(int *)p - *(int *)q;
}
int main(void) {
int arr[] = { 4, 2, 3, 0, 2, 5 };
size_t nelem = sizeof(arr) / sizeof(arr[0]);
isort(arr, nelem, sizeof(arr[0]), cmp_int);
for (size_t i = 0; i < nelem; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
Answer:
Too many calls to memcpy. You don't need to memcpy individual elements. Once you found the place where key_copy should land, memmove the entire block of elements in one go.
A mandatory no naked loops mantra.
Every loop implements and algorithm, and therefore deserves a name. Make the inner loop a function.
A mandatory insertion sort review.
This implementation is suboptimal. At every iteration of an inner loop two conditions are tested: curr > base &and compar(curr - size, key_copy) > 0. You may get away with only one test per iteration (and perhaps less calls to compar).
Compare the current key with the base key. If it is less, you know it shall land at the base; don't bother to compare anymore - just shift the entire block to the right. Otherwise, the base key serves as a natural sentinel, and you never hit a curr == base case. | {
"domain": "codereview.stackexchange",
"id": 44063,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, sorting, reinventing-the-wheel, insertion-sort, c99",
"url": null
} |
c, sorting, reinventing-the-wheel, insertion-sort, c99
All that said, consider
void isort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)) {
for (size_t i = 1; i < nmemb; i++) {
char * curr = (char *)base + i * size;
char * insertion_point = base;
if (compar(base, curr) <= 0) {
insertion_point = find_insertion_point_unguarded(base, curr, compar, size);
}
char key_copy[size];
memcpy(key_copy, curr, size);
memmove(insertion_point + size, insertion_point, curr - insertion_point);
memcpy(insertion_point, key_copy, size);
}
}
An implementation of find_insertion_point_unguarded left as an exercise to the reader. | {
"domain": "codereview.stackexchange",
"id": 44063,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, sorting, reinventing-the-wheel, insertion-sort, c99",
"url": null
} |
javascript, jquery
Title: Build JS object that will be pass into the Handler
Question: I am working on a web page where I am creating a JS object using {} and []. This object is passed into a handler. I wanted to see if there is a better way to create the object in JavaScript
My logic
Is to build the object is JS and then pass it into the Handler to be Deserialize and then saved into the db.
Can anyone please review this code and point out the mistakes/how to make the implementation better?
const MeetingPollingQuestionTypeId = {
LongAnswerText: 1,
MultipleChoice: 2,
MultipleChoiceGrid:3
};
const MeetingPollingPartsTypeId = {
Question: 1,
Image: 2,
Answer: 3
};
const MeetingPollingPartsValuesTypeId = {
Label: 1,
Img: 2,
Radio:3
}
function saveMultipleChoice() {
console.log('%c saveMultipleChoice ', 'background: #222; color: #bada55');
let sequenceorder = fnSequenceOrder();
MeetingPollingQuestion = {};
MeetingPollingQuestion.MeetingPollingId = $("#hfMeetingPollingId").val();
MeetingPollingQuestion.MeetingPollingQuestionType = "MultipleChoice";
MeetingPollingQuestion.SequenceOrder = sequenceorder;
MeetingPollingQuestion.MeetingPollingParts = [];
MeetingPollingParts = {};
MeetingPollingParts.MeetingPollingPartsTypeId = MeetingPollingPartsTypeId.Question;
MeetingPollingParts.MeetingPollingPartsValues = [];
MeetingPollingPartsValues = {};
MeetingPollingPartsValues.MeetingPollingPartsValuesTypeId = MeetingPollingPartsValuesTypeId.label,
MeetingPollingPartsValues.QuestionValue = $("#editor").data("kendoEditor").value();
MeetingPollingParts.MeetingPollingPartsValues.push(MeetingPollingPartsValues);
MeetingPollingQuestion.MeetingPollingParts.push(MeetingPollingParts);
MeetingPollingParts = {};
MeetingPollingParts.MeetingPollingPartsTypeId = MeetingPollingPartsTypeId.Image;
MeetingPollingParts.MeetingPollingPartsValues = []; | {
"domain": "codereview.stackexchange",
"id": 44064,
"lm_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, jquery",
"url": null
} |
javascript, jquery
MeetingPollingPartsValues = {};
MeetingPollingPartsValues.Type = "FileManagerId";
MeetingPollingPartsValues.FileManagerId = $("#hfFileManagerId").val();
MeetingPollingParts.MeetingPollingPartsValues.push(MeetingPollingPartsValues);
MeetingPollingQuestion.MeetingPollingParts.push(MeetingPollingParts);
MeetingPollingParts = {};
MeetingPollingParts.MeetingPollingPartsTypeId = MeetingPollingPartsTypeId.Answer;
MeetingPollingParts.MeetingPollingPartsValues = [];
var items = $("#selectanswer").data("kendoMultiSelect");
var selectedDataItems = items.dataItems();
$(selectedDataItems).each(function () {
MeetingPollingPartsValues = {};
MeetingPollingPartsValues.MeetingPollingPartsValuesTypeId = MeetingPollingPartsValuesTypeId.Radio
MeetingPollingPartsValues.QuestionValue = this.text;
MeetingPollingParts.MeetingPollingPartsValues.push(MeetingPollingPartsValues);
});
MeetingPollingParts.MeetingPollingPartsValues.push(MeetingPollingPartsValues);
MeetingPollingQuestion.MeetingPollingParts.push(MeetingPollingParts);
console.log(MeetingPollingQuestion); | {
"domain": "codereview.stackexchange",
"id": 44064,
"lm_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, jquery",
"url": null
} |
javascript, jquery
console.log(MeetingPollingQuestion);
Metronic.blockUI({ boxed: true, message: "Saving Question.." });
$.ajax({
type: 'POST',
url: 'ManagePolling.ashx',
data: { "PollingQuestion": JSON.stringify(MeetingPollingQuestion), "Action": "SaveQuestion" },
datatype: "JSON",
success: function (data) {
if (data.resultStatus.ResultCode == "1") {
toastr.success("Saved successfully", "Success");
console.log('%c MeetingPollingQuestion Success! ', 'background: #222; color: #bada55');
htmlBuilderMultipleChoice(MeetingPollingQuestion);
}
if (data.resultStatus.ResultCode == "2")
toastr.warning(data.resultStatus.Message, "Warning");
if (data.resultStatus.ResultCode == "3")
toastr.warning(data.resultStatus.Message, "Error");
Metronic.unblockUI();
},
error: function (data) {
toastr.error('An error has occured! \n' + data.resultStatus.Message);
Metronic.unblockUI();
}
});
}
Answer: It is better that you use ECMAScript standards.
Here is a slightly revised version of your code in ECMAScript:
const MeetingPollingQuestionTypeId = {
LongAnswerText: 1,
MultipleChoice: 2,
MultipleChoiceGrid: 3,
};
const MeetingPollingPartsTypeId = {
Question: 1,
Image: 2,
Answer: 3,
};
const MeetingPollingPartsValuesTypeId = {
Label: 1,
Img: 2,
Radio: 3,
};
const saveMultipleChoice = () => {
console.log("%c saveMultipleChoice ", "background: #222; color: #bada55");
let sequenceorder = fnSequenceOrder();
let MeetingPollingQuestion = {};
MeetingPollingQuestion.MeetingPollingId = $("#hfMeetingPollingId").val();
MeetingPollingQuestion.MeetingPollingQuestionType = "MultipleChoice";
MeetingPollingQuestion.SequenceOrder = sequenceorder;
MeetingPollingQuestion.MeetingPollingParts = []; | {
"domain": "codereview.stackexchange",
"id": 44064,
"lm_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, jquery",
"url": null
} |
javascript, jquery
let MeetingPollingParts = {};
MeetingPollingParts.MeetingPollingPartsTypeId =
MeetingPollingPartsTypeId.Question;
MeetingPollingParts.MeetingPollingPartsValues = [];
let MeetingPollingPartsValues = {};
(MeetingPollingPartsValues.MeetingPollingPartsValuesTypeId =
MeetingPollingPartsValuesTypeId.label),
(MeetingPollingPartsValues.QuestionValue = $("#editor")
.data("kendoEditor")
.value());
MeetingPollingParts.MeetingPollingPartsValues.push(MeetingPollingPartsValues);
MeetingPollingQuestion.MeetingPollingParts.push(MeetingPollingParts);
MeetingPollingParts = {};
MeetingPollingParts.MeetingPollingPartsTypeId =
MeetingPollingPartsTypeId.Image;
MeetingPollingParts.MeetingPollingPartsValues = [];
MeetingPollingPartsValues = {};
MeetingPollingPartsValues.Type = "FileManagerId";
MeetingPollingPartsValues.FileManagerId = $("#hfFileManagerId").val();
MeetingPollingParts.MeetingPollingPartsValues.push(MeetingPollingPartsValues);
MeetingPollingQuestion.MeetingPollingParts.push(MeetingPollingParts);
MeetingPollingParts = {};
MeetingPollingParts.MeetingPollingPartsTypeId =
MeetingPollingPartsTypeId.Answer;
MeetingPollingParts.MeetingPollingPartsValues = [];
let items = $("#selectanswer").data("kendoMultiSelect");
let selectedDataItems = items.dataItems();
$(selectedDataItems).each(() => {
MeetingPollingPartsValues = {};
MeetingPollingPartsValues.MeetingPollingPartsValuesTypeId =
MeetingPollingPartsValuesTypeId.Radio;
MeetingPollingPartsValues.QuestionValue = this.text;
MeetingPollingParts.MeetingPollingPartsValues.push(
MeetingPollingPartsValues
);
});
MeetingPollingParts.MeetingPollingPartsValues.push(MeetingPollingPartsValues);
MeetingPollingQuestion.MeetingPollingParts.push(MeetingPollingParts);
console.log(MeetingPollingQuestion); | {
"domain": "codereview.stackexchange",
"id": 44064,
"lm_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, jquery",
"url": null
} |
javascript, jquery
console.log(MeetingPollingQuestion);
Metronic.blockUI({ boxed: true, message: "Saving Question.." });
$.ajax({
type: "POST",
url: "ManagePolling.ashx",
data: {
PollingQuestion: JSON.stringify(MeetingPollingQuestion),
Action: "SaveQuestion",
},
datatype: "JSON",
success: (data) => {
if (data.resultStatus.ResultCode == "1") {
toastr.success("Saved successfully", "Success");
console.log(
"%c MeetingPollingQuestion Success! ",
"background: #222; color: #bada55"
);
htmlBuilderMultipleChoice(MeetingPollingQuestion);
}
if (data.resultStatus.ResultCode == "2")
toastr.warning(data.resultStatus.Message, "Warning");
if (data.resultStatus.ResultCode == "3")
toastr.warning(data.resultStatus.Message, "Error");
Metronic.unblockUI();
},
error: (data) => {
toastr.error("An error has occured! \n" + data.resultStatus.Message);
Metronic.unblockUI();
},
});
} | {
"domain": "codereview.stackexchange",
"id": 44064,
"lm_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, jquery",
"url": null
} |
python
Title: Automate the Boring Stuff Chapter 12 - 2048
Question: The project outline:
2048 is a simple game where you combine tiles by sliding them up,
down, left, or right with the arrow keys. You can actually get a
fairly high score by repeatedly sliding in an up, right, down, and
left pattern over and over again. Write a program that will open the
game at https://gabrielecirulli.github.io/2048/ and keep sending up,
right, down, and left keystrokes to automatically play the game.
My solution:
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
def main():
service = Service(r"C:\Program Files\WebDrivers\geckdriver\geckodriver.exe")
options = Options()
options.binary_location = r"C:\Program Files\Mozilla Firefox\firefox.exe"
driver = webdriver.Firefox(service=service, options=options)
driver.get("https://gabrielecirulli.github.io/2048/")
try:
cookie_elem = driver.find_element(By. XPATH, '//*[@id="ez-accept-all"]')
html_elem = driver.find_element(By.TAG_NAME, "html")
except:
print("Was not able to find an element with that name.")
cookie_elem.click()
time.sleep(1)
while True:
html_elem.send_keys(Keys.UP)
time.sleep(0.1)
html_elem.send_keys(Keys.RIGHT)
time.sleep(0.1)
html_elem.send_keys(Keys.DOWN)
time.sleep(0.1)
html_elem.send_keys(Keys.LEFT)
time.sleep(0.1)
if __name__ == '__main__':
main()
Answer: This code looks straight-forward and simple enough to me.
The 1 change request I'd make is around the bare except. With exception handling you should always try to be as specific as possible so ideally you'd have something like:
from selenium.common.exceptions import NoSuchElementException | {
"domain": "codereview.stackexchange",
"id": 44065,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
...
try:
driver.find_element(...)
except NoSuchElementException as e:
print(e)
...
or at the very least use except Exception: instead of except because bare excepts are almost always not what you want because you'll ignore all exceptions even things like KeyboardInterrupt which means you can't stop the script from running with Ctrl+C.
Also even with just except Exception, you should really try to capture exception information instead of swallowing it so here's a nasty one - you'll catch NameErrors so in a fresh file try these out:
try:
some_var_that_doesnt_exist_at_all
this_should_totally_not_work_and_break
except:
print("gonna ignore whatever I just caught")
# vs
some_var_that_doesnt_exist # you get an obvious NameError & stacktrace
# vs
try:
some_var_that_doesnt_exist_at_all
except Exception as e:
print(e) # prints 'name some_var_that_doesnt_exist_at_all is not defined' | {
"domain": "codereview.stackexchange",
"id": 44065,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
print will print to stdout and typically you want errors going out into stderr. In a production-ready app, you should leverage logging in favor of print and you can easily just logging.exception("a message") to capture stack traces and error information within an except block much better than just print(e).
Finally a suggestion (or what could be considered an extra feature).
Swappable configuration
1 thing that sticks out immediately to me is how this code is tightly coupled to a few things that would be nice if they were configurable at runtime dynamically and/or statically at startup. Specifically the driver to use (i.e. FireFox vs Chrome), the path to the driver binary, and the path to your browser executable. This would let you change these variables without having to go and edit code each time. Also you wouldn't have to hardcode the path to your binary which means if someone else tried to run your script on their machine, the code wouldn't just break. You could do this in a number of ways, but here are some:
Dynamic configuration at runtime
aka can be changed after script startup
Use something like sys.argv or argparse or typer to read input from a user.
Static configuration at startup
aka can configure without code changes before running the script
Read from a config file like json or use a .env file which is a bit more conventional. python-dotenv makes using a .env file super simple so I'd recommend that. | {
"domain": "codereview.stackexchange",
"id": 44065,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
Title: Automate the Boring Stuff Chapter 12 - Image Site Downloader
Question: The project outline:
Write a program that goes to a photo-sharing site like Flickr or
Imgur, searches for a category of photos, and then downloads all the
resulting images. You could write a program that works with any photo
site that has a search feature.
My solution:
import sys, requests, os, bs4, time
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.common.by import By
def get_image_posts(url):
# Returns a list of imgur post urls
res = requests.get(url)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, "html.parser")
image_posts = ["https://imgur.com" + a["href"] for a in soup.select(".post a", href=True)]
if not image_posts:
print("Could not find any image posts.")
else:
return image_posts
def download_images(image_posts, driver, download_folder):
# Finds the image url in the post and downloads it.
for image_post in image_posts:
driver.get(image_post)
time.sleep(1)
content = driver.page_source.encode("utf-8").strip()
soup = bs4.BeautifulSoup(content, "html.parser")
image_elem = soup.select_one("img.image-placeholder")
if not image_elem:
print("Could not find an image.")
else:
image_url = image_elem["src"]
res = requests.get(image_url)
res.raise_for_status()
with open(os.path.join(download_folder, os.path.basename(image_url)), "wb") as image_file:
for chunk in res.iter_content(100000):
image_file.write(chunk) | {
"domain": "codereview.stackexchange",
"id": 44066,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
def main():
search_term = sys.argv[1]
download_folder = sys.argv[2]
os.makedirs(download_folder, exist_ok=True)
service = Service(r"C:\Program Files\WebDrivers\geckdriver\geckodriver.exe")
options = Options()
options.binary_location = r"C:\Program Files\Mozilla Firefox\firefox.exe"
driver = webdriver.Firefox(service=service, options=options)
driver.get("https://imgur.com/")
try:
cookie_elem = driver.find_element(By. XPATH, "/html/body/div[1]/div/div/div/div[2]/div/button[2]")
search_elem = driver.find_element(By.CLASS_NAME, "Searchbar-textInput")
except:
print('Was not able to find an element with that name.')
cookie_elem.click()
search_elem.send_keys(search_term)
search_elem.submit()
time.sleep(1)
url = driver.current_url
image_posts = get_image_posts(url)
download_images(image_posts, driver, download_folder)
if __name__ == '__main__':
main()
I chose the site Imgur. My soluton works, though it is slow and clunky so I decided to limit it to one image download per page.
Answer: String Concatenation
Use str.format or f-strings instead of +:
# go from this
"https://imgur.com" + a["href"]
# to either str.format:
"https://imgur.com{}".format(a["href"])
# or using an f-string for python 3.5+
f"https://imgur.com{a['href']}"
Image Posts Iteration
In the case of an empty list, I would still return it:
def get_image_posts(url):
~snip~
if not image_posts:
print("No image posts")
# this is still a list, it just could be empty
return image_posts
Then, I'd move the iteration out of the download_images function and into main:
def main():
~snip~
for post in get_image_posts(url):
download_image(post, driver, download_folder) | {
"domain": "codereview.stackexchange",
"id": 44066,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
Then I'd probably handle looking up the image via browser separately from downloading it:
def get_image_url(post):
driver.get(post)
content = driver.page_source.encode("utf-8").strip()
soup = bs4.BeautifulSoup(content, "html.parser")
image_elem = soup.select_one("img.image-placeholder")
return image_elem
Then, it's easy to filter for downloading:
def main():
~snip~
for post in get_image_posts(url):
src = get_image_url(post, driver)
# skip empty sources
if not src:
continue
url = src['url']
download_image(url, download_folder)
# move the sleep here so it's more explicit
time.sleep(1)
And now download_image looks like:
def download_images(url, driver, download_folder):
res = requests.get(url)
res.raise_for_status()
with open(os.path.join(download_folder, os.path.basename(url)), "wb") as image_file:
for chunk in res.iter_content(100000):
image_file.write(chunk)
Line Length
The with open line is a bit long, so it might be worth defining a path separately like:
def download_images(url, driver, download_folder):
res = requests.get(url)
res.raise_for_status()
filepath = os.path.join(
download_folder,
os.path.basename(url)
)
with open(filepath, 'wb') as fh:
# write to file
sys.args
Since you are unpacking sys.argv[1] and sys.argv[2], I'd do that outside of main:
def main(search_term, download_folder):
~snip~
if __name__ == "__main__":
search_term, download_folder, *_ = sys.argv[1:]
# pass them as args to main
main(search_term, download_folder) | {
"domain": "codereview.stackexchange",
"id": 44066,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
# pass them as args to main
main(search_term, download_folder)
Passing them as args to main makes it easier to ascertain what arguments are to be expected, and it makes this more flexible. If you want to reuse this in another module, you have to know to pass these command line arguments for them to be accessible. Now that they are parameters, this isn't the case.
It also might be useful to define a usage string to tell the user what arguments are to be expected:
USAGE = """Downloads files from imgur.com using
a search_term to a specified download_folder.
Usage:
python myscript.py "my search term" "/path/to/folder"
"""
~snip~
if __name__ == "__main__":
try:
search_term, download_folder, *_ = sys.argv[1:]
except ValueError:
print(USAGE)
else:
# pass them as args to main
main(search_term, download_folder)
I'd also look into the argparse library
try/except => print
This pattern can result in NameErrors, which for a user will be baffling. Raise any unhandled exceptions:
try:
cookie_elem = driver.find_element(By. XPATH, "/html/body/div[1]/div/div/div/div[2]/div/button[2]")
search_elem = driver.find_element(By.CLASS_NAME, "Searchbar-textInput")
# for a bare except, always raise
except:
print('Was not able to find an element with that name.')
raise
The best thing to do is to figure out what exceptions will be raised and if you want to handle them. Catch them explicitly. Otherwise just a print won't do anything and you'll get search_elem not defined, which is true, but it masks the real error. | {
"domain": "codereview.stackexchange",
"id": 44066,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
ruby, file, ruby-on-rails
Title: Open a file, with a fallback path if it doesn't exist at one location
Question: I am parsing a file that exists in either app/components/ui or in app/components. If the one in the first dir (app/components/ui) doesn't exist, then fallback to the app/components directory. This is what I have currently.
def front_matter
return unless params[:filename].present?
path = Rails.root.join('app', 'components', 'ui', params[:filename])
path = Rails.root.join('app', 'components', params[:filename]) unless File.exist?(path)
@front_matter ||= FrontMatterParser::Parser.parse_file(path)
end
Is there a better way to write this?
Answer: It seems OK to me. You might put the file logic into another method, perhaps, so that #front_matter is only doing one thing?
def front_matter_path
path = Rails.root.join('app', 'components', 'ui', params[:filename])
return path if File.exist?(path)
Rails.root.join('app', 'components', params[:filename])
end
def front_matter
return unless params[:filename].present?
@front_matter ||= FrontMatterParser::Parser.parse_file(front_matter_path)
end | {
"domain": "codereview.stackexchange",
"id": 44067,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "ruby, file, ruby-on-rails",
"url": null
} |
sql
Title: 15 Days of Learning SQL (HackerRank Challenge) - is having multiple queries a good idea in this case?
Question: The challenge is as follows:
"Julia conducted a 15 days of learning SQL contest. The start date of the contest was March 01, 2016 and the end date was March 15, 2016.
Write a query to print total number of unique hackers who made at least one submission each day (starting on the first day of the contest), and find the hacker_id and name of the hacker who made maximum number of submissions each day. If more than one such hacker has a maximum number of submissions, print the lowest hacker_id. The query should print this information for each day of the contest, sorted by the date."
Details are here.
My solution was accepted, and I got a full score. However, my solution has 7 queries and 1 while loop. Since I mostly use python and C++, this is a natural way for me, and I find it more readable than just one very big query. Is it ok in this instance? Any other comment is welcome, too.
DECLARE @TODAY DATETIME = '2016-03-01', @STOP_DATE DATETIME = '2016-03-15', @TOMORROW DATETIME
SELECT * INTO #TEMP_CONSECUTIVE FROM (
SELECT submission_date, hacker_id AS h_id, COUNT(*) AS COUNT_ATTEMPTS FROM Submissions WHERE submission_date = @TODAY GROUP BY submission_date, hacker_id
)
AS X
WHILE (@TODAY < @STOP_DATE)
BEGIN
SET @TOMORROW = DATEADD(DAY, 1, @TODAY)
INSERT INTO #TEMP_CONSECUTIVE (submission_date, h_id, COUNT_ATTEMPTS) SELECT submission_date, hacker_id, COUNT(*) FROM Submissions WHERE submission_date = @TOMORROW AND EXISTS(SELECT * FROM #TEMP_CONSECUTIVE WHERE submission_date=@TODAY AND h_id=hacker_id) GROUP BY submission_date, hacker_id
SET @TODAY = @TOMORROW
END
SELECT * INTO #TEMP_ATTEMPTS_COUNT FROM (SELECT submission_date, hacker_id AS h_id, COUNT(*) AS COUNT_ATTEMPTS FROM Submissions --WHERE submission_date = @TOMORROW
GROUP BY submission_date, hacker_id) AS U | {
"domain": "codereview.stackexchange",
"id": 44068,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "sql",
"url": null
} |
sql
SELECT submission_date, MAX_COUNT_ATTEMPTS INTO #TEMP_MAX FROM (
SELECT submission_date, MAX(COUNT_ATTEMPTS) AS MAX_COUNT_ATTEMPTS FROM #TEMP_ATTEMPTS_COUNT GROUP BY submission_date
) AS Y
SELECT submission_date, COUNT_MAX_COUNT_ATTEMPTS, HACKER_ID, HACKER_NAME INTO #TEMP_RESULT FROM (
SELECT TM.submission_date, COUNT(DISTINCT TC.h_id) AS COUNT_MAX_COUNT_ATTEMPTS, MIN(TAC.h_id) AS HACKER_ID, CAST('' AS NVARCHAR(MAX)) AS HACKER_NAME
FROM #TEMP_MAX TM INNER JOIN #TEMP_ATTEMPTS_COUNT TAC ON (TM.submission_date=TAC.submission_date AND TM.MAX_COUNT_ATTEMPTS=TAC.COUNT_ATTEMPTS)
INNER JOIN #TEMP_CONSECUTIVE TC ON (TM.submission_date=TC.submission_date)
GROUP BY TAC.submission_date, TAC.COUNT_ATTEMPTS, TM.submission_date, TM.MAX_COUNT_ATTEMPTS
) AS Z
UPDATE TR SET TR.HACKER_NAME=H.NAME FROM HACKERS H INNER JOIN #TEMP_RESULT TR ON (TR.HACKER_ID = H.HACKER_ID)
SELECT * FROM #TEMP_RESULT ORDER BY submission_date
Answer: No; this doesn't look like a good way to use SQL.
Use of WHILE loops, temp tables, etc are sometimes helpful for performance reasons, but they're very rarely needed to express yourself in SQL, and used naively they will generally make performance worse.
Idiomatic SQL is "declarative", meaning you say what the result of the computation should be, and as much as practical you let the engine worry about how to compute it. In this case, you've been asked to do two things (list who submitted every day, and list who submitted the most each day), so I would expect to see just two "top level" queries. Different SQL variants will give you different options for nesting or breaking out sub-queries, but it would look roughly like
DECLARE @START_DATE DATETIME = '2016-03-01'
DECLARE @STOP_DATE DATETIME = '2016-03-15' | {
"domain": "codereview.stackexchange",
"id": 44068,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "sql",
"url": null
} |
sql
SELECT h.hacker_id -- 1) Tell me IDs
FROM ( -- 4) A daily submission is
SELECT s.hacker_id -- 5) just the ID
FROM Submissions AS s -- 6) of a submission
GROUP BY s.hacker_id, DATE(s.submission_date) -- 7) de-duplicated by date.
) AS h
GROUP BY h.hacker_id -- 2) de-duplicated
HAVING DAYS(@START_DATE, @END_DATE) = COUNT(*) -- 3) with daily submissions.
WITH scores AS ( -- 01) everyone's daily scores are
SELECT s.hacker_id -- 02) their id,
,DATE(s.submission_date) AS date -- 03) the date,
,COUNT(*) AS score -- 04) and their submission count
FROM Submissions AS s
GROUP BY date, s.hacker_id -- 05) for every hacker every day.
)
SELECT s.date, MIN(s.hacker_id) -- 14) and print the lowest ID.
FROM scores AS s -- 11) get the daily scores
INNER JOIN ( -- 06) The high scores are
SELECT hs.date, MAX(hs.score) AS score -- 07) the date and highest score
FROM scores AS hs
GROUP BY hs.date -- 08) each day.
) AS high_scores
ON s.date = high_scores.date -- 12) for that day
AND s.score = high_scores.score -- 13) that are the high score,
GROUP BY s.date -- 09) For each day
ORDER BY s.date -- 10) in order | {
"domain": "codereview.stackexchange",
"id": 44068,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "sql",
"url": null
} |
c++, linked-list
Title: Inserting into a Sorted Doubly Linked List
Question: Edited: incorporated some feedback and added a lot of features
I've written a basic Doubly Linked List Class where every insertion into the class should be sorted into ascending order. The project will eventually merge two LinkedLists so the prev pointers to the Nodes will assist with that.
For now, I was looking for feedback on how well implemented an insertion method. I elected to create two private methods to cover cases where you need to insert at the front and everywhere else.
SortedList.h
#include <iostream>
#pragma once
class SortedList
{
struct Node {
int data = 0;
Node* prev = nullptr;
Node* next = nullptr;
};
private:
int m_numItems;
Node* m_head;
public:
// CONSTRUCTOR
SortedList();
// copy constructor
SortedList(const SortedList& otherList);
// move constructor
SortedList(SortedList&& rhs) noexcept;
// DESTRUCTOR
~SortedList();
// ACCESSORS
/** Gets the current number of entries in this list.
@return The integer number of entries currently in the list. */
int size() const;
/** Sees whether this list is empty.
@return true if the list is empty, or false if not. */
bool empty() const;
/** Output the contents of a sorted list in order,
with each element separated by a space.*/
void display(std::ostream& out) const;
// MUTATORS
/** Creates a new Node (dynamically allocated) where Node member data = item.
Inserts in the correct location of the sorted list (ascending order), and increases m_numItems by 1.
@return true if the new Node with item was added successfully, otherwise returns false. */
bool insert(int item); | {
"domain": "codereview.stackexchange",
"id": 44069,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list",
"url": null
} |
c++, linked-list
/** Searches and removes the first occurrence of item in the list. If found,
deallocates memory for the removed Node.
@return true if item was removed successfully, otherwise returns false if item
was not found in the List or the List was empty.
Reduces m_numItems by 1 */
bool remove(int item);
/** Removes all entries from this list.
@post List contains no items, and the count of items is 0. */
void clear();
/** Overloads [] operator to find an index for a given item.
First item in the list is at location 0.
@return int index for a given value, -1 if item isn't found. */
int operator[] (int item) const;
/** Overloaded assignment operator for deep copy. First deallocates memory for all of the Nodes (if any) in the
sorted list on the left-hand side before creating new Nodes for all Nodes in the sorted list on the
right-hand side and copying each data item.
@return the new lhs list. If the lhs and rhs lists are the same, it will do nothing. */
SortedList& operator=(const SortedList& rhs);
/** Move assignment operator: will be used instead of the assignment operator when assigning a temporary SortedList
to another SortedList. Instead of copying the Nodes from the temporary list into a non-temporary list and destroying
the temporary list, it can simply pass that temporary list over to be assigned.
@return the new lhs list */
SortedList& operator=(SortedList&& rhs) noexcept;
/** Overloads the equality operator to check if the current sorted list (the left-hand side) is equal to
sl (the sorted list on the right-hand side). Two sorted lists are equal if they are the same size and every
item in one list is the same as the corresponding item in the other list.
@return true if the two sorted lists are equal, otherwise false. */
bool operator==(const SortedList& otherList) const;
bool operator!=(const SortedList& otherList) const;
private:
// MUTATORS | {
"domain": "codereview.stackexchange",
"id": 44069,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list",
"url": null
} |
c++, linked-list
bool operator!=(const SortedList& otherList) const;
private:
// MUTATORS
/** prepend new item to the head of the list
@return true if item was inserted successfully */
bool insertFront(int item);
/** append new item to the tail of the list
@return true if item was inserted successfully */
bool insertBack(Node* tail, int item);
/** Called by insert method to insert new item before a given node in the list
that is not at the head of the list
@return true if item was inserted successfully */
bool insertBefore(Node* curr_node, int item);
/** remove item at the head of the list
@return true if item was removed successfully*/
bool removeFront(Node* prev_node);
/** remove current Node that's not at head of list
@return true if item was removed successfully */
bool removeCurr(Node* prev_node, Node* curr_node);
/** Creates a deep copy of the sorted list that is passed in (otherList).
A deep copy will create new Node objects for each Node in otherList and copy the data for each Node in the correct order.
If otherList is empty, it will do nothing.*/
void copyListNodes(const SortedList& other_list);
public:
// FRIENDS
/** Overloads the stream insertion operator to output the contents of a sorted list in order,
with each element separated by a space. Makes the operator<< method a friend to SortedList class.*/
friend std::ostream& operator<<(std::ostream& output, const SortedList& list);
/** Function overloads + and is defined outside of the SortedList class.
Used to merge two SortedLists (lhs and rhs), keeping all items in sorted order.
@return new merged SortedList. */
friend SortedList operator+(const SortedList& lhs, const SortedList& rhs);
};
SortedList.cpp
#include "SortedList.h"
#include <iostream>
// CONSTRUCTOR
SortedList::SortedList() {
m_numItems = 0;
m_head = nullptr;
} | {
"domain": "codereview.stackexchange",
"id": 44069,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list",
"url": null
} |
c++, linked-list
// CONSTRUCTOR
SortedList::SortedList() {
m_numItems = 0;
m_head = nullptr;
}
// copy constructor
SortedList::SortedList(const SortedList& otherList) {
copyListNodes(otherList);
}
// move constructor
SortedList::SortedList(SortedList&& rhs) noexcept {
m_numItems = rhs.m_numItems;
m_head = rhs.m_head;
rhs.m_head = nullptr;
}
// DESTRUCTOR
SortedList::~SortedList() {
this->clear();
}
// ACCESSORS
/** Gets the current number of entries in this list.
@return The integer number of entries currently in the list. */
int SortedList::size() const {
return m_numItems;
}
/** Sees whether this list is empty.
@return true if the list is empty, or false if not. */
bool SortedList::empty() const {
return m_head == nullptr;
}
/** Output the contents of a sorted list in order,
with each element separated by a space.*/
void SortedList::display(std::ostream& out) const {
Node* curr = m_head;
if (curr == nullptr) {
out << "The sorted list is empty";
}
while (curr) {
out << curr->data << " ";
curr = curr->next;
}
out << std::endl;
}
// MUTATORS
/** Creates a new Node (dynamically allocated) where Node member data = item.
Inserts in the correct location of the sorted list (ascending order), and increases m_numItems by 1.
@return true if the new Node with item was added successfully, otherwise returns false. */
bool SortedList::insert(int item) {
Node* curr_node = m_head;
if (curr_node == nullptr) {
insertFront(item);
++m_numItems;
return true;
}
Node* prev_node = nullptr;
while (curr_node != nullptr) {
; if (item <= curr_node->data) {
if (curr_node->prev == nullptr) {
insertFront(item);
}
else {
insertBefore(curr_node, item);
}
++m_numItems;
return true;
}
prev_node = curr_node;
curr_node = curr_node->next;
}
insertBack(prev_node, item);
++m_numItems;
} | {
"domain": "codereview.stackexchange",
"id": 44069,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list",
"url": null
} |
c++, linked-list
/** Searches and removes the first occurrence of item in the List. If found,
deallocates memory for the removed Node.
@return true if item was removed successfully, otherwise returns false if anEntry
was not found in the List or the List was empty.
Reduces m_numItems by 1 */
bool SortedList::remove(int item) {
Node* curr_node = m_head;
Node* prev_node = nullptr;
while (curr_node != nullptr) {
if (item == curr_node->data) {
// item is at the head position
if (prev_node == nullptr) {
removeFront(prev_node);
}
// item is elsewhere
else {
removeCurr(prev_node, curr_node);
}
--m_numItems;
return true;
}
else {
// advance pointers
prev_node = curr_node;
curr_node = curr_node->next;
}
}
return false;
}
/** Removes all entries from this list.
@post List contains no items, and the count of items is 0. */
void SortedList::clear()
{
Node* current = m_head;
while (current) {
Node* next = current->next;
delete current;
--m_numItems;
current = next;
}
m_head = nullptr;
}
/**overloads [] operator to find an index for a given item.
First item in the list is at location 0.
@return int index for a given value, -1 if item isn't found. */
int SortedList::operator[] (int item) const {
Node* curr_node = m_head;
int curr_index = 0;
while (curr_node != nullptr) {
if (curr_node->data == item) {
return curr_index;
}
++curr_index;
curr_node = curr_node->next;
}
return -1;
} | {
"domain": "codereview.stackexchange",
"id": 44069,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list",
"url": null
} |
c++, linked-list
/** Overloaded assignment operator for deep copy. First deallocates memory for all of the Nodes (if any) in the
sorted list on the left-hand side before creating new Nodes for all Nodes in the sorted list on the
right-hand side and copying each data item.
@return the new lhs list. If the lhs and rhs lists are the same, it will do nothing.*/
SortedList& SortedList::operator=(const SortedList& rhs) {
if (this != &rhs) {
this->clear();
copyListNodes(rhs);
}
return *this;
}
/** Move assignment operator: will be used instead of the assignment operator when assigning a temporary SortedList
to another SortedList. Instead of copying the Nodes from the temporary list into a non-temporary list and destroying
the temporary list, it can simply pass that temporary list over to be assigned.
@return the new lhs list */
SortedList& SortedList::operator=(SortedList&& rhs) noexcept {
m_numItems = rhs.m_numItems;
m_head = rhs.m_head;
rhs.m_head = nullptr;
return *this;
}
/** Overloads the equality operator to check if the current sorted list (the left-hand side) is equal to
sl (the sorted list on the right-hand side). Two sorted lists are equal if they are the same size and every
item in one list is the same as the corresponding item in the other list.
@return true if the two sorted lists are equal, otherwise false. */
bool SortedList::operator==(const SortedList& otherList) const {
if (this->size() != otherList.size()) {
return false;
}
Node* this_curr = m_head;
Node* other_curr = otherList.m_head;
while (this_curr != nullptr || other_curr != nullptr) {
if (this_curr->data != other_curr->data) {
return false;
}
this_curr = this_curr->next;
other_curr = other_curr->next;
}
return true;
}
bool SortedList::operator!=(const SortedList& otherList) const {
if (this->size() != otherList.size()) {
return true;
} | {
"domain": "codereview.stackexchange",
"id": 44069,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list",
"url": null
} |
c++, linked-list
Node* this_curr = m_head;
Node* other_curr = otherList.m_head;
while (this_curr != nullptr || other_curr != nullptr) {
if (this_curr->data != other_curr->data) {
return true;
}
this_curr = this_curr->next;
other_curr = other_curr->next;
}
return false;
}
/** Called by insert method to prepend new item to the head of the list
@return true if item was inserted successfully*/
bool SortedList::insertFront(int item) {
Node* curr_node = new Node;
curr_node->data = item;
curr_node->next = m_head;
curr_node->prev = nullptr;
if (m_head != nullptr) {
m_head->prev = curr_node;
}
m_head = curr_node;
return true;
}
/** append new item to the tail of the list
@return true if item was inserted successfully */
bool SortedList::insertBack(Node* tail_node, int item) {
if (tail_node->next != nullptr) {
return false;
}
Node* new_node = new Node;
new_node->data = item;
tail_node->next = new_node;
new_node->prev = tail_node;
return true;
}
/** Called by insert method to insert new item before a given node in the list
that is not at the head of the list
@return true if item was inserted successfully */
bool SortedList::insertBefore(Node* curr_node, int item) {
if (curr_node->prev != nullptr) {
Node* new_node = new Node;
new_node->data = item;
new_node->next = curr_node;
new_node->prev = curr_node->prev;
curr_node->prev->next = new_node;
curr_node->prev = new_node;
}
else {
insertFront(item);
}
return true;
}
/** remove item at the head of the list
@return true if item was removed successfully */
bool SortedList::removeFront(Node* prev_node) {
prev_node = m_head;
m_head = m_head->next;
m_head->prev = nullptr;
delete prev_node;
return true;
} | {
"domain": "codereview.stackexchange",
"id": 44069,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list",
"url": null
} |
c++, linked-list
return true;
}
/** remove current Node that's not at head of list
@return true if item was removed successfully */
bool SortedList::removeCurr(Node* prev_node, Node* curr_node) {
prev_node->next = curr_node->next;
// conditional for when removing node at end of list
if (curr_node->next != nullptr) {
curr_node->next->prev = prev_node;
}
delete curr_node;
return true;
}
/** Creates a deep copy of the sorted list that is passed in (otherList).
A deep copy will create new Node objects for each Node in otherList and copy
the data for each Node in the correct order. If otherList is empty, it will
do nothing.*/
void SortedList::copyListNodes(const SortedList& otherList) {
Node* other_list_curr = otherList.m_head;
// copy first item new node to head
if (other_list_curr != nullptr) {
Node* new_node = new Node;
new_node->data = other_list_curr->data;
new_node->next = nullptr;
new_node->prev = m_head;
++m_numItems;
m_head = new_node;
other_list_curr = other_list_curr->next;
}
// copy remaining items to new nodes
Node* curr_node = m_head;
while (other_list_curr != nullptr) {
Node* new_node = new Node;
new_node->data = other_list_curr->data;
curr_node->next = new_node;
new_node->prev = curr_node;
curr_node = curr_node->next;
other_list_curr = other_list_curr->next;
++m_numItems;
}
}
// FRIENDS
/** Overloads the stream insertion operator to output the contents of a sorted list in order,
with each element separated by a space. Makes the operator<< method a friend to SortedList class.*/
std::ostream& operator<<(std::ostream& out, const SortedList& list) {
list.display(out);
return out;
} | {
"domain": "codereview.stackexchange",
"id": 44069,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list",
"url": null
} |
c++, linked-list
/** Function overloads + and is defined outside of the SortedList class.
Used to merge two SortedLists (lhs and rhs), keeping all items in sorted order.
@return new merged SortedList. */
SortedList operator+(const SortedList& lhs, const SortedList& rhs) {
SortedList mergedList;
if (&lhs == nullptr && &rhs == nullptr) {
return mergedList;
}
SortedList::Node* lhs_curr = lhs.m_head;
SortedList::Node* rhs_curr = rhs.m_head;
// for head, check if lhs data is <= rhs data
if (lhs_curr != nullptr && lhs_curr->data <= rhs_curr->data) {
SortedList::Node* new_node = new SortedList::Node;
new_node->data = lhs_curr->data;
new_node->next = nullptr;
new_node->prev = mergedList.m_head;
++mergedList.m_numItems;
mergedList.m_head = new_node;
lhs_curr = lhs_curr->next;
}
// for head, check if rhs data is <= lhs data
else if (rhs_curr != nullptr && rhs_curr->data <= lhs_curr->data) {
SortedList::Node* new_node = new SortedList::Node;
new_node->data = rhs_curr->data;
new_node->next = nullptr;
new_node->prev = mergedList.m_head;
++mergedList.m_numItems;
mergedList.m_head = new_node;
rhs_curr = rhs_curr->next;
}
SortedList::Node* ml_node = mergedList.m_head;
while (lhs_curr != nullptr || rhs_curr != nullptr) {
if (lhs_curr != nullptr) {
// while lhs is smaller or equal rhs, keep adding nodes from lhs
while (rhs_curr == nullptr || lhs_curr->data <= rhs_curr->data) {
SortedList::Node* new_node = new SortedList::Node;
new_node->data = lhs_curr->data;
ml_node->next = new_node;
new_node->prev = ml_node;
// advance nodes
ml_node = ml_node->next;
lhs_curr = lhs_curr->next;
++mergedList.m_numItems;
if (lhs_curr == nullptr) {
break;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44069,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list",
"url": null
} |
c++, linked-list
if (lhs_curr == nullptr) {
break;
}
}
}
if (rhs_curr != nullptr) {
// while rhs is smaller or equal rhs, keep adding nodes from rhs
while (lhs_curr == nullptr || rhs_curr->data <= lhs_curr->data) {
SortedList::Node* new_node = new SortedList::Node;
new_node->data = rhs_curr->data;
ml_node->next = new_node;
new_node->prev = ml_node;
// advance nodes
ml_node = ml_node->next;
rhs_curr = rhs_curr->next;
++mergedList.m_numItems;
if (rhs_curr == nullptr) {
break;
}
}
}
}
return mergedList;
}
Answer: Overview
This use of a list does not need to be doubly linked.
You could just as easily have made this a singly linked list and it would not have changed the complexity. The use of a singly linked list would reduce the memory used by 1/3.
Works great for int. But lots of things can be sorted. Would be nice to generalize this with a template so you can keep a sorted list of any type of object.
You should expand to have the basic properties of a container (i.e. you need to add iterators). | {
"domain": "codereview.stackexchange",
"id": 44069,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list",
"url": null
} |
c++, linked-list
Use your own namespace for your code.
Avoid magic numbers (-1).
Create a named constant value.
Use modern assignment operator form.
See below.
Learn the "Copy and Swap" idiom.
It is the exception-safe optimal way to implement assignment. It is worth studying so you can spot similar patterns in the code.
Use a sentinel value (here is an example)
if you plan to keep using the doubly linked list. It solves all corner cases with head and avoids you needing to check for null pointers.
Found 3 bugs.
Move operators (constructor/assignment) broken.
Undefined behavior because of a missing return.
Bad Interface design:
operator[] does not do what is expected.
If you templatize this code for the data, then you will need to add move semantics for the value being inserted.
Code review
Why is this outside the include guards?
#include <iostream>
This is not portable.
#pragma once
I would use normal include guards. Most IDEs will do it for you nowadays.
This is a perfectly good idea.
**BUT** is `-1` not a perfectly valid number that can be placed in the list?
How do you determine if it is a valid -1 or a -1 that indicates an out of range error? AVOID magic numbers.
/** Overloads [] operator to find an index for a given item.
First item in the list is at location 0.
@return int index for a given value, -1 if item isn't found. */
int operator[] (int item) const;
Most C++ containers would say it is undefined to access elements lower than zero or greater than or equal to size() (thus allowing for unchecked accesses). i.e. optimal access speed.
They usually also include an at() method for checked accesses that would throw for out of range index values. | {
"domain": "codereview.stackexchange",
"id": 44069,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list",
"url": null
} |
c++, linked-list
Leaving the above comment (though it is wrong). Because it shows that misusing the built in operators do do things that are not expected is a bad idea. I expected this to get the itemth item in the list. But it searches the list for item.
Bad Interface design.
People are going to trip up on this. Because people don't read documentation.
Don't delete data before you have correctly copied the source.
/** Overloaded assignment operator for deep copy. First deallocates memory for all of the Nodes (if any) in the
sorted list on the left-hand side before creating new Nodes for all Nodes in the sorted list on the
right-hand side and copying each data item.
@return the new lhs list. If the lhs and rhs lists are the same, it will do nothing. */
What happens if you start copying but there is an error?
In this situation, you are supposed to throw an exception. But if you do you have already released the original list, so your object has been modified. This means you don't provide the strong exception guarantee.
Strong Exception Guarantee: Either the operation works or the object is unmodified.
This is a bit old school.
SortedList& operator=(const SortedList& rhs);
SortedList& operator=(SortedList&& rhs) noexcept;
The modern way to do this:
SortedList& operator=(SortedList rhs) noexcept;
Then you would implement like this:
SortedList& operator=(SortedList rhs) noexcept
{
swap(rhs);
return *this;
}
Assuming you have implemented the Move constructor correctly, this works for both move and copy assignment optimally.
SortedList a;
SortedList b;
a = b; // This is now a standard copy and swap
a = std::move(b); // This moves the value to rhs.
// Then you swap rhs with the content of this.
// in both cases the destructor of rhs handles the cleanup
// of the original value in `a` | {
"domain": "codereview.stackexchange",
"id": 44069,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list",
"url": null
} |
c++, linked-list
// in both cases the destructor of rhs handles the cleanup
// of the original value in `a`
You have a bug here.
// move constructor
SortedList::SortedList(SortedList&& rhs) noexcept {
m_numItems = rhs.m_numItems;
m_head = rhs.m_head;
rhs.m_head = nullptr;
}
Think about this situation:
SortedList a;
a.insert(1)
SortedList b(std::move(a));
a.insert(2);
std::cout << "A Size: " << a.size() << " ?\n"; // why does it print 2.
std::cout << a << "\n"; // when this has one element.
Don't use this->.
SortedList::~SortedList() {
this->clear();
}
The only reason to use this-> is to disambiguate something.
Personally, for one-liners like this I would just leave in the header file. There is no need to have the implementation in the source file.
int SortedList::size() const {
return m_numItems;
}
bool SortedList::empty() const {
return m_head == nullptr;
}
Comment rot is a real thing.
/** Output the contents of a sorted list in order,
with each element separated by a space.*/
void SortedList::display(std::ostream& out) const {
Don't write the same thing in the header and source file. Write it once in one place. Otherwise you need to keep both versions in sync and that will not happen. Over time they will become out of sync. Then which do you believe?
Prefer "\n" over std::endl.
out << std::endl;
You don't want to force a flush every time!
bool SortedList::insert(int item) {
....
insertBack(prev_node, item);
++m_numItems;
// Forgot your return statement
}
Turn on all your compiler warnings and turn on the setting that treats them like errors. All warnings are logical errors in your thinking.
For g++ use -Wall -Wextra -Werror.
PS. This function always returns true at the moment.
I would expect it to return false if the value is already in the list or something like that.
/**
.....
Reduces m_numItems by 1 */
It's obvious. But you should probably say reduces by 1 if an item is removed. | {
"domain": "codereview.stackexchange",
"id": 44069,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list",
"url": null
} |
c++, linked-list
It's obvious. But you should probably say reduces by 1 if an item is removed.
bool SortedList::remove(int item) {
.....
return true;
}
else {
This else is redundant.
If the associated if() fired then you hit the above return statement.
void SortedList::clear()
{
....
while(...) {
...
--m_numItems;
....
}
Seems like an expensive way of saying:
m_numItems = 0;
Use the "Copy and Swap" Idiom.
SortedList& SortedList::operator=(const SortedList& rhs) {
if (this != &rhs) {
this->clear();
copyListNodes(rhs);
}
return *this;
}
Checking for assignment to self is a code pessimization.
Broken in the same way as the move constructor.
SortedList& SortedList::operator=(SortedList&& rhs) noexcept {
m_numItems = rhs.m_numItems;
m_head = rhs.m_head;
rhs.m_head = nullptr;
return *this;
}
Your don't reset the m_numItems on rhs. Remember that rhs must be in a valid state.
After moving from an object, the source of the move may return a non-zero value from size() but a call to empty() would return true.
// We have already established that the lists are the same size.
// So if `this_curr` is not nullptr then `other_curr` is not nullptr
// I suppose this protects against bugs in the code. But if your
// objects are already invalid because of a bug you want it to blow up sooner rather than later.
while (this_curr != nullptr || other_curr != nullptr) {
Don't repeat code.
bool SortedList::operator!=(const SortedList& otherList) const {
You should implement the != in terms of the == operator.
bool SortedList::operator!=(const SortedList& otherList) const {
return !(*this == otherList);
}
You can simplify this:
Node* curr_node = new Node;
curr_node->data = item;
curr_node->next = m_head;
curr_node->prev = nullptr;
It is the same as:
Node* curr_node = new Node{item, null, null}; | {
"domain": "codereview.stackexchange",
"id": 44069,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list",
"url": null
} |
c++, linked-list
It is the same as:
Node* curr_node = new Node{item, null, null};
In fact I would simplify to:
bool SortedList::insertFront(int item) {
m_head = new Node{item, nullptr, m_head};
if (m_head->next) {
m_head->next->prev = m_head;
}
return true;
}
Lets simplify:
bool SortedList::insertBack(Node* tail_node, int item) {
if (tail_node->next != nullptr) {
return false;
}
tail_node->next = new Node{item, tail_node, nullptr};
return true;
}
bool SortedList::insertBefore(Node* curr_node, int item) {
// Don't you already do this check before calling insertBefore()?
// Looks like you are doing the same check in two places.
// I would remove it from one place.
if (curr_node->prev != nullptr) {
.....
}
else {
insertFront(item);
}
return true;
}
void SortedList::copyListNodes(const SortedList& otherList) {
Node* other_list_curr = otherList.m_head;
// copy first item new node to head
if (other_list_curr != nullptr) {
Node* new_node = new Node;
new_node->data = other_list_curr->data;
new_node->next = nullptr;
new_node->prev = m_head;
++m_numItems;
m_head = new_node;
other_list_curr = other_list_curr->next;
}
// copy remaining items to new nodes
Node* curr_node = m_head;
while (other_list_curr != nullptr) {
Node* new_node = new Node;
new_node->data = other_list_curr->data;
curr_node->next = new_node;
new_node->prev = curr_node;
curr_node = curr_node->next;
other_list_curr = other_list_curr->next;
++m_numItems;
}
}
Seems very convoluted. I would change it. So it returns a new list.
Node* SortedList::copyNode(Node* result, Node*& end, Node const* src) {
Node* next = new Node{src->data, end, nullptr);
if (end) {
end->next = next;
}
end = next;
return result == nullptr ? next : result;
} | {
"domain": "codereview.stackexchange",
"id": 44069,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list",
"url": null
} |
c++, linked-list
Node* SortedList::copyList(Node const* other) {
Node* result = nullptr;
Node* endOfList = nullptr;
while (other != nullptr) {
result = copyNode(result, endOfList, other);
other = other->next;
}
return result;
}
SortedList operator+(const SortedList& lhs, const SortedList& rhs) {
......
// THIS CAN NEVER BE TRUE.
// IT IS ILLEGAL TO CONVERT A nullptr INTO A REFERENCE.
if (&lhs == nullptr && &rhs == nullptr) {
return mergedList;
}
The rest of this function is far too complicated.
// Non optimal but simpleway.
SortedList operator+(const SortedList& lhs, const SortedList& rhs) {
SortedList mergedList(lhs);
for (Node const* loop = rhs.m_head; loop; loop=loop->next) {
mergedList.insert(loop->data);
}
}
// More optimal way.
SortedList operator+(const SortedList& lhs, const SortedList& rhs) {
Node const* lhsData = lhs.m_head;
Node const& rhsData = rhs.m_head;
Node* result = nullptr;
Node* endOfList = nullptr;
// While there are values in both lists
// Then we have to choose which to copy next.
while (lhsData != nullptr && rhsData != nullptr) {
Node next;
if (lhsData->data < rhsData->data) {
next = lhsData;
lhsData = lhsData->next;
}
else {
next = rhsData;
rhsData = rhsData->next;
}
// See above
result = copyNode(result, endOfList, next);
}
// One of the lists is now empty.
// SO only one of these loops will be used.
// We just need to loop through the remaining items
// and add them to the list.
for (;lhsData; lhsData = lhsData->next) {
result = copyNode(result, endOfList, lhsData);
}
for (;rhsData; rhsData = rhsData->next) {
result = copyNode(result, endOfList, rhsData);
}
return result;
} | {
"domain": "codereview.stackexchange",
"id": 44069,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list",
"url": null
} |
c++, algorithm, primes
Title: Euler's totient function for large numbers
Question: I made this algorithm to compute Euler's totient function for large numbers. A sieve is used.
#include <iostream>
#include <cstdint>
#include <vector>
typedef uint64_t integer;
integer euler_totient(integer n) {
integer L1_CACHE = 32768;
integer phi_n=0;
if (n>0) {
phi_n++;
integer segment_size=std::min(L1_CACHE,n);
std::vector<char> SIEVE(segment_size, true);
std::vector<integer> PRIME;
integer len_PRIME=0;
for (integer p=2; p<segment_size; p++)
if (SIEVE[p]==true)
if (n%p==0) {
for (integer m=p; m<segment_size; m+=p)
SIEVE[m]=false;
PRIME.push_back(p);
len_PRIME++;
}
else
phi_n++;
if (n>segment_size) {
integer m,p;
for (integer segment_low=segment_size; segment_low<n; segment_low+=segment_size) {
std::fill(SIEVE.begin(), SIEVE.end(), true);
for (integer i=0; i<len_PRIME; i++) {
m=(PRIME[i]-segment_low%PRIME[i])%PRIME[i];
for(;m<segment_size;m+=PRIME[i])
SIEVE[m]=false;
}
for (integer i=0; i<segment_size && segment_low+i<n; i++)
if (SIEVE[i]==true){
p=segment_low+i;
if (n%p==0) {
for (m=i; m<segment_size; m+=p)
SIEVE[m]=false;
PRIME.push_back(p);
len_PRIME++;
}
else
phi_n++;
}
}
}
}
return phi_n;
}
int main() {
std::cout << euler_totient(1000000) << std::endl;
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 44070,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, primes",
"url": null
} |
c++, algorithm, primes
int main() {
std::cout << euler_totient(1000000) << std::endl;
return 0;
}
Is it a good solution?
Can it be improved in any way?
Answer:
Is it a good solution? | {
"domain": "codereview.stackexchange",
"id": 44070,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, primes",
"url": null
} |
c++, algorithm, primes
Answer:
Is it a good solution?
Unfortunately I'll have to go with "not really".
This approach can be summarized as taking the definition of the totient of n as "the number of positive integers up to n that are relatively prime to n" literally, turning it into an algorithm.
This approach does not take advantage of any factors that are found. What I mean by that is, for example, if n = 2^k, then an algorithm based on factorization will find the totient almost immediately, while this algorithm will still have to iterate up to n. Or, imagine you discover that n is divisible by 1009 (and only once, meaning that n is not divisible by 1009² - you can easily deal with prime powers, but I didn't want to do it for the example), then you would know that totient(n) = 1008 * totient(n / 1009). If you were going to iterate up to n (which is not necessary) then this would effectively cut the remaining amount of iteration by a factor of 1009.
Also not finding factors is useful: when n is a prime, that is a fact that can be discovered more quickly than iterating all the way up to n (doing it naively, discovering that n is prime would happen after sqrt(n) steps, significantly better than n), and then the totient is just n - 1.
The simplest factorization-based approach, which just uses trial division, nothing fancy, would only need to count up to sqrt(n), and only in the worst case, when n is prime. Otherwise, factors are found along the way and every time one of them is found, the bound up to which the trial division needs to go is significantly reduced.
To show how big the difference could be, let's take the totient of 2364968846596223957 (I got this by drawing a random 64bit number). Using a simple trial-division based computation that I quickly worked out, nothing special, my PC took 80 milliseconds to compute the result 2360645320368442380 (which is correct, verified with WolframAlpha). Counting up to that number would take years. | {
"domain": "codereview.stackexchange",
"id": 44070,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, primes",
"url": null
} |
c++, algorithm, primes
In terms of coding style, I have a couple of remarks as well. There is very little white space, such as around operators and also sometimes between the different "parts" in a for statement. Styles differ, but I don't find this nice to read. It's very visually dense. Also, there is a repeated use of if or for with non-trivial contents, yet without braces. That is commonly recommended against in style guides (sometimes recommendations even go so far as to always demand braces, even if the contents are trivial) and personally I also recommend against it. I also find typedef uint64_t integer questionable, what do you gain from this? | {
"domain": "codereview.stackexchange",
"id": 44070,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, primes",
"url": null
} |
c++, multithreading, c++14, thread-safety
Title: Force acquiring R/W lock
Question: I am trying to build an abstraction that forces lock acquisition before data can be accessed.
This seems to work, but please tell me if what I am doing horribly wrong, and what I could improve.
I am using C++14 hence shared_timed_mutex
#include <mutex>
#include <shared_mutex>
template <class T>
class rw_locked
{
public:
class write_access
{
public:
write_access(const write_access &) = delete;
write_access &operator=(write_access &) = delete;
write_access &operator=(const write_access &) = delete;
write_access(write_access &&) = delete;
write_access &operator=(write_access &&) = delete;
write_access(rw_locked &t_locked)
: m_lock(t_locked.m_mtx, std::defer_lock), m_hook(&t_locked.m_content){};
T *operator->() { return m_hook; }
T *get() { return m_hook; }
private:
T *m_hook;
const std::shared_lock<std::shared_timed_mutex> m_lock;
};
class read_access
{
public:
read_access(const read_access &) = delete;
read_access &operator=(read_access &) = delete;
read_access &operator=(const read_access &) = delete;
read_access(read_access &&) = delete;
read_access &operator=(read_access &&) = delete;
read_access(rw_locked &t_locked)
: m_lock(t_locked.m_mtx, std::defer_lock), m_hook(&t_locked.m_content){};
const T *operator->() { return m_hook; }
const T *get() { return m_hook; }
private:
const T *m_hook;
const std::unique_lock<std::shared_timed_mutex> m_lock;
};
template <typename... content_args>
explicit rw_locked(content_args &&...t_content_args)
: m_mtx(), m_content(std::forward<content_args>(t_content_args)...)
{
}
private:
std::shared_timed_mutex m_mtx;
T m_content;
};
It's meant to be used like this:
#include <iostream>
#include <string>
#include <vector>
//#include "rw_locked.h"
using locked_strings = rw_locked<std::vector<std::string>>;
int main()
{
locked_strings strs; | {
"domain": "codereview.stackexchange",
"id": 44071,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, c++14, thread-safety",
"url": null
} |
c++, multithreading, c++14, thread-safety
using locked_strings = rw_locked<std::vector<std::string>>;
int main()
{
locked_strings strs;
// these would be called from threads
{
locked_strings::write_access w_strs(strs);
w_strs->push_back("1");
w_strs->push_back("2");
w_strs->push_back("3");
}
{
locked_strings::read_access r_strs(strs);
for (auto &it : *r_strs.get())
{
std::cout << it << "\n";
}
}
return 0;
}
Thank you very much for your time!
Answer: The locks are never taken
By passing std::defer_lock when constructing m_lock, the mutexes will never be locked. Remove that parameter.
Swap std::shared_lock and std::unique_lock
Normally you want to allow multiple reads to share access to the data, but you only want to allow one unique writer at a time. So write_access should use a std::unique_lock, and read_access should use std::shared_lock.
Your example program is a very bad example; it never takes more than one lock at a time, so none of the properties you care about are tested. It shouldn't be difficult to add a multi-threaded example, see the example from std::shared_lock for how short it can be.
Add a test suite
The above issues could be found if you would add a test suite to your library that tests all the properties you want your classes to have.
Enable compiler warnings and fix them
GCC warns that m_lock and m_hook will be initialized in a different order than you specified in the constructors. Make sure you enable compiler warnings and fix all of them.
Add out-of-class helpers
Normally I am in favour of nesting classes where that makes sense. And in a way, it does so here as well. However, the problem is that now you have to remember the exact type. Having to write the following is very annoying:
rw_locked<std::vector<std::string>>::write_access w_strs(strs); | {
"domain": "codereview.stackexchange",
"id": 44071,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, c++14, thread-safety",
"url": null
} |
c++, multithreading, c++14, thread-safety
Which is why you used a using statement to reduce the amount you had to type. Consider how std::unique_lock is not a member of any mutex class. Wouldn't it be nice if you would have something similar, so you could write this instead?
write_access w_strs(strs);
I see two solutions. The first would be to move write_access and read_access out of rw_locked. They would become templates of their own of course, and it would require making them friends of rw_locked. It is possible, but a bit involved. Alternatively, keep the class hierarchy as it is, but add new helper classes that help deducing the right types. Consider:
template<typename RwLocked>
class write_access: public RwLocked::write_access
{
public:
write_access(RwLocked &t_locked): RwLocked::write_access(t_locked) {}
};
Make it more like the STL's lock types
To make it even better, consider adopting the same naming scheme as the STL, and support all the things the STL does. For example, instead of read_access and write_access, call it shared_access and unique_access.
Furthermore, when creating a shared_access object for example, consider making it support everything that std::shared_lock does: support std::defer_lock_t and related tags, and since you are using a std::shared_timed_mutex, you want to support timeout_duration and timeout_time parameters as well. You could also support all the member function. In fact, you could consider just inheriting from std::shared_lock:
template<class T>
class rw_locked
{
public:
using shared_lock_type = std::shared_lock<std::shared_timed_mutex>;
class shared_access: public shared_lock_type
{
public:
template<typename... lock_args>
shared_access(rw_locked &t_locked, lock_args &&...t_lock_args)
: shared_lock_type(t_locked.m_mtx,
std::forwward<lock_args>(t_lock_args)...)
, m_hook(&t_locked.m_content) {}
T *operator->() { return m_hook; }
T *get() { return m_hook; } | {
"domain": "codereview.stackexchange",
"id": 44071,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, c++14, thread-safety",
"url": null
} |
c++, multithreading, c++14, thread-safety
T *operator->() { return m_hook; }
T *get() { return m_hook; }
private:
T* m_hook;
}
...
};
But you could also argue that you should not do this; considering that the whole point is that access to the data is only possible if the lock is guaranteed to be held, and that the above would allow you to pass std::defer_lock_t or a duration that is too short while the lock was already taken by another thread, and the mutex might not be locked but you can still call get(). You could make get() and operator->() check that owns_lock() == true and throw some exception otherwise, but that adds a little bit of overhead. If you don't want that, you can still inherit from std::shared_lock like above, but then just never pass a tag, duration or time point, and then just use a std::shared_mutex instead of a std::shared_timed_mutex. | {
"domain": "codereview.stackexchange",
"id": 44071,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, c++14, thread-safety",
"url": null
} |
python, event-handling
Title: Count how many times left mouse button is clicked
Question: The code snippet works perfectly fine, but someone said, and I quote, "this is some of the weirdest code i've seen", so I'd just like any advice for it. It's supposed to count the amount of times I click my left mouse button.
Is there anyway to make it more concise?
from pynput.mouse import Listener
import logging
logging.basicConfig(filename='mouseLog.txt', level=logging.DEBUG, format = '%(asctime)s: %(message)s')
mouseCount = 0
#def on_move(x, y):
#print('Mouse moved to ({0}, {1})' .format(x, y))
def on_click(x, y, button, pressed):
global mouseCount
if pressed:
logging.info('Mouse clicked at ({0}, {1}) with {2}' .format(x, y, button))
while pressed == True:
mouseCount += 1
logging.info(f'mouseClick is at {mouseCount}')
break
#def on_scroll(x, y, dx, dy):
#print('Mouse scrolled at ({0}, {1}} ({2}, {3})' .format(x, y, dx, dy))
with Listener(on_click = on_click) as listener:
listener.join()
Answer: Probably the worst part of this code is:
while pressed == True:
# statements
break
The break at the end of the loop will stop the loop from executing a second time, meaning # statements will execute exactly once if and only if pressed == True. In other words, this could be rewritten as:
if pressed == True:
mouseCount += 1
logging.info(f'mouseClick is at {mouseCount}')
Assuming pressed will only ever take on the values True or False (the pynput documentation isn’t explicit, but doesn’t suggest otherwise), the == True is superfluous, and we can further simply this to:
if pressed:
mouseCount += 1
logging.info(f'mouseClick is at {mouseCount}') | {
"domain": "codereview.stackexchange",
"id": 44072,
"lm_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, event-handling",
"url": null
} |
python, event-handling
Now, immediately before this is another if pressed: statement, and pressed cannot change values between the two, so they can be combined into one if statement:
if pressed:
logging.info('Mouse clicked at ({0}, {1}) with {2}' .format(x, y, button))
mouseCount += 1
logging.info(f'mouseClick is at {mouseCount}')
f-strings
You’re using an f'string' in the mouseClick log statement, so why the explicit .format(…) call:
logging.info('Mouse clicked at ({0}, {1}) with {2}' .format(x, y, button))
Why not …
logging.info(f'Mouse clicked at ({x}, {y}) with {button}')
… and save 17 characters?
Logging
Having said that, the logging module was written with efficiency in mind. The logging level can be set to (say) logging.WARNING and then .info(…) statements will not generate any output. Unfortunately, time has been wasted interpolating the values into the format string.
A better practise is to pass the values to the logger, and let the logger do the formatting if that logger has the given log level enabled.
logging.info('Mouse clicked at (%d, %d) with %s', x, y, button) | {
"domain": "codereview.stackexchange",
"id": 44072,
"lm_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, event-handling",
"url": null
} |
python, event-handling
Efficiency likely doesn’t matter in this mouse button click counter, so the readability improvement of the f-string approach is probably more important here. Just be aware that logging can be made more efficient.
PEP 8
The Style Guide for Python Coding has style recommendations that Python code should follow to improve readability by the widest audience.
Naming
bumpyWords are not recommended anywhere in Python. snake_case should be used for function, member, and variable names. (CapWords are for class names, and CAP_WORDS are for constants)
mouseCount violates this naming. It is a variable, and should be named mouse_count. While we’re renaming it, the computer probably only has one mouse, and perhaps this should be named mouse_press_count or press_count or click_count.
Assignment -vs- Keywords
= is sometimes an operator, and should be surrounded with white space:
mouseCount = 0
In function calls, it is used as a keyword argument identifier, and no white space should be used, eg) filename='mouseLog.txt' and level=logging.DEBUG.
You violate the latter with format = '%(asctime)s: %(message)s' and on_click = on_click. There should be no space on either side of the =.
Code organization
Source code should be grouped into related chunks. import statements first, global constants and variables, then functions, then mainline code. logging.basicConfig(…) is a statement executed before functions have been defined. It is out of order.
Often, mainline code is placed in a main-guard, or even a main() function called from the main-guard.
Improved code
from pynput.mouse import Listener
import logging
LOG = logging.getLogger(__name__)
click_count = 0
def on_click(x, y, button, pressed):
global click_count
if pressed:
LOG.info(f'Mouse clicked at ({x}, {y}) with {button}')
click_count += 1
LOG.info(f'mouseClick is at {click_count}')
def main(): | {
"domain": "codereview.stackexchange",
"id": 44072,
"lm_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, event-handling",
"url": null
} |
python, event-handling
def main():
logging.basicConfig(filename='mouseLog.txt', level=logging.DEBUG,
format='%(asctime)s: %(message)s')
with Listener(on_click=on_click) as listener:
listener.join()
if __name__ == '__main__':
main()
Other improvements
Type-hints and doc-strings should be added, to improve readability. You should learn these.
Modifying global variables using the global statement is frowned upon. This could be replaced with a click counter class object, where the click_count was a member of the object. So, you should learn to use classes also. | {
"domain": "codereview.stackexchange",
"id": 44072,
"lm_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, event-handling",
"url": null
} |
c++, c++17, template-meta-programming, variadic
Title: Template to unpack arguments to a std::function
Question: I am writing some C++ code to interact with an external scripting language. I want to be able to register arbitrary C++ callable code as functions to be called from the script.
The scripting library offers an API to register function pointers with signature
std::string callback( std::vector<std::string> const& args);
ie any function called from the script is given an array of strings representing the functions input args and expects a String as a result.
Up to now I would create a wrapper function for each c++ function I want to expose to the script.
e.g. for function
int add_two_numbers(int a, int b){ return a + b; }
//I create and register
string add_two_numbers_wrapper( std::vector<std::string> const& args)
{
auto arg0 = std::stoi( args[0] );
auto arg1 = std::stoi( args[1] );
auto result = add_two_numbers( arg0, arg1 );
return std::to_string(result);
}
Not wanting to write the wrapper by hand each time I've tried to create some templates to manage the boilerplate. I had some success using a number of template wrappers that are written for each set of different argument counts but I want to support 'any' number of args in future without creating a new template.
This is my attempt at a one-size-fits-all function wrapper template.
Are there anyways of simplifying further?
I'm not too bothered about performance at this juncture and the priority is ease of use.
#include <string_view>
#include <string>
#include <functional>
#include <vector>
#include <tuple>
#include <type_traits>
///Helper Template to convert to and from the script's value types.
//should support functions:
// from_arg - convert string to expected c++ argument type
// to_result - convert result back to script type.
template < typename TType >
struct convert_type;
//specialisation for int
template <> struct convert_type <int >
{
static int from_arg (std::string const &arg)
{
return std::stoi (arg);
} | {
"domain": "codereview.stackexchange",
"id": 44073,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, template-meta-programming, variadic",
"url": null
} |
c++, c++17, template-meta-programming, variadic
static std::string to_result (int r)
{
return std::to_string (r);
}
};
template <> struct convert_type<void>
{
static std::string to_result()
{
return "";
}
};
//Wrapper template for adapting c++ function to function that is callable from script
template < typename > class fun_wrapper;
template < typename R, typename ... Args >
class fun_wrapper < R (Args ...) >
{
public:
using FunctionType = std::function < R (Args ...) >;
using ResultType = R;
using ArgTypes = std::tuple < Args ... >;
static constexpr int m_arg_count = sizeof ... (Args);
//constructor
fun_wrapper (FunctionType f)
:m_fun {f}
{
}
std::string operator ()( std::vector<std::string> const& inputs)
{
if constexpr( std::is_void_v<ResultType> ) //wrapped function returns void
{
if constexpr ( m_arg_count == 0) //wrapped function doesn't need args unpacking
{
m_fun();
}
else
{
unpack_args<0>( inputs );
}
std::string result = "";
return result;
}
else
{
ResultType r1;
if constexpr ( m_arg_count == 0) //wrapped function doesn't need args unpacking
{
r1 = m_fun();
}
else
{
r1 = make_call<0>(args);
}
std::string result = convert_type< ResultType >::to_result (r1);
return result;
}
}
//Helper template to unpack and convert each arg in inputs into a parameter pack that
//can then be passed into the function call
template < int index, typename... TArgs >
ResultType unpack_args( std::vector<std::string> const& inputs, TArgs... targs)
{
using CurrentArgType = std::tuple_element_t< index, ArgTypes >; | {
"domain": "codereview.stackexchange",
"id": 44073,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, template-meta-programming, variadic",
"url": null
} |
c++, c++17, template-meta-programming, variadic
if constexpr (index + 1 == m_arg_count) //all args unpacked - call function
{
return m_fun( targs..., convert_type< CurrentArgType >::from_arg( inputs[index]) );
}
else
{
//unpack next argument in list and keep going
return make_call< index + 1 >(args, targs..., convert_type< CurrentArgType >::from_arg( inputs[index]));
}
}
private:
std::function< R(Args...) > m_fun;
};
//Example usage.
int add_numbers(int in1, int in2)
{
return in1 + in2;
}
int main ()
{
fun_wrapper< int(int, int) > add_numbers_wrapper(add_numbers);
std::vector<std::string> args = {"18", "24"};
cout << add_numbers_wrapper( args ) << endl; //outputs "42"
return 0;
}
Answer: Your code has the right approach, but can indeed be simplified a lot. Let's start with string conversion. Consider that you want to use std::to_string() in most cases, but want to add some overloads for types it does not support (like void). Instead of creating a class template, consider just adding overloads. Since you are not allowed to overload std::to_string() itself, use this trick:
using std::to_string; // pull in all overloads from std:: into the global namespace
std::string to_string(void) // your own private overload
{
return {};
}
You also want a from_string(), but instead of a class template it can be a function template:
template<typename T>
T from_string(std::string const &);
template<>
int from_string(std::string const &arg)
{
return std::stoi(arg);
}
Apart from saving some lines of code when adding support for new to/from string conversion, it also makes usage shorter, compare:
convert_type<CurrentArgType>::from_arg(inputs[index])
Versus:
from_string<CurrentArgType>(inputs[index]) | {
"domain": "codereview.stackexchange",
"id": 44073,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, template-meta-programming, variadic",
"url": null
} |
c++, c++17, template-meta-programming, variadic
Versus:
from_string<CurrentArgType>(inputs[index])
A lot of code is spent on unpacking and converting the arguments one by one in a recursive manner. But this can also be improved.
As Soupy mentioned, you can make use of std::index_sequence, and combined with simultaneous parameter pack expansion and the simplifications mentioned above, this can result in some very compact code. Consider:
template<std::size_t... I>
std::string invoke_helper(std::vector<std::string> const& inputs,
std::index_sequence<I...>)
{
return to_string(m_fun(from_string<Args>(inputs.at(I))...));
}
std::string operator()(std::vector<std::string> const& inputs)
{
return invoke_helper(inputs, std::index_sequence_for<Args...>{});
}
You might want to check that inputs.size() == m_arg_count first. | {
"domain": "codereview.stackexchange",
"id": 44073,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, template-meta-programming, variadic",
"url": null
} |
c++, concurrency
Title: Sender/Receiver threads using std::unique_lock and std::condition_variable
Question: The code below is a sender/receiver setup in C++ where the sender is in one thread, the receiver is in another, and the data being sent/received is "shared" (global). The code uses the <thread> header, std::unique_lock, and std::condition_variable.
I would love a critique on everything below ConditionVariable.notify_one(); in the Receiver function and everything below ConditionVariable.notify_one(); in the Sender function.
Regarding those final line(s) of Receiver and Sender: I'm having some doubts around the effects of blocking that happens upon lock and wait. Also, at the bottom of each of the two functions, I'm not entirely sure about the need for lock... since, as soon as the loop iteration ends, the destructor of unique_lock will immediately do an unlock.
#include <mutex>
#include <thread>
#include <string>
// Declaration-only for brevity. Assume this returns the data that `Sender` will send.
std::string GenerateMyString();
// Global variables for threads (we'll have two threads, one for `Sender` and
// one for `Receiver`
std::mutex Mutex;
std::string DataGeneratedWithinSender;
bool Free = false;
std::condition_variable ConditionVariable;
// `Sender` and `Receiver` functions will each run in their own thread.
void Sender() {
for (int i = 0; i < 5; ++i) {
std::unique_lock<std::mutex> unq_lck{Mutex};
DataGeneratedWithinSender = GenerateMyString();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
Free = true;
unq_lck.unlock();
ConditionVariable.notify_one();
unq_lck.lock();
ConditionVariable.wait(unq_lck, []() { return !Free; });
}
} | {
"domain": "codereview.stackexchange",
"id": 44074,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, concurrency",
"url": null
} |
c++, concurrency
void Receiver() {
std::string data;
for (int i = 0; i < 5; ++i) {
std::unique_lock<std::mutex> unq_lck{Mutex};
ConditionVariable.wait(unq_lck, []() { return Free; });
data = DataGeneratedWithinSender;
Free = false;
unq_lck.unlock();
ConditionVariable.notify_one();
// *** DO SOMETHING WITH `data` HERE ***
// This `Receiver` function is now ready for the next piece of data to be sent to it.
unq_lck.lock();
}
}
int main() {
std::thread t_1(Receiver);
std::thread t_2(Sender);
t_1.join();
t_2.join();
return 0;
}
Answer: Avoid manual locking and unlocking
It's great that you use std::unique_lock, and using that to call lock() and unlock() is much safer than if you were to lock and unlock a std::mutex directly. However, it can be avoided by using scopes to cause unlocking to happen at the right point. Furthermore, if possible try to reduce the number of times you need to unlock and relock a std::unique_lock. For example, the sender could be rewritten like so:
void Sender() {
for (int i = 0; i < 5; ++i) {
{
std::unique_lock<std::mutex> unq_lck{Mutex};
ConditionVariable.wait(unq_lck, []() { return !Free; });
DataGeneratedWithinSender = GenerateMyString();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
Free = true;
}
ConditionVariable.notify_one();
}
}
Generate the data without holding the lock
You call GenerateMyString() while the lock is held. But what if generating the string takes a long time? Just like the receiver copies DataGeneratedWithinSender into data, so it can then unlock and process the data without blocking the sender, you can do the same in the sender itself:
void Sender() {
for (int i = 0; i < 5; ++i) {
auto data = GenerateMyString();
std::this_thread::sleep_for(std::chrono::milliseconds(100)); | {
"domain": "codereview.stackexchange",
"id": 44074,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, concurrency",
"url": null
} |
c++, concurrency
{
std::unique_lock<std::mutex> unq_lck{Mutex};
ConditionVariable.wait(unq_lck, []() { return !Free; });
DataGeneratedWithinSender = data;
Free = true;
}
ConditionVariable.notify_one();
}
}
std::move() data instead of copying it
You are copying the strings around, but this takes some time and might involve allocating memory. You can avoid that by invoking the move assignment operator of std::string using std::move():
DataGeneratedWithinSender = std::move(data);
...
data = std::move(DataGeneratedWithinSender);
Here is sender and receiver after incorporating everything from above:
void Sender() {
for (int i = 0; i < 5; ++i) {
auto data = GenerateMyString();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
{
std::unique_lock<std::mutex> unq_lck{Mutex};
ConditionVariable.wait(unq_lck, []() { return !Free; });
DataGeneratedWithinSender = std::move(data);
Free = true;
}
ConditionVariable.notify_one();
}
}
void Receiver() {
std::string data;
for (int i = 0; i < 5; ++i) {
{
std::unique_lock<std::mutex> unq_lck{Mutex};
ConditionVariable.wait(unq_lck, []() { return Free; });
data = std::move(DataGeneratedWithinSender);
Free = false;
}
ConditionVariable.notify_one();
// Presumably receiver does something with `data` here.
}
} | {
"domain": "codereview.stackexchange",
"id": 44074,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, concurrency",
"url": null
} |
c, socket, signal-handling
Title: A deamon for sending poem to clients based on KISS
Question: My code is about sending random poem from /etc/poem.conf to client using TCP sockets.
In this implementation my daemon have restart mechanism using SIGHUP signal and DEBUG mechanism using defining DEBUG macro during compilation.
My goals:
Simpler code
Less code
Cleaner code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <syslog.h>
#include <setjmp.h>
#include <time.h>
#include <errno.h>
#include <err.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#ifndef DEBUG
#define perror(msg) syslog(LOG_ERR, "%s: %s", msg, strerror(errno))
#define err(status, msg) perror(msg), _exit(status)
#endif
sigjmp_buf jmp;
void
sighub (__attribute__ ((unused)) int signo)
{
siglongjmp (jmp, 1);
}
int
main()
{
int sfd, cfd;
char poem[BUFSIZ];
struct sockaddr_in sa;
FILE *fpoem = NULL;
#ifndef DEBUG
if (daemon (0, 0))
err (1, "daemon");
#endif
if (signal (SIGHUP, sighub))
err (1, "signal");
if ((sfd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
err (1, "socket");
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = htonl (INADDR_ANY);
sa.sin_port = htons (1073);
if (bind (sfd, (struct sockaddr *)&sa, sizeof (sa)))
err (1, "bind");
if (listen (sfd, 10))
err (1, "listen");
if (sigsetjmp (jmp, 1))
fclose (fpoem), close (cfd);
if (! (fpoem = fopen ("/etc/poem.conf", "r")))
err (1, "/etc/poem.conf");
for (;;) {
if ((cfd = accept (sfd, NULL, NULL)) == -1)
perror ("accept");
srand (time (NULL) + rand());
fseek (fpoem, 0, SEEK_END);
fseek (fpoem, rand() % ftell (fpoem), SEEK_SET);
while (ftell (fpoem) > 0
&& fgetc (fpoem) != '\n')
fseek (fpoem, -2, SEEK_CUR); | {
"domain": "codereview.stackexchange",
"id": 44075,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, socket, signal-handling",
"url": null
} |
c, socket, signal-handling
fgets (poem, BUFSIZ, fpoem);
write (cfd, poem, strlen (poem));
close (cfd);
}
}
Answer: Make use of your operating system's facilities
A lot of the complexity in your code comes from wanting to call daemon() yourself, and then also wanting a way to run your code in the foreground. I strongly recommend that you just design your code as a foreground-running process, and then use whatever facilities your operating system provides for running it in the background if so desired.
Consider that most init systems allow you to start and manage a process running in the background, and will do a better job at this than you can from within your program. With systemd, you can create a .service file that will start your program automatically at boot, redirects all output to logfiles, can restart your program either manually or automatically when it crashes, synchronize with other services so it starts at the right time, and so on.
You can go further than that and even offload the TCP socket handling part to the init system. Again systemd has features for that, but even with the venerable SysV init system you have inetd.
Of course, you can go even further; if you consider coreutils to be part of the operating system, you can just replace your program with the command shuf -n1 /etc/poem.conf. This removes all code, so it perfectly fulfills the three goals you have.
Consider binding to an IPv6 socket
On many operating systems it is possible to create a single IPv6 socket that can listen on both IPv4 and IPv6. On some this happens automatically, on others you might have to set the IPV6_V6ONLY socket option:
int option = 0;
setsockopt(sfd, IPPROTO_IPV6, IPV6_V6ONLY, &option, sizeof option); | {
"domain": "codereview.stackexchange",
"id": 44075,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, socket, signal-handling",
"url": null
} |
c, socket, signal-handling
Unnecessary calls to fseek()
The first call to fseek() is only necessary once to get the length of the file, so it should be moved out of the for-loop. Also consider not scanning backwards for a newline, but scan forwards instead, this avoids the third call to fseek(). This also brings me to:
Efficiently getting to the start of a new line
If you scan forward for a newline, then you don't need to read character by character in a while-loop, you can just call fgets() to discard one partial line, and then the second call will get you a complete line.
Of course, you might have an issue when you first seek into the middle of the last line in the file. In that case, consider wrapping to the start of the file and returning the first line:
fseek(fpoem, 0, SEEK_END);
long size = ftell(fpoem);
for (;;) {
...
fseek(fpoem, rand() % size, SEEK_SET); // seek to random position
fgets(poem, BUFSIZ, fpoem); // discard partial line
fgets(poem, BUFSIZ, fpoem); // read full line
if (feof(fpoem)) {
fseek(fpoem, 0, SEEK_SET); // seek to start
fgets(poem, BUFSIZ, fpoem); // read first line
}
...
} | {
"domain": "codereview.stackexchange",
"id": 44075,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, socket, signal-handling",
"url": null
} |
c, socket, signal-handling
Of course, you could also just read the poem into an array of strings at the beginning of your program, this would avoid the overhead later on.
Missing error handling
You are checking for errors for most things, except when reading a random line and sending it to the peer. Consider that all calls to fseek(), fgetc(), fgets() and write() can fail, either because of a permanent error or because of something like EINTR.
Possibility of partial reads and writes
What if your poem contains a line equal to or longer than BUFSIZE? In that case, fgets() will still succeed, but read only the first BUFSIZ - 1 characters. Check if the last character in the string is a newline to verify if a whole line was read.
A call to write() might write less than you told it to. This is something you should handle by checking the return value, and in case of a partial write, retry sending the remaining part, and so on in a loop until everything has been sent or a permanent failure happens. Alternatively, consider using fdopen() to get a FILE * handle for the socket, so you can just call fputs() and not worry about these details.
Beware of corner cases
What if /etc/poem.conf exists but is empty? What if the last line doesn't contain a newline? What if an I/O error happens in the while-loop and? What if SIGHUP is sent right after sigsetjmp() but before you even opened fpoem (and cfd is still uninitialized)? Make sure you think about corner cases, and adress all of them. | {
"domain": "codereview.stackexchange",
"id": 44075,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, socket, signal-handling",
"url": null
} |
c++, collections, circular-list
Title: Simple C++ circular queue
Question: I wrote a simple C++20 circular queue.
https://github.com/torrentg/cqueue
Here is cqueue.hpp
#pragma once
#include <memory>
#include <utility>
#include <concepts>
#include <algorithm>
#include <stdexcept>
namespace gto {
/**
* @brief Circular queue.
* @details Iterators are invalidated by: push(), push_front(), emplace(), pop(), pop_back(), reset() and clear().
* @see https://en.wikipedia.org/wiki/Circular_buffer
* @see https://github.com/torrentg/cqueue
* @note This class is not thread-safe.
* @version 1.0.0
*/
template<std::semiregular T>
class cqueue {
public: // declarations | {
"domain": "codereview.stackexchange",
"id": 44076,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, collections, circular-list",
"url": null
} |
c++, collections, circular-list
//! cqueue iterator.
class iterator {
public:
using iterator_category = std::random_access_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = T *;
using reference = T &;
private:
cqueue<T> *queue = nullptr;
difference_type pos = 0;
private:
std::size_t cast(difference_type n) const { return (n < 0 ? queue->size() : static_cast<std::size_t>(n)); }
difference_type size() const { return static_cast<difference_type>(queue->size()); }
public:
explicit iterator(cqueue<T> *o, difference_type p = 0) : queue(o), pos(p < 0 ? -1 : (p < size() ? p : size())) {}
reference operator*() { return queue->operator[](cast(pos)); }
pointer operator->() { return &(queue->operator[](cast(pos))); }
reference operator[](difference_type rhs) const { return (queue->operator[](cast(pos + rhs))); }
bool operator==(const iterator &rhs) const { return (queue == rhs.queue && pos == rhs.pos); }
bool operator!=(const iterator &rhs) const { return (queue != rhs.queue || pos != rhs.pos); }
bool operator >(const iterator &rhs) const { return (queue == rhs.queue && pos > rhs.pos); }
bool operator <(const iterator &rhs) const { return (queue == rhs.queue && pos < rhs.pos); }
bool operator>=(const iterator &rhs) const { return (queue == rhs.queue && pos >= rhs.pos); }
bool operator<=(const iterator &rhs) const { return (queue == rhs.queue && pos <= rhs.pos); }
iterator& operator++() { pos = (pos + 1 < size() ? pos + 1 : size()); return *this; }
iterator& operator--() { pos = (pos < 0 ? -1 : pos -1); return *this; }
iterator operator++(int) { iterator tmp(queue, pos); operator++(); return tmp; }
iterator operator--(int) { iterator tmp(queue, pos); operator--(); return tmp; } | {
"domain": "codereview.stackexchange",
"id": 44076,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, collections, circular-list",
"url": null
} |
c++, collections, circular-list
iterator operator--(int) { iterator tmp(queue, pos); operator--(); return tmp; }
iterator& operator+=(difference_type rhs) { pos = (pos + rhs < size() ? pos + rhs : size()); return *this; }
iterator& operator-=(difference_type rhs) { pos = (pos - rhs < 0 ? -1 : pos - rhs); return *this; }
iterator operator+(difference_type rhs) const { return iterator(queue, pos + rhs); }
iterator operator-(difference_type rhs) const { return iterator(queue, pos - rhs); }
friend iterator operator+(difference_type lhs, const iterator &rhs) { return iterator(rhs.queue, lhs + rhs.pos); }
friend iterator operator-(difference_type lhs, const iterator &rhs) { return iterator(rhs.queue, lhs - rhs.pos); }
difference_type operator-(const iterator &rhs) const { return (pos - rhs.pos); }
}; | {
"domain": "codereview.stackexchange",
"id": 44076,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, collections, circular-list",
"url": null
} |
c++, collections, circular-list
//! cqueue const iterator.
class const_iterator {
public:
using iterator_category = std::random_access_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = const T;
using pointer = const T *;
using reference = const T &;
private:
const cqueue<T> *queue = nullptr;
difference_type pos = 0;
private:
std::size_t cast(difference_type n) const { return (n < 0 ? queue->size() : static_cast<std::size_t>(n)); }
difference_type size() const { return static_cast<difference_type>(queue->size()); }
public:
explicit const_iterator(const cqueue<T> *o, difference_type p = 0) : queue(o), pos(p < 0 ? -1 : (p < size() ? p : size())) {}
reference operator*() { return queue->operator[](cast(pos)); }
pointer operator->() { return &(queue->operator[](cast(pos))); }
reference operator[](difference_type rhs) const { return (queue->operator[](cast(pos + rhs))); }
bool operator==(const const_iterator &rhs) const { return (queue == rhs.queue && pos == rhs.pos); }
bool operator!=(const const_iterator &rhs) const { return (queue != rhs.queue || pos != rhs.pos); }
bool operator >(const const_iterator &rhs) const { return (queue == rhs.queue && pos > rhs.pos); }
bool operator <(const const_iterator &rhs) const { return (queue == rhs.queue && pos < rhs.pos); }
bool operator>=(const const_iterator &rhs) const { return (queue == rhs.queue && pos >= rhs.pos); }
bool operator<=(const const_iterator &rhs) const { return (queue == rhs.queue && pos <= rhs.pos); }
const_iterator& operator++() { pos = (pos + 1 < size() ? pos + 1 : size()); return *this; }
const_iterator& operator--() { pos = (pos < 0 ? -1 : pos -1); return *this; }
const_iterator operator++(int) { const_iterator tmp(queue, pos); operator++(); return tmp; } | {
"domain": "codereview.stackexchange",
"id": 44076,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, collections, circular-list",
"url": null
} |
c++, collections, circular-list
const_iterator operator--(int) { const_iterator tmp(queue, pos); operator--(); return tmp; }
const_iterator& operator+=(difference_type rhs) { pos = (pos + rhs < size() ? pos + rhs : size()); return *this; }
const_iterator& operator-=(difference_type rhs) { pos = (pos - rhs < 0 ? -1 : pos - rhs); return *this; }
const_iterator operator+(difference_type rhs) const { return const_iterator(queue, pos + rhs); }
const_iterator operator-(difference_type rhs) const { return const_iterator(queue, pos - rhs); }
friend const_iterator operator+(difference_type lhs, const const_iterator &rhs) { return const_iterator(rhs.queue, lhs + rhs.pos); }
friend const_iterator operator-(difference_type lhs, const const_iterator &rhs) { return const_iterator(rhs.queue, lhs - rhs.pos); }
difference_type operator-(const const_iterator &rhs) const { return (pos - rhs.pos); }
}; | {
"domain": "codereview.stackexchange",
"id": 44076,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, collections, circular-list",
"url": null
} |
c++, collections, circular-list
private: // static members
//! Capacity increase factor.
static constexpr std::size_t GROWTH_FACTOR = 2;
//! Default initial capacity (power of 2).
static constexpr std::size_t DEFAULT_RESERVED = 8;
//! Max capacity (user-defined power of 2).
static constexpr std::size_t MAX_CAPACITY = 67'108'864;
private: // members
//! Buffer.
std::unique_ptr<T[]> mData;
//! Buffer size.
std::size_t mReserved = 0;
//! Maximum number of elements (always > 0).
std::size_t mCapacity = 0;
//! Index representing first entry (0 <= mFront < mReserved).
std::size_t mFront = 0;
//! Number of entries in the queue (empty = 0, full = mReserved).
std::size_t mLength = 0;
private: // methods
//! Convert from pos to index (throw exception if out-of-bounds).
std::size_t getCheckedIndex(std::size_t pos) const noexcept(false);
//! Convert from pos to index.
std::size_t getUncheckedIndex(std::size_t pos) const noexcept;
//! Compute memory size to reserve.
std::size_t getNewMemoryLength(std::size_t n) const;
//! Ensure buffer size.
void reserve(std::size_t n);
public: // static methods
//! Maximum capacity the container is able to hold.
static std::size_t max_capacity() noexcept { return MAX_CAPACITY; }
public: // methods
//! Constructor (0 means unlimited).
cqueue(std::size_t capacity = 0);
//! Copy constructor.
cqueue(const cqueue &other);
//! Move constructor.
cqueue(cqueue &&other) noexcept { this->swap(other); }
//! Destructor.
~cqueue() = default;
//! Copy assignment.
cqueue & operator=(const cqueue &other);
//! Move assignment.
cqueue & operator=(cqueue &&other) { this->swap(other); return *this; } | {
"domain": "codereview.stackexchange",
"id": 44076,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, collections, circular-list",
"url": null
} |
c++, collections, circular-list
//! Return queue capacity.
std::size_t capacity() const { return (mCapacity == MAX_CAPACITY ? 0 : mCapacity); }
//! Return the number of items.
std::size_t size() const { return mLength; }
//! Current reserved size (numbers of items).
std::size_t reserved() const { return mReserved; }
//! Check if there are items in the queue.
bool empty() const { return (mLength == 0); }
//! Return the first element.
const T & front() const { return operator[](0); }
//! Return the first element.
T & front() { return operator[](0); }
//! Return the last element.
const T & back() const { return operator[](mLength-1); }
//! Return the last element.
T & back() { return operator[](mLength-1); }
//! Insert an element at the end.
void push(const T &val);
//! Insert an element at the end.
void push(T &&val);
//! Insert an element at the front.
void push_front(const T &val);
//! Insert an element at the front.
void push_front(T &&val);
//! Construct and insert an element at the end.
template <class... Args>
void emplace(Args&&... args);
//! Remove the front element.
bool pop();
//! Remove the back element.
bool pop_back();
//! Returns a reference to the element at position n.
T & operator[](std::size_t n) { return mData[getCheckedIndex(n)]; }
//! Returns a const reference to the element at position n.
const T & operator[](std::size_t n) const { return mData[getCheckedIndex(n)]; } | {
"domain": "codereview.stackexchange",
"id": 44076,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, collections, circular-list",
"url": null
} |
c++, collections, circular-list
//! Returns an iterator to the first element.
iterator begin() noexcept { return iterator(this, 0); }
//! Returns an iterator to the element following the last element.
iterator end() noexcept { return iterator(this, static_cast<std::ptrdiff_t>(size())); }
//! Returns an iterator to the first element.
const_iterator begin() const noexcept { return const_iterator(this, 0); }
//! Returns an iterator to the element following the last element.
const_iterator end() const noexcept { return const_iterator(this, static_cast<std::ptrdiff_t>(size())); }
//! Clear content.
void clear() noexcept;
//! Swap content.
void swap (cqueue<T> &x) noexcept;
};
} // namespace gto
/**
* @param[in] capacity Container capacity.
*/
template<std::semiregular T>
gto::cqueue<T>::cqueue(std::size_t capacity) {
if (capacity > MAX_CAPACITY) {
throw std::length_error("cqueue max capacity exceeded");
} else {
mCapacity = (capacity == 0 ? MAX_CAPACITY : capacity);
}
}
/**
* @param[in] other Queue to copy.
*/
template<std::semiregular T>
gto::cqueue<T>::cqueue(const cqueue &other) {
mCapacity = other.mCapacity;
reserve(mLength);
for (std::size_t i = 0; i < other.size(); i++) {
push(other[i]);
}
}
/**
* @param[in] other Queue to copy.
*/
template<std::semiregular T>
gto::cqueue<T> & gto::cqueue<T>::operator=(const cqueue &other) {
clear();
mCapacity = other.mCapacity;
for (std::size_t i = 0; i < other.size(); i++) {
push(other[i]);
}
return *this;
}
/**
* @param[in] num Element position.
* @return Index in buffer.
*/
template<std::semiregular T>
std::size_t gto::cqueue<T>::getUncheckedIndex(std::size_t pos) const noexcept {
return (mFront + pos) % (mReserved == 0 ? 1 : mReserved);
} | {
"domain": "codereview.stackexchange",
"id": 44076,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, collections, circular-list",
"url": null
} |
c++, collections, circular-list
/**
* @param[in] num Element position.
* @return Index in buffer.
* @exception std::out_of_range Invalid position.
*/
template<std::semiregular T>
std::size_t gto::cqueue<T>::getCheckedIndex(std::size_t pos) const noexcept(false) {
if (pos >= mLength) {
throw std::out_of_range("cqueue access out-of-range");
} else {
return getUncheckedIndex(pos);
}
}
/**
* @details Remove all elements.
*/
template<std::semiregular T>
void gto::cqueue<T>::clear() noexcept {
for (std::size_t i = 0; i < mLength; i++) {
mData[getUncheckedIndex(i)] = T{};
}
mFront = 0;
mLength = 0;
}
/**
* @details Swap content with another same-type cqueue.
*/
template<std::semiregular T>
void gto::cqueue<T>::swap(cqueue<T> &x) noexcept {
mData.swap(x.mData);
std::swap(mFront, x.mFront);
std::swap(mLength, x.mLength);
std::swap(mReserved, x.mReserved);
std::swap(mCapacity, x.mCapacity);
}
/**
* @brief Compute the new buffer size.
* @param[in] n New queue size.
*/
template<std::semiregular T>
std::size_t gto::cqueue<T>::getNewMemoryLength(std::size_t n) const {
std::size_t ret = (mReserved == 0 ? std::min(mCapacity, DEFAULT_RESERVED) : mReserved);
while (ret < n) {
ret *= GROWTH_FACTOR;
}
return std::min(ret, mCapacity);
}
/**
* @param[in] n Expected future queue size.
* @exception std::length_error Capacity exceeded.
*/
template<std::semiregular T>
void gto::cqueue<T>::reserve(std::size_t n) {
if (n < mReserved) {
return;
} else if (n > mCapacity) {
throw std::length_error("cqueue capacity exceeded");
}
std::size_t len = getNewMemoryLength(n);
auto tmp = std::make_unique<T[]>(len);
for (std::size_t i = 0; i < mLength; i++) {
tmp[i] = std::move(mData[getUncheckedIndex(i)]);
}
mReserved = len;
mData.swap(tmp);
mFront = 0;
} | {
"domain": "codereview.stackexchange",
"id": 44076,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, collections, circular-list",
"url": null
} |
c++, collections, circular-list
mReserved = len;
mData.swap(tmp);
mFront = 0;
}
/**
* @param[in] val Value to add.
* @exception std::length_error Number of values exceed queue capacity.
*/
template<std::semiregular T>
void gto::cqueue<T>::push(const T &val) {
reserve(mLength + 1);
mData[getUncheckedIndex(mLength)] = val;
mLength++;
}
/**
* @param[in] val Value to add.
* @exception std::length_error Number of values exceed queue capacity.
*/
template<std::semiregular T>
void gto::cqueue<T>::push(T &&val) {
reserve(mLength + 1);
mData[getUncheckedIndex(mLength)] = std::move(val);
mLength++;
}
/**
* @param[in] val Value to add.
* @exception std::length_error Number of values exceed queue capacity.
*/
template<std::semiregular T>
void gto::cqueue<T>::push_front(const T &val) {
reserve(mLength + 1);
mFront = (mLength == 0 ? 0 : (mFront == 0 ? mReserved : mFront) - 1);
mData[mFront] = val;
mLength++;
}
/**
* @param[in] val Value to add.
* @exception std::length_error Number of values exceed queue capacity.
*/
template<std::semiregular T>
void gto::cqueue<T>::push_front(T &&val) {
reserve(mLength + 1);
mFront = (mLength == 0 ? 0 : (mFront == 0 ? mReserved : mFront) - 1);
mData[mFront] = std::move(val);
mLength++;
}
/**
* @param[in] args Arguments of the new item.
* @exception std::length_error Number of values exceed queue capacity.
*/
template<std::semiregular T>
template <class... Args>
void gto::cqueue<T>::emplace(Args&&... args) {
reserve(mLength + 1);
mData[getUncheckedIndex(mLength)] = T{std::forward<Args>(args)...};
mLength++;
}
/**
* @return true = an element was erased, false = no elements in the queue.
*/
template<std::semiregular T>
bool gto::cqueue<T>::pop() {
if (mLength == 0) {
return false;
}
mData[mFront] = T{};
mFront = getUncheckedIndex(1);
mLength--;
return true;
} | {
"domain": "codereview.stackexchange",
"id": 44076,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, collections, circular-list",
"url": null
} |
c++, collections, circular-list
/**
* @return true = an element was erased, false = no elements in the queue.
*/
template<std::semiregular T>
bool gto::cqueue<T>::pop_back() {
if (mLength == 0) {
return false;
}
mLength--;
mData[getUncheckedIndex(mLength)] = T{};
return true;
}
Is there something wrong? What can be improved?
All ideas are welcome, I will be happy to know your opinions and objections. | {
"domain": "codereview.stackexchange",
"id": 44076,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, collections, circular-list",
"url": null
} |
c++, collections, circular-list
Answer: This looks quite good to me: a very complete interface, including iterators, matching the interface of STL containers quite closely, Doxygen documentation, lots of attention to details like const, move semantics, perfect forwarding and so on.
Unnecessary limitations
Why is there a MAX_CAPACITY, and where does the number 67108864 come from? It doesn't make any sense to me. The actual memory used also scales with sizeof(T), but the limitation you impose is only for the number of elements stored. I would remove this limitation completely.
Consider using an STL container to manage storage
Instead of allocating memory yourself and dealing with resizing, contructing and destructing elements, leave this to an existing STL container. In particular, std::deque is a good candidate for this, or perhaps std::queue. Apart from you having to write less code, it also fixes some problems that you have in your code, for example:
Your code default-constructs unused elements
When you call std::make_unique<T[]>(len), it will default-construct len elements. That's very surprising, since the STL containers do not have this behaviour. And this can cause problems if T's constructor has side-effects, and it prevents your code from compiling if T doesn't have a default constructor.
The usual way around this is to allocate raw memory, and then using placement new to construct elements inside that storage only when needed. But then you also have to remember to call the destructors, deal with alignment restrictions, and tip-toe around any potential problems with pointer conversions. It can all be done of course, but I would strongly recommend to use an appropriate existing container where possible.
What if an exception is thrown when resizing the storage? | {
"domain": "codereview.stackexchange",
"id": 44076,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, collections, circular-list",
"url": null
} |
c++, collections, circular-list
What if an exception is thrown when resizing the storage?
Consider that the assignment operator of T that is used inside reserve() could throw an exception. What if you were halfway moving from the old storage into the new storage? In your case, the program still is in a valid state, but now part of the elements in your circular queue have potentially unintented values. Ideally, your member functions would have a strong exception guarantee: the contents of the container are exactly the same as they were before the call that threw an exception. This can be achieved by copying instead of moving (indeed, this is why std::vector requires that its value type is copyable), or by never having to move or copy elements around to begin with (which is the property that std::deque has).
Naming
The name of the class is cqueue, but unless you know that this is a circular queue, it's hard to tell what the c stands for. Is it perhaps a "constant" queue (like constant iterators you get with cbegin() and cend())? Maybe it's a queue that can interact with C code? Avoid this problem by naming it circular_queue.
One might also wonder what is so circular about this queue. Will you be able to iterate infinitely, repeatedly looping through all elements? Will you be able to push elements when the queue is already full, automatically replacing the oldest element? While the implementation is using a circular buffer, for the user of this class the only difference between this and a std::queue is that there is a hard limit on the size, and it will throw std::length_error when you try to go past that limit. I would make sure you describe the properties of your class in more detail in the Doxygen comments describing the class.
Example implementation based on std::queue
Just to illustrate how much the code can be reduced by using an existing STL container, consider this which is based on the implementation of std::queue:
template<typename T, class Container = std::deque<T>>
class circular_queue { | {
"domain": "codereview.stackexchange",
"id": 44076,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, collections, circular-list",
"url": null
} |
c++, collections, circular-list
template<typename T, class Container = std::deque<T>>
class circular_queue {
public:
// Member types
using container_type = Container;
using value_type = Container::value_type;
using size_type = Container::size_type;
using reference = Container::reference;
using const_reference = Container::const_reference;
using iterator = Container::iterator;
using const_iterator = Container::const_iterator; | {
"domain": "codereview.stackexchange",
"id": 44076,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, collections, circular-list",
"url": null
} |
c++, collections, circular-list
// Constructors and assignment operators
circular_queue(size_type capacity = 0): mCapacity(capacity) {}
// That's it, rest is defaulted for us!
// Element access
reference front() { return mData.front(); }
const_reference front() const { return mData.front(); }
reference back() { return mData.back(); }
const_reference back() const { return mData.back(); }
reference at(size_type pos) { return mData.at(pos); }
const_reference at(size_type pos) { return mData.at(pos); }
reference operator[](size_type pos) { return mData[pos]; }
const_reference operator[](size_type pos) const { return mData[pos]; }
// Capacity
size_type capacity() const { return mCapacity; }
size_type size() const { return mData.size(); }
bool empty() const { return mData.empty(); }
// Modifiers
void push(const value_type& value) {
check_capacity();
mData.push_back(value);
}
void push(value_type&& value) {
check_capacity();
mData.push_back(std::move(value));
}
template<class... Args>
decltype(auto) emplace(Args&&... args) {
check_capacity();
return mData.emplace(std::forward<Args>(args)...);
}
void pop() { mData.pop_front(); }
void clear() { mData.clear(); }
void swap(circular_queue& other) {
using std::swap;
swap(mData, other.mData);
swap(mCapacity, other.mCapacity);
}
// Iterators
iterator begin() { return mData.begin(); }
const_iterator begin() const { return mData.begin(); }
const_iterator cbegin() const { return mData.cbegin(); }
iterator end() { return mData.end(); }
const_iterator end() const { return mData.end(); }
const_iterator cend() const { return mData.cend(); }
private:
Container mData;
std::size_t mCapacity; | {
"domain": "codereview.stackexchange",
"id": 44076,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, collections, circular-list",
"url": null
} |
c++, collections, circular-list
private:
Container mData;
std::size_t mCapacity;
void check_capacity() {
if (mCapacity == mData.size()) {
throw std::length_error("circular_queue capacity exceeded");
}
}
};
You could probably even reduce it further by inheriting from Container instead of having it as a member.
Think about constexpr, [[nodiscard]] and more noexcept
It's great to see const and noexcept being used, but it might also be possible to make things constexpr, and since C++17 you can add attributes such as [[nodiscard]] to guard against incorrect use of your class. Consider for example that empty() should ideally be all those things:
[[nodiscard]] constexpr bool empty() const noexcept;
Of course, some of these things require more recent versions of the C++ standard, so if you want to be compatible with older versions you might not be able to use these yet. | {
"domain": "codereview.stackexchange",
"id": 44076,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, collections, circular-list",
"url": null
} |
c++, performance, c, matrix, arduino
Title: Matrix led 7x10 with arduino
Question: Good afternoon, a few days ago I finished a personal project of a 7x10 led matrix programmed with the ATMEGA328p microcontroller. To control the matrix I use 2 74HC595 shift registers in cascade in the 10 columns and a CD4017 decade counter in the 7 rows. The 8 rows of the LED matrix are independently connected to a 2N3904 NPN transistor that provides a ground path to sink the combined current of all the LEDs in a row.
I've been programming microcontrollers for a few months and I would like some advice to improve my code, both in terms of good practices and program optimization.
Code:
#define CD4017_CLK PORTB1
#define CD4017_RST PORTB2
#define SERIAL_DATA PORTB3
#define ST_CLK PORTB4
#define SH_CLK PORTB5
#define MAX_CHARS 100
#define DELAY 30
#define SHIFT_STEP 1 | {
"domain": "codereview.stackexchange",
"id": 44077,
"lm_label": 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, c, matrix, arduino",
"url": null
} |
c++, performance, c, matrix, arduino
/*
char_data is a two dimensional constant array that holds the 5-bit column values
of individual rows for ASCII characters that are to be displayed on a 7x10 matrix.
*/
const byte char_data[95][7]={
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, // space
{0x4, 0x4, 0x4, 0x4, 0x4, 0x0, 0x4}, // !
{0xA, 0xA, 0xA, 0x0, 0x0, 0x0, 0x0}, // "
{0xA, 0xA, 0x1F, 0xA, 0x1F, 0xA, 0xA}, // #
{0x4, 0xF, 0x14, 0xE, 0x5, 0x1E, 0x4}, // $
{0x18, 0x19, 0x2, 0x4, 0x8, 0x13, 0x3}, // %
{0x8, 0x14, 0x14, 0x8, 0x15, 0x12, 0xD}, // &
{0x4, 0x4, 0x4, 0x0, 0x0, 0x0, 0x0}, // '
{0x4, 0x8, 0x10, 0x10, 0x10, 0x8, 0x4}, // (
{0x4, 0x2, 0x1, 0x1, 0x1, 0x2, 0x4}, // )
{0x4, 0x15, 0xE, 0x4, 0xE, 0x15, 0x4}, // *
{0x0, 0x4, 0x4, 0x1F, 0x4, 0x4, 0x0}, // +
{0x0, 0x0, 0x0, 0x0, 0x4, 0x4, 0x8}, // ,
{0x0, 0x0, 0x0, 0x1F, 0x0, 0x0, 0x0}, // -
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4}, // .
{0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x0}, // /
{0xE, 0x11, 0x13, 0x15, 0x19, 0x11, 0xE}, // 0
{0x6, 0xC, 0x4, 0x4, 0x4, 0x4, 0xE}, // 1
{0xE, 0x11, 0x1, 0x6, 0x8, 0x10, 0x1F}, // 2
{0x1F, 0x1, 0x2, 0x6, 0x1, 0x11, 0xF}, // 3
{0x2, 0x6, 0xA, 0x12, 0x1F, 0x2, 0x2}, // 4
{0x1F, 0x10, 0x1E, 0x1, 0x1, 0x11, 0xE}, // 5
{0xE, 0x11, 0x10, 0x1E, 0x11, 0x11, 0xE}, // 6
{0x1F, 0x1, 0x2, 0x4, 0x8, 0x8, 0x8}, // 7
{0xE, 0x11, 0x11, 0xE, 0x11, 0x11, 0xE}, // 8
{0xE, 0x11, 0x11, 0xF, 0x1, 0x11, 0xE}, // 9
{0x0, 0x0, 0x4, 0x0, 0x4, 0x0, 0x0}, // :
{0x0, 0x0, 0x4, 0x0, 0x4, 0x4, 0x8}, // ;
{0x2, 0x4, 0x8, 0x10, 0x8, 0x4, 0x2}, // <
{0x0, 0x0, 0x1F, 0x0, 0x1F, 0x0, 0x0}, // =
{0x8, 0x4, 0x2, 0x1, 0x2, 0x4, 0x8}, // >
{0xE, 0x11, 0x1, 0x2, 0x4, 0x0, 0x4}, // ?
{0xE, 0x11, 0x17, 0x15, 0x16, 0x10, 0xF}, // @
{0xE, 0x11, 0x11, 0x1F, 0x11, 0x11, 0x11}, // A
{0x1E, 0x11, 0x11, 0x1E, 0x11, 0x11, 0x1E}, // B
{0xE, 0x11, 0x10, 0x10, 0x10, 0x11, 0xE}, // C
{0x1E, 0x11, 0x11, 0x11, 0x11, 0x11, 0x1E}, // D | {
"domain": "codereview.stackexchange",
"id": 44077,
"lm_label": 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, c, matrix, arduino",
"url": null
} |
c++, performance, c, matrix, arduino
{0x1E, 0x11, 0x11, 0x11, 0x11, 0x11, 0x1E}, // D
{0x1F, 0x10, 0x10, 0x1E, 0x10, 0x10, 0x1F}, // E
{0x1F, 0x10, 0x10, 0x1E, 0x10, 0x10, 0x10}, // F
{0xE, 0x11, 0x10, 0x17, 0x15, 0x11, 0xE}, // G
{0x11, 0x11, 0x11, 0x1F, 0x11, 0x11, 0x11}, // H
{0x1F, 0x4, 0x4, 0x4, 0x4, 0x4, 0x1F}, // I
{0x1, 0x1, 0x1, 0x1, 0x1, 0x11, 0xE}, // J
{0x11, 0x11, 0x12, 0x1C, 0x12, 0x11, 0x11}, // K
{0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x1F}, // L
{0x11, 0x1B, 0x15, 0x15, 0x11, 0x11, 0x11}, // M
{0x11, 0x11, 0x19, 0x15, 0x13, 0x11, 0x11}, // N
{0xE, 0x11, 0x11, 0x11, 0x11, 0x11, 0xE}, // O
{0x1E, 0x11, 0x11, 0x1E, 0x10, 0x10, 0x10}, // P
{0xE, 0x11, 0x11, 0x11, 0x15, 0x13, 0xF}, // Q
{0x1E, 0x11, 0x11, 0x1E, 0x11, 0x11, 0x11}, // R
{0xF, 0x10, 0x10, 0xE, 0x1, 0x1, 0x1E}, // S
{0x1F, 0x4, 0x4, 0x4, 0x4, 0x4, 0x4}, // T
{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0xE}, // U
{0x11, 0x11, 0x11, 0x11, 0x11, 0xA, 0x4}, // V
{0x11, 0x11, 0x11, 0x15, 0x15, 0x1B, 0x11}, // W
{0x11, 0x11, 0xA, 0x4, 0xA, 0x11, 0x11}, // X
{0x11, 0x11, 0xA, 0x4, 0x4, 0x4, 0x4}, // Y
{0x1F, 0x1, 0x2, 0x4, 0x8, 0x10, 0x1F}, // Z
{0xE, 0x8, 0x8, 0x8, 0x8, 0x8, 0xE}, // [
{0x0, 0x10, 0x8, 0x4, 0x2, 0x1, 0x0}, // backward slash
{0xE, 0x2, 0x2, 0x2, 0x2, 0x2, 0xE}, // ]
{0x0, 0x0, 0x4, 0xA, 0x11, 0x0, 0x0}, // ^
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1F}, // _
{0x8, 0x4, 0x2, 0x0, 0x0, 0x0, 0x0}, // `
{0x0, 0x0, 0xE, 0x1, 0xF, 0x11, 0xF}, // a
{0x10, 0x10, 0x10, 0x1E, 0x11, 0x11, 0x1E}, // b
{0x0, 0x0, 0xE, 0x11, 0x10, 0x11, 0xE}, // c
{0x1, 0x1, 0x1, 0xF, 0x11, 0x11, 0xF}, // d
{0x0, 0x0, 0xE, 0x11, 0x1F, 0x10, 0xF}, // e
{0xE, 0x9, 0x1C, 0x8, 0x8, 0x8, 0x8}, // f
{0x0, 0x0, 0xE, 0x11, 0xF, 0x1, 0xE}, // g
{0x10, 0x10, 0x10, 0x1E, 0x11, 0x11, 0x11}, // h
{0x4, 0x0, 0x4, 0x4, 0x4, 0x4, 0xE}, // i
{0x1, 0x0, 0x3, 0x1, 0x1, 0x11, 0xE}, // j | {
"domain": "codereview.stackexchange",
"id": 44077,
"lm_label": 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, c, matrix, arduino",
"url": null
} |
c++, performance, c, matrix, arduino
{0x4, 0x0, 0x4, 0x4, 0x4, 0x4, 0xE}, // i
{0x1, 0x0, 0x3, 0x1, 0x1, 0x11, 0xE}, // j
{0x10, 0x10, 0x11, 0x12, 0x1C, 0x12, 0x11}, // k
{0xC, 0x4, 0x4, 0x4, 0x4, 0x4, 0xE}, // l
{0x0, 0x0, 0x1E, 0x15, 0x15, 0x15, 0x15}, // m
{0x0, 0x0, 0x1E, 0x11, 0x11, 0x11, 0x11}, // n
{0x0, 0x0, 0xE, 0x11, 0x11, 0x11, 0xE}, // o
{0x0, 0x0, 0xF, 0x9, 0xE, 0x8, 0x8}, // p
{0x0, 0x0, 0xF, 0x11, 0xF, 0x1, 0x1}, // q
{0x0, 0x0, 0x17, 0x18, 0x10, 0x10, 0x10}, // r
{0x0, 0x0, 0xF, 0x10, 0xE, 0x1, 0x1E}, // s
{0x4, 0x4, 0xE, 0x4, 0x4, 0x4, 0x3}, // t
{0x0, 0x0, 0x11, 0x11, 0x11, 0x13, 0x13}, // u
{0x0, 0x0, 0x11, 0x11, 0x11, 0xA, 0x4}, // v
{0x0, 0x0, 0x11, 0x11, 0x15, 0x1F, 0x15}, // w
{0x0, 0x0, 0x11, 0xA, 0x4, 0xA, 0x11}, // x
{0x0, 0x0, 0x11, 0x11, 0xF, 0x1, 0x1E}, // y
{0x0, 0x0, 0x1F, 0x2, 0x4, 0x8, 0x1F}, // z
{0x2, 0x4, 0x4, 0x8, 0x4, 0x4, 0x2}, // {
{0x4, 0x4, 0x4, 0x4, 0x4, 0x4, 0x4}, // |
{0x8, 0x4, 0x4, 0x2, 0x4, 0x4, 0x8}, // }
{0x0, 0x0, 0x0, 0xA, 0x15, 0x0, 0x0}, // ~
};
uint16_t frame_buffer[7];
char message[MAX_CHARS+2] = "MATRIZ LED 7X10 ";
int string_length = strlen(message); | {
"domain": "codereview.stackexchange",
"id": 44077,
"lm_label": 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, c, matrix, arduino",
"url": null
} |
c++, performance, c, matrix, arduino
void send_data(uint16_t data){
uint16_t mask = 1, flag = 0;
for (byte i=0; i<10; i++){
flag = data & mask;
if (flag) PORTB |= (1 << SERIAL_DATA);
else PORTB &= ~(1 << SERIAL_DATA);
PORTB |= (1 << SH_CLK);
PORTB &= ~(1 << SH_CLK);
mask <<= 1;
}
PORTB |= (1 << ST_CLK);
PORTB &= ~(1 << ST_CLK);
}
void send_frame_buffer(){
for (byte t=0; t<DELAY; t++){ // The delay we get with loops.
for (byte row=0; row<7; row++){ // For each row.
// Send 10 bits to shift registers.
send_data(frame_buffer[row]);
// This delay defines the time to play each pattern.
delayMicroseconds(800);
// Clear the row so we can go on to the next row without smearing.
send_data(0);
// On to the next row.
PORTB |= (1 << CD4017_CLK);
PORTB &= ~(1 << CD4017_CLK);
}
// Select the first row.
PORTB |= (1 << CD4017_RST);
PORTB &= ~(1 << CD4017_RST);
}
}
void display_message(){
for (byte c=0; c<string_length; c++){ // For each character.
byte mask = 0x10;
for (byte column=0; column<5; column++){ // For each column.
for (byte row=0; row<7; row++){ // For each row.
// To obtain the position of the current character in the char_data array, subtract 32 from the ASCII value of the character itself.
byte index = message[c];
byte temp = char_data[index-32][row];
frame_buffer[row] = (frame_buffer[row]<<1) | ((temp&mask)>>4-column);
}
send_frame_buffer();
mask >>= 1;
}
// One column of separation between characters.
for (byte row=0; row<7; row++){
frame_buffer[row] <<= SHIFT_STEP;
}
send_frame_buffer();
}
} | {
"domain": "codereview.stackexchange",
"id": 44077,
"lm_label": 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, c, matrix, arduino",
"url": null
} |
c++, performance, c, matrix, arduino
int main(){
// PORTB as output.
DDRB = 0b111111;
// Makes sure the 4017 value is 0.
PORTB |= (1 << CD4017_RST);
PORTB &= ~(1 << CD4017_RST);
while (true){
display_message();
}
}
Video: https://www.youtube.com/shorts/neCM424JKCY
Answer: The code is not bad at all, so mostly these are going to be some notes about style that won't make a significant difference to the underlying machine code as we will see.
Try not to confuse readers
This line is a little strange:
char message[MAX_CHARS+2] = "MATRIZ LED 7X10 ";
Apparently MAX_CHARS doesn't really mean MAX_CHARS? I'd suggest simply increasing the value of MAX_CHARS by two. It would be a lot less strange.
Add functions for readability
The current code includes this function.
void send_data(uint16_t data){
uint16_t mask = 1, flag = 0;
for (byte i=0; i<10; i++){
flag = data & mask;
if (flag) PORTB |= (1 << SERIAL_DATA);
else PORTB &= ~(1 << SERIAL_DATA);
PORTB |= (1 << SH_CLK);
PORTB &= ~(1 << SH_CLK);
mask <<= 1;
}
PORTB |= (1 << ST_CLK);
PORTB &= ~(1 << ST_CLK);
}
That works, of course, but it can be prone to error. It would be all to easy to type |= when you meant &= or to forget the ~. Also, the lines of code dealing with moving the clock from high to low must operate in pairs. For all of these reasons, I'd prefer to write it like this:
void send_data(uint16_t data){
for (uint16_t mask{1}; mask & 0x3ff; mask <<= 1) {
bit(SERIAL_DATA, data & mask);
bithilo(SH_CLK);
}
bithilo(ST_CLK);
} | {
"domain": "codereview.stackexchange",
"id": 44077,
"lm_label": 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, c, matrix, arduino",
"url": null
} |
c++, performance, c, matrix, arduino
You could use the digitalWrite functions provided by the Arduino platform, or you might prefer to create more efficient ones as I've done here:
inline void setbit(int bitnum) {
PORTB |= (1 << bitnum);
}
inline void clrbit(int bitnum) {
PORTB &= ~(1 << bitnum);
}
inline void bit(int bitnum, bool val) {
if (val)
setbit(bitnum);
else
clrbit(bitnum);
}
inline void bithilo(int bitnum) {
setbit(bitnum);
clrbit(bitnum);
}
One might object that it's more code, or that it will make the program slower, but in fact, as this online sample shows, the two versions produce identical assembly language instruction sequences.
Marking these functions as inline is a way to suggest to the compiler that inline substitution of this code might be better than having the code actually called as a subroutine. In this particular case, it allows the compiler's optimizer to recognize that the operations can be accomplished with a very efficient sbi or cbi assembly language instruction.
This line: for (uint16_t mask{1}; mask & 0x3ff; mask <<= 1) may seem confusing at first, but it's a common idiom, especially for embedded systems. We want to extract one bit at a time for ten bits. The 0x3ff is a uint16_t with the low ten bits set. As we shift the bits to the left, the value of mask & 0x3ff will be a non-zero number until we get to the eleventh bit. At that point, the experession is 0, which C++ interprets as false and so the loop ends.
As you can see from the online compiler demonstration, both versions result in identical code, so I would advocate using the one that you think makes the code easiest to read and maintain.
Make it easier to spot data errors
Here's the code for the '0' character, but with an error in it:
{0xE, 0x11, 0x13, 0x15, 0x1B, 0x11, 0xE}, // 0 but with an error | {
"domain": "codereview.stackexchange",
"id": 44077,
"lm_label": 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, c, matrix, arduino",
"url": null
} |
c++, performance, c, matrix, arduino
How long would it take you to find the error? I'd suggest doing one of two things. Either use an external program that runs on your computer (not the Arduino) to generate both the visual and hex form, or write the data in binary to make it easier to see what's going on:
{ 0b01110,
0b10001,
0b10011,
0b10101,
0b11011, // <-- this line has the error
0b10001,
0b01110
},
It's still not great, but I would suggest that it's a lot easier for a human to verify that 1) all lines are exactly 5 bits and 2) each character has a plausible representation. Consider if you were asked to change this character so that it didn't have a diagonal line in it. It would be a lot simpler in this form.
Consider using objects
Arduino's language is actually a C++ variant, which has some very useful object oriented features. You could for example wrap the display into an object so that if you wanted to change it to accommodate two 10x7 displays side-by-side acting as a 20x7 display, the interface to the rest of the code could stay the same. | {
"domain": "codereview.stackexchange",
"id": 44077,
"lm_label": 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, c, matrix, arduino",
"url": null
} |
python, performance, python-3.x
Title: How to speed up combinations code
Question: from itertools import combinations
for comb in combinations(range(1, 70), 5):
for PB in combinations(range(1, 27), 1):
if PB[0] in range(1, 27):
a = open(f"PowerBall{PB[0]}.txt", "a")
a.write(str(comb + PB))
a.write("\n")
print("\r", f"on: {comb + PB}", end="")
Trying to find all combination for those set of ranges.
Answer: Perhaps open all 26 files. Then generate the combinations just once and write each one to all the files. Use contextlib.ExitStack() to ensure all the files get closed. Something like this (untested):
from contextlib import ExitStack
from itertools import combinations
with ExitStack() as stack:
files = [stack.enter_context(open(f"PowerBall{i}.txt", "a")) for i in range(1,27)]
for comb in combinations(range(1, 70), 5):
for pb, pb_file in enumerate(files, 1):
print(*comb, pb, file=pb_file, sep=", ")
The files = [...] list comprehension opens all 26 files and pushes them onto the ExitStack. When the with statement exits, the __exit__() method is called on all items on the stack, which for a file causes it to be closed. | {
"domain": "codereview.stackexchange",
"id": 44078,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x",
"url": null
} |
c#, reinventing-the-wheel, reflection
Title: Mapping various input values to a data accumulation class
Question: This function takes inputs from multiple different controls on a form, and maps them to values in a data accumulation class. This code was written specifically to keep logic, data, and display separated. I ended up at the time using reflection to take the values from the controls and mapping them to variables with the same names in the accumulation class. The reasoning behind doing it this way was I didn't want a bunch of:
variable = control.value
Calls being repeated throughout this section of code, and should it end up that I needed additional controls on that form, I wanted to be able to just add the appropriate variable to the accumulation class and let the program handle adding that information to the accumulator dynamically.
I'm posting here to see what if any better ways to do this exist. (I'm sure there must be one, but this was the method I found that works.)
What I've written works well, and does it's job, but feels like very very bad code.
This is the mapping method:
/// <summary>
/// Updates the random accumulator. One method to rule *ALL* The random controls!
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void UpdateRandomAccumulator ( object sender, EventArgs e ) {
//Dear Future Me: You are a genius. You made this work. Despite overwhelming odds, you are victorious!
//Be proud future me, when you look upon this method in total confusion, since you probably forgot
//*exactly how* it works 10 minutes after closing this class. | {
"domain": "codereview.stackexchange",
"id": 44079,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, reinventing-the-wheel, reflection",
"url": null
} |
c#, reinventing-the-wheel, reflection
Control control = sender as Control;
if ( control is TrackBar ) {
TrackBar tbar = control as TrackBar;
string controlName = control.Name.Remove ( 0, 9 );
//okay limiting our MinBads/MaxTourists here.
if ( controlName.Equals ( "MinNumberOfBadasses" ) || controlName.Equals ( "MaxNumberOfTourists" ) ) {
if ( tbar.Value >= randAccum.NumberToCreate ) {
tbar.Value = randAccum.NumberToCreate;
}
}
foreach ( var prop in randAccum.GetType( ).GetProperties( ) ) {
if ( controlName == prop.Name ) {
if ( prop.PropertyType == typeof(float) ) {
prop.SetValue ( randAccum, (float) tbar.Value / 100 );
}
else if ( prop.PropertyType == typeof(int) ) {
prop.SetValue ( randAccum, tbar.Value );
}
else {
Logger.LogEvent ( prop.PropertyType.ToString ( ) );
}
}
}
tbar_rnd_MaxNumberOfTourists.Maximum = randAccum.NumberToCreate;
tbar_rnd_MinNumberOfBadasses.Maximum = randAccum.NumberToCreate;
if ( tbar_rnd_MaxNumberOfTourists.Value > randAccum.NumberToCreate ) {
tbar_rnd_MaxNumberOfTourists.Value = randAccum.NumberToCreate;
}
if ( tbar_rnd_MinNumberOfBadasses.Value > randAccum.NumberToCreate ) {
tbar_rnd_MinNumberOfBadasses.Value = randAccum.NumberToCreate;
}
} | {
"domain": "codereview.stackexchange",
"id": 44079,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, reinventing-the-wheel, reflection",
"url": null
} |
c#, reinventing-the-wheel, reflection
if ( control is CheckBox ) {
CheckBox cbox = control as CheckBox;
string controlName = cbox.Name.Remove ( 0, 8 );
//because use Ratio is notted, we have to set it by hand.
//The For loop is left incase we add any more checkboxes.
if ( controlName.Equals ( "useRatio" ) ) {
tbar_rnd_FtMRatio.Enabled = !cbox.Checked;
randAccum.useRatio = !cbox.Checked;
}
else {
foreach ( var prop in randAccum.GetType( ).GetProperties( ) ) {
if ( controlName == prop.Name ) {
if ( prop.PropertyType == typeof(bool) ) {
prop.SetValue ( randAccum, cbox.Checked );
}
}
}
}
}
randAccum.NumberToCreate = randAccum.Pilots + randAccum.Engineers + randAccum.Scientists;
UpdateRandomDisplay ( );
}
And here's the accumulation class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KerbalTherapist.Accumulators {
public class RandomAccumulator {
//number of kerbals to create
public int NumberToCreate { get; set; }
public bool useRatio { get; set; }
public bool isKerman { get; set; }
//gendersettings;
public float FtMRatio { get; set; }
//ability scores
public float MinStupid { get; set; }
public float MaxStupid { get; set; }
public float MinBrave { get; set; }
public float MaxBrave { get; set; }
public int MinNumberOfBadasses { get; set; }
public int MaxNumberOfTourists { get; set; }
//Profession Ratios
public int Pilots { get; set; }
public int Engineers { get; set; }
public int Scientists { get; set; } | {
"domain": "codereview.stackexchange",
"id": 44079,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, reinventing-the-wheel, reflection",
"url": null
} |
c#, reinventing-the-wheel, reflection
public int Engineers { get; set; }
public int Scientists { get; set; }
public RandomAccumulator ( ) {
NumberToCreate = 1;
FtMRatio = 0;
useRatio = true; //needs to be true by default.
MinStupid = 0.0f;
MaxStupid = 0.0f;
MinBrave = 0.0f;
MaxBrave = 0.0f;
MinNumberOfBadasses = 0;
MaxNumberOfTourists = 0;
Pilots = 0;
Engineers = 0;
Scientists = 0;
}
public RandomAccumulator Reset ( ) {
return new RandomAccumulator ( );
}
}
Answer: Quite frankly I'm not sure what your code fragment does, so I've reviewed your code in the way how can we improve legibility.
Split the UpdateRandomAccumulator method
You can easily extract the TrackBar and Checkbox handling code into their own methods
After that the UpdateRandomAccumulator method would like something like this
private void UpdateRandomAccumulator(object sender, EventArgs e)
{
var control = sender as Control;
if (control is TrackBar tbar)
{
HandleTrackbar(tbar, control.Name.Remove(0, 9));
}
else if (control is CheckBox cbox)
{
HandleCheckbox(cbox, cbox.Name.Remove(0, 8));
}
randAccum.NumberToCreate = randAccum.Pilots + randAccum.Engineers + randAccum.Scientists;
UpdateRandomDisplay();
}
Please be aware that this Name.Remove(x, y) is super fragile so try to avoid it if possible
The HandleTrackbar
As I've stated in the first sentence without proper context it is impossible to know what your code really does
So, my suggestions here might be not applicable
static string[] ControlNames = { "MinNumberOfBadasses", "MaxNumberOfTourists" };
void HandleTrackbar(TrackBar tbar, string controlName)
{
if (ControlNames.Contains(controlName) && tbar.Value >= randAccum.NumberToCreate)
{
tbar.Value = randAccum.NumberToCreate;
}
var prop = randAccum.GetType().GetProperty(controlName); | {
"domain": "codereview.stackexchange",
"id": 44079,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, reinventing-the-wheel, reflection",
"url": null
} |
c#, reinventing-the-wheel, reflection
var prop = randAccum.GetType().GetProperty(controlName);
if (prop.PropertyType == typeof(float))
{
prop.SetValue(randAccum, tbar.Value / 100f);
}
else if (prop.PropertyType == typeof(int))
{
prop.SetValue(randAccum, tbar.Value);
}
else
{
Logger.LogEvent(prop.PropertyType.ToString());
}
tbar_rnd_MaxNumberOfTourists.Maximum = randAccum.NumberToCreate;
tbar_rnd_MaxNumberOfTourists.Value = tbar_rnd_MaxNumberOfTourists.Value > randAccum.NumberToCreate
? randAccum.NumberToCreate
: tbar_rnd_MaxNumberOfTourists.Value;
tbar_rnd_MinNumberOfBadasses.Maximum = randAccum.NumberToCreate;
tbar_rnd_MinNumberOfBadasses.Value = tbar_rnd_MinNumberOfBadasses.Value > randAccum.NumberToCreate
? randAccum.NumberToCreate
: tbar_rnd_MinNumberOfBadasses.Value;
}
I've replaced your control name check logic to a collection lookup
As far I understand your code you don't need to get all properties, rather you are looking for a specific one based on the control name
So, I've removed your foreach loop and replaced your GetProperties to GetProperty call
I've replaced your (float)tbar.Value / 100 to tbar.Value / 100f because the intent is more explicit here IMHO
I've also replaced your guard expression for value assignments with ternary conditional operators
HandleCheckbox
void HandleCheckbox(ChechBox cbox, string controlName)
{
if (controlName.Equals("useRatio"))
{
tbar_rnd_FtMRatio.Enabled = !cbox.Checked;
randAccum.useRatio = !cbox.Checked;
return;
}
var prop = randAccum.GetType().GetProperty("prop.Name");
if (prop.PropertyType == typeof(bool))
{
prop.SetValue(randAccum, cbox.Checked);
}
}
More or less the same simplification as before
+1: I've used early exit to avoid having else block
RandomAccumulator | {
"domain": "codereview.stackexchange",
"id": 44079,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, reinventing-the-wheel, reflection",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.