text
stringlengths
1
2.12k
source
dict
c++, design-patterns, abstract-factory In case you do in fact need the full abstract pattern, the only changes you would need to make to your code would be to change the return type from AbstractWindow* and AbstractDoor* to std::unique_ptr<AbstractWindow> and std::unique_ptr<AbstractDoor>—and to fix one serious bug. Namely: Every Abstract Base Class Needs a virtual Destructor! This is a big one. This particular toy program frees all its memory when it returns from main. Any real-world program that needs this pattern would leak memory or corrupt the heap in unpredictably dangerous ways whenever a factory got destroyed, because you never declare a destructor. The default implicit destructor doesn’t delete anything. And, worse, it does not call the derived class’ destructor. In the real world, any class hierarchy complex enough that you’d really need this will need a non-trivial destructor. This would include, for example, any factory object that uses dynamic memory to manage what kind of windows and doors it creates. This will not get called unless you give your base class something like virtual ~AbstractWindow() = default;
{ "domain": "codereview.stackexchange", "id": 42817, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns, abstract-factory", "url": null }
c++, design-patterns, abstract-factory Then, any unique_ptr<AbstractWindow> will call the appropriate destructor for the object it stored, through the interface’s virtual function table, when it is destroyed. You don’t need to do anything special in any of the derived classes. The implicit destructors the compiler creates automatically for them should work. But any abstract base class should declare its destructor virtual. (Technically, it only absolutely must do this whenever base-class pointers are used to destroy the object, and not just as weak references, but there is practically no cost to declaring a destructor virtual if the class has another virtual function anyway.) If you need to implement a yser-defined destructor in a derived class, be sure to declare it override so the compiler will tell you when the base class lacks a virtual destructor. You will save yourself a lot of hassle tracking down memory leaks later. Many compilers have flags that enable warnings whenever you do not give a base class a virtual destructor, and it would be a good idea to turn those warnings on. Use const and static Where Appropriate Most of your functions, such as .identify() and .buildDoor(), don’t modify the objects, and should therefore be const so you can use const objects. In fact, none of your factory methods use any per-instance data at all. If they were storing instance data, passing it to the factory methods, and possibly modifying it (for example, giving each object a unique serial number), it would make sense for them to use this interface. But, if it’s only ever returning default objects, it should be a singleton with static factory methods. Prefer Composition to Inheritance Your AbstractFactory is just a composition of an AbstractDoor allocator and an AbstractWindow allocator. You don’t really need to combine them into one factory class at all; you can just create (smart or dumb) pointers to AbstractWindow and AbstractDoor by assigning to them.
{ "domain": "codereview.stackexchange", "id": 42817, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns, abstract-factory", "url": null }
c++, design-patterns, abstract-factory So let’s turn this into something that meaningfully uses the pattern by creating some kind of object that couples a window and a door: template < typename WindowT, typename DoorT> struct HouseParts { std::unique_ptr<WindowT> windowRef; std::unique_ptr<DoorT> doorRef; };
{ "domain": "codereview.stackexchange", "id": 42817, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns, abstract-factory", "url": null }
c++, design-patterns, abstract-factory template< typename WindowT, typename DoorT > class HousePartsFactory { public: static HouseParts< WindowT, DoorT > build() { return { std::make_unique<WindowT>(), std::make_unique<DoorT>() }; } }; If you want to get fancier, you can restrict the template so that it checks whether your WindowT is actually a window and your DoorT is actually a door. This is a good idea here, since the two classes accidentally duck-type to each other, and the compiler would not otherwise catch a bug where you write them in reverse order. One way to do this in C++20 is with a concept: template<class WindowT> concept type_of_window = std::derived_from< WindowT, AbstractWindow >; template<class DoorT> concept type_of_door = std::derived_from< DoorT, AbstractDoor >; Which then lets you write: template < type_of_window WindowT, type_of_door DoorT >
{ "domain": "codereview.stackexchange", "id": 42817, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns, abstract-factory", "url": null }
c++, design-patterns, abstract-factory The older methods, such as restrict or std::enable_if, will still work, too. This is not run-time polymorphism. It does not define an interface that can reference any kind of HouseParts. Each function that uses this must be templated to some type of window and door. In fact, because the factory method is static, we do not need to create any instance of the factory object at all. This would change based on what data it needs at runtime. If all factories in the program are supposed to generate unique serial numbers for each object they create, for example, they should increment a shared counter. If an individual factory is configurable, such as telling it to switch to making its wood windows and doors from fir instead of oak, it would then need some instance data, and its factory method could no longer be static. How to store the objects in the struct has trade-offs. I used unique_ptr references, which are the closest equivalent to dumb pointers in modern C++. These can be moved efficiently, but cannot be automatically copied. This also facilitates, later on, allowing a generic house-parts interface to replace one with a house part of a different type. If you want the object to be copyable, like with auto moreHouseParts = someHouseParts;, you must define your own copy constructor that makes a deep copy, or change std::unique_ptr to std::shared_ptr (which has higher overhead), or store the door and window objects themselves rather than pointers to them. But you always really had to do one of these three things, or your program would have a memory-management bug. The compiler just didn’t check for them. Everybody just assumed that any big C++ program did. A Few Minor Things If I don’t tell you that it’s slightly more efficient, as well as shorter, to write << "...\n"; than << "..." << std::endl;, someone else is sure to. So I'll save them the trouble.
{ "domain": "codereview.stackexchange", "id": 42817, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns, abstract-factory", "url": null }
c++, design-patterns, abstract-factory In this simple example, many of the functions and constructors could be declared constexpr. The downside is, you might later paint yourself into a corner, where you can’t remove the constexpr from the interface without breaking your codebase, but leaving it might prevent an implementation from doing something it needs to, such as logging or allocating dynamic memory. One way around that is to declare a particular specialization of the class template to have a constexpr constructor, without putting any limitations on the more general version. I didn’t make anything noexcept, since in general we can’t be sure what a derived class implementing our interface might need to do. You can often eke a little more optimization out of this keyword, if you know what you’re doing. A good example of what to make noexcept in a production interface would be moves and swaps. Putting it All Together (with Templates) #include <concepts> #include <iostream> #include <memory> #include <string>
{ "domain": "codereview.stackexchange", "id": 42817, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns, abstract-factory", "url": null }
c++, design-patterns, abstract-factory using namespace std::literals::string_literals; class AbstractDoor { public: virtual const std::string& to_string() const = 0; virtual ~AbstractDoor() = default; }; std::ostream& operator<< ( std::ostream& os, const AbstractDoor& door ) { return os << door.to_string(); } class AbstractWindow { public: virtual const std::string& to_string() const = 0; virtual ~AbstractWindow() = default; }; std::ostream& operator<< ( std::ostream& os, const AbstractWindow& window ) { return os << window.to_string(); } class WoodDoor : public AbstractDoor { public: const std::string& to_string() const override { static const std::string message = "This is a wooden door."s; return message; } }; class GumDoor : public AbstractDoor { public: const std::string& to_string() const override { static const std::string message = "This is a gum door."s; return message; } }; class WoodWindow : public AbstractWindow { public: const std::string& to_string() const override { static const std::string message = "This is a wooden window."s; return message; } }; class GumWindow : public AbstractWindow { public: const std::string& to_string() const override { static const std::string message = "This is a gum window."s; return message; } }; template<class WindowT> concept is_a_window = std::derived_from< WindowT, AbstractWindow >; template<class DoorT> concept is_a_door = std::derived_from< DoorT, AbstractDoor >; template < is_a_window WindowT, is_a_door DoorT > struct HouseParts { std::unique_ptr<WindowT> windowRef; std::unique_ptr<DoorT> DoorRef; }; template< is_a_window WindowT, is_a_door DoorT > class HousePartsFactory { public: static HouseParts< WindowT, DoorT > build() { return { std::make_unique<WindowT>(), std::make_unique<DoorT>() }; } }; #include <cstdlib>
{ "domain": "codereview.stackexchange", "id": 42817, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns, abstract-factory", "url": null }
c++, design-patterns, abstract-factory #include <cstdlib> int main() { using std::cout; std::cout << "Let's build a wooden window and gum door!\n"; const auto [ windowRef, doorRef ] = HousePartsFactory< WoodWindow, GumDoor >::build(); cout << *windowRef << ' ' << *doorRef << '\n'; return EXIT_SUCCESS; } Going through the changes: There is no dynamic typing in the program. The only virtual function calls are to cout <<. Everything else is declared as a class template (and output could be a function template, if you wanted). The interface is not hardcoded to print to cout, but returns a std::string that you can use for other purposes (such as logging somewhere other than standard output, or passing to a formatter). There is a generic function that passes an AbstractWindow or AbstractDoor to a std::ostream. All class functions that can be static or const are. This means the program never actually creates a factory object. All objects in the program have their memory managed automatically. As a side-effect of using std::unique_ptr instead of std::shared_ptr, the compiler will not let you copy a HouseParts object. I used slightly different formatting conventions, which is a matter of personal preference. Putting it all Together with Polymorphism You asked about this specific pattern. First, let’s create factory objects that return an abstract data types. So let’s define an AbstractHouseParts interface, which encapsulates any kind of object representing a window and a door. This example will have a pair of getter functions. class AbstractHouseParts { public: virtual ~AbstractHouseParts() = default; // Non-const getters: virtual AbstractWindow& window() = 0; virtual AbstractDoor& door() = 0; // const getters: virtual const AbstractWindow& window() const = 0; virtual const AbstractDoor& door() const = 0;
{ "domain": "codereview.stackexchange", "id": 42817, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns, abstract-factory", "url": null }
c++, design-patterns, abstract-factory Now, this interface (like the implementations of AbstractDoor and AbstractWindow above) violates the Rule of Three, because it declares a user-provided destructor without a user-provided copy constructor or assignment operator. The way around this is to add some more boilerplate to the end of the class: protected: /* Declare the constructors and assignment protected, so this class * cannot be instantiated, except through a daughter class. */ AbstractHouseParts() = default; AbstractHouseParts(const AbstractHouseParts&) = default; AbstractHouseParts(AbstractHouseParts&&) = default; AbstractHouseParts& operator= (const AbstractHouseParts&) = default; AbstractHouseParts& operator= (AbstractHouseParts&&) = default; }; We can’t delete any of these operations or declare them private, because then daughter classes can’t implicitly access them. If you don’t care about having the compiler prevent you from creating an instance of your abstract base class, you could declare them public:. As it is, any of these that we want the child classes to implement need to be redeclared as public in the children. We still declare HouseParts as a class template, but now each specialization of the template inherits from AbstractHouseParts. We therefore can store one in an AbstractHouseParts& reference or an AbstractHouseParts* pointer. We remove all the pointers from the HouseParts class template itself and store a pair of objects inside. if we need something moveable, we create a smart pointer to HouseParts. template < is_a_window WindowT, is_a_door DoorT > class HouseParts : public AbstractHouseParts Which contains overrides of the abstract interface and the data members private: WindowT m_window; DoorT m_door; Putting it all together again, we now get: #include <concepts> #include <iostream> #include <memory> #include <string> #include <utility> using namespace std::literals::string_literals;
{ "domain": "codereview.stackexchange", "id": 42817, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns, abstract-factory", "url": null }
c++, design-patterns, abstract-factory using namespace std::literals::string_literals; class AbstractDoor { public: // An abstract base class needs a virtual destructor. virtual ~AbstractDoor() = default; virtual const std::string& to_string() const = 0; protected: /* We declare the default constructors and assignment protected, so * that this class cannot be instantiated, except through a daughter * class. */ AbstractDoor() = default; AbstractDoor(const AbstractDoor&) = default; AbstractDoor& operator= (const AbstractDoor&) = default; }; std::ostream& operator<< ( std::ostream& os, const AbstractDoor& door ) { return os << door.to_string(); } class AbstractWindow { public: virtual ~AbstractWindow() = default; virtual const std::string& to_string() const = 0; protected: /* We declare the default constructors and assignment protected, so * that this class cannot be instantiated, except through a daughter * class. */ AbstractWindow() = default; AbstractWindow(const AbstractWindow&) = default; AbstractWindow& operator= (const AbstractWindow&) = default; }; std::ostream& operator<< ( std::ostream& os, const AbstractWindow& window ) { return os << window.to_string(); } class WoodDoor : public AbstractDoor { public: // Default what was hidden in the base. WoodDoor() = default; WoodDoor(const WoodDoor&) = default; WoodDoor& operator= (const WoodDoor&) = default; // And by the rule of three: ~WoodDoor() override = default; const std::string& to_string() const override { static const std::string message = "This is a wooden door."s; return message; } };
{ "domain": "codereview.stackexchange", "id": 42817, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns, abstract-factory", "url": null }
c++, design-patterns, abstract-factory class GumDoor : public AbstractDoor { public: // Default what was hidden in the base. GumDoor() = default; GumDoor(const GumDoor&) = default; GumDoor& operator= (const GumDoor&) = default; // And by the rule of three: ~GumDoor() override = default; const std::string& to_string() const override { static const std::string message = "This is a gum door."s; return message; } }; class WoodWindow : public AbstractWindow { public: // Default what was hidden in the base. WoodWindow() = default; WoodWindow(const WoodWindow&) = default; WoodWindow& operator= (const WoodWindow&) = default; // And by the rule of three: ~WoodWindow() override = default; const std::string& to_string() const override { static const std::string message = "This is a wooden window."s; return message; } }; class GumWindow : public AbstractWindow { public: // Default what was hidden in the base. GumWindow() = default; GumWindow(const GumWindow&) = default; GumWindow& operator= (const GumWindow&) = default; // And by the rule of three: ~GumWindow() override = default; const std::string& to_string() const override { static const std::string message = "This is a gum window."s; return message; } }; template<class WindowT> concept is_a_window = std::derived_from< WindowT, AbstractWindow >; template<class DoorT> concept is_a_door = std::derived_from< DoorT, AbstractDoor >; class AbstractHouseParts { public: virtual ~AbstractHouseParts() = default; // Non-const getters: virtual AbstractWindow& window() = 0; virtual AbstractDoor& door() = 0; // const getters: virtual const AbstractWindow& window() const = 0; virtual const AbstractDoor& door() const = 0;
{ "domain": "codereview.stackexchange", "id": 42817, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns, abstract-factory", "url": null }
c++, design-patterns, abstract-factory protected: /* Declare the constructors and assignment protected, so this class * cannot be instantiated, except through a daughter class. */ AbstractHouseParts() = default; AbstractHouseParts(const AbstractHouseParts&) = default; AbstractHouseParts(AbstractHouseParts&&) = default; AbstractHouseParts& operator= (const AbstractHouseParts&) = default; AbstractHouseParts& operator= (AbstractHouseParts&&) = default; }; template < is_a_window WindowT, is_a_door DoorT > class HouseParts : public AbstractHouseParts { public: // By the Rule of Five: HouseParts(const HouseParts&) = default; HouseParts(HouseParts&&) = default; HouseParts& operator= (const HouseParts&) = default; HouseParts& operator= (HouseParts&&) = default; ~HouseParts() override = default; // Declare the constructor we use: HouseParts( const WindowT& w, const DoorT& d ) : m_window(w), m_door(d) {} // This is what actually gets called: HouseParts( WindowT&& w, DoorT&& d ) : m_window(std::move(w)), m_door(std::move(d)) {} AbstractWindow& window() override { return m_window; } AbstractDoor& door() override { return m_door; } const AbstractWindow& window() const override { return m_window; } const AbstractDoor& door() const override { return m_door; } private: WindowT m_window; DoorT m_door; }; template< is_a_window WindowT, is_a_door DoorT > class HousePartsFactory { public: static HouseParts< WindowT, DoorT > build() { return{ WindowT(), DoorT() }; } }; #include <cstdlib> int main() { using std::cout; std::cout << "Let's build a wooden window and gum door!\n"; const auto parts = HousePartsFactory< WoodWindow, GumDoor >::build(); const AbstractHouseParts& abstract = parts; cout << abstract.window() << ' ' << abstract.door() << '\n'; return EXIT_SUCCESS; }
{ "domain": "codereview.stackexchange", "id": 42817, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns, abstract-factory", "url": null }
c++, design-patterns, abstract-factory return EXIT_SUCCESS; } This has no function to explicitly create a generic object, because the abstract interface is the superclass of all the objects the factory creates, and therefore you can just assign their return values to an abstract reference or pointer. This implementation has no ability to set its data members after the class is created, but you could also turn a class with a unique_ptr<AbstractWindow> and a unique_ptr<AbstractDoor> into a kind of generic placeholder. It could set these two generic smart pointers to reference any type of window and any type of door, so you could write generic setters for it. Hiding the default constructors, to make the compiler stop us from accidentally instantiating an abstract base class, required a significant amount of boilerplate. So, decide if that’s worth it. Putting it All Together One Last Time What you originally had, though, was not a static factory that creates abstract objects (or objects that implicitly convert to an abstract base class), but an abstract factory type with polymorphic subclasses representing different types of factory. Maybe you want a data structure representing arbitrary factory classes at runtime. This can still be done. Since the abstract interface does not know at compile time what type a factory will create, the factory member function must return a smart pointer to the abstract datatype, which will be automatically destroyed when its lifetime expires. The AbstractHousePartsFactory abstract base class therefore has one function in its interface, plus boilerplate. virtual std::unique_ptr<AbstractHouseParts> build() = 0; The HousePartsFactory class template now inherits from it: template< is_a_window WindowT, is_a_door DoorT > class HousePartsFactory : public AbstractHousePartsFactory
{ "domain": "codereview.stackexchange", "id": 42817, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns, abstract-factory", "url": null }
c++, design-patterns, abstract-factory Its implementation of .build() essentially wraps the code I wrote above, to implicitly convert a smart pointer of a daughter class to a smart pointer of the parent class. std::unique_ptr<AbstractHouseParts> build() override { return std::make_unique<HouseParts< WindowT, DoorT >>(); } It turns out I'd protected the default constructor of HouseParts, though, so I needed to go back to the HouseParts class definition and re-declare HouseParts() = default as public for this to work. Finally, I made the statically-typed factory member from before available as a static constexpr member function, renamed buildStatic(). This lets you still use it when you don’t need polymorphism. The full, compilable code: This has a test driver that stores different types of factories in a data structure, then the polymorphic output of each factory in another, with automatic memory management. #include <concepts> #include <iostream> #include <memory> #include <string> #include <utility> using namespace std::literals::string_literals; class AbstractDoor { public: // An abstract base class needs a virtual destructor. virtual ~AbstractDoor() = default; virtual const std::string& to_string() const = 0; protected: /* We declare the default constructors and assignment protected, so * that this class cannot be instantiated, except through a daughter * class. */ AbstractDoor() = default; AbstractDoor(const AbstractDoor&) = default; AbstractDoor& operator= (const AbstractDoor&) = default; }; std::ostream& operator<< ( std::ostream& os, const AbstractDoor& door ) { return os << door.to_string(); } class AbstractWindow { public: virtual ~AbstractWindow() = default; virtual const std::string& to_string() const = 0;
{ "domain": "codereview.stackexchange", "id": 42817, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns, abstract-factory", "url": null }
c++, design-patterns, abstract-factory virtual const std::string& to_string() const = 0; protected: /* We declare the default constructors and assignment protected, so * that this class cannot be instantiated, except through a daughter * class. */ AbstractWindow() = default; AbstractWindow(const AbstractWindow&) = default; AbstractWindow& operator= (const AbstractWindow&) = default; }; std::ostream& operator<< ( std::ostream& os, const AbstractWindow& window ) { return os << window.to_string(); } class WoodDoor : public AbstractDoor { public: // Default what was hidden in the base. WoodDoor() = default; WoodDoor(const WoodDoor&) = default; WoodDoor& operator= (const WoodDoor&) = default; // And by the rule of three: ~WoodDoor() override = default; const std::string& to_string() const override { static const std::string message = "This is a wooden door."s; return message; } }; class GumDoor : public AbstractDoor { public: // Default what was hidden in the base. GumDoor() = default; GumDoor(const GumDoor&) = default; GumDoor& operator= (const GumDoor&) = default; // And by the rule of three: ~GumDoor() override = default; const std::string& to_string() const override { static const std::string message = "This is a gum door."s; return message; } }; class WoodWindow : public AbstractWindow { public: // Default what was hidden in the base. WoodWindow() = default; WoodWindow(const WoodWindow&) = default; WoodWindow& operator= (const WoodWindow&) = default; // And by the rule of three: ~WoodWindow() override = default; const std::string& to_string() const override { static const std::string message = "This is a wooden window."s; return message; } };
{ "domain": "codereview.stackexchange", "id": 42817, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns, abstract-factory", "url": null }
c++, design-patterns, abstract-factory class GumWindow : public AbstractWindow { public: // Default what was hidden in the base. GumWindow() = default; GumWindow(const GumWindow&) = default; GumWindow& operator= (const GumWindow&) = default; // And by the rule of three: ~GumWindow() override = default; const std::string& to_string() const override { static const std::string message = "This is a gum window."s; return message; } }; template<class WindowT> concept is_a_window = std::derived_from< WindowT, AbstractWindow >; template<class DoorT> concept is_a_door = std::derived_from< DoorT, AbstractDoor >; class AbstractHouseParts { public: virtual ~AbstractHouseParts() = default; // Non-const getters: virtual AbstractWindow& window() = 0; virtual AbstractDoor& door() = 0; // const getters: virtual const AbstractWindow& window() const = 0; virtual const AbstractDoor& door() const = 0; protected: /* Declare the constructors and assignment protected, so this class * cannot be instantiated, except through a daughter class. */ AbstractHouseParts() = default; AbstractHouseParts(const AbstractHouseParts&) = default; AbstractHouseParts(AbstractHouseParts&&) = default; AbstractHouseParts& operator= (const AbstractHouseParts&) = default; AbstractHouseParts& operator= (AbstractHouseParts&&) = default; }; template < is_a_window WindowT, is_a_door DoorT > class HouseParts : public AbstractHouseParts { public: // By the Rule of Five: HouseParts(const HouseParts&) = default; HouseParts(HouseParts&&) = default; HouseParts& operator= (const HouseParts&) = default; HouseParts& operator= (HouseParts&&) = default; ~HouseParts() override = default;
{ "domain": "codereview.stackexchange", "id": 42817, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns, abstract-factory", "url": null }
c++, design-patterns, abstract-factory // Declare the constructor we use: HouseParts() = default; HouseParts( const WindowT& w, const DoorT& d ) : m_window(w), m_door(d) {} HouseParts( WindowT&& w, DoorT&& d ) : m_window(std::move(w)), m_door(std::move(d)) {} AbstractWindow& window() override { return m_window; } AbstractDoor& door() override { return m_door; } const AbstractWindow& window() const override { return m_window; } const AbstractDoor& door() const override { return m_door; } private: WindowT m_window; DoorT m_door; }; class AbstractHousePartsFactory { public: virtual ~AbstractHousePartsFactory() = default; // Not const, because some implementations might want to modify it. virtual std::unique_ptr<AbstractHouseParts> build() = 0; protected: /* As before, only a daughter class can be created. */ AbstractHousePartsFactory() = default; AbstractHousePartsFactory(const AbstractHousePartsFactory&) = default; AbstractHousePartsFactory& operator= (const AbstractHousePartsFactory&) = default; }; template< is_a_window WindowT, is_a_door DoorT > class HousePartsFactory : public AbstractHousePartsFactory { public: // Allow this implementation to be created. HousePartsFactory() = default; // By the Rule of Three: HousePartsFactory(const HousePartsFactory&) = default; HousePartsFactory& operator= (const HousePartsFactory&) = default; ~HousePartsFactory() override = default; std::unique_ptr<AbstractHouseParts> build() override { return std::make_unique<HouseParts< WindowT, DoorT >>(); } static constexpr HouseParts< WindowT, DoorT > buildStatic() { return{ WindowT(), DoorT() }; } }; #include <cstdlib>
{ "domain": "codereview.stackexchange", "id": 42817, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns, abstract-factory", "url": null }
c++, design-patterns, abstract-factory #include <cstdlib> int main() { using std::cout; // A data structure holding arbitrary types of factory: const std::unique_ptr<AbstractHousePartsFactory> factories[] = { std::make_unique<HousePartsFactory<WoodWindow, GumDoor>>(), std::make_unique<HousePartsFactory<GumWindow, WoodDoor>>() }; const std::unique_ptr<const AbstractHouseParts> outputs[] = { factories[0]->build(), factories[1]->build() }; cout << outputs[0]->window() << ' ' << outputs[0]->door() << '\n' << outputs[1]->window() << ' ' << outputs[1]->door() << '\n'; return EXIT_SUCCESS; }
{ "domain": "codereview.stackexchange", "id": 42817, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, design-patterns, abstract-factory", "url": null }
c++, template-meta-programming, c++20 Title: An rough implementation of `std::is_constructible` Question: As a challenge/fun activity/task, I have implemented my version of std::is_constructible. Here is the source code: #include <cbrainx/cbrainx.hpp> #include <iostream> template <typename T, typename ...V> auto aux(long) -> cbx::false_type; template <typename T, typename ...V> static auto aux(int) -> cbx::type_switch_t< cbx::branch<cbx::false_type, cbx::detail::void_t<decltype(::new(cbx::declval<void *>()) T{cbx::declval<V>()...})>>, cbx::otherwise<cbx::true_type>>; template <typename T, typename ...V> auto is_constructible() -> decltype(aux<T, V...>(0)); struct X { X() { std::cout << "constructed..." << std::endl; } private: X(int) { } public: X(const X &) = delete; X(X &&) {} ~X() { std::cout << "destroyed..." << std::endl; } static void xd() { X{1}; std::cout << decltype(is_constructible<X, int>())::value << std::endl; } }; auto main() -> int { std::cout << std::boolalpha; std::cout << decltype(is_constructible<X, X>())::value << std::endl; std::cout << decltype(is_constructible<X, X &>())::value << std::endl; std::cout << decltype(is_constructible<X, X &&>())::value << std::endl; return 0; } IMPORTANT: cbx::false_type is equivalent to std::false_type. It has a value of type bool. Likewise cbx::true_type. cbx::type_switch_t is equivalent to switch clause but, for types and evaluated statically at compile time. cbx::branch is like the if branch. The first argument is the condition and must have a value of type bool. The second argument is the type itself. cbx::otherwise is like the else branch. Things I know It does not work for private constructors. (I am okay with that!) It's a rough implementation. Things I want to know Is this implementation correct? Am I missing anything? How close it is to the actual std::is_constructible? How can I improve? C++ Standard: 20
{ "domain": "codereview.stackexchange", "id": 42818, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template-meta-programming, c++20", "url": null }
c++, template-meta-programming, c++20 C++ Standard: 20 Answer: It would help to cleanly separate your is_constructible from the "test harness" code that follows it — either with a //----- comment, or by putting your thing in a namespace, or something. Your thing is a function template, whereas the standard std::is_constructible is a type-trait (that is, a class template). Without seeing the definitions of branch, otherwise, etc., it's hard to judge whether your code is even correct, let alone performant. You name both your template parameter T and your parameter pack V... with singular names. It would be helpful to name the pack with a plural name, e.g. Vs... or Args.... Your unit tests take the form of std::cout << foo. Prefer to use static_assert(foo), so that the compiler will tell you whether your tests passed or failed — you shouldn't have to eyeball the terminal output to tell whether you implemented is_constructible right! You should become familiar with the traditional SFINAE idioms. For a simple type-trait like is_constructible, where all you want to know is whether a particular expression is well-formed, the idiom is template<class T, class = void> struct is_fooable : std::false_type {}; template<class T> struct is_fooable<T, decltype(( your-expression-here ), void())> : std::true_type {}; Or, since you tagged this question c++20, you could just use a requires-expression: template<class T> struct is_fooable : std::bool_constant<requires { your-expression-here; }> {}; In the specific case of is_constructible, the expression you care about is new T(args...). So you might write template<class, class T, class... Args> struct is_constructible_impl : std::false_type {}; template<class T, class... Args> struct is_constructible_impl<decltype(( new T(std::declval<Args>()...) ), void()), T, Args...> : std::true_type {}; template<class T, class... Args> struct is_constructible : is_constructible_impl<void, T, Args...> {};
{ "domain": "codereview.stackexchange", "id": 42818, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template-meta-programming, c++20", "url": null }
c++, template-meta-programming, c++20 Or: template<class T, class... Args> struct is_constructible : std::bool_constant<requires (Args&&... args) { new T(static_cast<Args&&>(args)...); }> {}; (Godbolt.) By writing unit tests and comparing them to the standard std::is_constructible, we soon find a problem: std::is_constructible<int&, int&>::value is true, but our new T(args...) formulation yields false, because you can't new a reference type. Solving this problem is left as an exercise for the reader, because I'm too lazy to look it up right now. :)
{ "domain": "codereview.stackexchange", "id": 42818, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template-meta-programming, c++20", "url": null }
python, networking, twitter, benchmarking, status-monitoring Title: Send a tweet to ISP when internet speed drops Question: I have written an app in Python 3 which monitors internet speed and will send a tweet to an ISP when the speed drops too low. The app has a config file where the ISP and target speeds can be configured. The program has two threads running simultaneously. SpeedTestThread monitors internet speeds at set intervals using python module speedtest-cli. TwitterThread uses tweepy to send tweets containing data from speed tests. When SpeedTestThread gets speeds below threshold the data is pushed to tweet_data_queue and the global tweetFlag is set. TwitterThread monitors the tweetFlag and, when set, retrieves the data from the queue and generates a tweet using it. I have removed the docstrings to save space; they can be found in my Github repository. speed_test.py: import speedtest import json import time import csv import os import threading import queue import tweepy import random config = json.load(open('config.json')) exitFlag = 0 tweetFlag = 0 # Global queue for tweet data, shared between threads tweet_data_queue = queue.Queue() def main(): error_logger = ErrorLogger(config['errorFilePath']) test_thread = SpeedTestThread(1, "SpeedTestThread1", error_logger) tweet_thread = TwitterThread(2, "TwitterThread1", error_logger) test_thread.start() tweet_thread.start() class SpeedTestThread(threading.Thread): def __init__(self, thread_id, name, error_logger): threading.Thread.__init__(self) self.name = name self.thread_id = thread_id self.s = speedtest.Speedtest() self.targetSpeeds = config['internetSpeeds'] self.dataLogger = ErrorLogger(config['logFilePath']) self.error_logger = error_logger
{ "domain": "codereview.stackexchange", "id": 42819, "lm_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, networking, twitter, benchmarking, status-monitoring", "url": null }
python, networking, twitter, benchmarking, status-monitoring def run(self): global exitFlag prevError = False while exitFlag == 0: try: results = self.getSpeeds() self.checkSpeeds(results) self.dataLogger.logCsv(results) except Exception as e: error = {"time": time.ctime(), "error": "Unable to retrieve results", "exception": e} self.error_logger.logError(error) prevError = True if prevError: self.error_logger.counter = 0 time.sleep(config['testFreq']) def getSpeeds(self): self.s.get_best_server() self.s.upload() self.s.download() return self.s.results.dict() def checkSpeeds(self, results): global tweetFlag down = results['download'] up = results['upload'] ping = results['ping'] if (down / (2**20) < self.targetSpeeds['download'] or up / (2**20) < self.targetSpeeds['upload'] or ping > self.targetSpeeds['ping']): print("Unnaceptable speed results:\n" "Download: %s\n" "Upload: %s\n" "Ping: %s\n" % (down, up, ping)) tweetFlag = 1 tweet_data_queue.put(results) print("Results queued for tweet") class TwitterThread(threading.Thread): def __init__(self, thread_id, name, error_logger): threading.Thread.__init__(self) self.thread_id = thread_id self.name = name self.error_logger = error_logger # Set up tweepy with twitter API authentication self.apiData = config['twitterAPI'] auth = tweepy.OAuthHandler( self.apiData['apiKey'], self.apiData['apiSecret']) auth.set_access_token(self.apiData['accessToken'], self.apiData['accessTokenSecret']) self.twitterAPI = tweepy.API(auth)
{ "domain": "codereview.stackexchange", "id": 42819, "lm_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, networking, twitter, benchmarking, status-monitoring", "url": null }
python, networking, twitter, benchmarking, status-monitoring def run(self): global exitFlag global tweetFlag prevError = False while True: if exitFlag == 1: break if tweetFlag == 1: tweet = self.getTweet() try: self.twitterAPI.update_status(tweet) print("Tweet successful") except Exception as e: error = {"time": time.ctime(), "error": "Unable to send tweet", "exception": e} self.error_logger.logError(error) prevError = True if prevError: self.error_logger.counter = 0 if tweet_data_queue.qsize() == 0: tweetFlag = 0 def getTweet(self): data = tweet_data_queue.get() down = round(data['download'] / (2**20), 2) up = round(data['upload'] / (2**20), 2) content = random.choice(config['tweetContent']) return content.format(config['ispTwitter'], down, up) class Logger(object): def __init__(self, filepath): self.filepath = filepath def logCsv(self, data): print("Logging ...") with open(self.filepath, 'a') as f: writer = csv.DictWriter(f, fieldnames=data.keys()) if os.stat(self.filepath).st_size == 0: writer.writeheader() writer.writerow(data) print("Done -> '%s'" % self.filepath) class ErrorLogger(Logger): def __init__(self, filepath): Logger.__init__(self, filepath) self.counter = 0 def logError(self, errorData): global exitFlag if self.counter >= config['testAttempts']: exitFlag = 1 errorData['error'] = "10 Failed test attempts, exiting." self.counter = 0 print(errorData['error']) self.logCsv(errorData)
{ "domain": "codereview.stackexchange", "id": 42819, "lm_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, networking, twitter, benchmarking, status-monitoring", "url": null }
python, networking, twitter, benchmarking, status-monitoring Answer: Overall this is quite a nice module. Here are a few usability issues/nitpicks, though: When running the script, there is no easy way to stop it. CTRL+C does not work, I have to manually kill the process. This is probably because of how threading.Thread handles it, but I'm not sure. It would be nice if it was slightly easier to add a different handler than the tweeter. For example, I might want to send myself an email, instead of tweeting it right away. To fix this, you should remove all mentions of tweeting from the SpeedTestThread class and maybe define a general EventHandler class, from which TwitterThread derives, which calls some method action(self, up, down) which needs to be defined in the derived class. This way you can easily define a MailThread(EventHandler) with a different action method that sends a mail instead. You are mixing two variable naming styles, camelCase and lower_case_with_underscores. Python's official style-guide, PEP8, recommends sticking to the latter for all variables and functions/methods. Global constants should be in UPPER_CASE. For flags you should just use True and False, it is a bit easier to read. Note that you can do while not exitFlag: instead of while True: if exitFlag == 1: break and if prevError instead of if prevError == 1. You never increase your error_logger.counter, it should be if prevError: self.error_logger.counter += 1 else: self.error_logger.counter = 0.
{ "domain": "codereview.stackexchange", "id": 42819, "lm_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, networking, twitter, benchmarking, status-monitoring", "url": null }
c++, multithreading Title: Leaky Bucket algorithm with concurrency Question: Trying to mimic a scenario where multiple threads are creating the traffic to fill the buckets & a thread which leaks the bucket at a specified rate. Could you review this code? #include <iostream> #include <mutex> #include <condition_variable> #include <thread> #include <atomic> #include <chrono> using namespace std; class LeakyBucket { public: LeakyBucket(int size, int rate) : maxCapacity(size), leakRate(rate), filled(0) {} void add(int newDataSize) { unique_lock<mutex> lk(_mtx); _cond.wait(lk, [this](){ return filled<=maxCapacity; }); filled = (filled+newDataSize) > maxCapacity ? maxCapacity:(filled+newDataSize); cout<<"\n Filled bucket with : "<<newDataSize; cout<<"\n Filled: "<<filled<<"\n ----------"; _cond.notify_one(); } void leak() { while(1) { { unique_lock<mutex> lk(_mtx); _cond.wait(lk, [this]() { return filled > 0 || _done; }); if(_done) break; filled = (filled-leakRate<0) ? 0 : (filled-leakRate); cout << "\n Leaked bucket with leakRate"; cout << "\n BucketFilledRemain: " << filled << "\n ----------"; _cond.notify_one(); } _sleep: this_thread::sleep_for(chrono::seconds(1)); } } bool _done = false; private: atomic<int> filled; int maxCapacity; int leakRate; // Per second mutex _mtx; condition_variable _cond; }; void runLeakyBucketAlgorithm() { LeakyBucket *lb = new LeakyBucket(30, 20);
{ "domain": "codereview.stackexchange", "id": 42820, "lm_label": 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", "url": null }
c++, multithreading }; void runLeakyBucketAlgorithm() { LeakyBucket *lb = new LeakyBucket(30, 20); thread t1(&LeakyBucket::leak, lb); thread t2([&](){ for(int i=0; i<10; i++) { cout<<"\n launching thread: "<<i; lb->add(rand()%40); } this_thread::sleep_for(chrono::seconds(5)); lb->_done = true; }); if(t2.joinable()) { t2.join(); } t1.join(); } O/P launching thread: 0 Filled bucket with : 7 Filled: 7 ---------- launching thread: 1 Filled bucket with : 9 Filled: 16 ---------- launching thread: 2 Leaked bucket with leakRate BucketFilledRemain: 0 ---------- Filled bucket with : 33 Filled: 30 ---------- launching thread: 3 Filled bucket with : 18 Filled: 30 ---------- launching thread: 4 Filled bucket with : 10 Filled: 30 ---------- launching thread: 5 Filled bucket with : 32 Filled: 30 ---------- launching thread: 6 Filled bucket with : 24 Filled: 30 ---------- launching thread: 7 Filled bucket with : 38 Filled: 30 ---------- launching thread: 8 Filled bucket with : 3 Filled: 30 ---------- launching thread: 9 Filled bucket with : 29 Filled: 30 ---------- Leaked bucket with leakRate BucketFilledRemain: 10 ---------- Leaked bucket with leakRate BucketFilledRemain: 0 Answer: Avoid leading underscores in names Some uses of underscores are reserved by the standard, I recommend just avoiding all leading underscores in names. Also, why do only some member variables have a leading underscore? If you are going to use them, be consistent. Add a newline at the end of each line When printing, add the newline at the end of each line instead of at the start. This ensures whatever comes next (which might be an error message, or the shell's prompt if your program ends) starts on its own line. Make use of std::min() Instead of using a ternary expression, use std::min() if you want to limit some value. For example: filled = std::min(filled + newDataSize, maxCapacity);
{ "domain": "codereview.stackexchange", "id": 42820, "lm_label": 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", "url": null }
c++, multithreading This avoids having to repeat yourself. Avoid needing signed integers The current fill level, the maximum capacity and the leak reate should all be non-negative numbers. Consider using unsigned ints for them. You should also then avoid subtracting values if the result could be negative. Instead, find a way to do everything with non-negative values, like so in leak(): filled -= std::min(leakRate, filled); Unnecessary use of new There is no reason to use new to create an instance of a LeakyBucket inside runLeakyBucketAlgorithm(). You can just declare it on the stack: void runLeakyBucketAlgorithm() { LeakyBucket lb(30, 20); thread t1(&LeakyBucket::leak, &lb); ... }; Redesigning the leaky part Adding things to the bucket is done nicely. However, the leaking part is not very useful at the moment, and it also requires the user to create a thread themselves. I would redesign this in one of two ways: Add a callback function that is called when leaking It would be nice if the user of a LeakyBucket didn't have to know anything about threads, but still be able to tell the bucket what to do when it leaks. You can move thread management to the constructor and destructor of LeakyBucket, and add a callback function as a parameter to the constructor. This way, you could use it like so: LeakyBucket lb(30, 20, [](unsigned int leaked) { std::cout << "Bucket leaked " << leaked << " units\n"; }); Let leak() return how much has leaked Instead of letting leak() be an infinite loop that has to run in its own thread, consider making leak() similar to add(), but instead of telling it how much to add, have it return how much has leaked since the last call to leak(). This way, the caller can decide how long to sleep, if at all: LeakyBucket lb(30, 20); std::thread t1([&]() { for (int i = 0; i < 60; i++) { std::cout << "Bucket leaked " << lb.leak() << " units\n"; std::this_thread::sleep_for(std::chrono::seconds(1)); } });
{ "domain": "codereview.stackexchange", "id": 42820, "lm_label": 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", "url": null }
c++, multithreading Accurate timing std::this_thread::sleep_for() does not guarantee it will sleep exactly for the duration you specified. And even if it did, all the other operations you are doing inside the loop in leak() also take some time. So in effect, you are leaking a bit slower than you specified. It should be possible to get the current time and compare it to the time from the last iteration of the loop, and this way more accurately account for the passage of time. For sure you need to do something like this if you want to implement the version of leak() that returns how much has leaked since the last call.
{ "domain": "codereview.stackexchange", "id": 42820, "lm_label": 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", "url": null }
beginner, c, programming-challenge, sorting Title: CodeForce 230 Dragon Fighting, Sorting without using array Question: Problem: https://codeforces.com/problemset/problem/230/A Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all \$n\$ dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito's strength equals \$s\$. If Kirito starts duelling with the i-th (1 ≤ i ≤ n) dragon and Kirito's strength is not greater than the dragon's strength \$x_i\$, then Kirito loses the duel and dies. But if Kirito's strength is greater than the dragon's strength, then he defeats the dragon and gets a bonus strength increase by \$y_i\$. Kirito can fight the dragons in any order. Determine whether he can move on to the next level of the game, that is, defeat all dragons without a single loss. Input The first line contains two space-separated integers \$s\$ and \$n\$ (\$1 ≤ s ≤ 10^4, 1 ≤ n ≤ 10^3\$). Then \$n\$ lines follow: the i-th line contains space-separated integers \$x_i\$ and \$y_i\$ (\$1 ≤ x_i ≤ 10^4, 0 ≤ y_i ≤ 10^4\$) — the i-th dragon's strength and the bonus for defeating it. Output On a single line print "YES" (without the quotes), if Kirito can move on to the next level and print "NO" (without the quotes), if he can't. Examples Input 2 2 1 99 100 0 Output YES Input 10 1 100 100 Output NO Note: In the first sample Kirito's strength initially equals 2. As the first dragon's strength is less than 2, Kirito can fight it and defeat it. After that he gets the bonus and his strength increases to 2 + 99 = 101. Now he can defeat the second dragon and move on to the next level. In the second sample Kirito's strength is too small to defeat the only dragon and win.
{ "domain": "codereview.stackexchange", "id": 42821, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, programming-challenge, sorting", "url": null }
beginner, c, programming-challenge, sorting I have used array to solve the problem. What I have tried[accepted but I didn't like my solution]: #include<stdio.h> int main(void) { int i=0, j=0, k=0, l=0, count=0; int myStrength, testCase; int dragonStrength[1000], killingBonus[1000]; scanf("%d%d", &myStrength, &testCase); for(k=0; k<testCase; k++){ scanf("%d%d", &dragonStrength[k], &killingBonus[k]); } while(l<testCase){ i=0, j=0; while(i<testCase && j<testCase){ if(myStrength>dragonStrength[j] && dragonStrength[j]!=-1){ myStrength = myStrength + killingBonus[j]; dragonStrength[j] = -1; count++; } i++; j++; } l++; } if(count==testCase){ printf("YES"); }else{ printf("NO"); } return 0; } I want to solve it without using array. Answer: There are many things besides properly formatting the code that would improve it. Complexity The function main() is too complex (does too much). This isn't clear in this program because it is simple, but as programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program. There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states: that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function. There are at least 2 possible functions in main(). Get the user input Sort the input #define MAX_DUELS 1000
{ "domain": "codereview.stackexchange", "id": 42821, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, programming-challenge, sorting", "url": null }
beginner, c, programming-challenge, sorting Get the user input Sort the input #define MAX_DUELS 1000 void get_input(int *testCase, int *myStrength, int dragonStrength[MAX_DUELS], int killingBonus[MAX_DUELS]) { scanf("%d%d", &myStrength, &testCase); int k = 0; for(k=0; k<testCase; k++){ scanf("%d%d", &dragonStrength[k], &killingBonus[k]); } } int sort_input_and_count_wins(int testCase, int myStrength, int dragonStrength[MAX_DUELS], int killingBonus[MAX_DUELS]) { int wins = 0; int l = 0; while(l < testCase){ int i = 0; int j = 0; while(i < testCase && j < testCase){ if(myStrength>dragonStrength[j] && dragonStrength[j] != -1){ myStrength = myStrength + killingBonus[j]; dragonStrength[j] = -1; wins++; } i++; j++; } l++; } return wins; } int main(void) { int myStrength; int testCase; int dragonStrength[MAX_DUELS]; int killingBonus[MAX_DUELS]; get_input(&testCase, &myStrength, dragonStrength, killingBonus); int wins = sort_input_and_count_wins(testCase, myStrength, dragonStrength, killingBonus) if(wins == testCase){ puts("YES"); }else{ puts("NO"); } }
{ "domain": "codereview.stackexchange", "id": 42821, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, programming-challenge, sorting", "url": null }
beginner, c, programming-challenge, sorting Declare the Variables as Needed In the original version of C back in the 1970s and 1980s variables had to be declared at the top of the function. That is no longer the case, and a recommended programming practice to declare the variable as needed. In C the language doesn't provide a default initialization of the variable so variables should be initialized as part of the declaration. For readability and maintainability each variable should be declared and initialized on its own line. See the declarations in the above example. Magic Numbers There are Magic Numbers in the main() function (1000), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier. Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow. Horizontal Spacing To make code more readable a common practice is to leave spaces between operands and operators in expressions.
{ "domain": "codereview.stackexchange", "id": 42821, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, programming-challenge, sorting", "url": null }
python, python-3.x, object-oriented, physics Title: Python: Class to calculate different variables of a projectile motion with angle, velocity (+ initial height) (first OOP program) Question: I'd like to hear your constructive criticisms about my first OOP project. I explain more what I actually do in the code's comments, and I tried to be quite explanatory with names etc. import math as m class projectileMotion(): """ This class calculate the movement of a projectile using its initial velocity and the angle at witch it is thrown/shot. The initial height of the projectile is 0 by default but can be set by the user when creating an instance. The friction forces are neglected, thus the only formula used is the following: # △X = x0 + v_x⋅△t - a_x/2⋅△t^2 (and some of its variations) """ n_steps = 5 #small here for testing purpose. Between 30 and 50 for more accuracy g = 9.81 def __init__(self, velocity, angle, y_init=0): self.y_init = y_init self.angle_init = angle self.velocity_init = velocity self.vx_init = self.calc_vx_init() #Turn the angled velocity vector self.vy_init = self.calc_vy_init() #into two normal velocity vectors. self.dt, self.dt_vect = self.calc_dt_and_vect() self.dx, self.dx_vect = self.calc_dx_and_vect() self.dy, self.dy_vect = self.calc_dy_and_vect() self.coords_max_y = self.coords_when_y_is_maximum() self.pos_vect = self.gives_pos_vect() def calc_vx_init(self): return self.velocity_init * m.cos(m.radians(self.angle_init)) def calc_vy_init(self): return self.velocity_init * m.sin(m.radians(self.angle_init))
{ "domain": "codereview.stackexchange", "id": 42822, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, physics", "url": null }
python, python-3.x, object-oriented, physics def calc_vy_init(self): return self.velocity_init * m.sin(m.radians(self.angle_init)) def calc_dt_and_vect(self): """ t_total = time taken for the object to fall on the ground (y=0) t_total = (vy + sqrt(vy**2 + 2*y0*g)) / g dt_vect contains the time at n_steps, the first one being 0 => need to divide by n_steps-1 """ dt = (self.vy_init + m.sqrt(self.vy_init**2 + 2*self.y_init*self.g))/self.g return dt, [(dt/(self.n_steps-1))*i for i in range(self.n_steps)] def calc_dx_and_vect(self): dx_vect = [self.vx_init*t for t in self.dt_vect] dx = dx_vect[len(dx_vect)-1] return dx, dx_vect def calc_dy_and_vect(self): dy_vect = [(self.y_init + self.vy_init*t - self.g/2*t**2) for t in self.dt_vect] dy = dy_vect[len(dy_vect)-1] - self.y_init return dy, dy_vect def coords_when_y_is_maximum(self): """ max_y atteined when vy - g*t = 0 (when the velocity induced by gravity = vy) """ max_y_t = self.vy_init/self.g x = max_y_t*self.vx_init y = self.y_init + self.vy_init*max_y_t - self.g/2 * max_y_t**2 return (x, y) def gives_pos_vect(self): return list(zip(self.dx_vect, self.dy_vect)) if __name__ == '__main__': obj = projectileMotion(velocity=10, angle=30, y_init=5) for k, val in obj.__dict__.items(): print(k, val, "\n\n") Now, this is a second file I used to try doing things with the class. I include it as well since you could have things to say about the way I do things. from projectile_oop_v2 import projectileMotion
{ "domain": "codereview.stackexchange", "id": 42822, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, physics", "url": null }
python, python-3.x, object-oriented, physics def find_best_angle(speed, y0): """ Find the angle at which the thow goes the farthest """ max_distance = 0 for angle in range(50): distance = projectileMotion(angle=angle, velocity=speed, y_init=y0).dx if distance > max_distance: max_distance = distance best_angle = angle return (speed, y0, round(max_distance,1), best_angle) speed_y0_distance_best_angle = [] for speed in range(1, 101): y0 = speed speed_y0_distance_best_angle.append(find_best_angle(speed, y0)) """Could then be processed to make graphs and whatnot""" for line in speed_y0_distance_best_angle: print(line) Note: a run() method will most likely be added instead of running everything in the initialization. But you can still comment on that ;) As a beginner, any genuine advice is a blessing, so please feel free to share all your thoughts.
{ "domain": "codereview.stackexchange", "id": 42822, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, physics", "url": null }
python, python-3.x, object-oriented, physics Answer: projectileMotion should be ProjectileMotion by PEP8. Don't alias math as m; math should be fine for your purposes. You need to somehow document - either by comment or by variable name - that the angle you accept is in degrees. Technically you don't accept "velocity", since velocity is a vector; you're accepting speed. When you break it down into vector components, then it's velocity. Your class currently stores more than it should as state. It should only contain enough to "define the curve", rather than storing the entire curve itself. Add PEP484 type hints. Consider using generator functions instead of lists when you do iterate over time. "Coordinates when Y is maximum" is just called the "apex", which is more terse. Grammar: "this class calculate" -> "this class calculates"; "witch" -> "which". Your best-angle calculation is brute-force, and an analytical solution is feasible (though I don't know what your level of math is, so you might find it tricky to derive on your own). I adapted a solution from Henelsmith 2016 which describes the problem in great detail. I don't think it's a good idea to dump your object via blind __dict__ iteration. Make a proper description method. Your g = 9.81 is technically not the standard gravitational acceleration constant at sea level, and should instead be 9.80665. Could then be processed to make graphs and whatnot Indeed; matplotlib makes this easy. Suggested import math from numbers import Real from typing import Iterator from matplotlib import pyplot as plt class ProjectileMotion: """ This class calculates the movement of a projectile using its initial velocity and the angle at which it is thrown/shot. The initial height of the projectile is 0 by default but can be set by the user when creating an instance. The friction forces are neglected, thus the only formula used is the following: # △X = x0 + v_x⋅△t - a_x/2⋅△t^2 (and some of its variations) """ G = 9.80665
{ "domain": "codereview.stackexchange", "id": 42822, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, physics", "url": null }
python, python-3.x, object-oriented, physics def __init__(self, speed0: Real = 1, angle0_degrees: Real = 45, y0: Real = 0) -> None: self.y0 = y0 self.angle0 = math.radians(angle0_degrees) self.vx0, self.vy0 = self._get_v0(speed0) self.t_apex = self._get_apex_time() self.t1 = self._get_t1() def _get_v0(self, speed0: Real) -> tuple[float, float]: return ( speed0 * math.cos(self.angle0), speed0 * math.sin(self.angle0), ) def _get_t1(self) -> float: """ t_total = time taken for the object to fall on the ground (y=0) t_total = (vy + sqrt(vy**2 + 2*y0*g)) / g """ return ( self.vy0 + math.sqrt(self.vy0**2 + 2*self.y0*self.G) ) / self.G def get_t(self, n_steps: int) -> Iterator[float]: """ t_vect contains the time at n_steps, the first one being 0 => need to divide by n_steps-1 """ for i in range(n_steps): yield self.t1 * i / (n_steps - 1) def x_for_t(self, t: float) -> float: return self.vx0 * t def y_for_t(self, t: float) -> float: return self.y0 + self.vy0*t - self.G/2*t**2 def angle_for_t(self, t: float) -> float: return math.degrees(math.atan2( self.vy0 - t*self.G, self.vx0 )) @property def x1(self) -> float: return self.x_for_t(self.t1) def _get_apex_time(self) -> float: """ max_y attained when vy - g*t = 0 (when the velocity induced by gravity = vy) """ return self.vy0 / self.G def desc(self, n_steps: int = 10) -> str: return ( f'Curve over {n_steps} steps:' f'\n{"t":>5} {"x":>5} {"y":>5} {"angle°":>6}' f'\n' ) + '\n'.join( f'{t:>5.2f}' f' {self.x_for_t(t):>5.2f}' f' {self.y_for_t(t):>5.2f}' f' {self.angle_for_t(t):>6.1f}' for t in self.get_t(n_steps) )
{ "domain": "codereview.stackexchange", "id": 42822, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, physics", "url": null }
python, python-3.x, object-oriented, physics @classmethod def with_best_angle(cls, speed0: float, y0: float) -> 'ProjectileMotion': """ https://www.whitman.edu/Documents/Academics/Mathematics/2016/Henelsmith.pdf equations 12 & 13 h: initial height = y0 v: initial velocity magnitude = speed Impact coefficients m = 0, a = 0 arccotangent(x) = atan(1/x) """ g = ProjectileMotion.G v = speed0 angle = math.atan( 1/math.sqrt( 2*y0*g/v/v + 1 ) ) return cls( speed0=speed0, angle0_degrees=math.degrees(angle), y0=y0, ) def graph(motion: ProjectileMotion) -> plt.Figure: fig, ax_x = plt.subplots() ax_t: plt.Axes = ax_x.twiny() ax_x.set_title('Projectile Motion') times = tuple(motion.get_t(n_steps=100)) ax_x.plot( [motion.x_for_t(t) for t in times], [motion.y_for_t(t) for t in times], ) ax_x.set_xlabel('x') ax_t.set_xlabel('t') ax_x.set_ylabel('y') ax_x.set_xlim(left=0, right=motion.x_for_t(motion.t1)) ax_t.set_xlim(left=0, right=motion.t1) ax_x.set_ylim(bottom=0) return fig def simple_test() -> None: motion = ProjectileMotion(speed0=10, angle0_degrees=30, y0=5) print(motion.desc()) graph(motion) plt.show() def optimisation_test() -> None: for y0 in range(1, 102, 10): best = ProjectileMotion.with_best_angle(y0=y0, speed0=y0) print(f'speed0={y0:3} y0={y0:3} x1={best.x1:6.1f} ' f'angle0={math.degrees(best.angle0):.1f}') if __name__ == '__main__': print('Simple projectile test:') simple_test() print() print('Angle optimisation test:') optimisation_test()
{ "domain": "codereview.stackexchange", "id": 42822, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, physics", "url": null }
python, python-3.x, object-oriented, physics print('Angle optimisation test:') optimisation_test() Output Simple projectile test: Curve over 10 steps: t x y angle° 0.00 0.00 5.00 30.0 0.18 1.58 5.75 20.3 0.36 3.16 6.17 9.3 0.55 4.74 6.27 -2.4 0.73 6.32 6.04 -14.0 0.91 7.90 5.48 -24.5 1.09 9.47 4.60 -33.5 1.28 11.05 3.39 -41.0 1.46 12.63 1.86 -47.1 1.64 14.21 0.00 -52.0 Angle optimisation test: speed0= 1 y0= 1 x1= 0.5 angle0=12.4 speed0= 11 y0= 11 x1= 20.6 angle0=30.9 speed0= 21 y0= 21 x1= 62.5 angle0=35.7 speed0= 31 y0= 31 x1= 125.2 angle0=38.0 speed0= 41 y0= 41 x1= 208.4 angle0=39.4 speed0= 51 y0= 51 x1= 312.1 angle0=40.4 speed0= 61 y0= 61 x1= 436.2 angle0=41.0 speed0= 71 y0= 71 x1= 580.7 angle0=41.5 speed0= 81 y0= 81 x1= 745.6 angle0=41.9 speed0= 91 y0= 91 x1= 931.0 angle0=42.2 speed0=101 y0=101 x1=1136.7 angle0=42.5 Bonus round: generalised vectors A different answer suggests performing generalised vector math. While I don't agree with that class-based approach I do agree with the idea: the most direct way to implement this is to use the complex numbers built into Python. Among other benefits, this significantly simplifies the best-angle calculation since it can be expressed in rectilinear space. import cmath import math from typing import Iterator from matplotlib import pyplot as plt class ProjectileMotion: """ This class calculates the movement of a projectile using its initial velocity and the angle at which it is thrown/shot. The initial height of the projectile is 0 by default but can be set by the user when creating an instance. The friction forces are neglected, thus the only formula used is the following: # △X = x0 + v_x⋅△t - a_x/2⋅△t^2 (and some of its variations) """ G = -9.80665j def __init__(self, v0: complex, p0: complex) -> None: self.v0 = v0 self.p0 = p0 self.t_apex = self._get_apex_time() self.t1 = self._get_t1()
{ "domain": "codereview.stackexchange", "id": 42822, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, physics", "url": null }
python, python-3.x, object-oriented, physics @classmethod def from_polar(cls, speed0: float, angle0_degrees: float, x0: float = 0, y0: float = 0) -> 'ProjectileMotion': return cls( p0=x0 + y0*1j, v0=cmath.rect(speed0, math.radians(angle0_degrees)) ) def _get_apex_time(self) -> float: """ max_y attained when vy - g*t = 0 (when the velocity induced by gravity = vy) """ return -self.v0.imag / self.G.imag def _get_t1(self) -> float: """ t_total = time taken for the object to fall on the ground (y=0) t_total = (vy + sqrt(vy**2 + 2*y0*g)) / g """ y0 = self.p0.imag vy0 = self.v0.imag ay = -self.G.imag return ( vy0 + math.sqrt(vy0**2 + 2*ay*y0) ) / ay def get_t(self, n_steps: int) -> Iterator[float]: """ t_vect contains the time at n_steps, the first one being 0 => need to divide by n_steps-1 """ for i in range(n_steps): yield self.t1 * i / (n_steps - 1) def p_for_t(self, t: float) -> complex: return self.p0 + self.v0*t + self.G*t**2/2 def v_for_t(self, t: float) -> complex: return self.v0 + self.G*t def angle_for_t(self, t: float) -> float: speed, angle = cmath.polar(self.v_for_t(t)) return math.degrees(angle) @property def x1(self) -> float: return self.p_for_t(self.t1).real def desc(self, n_steps: int = 10) -> str: return ( f'Curve over {n_steps} steps:' f'\n{"t":>5} {"x":>5} {"y":>5} {"angle°":>6}' f'\n' ) + '\n'.join( f'{t:>5.2f}' f' {(p := self.p_for_t(t)).real:>5.2f}' f' {p.imag:>5.2f}' f' {self.angle_for_t(t):>6.1f}' for t in self.get_t(n_steps) )
{ "domain": "codereview.stackexchange", "id": 42822, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, physics", "url": null }
python, python-3.x, object-oriented, physics @classmethod def with_best_angle(cls, speed0: float, y0: float) -> 'ProjectileMotion': """ https://www.whitman.edu/Documents/Academics/Mathematics/2016/Henelsmith.pdf equations 12 & 13 h: initial height = y0 v: initial velocity magnitude = speed Impact coefficients m = 0, a = 0 arccotangent(x) = atan(1/x), but do this in rectilinear space, not polar space """ g = ProjectileMotion.G.imag v = speed0 tan2 = 1/( 1 - 2*y0*g/v/v ) vx = v/math.sqrt(1 + tan2) vy = vx*math.sqrt(tan2) return cls( v0=vx + 1j*vy, p0=y0*1j, ) def graph(motion: ProjectileMotion) -> plt.Figure: fig, ax_x = plt.subplots() ax_t: plt.Axes = ax_x.twiny() ax_x.set_title('Projectile Motion') pos = [motion.p_for_t(t) for t in motion.get_t(n_steps=100)] ax_x.plot( [p.real for p in pos], [p.imag for p in pos], ) ax_x.set_xlabel('x') ax_t.set_xlabel('t') ax_x.set_ylabel('y') ax_x.set_xlim(left=0, right=motion.p_for_t(motion.t1).real) ax_t.set_xlim(left=0, right=motion.t1) ax_x.set_ylim(bottom=0) return fig def simple_test() -> None: motion = ProjectileMotion.from_polar(speed0=10, angle0_degrees=30, y0=5) print(motion.desc()) graph(motion) plt.show() def optimisation_test() -> None: for y0 in range(1, 102, 10): best = ProjectileMotion.with_best_angle(y0=y0, speed0=y0) speed0, angle0 = cmath.polar(best.v0) print(f'speed0={y0:3} y0={y0:3} x1={best.x1:6.1f} ' f'angle0={math.degrees(angle0):.1f}') if __name__ == '__main__': print('Simple projectile test:') simple_test() print() print('Angle optimisation test:') optimisation_test()
{ "domain": "codereview.stackexchange", "id": 42822, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, physics", "url": null }
python, design-patterns, reinventing-the-wheel, unit-conversion Title: Python - Temperature - descriptors with conversion Question: So I'm trying to understand the concept of descriptors and gathered some code together and made an exampel out of different sources. Like the offical documentation and StackOverflow answers. I'd hope someone can me tell some tricks about this concept or how to make this code better in general. Thanks in advanced. PS: If someon could tell me why celsius needs to be 9_007_199_254_740_991 + 1 higher instead of just * += 1 * would be nice to know. from abc import ABC class Validator(ABC): def __set_name__(self,owner,name): self.private_name = '_' + name def __get__(self,obj,objtype=None): return getattr(obj,self.private_name) def __set__(self,obj,value): self.validate(obj,value) rval = round(value,3) setattr(obj,self.private_name,rval) return obj._notify(self.private_name.replace('_','')) def validate(self,obj,value): if not isinstance(value, (int, float)): raise TypeError(f'Expected {value!r} to be an int or float') if self.minvalue is not None and value < self.minvalue: raise ValueError( f'Expected {value!r} to be at least {self.minvalue!r}' ) if self.maxvalue is not None and value > self.maxvalue: raise ValueError( f'Expected {value!r} to be no more than {self.maxvalue!r}' ) class Celsius(Validator): minvalue = -273.150 #Absolute zero maxvalue = 1.42*pow(10,32) #Planck temperature class Farenheit(Validator): minvalue = -459.670 #Absolute zero maxvalue = 2.55*pow(10,32) #Planck temperature class Kelvin(Validator): minvalue = 0 #Absolute zero maxvalue = 1.417*pow(10,32) #Planck temperature class Temperature( object ): celsius= Celsius() farenheit= Farenheit() kelvin = Kelvin() def __init__(self,typ='celsius',val=0.0): setattr(self,typ,val)
{ "domain": "codereview.stackexchange", "id": 42823, "lm_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, design-patterns, reinventing-the-wheel, unit-conversion", "url": null }
python, design-patterns, reinventing-the-wheel, unit-conversion def _notify(self,changed_by): lst = ['celsius','farenheit','kelvin'] lst.remove(changed_by) val = getattr(self,changed_by) for i in lst: con = getattr(Temperature,f'convert_{changed_by}_to_{i}')(val) rcon= round(con,3) setattr(self,'_'+i,rcon) @staticmethod def convert_kelvin_to_celsius(kelvin) -> celsius: return kelvin-273.15 @staticmethod def convert_celsius_to_kelvin(celsius) -> kelvin: return celsius+273.15 @staticmethod def convert_celsius_to_farenheit(celsius) -> farenheit: return celsius*1.8+32 @staticmethod def convert_kelvin_to_farenheit(kelvin) -> farenheit: return kelvin*1.8-459.67 @staticmethod def convert_farenheit_to_kelvin(farenheit) -> kelvin: return (farenheit+459.67)*1.8 @staticmethod def convert_farenheit_to_celsius(farenheit) -> celsius: return (farenheit-32)*1.8 if __name__ == '__main__': t = Temperature(typ='celsius',val=0.0) print(t.kelvin,t.farenheit) t.celsius = -273.15 print(t.kelvin,t.farenheit) t.celsius = 1.42*pow(10,32) print(t.kelvin,t.farenheit) t.celsius += 9_007_199_254_740_991 #+ 1 Output 273.15 32.0 0.0 -459.67 1.42e+32 2.556e+32 Answer: I'm not in love with the descriptor pattern in general: it lends itself poorly to immutable data. Assuming for now that we're sticking with descriptors,
{ "domain": "codereview.stackexchange", "id": 42823, "lm_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, design-patterns, reinventing-the-wheel, unit-conversion", "url": null }
python, design-patterns, reinventing-the-wheel, unit-conversion Your validation is redundant since you only have criteria that apply to Kelvin, but then repeat those criteria for every unit. Just express this once. You don't need abstract classes and you don't need inheritance. You can instantiate three descriptors, one for each unit. For better or worse, the typical Python approach is so-called duck typing: if it walks like a duck, and quacks like a duck, it might as well be a duck. In this approach, you would not isinstance, and would apply your conversions and comparisons in the hope that whatever value goes in has the appropriate operators implemented. This will also help to accommodate exotic numeric classes. Add PEP484 type hints. Do not express a conversion for every single unit pair. Only express conversions to and from the "native" unit of Kelvin. Since all conversions are linear, express this via offset and coefficient. Add unit tests. Stop writing pow(10, for literals; use e notation. It doesn't matter if you're only doing this once: exponential notation is more concise, easier to read and easier to optimise (if optimisation ends up being needed). It's also a better match to the output format used by basically all computers, running Python programs or otherwise, for very small or large numbers. Spelling: farenheit -> fahrenheit Don't inherit from object; we aren't in Python 2. You claim to do this because it's more explicit, but I'm going to claim that that guideline doesn't apply here: a bare class declaration will be a mystery to no one. Suggested import math from numbers import Real from typing import Type class TemperatureDescriptor: def __init__(self, coeff: Real, offset: Real) -> None: self.coeff, self.offset = coeff, offset def __get__(self, obj: 'Temperature', objtype: Type['Temperature']) -> float: return obj._kelvin*self.coeff - self.offset
{ "domain": "codereview.stackexchange", "id": 42823, "lm_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, design-patterns, reinventing-the-wheel, unit-conversion", "url": null }
python, design-patterns, reinventing-the-wheel, unit-conversion def __set__(self, obj: 'Temperature', value: Real) -> None: k = (value + self.offset)/self.coeff if k < 0: raise ValueError('Temperature is less than absolute zero') if k > 1.42e32: raise ValueError('Temperature is greater than the Planck limit') obj._kelvin = k class Temperature: kelvin = TemperatureDescriptor(1, 0) celsius = TemperatureDescriptor(1, 273.15) fahrenheit = TemperatureDescriptor(1.8, 273.15*1.8 - 32) def test() -> None: def isclose(expected: Real, actual: Real) -> None: assert math.isclose(expected, actual, rel_tol=0, abs_tol=1e-12) t = Temperature() t.celsius = 30 isclose(30, t.celsius) isclose(86, t.fahrenheit) isclose(303.15, t.kelvin) t.celsius = 0 isclose(0, t.celsius) isclose(32, t.fahrenheit) isclose(273.15, t.kelvin) t.celsius = 100 isclose(100, t.celsius) isclose(212, t.fahrenheit) isclose(373.15, t.kelvin) t.fahrenheit = 0 isclose(0, t.fahrenheit) isclose(-17.777777777778, t.celsius) isclose(255.372222222222, t.kelvin) t.kelvin = 0 isclose(0, t.kelvin) isclose(-273.15, t.celsius) isclose(-459.67, t.fahrenheit) try: t.kelvin = -1 raise AssertionError() except ValueError: pass try: t.kelvin = 2e32 raise AssertionError() except ValueError: pass if __name__ == '__main__': test()
{ "domain": "codereview.stackexchange", "id": 42823, "lm_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, design-patterns, reinventing-the-wheel, unit-conversion", "url": null }
c++, interview-questions Title: Coding style and idiomaticity of solution to the Word Search II problem on LeetCode Question: "Word Search II" is a hard problem on LeetCode (problem #212): Given an m x n board of characters and a list of strings words, return all words on the board. Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. The following solution of mine passes all the tests. I would very much appreciate comments as to how I can improve on the coding style and idiomatic use of C++. struct TrieNode { bool endFlag = false; // The pointer has to be shared. // Otherwise deletion of words may invalidate pointers in the caller. unordered_map<char, shared_ptr<TrieNode>> children; shared_ptr<TrieNode> getChild(char c) { auto it = children.find(c); return (it != children.end()) ? it->second : nullptr; } TrieNode *addChild(char c) { TrieNode *res = new TrieNode; children.insert(make_pair(c, shared_ptr<TrieNode>(res))); return res; } };
{ "domain": "codereview.stackexchange", "id": 42824, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, interview-questions", "url": null }
c++, interview-questions struct Trie { TrieNode head; void insert(const string &s) { TrieNode *cur = &head; for (char c: s) { TrieNode *next = (cur->getChild(c)).get(); if (!next) next = cur->addChild(c); cur = next; } cur->endFlag = true; } void erase(const string &s) { erase(&head, s, 0); } // For debugging void dump() { cout << endl << endl << "DUMPING THE TRIE" << endl; dump(&head, 0); } private: // Return whether there are words below node; bool erase(TrieNode *node, const string &s, int i) { if (i == s.size()) node->endFlag = false; else { bool res = erase((node->getChild(s[i])).get(), s, i + 1); if (!res) (node->children).erase(s[i]); } return (node->children).size() || node->endFlag; } // For debugging void dump(TrieNode *node, int depth) { string indent(4 * depth, ' '); if (node->endFlag) cout << indent << "END" << endl; for (char c = 'a'; c <= 'z'; ++c) { TrieNode *child = (node->getChild(c)).get(); if (child) { cout << indent << c << endl; dump(child, depth + 1); } } } };
{ "domain": "codereview.stackexchange", "id": 42824, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, interview-questions", "url": null }
c++, interview-questions class Solution { int m, n; unordered_set<string> res; Trie trie; void buildTrie(const vector<string> &words) { for (const auto &w: words) trie.insert(w); } string stackToWord(const vector<vector<char>>& board, vector<vector<int>> &stack) { string res; for (const auto &loc: stack) res += board[loc[0]][loc[1]]; return res; } void search (const vector<vector<char>>& board, const vector<int> &loc, vector<vector<int>> &stack, TrieNode *trieNode) { if (trieNode->endFlag) { string word = stackToWord(board, stack); res.insert(word); trie.erase(word); } int r = loc[0], c = loc[1]; if (r < 0 || r > m - 1) return; if (c < 0 || c > n - 1) return; if (find(stack.begin(), stack.end(), loc) != stack.end()) return; shared_ptr<TrieNode>child = trieNode->getChild(board[r][c]); if (!child) return; stack.push_back(loc); search(board, {r + 1, c}, stack, child.get()); search(board, {r - 1, c}, stack, child.get()); search(board, {r, c + 1}, stack, child.get()); search(board, {r, c - 1}, stack, child.get()); stack.pop_back(); } public: vector<string> findWords(vector<vector<char>>& board, vector<string>& words) { buildTrie(words); m = board.size(); n = board[0].size(); vector<vector<int>> stack; for (int r = 0; r < m; ++r) for (int c = 0; c < n; ++c) search(board, {r, c}, stack, &trie.head); return vector<string>(res.begin(), res.end()); } }; ```
{ "domain": "codereview.stackexchange", "id": 42824, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, interview-questions", "url": null }
c++, interview-questions Answer: Use full names First of all, don't use arbitary abbreviations: HTTP is fine, it's well known and "domain knowledge", res isn't. It takes very little effort to use result instead, just type it in full. Naming is difficult, but good naming makes code incredibly clearer. It's a skill worth polishing, and time well spent. Create meaningful types What is a std::vector<std::vector<char>>? A list of words? Something else? The main issue with issue an all-purpose type directly is that it can represent anything and it can do anything, even operations that would be wild. A type is all of: A name, the who. A set of invariants on the values it can take, the what. A collection of operations, the how. It is important to fully think out the invariants and the operations: What does it mean for a board to be "unbalanced"? That is, having 2 rows of different length? Should that be allowed? What does it mean, then, to erase a character in a row? Should that be allowed? Should reordering the rows be allowed? Ideally, you want to ensure that: A 100% valid/representable ratio for the set of values. A 100% meaningful/possible ratio for the set of operations. I advise naming first, and setting them some representation of the state to get started. If well encapsulated, you can change it easily enough after all: class Board { public: // I generally recommend public first; it's the API after all. private: std::vector<std::vector<char>> colums; }; struct Dimensions { int rows = 0; int columns = 0; }; struct Position { int x = 0; int y = 0; }; This sets you up to write better code. Note: I do not particularly endorse the std::vector<std::vector<char>> representation but... it doesn't matter. Now that it's private it can be changed at leisure without any impact on existing clients! And with regard to API, let's start with a streaming operator to be able to print... everything. bool operator<<(std::ostream& out, Position const& position);
{ "domain": "codereview.stackexchange", "id": 42824, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, interview-questions", "url": null }
c++, interview-questions Then let's review what we need of the board: class Board { public: // As supplied by LeetCode. explicit Board(std::vector<std::vector<char>> const& board); Dimensions get_dimensions() const noexcept; // Throws on positions out of bounds. char operator[](Position position) const; private: // ... }; This means we can talk about Position: bool operator==(Position const& left, Position const& right) noexcept; bool operator!=(Position const& left, Position const& right) noexcept; Adding equality should generally be seen as a trigger to consider hashing, so let's: template <> struct std::hash<Position> { std::size_t operator()(Position const& position) const; }; And it'd be nice to have a way to check whether a Position is within the bounds of the board: bool is_within(Position const& position, Dimensions const& dimensions); That sets up nicely. Encapsulate, encapsulate, encapsulate. Some types, like Position and Dimensions, do not really have much in the sense of invariants (though negative dimensions should raise an eyebrow), so having them as struct is fine. On the other hand, types like a Trie do maintain complex invariants; for example your Trie is pruning the nodes it no longer needs. Those should be well encapsulated: Members should be private. And mutable references to them should not be exposed. Encapsulation is also nice to reduce dependencies, such as the inner representation of Board which can be changed at will. So... let's rethink Trie: class Trie { public: class Node { public: // We'll come back later private: bool endWord = false; std::unordered_map<char, Node> children; }; // We'll come back later private: Node root; }; Now, the operations: // Of course! std::ostream& operator<<(std::ostream& out, Trie const& trie); We'll need to iterate over the Trie, as well as insert and remove words from it: class Trie { public: Node const* root() const;
{ "domain": "codereview.stackexchange", "id": 42824, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, interview-questions", "url": null }
c++, interview-questions void insert(std::string_view word); void remove(std::string_view word); private: // ... }; And the same for Node, really. class Node { public: Node const* get_child(char c) const; void insert(std::string_view suffix); void remove(std::string_view suffix); private: // ... }; Do note how I "raised the level" of the operations, from talking about nitty gritty details (getChild/addChild) to talking about the problem domain. In general, it's a win, as it encapsulates implementation details. Lifetime of Nodes As you noted, there's a lifetime issue: what if a node is removed that is still referenced? You solved it by std::shared_ptr which works, though it's expensive and verbose. In this particular problem, however, you didn't need to. That is, you can separate the logical concept of removing a word from the Trie and the implementation concern of removing a node from the Trie. You're starting with a fixed list of words, after all, so there won't be unbounded growth. The lifetime problem can therefore be fixed, cheaply, by simply moving the node to a deleted list. class Node { public: // As above. private: using Children = std::unordered_map<char, Node>; bool endWord = false; Children children; std::vector<Children::node_type> deleted_children; }; node_type comes from C++17's extract method; very useful to avoid allocating separately: The node still exists, though outside the container so that find, or iteration do not see it. All iterators to it are invalidated, but pointers and references are not. You can also merge it back into this container (or another) but that won't be of use here. Don't Repeat Yourself. This is painful to write, and to read: search(board, {r + 1, c}, stack, child.get()); search(board, {r - 1, c}, stack, child.get()); search(board, {r, c + 1}, stack, child.get()); search(board, {r, c - 1}, stack, child.get());
{ "domain": "codereview.stackexchange", "id": 42824, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, interview-questions", "url": null }
c++, interview-questions Hopefully the only difference are the coordinates... Instead imagine: for (Direction direction : { Down, Up, Right, Left }) { search(board, position.next(direction), stack, child); } Isn't it much clearer? Or you could go with: std::array<Position; 4> get_neighbours(Position p) { return {{ { p.x + 1, p.y }, { p.x - 1, p.y } { p.x, p.y + 1 }, { p.x, p.y - 1 } }}; } for (auto neighbour : get_neighbours(loc)) { search(board, neighbour, stack, child); } It has the advantage of avoiding to forget a neighbour in the list, and since the directions are not otherwise used, that may be good enough without introducing a long-ish next method. Anything but copy/pasting mostly identical lines of code is better, really.
{ "domain": "codereview.stackexchange", "id": 42824, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, interview-questions", "url": null }
c++, interview-questions With regard to the algorithmic details: I'm somewhat concerned about the algorithmic complexity of that std::find(stack.begin(), stack.end(), loc) call. Your stack can get as long as the longer word (or close to), so we're talking O(L) for each individual call, and it's called within a recursion called within the inner loop. Sounds like a recipe for quadratic complexity in the inner loop; best avoided. It may be worth keeping a std::hash_set<Position> instead to get O(1).1 Similarly, it may be worth eliminating impossible words from the get go. Since you can't reuse any board cell within a given word, doing a quick count of the number of occurrences of each character on the board and comparing it to a quick count for each word would eliminate the words that cannot possibly be on the board very cheaply. I'd suggest doing it even before creating the Trie. Bonus: it automatically eliminates words longer than the number of cells of the board; a nice way to introduce terrible complexity in your current algorithm.... 1 I'd create a Path class containing the set of Positions and a string equal to the sequence of characters seen so far with add(Position, Board const&) and remove(Position, Board const&) methods. As a bonus, you can remove stackToWord. With regard to the nitpicky details: Write tests. Yes, I know that you can't submit them. Write them anyway, in a separate file, and compile and run locally to check your edge cases. And also check performance edge cases; like... a 8x8 board with a square of 7x7 As (upper left), then an A in bottom right, and the rest all Bs, with a word being 50 As: is it much slower than usual 8x8 boards? Don't hardcode cout, that's what operator<< is for: It allows bundling additional detail on the line. It instantly becomes trivial to write a test for that code too; it's nice to ensure debug code works, if you can't rely on it, how are you going to debug the rest? Don't want to go chasing gooses!
{ "domain": "codereview.stackexchange", "id": 42824, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, interview-questions", "url": null }
c++, interview-questions Always use {} around blocks, even when the grammar allows omitting it such as after if. Search for GOTO FAIL to learn how blocks can save the day...
{ "domain": "codereview.stackexchange", "id": 42824, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, interview-questions", "url": null }
python-3.x, hash-map Title: Calculate how many categories I can construct Question: I would appreciate to have your opinion on this code and whether I can refactor it and make it cleaner. I don't like the fact that I have 3 nested for loops, which makes the complexity of this code O(n³). categories = {} for k1, v1 in res["relationship_types"].items(): for k2, v2 in res["remote_types"].items(): count = 0 for k3, v3 in RELATIONSHIPS_CATEGORIES.items(): relationship_types = v3["relationship_types"] if k1 in relationship_types: target_types = v3["target_types"] if len(target_types) == 0: count = v1 categories[k3] = count break elif k2 in target_types: count = min(v1, v2) if k3 in categories: categories[k3] += count else: categories[k3] = count This is my res: res={'remote_types': {'identity': 2, 'location': 1, 'indicator': 2}, 'relationship_types': {'targets': 2, 'uses': 1, 'indicates': 2}} And this is my RELATIONSHIP_CATEGORIES: RELATIONSHIPS_CATEGORIES = { "campaigns": { "relationship_types": ["targets"], "target_types": ["identity"], }, "ttps": { "relationship_types": ["uses"], "target_types": ["attack-pattern"], } } What I want to do is calculate how many categories I can construct based on my res dictionary. For instance, for the category campaigns of RELATIONSHIPS_CATEGORIES I need to have at least one targets in my res["relationship_types"] and one identity in my res["remote_types"], but since I have 2 of each, my categories dictionary would look like: categories = { "campaigns": 2, }
{ "domain": "codereview.stackexchange", "id": 42825, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, hash-map", "url": null }
python-3.x, hash-map Answer: Your logic is pretty convoluted, not helped by your mystery k1, k2 (etc.) names. So far as I can tell, you shouldn't be doing any length comparison. Use more meaningful variable names, replace your confusing target_types mapping with direct reference to remote_types, and you have res = { 'remote_types': {'identity': 2, 'location': 1, 'indicator': 2}, 'relationship_types': {'targets': 2, 'uses': 1, 'indicates': 2}, } RELATIONSHIPS_CATEGORIES = { 'campaigns': { 'relationship_types': ['targets'], 'remote_types': ['identity'], }, 'ttps': { 'relationship_types': ['uses'], 'remote_types': ['attack-pattern'], }, } categories = { rel_key: min( res_items.get(criterion, 0) for res_items, criteria in ( (res.get(criterion_key, {}), criteria) for criterion_key, criteria in rel_criteria.items() ) for criterion in criteria ) for rel_key, rel_criteria in RELATIONSHIPS_CATEGORIES.items() } print(categories) or perhaps more legibly def count_criteria(rel_criteria: dict[str, list[str]]) -> Iterator[int]: for criterion_key, criteria in rel_criteria.items(): res_items = res.get(criterion_key, {}) for criterion in criteria: yield res_items.get(criterion, 0) categories = { rel_key: min(count_criteria(rel_criteria)) for rel_key, rel_criteria in RELATIONSHIPS_CATEGORIES.items() } both resulting in {'campaigns': 2, 'ttps': 0} It's not the fastest thing in the world, but strictly speaking this is not true: the complexity of this code [is] O(n³)
{ "domain": "codereview.stackexchange", "id": 42825, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, hash-map", "url": null }
python-3.x, hash-map the complexity of this code [is] O(n³) because your iterations are iterating over dimensions of potentially different sizes. You have not given any hints as to the scale of your problem, so all optimisation may be premature, but if you really needed to run complexity analysis you'd find O(mnp) with m, n and p each a separate dimension. If enough of those dimensions stay constant and low you can effectively consider them to be 1.
{ "domain": "codereview.stackexchange", "id": 42825, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, hash-map", "url": null }
python, python-2.x Title: Is there a faster way to write dictionary values to csv? Question: I have a dictionary that I am writing to a csv file, however I am only writing the values. I want to know if there is a faster way than using a for loop. I am using python 2.7 here is my code. empty = "" with open("parse_data.csv", "w") as f: for key, value in order_dic_keys.items(): if value is None or value == "": empty += "" + "|" else: empty += str(value) + "|" f.write(empty[:]) As you can see I have a conditional statement to check the value. So I am unaware if there are other possibilities or if this is the best case scenario. Answer: Writing to a csv file and grabbing all the values from a dictionary are two very common tasks in python, and so the language has built-in capabilities for both: import csv with open("parse_data.csv", "w") as f: writer = csv.writer(f, delimiter="|") writer.writerow(order_dic_keys.values()) This has a few nice properties compared to your code: In your code, you needed to do string handling (e.g. concatenation), while this handles that for you. This automatically handles annoying things to remember, like newlines at the end of your output (you actually didn't include one in your code) This automatically handles data that has the "|" character in it, putting it in quotes so you don't interpret it as two separate data elements This automatically handles data like None so you don't need to treat it as a special case, as you do in your code It would be straightforward to add a header row -- you would just add writer.writerow(order_dic_keys.keys()) right after you create the writer object
{ "domain": "codereview.stackexchange", "id": 42826, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-2.x", "url": null }
c++, algorithm Title: C++ : Garage Sale Algorithm Question: I'm studying Dasgupta's "Algorithms". I solved this problem in C++: The garage sale problem. On a given Sunday morning, there are \$n\$ garage sales going on, \$g_{1}, \cdots, g_{n}\$. For each garage sale \$g_{j}\$ , you have an estimate of its value to you, \$v_{j}\$ . For any two garage sales you have an estimate of the transportation cost \$d_{ij}\$ of getting from \$g_{i}\$ to \$g_{j}\$ . You are also given the costs \$d_{0j}\$ and \$d_{j0}\$ of going between your home and each garage sale. You want to find a tour of a subset of the given garage sales, starting and ending at home, that maximizes your total benefit minus your total transportation costs. Give an algorithm that solves this problem in time \$O(n^{2}2^{n})\$. (Hint: This is closely related to the traveling salesman problem.) Here is my code: (I assumed \$n < 16\$, to use std::uint16_t as a bitmask that represents the set of visited garages. I could suppose \$n < 32\$ and use std::uint32_t instead, but \$n = 31\$ is not feasible for \$O(n^{2}2^{n})\$) std::pair<std::vector<std::size_t>, double> getMaxValue(const std::vector<double>& vals, const std::vector<std::vector<double>>& dist_costs) { std::tuple<std::uint16_t, std::size_t, double> ans {0, -1, std::numeric_limits<double>::lowest()}; const std::size_t n = vals.size(); assert(n < 16); // valueMap[i][j] is total max benefit up to path of length i that ends with garage j std::unordered_map<std::uint16_t, std::vector<double>> valueMap; valueMap[0].resize(n); for (std::size_t j = 0; j < n; ++j) { valueMap[0][j] = vals[j] - dist_costs[0][j + 1]; } // subsets[i] is set of paths of length i: // each element in subsets[i] is uint16_t bitmask // where each bit represents whether a garage is visited or not. std::vector<std::unordered_set<std::uint16_t>> subsets (n + 1);
{ "domain": "codereview.stackexchange", "id": 42827, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm", "url": null }
c++, algorithm // warning : n = 16 will cause (defined) infinite loop! for (std::uint16_t index = 0; index <= static_cast<std::uint16_t>((1u << n) - 1); ++index) { int cnt = std::popcount(index); subsets[cnt].insert(index); } // optimal back element to extend to unvisited j std::unordered_map<std::uint16_t, std::vector<std::size_t>> optimalBack; for (std::size_t k = 1; k < n; ++k) { for (auto subset_k : subsets[k]) { optimalBack[subset_k].resize(n); valueMap[subset_k].resize(n); for (std::size_t j = 0; j < n; ++j) { if (!(subset_k & (1u << j))) { // extend to unvisited j. std::size_t max_i = -1; double valueMap_subsetk_j = std::numeric_limits<double>::lowest(); for (std::size_t i = 0; i < n; ++i) { if (subset_k & (1u << i)) { // backtrack the last visited. auto subset_k_minus_i = subset_k & ~(1u << i); double value_from_i_to_j = valueMap[subset_k_minus_i][i] + vals[j] - dist_costs[i + 1][j + 1]; if (valueMap_subsetk_j < value_from_i_to_j) { valueMap_subsetk_j = value_from_i_to_j; max_i = i; } } } valueMap[subset_k][j] = valueMap_subsetk_j; assert(max_i != -1); optimalBack[subset_k][j] = max_i; auto ans_candidate = valueMap_subsetk_j - dist_costs[j + 1][0]; // update best answer if (std::get<2>(ans) < ans_candidate) { ans = {subset_k | (1u << j), j, ans_candidate}; } } } } }
{ "domain": "codereview.stackexchange", "id": 42827, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm", "url": null }
c++, algorithm auto [optimalSet, optimalLast, optimalVal] = ans; // backtrack to construct optimal path. std::vector<std::size_t> optimalSequence; while (true) { optimalSequence.push_back(optimalLast); optimalSet = optimalSet & ~(1u << optimalLast); if (!optimalSet) { break; } auto optimalSecondLast = optimalBack[optimalSet][optimalLast]; optimalLast = optimalSecondLast; } std::ranges::reverse(optimalSequence); return {optimalSequence, optimalVal}; } Feel free to comment anything! Answer: Use std::bitset I assumed \$n<16\$, to use std::uint16_t as a bitmask that represents the set of visited garages. I could suppose \$n<32\$ and use std::uint32_t instead, but n=31 is not feasible for \$O(n^2 2^n)\$
{ "domain": "codereview.stackexchange", "id": 42827, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm", "url": null }
c++, algorithm There are a few flaws in this assumption. Even if n=31 were not feasible, consider that n=17 might be very feasible, so you would still need a std::uint32_t. Second, even n=31 is not as unfeasible as you might think with today's hardware. Contemporary CPUs and GPUs can process multiple TFLOP/s. For example, an NVIDIA GeForce RTX 3090 can process 35.6 TFLOP/s, or \$2^{35}\$ FLOP/s. While expensive, this is just a single consumer graphics card. So if you only needed one FLOP per step of the algorithm, it would take only \$\frac{31^2 2^{31}}{2^{35}} = \frac{961}{16} \approx 60\$ seconds. Of course it will take a bit more than that, but it definitely isn't outside the realm of possibilities, even for a single PC. I recommend you use a std::bitset instead of an unsigned int for storing the bitmask. It is then easy to change the size of the bitset. Also, the way it is used, I don't think there is any benefit to making it only 16 bits. Only when you store many of them consecutively in memory would it help to choose the smallest possible size. It will also help you distinguish more easily between a bitmask and a path length in your code. Naming things getMaxValue() is not a great name. It doesn't explain what exactly this function is doing. It's even returning more than just a single value, so just by looking at the return type you know the name is a lie. If this function would be part of a larger program, consider naming it calculateOptimalGarageSalePath(). The variable names inside the function are not super great. I see both camelCase and snake_case names, I recommend picking one style and sticking with it. They are mostly fine, except for ans. Is this an abbreviation of answer? But if so, it's actually not the final answer. But most importantly, use a struct instead of a std::tuple, so you can give names to each of the elements: struct { std::bitset<16> subset; std::size_t lastGarage; double value; } currentBest; ...
{ "domain": "codereview.stackexchange", "id": 42827, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm", "url": null }
c++, algorithm ... auto candidateValue = valueMap_subsetk_j - dist_costs[j + 1][0]; if (currentBest.value < candidateValue) { currentBest = {subset_k | (1u << j), j, candidateValue}; } I would also pay attention to the function parameters and return value. It would be great if these things were more clearly named. To do that, I recommend creating two structs; one describing a garage sale, and one describing the return type: struct garage { double value; std::vector<double> dist_costs; }; struct optimalPath { std::vector<std::size_t> garages; double value; }; optimalPath calculateOptimalGarageSalePath(const std::vector<garage>& garages) { const std::size_t n = garages.size(); ... return {optimalSequence, optimalVal}; }
{ "domain": "codereview.stackexchange", "id": 42827, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm", "url": null }
c++, multithreading, c++20, locking Title: Block-free priority lock Question: Background I wanted to write an event loop that supports scheduling, but found that no implementation of priority queue that I know of supports waiting on a condition variable (the idea is that the looping thread will wait on the condition variable and if the wait timed out, it means that it can pop the top of the queue and execute that, otherwise it was interrupted and needs to reconsider sleeping time). I thought about using plain std::mutexes. Somebody already found out how to do that. But I thought perhaps I could do better. So I ventured forth into a world of atomics ... and there was no end to surprises. Priority lock The basic idea was stolen from a bakery lock (I believe it is also called a ticket lock). Normal priority threads take a "ticket" on attempt to enter into critical section. When the critical section has their ticket number, they enter the critical section. The leaving thread will increment the ticket number that should enter the critical section. The only change is that there is an additional atomic flag that is used to control mutual exclusion for the priority thread in case it needs to skip the line. Guarantees Mutual exclusion Mutual exclusion guarantee is provided by the atomic flag is_lock_held. The entering thread can enter only if it is false, and it acquires the lock via strong compare and exchange (CAS). When the thread that owns the lock exits the critical section, it sets the flag to false. Strong order among normal priority threads This is guaranteed by ticketing system. The thread that enters the wait state earlier in the view of next_label will enter the critical section earlier than others. Only highest priority thread (of which there is only one) can skip the line. Deadlock freedom
{ "domain": "codereview.stackexchange", "id": 42828, "lm_label": 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++20, locking", "url": null }
c++, multithreading, c++20, locking Deadlock freedom Unless there was some serious error (process crash or some other way to bypass RAII) the lock is guaranteed to be released in case of exceptions and any other control flow RAII can affect. There is also absence of ways for threads to actively block each other by doing actions that would prevent the other from progress. Only the current owner of the critical section will decide if anybody will progress and then cache effects will determine which thread goes next (since atomics are used, exactly one is guaranteed to progress). - Only one high priority lock at a time The implementation does CAS on high priority lock creation (if the counter is 0, replace with 1). The destructor of the high priority lock will reset it back to 0. Facepalm. I somehow managed to put the reset to zero in the constructor. I guess writing code at night is a bad idea. The ugly parts Potential starvation As any atomics only algorithm, the lock can starve any thread. The high priority lock might get starved because it is not fast enough to acquire the boolean flag (getting scheduled out of CPU in inopportune moment). The normal priority threads can be starved by design. Code #include <cstddef> #include <atomic> #include <stdexcept> #include <immintrin.h> namespace shino { /** * @brief the shared state of the normal priority and highest priority locks. This class is intended to be * a factory to the mentioned locks, thus not usable directly. * * Use `create_normal_priority_lock` and `create_highest_priority_lock` to obtain locks which are akin to * std::unique_lock (they do provide exception safety by unlocking in the destructor). */ class priority_mutex { std::atomic<std::size_t> current_label = 0; std::atomic<std::size_t> next_label = 0; std::atomic<bool> is_lock_held = false;
{ "domain": "codereview.stackexchange", "id": 42828, "lm_label": 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++20, locking", "url": null }
c++, multithreading, c++20, locking std::atomic<int> priority_thread_count = 0; public: /** * @brief a lock class intended to be used by normal priority thread. * * The mechanism of acquiring lock is by obtaining * a new label to wait on, and then when the other normal priority thread sets the label of the lock to the label * obtained by this thread, it will try to lock the boolean which is used to allow high priority thread to * skip the waiting line and be the next owner of the lock. */ class normal_priority_thread_lock { priority_mutex* shared_state = nullptr; std::size_t my_label = -1; bool is_locked = false; public: normal_priority_thread_lock(const normal_priority_thread_lock&) = delete; normal_priority_thread_lock& operator=(const normal_priority_thread_lock&) = delete; /** * @brief Lock the priority_mutex using normal priority (will yield to high priority thread if contended), * the calling thread will be granted exclusive ownership to the critical section guarded by this `priority_mutex` * * @pre the lock is in unlocked state (all previous `lock()` calls were followed by `unlock()` in one by one manner) * @post the lock is in locked state */ void lock() { if (is_locked) { throw std::logic_error("attempt to deadlock by double locking"); } my_label = shared_state->next_label++; while (shared_state->current_label.load(std::memory_order_consume) != my_label) { _mm_pause(); }
{ "domain": "codereview.stackexchange", "id": 42828, "lm_label": 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++20, locking", "url": null }
c++, multithreading, c++20, locking /* * attempt to reduce starvation of the priority thread. Since pause takes more than one instruction, * when the pause points don't exactly align, the priority thread might miss the window to lock the * atomic bool. That is why there is exactly one pause after the loop */ _mm_pause(); /* * don't spin on CAS to decrease cache traffic */ bool expected = false; do { expected = false; while (shared_state->is_lock_held.load(std::memory_order_consume) != expected) { _mm_pause(); } } while (!shared_state->is_lock_held.compare_exchange_strong(expected, true, std::memory_order_acq_rel, std::memory_order_consume)); is_locked = true; } /** * @brief Unlock the critical section guarded by this `priority_mutex` thus allowing the next thread to progress. * If highest_priority_thread_lock contends with other locks, the highest priority one will get priority. * * @pre the lock is in locked state (all previous `unlock()` calls were followed by `lock()` in one by one manner) * @post the lock is in unlocked state */ void unlock() { if (!is_locked) { throw std::logic_error("attempting to unlock non locked lock"); } bool expected = true; if (!shared_state->is_lock_held.compare_exchange_strong(expected, false, std::memory_order_acq_rel, std::memory_order_consume)) { throw std::logic_error("either double unlock or something wrong with the lock itself"); }
{ "domain": "codereview.stackexchange", "id": 42828, "lm_label": 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++20, locking", "url": null }
c++, multithreading, c++20, locking const auto next_in_line = my_label + 1; auto stored_label = my_label; if (!shared_state->current_label.compare_exchange_strong(stored_label, next_in_line, std::memory_order_acq_rel, std::memory_order_consume)) { throw std::logic_error("somebody acquired the lock before this lock unlocked?"); } is_locked = false; } ~normal_priority_thread_lock() { if (is_locked) { unlock(); } } private: friend priority_mutex; normal_priority_thread_lock(priority_mutex* shared_state, bool start_locked): shared_state(shared_state) { if (start_locked) { lock(); } } }; /** * @brief a lock class intended to be used by highest priority thread. * * The mechanism of locking is to acquire atomic boolean by setting it to true when it is false. Normal priority * thread is unlikely to contend if both were waiting on the locked lock, because the boolean will be unlocked * first and only then the label will be set to the label of the waiting normal priority thread. **Staration is * possible in theory**. */ class highest_priority_thread_lock { priority_mutex* shared_state = nullptr; bool is_locked = false; public: highest_priority_thread_lock(const highest_priority_thread_lock&) = delete; highest_priority_thread_lock& operator=(const highest_priority_thread_lock&) = delete;
{ "domain": "codereview.stackexchange", "id": 42828, "lm_label": 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++20, locking", "url": null }
c++, multithreading, c++20, locking /** * @brief Lock the priority_mutex using highest priority (will skip the line if contended on a locked lock), * the calling thread will be granted exclusive ownership to the critical section guarded by this `priority_mutex` * * @pre the lock is in unlocked state (all previous `lock()` calls were followed by `unlock()` in one by one manner) * @post the lock is in locked state */ void lock() { if (is_locked) { throw std::logic_error("attempting to deadlock via double locking"); } /* * don't spin on CAS to decrease cache traffic */ bool expected = false; do { expected = false; while (shared_state->is_lock_held.load(std::memory_order_consume) != expected) { _mm_pause(); } } while (!shared_state->is_lock_held.compare_exchange_strong(expected, true, std::memory_order_acq_rel, std::memory_order_consume)); is_locked = true; } /** * @brief Unlock the critical section guarded by this `priority_mutex` thus allowing the next thread to progress. * If highest_priority_thread_lock contends with other locks, the highest priority one will get priority. * * @pre the lock is in locked state (all previous `unlock()` calls were followed by `lock()` in one by one manner) * @post the lock is in unlocked state */ void unlock() { if (!is_locked) { throw std::logic_error("attempting to unlock non-locked lock"); }
{ "domain": "codereview.stackexchange", "id": 42828, "lm_label": 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++20, locking", "url": null }
c++, multithreading, c++20, locking bool expected = true; if (!shared_state->is_lock_held.compare_exchange_strong(expected, false, std::memory_order_acq_rel, std::memory_order_acquire)) { throw std::logic_error("either double unlock or something wrong with the lock itself"); } is_locked = false; } ~highest_priority_thread_lock() { if (is_locked) { unlock(); } } private: friend priority_mutex; highest_priority_thread_lock(priority_mutex* shared_state, bool start_locked): shared_state(shared_state) { if (start_locked) { lock(); } shared_state->priority_thread_count.store(0, std::memory_order_release); } }; /** * @brief creates an instance of `normal_priority_thread_lock` that shares inner state with this mutex * @param start_locked if true the lock will be locked on construction, otherwise it will be constructed in * unlocked state * @return instance of `normal_priority_thread_lock` */ normal_priority_thread_lock create_normal_priority_lock(bool start_locked = true) { return {this, start_locked}; }
{ "domain": "codereview.stackexchange", "id": 42828, "lm_label": 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++20, locking", "url": null }
c++, multithreading, c++20, locking /** * @brief creates an instance of `highest_priority_thread_lock` that shares inner state with this mutex. * There can be only one highest priority lock at a time. * * @param start_locked if true the lock will be locked on construction, otherwise it will be constructed in * unlocked state * @return instance of `highest_priority_thread_lock` */ highest_priority_thread_lock create_highest_priority_lock(bool start_locked = true) { int desired = 0; if (priority_thread_count.compare_exchange_strong(desired, 1, std::memory_order_acq_rel)) { return {this, start_locked}; } else { throw std::logic_error("attempting to create multiple highest priority locks"); } } }; } /* * Test: the idea is to have a normal priority thread to be first and lock for a long amount of time, * and then the priority thread should take the lock even though there are threads waiting before it */ #include <iostream> #include <thread> void first_thread_function(shino::priority_mutex& mutex, std::atomic<bool>& flag) { auto normal_lock = mutex.create_normal_priority_lock(); flag.store(true, std::memory_order_release); std::cout << "print from normal thread\n"; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } void normal_priority_function(shino::priority_mutex& mutex) { auto normal_lock = mutex.create_normal_priority_lock(); std::cout << "print from normal thread\n"; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } void high_priority_function(shino::priority_mutex& mutex) { auto priority_lock = mutex.create_highest_priority_lock(); std::cout << "print from priority thread\n"; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); }
{ "domain": "codereview.stackexchange", "id": 42828, "lm_label": 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++20, locking", "url": null }
c++, multithreading, c++20, locking int main() { for (std::size_t i = 0; i < 4; ++i) { std::atomic<bool> start_flag = false; shino::priority_mutex mutex; auto t0 = std::thread(first_thread_function, std::ref(mutex), std::ref(start_flag)); while (!start_flag.load(std::memory_order_consume)) {_mm_pause();} auto t1 = std::thread(normal_priority_function, std::ref(mutex)); auto t2 = std::thread(normal_priority_function, std::ref(mutex)); auto t3 = std::thread(high_priority_function, std::ref(mutex)); t0.join(); t1.join(); t2.join(); t3.join(); std::cout << "=======\n"; } return 0; } Why there is insufficient testing? I only did a sanity check because I am planning on getting the tests reviewed as well separately. The reason for separation is to not overwhelm the reviewers with complexity. Please downvote and comment if you think this approach is wrong. The output of the test should be print from normal thread print from priority thread print from normal thread print from normal thread ======= print from normal thread print from priority thread print from normal thread print from normal thread ======= print from normal thread print from priority thread print from normal thread print from normal thread ======= print from normal thread print from priority thread print from normal thread print from normal thread ======= Build Since this is a single file, any compiler invocation with C++17 mode will do. What review I would prefer? I would prefer a code review that would focus on proper usage of atomics and better mechanisms to reduce starvation. I thought about the layout of the class all falling on the same cache line, but making the class bigger was not the decision I wanted to make.
{ "domain": "codereview.stackexchange", "id": 42828, "lm_label": 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++20, locking", "url": null }
c++, multithreading, c++20, locking Answer: Should You Really Create the High-Priority Mutex Separately? This introduces a new, invalid state (where the high-priority mutex hasn’t been created yet), and prevents you from checking multiple state variables with the same atomic operation (see below). Consider Using an atomic_flag You currently are reinventing the wheel with a CAS loop on an atomic<bool>, but there’s already std::atomic_flag::test_and_set() in the standard library. One reason not to would be, Check Multiple State Variables with a Single CAS Currently, your lock() algorithm has multiple steps and is pretty complicated. But what it’s really trying to do is, wait for one specific state: This thread’s ticket is next in line The mutex lock is clear There are zero high-priority threads waiting It always wants to update to a specific state: The current ticket is this thread’s The mutex lock is set There are zero high-priority threads waiting
{ "domain": "codereview.stackexchange", "id": 42828, "lm_label": 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++20, locking", "url": null }
c++, multithreading, c++20, locking If you pack a ticket number, a count of high-priority waiting threads, and a lock value into a struct, and wrap that into something like atomic<priority_mutex::state_t> the .lock() algorithm simplifies to a CAS loop that awaits that specific state. If this all fits into 64 bits, you’re golden. If you can fit it into 128 bits, and declare the type alignas(16), many x86_64 compilers (including Clang++ 13, MSVC 19 and ICX 2022) will automatically use the native cmpxchg16b instruction. ICX is even smart enough not to need the alignment hint. Edit: It is in fact much faster to wait for the expected state with atomic loads than by attempting a CAS, which on x86-64 locks the bus. The high-priority lock is a little more complicated, as it wants to be able to increment the count of waiting high-priority threads as a separate operation, test-and-set the lock, and ignore the ticket number. You don’t want a high-priority thread to be blocked because a lower-priority one updated the ticket. This implementation doesn’t let you check for double-lock as you currently do, as multiple high-priority threads attempting to wait on the same queue is not a bug. (If you still want to check for double-increment or double-decrement, maybe each thread remembers whether it’s currently holding a lock, and checks that thread variable off the critical path.) Is All the World an X86? Currently, you have a non-portable function, _mm_pause(), scattered all over the place. As far as dependencies on specific hardware go, this isn’t the worst; you can do a search-and-replace if you ever have to. So you might as well do it up front. Here’s a good start: #if __x86__ || __x86_64__|| _M_IX86 || _M_X64 #include <immintrin.h> inline void spin_pause() { return _mm_pause(); } #else # error "Implement spin_pause() for this target." #endif // Target check
{ "domain": "codereview.stackexchange", "id": 42828, "lm_label": 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++20, locking", "url": null }
c++, multithreading, c++20, locking #else # error "Implement spin_pause() for this target." #endif // Target check Then, if you need to migrate to ARM64, for example, you can update this to generate an isb sy instruction in your spinlocks on Clang, GCC or MSVC with: #if __x86__ || __x86_64__ || _M_IX86 || _M_X64 #include <immintrin.h> inline void spin_pause() { return _mm_pause(); } #elif __aarch64__ inline void spin_pause() { asm volatile("isb sy"); } #elif _M_ARM64 && _MSC_VER #include <intrin.h> inline void spin_pause() { __isb(_ARM64_BARRIER_SY); } #else # error "Implement spin_pause() for this ISA." #endif // ISA check (This is a hypothetical example; many real spinlocks for ARM64 use acquire/release semantics to generate a dmb instruction instead.) Consider Yielding On Intel, a PAUSE instruction will tell the CPU to let any other hardware threads on the same core make progress, but it won’t necessarily tell the OS that your thread is spinning. This makes it more likely to lose its timeshare in the middle of a critical section. A good compromise is to optimistically retry with a barrier wait for a few times—I’ve read that 16 seems to work well on current hardware—and then yield the thread. If the first sixteen or one hundred waits all timed out, maybe you should yield the CPU. Which might look something like: #include <assert.h> #include <atomic> #include <bit> #include <stdint.h> #include <thread> #if __x86__ || __x86_64__ || _M_IX86 || _M_X64 #include <immintrin.h> inline void spin_pause() { return _mm_pause(); } #else # error "Implement spin_pause() for this ISA." #endif // ISA check /* The alignas hint is needed for some compilers, such as Clang++ 13 x86_64, to * generate cmpxchg instructions. */ struct alignas(8) state_t { uint32_t ticket; uint16_t priority_threads_waiting; bool in_use; // G++ generates much better code if we pad this out to exactly 64 bits. char pad[sizeof(uint64_t) - sizeof(uint32_t) - sizeof(uint16_t) - sizeof(bool)] = {}; };
{ "domain": "codereview.stackexchange", "id": 42828, "lm_label": 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++20, locking", "url": null }
c++, multithreading, c++20, locking /* The default comparison operator on a state_t does separate comparisons on each * member variable. It is more efficient to compare the object representations. */ bool inline operator==( const state_t& a, const state_t& b ) { static_assert( sizeof(state_t) == sizeof(uint64_t), "" ); static_assert( alignof(state_t) >= alignof(uint64_t), "" ); return std::bit_cast<uint64_t>(a) == std::bit_cast<uint64_t>(b); /* A compiler that does not support std::bit_cast might instead need: return *reinterpret_cast<const uint64_t*>(&a) == *reinterpret_cast<const uint64_t*>(&b); * That is technically undefined behavior, though. Could also use memcmp(). */ } bool inline operator!=( const state_t& a, const state_t& b ) { return !(a == b); } static_assert( std::atomic<state_t>::is_always_lock_free, "" ); #include <cstdlib> #include <iomanip> #include <iostream> using std::cout; /* Spins until it successfully observes the expected value of the variable, * and replaces it with the desired value. Returns the desired value. T * must be comparable and copyable. It should fit in one or two registers and * atomic<T> should be lock-free. Not currently required as constraints. */ template<class T> T spin_CAS( std::atomic<T>& variable, const T expected, const T desired ) { constexpr unsigned spin_optimism = 16; /* It is significantly faster to check for the desired state with a load * than by attempting a compare-exchange, which locks the bus on x86_64. */ do { // Attempt a limited number of retries, then yield the thread. for ( unsigned i = spin_optimism; i > 0; --i ) { T current = expected; if ( variable.load(std::memory_order_relaxed) == current && variable.compare_exchange_weak( current, desired, std::memory_order_acquire ) ) { return desired; } // end if spin_pause(); } // end for
{ "domain": "codereview.stackexchange", "id": 42828, "lm_label": 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++20, locking", "url": null }
c++, multithreading, c++20, locking // Checking for an erroneous state would go here. std::this_thread::yield(); } while (true); } void thread_increment( std::atomic<state_t>& s, const std::atomic_uint32_t& ticket ) /* This simulates the other low-priority threads in the program by updating the * counter with acquire-release semantics. */ { // constexpr unsigned spin_optimism = 16; state_t current = s.load(std::memory_order_relaxed); state_t desired = { current.ticket+1, 0, false }; unsigned long counter = 0x01000000; while ( !s.compare_exchange_strong( current, desired, std::memory_order_acq_rel ) || desired.ticket < ticket.load(std::memory_order_acquire)-1 ) { if (current.ticket >= counter ) { cout.flush(); cout << std::hex << current.ticket << std::endl; counter += 0x01000000; } desired = { current.ticket+1, 0, false }; } // end while cout.flush(); cout << "Incrementer: " << std::hex << desired.ticket << std::endl; } std::atomic_uint32_t our_ticket = 0x12345678; std::atomic<state_t> test_state = state_t{ 0x01, 0, false }; int main() { auto t1 = std::thread( thread_increment, std::ref(test_state), std::ref(our_ticket) ); const auto ticket = our_ticket++; auto current = spin_CAS( test_state, state_t{ ticket, 0, false }, state_t{ ticket, 1, false } ); const auto punched_ticket = current.ticket; cout.flush(); cout << "Main thread: {" << std::hex << current.ticket << ", " << current.priority_threads_waiting << ", " << (current.in_use ? "true" : "false") << "}" << std::endl;
{ "domain": "codereview.stackexchange", "id": 42828, "lm_label": 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++20, locking", "url": null }
c++, multithreading, c++20, locking while(!test_state.compare_exchange_strong( current, { punched_ticket+1, 0, false }, std::memory_order_release )) { cout.flush(); cout << "Incorrectly spinning: {" << std::hex << current.ticket << ", " << current.priority_threads_waiting << ", " << (current.in_use ? "true" : "false") << "}" << std::endl; } t1.join(); return EXIT_SUCCESS; } Edit: All compilers I tested generate much better code when the structure used for CAS is padded and aligned to an exact 64-bit boundary. It also compiles correctly on ICX 2022 and MSVC, although neither optimizes it as well. On Clang++ 13.0.0 on Linux with -std=c++20 -Os -march=x86-64-v4, the spin_CAS function compiles to the following inline loop: .LBB1_1: # =>This Loop Header: Depth=1 mov ecx, 16 .LBB1_2: # Parent Loop BB1_1 Depth=1 mov rax, qword ptr [rip + test_state] cmp rax, rbp jne .LBB1_4 mov rax, rbp lock cmpxchg qword ptr [rip + test_state], r14 je .LBB1_6 .LBB1_4: # in Loop: Header=BB1_2 Depth=2 pause dec ecx jne .LBB1_2 call sched_yield jmp .LBB1_1
{ "domain": "codereview.stackexchange", "id": 42828, "lm_label": 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++20, locking", "url": null }
c++, multithreading, c++20, locking There is, as you can see, a small bug in both Clang++13.0.0 and ICX 2022: they generate a wasteful mov instruction in the not-taken branch of a jump-if-not-equal, which sets a register to the register it just compared equal to! So, this loop should ideally be shorter. You’d have to test to see if this improves performance, but in theory, this should allow other threads to progress make it less likely that a thread will time out while holding the lock, and perhaps save some battery life. Are You Using the Right Memory Order? Right now, you’re performing compare-and-swap with memory_order_acq_rel semantics. If you’re not depending on any data updates to or from other threads to be visible, you probably want memory_order_relaxed (although, if you’re using the right structures, the memory order should not actually generate different code on x86_64). You don’t want your CAS loop to give every other core a chance to alter the variable and starve you before you attempt to set it. Is There a Better Algorithm? You’re using a locking algorithm, but you sound like you want to minimize starvation. Would you be able to use a wait-free algorithm instead, at the cost of lower average throughput? This would avoid CAS and spinlocks entirely, using only operations such as test-and-set, increment and decrement. Can you use a Receive-Copy-Update pattern that does not need to hold a lock, only to swap an atomic pointer?
{ "domain": "codereview.stackexchange", "id": 42828, "lm_label": 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++20, locking", "url": null }
python, windows, graphics Title: Python module to print in printer Question: I made a code that simplifies the job of sending anything to print with the Windows API. The module has a Document object which stores a reference to the actual device context within it. You can access some of the real DC functions, like Document.dc.Polygon to draw polygons. Any recommendation or improvement that occurs to you is welcome. import win32print import win32gui import win32ui import win32con import win32api #https://stackoverflow.com/a/25610343/12913664 # import gdi32 (used to be able to load font files) import ctypes gdi32 = ctypes.WinDLL('gdi32') #if pillow is not installed, this fails silently. try: from PIL import Image, ImageWin except ImportError: pass class Anchor: # Each of these constants signifies a specific origin of coordinates. NW = 0 N = 1 NE = 2 E = 3 W = 4 SW = 5 S = 6 SE = 7 C = 8 def nw_to(new_origin, x, y, width, height): "Internal use. Transforms coordinates whose origin is northwest to another origin." if(new_origin == Anchor.N): x -= width//2 elif(new_origin == Anchor.NE): x -= width elif(new_origin == Anchor.E): x -= width y -= height//2 elif(new_origin == Anchor.W): y -= height//2 elif(new_origin == Anchor.SW): y -= height elif(new_origin == Anchor.S): x -= width//2 y -= height elif(new_origin == Anchor.SE): x -= width y -= height elif(new_origin == Anchor.C): x -= width//2 y -= height//2 return x, y class Document: def __init__(Self, printer=None, properties={}, mapmode=win32con.MM_LOMETRIC): """ Create a new instance of Document. This allows you to send to the printer.
{ "domain": "codereview.stackexchange", "id": 42829, "lm_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, windows, graphics", "url": null }
python, windows, graphics printer: This argument is passed to the win32print.OpenPrinter function. If None, the default printer is passed. properties: This argument should be a dictionary. Each dictionary key must be a valid attribute for the PyDevMode object. This dictionary is used to set attributes to the object returned by win32print.GetPrinter(hprinter, 2)["pDevMode"]. By default this is an empty dictionary. mapmode: This argument is passed to Self.dc.SetMapMode(mapmode). By default it is win32con.MM_LOMETRIC. """ #https://newcenturycomputers.net/projects/pythonicwindowsprinting.html if(printer is None): printer = win32print.GetDefaultPrinter() hprinter = win32print.OpenPrinter(printer) devmode = win32print.GetPrinter(hprinter, 2)["pDevMode"] #http://timgolden.me.uk/pywin32-docs/PyDEVMODEW.html for k, v in properties.items(): setattr(devmode, k, v) Self.hdc = win32gui.CreateDC("WINSPOOL", printer, devmode) Self.dc = win32ui.CreateDCFromHandle(Self.hdc) #https://docs.microsoft.com/en-us/cpp/mfc/reference/cdc-class?view=msvc-170#remarks-160 Self.dc.SetMapMode(mapmode) def text(Self, x, y, text, width=None, height=None, format=win32con.DT_LEFT, anchor=Anchor.NW): """ Draw text on the page. x: The x coordinate. y: The y coordinate. text: The text to draw. It can contain line breaks and non-ascii characters among other things. width: The width of the rectangle where the text is drawn. By default, it is calculated. height: The height of the rectangle where the text is drawn. By default, it is calculated.
{ "domain": "codereview.stackexchange", "id": 42829, "lm_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, windows, graphics", "url": null }
python, windows, graphics height: The height of the rectangle where the text is drawn. By default, it is calculated. format: Characteristics of the text to draw. More information here: https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-drawtextw#parameters. Constants can be obtained with win32con.theconstant. To use more than one you can put win32con.theconstant|win32con.theconstant2... Default is win32con.DT_LEFT. anchor: Specifies the coordinate origin relative to the text. By default it is Anchor.NW. """ #https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-drawtextw calcwidth = (width is None) calcheight = (height is None) if(calcwidth or calcheight): rect = (0, 0, (0 if(calcwidth) else width), (0 if(calcheight) else height)) rect = win32gui.DrawTextW(Self.hdc, text, -1, rect, format|win32con.DT_CALCRECT)[1] if(calcwidth): width = rect[2] if(calcheight): height = rect[3] x, y = Anchor.nw_to(anchor, x, y, width, height) win32gui.DrawTextW(Self.hdc, text, -1, (x, y, x+width, y+height), format) def image(Self, x, y, image, anchor=Anchor.NW): """ Draw an image on the page (requires Pillow) x: the x coordinate y: the y coordinate image: An image-like object or an instance of str that represents the path of the image to draw. anchor: Specifies the coordinate origin relative to the image. By default it is Anchor.NW. """ if(isinstance(image, str)): image = Image.open(image) x, y = Anchor.nw_to(anchor, x, y, image.width, image.height) ImageWin.Dib(image).draw(Self.hdc, (x, y, x+image.width, y+image.height)) def line(Self, *points): """ draw one or more lines.
{ "domain": "codereview.stackexchange", "id": 42829, "lm_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, windows, graphics", "url": null }
python, windows, graphics def line(Self, *points): """ draw one or more lines. Each argument to this function must be a tuple of the format (x, y) """ first_point, *points = points Self.dc.MoveTo(first_point) for point in points: Self.dc.LineTo(point) @property def printable_area_size(Self): "Gets the width and height of the printable area in logical units." return Self.dc.DPtoLP((Self.dc.GetDeviceCaps(win32con.HORZRES), Self.dc.GetDeviceCaps(win32con.VERTRES))) def close(Self): "Close the document. Any correction or process that needs to be done to correctly clean the memory is welcome c:" Self.dc.EndDoc() del Self.dc def load_font_file(file): #https://stackoverflow.com/questions/11993290/truly-custom-font-in-tkinter "Upload a font file." FR_PRIVATE = 0x10 file = ctypes.byref(ctypes.create_unicode_buffer(file)) font_count = gdi32.AddFontResourceExW(file, FR_PRIVATE, 0) if(font_count == 0): raise RuntimeError("Error durante la carga de la fuente.") # example code # if(__name__ == "__main__"): doc = Document("Microsoft Print to PDF", properties=dict(Orientation=win32con.DMORIENT_LANDSCAPE), mapmode=win32con.MM_TEXT) # startdoc doc.dc.StartDoc("prueba", "prueba.pdf") doc.dc.StartPage() area_width, area_height = doc.printable_area_size # image image = Image.new("RGB", (1000, 1000), color=(200, 100, 0)) doc.image(area_width//2, area_height//2, image, anchor=Anchor.C) # text doc.dc.SetBkMode(win32con.TRANSPARENT) font = win32ui.CreateFont({"name":"Calibri", "height":200}) doc.dc.SelectObject(font) doc.text(area_width//2, area_height//2, "Esto es un mensaje de prueba con tilde y ñ: canción", width=image.width, format=win32con.DT_WORDBREAK|win32con.DT_CENTER, anchor=Anchor.C)
{ "domain": "codereview.stackexchange", "id": 42829, "lm_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, windows, graphics", "url": null }
python, windows, graphics # enddoc doc.dc.EndPage() doc.close() Answer: Wrong Conceptual Model An interesting module, but you need to rethink it a bit. It is a print context, not a document. A document would hold things like paragraphs, images, charts, and what not. Your Document class holds a dc and an hdc, but no content. You should rename it to something else. Autoclose You have a close() method. You should implement the __enter__ and __exit__ methods, so the class could be used as a context manager in a with statement, so the close() method is automatically called. Eg) class Document: ... # other methods def close(self): """Close the document. Any correction or process that needs to be done to correctly clean the memory is welcome c:""" # Only close if not already closed if self.dc: self.dc.EndDoc() self.dc = None def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() ... if __name__ == '__main__': with Document("Microsoft Print to PDF", properties=dict(Orientation=win32con.DMORIENT_LANDSCAPE), mapmode=win32con.MM_TEXT) as doc: doc.dc.StartDoc("prueba", "prueba.pdf") doc.dc.StartPage() ... etc ... # no need for doc.close() at the end You can still call doc.close() if you want to. You don't need to use the with statement and rely on the automatic closing, but if you don't then being correct when handling exceptions becomes much more difficult. PEP 8 The Style Guide for Python Code enumerates many requirements you should follow. If you ever want to lint/check your code with pylint, pyflakes, pypy, mypy, etc., you'll find you'll have far too many messages generated by the checkers if you do not follow them! These include:
{ "domain": "codereview.stackexchange", "id": 42829, "lm_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, windows, graphics", "url": null }
python, windows, graphics Python does not require ()’s around the condition in an if statements. You should remove these. white space on either side of operators, so statements like x -= width//2 should be x -= width // 2. variables should be snake_case. In particular, Self should be self. If you intend on publishing the module, and hope to have anyone contribute to help you improve the code, you'll turn those contributors off right at the start if your code isn't even close to being PEP 8 compliant! Enum Your Anchor class should be an Enum class. Coding from the hip, this might look like: from enum import Enum class Anchor(Enum): NW = 0 N = 1 NE = 2 E = 3 W = 4 SW = 5 S = 6 SE = 7 C = 8 def from_nw(self, x: int, y: int, width: int, height: int) -> tuple[int, int]: if self in {Anchor.NE, Anchor.E, Anchor.SE}: x -= width elif self in {Anchor.N, Anchor.C, Anchor.S}: x -= width // 2 if self in {Anchor.SE, Anchor.S, Anchor.SW}: y -= height elif self in {Anchor.E, Anchor.C, Anchor.W}: y -= height // 2 return x, y And instead of: x, y = Anchor.nw_to(anchor, x, y, width, height) you'd use it like: x, y = anchor.from_nw(x, y, width, height) General Nice to see """docstrings""". You should also add type hints to methods parameters and return values, to improve the documentation even further.
{ "domain": "codereview.stackexchange", "id": 42829, "lm_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, windows, graphics", "url": null }
c#, beginner, sql, error-handling, ado.net Title: Try-catch-finally with 'using' in ADO.NET Question: I want to check if I'm correctly disposing of resources using Ado.NET. I'm not sure when the 'using' statement makes .Dispose() irrelevant. Please bear in mind I'm aware I shouldn't hardcode my SQL commands, this is just for training purposes. internal void CreateTable(string connectionString) { using (var connection = new SqliteConnection(connectionString)) { using (var tableCmd = connection.CreateCommand()) { connection.Open(); tableCmd.CommandText = @"CREATE TABLE IF NOT EXISTS coding ( Id INTEGER PRIMARY KEY AUTOINCREMENT, Date TEXT, Duration TEXT )"; try { int rowCount = tableCmd.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } finally { connection.Dispose(); tableCmd.Dispose(); } } // Console.WriteLine($"\n\nDatabase created! \n\n"); } } } Answer: The using block or the using expression (collectively know as using statements) are just syntactical sugar. They will be translated to a proper try-finally block. If you visit sharplab.io and copy-paste there the following code: using System; public class C { public void M() { using (var disposable = new Disposable()) { Console.WriteLine("Inside the using block"); } } } public class Disposable : IDisposable { public void Dispose() { } }
{ "domain": "codereview.stackexchange", "id": 42830, "lm_label": 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, sql, error-handling, ado.net", "url": null }
c#, beginner, sql, error-handling, ado.net public class Disposable : IDisposable { public void Dispose() { } } then the decompile code will look like this: public class C { public void M() { Disposable disposable = new Disposable(); try { Console.WriteLine("Inside the using block"); } finally { if (disposable != null) { ((IDisposable)disposable).Dispose(); } } } } public class Disposable : IDisposable { public void Dispose() { } } For the sake of simplicity I have omitted the attributes. The good news is that the compiler is smart enough to incorporate catch blocks into the generated code (instead of naively have two nested try blocks). Source using System; public class C { public void M() { using var disposable = new Disposable(); try { _ = disposable.Get(); } catch (DivideByZeroException) { Console.WriteLine("Something went wrong"); } } } public class Disposable : IDisposable { public int Get() { throw new DivideByZeroException(); } public void Dispose() { } } Decompiled public class C { public void M() { Disposable disposable = new Disposable(); try { disposable.Get(); } catch (DivideByZeroException) { Console.WriteLine("Something went wrong"); } finally { if (disposable != null) { ((IDisposable)disposable).Dispose(); } } } } public class Disposable : IDisposable { public int Get() { throw new DivideByZeroException(); } public void Dispose() { } }
{ "domain": "codereview.stackexchange", "id": 42830, "lm_label": 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, sql, error-handling, ado.net", "url": null }
c#, game Title: Create walls in a game from a random maze Question: I use four bools, if true a wall is in that direction: bool top = true; bool bottom = true; bool left = true; bool right = true; Then I work through the four and create a wall for each: //Create Walls if (top) { GameObject myWallSelection = WallSectionTop[Random.Range(0, WallSectionTop.Count)]; var myWall = Instantiate(myWallSelection, transform.position, Quaternion.identity); myWall.transform.parent = GameObject.Find("LevelDesign").transform; } if (bottom) { GameObject myWallSelection = WallSectionBottom[Random.Range(0, WallSectionBottom.Count)]; var myWall = Instantiate(myWallSelection, transform.position, Quaternion.identity); myWall.transform.parent = GameObject.Find("LevelDesign").transform; } if (left) { GameObject myWallSelection = WallSectionLeft[Random.Range(0, WallSectionLeft.Count)]; var myWall = Instantiate(myWallSelection, transform.position, Quaternion.identity); myWall.transform.parent = GameObject.Find("LevelDesign").transform; } if (right) { GameObject myWallSelection = WallSectionRight[Random.Range(0, WallSectionRight.Count)]; var myWall = Instantiate(myWallSelection, transform.position, Quaternion.identity); myWall.transform.parent = GameObject.Find("LevelDesign").transform; } How can I optimise this code and remove duplication?
{ "domain": "codereview.stackexchange", "id": 42831, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, game", "url": null }
c#, game How can I optimise this code and remove duplication? Answer: While Peter Csala's answer starts off well, I personally find that it goes off the rails halfway through and overcomplicates things; but I was following him at the start, so this answer will start from the same point: identify the differences. Each of the four blocks has the same pattern: GameObject myWallSelection = {THE_DIFFERENCE}[Random.Range(0, {THE_DIFFERENCE}.Count)]; var myWall = Instantiate(myWallSelection, transform.position, Quaternion.identity); myWall.transform.parent = GameObject.Find("LevelDesign").transform; Straight off the bat, we can see that the second and third line are never any different. They will clearly be moved in the common logic. When we look at the first line, the only difference is in the choice of the collection that you're using. In all cases, you're really just picking a random element from the chosen collection. The only difference is the collection. This immediately suggests that we can abstract this method, and that the only parameter is the collection. private void DoStuff(GameObject[] myCollection) { // } DoStuff is a terrible name; you should improve this based on what makes sense in the current context. The question doesn't reveal enough context for me to appropriately name it. The logic here is simple enough that you can simply copy/paste your code and make sure to refer to myCollection (again, myCollection should be renamed by you). private void DoStuff(IEnumerable<GameObject> myCollection) { GameObject myWallSelection = myCollection[Random.Range(0, myCollection.Count)]; var myWall = Instantiate(myWallSelection, transform.position, Quaternion.identity); myWall.transform.parent = GameObject.Find("LevelDesign").transform; } Your original code then simple has to choose the appropriate collection and call this method: if (top) DoStuff(WallSectionTop); if (bottom) DoStuff(WallSectionBottom); if (left) DoStuff(WallSectionLeft);
{ "domain": "codereview.stackexchange", "id": 42831, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, game", "url": null }
c#, game if (bottom) DoStuff(WallSectionBottom); if (left) DoStuff(WallSectionLeft); if (right) DoStuff(WallSectionRight); I disagree with the additional part of Peter's answer to introduce a mapping list. Not that it can't be done, but that it obfuscates the code more than it should, especially with the tuple being added into the mix. If the variables weren't individually defined, I would agree. For example, if instead of four boolean values, you had an enum to decide the direction; then the additional mapping would make more sense as the individual directions wouldn't be individually listed in the code. But if you're going with predefined booleans, which the question presupposes, then keeping the handling of each boolean separate yields the best readability. For good measure, I think the random selection logic should be abstracted into a method of its own, simply because it would be much more readable when someone wants to understand what DoStuff does. This random selection can be abstracted generically and added as an extension method to IEnumerable<T>: public static class Extensions { public static IEnumerable<T> SelectRandomElement<T>(this IEnumerable<T> collection) { return collection[Random.Range(0, collection.Count)] } } This improves the readability for DoStuff, because now the reader doesn't have to figure out the random selection logic to understand that a random item is being selected: private void DoStuff(IEnumerable<GameObject> myCollection) { GameObject myWallSelection = myCollection.SelectRandomElement(); var myWall = Instantiate(myWallSelection, transform.position, Quaternion.identity); myWall.transform.parent = GameObject.Find("LevelDesign").transform; }
{ "domain": "codereview.stackexchange", "id": 42831, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, game", "url": null }
performance, c, hash-map Title: Implementing hash table Question: I am implementing a program to interact with hash table, the data to be hashed is just number. It works but I want to know if there is any error like: memory leak,... in my code and how to improve my code. Any help would be appreciated. #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <stdbool.h> typedef struct node { int val; struct node *next; }node; int hash(int val, int n); node **create_hash_table(int n); node *allocate_new_node(int val, node *next); void add_new_node(node **hash_table, int n, int val); void destroy_hash_table(node **hash_table, int n); bool find(node **hash_table, int n, int val); int main(){ //some operation to test the program int n=3; // n is length of hash table node **htable=create_hash_table(n); add_new_node(htable, n, 1); add_new_node(htable, n, -2); add_new_node(htable, n, 3); add_new_node(htable, n, 4); add_new_node(htable, n, 5); printf("%d", find(htable, n, -2)); destroy_hash_table(htable, n); return 0; } int hash(int val, int n){ return abs(val) % n; } node **create_hash_table(int n){ node **tmp=calloc(n, sizeof *tmp); // initialize all pointer to NULL if(!tmp){ fprintf(stderr, "create hash table failed"); exit(EXIT_FAILURE); } return tmp; } node *allocate_new_node(int val, node *next){ node *tmp=malloc(sizeof *tmp); if (!tmp) { fprintf(stderr, "allocate new node failed"); exit(EXIT_FAILURE); } tmp->val=val; tmp->next=next; return tmp; } void add_new_node(node **hash_table, int n, int val){ // insert new node to the head of the linked list int hashNumber=hash(val, n); node *tmp=allocate_new_node(val, hash_table[hashNumber]); hash_table[hashNumber]=tmp; }
{ "domain": "codereview.stackexchange", "id": 42832, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, hash-map", "url": null }
performance, c, hash-map void destroy_hash_table(node **hash_table, int n){ for (size_t i = 0; i < n; i++) { node *head=hash_table[i]; node *tmp=head; while (head) { tmp=head->next; free(head); head=tmp; } } } bool find(node **hash_table, int n, int val){ int hashNumber=hash(val, n); node *tmp=hash_table[hashNumber]; while (tmp) { if (tmp->val==val) { return true; } tmp=tmp->next; } return false; } Answer: You do leak memory because you forgot to free hash_table in destroy_hash_table(). To correct the issue, you need to free the allocated hash table after freeing all allocated nodes, e.g. void destroy_hash_table(node **hash_table, int n){ for (int i = 0; i < n; i++) { node *head=hash_table[i]; node *tmp=head; while (head) { tmp=head->next; free(head); head=tmp; } } free (hash_table); } The other issue is just a "nit". Keep your types consistent to prevent comparison between signed and unsigned values in destroy_hash_table(). You pass in n as int, but then declare your loop variable as size_t. Change the size_t to int (or go back through your code and change all int to size_t since n is a counter and can't be negative). The immediate fix is: for (int i = 0; i < n; i++)
{ "domain": "codereview.stackexchange", "id": 42832, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, hash-map", "url": null }
performance, c, hash-map That seems to be the two I saw. The final issue in your implementation is you completely omit the concept of load-factor. For efficient operation of the hash table, the number of buckets filled divided by the total buckets is the load-factor. It should never exceed 0.7. You should keep track of the number of buckets filled and available and reallocate/rehash when your load-factor exceeds the target. You may find Coding up a Hash Table and Hash tables - eternally confuzzled useful in further implementing the load-factor test, and for hash tables generally. A working example of a load-factor implementation is Hashtable for Strings using LH_strhash() Hash Function.. That example hashes strings instead of numbers, but the load-factor handling is the same.
{ "domain": "codereview.stackexchange", "id": 42832, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, hash-map", "url": null }
javascript, html, css, api, event-handling Title: Updating active cards dynamically added by API Question: I am making a website where you can search through all the countries in the world. Once you have found a country you want more detail about you should be able to click and view a detailed page with more info. I am having trouble updating the countries that are currently shown with the user's restrictions. I want to add an eventListener to every active card to be able to open the detail page for that specific country. Is there a way to do it without an interval function checking every other second? I have a feeling this is not the correct way. Here is the interval function: function updateActiveCards(){ activeCards = Array.from(document.querySelectorAll('.search-result-card')); } setInterval(updateActiveCards, 1000); Here is an example of how a search result would look All the added cards get a class of 'search-result-card' and they are added by this code: async function loadCountriesByName(name){ const respone = await fetch('https://restcountries.com/v2/name/' + name); const data = await respone.json(); data.map(element => { addCountry(element); }); } async function loadAllCountries(){ const response = await fetch('https://restcountries.com/v2/all'); const data = await response.json(); data.map(element => { addCountry(element); }); } searchBar.addEventListener('input', () => { const currentValue = searchBar.value; if(currentValue == ''){ results.innerHTML = ''; loadAllCountries(); } else { results.innerHTML = ''; loadCountriesByName(currentValue); } });
{ "domain": "codereview.stackexchange", "id": 42833, "lm_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, html, css, api, event-handling", "url": null }
javascript, html, css, api, event-handling function addCountry(CountryData){ const newCard = document.createElement('div'); newCard.classList.add('search-result-card'); newCard.innerHTML = ` <div class="country-img"> <img src="${CountryData.flag}" alt=""> </div> <div class="country-info"> <h2>${CountryData.name}</h2> <h3>Population: <span>81,770,900</span></h3> <h3>Region: <span>Europe</span></h3> <h3>Capital: <span>Berlin</span></h3> </div> ` results.append(newCard); } loadAllCountries() Thanks in advance! Answer: Disclaimer This is my response based on the following information: At the start, all countries with basic details shall be listed. A user can type some string and the countries displayed will be reduced to only those matching the filter. At anytime, before or after searching, a country "card" can be clicked, forcing the page to update with more detailed information. Solution I have created a small repo using some of your code examples and expanding on them as needed. I did not worry about styling or populating information on the page as the concern was regarding the click event. This line has what I believe you are looking for regarding an eventListener. newCard.onclick = cardClickHandler Once you have your element, you can attach a function as a handler for any of its events. Code Review As this is the codereview stackexchange, I feel obliged to pass along a few comments on your approach. As a common courtesy to API providers (internal or external) try to make as few requests as needed to accomplish your goals. This block of code makes a request to the all countries end point every time the search is cleared, which I feel is not necessary in this case. You would be safe to assume that this data is not going to change during a user's visit to this page. See these lines of code for an alternative. if(currentValue == ''){ results.innerHTML = ''; loadAllCountries(); } else {
{ "domain": "codereview.stackexchange", "id": 42833, "lm_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, html, css, api, event-handling", "url": null }
javascript, html, css, api, event-handling I'm not sure what the purpose of this assignment is (school, work, hobby, etc.), but you should consider approaching problems like this with a library (react, angular, vue) designed for helping with some of the ideas you are trying to implement (components, event handling) Hopefully this helps.
{ "domain": "codereview.stackexchange", "id": 42833, "lm_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, html, css, api, event-handling", "url": null }
python, web-scraping, selenium Title: Web-scrape bonds information from nasdaqomxnordic Question: I'm a newbie getting into web scrapers. I've made something that works, it takes 3.2 hours to complete job and randomly have 10 lines blank each time I run this job. Help is much appreciated! import sys import pandas as pd from selenium import webdriver import time from datetime import datetime from bs4 import BeautifulSoup from selenium.webdriver.support.select import Select from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import NoSuchElementException from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from webdriver_manager.chrome import ChromeDriverManager def getBrowser(): options = Options() options.add_argument("--incognito") global browser options.add_argument("start-maximized") s = Service('''C:\\Users\\rajes\\yogita\\drivers\\chromedriver.exe''') browser = webdriver.Chrome('''C:\\Users\\rajes\\yogita\\drivers\\chromedriver.exe''') return browser
{ "domain": "codereview.stackexchange", "id": 42834, "lm_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, web-scraping, selenium", "url": null }
python, web-scraping, selenium def getISINUrls(browser): url = 'http://www.nasdaqomxnordic.com/bonds/denmark/' browser.get(url) browser.maximize_window() time.sleep(1) bonds = {} try: getUrls(browser, bonds) pg_down = browser.find_element(By.CSS_SELECTOR, "#bondsSearchDKOutput > div:nth-child(1) > table > tbody > tr > td.pgDown") browser.execute_script("arguments[0].click();", pg_down) time.sleep(1) while (True): # pages = browser.find_element(By.ID, 'bondsSearchDKOutput') getUrls(browser, bonds) pg_down = browser.find_element(By.CSS_SELECTOR, "#bondsSearchDKOutput > div:nth-child(1) > table > tbody > tr > td.pgDown") browser.execute_script("arguments[0].click();", pg_down) time.sleep(1) except NoSuchElementException as e: pass return bonds def getUrls(browser, bonds): hrefs_in_table = browser.find_elements(By.XPATH, '//a[@href]') count = 0 for element in hrefs_in_table: href = element.get_attribute('href') if 'microsite?Instrumen' in href: bonds[element.text] = href count += 1 def saveURLs(bond): filename = "linkstoday.txt" fo = open(filename, "w") for k, v in bonds.items(): fo.write(str(v) + '\n') fo.close() def getSleepTime(count): first = 1 res = 1 i = 0; while i < count: i += 1 temp = res res = temp + first first = temp return res def getISINData(browser2): with open("linkstoday.txt", "r") as a_file: denmark_drawing = []
{ "domain": "codereview.stackexchange", "id": 42834, "lm_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, web-scraping, selenium", "url": null }
python, web-scraping, selenium for line in a_file: result_found = False count = 2 Isin_code = str() short_name = str() Volume_circulating = str() Repayment_date = str() Drawing_percent = str() wait_time = getSleepTime(0) + 1 while not result_found and count < 5: stripped_line = line.strip() browser2.get(stripped_line) browser2.maximize_window() time.sleep(getSleepTime(count) + 1) WebDriverWait(browser2, 1).until( EC.element_to_be_clickable((By.CSS_SELECTOR, '#ui-id-3 > span'))).click() time.sleep(getSleepTime(count)) Isin_code = browser2.find_element(By.CSS_SELECTOR, '#db-f-isin').text short_name = browser2.find_element(By.CSS_SELECTOR, '#db-f-nm').text Volume_circulating = browser2.find_element(By.CSS_SELECTOR, '#db-f-oa').text Repayment_date = browser2.find_element(By.CSS_SELECTOR, '#db-f-drd').text Drawing_percent = browser2.find_element(By.CSS_SELECTOR, '#db-f-dp').text if Isin_code == " ": count += 1 else: result_found = True temp_data = [Isin_code, short_name, Volume_circulating, Repayment_date, Drawing_percent] denmark_drawing.append(temp_data) # Writing data to dataframe df3 = pd.DataFrame(denmark_drawing, columns=['ISIN', 'Shortname', 'OutstandingVolume', 'Repaymentdate', 'Drawingpercent']) df3.to_csv('Denamrkscrapedsata_20220121.csv', index=False)
{ "domain": "codereview.stackexchange", "id": 42834, "lm_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, web-scraping, selenium", "url": null }