text
stringlengths
1
2.12k
source
dict
c++, object-oriented, design-patterns, entity-component-system, constrained-templates private: inline static size_t IDCounter = 0; friend class ECSManager; }; EntityManager.h #pragma once #include <memory> #include <vector> #include "EntityExceptions.h" class EntityManager { public: std::weak_ptr<Entity> createEntity(); void removeEntity(Entity entity); size_t getEntityCount() const { return entities.size(); } private: inline static std::vector<std::shared_ptr<Entity>> entities; }; EntityManager.cpp #include "EntityManager.h" std::weak_ptr<Entity> EntityManager::createEntity() { auto entity = std::make_shared<Entity>(entities.size()); entities.push_back(entity); return entity; } void EntityManager::removeEntity(Entity entity) { if (entity.index >= entities.size() || entities.empty()) throw EntityOutOfBoundsException(entity); if (entity.index < entities.size()) { entities[entity.index] = entities.back(); entities[entity.index]->index = entity.index; } entities.pop_back(); } EntityManager.h #pragma once #include <memory> #include <vector> #include "EntityExceptions.h" class EntityManager { public: std::weak_ptr<Entity> createEntity(); void removeEntity(Entity entity); size_t getEntityCount() const { return entities.size(); } private: inline static std::vector<std::shared_ptr<Entity>> entities; }; System.h #pragma once #include "SystemContext.h" class System { public: virtual ~System() = default; virtual void onAdded() = 0; virtual void update(float deltaTime, SystemContext& context) = 0; virtual void onRemoved() = 0; void enable(bool enabled) { this->enabled = enabled; } bool isEnabled() const { return enabled; } private: bool enabled = true; }; SystemContext.h #pragma once #include <iterator> #include "ComponentManager.h" #include "EntityManager.h" #include "ArchetypeManager.h" #include "Cache.h"
{ "domain": "codereview.stackexchange", "id": 44878, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates", "url": null }
c++, object-oriented, design-patterns, entity-component-system, constrained-templates class SystemContext { public: template<typename... ComponentTypes> using UpdateFn = std::function<void(Entity entity, ComponentTypes&...)>; SystemContext(const EntityManager& entityManager, ComponentManager& componentManager, ArchetypeManager& archetypeManager) : entityManager(entityManager), componentManager(componentManager), archetypeManager(archetypeManager) { } template<typename ComponentType> bool hasComponent(Entity entity) const { return componentManager.hasComponent<ComponentType>(entity); } template<typename ComponentType> const ComponentType& getComponent(Entity entity) const { return componentManager.getComponent<ComponentType>(entity); } template<typename ComponentType, typename... Args> void createComponent(Entity entity, Args&&... args) { componentManager.addComponent<ComponentType>(entity, std::forward(args)...); archetypeManager.addComponent<ComponentType>(entity); } template<typename... ComponentTypes> void updateEntitiesWithComponents(const UpdateFn<ComponentTypes...>& update) const { for (auto entity : archetypeManager.findCommonEntities<ComponentTypes...>()) update(entity, componentManager.getComponent<ComponentTypes>(entity)...); } private: const EntityManager& entityManager; ComponentManager& componentManager; ArchetypeManager& archetypeManager; }; SystemExceptions.h #pragma once #include <stdexcept> class SystemNotFoundException : public std::runtime_error { public: SystemNotFoundException(const std::string& systemType) : std::runtime_error("System not found: " + systemType) {} }; class SystemAlreadyAddedException : public std::runtime_error { public: SystemAlreadyAddedException(const std::string& systemType) : std::runtime_error("System is already added: " + systemType) {} }; SystemManager.h #pragma once
{ "domain": "codereview.stackexchange", "id": 44878, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates", "url": null }
c++, object-oriented, design-patterns, entity-component-system, constrained-templates SystemManager.h #pragma once #include <list> #include <memory> #include <stdexcept> #include "System.h" #include "SystemExceptions.h" #include "TypeTag.h" class SystemManager { public: SystemManager(const SystemContext& context) : context(context) { } template<typename SystemType, typename... Args> void addSystem(Args&&... args) { size_t index = SystemTypeTag<SystemType>::index; if(index >= systems.size()) systems.resize(index + 1); if(systems[index]) throw SystemAlreadyAddedException(typeid(SystemType).name()); systems[index] = std::make_unique<SystemType>(std::forward<Args>(args)...); systems[index]->onAdded(); } template<typename SystemType> void removeSystem() { size_t index = SystemTypeTag<SystemType>::index; if(index >= systems.size() || systems[index] == nullptr) throw SystemNotFoundException(typeid(SystemType).name()); systems[index]->onRemoved(); systems[index].reset(); } template<typename SystemType> bool hasSystem() const { size_t index = SystemTypeTag<SystemType>::index; return index < systems.size() && systems[index]; } template<typename SystemType> void enableSystem(bool enabled) { size_t index = SystemTypeTag<SystemType>::index; systems[index]->enabled(enabled); } void updateSystems(float deltaTime) { for (auto& system : systems) if(system != nullptr && system->isEnabled()) system->update(deltaTime, context); } private: inline static std::vector<std::unique_ptr<System>> systems; SystemContext context; }; TypeTag.h #pragma once struct BaseComponentTypeTag { inline static size_t typeCounter = 0; }; template <typename ComponentType> struct ComponentTypeTag : public BaseComponentTypeTag { inline static size_t index = typeCounter++; };
{ "domain": "codereview.stackexchange", "id": 44878, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates", "url": null }
c++, object-oriented, design-patterns, entity-component-system, constrained-templates struct BaseSystemTypeTag { inline static size_t typeCounter = 0; }; template <typename ComponentType> struct SystemTypeTag : public BaseSystemTypeTag { inline static size_t index = typeCounter++; }; struct BaseVariadicTypeTag { inline static size_t typeCounter = 0; }; template <typename... ComponentTypes> struct VariadicTypeTag : BaseVariadicTypeTag { inline static size_t index = typeCounter++; }; Note- I hope I didn't forget any files here Answer: Performance is important The goal of an ECS is to improve performance when handling large numbers of objects. It does that by separating the components from the entities and storing them separately. However, your implementation might actually be slower and use more memory than if you had no ECS at all. Again, both memory and CPU performance matter. You also want to think about how often you do certain operations: you probably are going to update() several systems every frame, and you might add and remove multiple entities each frame. You want high, and just as important, consistent performance. There are a lot of memory allocations happening in your code. That is a problem, because it takes some CPU time to do the allocation, memory might get fragmented, and there is some bookkeeping overhead for each allocation, so even if you do new int you might use a lot more memory than sizeof(int). While you don't explicitly call new (which is good), the following things allocate memory: std::unqiue_ptr<>: one allocation std::shared_ptr<>: at least one allocation (see std::make_shared<>()) std::unordered_set<>: one allocation for each element in the set std::vector<>: one contiguous allocation to hold all elements, but if you don't reserve() up front it might cause multiple allocations/deallocations while the vector is growing
{ "domain": "codereview.stackexchange", "id": 44878, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates", "url": null }
c++, object-oriented, design-patterns, entity-component-system, constrained-templates What you want to achieve is that calls to update() require zero memory allocations, and that adding/removing entities and components also requires close to zero allocations. A cache that you throw away whenever you add/remove components is pretty bad. Why not just in removeComponent() if you can just remove that one entity from the stored set of entities? And in addComponent(), check if you can just add it? Instead of using a cache, it would be better to lay out data in memory so that it's efficient to add and remove components to begin with. Have a look at this Code Review question, where the poster has written an ECS framework that focussed heavily on keeping things in dense arrays and vectors, and having fast updates.
{ "domain": "codereview.stackexchange", "id": 44878, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates", "url": null }
c++, multithreading, tree, graph Title: Parallel semi-sequential bottom-up tree traversal algorithm Question: I'm trying to traverse a tree-like structure from the bottom-up, and in parallel. Due to some other constraints I also have to allow for thread counts that may be lower than the width of a given set of child nodes. Each parent node also requires all child nodes to be visited before it itself can be visited. I've come up with an implementation that seems to work, but I'd like to get your opinion on it, and know whether there are some obvious issues with the logic it depends on. Note that I'm using the dp thread pool library for the thread pool itself. Algorithm #include <iostream> #include <map> #include <queue> class node { public: node(int value) : m_value(value) {} const std::vector<node*>& get_children() const { return m_children; } void add_child(node* child) { m_children.push_back(child); } void print() const { std::cout << m_value << '\n'; } private: int m_value; std::vector<node*> m_children; }; // get nodes in breadth-first order std::vector<node*> get_bfs_ordered_nodes(node* root) { std::vector<node*> order; std::queue<node*> q; q.push(root); while (!q.empty()) { node* current_node = q.front(); q.pop(); order.push_back(current_node); for (node* child : current_node->get_children()) { q.push(child); } } return order; } void parallel_bottom_up_traversal(node* root, dp::thread_pool<>& pool) { // get nodes in breadth-first order std::vector<node*> nodes = get_bfs_ordered_nodes(root); std::map<node*, std::shared_future<void>> node_futures; for (auto it = nodes.rbegin(); it != nodes.rend(); ++it) { node* current_node = *it;
{ "domain": "codereview.stackexchange", "id": 44879, "lm_label": 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, tree, graph", "url": null }
c++, multithreading, tree, graph for (auto it = nodes.rbegin(); it != nodes.rend(); ++it) { node* current_node = *it; // store futures of children std::vector<std::shared_future<void>> child_futures; for (node* child : current_node->get_children()) { child_futures.push_back(node_futures[child]); } // create a task for the node and add it to the thread pool const auto future = pool.enqueue([current_node, child_futures]() { // wait for all children to be processed for (auto& fut : child_futures) { fut.get(); } // process the node current_node->print(); }); // store the future for this node node_futures[current_node] = future; } // wait for the root to be processed node_futures[root].get(); } Usage int main() { dp::thread_pool pool(2); node* root = new node(0); node* child1 = new node(1); node* child2 = new node(2); node* child3 = new node(3); node* child4 = new node(4); node* child5 = new node(5); root->add_child(child1); root->add_child(child2); child1->add_child(child3); child3->add_child(child4); child3->add_child(child5); parallel_bottom_up_traversal(root, pool); delete child5; delete child4; delete child3; delete child2; delete child1; delete root; return 0; } The tree represented in my usage example can be seen below: The traversal order is as follows: 5 4 3 2 1 Answer: Use a depth-first search I know you want the results to be in bottom-up order, but that doesn't mean you have to do a reverse breadth-first search. You can greatly simplify your algorithm by using a depth-first search, which is easy to do using recursion: std::future<void> parallel_bottom_up_traversal(node* root, dp::thread_pool<>& pool) { std::vector<std::future<void>> futures;
{ "domain": "codereview.stackexchange", "id": 44879, "lm_label": 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, tree, graph", "url": null }
c++, multithreading, tree, graph for (auto child: root->get_children()) { futures.push_back(parallel_bottom_up_traversal(child, pool)); } return pool.enqueue([root, futures=std::move(futures)]() mutable { for (auto& future: futures) future.get(); root->print(); }); } How does this work? For each node we will first descend to its children, collect the std::futures the recursive calls return, then enqueue a task that waits for those futures to finish, and then it prints the node's value. The order in which tasks are enqueued is different from your algorithm, but since the tasks are all executed in parallel, and thus there is no guarantee in which order they are completed (apart from that parents wait for children in both your and my version), does that matter? Note that in the version above, a future is returned for the root node. The caller has to call .get() on that future. If you want a function that waits for the algorithm to complete and that returns void, you could make a helper function that does this. Although I think this is nicer; it allows the caller to start multiple traversals in parallel. This DFS version also has the advantage that parallel work is started much sooner; your version first needs a sequential step where it gets the nodes in BFS order. Memory is saved as well; there's no longer a need for nodes and node_futures, only the equivalent of child_futures is used. Make it more generic Your code only works with trees that store ints, and it can only print those ints. What if I want to sum the values of a tree of floats? It's quite easy to make your code more generic by making node a templated class, and have parallel_bottom_up_traversal() take an arbitrary function as a parameter: template<typename T> class node { … T m_value; std::vector<node*> children; };
{ "domain": "codereview.stackexchange", "id": 44879, "lm_label": 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, tree, graph", "url": null }
c++, multithreading, tree, graph template<typename T, typename Function> parallel_bottom_up_traversal(node<T>* root, dp::thread_pool<>& pool, Function& function) { … std::invoke(function, current_node); … } And use it like: auto root = new node<float>(3.1415); … std::atomic<float> sum = 0; parallel_bottom_up_traversal(root, pool, [](auto& value) { sum += value; }); Even nicer would be to allow functions that return values as well, and that take a vector of futures as an argument so it can access the values returned by the children. That way, the above summation could be done without needing an atomic variable: auto root = new node<float>(3.1415); … auto sum = parallel_bottom_up_traversal(root, pool, [](auto& value, auto& child_futures) { float child_sum = 0; for (auto& future: child_futures) child_sum += future.get(); return child_sum + value; } ).get(); How to change parallel_bottom_up_traversal() for this to work is left as an excercise for the reader. Avoid raw pointers It's easy to make mistakes when using raw pointers, new and delete. Consider using std::unique_ptr to manage memory. For example, you could make a parent node own its children: class node { void add_child(std::unique_ptr<node>&& child) { children.push_back(std::move(child)); } … std::vector<std::unique_ptr<node>> children; }; int main() { auto root = std::make_unique<node>(0); auto child1 = std::make_unique<node>(1); auto child3 = std::make_unique<node>(3); … // Move children into parents, bottom up … child1.add_child(std::move(child3)); root.add_child(std::move(child1)); parallel_bottom_up_traversal(root.get(), pool); // No need to delete anything! } Note that this is just one way to do it, the main point is that ownership is clear and you don't have to do manual cleanups.
{ "domain": "codereview.stackexchange", "id": 44879, "lm_label": 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, tree, graph", "url": null }
python-3.x, bitwise Title: Leetcode 137: Single Number II -- python bit operations Question: I solved LeetCode 137 in C++. TLDR of the problem: array of numbers, nums is given; all numbers appear 3 times, except one which appear only once. Find the number that appears once. When trying to convert my C++ solution to python, I came across few funny things, i.e. the bit operations seem to behave a bit differently in python, on negative integers. So, I switched to using formatting as binary string - but, to my surprise, INT_MIN (-2^32 - 1) resulted in a string of length 33, containing the sign as well. Where could I read more about this and understand why it happens? How can I improve the code below, to make it more pythonic? def singleNumber(self, nums: List[int]) -> int: INT_BASE = 33 # because of INT32_MIN # give python what it likes counts_nz = [0 for _ in range(INT_BASE)] vals_bit = ["0" for _ in range(INT_BASE)] for num in nums: # 33 because of INT32_MIN takes 33 bits to represent. for idx, bin_val in enumerate(f"{num:033b}"): if bin_val != "0": # can be "1" or "-" counts_nz[idx] += 1 vals_bit[idx] = bin_val # make the bits binary string -- set to value for M3 + 1 and 0 otherwise bin_res = "".join( [ vals_bit[idx] if count % 3 == 1 else "0" for idx, count in enumerate(counts_nz) ] ) return int(bin_res, 2) Answer: INT_MIN Yeah, python doesn't really expose a "machine integer" concept. Page 5 of the 1974 MACLISP manual explained it is impossible to get "overflow" in bignum arithmetic ...
{ "domain": "codereview.stackexchange", "id": 44880, "lm_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, bitwise", "url": null }
python-3.x, bitwise it is impossible to get "overflow" in bignum arithmetic ... Now if C code assigns int16 n = 32767 and then n++ increments, we may get the most negative int rather than 32768. Which is fine by programmers but makes mathematicians a bit cross. In python the sign bit is entirely separate. The bit counting trick is nice, I like it. Here is an implementation of that which treats the sign bit seperately. Also, pep-8 asks for a snake_case function name. And List[int] works but in modern interpreters we prefer a lower list[int] annotation. import random import unittest from hypothesis import given import hypothesis.strategies as st def single_number(nums: list[int]) -> int: res = 0 for bit in range(32): counts = sum(num < 0 for num in nums) mask = 1 << bit for num in nums: if abs(num) & mask: counts += 1 if counts % 3 == 1: res |= mask BIAS = 2**31 if res >= BIAS: # caller will need to see a negative result res -= (2 * BIAS - 1) return res class TestLeet137(unittest.TestCase): def test_leet137(self): self.assertEqual(3, single_number([2, 2, 3, 2])) self.assertEqual(0, single_number([2, 1, 2, 1, 2, 1, 0])) self.assertEqual(-99, single_number([0, 1, 0, 1, 0, 1, -99])) def test_negative_binary(self): num = -6 self.assertEqual("-00000000000000000000000000000110", f"{num:033b}") # These constants are specified by https://leetcode.com/problems/single-number-ii LO = -(2**31) HI = 2**31 - 1 @given(st.lists(st.integers(min_value=LO, max_value=HI), min_size=1)) def test_leet(randoms: list[int]): target, *distractors = randoms arg = [target] + distractors * 3 assert single_number(arg) == target arg.sort() assert single_number(arg) == target random.shuffle(arg) assert single_number(arg) == target
{ "domain": "codereview.stackexchange", "id": 44880, "lm_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, bitwise", "url": null }
python-3.x, bitwise random.shuffle(arg) assert single_number(arg) == target The loop effectively produces a 32-bit machine word, so we clean up at the end in order to properly return a negative result. Also in the 2nd test I was highlighting the not-very-binary {"-", "0", "1"} bits you were getting from that string conversion. This might be a good opportunity to import ctypes or fixedint. Given that we need to apply a bias anyway, it seems more convenient to operate on strictly non-negative numbers: def single_number(nums: list[int]) -> int: BIAS = 2**31 nums = [num + BIAS for num in nums] assert all(num >= 0 for num in nums) res = 0 for bit in range(32): counts = 0 mask = 1 << bit for num in nums: if abs(num) & mask: counts += 1 if counts % 3 == 1: res |= mask return res - BIAS No loop change after the counts assignment -- we're just removing negatives up front and then re-adjusting at end. Well, ok, I suppose that pasted abs() is superfluous and should be deleted.
{ "domain": "codereview.stackexchange", "id": 44880, "lm_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, bitwise", "url": null }
c, game, ms-dos Title: DOS-based Boggle simulator Question: I'm testing my C skills by writing my first-ever full application in C. I'm targeting DOS (as in MS-DOS/PC-DOS and DOSBox) and am compiling the code with Open Watcom v2.0. The application does the following: Provides the user with a simple command-based user interface. Generates legal Boggle game boards via emulated Boggle cubes and pseudorandom numbers. Plays a tone when three minutes has elapsed after a round of Boggle has started. Allows the user to terminate a Boggle round mid-game. Uses a simple "dictionary" (which is just a list of words) to allow users to check if words are legal. Displays built-in help on request. This is my first "major" C program and was coded in a rather short amount of time. I realize that many of my variable and function name choices are less-than-awesome, but other than that, what suggestions do you have on how this code could be better as far as code quality and readability? (Note that I'm not interested in optimization - I tested the program on PC-DOS 3.30 with an emulated IBM PC with 256 KB RAM (using 86Box), and it performed acceptably well there, so I'm fairly certain it will perform well enough almost anywhere.) The code: /* --------------------------------------------------------------------------- * |Doggle - Boggle for DOS | * |Copyright (c) 2023 Aaron Rainbolt. Licensed under the MIT License. | * --------------------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <ctype.h> #include <time.h> #include <string.h> #include <i86.h>
{ "domain": "codereview.stackexchange", "id": 44881, "lm_label": 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, ms-dos", "url": null }
c, game, ms-dos /* all of the letters in a box of Boggle dice */ char dice[16][6] = { { 'R', 'H', 'Z', 'L', 'N', 'N' }, { 'G', 'E', 'W', 'N', 'E', 'H' }, { 'B', 'O', 'O', 'J', 'B', 'A' }, { 'F', 'P', 'S', 'A', 'K', 'F' }, { 'S', 'T', 'I', 'T', 'D', 'Y' }, { 'X', 'R', 'D', 'I', 'E', 'L' }, { 'H', 'N', 'U', 'I', 'M', '@' }, /* @ = Qu */ { 'R', 'E', 'T', 'W', 'V', 'H' }, { 'E', 'G', 'N', 'E', 'A', 'A' }, { 'Y', 'T', 'L', 'E', 'T', 'R' }, { 'S', 'H', 'A', 'P', 'C', 'O' }, { 'O', 'T', 'W', 'O', 'T', 'A' }, { 'I', 'E', 'N', 'U', 'S', 'E' }, { 'I', 'O', 'T', 'M', 'U', 'C' }, { 'E', 'Y', 'L', 'D', 'V', 'R' }, { 'T', 'O', 'E', 'S', 'S', 'I' } }; /* Searches for an integer in an int array. * Returns the index of the first matching element if found, or -1 if the * element was not found. */ int intidx(int *arr, int arrLen, int idx) { int i; for (i = 0;i < arrLen;i++) { if (arr[i] == idx) { return idx; } } return -1; } /* Returns a pseudorandom integer less than or equal to upperBound. Thie * function avoids modulo bias. */ int randLte(int upperBound) { int final; int rawUpperBound = 32767 - (32767 % upperBound); while (1) { final = rand(); if (final <= rawUpperBound) { final = final % upperBound; return final; } } }
{ "domain": "codereview.stackexchange", "id": 44881, "lm_label": 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, ms-dos", "url": null }
c, game, ms-dos /* Unsurprisingly, prints a help message. */ void printhelp() { printf("Doggle is a Boggle simulator for DOS.\n"); printf("Press N to generate a new Boggle board.\n"); printf("Press D to search through the dictionary.\n"); printf("Press X to exit.\n"); printf("Press H to display this help message.\n\n"); printf("If you accept a letter grid, and decide that was a bad idea, you can cancel\n"); printf("the current round by pressing X during the game.\n"); } /* Generates a new Boggle board and allows it to be played or discarded. */ void newboard() { char board[16]; int usedIdxs[16]; int i; int j; int idx; int letter; char *letterLine; char currentChar; char input; time_t start; time_t now; /* Generate the board - we randomly select each die **only once**, then randomly select a character from each die.*/ for (i = 0;i < 16;i++) { idx = randLte(16); if (intidx(usedIdxs, 16, idx) == -1) { letter = randLte(6); board[i] = dice[idx][letter]; usedIdxs[i] = idx; } else { i--; } } /* Print the board. */ for (i = 0;i < 4;i++) { printf("+-----+-----+-----+-----+\n"); printf("| | | | |\n"); /* each line of the Boggle board is 27 characters long */ letterLine = malloc(27 * sizeof(char)); strcpy(letterLine, "| | | | |\n"); for (j = 0;j < 4;j++) { currentChar = board[(i * 4) + j]; if (currentChar != '@') { letterLine[(j * 6) + 3] = currentChar; } else { letterLine[(j * 6) + 3] = 'Q'; letterLine[(j * 6) + 4] = 'u'; } } printf(letterLine); printf("| | | | |\n"); } printf("+-----+-----+-----+-----+\n"); /* The bottom side of the board. */ /* Allow the user to reject or accept the board. */ while (1) { printf("Accept board? Y/N "); fflush(stdout); input = getche(); printf("\n"); input = toupper(input);
{ "domain": "codereview.stackexchange", "id": 44881, "lm_label": 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, ms-dos", "url": null }
c, game, ms-dos if (input == 'Y') { /* Start the timer, allowing the user to terminate the game early with the X key. */ start = time(NULL); while (1) { delay(250); now = time(NULL); if (now - start == 180) { /* Three minutes has passed! */ sound(2500); delay(1000); nosound(); break; } if (kbhit()) { input = getch(); input = toupper(input); if (input == 'X') { printf("Game stopped.\n"); break; } } } break; } else if (input == 'N') { break; } free(letterLine); } } /* Allows the user to determine if a particular word exists in Doggle's * dict.txt file. */ void dictionary() { char *input = NULL; char *dictWord = NULL; size_t inputSize = 0; size_t dictWordSize = 0; int i; FILE *dict = fopen("dict.txt", "r"); int wordFound = 0; printf("Type a word and press Enter to see if it exists in the dictionary.\n"); printf("Type \"x\" and press Enter to exit.\n"); while (1) { printf("Doggle:\\dict\\>"); fflush(stdout); getline(&input, &inputSize, stdin); for(i = 0;i < inputSize;i++) { if (input[i] == '\0') { break; } input[i] = tolower(input[i]); } if (strcmp(input, "x\n") == 0) { break; } while (getline(&dictWord, &dictWordSize, dict) != -1) { if(strcmp(input, dictWord) == 0) { printf("Found word in dictionary!\n"); wordFound = 1; break; } } if (wordFound == 0) { printf("Did not find word in dictionary.\n"); } wordFound = 0; fseek(dict, 0, SEEK_SET); } fclose(dict); free(input); free(dictWord); } int main(int argc, char** argv) { char input;
{ "domain": "codereview.stackexchange", "id": 44881, "lm_label": 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, ms-dos", "url": null }
c, game, ms-dos fclose(dict); free(input); free(dictWord); } int main(int argc, char** argv) { char input; srand((int)time(NULL)); printf("Doggle - Boggle for DOS\n"); printf("Doggle is in no way associated with Hasbro, the owners of the Boggle trademark.\n"); printf("Press H for help\n\n"); while (1) { printf("Doggle:\\> "); fflush(stdout); input = getche(); printf("\n"); input = toupper(input); switch (input) { case 'H': printhelp(); break; case 'N': newboard(); break; case 'D': dictionary(); break; case 'X': return 0; default: printf("Illegal command: %c. Press H for help.\n", input); break; } } } Answer: Nice first real C program, and nice self-answer. I’ll add a handful of things Array Indices are size_t (or Maybe ptrdiff_t), not int You currently have: int intidx(int *arr, int arrLen, int idx)
{ "domain": "codereview.stackexchange", "id": 44881, "lm_label": 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, ms-dos", "url": null }
c, game, ms-dos On 16-bit DOS, int has a maximum size of only 32,767 elements, then overflows to a negative number. A caller could pass in invalid values, which is not checked. It’s also extremely likely that you’re going to want to port this project to another target, such as a 32-bit DOS extender or even a modern 64-bit OS, where int might be far too small. You also give idx a confusing name: it’s not an index at all, but a key to be searched for. Generally, you should declare parameters and variables that won’t be modified const. You’ve chosen to return -1 if you fail to find the key in the array. This means your return type does need to be signed. However, since you don’t want to limit the size of the array you can search, it would be better to return a signed value wider than size_t, such as long. That way, the return value will be either an index between 0 and 65,535, or -1. (Unfortunately, there’s no type in standard C that means, “signed and wider than size_t,” so you might need to widen this when you port.) It’s also better to define your special codes as symbolic names than as magic numbers. Another approach would be to have the function return a result code, and take a pointer of the address to set to the size_t index. If you do want to use signed array indices, to catch wraparound errors with subtraction, the type you want is ptrdiff_t from <stddef.h>. Use assert to Check for Logic Errors The intidx function is a good example. If you don’t make the array size size_t, it might be too small or too large. On an OS where null pointer accesses don’t trap, you might also want to check for NULL religiously. If you follow my advice above to return either (long)-1 or a value between 0 and SIZE_MAX, you want to double-check that a long is in fact wider than a size_t. In modern C, some of those checks can be done at compile-time with static_assert. Since you seem to be using C89, you don’t have that and can use assert() for them all. Check for Runtime Errors
{ "domain": "codereview.stackexchange", "id": 44881, "lm_label": 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, ms-dos", "url": null }
c, game, ms-dos Check for Runtime Errors If an end user sees a failed assertion, that’s a bug in the program. Their purpose is to check for logic errors, such as calling an array-search with a negative array size, or a NULL pointer for the array base. If anyone but the developer will be using it, you should write code that catches the bugs that can actually happen, and prints a more human-readable error message. You also want to do this in a way that you can get a useful backtrace from the debugger. Boilerplate that I use in many of my C programs: /* Abort with an error message that includes the line number, the system * error string, and what the program was doing. */ void fatal_system_error_helper( const char* const msg, const char* const sourcefile, const int line, const int err ) { fflush(stdout); fprintf( stderr, "Error %s (%s:%d): %s\n", msg, sourcefile, line, strerror(err) ); exit(EXIT_FAILURE); }
{ "domain": "codereview.stackexchange", "id": 44881, "lm_label": 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, ms-dos", "url": null }
c, game, ms-dos #define fatal_system_error(msg) \ fatal_system_error_helper( (msg), __FILE__, __LINE__, errno )
{ "domain": "codereview.stackexchange", "id": 44881, "lm_label": 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, ms-dos", "url": null }
c, game, ms-dos This creates a fatal_system_error("Error fooing bar"); macro, suitable for reporting the failure of a system call that sets errno. It prints the error string, the strerror description of errno, and the source file and line number. Failing fast with that information makes it much easier to locate bugs and set breakpoints or get stack traces. For fatal errors that do not set errno, you might want to create a similar version without err. For example, malloc() on a DOS system with only 128K of RAM can easily fail. (Many coders here have gotten into the habit of assuming that it realistically can’t on a modern computer, or at least that it would thrash to a halt first, but DOS can very definitely run out of conventional memory.) Avoid Uninitialized Values C89 makes it hard to write static single assignments, which are generally much safer. And the alternative to writing a declaration like int x; and setting it later, int x = 0;, has the disadvantage that some compilers might no longer be able to warn you if it spots a path through the code where x never gets set. However, if you always initialize every variable to a deterministic value, there’s no way to ever use it by accident when it’s still undefined. Even if you forget to set it in some path through the program, it will have predictable behavior, and not some irreproducible Heisenbug. So I recommend initializing all automatic variables when they are declared. (This is already what C does with static variables.) Allocate Dynamic Memory Only When Necessary Within newboard, you create letterLine with malloc(), with a static size, and then free() it within the same function. There is no reason this needed malloc(). You could simply have declared a local array. Name Your Magic Numbers
{ "domain": "codereview.stackexchange", "id": 44881, "lm_label": 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, ms-dos", "url": null }
c, game, ms-dos Name Your Magic Numbers It’s, again, better to use a symbolic name, like ROW_LEN, instead of a magic number. This is especially true if you change the number, and now have to go through all your source files and figure out which 6s are that magic number and which ones are some other magic number. Use const Where Appropriate Again, C89 makes it extremely difficult to declare const local variables, compared to modern C, but dice stands out as an object that it would be a logic error to ever modify. You want the compiler to stop you from shooting yourself in the foot: it is very easy to write = when you meant ==. Modern compilers at least warn you about this, unless you put an extra pair of parentheses around them, but I don’t know if a 16-bit compiler from the ’90s does. Thirty years ago, when some didn’t, I would write “Yoda conditionals” like 0 == x instead of x == 0, so that if I accidentally wrote 0 = x, it would fail to compile. Local variables, in function scope, that should be initialized to constants known at compile time, and never modified, should be static const. Although you sometimes do want to modify function parameters, usually these should also be declared const. Track Program State Currently, your program displays a line of the board, prompts for a word, and looks up whether that word is in the dictionary. But it never checks the word against the board! It doesn’t even remember what’s on the board. In fact, all the functions you call from the input loop return void, and the program keeps no state at all, not even a score. Your project would be a lot more lie real-world programs if it maintains some kind of internal state.
{ "domain": "codereview.stackexchange", "id": 44881, "lm_label": 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, ms-dos", "url": null }
python, programming-challenge, python-2.x, tree Title: Google Foobar Challenge: Lucky Triples Question: Note: Since my time has passed for this challenge, I do not remember exactly the stipulations but will attempt to recapitulate them to the best of my knowledge. Essentially, the challenge was this: Given a list (from 1 to 2000 elements) of random integers (from 1 to 999999) write a function, answer(l) that accepts a list as input and returns the number of "lucky triples" present in the list. For this purpose, a lucky triple is defined as a list of three numbers \$(x, y, z)\$ such that \$x\$ divides \$y\$, \$y\$ divides \$z\$, and \$x \le y \le z\$. So, for instance, \$(2, 4, 8)\$ is a lucky triple and so is \$(1, 1, 1)\$. Test cases: input: [1, 1, 1] ouput: 1 input: [1, 2, 3, 4, 5, 6] output: 3 Theory First, a brief explanation about the theory behind my answer. I first noticed that for any list of multiples where each element \$n\$ is a factor of element \$n + 1\$, for example 1, 2, 4, 8, 16, the number of lucky triples in the list is equal to the summation from x = 0 to x = length - 2. So, for the previous example, the number of lucky triples in the list is equal to 3 + 2 + 1 or 6: 1, 2, 4 1, 2, 8 1, 2, 16 2, 4, 8 2, 8, 16 4, 8, 16 My idea, then, was to construct a tree of from the list, each branch representing a list of factors, and record the depth of each branch in the tree. From there, the number of lucky triples in each branch could be readily calculated with sum(). Unfortunately, I was a little too late and can therefore no longer validate my code. I've tested it on rather trivial cases, but have no way of knowing: If my code is optimized; If it returns the correct answer in more intricate examples, say a list from 1 to 2000.
{ "domain": "codereview.stackexchange", "id": 44882, "lm_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, programming-challenge, python-2.x, tree", "url": null }
python, programming-challenge, python-2.x, tree I preemptively apologize for any ambiguity in my explanation - feel free to ask for clarification - (this is the first time I've submitted code for review) as well as for the formatting of my code (if it is not readily comprehensible/Pythonic). But feedback would be much appreciated! Code # {{{ Imports from collections import Counter from itertools import imap, izip # }}} # {{{ LuckyTriples(object) class LuckyTriples(object): # {{{ __init__(self, list_of_random_int) def __init__(self, list_of_random_int): self._node_pool = set(sorted(list_of_random_int)) self._tree_space_parents = {} self._tree_space_children = {} self._roots = [] self._depths = [] map(self.build_tree_space, self._node_pool) map(self.get_all_roots, self._node_pool) for root in self._roots: self.embark(root, [1]) self._lucky_triple_count = 0 self.enumerate_lucky_triples(list_of_random_int) # }}} # {{{ build_tree_space(self, node_pool) def build_tree_space(self, node): parents = self.get_all_parents(node, self._node_pool) self._tree_space_parents[node] = parents children = self.get_all_children(node, self._node_pool) self._tree_space_children[node] = children return # }}} # {{{ get_all_parents(self, node, node_pool) def get_all_parents(self, node, node_pool): parents = [ parent for parent in node_pool if parent < node and node % parent == 0 ] return parents # }}} # {{{ get_all_roots(self, node_pool) def get_all_roots(self, node): parents = self.get_all_parents(node, self._node_pool) if not parents: self._roots.append(node) return # }}} # {{{ get_all_children(self, node, node_pool)
{ "domain": "codereview.stackexchange", "id": 44882, "lm_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, programming-challenge, python-2.x, tree", "url": null }
python, programming-challenge, python-2.x, tree # }}} # {{{ get_all_children(self, node, node_pool) def get_all_children(self, node, node_pool): children = [ child for child in node_pool if child > node and child % node == 0 ] return children # }}} # {{{ get_children_to_visit(self, nodes) def get_children_to_visit(self, nodes): nodes = [ subbranch for branches in nodes for subbranch in branches ] children_to_visit = [] for node in nodes: immediate_children = set( self._tree_space_children.get(node) ) descendants = set() nodes_to_visit = list(immediate_children) while nodes_to_visit: node = nodes_to_visit.pop() children = self._tree_space_children.get(node) descendants.update(children) children_to_visit.append(list( immediate_children - descendants) ) return children_to_visit # }}} # {{{ branch_off(self, branches, depths) def branch_off(self, branches, depths): for subbranch in branches: depths.extend(depths[0] for i in range(len(subbranch) - 1) ) return depths # }}} # {{{ explore_deeper(self, depths) def explore_deeper(self, level, depths): branches = [node for branch in level for node in branch] explore_deeper = [1] * len(branches) explore_deeper += [0 for i in range(len(depths) - len(explore_deeper)) ] new_depths = map(sum, izip(depths, explore_deeper)) return new_depths # }}} # {{{ def embark(self, node, depths)
{ "domain": "codereview.stackexchange", "id": 44882, "lm_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, programming-challenge, python-2.x, tree", "url": null }
python, programming-challenge, python-2.x, tree # }}} # {{{ def embark(self, node, depths) def embark(self, node, depths): nodes_to_visit = [[node]] while any(nodes_to_visit): children = self.get_children_to_visit(nodes_to_visit) depths = self.branch_off(children, depths) depths = self.explore_deeper(children, depths) nodes_to_visit = children self._depths.extend(depths) return # }}} # {{{ enumerate_lucky_triples(self, list_of_random_int) def enumerate_lucky_triples(self, list_of_random_int): for depth in self._depths: tmp = range(1, depth - 1) self._lucky_triple_count += sum(tmp) multiples = [ node for node in list_of_random_int if list_of_random_int.count(node) > 1 ] multiples = Counter(multiples) for multiple in multiples: parents = self._tree_space_parents[multiple] children = self._tree_space_children[multiple] nodes_in_branch = len(parents) + len(children) if multiples[multiple] == 2: self._lucky_triple_count += nodes_in_branch elif multiples[multiple] >= 3: self._lucky_triple_count += nodes_in_branch + 1 # }}} # }}} # {{{ answer(l) def answer(l): lock_codes = LuckyTriples(l) return lock_codes._lucky_triple_count # }}} Answer: 1. Testing Let's take a look at your second problem: I've tested it on rather trivial cases, but have no way of knowing [...] if it returns the correct answer in more intricate examples
{ "domain": "codereview.stackexchange", "id": 44882, "lm_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, programming-challenge, python-2.x, tree", "url": null }
python, programming-challenge, python-2.x, tree A good strategy in this kind of situation, where you have a complex implementation that you are not sure is correct, is to implement a simple and clearly correct (but slow) solution. Then you can generate some test data and compare the outputs of the two implementations. But before doing that, I have to confront an ambiguity in the problem description: am I supposed to count all the triples satisfying the "lucky" condition, or only the distinct triples? The examples in the problem description don't make this clear. So the only thing I have to go on is your implementation, and you've used the "distinct triples" interpretation: >>> answer([1, 1, 1, 1]) 1 (In the "all triples" interpretation, the result here would be 4.) So, back to writing a slow-but-correct implementation. Let's write a function that loops over all the triples, checks each one to see if it is lucky, and builds a set (to ensure distinctness): from itertools import combinations def lucky_triples(iterable): """Return the set of distinct triples x, y, z from an iterable of numbers, such that x <= y <= z and x divides y and y divides z. """ return set((x, y, z) for x, y, z in combinations(sorted(iterable), 3) if y % x == 0 and z % y == 0) Then we can use this as an oracle for our tests: from random import randrange def test(m, n): data = [randrange(1, m) for _ in range(n)] if answer(data) != len(lucky_triples(data)): print("Failed on {!r}".format(data)) Let's try it: >>> test(10, 10) Failed on [4, 5, 2, 8, 5, 9, 2, 2, 7, 1] Oops. What's gone wrong here? Our oracle function shows that there are nine distinct lucky triples here: >>> sorted(lucky_triples([4, 5, 2, 8, 5, 9, 2, 2, 7, 1])) [(1, 2, 2), (1, 2, 4), (1, 2, 8), (1, 4, 8), (1, 5, 5), (2, 2, 2), (2, 2, 4), (2, 2, 8), (2, 4, 8)] But the code from the post only counts eight of them: >>> answer([4, 5, 2, 8, 5, 9, 2, 2, 7, 1]) 8
{ "domain": "codereview.stackexchange", "id": 44882, "lm_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, programming-challenge, python-2.x, tree", "url": null }
python, programming-challenge, python-2.x, tree But the code from the post only counts eight of them: >>> answer([4, 5, 2, 8, 5, 9, 2, 2, 7, 1]) 8 So, it's back to the drawing board, I'm afraid. 2. Analysis If the problem isn't immediately clear, it often helps to perform test case reduction — that is, to remove superfluous elements from the failing test case until no more elements can be removed without causing the test to pass. In this case we get following minimal test case: >>> answer([1, 2, 4, 8]) 3 >>> sorted(lucky_triples([1, 2, 4, 8])) [(1, 2, 4), (1, 2, 8), (1, 4, 8), (2, 4, 8)] It's clear that the problem is here: for any list of multiples where each element \$n\$ is a factor of element \$n+1\$, for example 1, 2, 4, 8, 16, the number of lucky triples in the list is equal to the summation from x = 0 to x = length - 2. Suppose that the list has length \$k\$, then you'd calculate the count of lucky triples as $$ \sum_{0 \le x \le k-2} x = {(k-1)(k-2) \over 2}.$$ But actually in such a list any combination of three numbers form a lucky triple, so the count we need is $${k \choose 3} = {k(k-1)(k-2) \over 6}.$$ You'll see that these are the same when \$k=3\$, but that's just a coincidence. So let's try replacing this code: for depth in self._depths: tmp = range(1, depth - 1) self._lucky_triple_count += sum(tmp) with this code: for k in self._depths: self._lucky_triple_count += k * (k - 1) * (k - 2) // 6 Now the result is correct for the test case that failed: >>> answer([1, 2, 4, 8]) 4 So that fixes one problem. But might there be any other problems? Let's test lots of cases: >>> for i in range(2, 20): ... test(i, i) Failed on [7, 4, 2, 15, 14, 11, 10, 1, 13, 3, 6, 4, 12, 15, 5, 11] What's the problem here? >>> answer([7, 4, 2, 15, 14, 11, 10, 1, 13, 3, 6, 4, 12, 15, 5, 11]) 25 >>> len(lucky_triples([7, 4, 2, 15, 14, 11, 10, 1, 13, 3, 6, 4, 12, 15, 5, 11])) 23
{ "domain": "codereview.stackexchange", "id": 44882, "lm_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, programming-challenge, python-2.x, tree", "url": null }
python, programming-challenge, python-2.x, tree In this case, the code is counting too many triples! After removing superfluous elements, we get this minimal test case: >>> answer([1, 2, 4, 6, 12]) 8 >>> len(lucky_triples([1, 2, 4, 6, 12])) 7 Now it is clear what the problem is: we have two divisibility chains here, both of length four, namely \$1 \mid 2 \mid 4 \mid 12\$ and \$1 \mid 2 \mid 6 \mid 12\$: >>> LuckyTriples([1, 2, 4, 6, 12])._depths [4, 4] Each of these chains contributes four lucky triples to the sum — but this leads to double-counting, because the lucky triple \$(1, 2, 12)\$ belongs to both divisibility chains but must be counted just once. It's clear, I think, from this example, that the whole approach (of searching for divisibility chains and counting their length) is not going to work. That's because some lucky triples are going to appear on multiple divisibility chains and it is not clear how to avoid double-counting. 3. Alternative implementation So here's an alternative implementation that runs in time \$Θ(n^2)\$. For each number \$x\$ in the input, it counts the number of distinct proper divisors of \$x\$, \$d(x)\$, and the number of distinct proper multiples of \$x\$, \$m(x)\$. Then the number of distinct lucky triples \$(w, x, y)\$ with \$w < x < y\$ is \$d(x)m(x)\$. If there are at least 2 occurrences of \$x\$, then there are also \$d(x)\$ lucky triples \$(w, x, x)\$ with \$w < x\$ and \$m(x)\$ lucky triples \$(x, x, y)\$ with \$x < y\$. Finally, if there are at least 3 occurrences of \$x\$, then there is one lucky triple \$(x, x, x)\$. from collections import Counter from itertools import combinations def lucky_triple_count(iterable): """Return the number of distinct triples x, y, z from an iterable of numbers, such that x <= y <= z and x divides y and y divides z.
{ "domain": "codereview.stackexchange", "id": 44882, "lm_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, programming-challenge, python-2.x, tree", "url": null }
python, programming-challenge, python-2.x, tree """ counts = Counter(iterable) # {x: occurrences of x} divisors = Counter() # {x: distinct proper divisors of x} multiples = Counter() # {x: distinct proper multiples of x} for x, y in combinations(sorted(counts), 2): if y % x == 0: divisors[y] += 1 multiples[x] += 1 result = 0 for x, n in counts.items(): result += divisors[x] * multiples[x] if n >= 2: result += divisors[x] + multiples[x] if n >= 3: result += 1 return result
{ "domain": "codereview.stackexchange", "id": 44882, "lm_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, programming-challenge, python-2.x, tree", "url": null }
opengl, glsl, shaders Title: Basic GLSL fragment shader with palette lookups and palette shift Question: I am remaking an old game, which animates water by rotating its palettes over time. I have written a basic fragment shader to replicate this behavior. It checks which color we are trying to render, and if that color is known to be water, we apply a palette shift. This works well, but there is a lot of branching involved. Should I be concerned about this? How could it be improved? #version 330 core uniform sampler2D tex; uniform sampler2D palette; uniform float palette_txy; uniform int transparent_index = 0; uniform int water_shift_1; uniform int water_shift_2; in vec2 tex_coords; out vec4 frag_color; int add_wrapped(int value, int addend, int range_min, int range_size) { return (value + addend - range_min) % range_size + range_min; } void main() { float palette_index = texture(tex, tex_coords).r; if (palette_index == transparent_index || palette_index == 1) { discard; } // Get the size of 1 pixel int tex_width = textureSize(palette, 0).x; float px_size = 1.f / float(tex_width); // Apply a palette shift for water pixels int palette_index_int = int(palette_index * 256); if (palette_index_int >= 224 && palette_index_int < 228) { // Water palette_index_int = add_wrapped(palette_index_int, water_shift_1, 224, 4); palette_index = palette_index_int * px_size; } else if (palette_index_int >= 228 && palette_index_int < 232) { // Wakes // Use the inverse of water_shift_1 int shift = 3 - water_shift_1; palette_index_int = add_wrapped(palette_index_int, shift, 228, 4); palette_index = palette_index_int * px_size; } else if (palette_index_int >= 232 && palette_index_int < 239) { // Coastlines palette_index_int = add_wrapped(palette_index_int, water_shift_2, 232, 7); palette_index = palette_index_int * px_size; }
{ "domain": "codereview.stackexchange", "id": 44883, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "opengl, glsl, shaders", "url": null }
opengl, glsl, shaders vec2 palette_lookup = vec2(palette_index, palette_txy); frag_color = texture(palette, palette_lookup); } ``` Answer: This code works, it isn't so bad. DRY There's an obvious cleanup of consolidating those px_size multiplies: if (224 <= palette_index_int && palette_index_int < 239) { palette_index_int = get_water_effect(palette_index_int); palette_index = palette_index_int * px_size; } ... int get_water_effect(int palette_index_int) { [deal with water, wake, coast] } lookup table Alternatively, you might init a 256-element lookup table which holds enums, or three distinct add_wrapped base indexes, or pointers to {water, wake, coast} helper functions. Perhaps entries less than 224 would point to a no-op helper. profiling There's not a lot going on here. It's unclear if most of the time would be spent on branch mispredictions, lookup latencies, or other things that are just unavoidable. Bench the alternatives and post the measurements.
{ "domain": "codereview.stackexchange", "id": 44883, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "opengl, glsl, shaders", "url": null }
c++, matrix, bitwise Title: C++ Bitwise adjacency matrix implementation Question: I have tried to implement a bitwise adjacency matrix to represent a graph with a fixed number of vertices. Instead of wastefully representing each connection with an integer, 64 connections are packed into a single uint64_t, to improve memory and hopefully performance (via improved cache locality). Instead of vector<vector<uint64_t>>, using a contiguous vector<uint64_t>, once again to improve cache locality. A user interface similar to that of an vector<unordered_set<int>> adjacency list: adjmat[i] to access a row adjmat[i].contains(j) to check edge existence between i and j. for(int neighbor : adjmat[i]) neighbor iteration. My main motivation is just to create a really fast, efficient representation for dense graphs. However, I am quite inexperienced, and since performance optimization is quite technical, I'd really like some feedback since I might be out of my depth. Currently some concerns I have with my code include: Is this actually a valid way to improve performance of an adjacency matrix? I am using memory much more efficiently, but at the expense of more arithmetic and bit-shifting operations - does that erode any potential gains? I want to add familiar layers of abstraction (e.g. iterators) to replicate some functionality of vector<unordered_set<int>>. However, since I am already operating at such a low-level, I'm worried that the overhead of an iterator offsets all potential gains - if so, how can I create that abstraction without sacrificing performance? Also, I can't figure out why I can't constexpr my constructor, and if I can't, does that make all the other constexpr methods useless? Of course, any other comments or thoughts are appreciated too. Thanks! Compiler explorer link #include <vector> #include <cstdint> #include <iostream> class BitAdjmat { public:
{ "domain": "codereview.stackexchange", "id": 44884, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, matrix, bitwise", "url": null }
c++, matrix, bitwise class BitAdjmat { public: // Abstraction for a "Row" of the BitAdjmat class Row { public: /** * This row iterator should only iterate through existing edges, e.g. "1" entries. * I've settled for only using a read-only iterator (i.e. const_iterator), since * there is no way to hold a reference to a single bit. */ class const_iterator { public: constexpr const_iterator(std::size_t index, std::vector<uint64_t>::const_iterator start, std::size_t end_index) : index{index}, start{start}, end_index{end_index} { if (!exists()) { seek_next(); } } /** * Warning: This is special constructor that is optimized for constructing * the end() iterator, and shouldn't be used for anything else. */ constexpr const_iterator(std::size_t end_index, std::vector<uint64_t>::const_iterator start) noexcept : index{end_index}, start{start}, end_index{end_index} {} constexpr const_iterator &operator++() noexcept { seek_next(); return *this; } constexpr std::size_t operator*() const noexcept { return index; } constexpr bool operator==(const const_iterator &other) const noexcept { return index == other.index && start == other.start; } constexpr bool operator!=(const const_iterator &other) const noexcept { return !(*this == other); } private: // Check if current neighbor pointed to by *(start+index/N) exists, i.e., if the bit returned is 1. constexpr bool exists() const noexcept { return ((*(start + index / N)) >> (index % N)) & 1ULL; }
{ "domain": "codereview.stackexchange", "id": 44884, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, matrix, bitwise", "url": null }
c++, matrix, bitwise constexpr void seek_next() noexcept { while (index != end_index) { ++index; if (exists()) return; } } private: std::size_t index; // logical vertex index (not vector<uint64_t> index) const std::vector<uint64_t>::const_iterator start; const std::size_t end_index; }; public: constexpr Row(const BitAdjmat &parent, std::size_t row_index) noexcept : start{parent.matrix.begin() + parent.num_uint64_per_row * row_index}, num_vertices{parent.num_vertices} {} constexpr bool contains(std::size_t nb_index) const noexcept { return ((*(start + nb_index / N)) >> (nb_index % N)) & 1ULL; } constexpr const_iterator begin() const noexcept { return const_iterator(0, start, num_vertices); } constexpr const_iterator end() const noexcept { return const_iterator(num_vertices, start); } private: const std::vector<uint64_t>::const_iterator start; const std::size_t num_vertices; }; public: BitAdjmat(std::size_t num_vertices) : num_vertices{num_vertices}, num_uint64_per_row{num_vertices / N + (num_vertices % N != 0)}, matrix{std::vector<uint64_t>(num_vertices * num_uint64_per_row, 0)} {} constexpr Row operator[](std::size_t row_index) noexcept { return Row(*this, row_index); } constexpr const Row operator[](std::size_t row_index) const noexcept { return Row(*this, row_index); } constexpr std::size_t size() const { return num_vertices; } // Direct access to adjmat entry, where 'i' and 'j' are logical vertex indices. constexpr bool get(std::size_t i, std::size_t j) const noexcept { return (matrix[flat_index(i, j / N)] >> (j % N)) & 1ULL; }
{ "domain": "codereview.stackexchange", "id": 44884, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, matrix, bitwise", "url": null }
c++, matrix, bitwise // Direct setting of adjmat entries, where 'i' and 'j' are logical vertex indices. constexpr void set(std::size_t i, std::size_t j, bool val) noexcept { std::size_t q = j / N; std::size_t r = j % N; matrix[flat_index(i, q)] = (matrix[flat_index(i, q)] & ~(1ULL << r)) | (static_cast<uint64_t>(val) << r); } private: const std::size_t num_vertices; const std::size_t num_uint64_per_row; std::vector<uint64_t> matrix; // Flat container representating a 2D vector<vector<uint64_t>>. constexpr static std::size_t N = 64; private: constexpr std::size_t flat_index(std::size_t i, std::size_t j) const { return i * num_uint64_per_row + j; } }; Answer: Is this actually a valid way to improve performance of an adjacency matrix? Yes, I have used this technique in several software projects to great effect. But it only really works well if you actually use the fact that you've bit-packed your booleans, I mean beyond just saving space. By the way you cannot really use the "packedness" if you use a vector<bool>, so I'll make the opposite recommendation of Toby Speight: keep the vector<uint64_t>. But use it. How to use a bit-packed format The key to actually making use of bit-packed data, is doing as much as possible with whole uint64_ts, and as little as possible bit-by-bit. So don't do this, this wastes the potential that you created by packing your bits: constexpr void seek_next() noexcept { while (index != end_index) { ++index; if (exists()) return; } } Instead, change your iterator state to a pair of "index of the current uint64_t" and "copy of current uint64_t but with the bits that have already been iterated over reset". Then you can do:
{ "domain": "codereview.stackexchange", "id": 44884, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, matrix, bitwise", "url": null }
c++, matrix, bitwise While the current uint64_t (with the bits that have already been iterated over reset) is zero, skip ahead to the next uint64_t. If it's not zero, calculate where the next set bit is with std::countr_zero. Remember to reset that bit in the iterator state. That way there is much less "searching", the only actual searching that happens is on the level of uint64_ts, not individual bits. Large blocks of zeroes are efficiently skipped. High-entropy blocks of 50% zeroes and 50% ones do not suffer from branch misprediction, since there is no branch per individual bit. Here's a reference: Daniel Lemire's blog: Iterating over set bits quickly. The iteration is "out in the open" there, but you can put that into an iterator. And you can use the standard std::countr_zero these days. There are other operations that you can implement efficiently using similar principles, such as counting neighbours (std::popcount) or computing the complement graph. You can use bulk operations that treat each row as a bit set as the building blocks for graph search algorithms and such.
{ "domain": "codereview.stackexchange", "id": 44884, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, matrix, bitwise", "url": null }
c# Title: Split Larger String Into Console Window based on window size Question: Issue: Our application logs and traces are not standard, to help our aggregation tool for multiline content required some intervention on our part. Below I wrote some code to partition those longer strings into lines based on window size. I feel like the code could be improved. private static IEnumerable<string> Partition(this string content, int size) { var index = 1; var line = String.Empty; var lines = new List<string>(); var words = content.Split(' ', StringSplitOptions.RemoveEmptyEntries); foreach(var word in words) { if((line.Length + word.Length) <= size) line += $"{word} "; if((line.Length + word.Length + words.ElementAt(index).Length > 96) { lines.Add(line); line = String.Empty; } index++; } return lines; } The complaint or area that stands out: The excessive instantiation of string The collection and loop combination
{ "domain": "codereview.stackexchange", "id": 44885, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#", "url": null }
c# The excessive instantiation of string The collection and loop combination Answer: I suggest a simpler implementation. Instead of looking ahead in a second if-statement, we output the current line if adding the new word would exceed the maximum line size and clear the StringBuilder used to build the lines (see below). We ensure the last line is returned after the loop. We use a StringBuilder Class to minimize the number of string allocations. Also, we return the lines immediately by using an iterator method. This makes the List<string> collection superfluous, which saves allocations again. public static IEnumerable<string> Partition(this string content, int maxLineLength) { string[] words = content.Split(' ', StringSplitOptions.RemoveEmptyEntries); var sb = new StringBuilder(maxLineLength + 1); // + 1 for the trailing white space. foreach (string word in words) { if (sb.Length > 0 && sb.Length + word.Length > maxLineLength) { sb.Length--; // Remove the trailing white space. yield return sb.ToString(); sb.Clear(); } sb.Append(word).Append(' '); } if (sb.Length > 1) { sb.Length--; // Remove the trailing white space. yield return sb.ToString(); } } I also tested for sb.Length > 0 in the if-condition, just in case a single word exceeds the maximum line length. Removing the trailing white spaces is an addition to your implementation. Test string input = "Issue: Our application logs and traces are not standard, to help our aggregation tool for multiline content required some intervention on our part. Below I wrote some code to partition those longer strings into lines based on window size. I feel like the code could be improved."; foreach (string line in input.Partition(40)) { Console.WriteLine(line); }
{ "domain": "codereview.stackexchange", "id": 44885, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#", "url": null }
c# outputs: Issue: Our application logs and traces are not standard, to help our aggregation tool for multiline content required some intervention on our part. Below I wrote some code to partition those longer strings into lines based on window size. I feel like the code could be improved. A more advanced implementation could use a ReadOnlySpan<char> and the MemoryExtensions.Split Method (.NET 8.0) to save even more memory allocations.
{ "domain": "codereview.stackexchange", "id": 44885, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#", "url": null }
python, programming-challenge, random Title: Lottery Analysis (Python Crash Course, exercise 9-15) Question: I was working on Python Crash Course, exercise 9-15: 'Lottery Analysis'. It took me a very long time to get it to work. The reason it took that long is I wanted to use my existing class from the previous exercise 9-14 which used choices() method not choice(). I have looked at the author's and some other solutions but still don't get the logic behind those solutions, especially incrementing and then showing the number of attempts it took to win. I have looked at the book's material over and over again and still couldn't get it to work using choice() on my own. Until I found a few articles talking about different methods for using random. I went over those articles and finally got the other exercise 9-14 to work. First, I want to know what I did is normal for anyone who just started learning Python with no coding background. Am I complicating things to work this way? How can I get my code, see below, to work using choice()? Can the following code be simplified with fewer lines? Any advice is much appreciated! Full code from random import choices class WinningTicket: """ Randomly select characters to generate tkt numbers. Take a tkt no. and see how many tries it will take to win. """ def __int__(self, selection, final): """Initializing attributes.""" self.selection = selection self.final = final def generate_tkt(self, length): """Randomly select a series of characters to generate tkt num.""" series = ["a", "b", "c", "d", "e", 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] self.selection = choices(series, k=length) self.final = "".join(map(str, self.selection)) return self.final def pull_tkt(self, my_tkt): attempt_num = 0 while self.generate_tkt(len(my_tkt)): attempt_num += 1
{ "domain": "codereview.stackexchange", "id": 44886, "lm_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, programming-challenge, random", "url": null }
python, programming-challenge, random while self.generate_tkt(len(my_tkt)): attempt_num += 1 if self.final == my_tkt: print(f"\nYou've won with tkt no. {self.final}") print(f"It took {attempt_num} tries to win.\n") break else: print(f"Trying to win: attempt no. {attempt_num}") Create obj and call method tkt_num = WinningTicket() tkt_num.pull_tkt("45da") Results . . . . Trying to win: attempt no. 4138 Trying to win: attempt no. 4139 Trying to win: attempt no. 4140 Trying to win: attempt no. 4141 Trying to win: attempt no. 4142 Trying to win: attempt no. 4143 You've won with tkt no. 45da It took 4144 tries to win.
{ "domain": "codereview.stackexchange", "id": 44886, "lm_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, programming-challenge, random", "url": null }
python, programming-challenge, random You've won with tkt no. 45da It took 4144 tries to win. Answer: Without knowing exactly the problem you're trying to solve, I will probably miss some points, but I'll try a review anyway. Style Your code is very clean and pretty well documented, it's a pleasure to read. Kudos for that. Typos/unintended behavior/bug You define an __int__ magic method. Judging by the docstring and code, it is probably intended to be __init__. However, __int__ is a valid magic method, intended for casting the class to an integer, introducing a lot of confusion. Moreover, since your code doesn't define an __init__ initialization method, a default one is used, which doesn't take any parameters (besides self). This is used in your example usage: tkt_num = WinningTicket(). Should you fix the typo in "init", this line would raise an exception, as the initializer now requires 2 more parameters. Naming Your naming could be improved. WinningTicket is an odd name for the class, as it does not really represent a ticket, and definitely not always a winning one. Lottery would be better IMO. You shouldn't use abbreviations in names, unless they are very common ones. Spell out "ticket"; the 3 characters saved by writing "tkt" are definitely not worth the hit on readability. Constants You use hard-coded constants for the item pool used in the lottery. This should be a named constant for readability and modifiability. It should probably be defined outside of the method, and either passed as a parameter or set and accessed as an class member. Finally, since string are iterable in Python, you can use a single string instead of an array of characters and integers, which would simplify the code down the line, saving a call to map print in a loop Your pull_tkt method repeatedly prints inside a loop that runs many times, and that should run fast. There are a couple of issues with that:
{ "domain": "codereview.stackexchange", "id": 44886, "lm_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, programming-challenge, random", "url": null }
python, programming-challenge, random This violates separation of concerns. It spams the output with output containing no information. If you are only given the final line of the output, "It took 4144 tries to win.", you can infer it missed 4143 times. There is absolutely no gain in writing that you tried that many times. However, it buries the relevant information in noise. Worse, assuming you output on a terminal, if you run the simulation more than once, the important information will be deleted to make room for the noise by the time the next simulation terminates, and will be lost forever. print is slow (as a general rule of thumb, IO is slow, whatever kind of IO on whatever language). Since the loop runs many times, you would want it to run as fast as possible, it could save minutes or hours on longer tickets. Incorrect use of classes There is no need for a class as you use it. As it stands, all functionality could be provided by two functions: from random import choices def generate_ticket(length, pool): """Randomly select a series of characters to generate ticket number.""" return "".join(map(str, choices(pool, k=length))) def simulate(pool, target): attempts = 0 while generate_ticket(len(target), pool) != target: attempts += 1 return attempts POOL = '123abc' my_ticket = generate_ticket(3, POOL) print(f'It took {simulate(POOL, my_ticket)} tries to win.') No need to instantiate classes or keep state in members.
{ "domain": "codereview.stackexchange", "id": 44886, "lm_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, programming-challenge, random", "url": null }
python, html, classes, rss, blog Title: Blog site generator in python Question: Summary: This project is a simple static blog site generator written in python, utilizing pandoc to convert posts written in Markdown to HTML. It is essentially a follow up to my previous post: blog site generator in shell script. I got a lot of positive feedback, and multiple people suggested that I rewrite this project in a proper language, like python. So I did. This should make it easier to maintain the code-base and add additional features. Since the previous post, the blog also got a tag-filtering feature, and provides an RSS feed. Setup: While reviewing the code is one thing, you might want to spin up a quick demo instance for testing. To do this, clone the μblog repository and run python mublog.py, followed by cd dst && python3 -m http.server 8000. The commit for this version is 21db98a (It has not been merged to the main branch yet). Review: As for the code review, I am especially interested in feedback on the following aspects:
{ "domain": "codereview.stackexchange", "id": 44887, "lm_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, html, classes, rss, blog", "url": null }
python, html, classes, rss, blog Path Handling: The script handles a lot of different paths. Currently those are specified in the Config class, and assembled together in the places where they are needed to allow for modularity (e.g. if the user wants to change some path names). I wonder if I can improve this. Currently I have variables for all the important sub-directories, bu tmaybe it would make sense to split this up, so I have variables for the individual directory names, and use those to build the path names, so I have no hardcoded paths in the script at all? RSS Generation / Path conversion: The blog is also able to generate a RSS feed file from the blog posts. This requires encoding of the content, so that special characters don't cause problems. Furthermore, relative links need to be replaced with absolute links, otherwise they won't work in the feed. For this I wrote a regex to extract relative links, and I attempt to replace them with absolute ones. (I feel like this is not ideal). Handling of HTML: I already tried to have as little HTML code as possible hard-coded in the script. Therefore, I load "templates", and insert the relevant content. But some HTML bits are still hard-coded in the script. However, I feel like the entire handling of HTML could be improved - maybe by having specific small functions that generate one specific tag - e.g. generate_html_article_item(relevan_params)? Curious what would work best here. General feedback regarding style and structure Code: import glob import os import shutil import subprocess import re import urllib.parse from string import Template import html from urllib.parse import urljoin class Config: def __init__(self): self.dst_root_dir = "dst/" self.dst_posts_dir = f"{self.dst_root_dir}posts/" self.dst_css_dir = f"{self.dst_root_dir}css/" self.dst_assets_dir = f"{self.dst_root_dir}assets/" self.dst_js_dir = f"{self.dst_root_dir}js/"
{ "domain": "codereview.stackexchange", "id": 44887, "lm_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, html, classes, rss, blog", "url": null }
python, html, classes, rss, blog self.src_root_dir = "src/" self.src_posts_dir = f"{self.src_root_dir}posts/" self.src_css_dir = f"{self.src_root_dir}css/" self.src_assets_dir = f"{self.src_root_dir}assets/" self.src_templates_dir = f"{self.src_root_dir}templates/" self.blog_url = "https://my-blog.com/" self.blog_title = "John's Awesome Blog" self.blog_description = "Short description what the blog is about" self.blog_author_name = "John Doe" self.blog_author_mail = "johndoe@example.com" self.blog_author_copyright = f"Copyright 2023 {self.blog_author_name}" self.post_ignore_prefix = "_" self.posts = [] self.pages = [] class PathHandler: def __init__(self, dst_root_dir, src_root_dir, blog_url): self.dst_root_dir = dst_root_dir self.src_root_dir = src_root_dir self.blog_url = blog_url def generate_absolute_path(self, relative_path): if relative_path.startswith('/'): # Absolute path from the web-root directory return urljoin(self.blog_url, relative_path.lstrip('/')) elif relative_path.startswith('../'): # Relative path from a post return urljoin(self.blog_url, relative_path) else: # Relative path within a post return urljoin(self.blog_url, 'posts/' + relative_path) def is_text_link(self, text): return text.startswith('"') or text.startswith("'") def is_relative_path(self, path): absolute_prefixes = ["http://", "https://", "ftp://", "sftp://"] for prefix in absolute_prefixes: if path.startswith(prefix): return False return True def convert_relative_urls(self, ref_location): print(f"Relative URL found at: {ref_location}")
{ "domain": "codereview.stackexchange", "id": 44887, "lm_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, html, classes, rss, blog", "url": null }
python, html, classes, rss, blog def make_relative_urls_absolute(self, html_input: str): # Information: Matches relative URLs if they are in a link, a, script or img tag. # For a URL to be considered relative, it can't start with http:// or https:// or data:// # It also excludes fragment identifiers (aka #) regex_pattern = r'''(?:url\(|<(?:link|a|script|img)[^>]+(?:src|href)\s*=\s*)(?!['"]?(?:data|http|https))['"]?([^'"\)\s>#]+)''' new_html = html_input offset = 0 for match in re.finditer(regex_pattern, html_input): relative_url = match.group(1) absolute_url = self.generate_absolute_path(relative_url) Logger.log_info(f"Convert relative URL for RSS feed: {relative_url} => {absolute_url}") start_index = match.start(1) + offset end_index = match.end(1) + offset new_html = new_html[:start_index] + absolute_url + new_html[end_index:] offset += len(absolute_url) - len(relative_url) return new_html class Helper: @staticmethod def check_pandoc_installed() -> None: if not shutil.which("pandoc"): Logger.log_fail("Pandoc is not installed. Please install Pandoc before continuing.") @staticmethod def strip_top_directory_in_path(path: str) -> str: parts = path.split(os.sep) return os.sep.join(parts[1:]) if len(parts) > 1 else path @staticmethod def clean_build_directory(directory: str) -> None: try: shutil.rmtree(directory, ignore_errors=True) except Exception as e: Logger.log_fail(f"Failed to remove old build directory: {str(e)}") @staticmethod def create_directory(directory: str) -> None: try: os.makedirs(directory, exist_ok=True) except Exception as e: Logger.log_fail(f"Failed to create directory: {str(e)}")
{ "domain": "codereview.stackexchange", "id": 44887, "lm_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, html, classes, rss, blog", "url": null }
python, html, classes, rss, blog @staticmethod def copy_files(src_path: str, dst_path: str) -> None: try: for f in glob.glob(f"{src_path}/*"): shutil.copy(f, dst_path) except Exception as e: Logger.log_fail(f"Failed to copy files: {str(e)}") @staticmethod def read_file_contents(file_path: str) -> list[str]: try: with open(file_path, 'r') as file: return file.readlines() except FileNotFoundError: Logger.log_fail(f"Failed to load file '{file_path}'.") @staticmethod def src_to_dst_path(src_file_path: str, dst_dir: str, dst_ext: str) -> str: file_name = os.path.basename(src_file_path) base_name, _ = os.path.splitext(file_name) return os.path.join(dst_dir, base_name + dst_ext) @staticmethod def replace_file_extension(file_path: str, ext: str) -> str: root, old_extension = os.path.splitext(file_path) if not old_extension: Logger.log_fail(f"The file path '{file_path}' does not have an extension to replace.") return root + '.' + ext.strip('.') @staticmethod def writefile(path: str, contents: str) -> None: with open(path, "w", encoding="utf-8") as f: f.write(contents) @staticmethod def substitute(mapping: dict[str, str], in_path: str, out_path: str = None) -> None: if not out_path: out_path = in_path template_text = Helper.read_file_contents(in_path) template = Template("".join(template_text)) output = template.substitute(mapping) Helper.writefile(out_path, output) class Blog: def __init__(self, config: Config): self.config = config def generate(self) -> None: Helper.check_pandoc_installed() self.clean_build_directory() self.create_output_directories() self.copy_files_to_dst() self.process_posts() self.process_pages()
{ "domain": "codereview.stackexchange", "id": 44887, "lm_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, html, classes, rss, blog", "url": null }
python, html, classes, rss, blog def clean_build_directory(self) -> None: Helper.clean_build_directory(self.config.dst_root_dir) def create_output_directories(self) -> None: directories = [ self.config.dst_root_dir, self.config.dst_posts_dir, self.config.dst_css_dir, self.config.dst_assets_dir, self.config.dst_js_dir, ] for directory in directories: Helper.create_directory(directory) def copy_files_to_dst(self) -> None: Helper.copy_files(self.config.src_css_dir, self.config.dst_css_dir) Helper.copy_files(self.config.src_assets_dir, self.config.dst_assets_dir) def process_posts(self) -> None: builder = SiteBuilder(self.config) for file_path in glob.glob(self.config.src_posts_dir + "*.md"): if not os.path.basename(file_path).startswith(self.config.post_ignore_prefix): post = Post(self.config, file_path) self.config.posts.append(post) builder.generate_post(post) builder.generate_js() builder.generate_rss_feed() def process_pages(self) -> None: builder = SiteBuilder(self.config) for file_path in glob.glob(self.config.src_root_dir + "*.md"): page = Page(self.config, file_path) self.config.pages.append(page) if page.src_path.endswith("tags.md"): builder.generate_tags_page(page) elif page.src_path.endswith("articles.md"): builder.generate_articles_page(page) else: builder.generate_page(page) class Page: def __init__(self, config: Config, src_page_path: str): self.config = config self.src_path = src_page_path self.dst_path = Helper.src_to_dst_path(src_page_path, self.config.dst_root_dir, ".html")
{ "domain": "codereview.stackexchange", "id": 44887, "lm_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, html, classes, rss, blog", "url": null }
python, html, classes, rss, blog class Post: def __init__(self, config: Config, src_file_path: str): self.config = config self.title = "" self.description = "" self.date = "" self.tags = [] self.src_path = "" self.dst_path = "" self.dst_path_remote = "" self.raw_file_contents = "" self.raw_html_content = "" self.validate_post(src_file_path) self.src_path = src_file_path self.dst_path = Helper.src_to_dst_path(src_file_path, self.config.dst_posts_dir, ".html") self.dst_path_remote = Helper.strip_top_directory_in_path(Helper.replace_file_extension(self.src_path, ".html")) self.filename = os.path.basename(self.dst_path) def validate_post(self, src_file_path: str) -> None: Logger.log_info(f"Processing {src_file_path} ...") self.raw_file_contents = Helper.read_file_contents(src_file_path) # Check that file is long enough to accommodate header if len(self.raw_file_contents) < 6: Logger.log_fail(f"Failed to validate header of {src_file_path}.") # Validation line 1: Starting marker if self.raw_file_contents[0].strip() != "---": Logger.log_fail(f"Failed to validate header of {src_file_path}") Logger.log_fail(f"The starting marker \"---\" is missing or incorrect") # Validation line 2: title field if not re.match(r'^title:\s*(\S+)', self.raw_file_contents[1]): Logger.log_fail(f'Failed to validate header of {src_file_path}') Logger.log_fail(f'The title field is missing, empty, or incorrect.') self.title = re.search(r'^title:\s*(.*?)\s*$', self.raw_file_contents[1]).group(1)
{ "domain": "codereview.stackexchange", "id": 44887, "lm_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, html, classes, rss, blog", "url": null }
python, html, classes, rss, blog # Validation line 3: description field if not re.match(r'^description:\s*(\S+)', self.raw_file_contents[2]): Logger.log_fail(f'Failed to validate header of {src_file_path}') Logger.log_fail(f'The description field is missing, empty, or incorrect.') self.description = re.search(r'^description:\s*(.*?)\s*$', self.raw_file_contents[2]).group(1) # Validation line 4: date field if not re.match(r'^date:\s*([0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$)', self.raw_file_contents[3]): Logger.log_fail(f'Failed to validate header of {src_file_path}') Logger.log_fail(f'The date field is missing, empty, or not in the correct format (YYYY-MM-DD)') self.date = re.search(r'([0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$)', self.raw_file_contents[3]).group(1) # Validation line 5: tags field if not re.match(r'^tags:\s*(\S+)', self.raw_file_contents[4]): Logger.log_fail(f'Failed to validate header of {src_file_path}') Logger.log_fail(f'The tags field is missing, empty, or incorrect.') tag_values = re.search(r'^tags:\s*(.*?)\s*$', self.raw_file_contents[4]).group(1) self.tags = [tag for tag in re.findall(r'[^,\s][^,]*[^,\s]|[^,\s]', tag_values)] # Validation line 6: Ending marker if self.raw_file_contents[5].strip() != "---": Logger.log_fail(f"Failed to validate header of {src_file_path}") Logger.log_fail(f"The ending marker \"---\" is missing or incorrect") class SiteBuilder: def __init__(self, config: Config): self.config = config
{ "domain": "codereview.stackexchange", "id": 44887, "lm_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, html, classes, rss, blog", "url": null }
python, html, classes, rss, blog class SiteBuilder: def __init__(self, config: Config): self.config = config def load_template(self, template_path: str) -> str: try: with open(template_path, encoding="utf-8") as f: return f.read() except FileNotFoundError: Logger.log_fail(f"Template file {template_path} not found.") except IOError: Logger.log_fail(f"Failed to open template file {template_path}.") def generate_js(self) -> None: js_template = self.load_template(self.config.src_templates_dir + "tags.js.template") entries = [ f' "{post.filename}": [{", ".join([f"{tag!r}" for tag in post.tags])}]' for post in self.config.posts ] mapping = "\n" + ",\n".join(entries) + "\n" substitutions = {"tag_mapping": mapping} js_data = Template(js_template).substitute(substitutions) Helper.writefile(self.config.dst_js_dir + "/tags.js", js_data) Logger.log_pass(f"Processed JS file.") def generate_post(self, post: Post) -> None: content = self.convert_md_html_with_pandoc(post.src_path) post.raw_html_content = content post_template = self.load_template(self.config.src_templates_dir + "post.template") # Generate the tags for the post post_tags = "<div class=\"tags\">" for tag in post.tags: tag_param = urllib.parse.urlencode({"tag": tag}) post_tags += ( f'<div class="tag-bubble" onclick="location.href=\'/articles.html?{tag_param}\'">' f"{tag}</div>" ) post_tags += "</div>"
{ "domain": "codereview.stackexchange", "id": 44887, "lm_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, html, classes, rss, blog", "url": null }
python, html, classes, rss, blog substitutions = { "author_mail": self.config.blog_author_mail, "author_copyright": self.config.blog_author_copyright, "title": post.title, "content": content, "post_tags": post_tags, "css_dir": Helper.strip_top_directory_in_path(self.config.dst_css_dir), "js_dir": Helper.strip_top_directory_in_path(self.config.dst_js_dir), } post_data = Template(post_template).substitute(substitutions) Helper.writefile(post.dst_path, post_data) Logger.log_pass(f"Successfully processed {post.src_path}") def generate_tags_page(self, page: Page) -> None: unique_tags = list(set(tag for post in self.config.posts for tag in post.tags)) tag_counts = {tag: sum(tag in post.tags for post in self.config.posts) for tag in unique_tags} sorted_tags = sorted(unique_tags, key=lambda tag: tag_counts[tag], reverse=True) content = self.convert_md_html_with_pandoc(page.src_path) content += "<div class=\"tags\">" for tag in sorted_tags: tag_count = tag_counts[tag] tag_param = urllib.parse.urlencode({"tag": tag}) content += ( f'<div class="tag-bubble" onclick="location.href=\'articles.html?{tag_param}\'">' f"{tag}<span>{tag_count}</span></div>" ) content += "</div>"
{ "domain": "codereview.stackexchange", "id": 44887, "lm_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, html, classes, rss, blog", "url": null }
python, html, classes, rss, blog post_template = self.load_template(self.config.src_templates_dir + "page.template") substitutions = { "author_mail": self.config.blog_author_mail, "author_copyright": self.config.blog_author_copyright, "title": "Blog", "content": content, "css_dir": Helper.strip_top_directory_in_path(self.config.dst_css_dir), "js_dir": Helper.strip_top_directory_in_path(self.config.dst_js_dir), } page_data = Template(post_template).substitute(substitutions) Helper.writefile(page.dst_path, page_data) Logger.log_pass(f"Successfully processed {page.src_path}") def generate_articles_page(self, page: Page) -> None: content = self.convert_md_html_with_pandoc(page.src_path) content += "<article>\n" content += "<ul class=\"articles\">\n" for post in self.config.posts: content += ( f'<li id=\"{post.filename}\"><b>[{post.date}]</b> <a href="{post.dst_path_remote}">{post.title}</a></li>\n' ) content += "</ul>\n" content += "</article>" post_template = self.load_template(self.config.src_templates_dir + "page.template") substitutions = { "author_mail": self.config.blog_author_mail, "author_copyright": self.config.blog_author_copyright, "title": "Blog", "content": content, "css_dir": Helper.strip_top_directory_in_path(self.config.dst_css_dir), "js_dir": Helper.strip_top_directory_in_path(self.config.dst_js_dir), } page_data = Template(post_template).substitute(substitutions) Helper.writefile(page.dst_path, page_data) Logger.log_pass(f"Successfully processed {page.src_path}")
{ "domain": "codereview.stackexchange", "id": 44887, "lm_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, html, classes, rss, blog", "url": null }
python, html, classes, rss, blog def generate_page(self, page: Page) -> None: Logger.log_info(f"Generating page: {page.src_path} ...") content = self.convert_md_html_with_pandoc(page.src_path) post_template = self.load_template(self.config.src_templates_dir + "page.template") substitutions = { "author_mail": self.config.blog_author_mail, "author_copyright": self.config.blog_author_copyright, "title": "Blog", "content": content, "css_dir": Helper.strip_top_directory_in_path(self.config.dst_css_dir), "js_dir": Helper.strip_top_directory_in_path(self.config.dst_js_dir), } page_data = Template(post_template).substitute(substitutions) Helper.writefile(page.dst_path, page_data) Logger.log_pass(f"Successfully processed {page.src_path}") def generate_rss_feed(self): rss_template = self.load_template(self.config.src_templates_dir + "/rss.xml.template") rss_items = "" for post in self.config.posts: # Replace relative urls with absolute URLs edited = pm.make_relative_urls_absolute(post.raw_html_content) rss_items += "<item>\n" rss_items += f"<title>{html.escape(post.title)}</title>\n" link = self.config.blog_url + Helper.strip_top_directory_in_path(self.config.dst_posts_dir) + post.filename rss_items += f"<link>{link}</link>\n" rss_items += f"<description>{html.escape(edited)}</description>\n" rss_items += "</item>\n" substitutions = { "blog_title": self.config.blog_title, "blog_url": self.config.blog_url, "blog_description": self.config.blog_description, "rss_items": rss_items } feed = Template(rss_template).substitute(substitutions) Helper.writefile(self.config.dst_root_dir + "feed.xml", feed) Logger.log_pass(f"Successfully generated rss feed")
{ "domain": "codereview.stackexchange", "id": 44887, "lm_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, html, classes, rss, blog", "url": null }
python, html, classes, rss, blog @staticmethod def convert_md_html_with_pandoc(src_path: str) -> str: command = ["pandoc", src_path, "-f", "markdown", "-t", "html"] try: result = subprocess.run(command, check=True, capture_output=True, text=True) return result.stdout except subprocess.CalledProcessError: Logger.log_fail(f"Pandoc failed while processing {src_path}") class Logger: PASS = "\033[32m[PASS]\033[0m" FAIL = "\033[31m[FAIL]\033[0m" INFO = "\033[34m[INFO]\033[0m" WARN = "\033[33m[WARN]\033[0m" @staticmethod def log_info(message: str) -> None: print(f"{Logger.INFO} {message}") @staticmethod def log_fail(message: str) -> None: print(f"{Logger.FAIL} {message}") exit(1) @staticmethod def log_warn(message: str) -> None: print(f"{Logger.WARN} {message}") @staticmethod def log_pass(message: str) -> None: print(f"{Logger.PASS} {message}") cfg = Config() pm = PathHandler(cfg.dst_root_dir, cfg.src_root_dir, cfg.blog_url) blog = Blog(cfg) blog.generate() Thanks for reading, and I am looking forward for your feedback! Answer: Directories Your path-formatting such as f"{self.dst_root_dir}posts/" should be replaced with operations from pathlib.Path. Similar for os.sep.join. You need to shift gears and add argparse configurability. Configuration Config has confused responsibilities: it contains configuration for the top-level server (directories) and configuration for the site. In a mature web application, the server and site are configured separately. This makes it much easier to support multiple sites. Web odds and ends is_relative_path should not iterate. Instead, do a built-in urlparse to get the scheme. But... this method is a little strange, because it doesn't cover all cases where the path is absolute. The scheme-less /foo/bar is also an absolute path. You say:
{ "domain": "codereview.stackexchange", "id": 44887, "lm_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, html, classes, rss, blog", "url": null }
python, html, classes, rss, blog By "absolute," I mean providing the full server URL to the file rather than just an absolute path within the web-root directory That isn't "absolute", and you need to change your terminology. I think you mean "domain-qualified". Again, /foo/bar is an absolute path. convert_relative_urls doesn't convert anything; it just prints. make_relative_urls_absolute is terrifying. There is no universe where this is a good idea. If you absolutely had to parse HTML to sanitize links, this is not the way to do it; but - what is the purpose for sanitizing links here? Is the blog content already HTML, and you're doing some kind of processing step? For what purpose? If it's in the name of security, you have vastly bigger problems. You say: The reason for this workaround is to ensure images etc. are shown correctly in the RSS feed. RSS does not allow relative links. So then either: Document that the user cannot include relative links; or Throw an error if relative links are detected upon parse of the document by something like BeautifulSoup (not a regex); or Parse by BeautifulSoup and operate on the DOM from a well-defined in-memory representation, substituting out links in elements instead of in text manipulation. You further ask: I would also like some more feedback on how to improve the parts, where I generate HTML that gets inserted
{ "domain": "codereview.stackexchange", "id": 44887, "lm_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, html, classes, rss, blog", "url": null }
python, html, classes, rss, blog If the blog-writing developer is implicitly trusted, just accept Jinja2 templates from them and render them as needed (you can compose user templates with your own program templates if needed). If the blogger is untrusted, parse the DOM with BeautifulSoup and manipulate it with strainer expressions before re-rendering it. Misc Helper needs to not be a class. Move it to its own helper.py module and demote all of those methods to globals. You get scope from the module, and don't have to worry about class statics. Don't write your own Logger. Don't do it. Configure the built-in logging, and add your fancy formats there if you want. check_pandoc_installed is less than helpful. You should throw an exception from here, or at least return a boolean. read_file_contents and writefile shouldn't exist. The former hides exceptions from the scope where they actually matter. File I/O is so simple that there's no benefit to writing a helper for this, and you'll be better off writing out open whenever you need it. Move this: cfg = Config() pm = PathHandler(cfg.dst_root_dir, cfg.src_root_dir, cfg.blog_url) blog = Blog(cfg) blog.generate() to a def main(), and call it from if __name__ == '__main__'. Regexes Sometimes they're called-for; sometimes they're extremely not (parsing HTML). When they are called-for, something like r'^date:\s*([0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$)' can and should be rewritten for legibility; something like: r'''(?x) ^date:\s* # start tag (?P<year>[0-9]{4})- # ISO 8601 YYYY (?P<month>0[1-9]|1[0-2])- # ISO 8601 MM (?P<day>(0[1-9]|[1-2][0-9]|3[0-1]) # ISO 8601 DD $ ''' The x gets you verbose mode, which allows for comments and whitespace trimming. Once the regex is compiled this will not have any impact on performance.
{ "domain": "codereview.stackexchange", "id": 44887, "lm_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, html, classes, rss, blog", "url": null }
c++, parsing, console Title: Command-line parser with built-in error checking Question: Simple command-line option parser with automatic setting of variables and built-in error checking. The story is I was working on another new project that had a lot of configurable options, as they usually do. I got tired of writing the same parser 50 different times, so I spent some time to write one that hopefully I could reuse. It's nothing fancy, and I realized later of a more OO way to do this, but it worked for my purpose, and I'm looking forward to being done with the boring dry parsing bits forever. The end. The syntax is simple: blah.exe [<option>=<value>, ...] <option> is the name and <value> can be an integer, boolean, or string type. As usual, any and all criticism welcome. example usage > program.exe bar=5 foo=2 bim=prog.conf baz=1 foo is 2 bar is 5 baz is 1 bim is "prog.conf" example where bounds checking kicks in > program.exe bar=5 foo=12 bim=prog.conf baz=1 error: value out of bounds, option #2 "foo=12" exiting... main.cpp /* Author: Mode77 Date: 7/2/2023 */ #include <string> #include <iostream> #include "cmdopt.h" int foo; int bar; bool baz; std::string bim; int main(int argc, char *argv[]) { for(int i = 1; i < argc; i++) { if(intOption(argv[i], i, "foo", 0, 9, foo, argv[0])) { } else if(intOption(argv[i], i, "bar", 3, 5, bar, argv[0])) { } else if(boolOption(argv[i], i, "baz", baz, argv[0])) { } else if(stringOption(argv[i], i, "bim", bim, argv[0])) { } else unknownOptionError(argv[i], i); } std::cout << "foo is " << foo << "\n"; std::cout << "bar is " << bar << "\n"; std::cout << "baz is " << baz << "\n"; std::cout << "bim is \"" << bim << "\"\n"; } cmdopt.h /* Author: Mode77 Date: 7/2/2023 */ #pragma once #include <string>
{ "domain": "codereview.stackexchange", "id": 44888, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, parsing, console", "url": null }
c++, parsing, console cmdopt.h /* Author: Mode77 Date: 7/2/2023 */ #pragma once #include <string> // Processes an integer-typed command-line option in three stages. // First, the syntax of the assignment string is checked. If the syntax check // fails, an error message is printed, and the program is halted and exited // with EXIT_FAILURE. // // Otherwise, the option name in the assignment is checked against // the given option name. If the name check fails, the function returns false. // // Finally, the value is parsed as an integer. If there is a parsing error // (value is not a number, under/overflow, value outside of given range), // an error message is printed, and the program is halted and exited // with EXIT_FAILURE. // // If all checks pass, the destination variable is written with the parsed // value and the function returns true. // // assignment: Option assignment string // optionNumber: Used for possible error messages // optionName: The name which the option is expected to match // minimum: The smallest value allowed for the option // maximum: The largest value allowed for the option // destination: The variable written to if the parse succeeds // programName: Used for possible error messages bool intOption( std::string const & assignment, unsigned optionNumber, std::string const & optionName, int minimum, int maximum, int & destination, std::string const & programName);
{ "domain": "codereview.stackexchange", "id": 44888, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, parsing, console", "url": null }
c++, parsing, console // Processes a boolean-typed command-line option using the same three-stage // process as intOption(). // // The value is parsed as a boolean; 0 represents false and any other // value is interpreted as true. // // The strings "true" and "false" are not allowed (Todo: YET!!!) // // assignment: Option assignment string // optionNumber: Used for possible error messages // optionName: The name which the option is expected to match // destination: The variable written to if the parse succeeds // programName: Used for possible error messages bool boolOption( std::string const & assignment, unsigned optionNumber, std::string const & optionName, bool & destination, std::string const & programName); // Processes a string-typed command-line option using the same three-stage // process as intOption() and boolOption(). // // assignment: Option assignment string // optionNumber: Used for possible error messages // optionName: The name which the option is expected to match // destination: The variable written to if the parse succeeds // programName: Used for possible error messages bool stringOption( std::string const & assignment, unsigned optionNumber, std::string const & optionName, std::string & destination, std::string const & programName); // Prints an unknown option error message and exits the program with the failure code void unknownOptionError(std::string const &assignment, unsigned optionNumber); cmdopt.cpp /* Author: Mode77 Date: 7/2/2023 */ #include <string> #include <iostream> #include <cstdlib> #include <climits> #include "cmdopt.h"
{ "domain": "codereview.stackexchange", "id": 44888, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, parsing, console", "url": null }
c++, parsing, console #include <string> #include <iostream> #include <cstdlib> #include <climits> #include "cmdopt.h" static bool isValidOptionSyntax(std::string const &); static bool optionMatches(std::string const &, std::string const &); static int expectInt(std::string const &, unsigned, int, int); static void invalidSyntaxError(std::string const &, unsigned, std::string const &); static void invalidValueError(std::string const &, unsigned); static void valueOutOfBoundsError(std::string const &, unsigned); bool intOption( std::string const & assignment, unsigned optionNumber, std::string const & optionName, int minimum, int maximum, int & destination, std::string const & programName) { if(!isValidOptionSyntax(assignment)) { invalidSyntaxError(assignment, optionNumber, programName); return false; // Unreachable since the above will exit } if(!optionMatches(assignment, optionName)) { return false; } destination = expectInt(assignment, optionNumber, minimum, maximum); return true; } bool boolOption( std::string const & assignment, unsigned optionNumber, std::string const & optionName, bool & destination, std::string const & programName) { if(!isValidOptionSyntax(assignment)) { invalidSyntaxError(assignment, optionNumber, programName); return false; // Unreachable since the above will exit } if(!optionMatches(assignment, optionName)) { return false; } destination = static_cast<bool>(expectInt(assignment, optionNumber, INT_MIN, INT_MAX)); return true; }
{ "domain": "codereview.stackexchange", "id": 44888, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, parsing, console", "url": null }
c++, parsing, console bool stringOption( std::string const & assignment, unsigned optionNumber, std::string const & optionName, std::string & destination, std::string const & programName) { if(!isValidOptionSyntax(assignment)) { invalidSyntaxError(assignment, optionNumber, programName); return false; // Unreachable since the above will exit } if(!optionMatches(assignment, optionName)) { return false; } size_t const indexOfEquals = assignment.find('='); destination = assignment.substr(indexOfEquals + 1, std::string::npos); return true; } void unknownOptionError(std::string const &assignment, unsigned optionNumber) { size_t const indexOfEquals = assignment.find('='); std::string const option(assignment.substr(0, indexOfEquals)); std::cout << "error: unknown option, " "option #" << optionNumber << " \"" << option << "\"\n"; std::cout << "exiting...\n"; exit(EXIT_FAILURE); } // Returns true if the option assignment string has the syntax: // <option>=<value> // where option and value are at least one character each. // Returns false otherwise. static bool isValidOptionSyntax(std::string const &assignment) { size_t const indexOfEquals = assignment.find('='); bool const containsEqualsSign = indexOfEquals != std::string::npos; bool const hasAtLeastThreeCharacters = assignment.length() > 2; bool const equalsIsNotFirstOrLast = (indexOfEquals > 0) && (indexOfEquals < (assignment.length() - 1)); return containsEqualsSign && hasAtLeastThreeCharacters && equalsIsNotFirstOrLast; }
{ "domain": "codereview.stackexchange", "id": 44888, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, parsing, console", "url": null }
c++, parsing, console return containsEqualsSign && hasAtLeastThreeCharacters && equalsIsNotFirstOrLast; } // Given a string in option assignment syntax, compares the assignment option // with the given expected name. // // Returns true if they compare the same, false otherwise. static bool optionMatches(std::string const &assignment, std::string const &expected) { size_t const indexOfEquals = assignment.find('='); std::string const option(assignment.substr(0, indexOfEquals)); return option == expected; } // Given a string in option assignment syntax, returns the value as an integer. // // If there was a parsing error (value is not a number, under/overflow, value is // outside of given range), an error message is printed, and the program is halted // and exited with EXIT_FAILURE. static int expectInt(std::string const &assignment, unsigned optionNumber, int mini, int maxi) { size_t const indexOfEquals = assignment.find('='); std::string const value(assignment.substr(indexOfEquals + 1, std::string::npos)); int v; try { v = std::stoi(value); } catch(std::invalid_argument const &) { invalidValueError(assignment, optionNumber); } catch(std::out_of_range const &) { valueOutOfBoundsError(assignment, optionNumber); } if(v < mini || v > maxi) { valueOutOfBoundsError(assignment, optionNumber); } return v; } // Prints an invalid syntax error message and exits the program with the failure code static void invalidSyntaxError( std::string const & assignment, unsigned optionNumber, std::string const & programName) { std::cout << "error: invalid syntax, " "option #" << optionNumber << " \"" << assignment << "\"\n"; std::cout << "usage: " << programName << " [<option>=<value>...]\n"; std::cout << "exiting...\n"; exit(EXIT_FAILURE); }
{ "domain": "codereview.stackexchange", "id": 44888, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, parsing, console", "url": null }
c++, parsing, console // Prints an invalid value error message and exits the program with the failure code static void invalidValueError(std::string const &assignment, unsigned optionNumber) { std::cout << "error: invalid value, " "option #" << optionNumber << " \"" << assignment << "\"\n"; std::cout << "exiting...\n"; exit(EXIT_FAILURE); } // Prints a value out of bounds error message and exits the program with the failure code static void valueOutOfBoundsError(std::string const &assignment, unsigned optionNumber) { std::cout << "error: value out of bounds, " "option #" << optionNumber << " \"" << assignment << "\"\n"; std::cout << "exiting...\n"; exit(EXIT_FAILURE); } Answer: Avoid code repetition While you already reduced a lot of code by introducing functions like intOption(), boolOption() and so on, there's still a lot of repetition inside your main() function. In particular, you have to repeat else if (…, argv[i], i, …, argv[0])) {…}, where … marks the only places where something (potentially) different is placed. Every time you have to repeat something, there is a chance you make a mistake, which at best causes a compilation error, but at worst results in hard to diagnose misbehavior at runtime. To solve that though, we'll have to remove the whole if-else chain, which brings me to: It's inefficient Your example program only has 4 options, but what if you had hundreds of possible options? Then for each argument, it has to do hundreds of string comparisons. That could slow option parsing significantly. It would be nicer if we had some way to quickly look up the option from some table. Consider this: std::unordered_map<std::string, std::function<void(std::string)>> options = { {"foo", [&](std::string value){ foo = std::stoi(value); }, {"bar", [&](std::string value){ bar = std::stoi(value); }, … };
{ "domain": "codereview.stackexchange", "id": 44888, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, parsing, console", "url": null }
c++, parsing, console Then in main() your loop could look like: for (int i = 1; i < argc; ++i) { auto [name, value] = splitAssignment(argv[i]); options[name](value); } Where splitAssignment() is a function that returns the name and value parts of an assignment string. Now, each line in the declaration of options still looks quite long, and it didn't have the range checks for allowed values. But you can make function that return lambdas, so you could rewrite intOption() and friends to return a lambda for you: auto intOption(int minimum, int maximum, int& destination) { return [=, &destination](std::string value) { int v = std::stoi(value); if (v < minimum || v > maximum) { /* return error somehow */ } destination = v; }; } And then you can rewrite your table to: std::unordered_map<std::string, std::function<void(std::string)>> options = { {"foo", intOption(0, 9, foo) }, {"bar", intOption(3, 5, bar) }, … }; Now there really is no redundant information in each line of that table anymore. Use exceptions to handle errors Since all the errors we encounter here are indeed exceptional and will eventually cause us to exit the program, we can use exceptions. That means we don't have to pass programName and optionNumber down. For example, if we just throw a standard exception (or a custom one derived from it) whenever we encounter an error, then in the outermost loop we can write: for (int i = 1; i < argc; ++i) { try { auto [name, value] = splitAssignment(argv[i]); options[name](value); } catch (std::exception& ex) { std::cerr << "Error parsing option #" << i << ": " << ex.what() << '\n' << "Usage: " << argv[0] << " [<option>=<value>...]\n"; std::exit(EXIT_FAILURE); } }
{ "domain": "codereview.stackexchange", "id": 44888, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, parsing, console", "url": null }
c++, parsing, console Create a function for the outermost loop You made lots of functions to help parse options, but you still have a loop you have to manually write in main(). You can easily make a function for that, so that your main() would look like: int main(int argc, char* argv[]) { parseOptions(options, argc, argv); std::cout << "foo is " << foo << '\n'; … } Use the Doxygen format to document your code I see you added extensive comments to document your code. This is quite helpful, but with some minor changes it can be much better. If you use the Doxygen format, then the Doxygen tools can process your code and create hyperlinked HTML and PDF files containing the documentation. If you enable warnings, it can also warn you about functions and parameters you forgot to document. Finally, some code editors and IDEs might understand this format and use it to automatically add excerpts of your documentation into mouseover bubbles or tab completion popups.
{ "domain": "codereview.stackexchange", "id": 44888, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, parsing, console", "url": null }
performance, c, mathematics, fractals Title: Newton Fractal writen in C Question: The code has no errors, it is just slow. It takes 1.19s to start. How can I reduce runtime without using threads or multiple processes? I have tried compiler optimization (-o1, -o2 and -o3) These did not do much. typedef struct s_float2{ double x; double y; } t_float2; static t_float2 next(t_float2 z) { t_float2 new; double temp_deno; temp_deno = 3 * (z.x * z.x + z.y * z.y) * (z.x * z.x + z.y * z.y); new.x = ((z.x * z.x * z.x * z.x * z.x + 2 * z.x * z.x * z.x * z.y * z.y - z.x * z.x + z.x * z.y * z.y * z.y * z.y + z.y * z.y) / temp_deno); new.y = ((z.y * (z.x * z.x * z.x * z.x + 2 * z.x * z.x * z.y * z.y + 2 * z.x + z.y * z.y * z.y * z.y)) / temp_deno); z.x -= new.x; z.y -= new.y; return (z); } static t_float2 find_diff(t_float2 z, t_float2 root) { t_float2 new; new.x = z.x - root.x; new.y = z.y - root.y; return (new); } void init_roots(t_float2 *roots) { static unsigned int flag; if (!flag) { roots[0] = (t_float2){1, 0}; roots[1] = (t_float2){-0.5, 0.866025403784438}; roots[2] = (t_float2){-0.5, -0.866025403784438}; flag = 1; } } unsigned int checker_tolerance(t_fractal *fractal, t_float2 z, unsigned int iterations) { t_float2 difference; static t_float2 roots[3]; init_roots(&roots); difference = find_diff(z, roots[0]); if (fabs(difference.x) < fractal->tolerance && fabs(difference.y) < fractal->tolerance) return (1); difference = find_diff(z, roots[1]); if (fabs(difference.x) < fractal->tolerance && fabs(difference.y) < fractal->tolerance) return (1); difference = find_diff(z, roots[2]); if (fabs(difference.x) < fractal->tolerance && fabs(difference.y) < fractal->tolerance) return (1); return (0); }
{ "domain": "codereview.stackexchange", "id": 44889, "lm_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, mathematics, fractals", "url": null }
performance, c, mathematics, fractals void calculate_newton(t_fractal *fractal) { t_float2 z; unsigned int iterations; iterations = 0; z.x = (fractal->x / fractal->zoom) + fractal->offset_x; z.y = (fractal->y / fractal->zoom) + fractal->offset_y; while (iterations < fractal->max_iterations) { z = next(z); if (checker_tolerance(fractal, z, iterations) == 1) return (put_color_to_pixel(fractal, fractal->x, fractal->y, fractal->color * iterations / 2)); ++iterations; } put_color_to_pixel(fractal, fractal->x, fractal->y, 0x000000); } The github link is https://github.com/MehdiMirzaie2/fractol. Also, if you just want the main here it is: # include <mlx.h> # include <stdlib.h> # include <unistd.h> typedef struct s_fractal { void *mlx; void *window; void *image; void *pointer_to_image; int bits_per_pixel; int size_line; int endian; int x; int y; double zx; double zy; double cx; double cy; int color; double offset_x; double offset_y; double zoom; int name; int max_iterations; float tolerance; } t_fractal; static void free_and_explain(t_fractal *fractal) { ft_putendl_fd("Available fractals: a = mandel, b = julia, c = newton\ \n\033[1;31mASK FOR EXTRA, check your program!\033[0m", 1); exit_fractal(fractal); }
{ "domain": "codereview.stackexchange", "id": 44889, "lm_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, mathematics, fractals", "url": null }
performance, c, mathematics, fractals int draw_fractal(t_fractal *fractal, double cx, double cy) { fractal->x = 0; fractal->y = 0; while (fractal->x < SIZE) { while (fractal->y < SIZE) { if (fractal->name == 'a') calculate_mandelbrot(fractal); else if (fractal->name == 'b') calculate_julia(fractal, cx, cy); else if (fractal->name == 'c') calculate_newton(fractal); else free_and_explain(fractal); fractal->y++; } fractal->x++; fractal->y = 0; } mlx_put_image_to_window(fractal->mlx, fractal->window, fractal->image, 0, 0); return (0); } int main(int argc, char **argv) { t_fractal *fractal; if (argc != 2 || argv[1][1] != '\0') { ft_putendl_fd("Available fractals: a = mandel, b = julia, c = newton\ \n\033[1;31mASK FOR EXTRA!\033[0m", 1); return (0); } fractal = malloc(sizeof(t_fractal)); init_fractal(fractal); init_mlx(fractal); fractal->name = argv[1][0]; mlx_key_hook(fractal->window, key_hook, fractal); mlx_mouse_hook(fractal->window, mouse_hook, fractal); mlx_hook(fractal->window, 17, 0L, exit_fractal, fractal); draw_fractal(fractal, -0.79, 0.15); mlx_loop(fractal->mlx); return (0); } ``` Answer: I don't like parentheses around expressions returned. I do not understand init_roots(). Why not just initialise checker_tolerance()'s roots, or make it a compilation unit static const? (Do the numbers have a meaning? ±sqrt(¾), sin(±60°)?) Do not repeat yourself: unsigned int checker_tolerance(t_fractal const *fractal, t_float2 z, unsigned int iterations) { static const t_float2 roots[3] = { (t_float2){1, 0}, (t_float2){-0.5, 0.866025403784439}, (t_float2){-0.5, -0.866025403784439} }; const int nroots = sizeof roots / sizeof *root;
{ "domain": "codereview.stackexchange", "id": 44889, "lm_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, mathematics, fractals", "url": null }
performance, c, mathematics, fractals for (int root = 0 ; root < nroots ; root++) { t_float2 difference = find_diff(z, roots[root]); if (fabs(difference.x) < fractal->tolerance && fabs(difference.y) < fractal->tolerance) return 1; return 0; } – still looks weird: make roots a vector parameter? (Darn - C, not C++, and array/pointer & length sucks.) In next(), I need to count "multiplicities" - I'd rather not: static t_float2 next(t_float2 z) // const t_float2 *z? { const double x2 = z.x * z.x, // x4 = x2 * x2, // x3 = x2 * z.x, x5 = x2 * x3, y2 = z.y * z.y, // y4 = y2 * y2, sum_of_squares = x2 + y2, sum_of_squares2 = sum_of_squares * sum_of_squares, // x4 + 2*x2*y2 + y4 denominator = 3 * sum_of_squares, // z.x * z.x * z.x * z.x * z.x + 2 * z.x * z.x * z.x * z.y * z.y // - z.x * z.x + z.x * z.y * z.y * z.y * z.y + z.y * z.y x = // ( x5 + 2 * x3 * y2 - x2 + z.x * y4 + y2) / denominator, // (z.x * (x4 + 2 * x2 * y2 - z.x + y4) + y2) / denominator, (z.x * (sum_of_squares2 - z.x) + y2) / denominator, // z.y * (z.x * z.x * z.x * z.x + 2 * z.x * z.x // * z.y * z.y + 2 * z.x + z.y * z.y * z.y * z.y) y = // (z.y * (x4 + 2 * x2 * y2 + 2 * z.x + y4) / denominator; z.y * (sum_of_squares2 + 2 * z.x) / denominator; z.x -= x; z.y -= y; return z; } Oh, look: I think I recognized how similar the modifications to x and y have been. Seeing how fractal in calculate_newton(t_fractal *fractal) gets used, consider a const t_fractal *fractal). And return ‹expression› looks weird in a void function even with a void expression.
{ "domain": "codereview.stackexchange", "id": 44889, "lm_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, mathematics, fractals", "url": null }
python, performance, python-3.x, algorithm Title: Python script to split overlapping ranges, version 4
{ "domain": "codereview.stackexchange", "id": 44890, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm", "url": null }
python, performance, python-3.x, algorithm Question: This is the fourth iteration of a Python script I wrote that splits overlapping ranges, and this is the fastest version I have wrote so far, and also a version that works for all inputs. I have done rigorous testing using randomly generated samples and compared the output against the output of a method that is known to be correct, and there are no errors. I have a literally millions of triplets, the first two elements of each are integers, the third is of arbitrary type. The first number is always no larger than the second number, each triplet represents a integer range (inclusive) with associated data, the two numbers are start and end of the range, and the third element is the data that is associated with the range. Each triplet (start, end, data) is equivalent to a dictionary, where the keys are all integers from start to end (including both), and the value for all the keys is data, for example, (42, 50, 'A') is equivalent to {42: 'A', 43: 'A', 44: 'A', 45: 'A', 46: 'A', 47: 'A', 48: 'A', 49: 'A', 50: 'A'}. Now the ranges often overlap, and I wish to split the ranges so that all ranges are discrete and all ranges only have one datum which is the latest, and the number of ranges is minimal. It is important to note if two ranges (s1, e1, d1) and (s2, e2, d2) overlap, one is always completely inside the other, one is always a complete subset, either s1 <= s2 <= e2 < e1 or s2 <= s1 <= e1 < e2, they never intersect in my data. Two overlapping ranges can share the same data, in this case the smaller range needs to be ignored because there is no new data. For example, (48, 49, 'A') is {48: 'A', 49: 'A'} and it is already contained in my previous example, there is no data change.
{ "domain": "codereview.stackexchange", "id": 44890, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm", "url": null }
python, performance, python-3.x, algorithm If they overlap but have different data, then the smaller range's data overwrites the larger range, the data of the overlap is inherited from the newer one, the overlapping portion of the larger range is deleted, this is similar to dictionary update. For example, (43, 45, 'B') is {43: 'B', 44: 'B', 45: 'B'}, after operation with the first example, the data would be {42: 'A', 43: 'B', 44: 'B', 45: 'B', 46: 'A', 47: 'A', 48: 'A', 49: 'A', 50: 'A'}, and the triplet representation is [(42, 42, 'A'), (43, 45, 'B'), (46, 50, 'A')]. And finally sometimes the start of one range is the end of the previous range plus one, and both share the same data, they need to be joined, the previous range needs to be extended to the end of the new range, for example, given another range (51, 60, 'A'), the expected output for all the ranges given should be [(42, 42, 'A'), (43, 45, 'B'), (46, 60, 'A')].
{ "domain": "codereview.stackexchange", "id": 44890, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm", "url": null }
python, performance, python-3.x, algorithm Code from collections import deque class Range: processed = deque() stack = deque() def __init__(self, ini, fin, data) -> None: self.ini = ini self.fin = fin self.data = data def __repr__(self): return f'Range({self.ini}, {self.fin}, {self.data})' def cover(self, fin): if fin <= self.fin: return True def join(self, ini, fin): if ini <= self.fin + 1: self.fin = fin return True def prepend(self, ini): if self.ini < ini: Range.processed.append(Range(self.ini, ini - 1, self.data)) def climb(self, fin): if self.ini < (ini := fin + 1) <= self.fin: self.ini = ini def update(self, ini, fin, data): if self.ini == ini and self.fin == fin: self.data = data return True def process(self, ini, fin, data): ignore = past = False if self.data == data: ignore = self.cover(fin) or self.join(ini, fin) elif ini <= self.fin and not (ignore := self.update(ini, fin, data)): self.prepend(ini) if not ignore: if ini > self.fin: Range.processed.append(self) Range.stack.pop() past = True self.climb(fin) return not ignore, past def discretize(ranges): Range.processed.clear() Range.stack.clear() for ini, fin, data in ranges: if not Range.stack: Range.stack.append(Range(ini, fin, data)) else: append, past = Range.stack[-1].process(ini, fin, data) while past and Range.stack: _, past = Range.stack[-1].process(ini, fin, data) if append: Range.stack.append(Range(ini, fin, data)) Range.processed.extend(reversed(Range.stack)) return Range.processed
{ "domain": "codereview.stackexchange", "id": 44890, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm", "url": null }
python, performance, python-3.x, algorithm I did hundred of tests using examples generated using this and compared the result against the method from the answer linked above, and the results were all correct, the script truly does exactly what I intend and there are no bugs. But it is very important to note the input must be sorted by the start ascending and end descending before processing using my method, though in my case the input is always pre-sorted, and it won't work correctly if the ranges intersect instead of one being subset of the other, this is intentional because in my data this never happens, so I optimized that out. I did try using Interval Tree as suggested by this answer, but it is extremely slow and doesn't suit my needs: data = [ (3, 2789, 2681), (27, 2349, 2004), (29, 1790, 2072), (32, 1507, 1173), (35, 768, 3453), (63, 222, 2108), (341, 501, 2938), (378, 444, 258), (870, 888, 1364), (1684, 1693, 880) ] In [73]: %timeit merge_rows(data) 1.24 ms ± 9.43 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each) My method is by far faster, in fact all my previous methods are much faster than that, and the current one is the fastest: In [76]: %timeit discretize(data) 23.3 µs ± 525 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) Given this: sample = [(2518812, 3931503981, 1222922854), (8283077, 3890282434, 2360189310), (21368257, 3571587114, 2651809994), (24571285, 2875098555, 1506778869), (40433776, 1751972813, 4162881198), (60822897, 1413187009, 921758666), (73435921, 1245663774, 3798627995), (169616863, 530686872, 1316302364), (273065748, 432363205, 3428529648), (291266380, 409571968, 4206669862), (558988640, 574048639, 4272236023), (619240775, 631101725, 1910576108), (727687992, 756241696, 3095538347), (825700858, 866696475, 2647033502), (853058882, 854026525, 2456782176), (967641241, 1001077664, 3556790281)]
{ "domain": "codereview.stackexchange", "id": 44890, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm", "url": null }
python, performance, python-3.x, algorithm The performance of my code is: In [80]: %timeit discretize(sample) 36.8 µs ± 790 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) The code from the linked Stack Overflow answer is faster than mine, but it looks extremely ugly and I don't like it, it took me a while to understand how it works, and I have tried to optimize and refactor it but found it hard to do, so I wrote another version, but it somehow is a little slower: In [81]: %timeit descretize(sample) 28.1 µs ± 1.06 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each) How can I make my code more efficient? (I used ini for start and fin for end, to save characters thus making the code more concise, they are from Latin, initus is Latin for start and where you get __init__, finis is Latin for end and where you get "finish") Update It turns out my original code doesn't work properly, if a sub range shares the same data as the parent range, it should be ignored, but if the sub range is separated from the parent range by some other range, sometimes the sub range isn't properly ignored. I only found this out after I have written a clever method to generate a big number of overlapping ranges, as answers are posted I am not allowed to edit the code. Also the answer by @booboo doesn't work properly for the test cases generated by my new method, I have tested extensively using both the original method and the method optimized by me, they both fail for many test cases, and somehow frequently eats literally Gibibytes of RAM (I have 16 GiB and it uses 8GiB+ in a short time), freezing my computer and I had to reboot my computer. So there aren't answers that are bounty worthy. If there are no new answers then the bounty has to be wasted. The function I wrote to generate test cases: import random
{ "domain": "codereview.stackexchange", "id": 44890, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm", "url": null }
python, performance, python-3.x, algorithm def make_sample(num, lim, dat): if num * 2 > lim: lim = num * 2 + random.randrange(num) stack = [sorted(random.choices(range(lim), k=2*num))] ranges = [] while stack: top = stack.pop(0) l = len(top) if l == 2: ranges.append(top) elif l == 4: ranges.extend([top[:2], top[2:]]) else: choice = random.randrange(3) if not choice: ranges.append([top[0], top[-1]]) stack.append(top[1:-1]) elif choice == 1: i = l//3 i += i % 2 index = random.randrange(i, 2*i, 2) ranges.append(top[index:index+2]) stack.extend([top[:index], top[index+2:]]) else: index = random.randrange(2, l - 2, 2) stack.extend([top[:index], top[index:]]) ranges.sort(key=lambda x: (x[0], -x[1])) return [(a, b, random.randrange(dat)) for a, b in ranges] New answers must generate the correct output for make_sample(2048, 65536, 32), the correct output can be verified by comparing against the output of descritize function found in the answer on Stack Overflow linked at the top of the question in the first paragraph. And it also needs to be comparable in performance to it, and of course for it to be of comparable performance it must not eat up RAM and freeze the computer.
{ "domain": "codereview.stackexchange", "id": 44890, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm", "url": null }
python, performance, python-3.x, algorithm I edited the code that generates the samples to address bugs in the logic. The code generates invalid input because the numbers are required to be unique, [(0, 1, 'A'), (0, 1, 'B')] is invalid, but cases like this can be generated by my code. I first thought random.choices guarantees the choices to be unique if sample size is less than population size, I was wrong, it is just highly likely. I fixed the code so that all numbers are guaranteed to be unique, and invalid test cases won't generated. I edited the code but I haven't tested the functions thoroughly yet, my edit was immediately rolled back, though I would argue the edited code isn't what I wanted reviewed, this is an error by the one who made the reversion, though I won't edit the code again lest it be rolled back again. And yes, the input is guaranteed to be sorted in ascending order, as I mentioned in my question multiple times and demonstrated with the code that generates test cases. Lastly I am experiencing some "technical difficulties", more specifically my computer doesn't have internet connections right now because I just broke my modem (I just bought a new one online), and I am using my phone right now (which doesn't have reliable VPN connection now and in China Stack Exchange is throttled to nearly inaccessible), so updates will be much less frequent as of now. But I will try to award the bounty within the bounty grace period if I found a bounty-worthy answer (if new answers are posted) or if I determined @booboo's method to be correct. That is, if I managed to visit this site at all, of course. It is summer and my apartment building has experienced yet another blackout, my computer is a desktop and I can't even boot my computer to test the code. I was out before and now my phone is running out of juice, I don't know how long the blackout will last so there is a chance I won't be able to award the bounty.
{ "domain": "codereview.stackexchange", "id": 44890, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm", "url": null }
python, performance, python-3.x, algorithm Answer: Update I have abandoned my implementation, which I agree does not work on the test case the OP posted. However, I do believe that the OP's code also produces erroneous results. So first I am replicating below comments I had made to my answer that highlight what I perceive to be the problem: I have been trying to modify my code so that I get the same results with the test data you posted here. I printed out the first few ranges in your results and ranges 17 through 19 (origin 0) are Range(2414, 2573, 14), Range(2574, 2599, 9), Range(2414, 2574, 14). That does not look right to me. The algorithm you state is correct, which I have not studied, has the following ranges for elements 17 - 19: (2414, 2574, 14), (2575, 2599, 9), (2600, 2816, 6), which is clearly different from what your code produced. The test data has as input [... (2414, 2574, 14), (2574, 2599, 9), ...]. I would think that the value for key 2574 should be 9 if we apply the dictionary updates in order. This suggests to me that the known "correct" algorithm is not so correct and elements 17 - 19 should be (2414, 2573, 14), (2574, 2599, 9), (2600, 2816, 6). To verify what I expected the correct results to be, I implemented code that computes the ranges in an inefficient but hopefully correct way: I allocate a list values whose size if MAX_RANGE_NUMBER - MIN_RANGE_NUMBER + 1 where MAX_RANGE_NUMBER would correspond to the maximum value of t[1] where t enumerates all the tuples in your test data and MIN_RANGE_NUMBER is the minimum value of t[0]. I initialize each element of the list to None. I then proceed to iterate each tuple in the test data. If a tuple were, for example, (17, 27, 19) I would assign values[17-MIN_RANGE_NUMBER:27+MIN_RANGE_NUMBER+1] = [19] * 11. After all ranges have been thus processed it is fairly simple to process the values list to come up with the non-overlapping ranges. I then print out the first 20 such ranges: from typing import List, Tuple
{ "domain": "codereview.stackexchange", "id": 44890, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm", "url": null }
python, performance, python-3.x, algorithm def discretize_correct(ranges: List[Tuple]) -> List[Tuple]: """We are passed a list of tuples each representing a range and we return a new list of range tuples.""" if not ranges: # Empty list return [] results = [] MIN_RANGE_NUMBER = min(range[0] for range in ranges) MAX_RANGE_NUMBER = max(range[1] for range in ranges) range_size = MAX_RANGE_NUMBER - MIN_RANGE_NUMBER + 1 values = [None] * range_size for range in ranges: start, end, value = range start -= MIN_RANGE_NUMBER end -= MIN_RANGE_NUMBER values[start:end+1] = [value] * (end + 1 - start) results = [] start_idx, last_value = None, None for idx, value in enumerate(values, start=MIN_RANGE_NUMBER): if value is None: if last_value is not None: results.append((start_idx, idx - 1, last_value)) last_value = None elif last_value is None: start_idx = idx last_value = value elif value != last_value: results.append((start_idx, idx - 1, last_value)) start_idx = idx last_value = value if last_value is not None: results.append((start_idx, MAX_RANGE_NUMBER, last_value)) return results if __name__ == '__main__': from ast import literal_eval with open('test.txt') as f: data = literal_eval(f.read()) ranges = discretize_correct(data) # Print out first 20 ranges: for i in range(20): print(f'{i}: {ranges[i]}') Prints: 0: (10, 181, 2) 1: (182, 706, 11) 2: (707, 920, 6) 3: (921, 1018, 7) 4: (1019, 1032, 6) 5: (1033, 1200, 2) 6: (1201, 1204, 6) 7: (1205, 1617, 0) 8: (1618, 1667, 6) 9: (1668, 1905, 11) 10: (1906, 1977, 6) 11: (1978, 2015, 2) 12: (2016, 2075, 6) 13: (2076, 2082, 3) 14: (2083, 2201, 6) 15: (2202, 2320, 10) 16: (2321, 2413, 6) 17: (2414, 2573, 14) 18: (2574, 2599, 9) 19: (2600, 2816, 6)
{ "domain": "codereview.stackexchange", "id": 44890, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm", "url": null }
python, performance, python-3.x, algorithm Conclusion The above verifies that the OP's code and the supposedly correct code posted here both produce results not only different from one another but also from what I believe are truly the correct results. Even if I have misunderstood the problem definition rendering the above results from my discretize_correct function irrelevant, the OP's results still vary from those produced from what the OP says is correct code. Consequently, should the OP's code now be moved to stackoverflow.com for correction before it is re-posted here?
{ "domain": "codereview.stackexchange", "id": 44890, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm", "url": null }
beginner, rust Title: Convert decimal to base K Question: Problem statement: Write a program that takes two command-line arguments number and k. The program should convert number to base k. Assume the base is between 2 and 16 inclusive. For bases greater than 10, use the letters A through F to represent the digits 10 through 15, respectively. This is one of my self-imposed challenges in Rust to become better at it. The problem was taken from Sedgewick Exercise 1.3.21. Here is my code: use std::env; fn main() { let arguments: Vec<String> = env::args().collect(); let mut number: u32 = arguments[1].parse().unwrap(); let k: u32 = arguments[2].parse().unwrap(); let number_original: u32 = number; let mut largest_power: u32 = 1; let mut kary: String = String::new(); while largest_power <= number/k { largest_power *= k; } while largest_power > 0 { if largest_power > number { kary.push_str(&format!("{}", "0")); } else { let dividend: u32 = number/largest_power; if number/largest_power < 10 { kary.push_str(&format!("{}", dividend.to_string())); number -= dividend*largest_power; } else if number/largest_power == 10 {kary.push_str(&format!("{}", "A")); number -= dividend*largest_power;} else if number/largest_power == 11 {kary.push_str(&format!("{}", "B")); number -= dividend*largest_power;} else if number/largest_power == 12 {kary.push_str(&format!("{}", "C")); number -= dividend*largest_power;} else if number/largest_power == 13 {kary.push_str(&format!("{}", "D")); number -= dividend*largest_power;} else if number/largest_power == 14 {kary.push_str(&format!("{}", "E")); number -= dividend*largest_power;} else if number/largest_power == 15 {kary.push_str(&format!("{}", "F")); number -= dividend*largest_power;} } largest_power /= k; }
{ "domain": "codereview.stackexchange", "id": 44891, "lm_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, rust", "url": null }
beginner, rust largest_power /= k; } match k { 2..=16 => println!("The number {} at base {} is represented with {}.", number_original, k, kary), _ => panic!("Base must be between 2 and 16."), } } Is there any way that I can improve my code? Answer: Don't unwrap Panicking is not a good way to handle errors. Rather provide an error message in case of an Err and exit the program gracefully. Use libraries If you'd use e.g. clap you can let it parse the CLI arguments for you as the desired data type (u32 in your case) and gracefully handle the respective errors. There's also radix_fmt available to do the conversion to any base. Use expressive variable names The name kary is misleading. It sounds like a person's name. If you're referring to k-ary numbers, maybe rename it to k_ary. Though a less technical term such as digits should also suffice and might be more widely understood. Use rustfmt or cargo fmt ... to format your code with a standardized style. Validate your input. Running the program e.g. with a base 1 results in an infinite loop. Invalid input as base-1 should be caught early. Similarly base-0 inputs panic the program. Don't panic!() If you encounter an error use e.g. eprintln!() to print an error message and use std::process::exit() to exit the program with a possibly nonzero return code. Suggested: src/main.rs use clap::Parser; use radix_fmt::radix; use std::ops::RangeInclusive; use std::process::exit; const VALID_BASES: RangeInclusive<u8> = 2..=36; #[derive(Debug, Parser)] struct Args { #[arg(index = 1)] number: u32, #[arg(index = 2)] base: u8, } fn main() { let args = Args::parse(); if !VALID_BASES.contains(&args.base) { eprintln!( "Base must be in {}..={}", VALID_BASES.start(), VALID_BASES.end() ); exit(1); }
{ "domain": "codereview.stackexchange", "id": 44891, "lm_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, rust", "url": null }
beginner, rust println!( "Number {} in base {} is: {}", args.number, args.base, radix(args.number, args.base) ); } Cargo.toml [package] name = "bases" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] clap = { version = "4.3.11", features = ["derive"] } radix_fmt = "1.0.0"
{ "domain": "codereview.stackexchange", "id": 44891, "lm_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, rust", "url": null }
performance, python-3.x, file, iteration Title: Increasing writing speed to file inside a for-loop for large files Question: I have a .csv file containing 100 millions records, I would to create multiple files from this file, after certain condition satisfied in each line, I came to this code below, but it is slow, I think, it is due the fact the a file is opened and closed in each iteration. The result is many files renamed after countries, each file has inside the correspondant line from the large file. Is there any approach or method that can get rid of this problem and increase the speed? import csv with open('stats.csv','r', encoding = 'utf-8') as inf, open('stats_failed.txt', 'a', encoding = 'utf-8', newline = '') as failed_ouf: csr = csv.reader(inf) for i, record in enumerate(csr): try: country = record[3] #because some country have these characters, invalid for file renaming if '/' in country: country = country.replace('/','_SLASH_') elif '\\' in country: country = country.replace('\\','_BACKSLASH_') #pop the country because irrelevant since the file has its name record.pop(3) with open(country, 'a', encoding = 'utf-8', newline = '') as output: csw = csv.writer(output) csw.writerow(record) #just for tracking if i % 100_000 == 0: print(i) output.flush() except: failed_csw = csv.writer(failed_ouf) failed_csw.writerow(record)
{ "domain": "codereview.stackexchange", "id": 44892, "lm_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, python-3.x, file, iteration", "url": null }
performance, python-3.x, file, iteration EDITED To those who asked: It looks like this: col1,col2,country,mod1,code,mod2 \N,\N,Germany,C510,\N,C510 \N,\N,"China, Taipei",C25C,\N,C25C \N,\N,Italy,GLF5,\N,GLF5 \N,\N,France,C25B,\N,C25B \N,\N,Germany,C525,\N,C525 \N,\N,Turkey,PC12,\N,PC12 \N,\N,Germany,C680,\N,C680 \N,\N,Germany,GL5T,\N,GL5T \N,\N,Germany,C25B,\N,C25B \N,\N,Italy,GLF4,\N,GLF4 \N,\N,France,CRJ2,\N,CRJ2 \N,\N,Palestine,G280,\N,G280 \N,\N,Slovakia,C525,\N,C525 .... \N,\N,United States,E55P,\N,E55P \N,\N,Russia,C56X,\N,C56X EDITED2 If it is relevant, the size is about 4 GB Answer: This is slow for a lot of reasons: It's Python The data-processing operations are non-vectorized There's one file open/write/close per row! So delete your code and use Pandas, which is written in part in C and has Python FFI. 4 GB should fit into the working memory of most modern computers so you don't need to be clever with segmentation, etc. I'm sure most other programs would sooner expect a blank ,, CSV record to mean "nothing" than \N, so tell Pandas to load the latter as a NaN. Your list of incompatible characters (at least on Windows) for filesystems is not complete. Also: since you're removing those characters from the filename, are you sure it's such a good idea to drop the original country string from the data? Never bare try/except. Suggested import pandas as pd df = pd.read_csv('stats.csv', na_values=r'\N') df['filename'] = df.country.str.replace(r'[^,\w_.)( -]+', '_', regex=True) + '.csv' for filename, group in df.groupby('filename'): group.drop('filename', axis=1).to_csv(filename, index=False) col1,col2,country,mod1,code,mod2 ,,"China, Taipei",C25C,,C25C
{ "domain": "codereview.stackexchange", "id": 44892, "lm_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, python-3.x, file, iteration", "url": null }
python Title: Combination of three vocabulary sets Question: "Core", "advanced", "extra" are sets of vocabulary for those who study a foreign language. A user has to choose one, two or all three sets. I would like to get all possible combinations: from itertools import product variants = list(product([0, 1], repeat=3)) variants.remove((0, 0, 0)) # In this case a validation exception is risen. print(list(variants)) sample = ["core", "advanced", "extra",] result = [] for variant in variants: tmp = [] for i in range(3): if variant[i]: tmp.append(sample[i]) result.append(tmp) print (result) The result is achieved. But could you tell me whether my code can be written more elegantly? Answer: I would go with the itertools.compress method where: compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F Then your code becomes: from itertools import compress, product variants = list(product([0, 1], repeat=3)) variants.remove((0, 0, 0)) # At least one type of vocabulary must be selected sample = ["core", "advanced", "extra",] result = list(list(compress(sample, variant)) for variant in variants) print(result) Prints: [['extra'], ['advanced'], ['advanced', 'extra'], ['core'], ['core', 'extra'], ['core', 'advanced'], ['core', 'advanced', 'extra']]
{ "domain": "codereview.stackexchange", "id": 44893, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
c#, .net-core Title: Class `SettingView` sending messages to a console in C# Question: My challenge is to transfer examples from textbooks or videos into something I am coding on my own. Environment Visual Studio 2022 Net 7.0 ConsoleApp My goal My idea is to have a solution to provide messages to a console. Like "press enter to continue ..." or "you are leaving the app ...". And some functions like "clear screen" or "resize screen". Thus, nothing really smart or special. In the long run the view SettingView shall display some setting information on the console. My goal is to get used to the SOLID principles. So far, I was putting everything in just a few classes (the less the better) and I was hardly using any interfaces. It is kind of challanging to get rid of these old coding habits. To reach my goal I did the following
{ "domain": "codereview.stackexchange", "id": 44894, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net-core", "url": null }
c#, .net-core Splitting up the huge class and interface into smaller ones. Each of the should perform simple tasks. e.g. classes implementing IMessaging just have a Show() method to display some content on the console. Using interfaces to make it easy to exchange classes. e.g. SettingView does have the property StartMessage of type IMessaging. To alter the output on the console I just need to replace instancing StartingView with StartingApp. Implementing dependency injection. e.g. SettingView and ISettingView. Instead of implementing all the interfaces like IMessaging I have created properties which contain all the logic, like StartMessage of type IMessaging. I just wanted to have one method in ISettingView and this was Run. That should be the starting point when GetService<ISettingView> is called. Making the code expandable. This I tested by not just having one class StartingView but also to have the class StartingApp. In this second class I could do different stuff, but I would not have to change any code in the main logic of SettingView. To follow the MVVM pattern I have created SettingViewModel but I am not sure what to put there. The ViewModel should host the logic of the View. And so far I am just working on the View itself. I suppose all the information that will be displayed in ShowContent() should be provided by the ViewModel. Source Code The project is available on github. Program.cs using BasicCodingConsole.Views.MainView; using BasicCodingConsole.Views.SettingView; using BasicCodingLibrary.Models; using BasicCodingLibrary.ViewModels; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog;
{ "domain": "codereview.stackexchange", "id": 44894, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net-core", "url": null }
c#, .net-core #region ***** Configuration ***** var builder = new ConfigurationBuilder(); builder.SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", false, true) .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", true) .AddEnvironmentVariables() .AddCommandLine(args); Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(builder.Build()) .Enrich.FromLogContext() //.WriteTo.Console() // activate to send the logging to the console .WriteTo.File("LogFiles/apploggings.txt") // activate to send the logging to a file .CreateLogger(); var host = Host.CreateDefaultBuilder() .ConfigureServices((context, services) => { services.AddLogging(); services.Configure<UserInformation>(builder.Build().GetSection("UserInformation")); services.Configure<ApplicationInformation>(builder.Build().GetSection("ApplicationInformation")); services.AddTransient<IMainView, MainView>(); services.AddTransient<IMainViewModel, MainViewModel>(); services.AddTransient<IAppSettingProvider, AppSettingProvider>(); services.AddTransient<ISettingView, SettingView>(); services.AddTransient<ISettingViewModel, SettingViewModel>(); }) .UseSerilog() .Build(); var scope = host.Services.CreateScope(); var services = scope.ServiceProvider; #endregion
{ "domain": "codereview.stackexchange", "id": 44894, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net-core", "url": null }
c#, .net-core var scope = host.Services.CreateScope(); var services = scope.ServiceProvider; #endregion #region ***** Run ***** try { Log.Logger.Information("***** Run Application *****"); Log.Logger.Information($"EnvironmentVariable: {Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")}"); Console.WriteLine($"EnvironmentVariable: {Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")}"); Log.Logger.Information($"CommandLineArgument: {builder.Build().GetValue<string>("CommandLineArgument")}"); Console.WriteLine($"CommandLineArgument: {builder.Build().GetValue<string>("CommandLineArgument")}"); foreach (var item in args) { Log.Logger.Information($"Args: {item}"); Console.WriteLine($"Args: {item}"); } Console.ReadLine(); services.GetService<IMainView>()! .Run(args); } catch (Exception e) { Log.Logger.Error("Unexpected Exception!", e); Console.WriteLine("Unexpected Exception!"); Console.WriteLine(e); Console.WriteLine($"\n***** Press ENTER To Continue *****"); Console.ReadLine(); } finally { Log.Logger.Information("***** End Application *****"); #if DEBUG Console.Clear(); Console.WriteLine($"\n***** End Of Debug Mode - Press ENTER To Close The Window *****"); Console.ReadLine(); #endif } #endregion MainView.cs (just a little codesnippet, since this class needs to be worked on extensive). When clicking C in a menu this method is called. private void Action_C() { using var scope = _hostProvider.Services.CreateScope(); var services = scope.ServiceProvider; services.GetService<ISettingView>()!.Run(); }
{ "domain": "codereview.stackexchange", "id": 44894, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net-core", "url": null }
c#, .net-core SettingView here I want to display the information provided by appsettings.json (whether got from the CommandLine, launchSettings.json, appsettings.Production.json or appsettings.json. using BasicCodingConsole.ConsoleMessages; using BasicCodingConsole.ConsoleViews; using BasicCodingLibrary.ViewModels; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System.Diagnostics; namespace BasicCodingConsole.Views.SettingView; public class SettingView : ISettingView { #region ***** Field ***** private readonly ILogger<SettingView> _logger; private readonly IConfiguration _configuration; private readonly ISettingViewModel _settingViewModel; #endregion #region ***** Property ***** public IMessaging StartMessage => new StartingView(nameof(SettingView)); public IMessaging EndMessage => new EndingView(nameof(SettingView)); public IView Display => new View(); #endregion #region ***** Constructor ***** public SettingView(ILogger<SettingView> logger, IConfiguration configuration, ISettingViewModel settingViewModel) { Debug.WriteLine($"Passing <Constructor> in <{nameof(SettingView)}>."); _logger = logger; _configuration = configuration; _settingViewModel = settingViewModel; } #endregion #region ***** Interface Member (ISettingView) ***** public void Run() { Display.Clear(); Display.Resize(0, 0); StartMessage.Show(); ShowContent(); EndMessage.Show(); } #endregion #region ***** Private Member ***** private void ShowContent() { string message = "This is individual text by karwenzman!"; Console.WriteLine(message); _logger.LogInformation(message); Console.WriteLine($"\nConnectionString (key = Default): {_configuration.GetConnectionString("Default")}"); } #endregion }
{ "domain": "codereview.stackexchange", "id": 44894, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net-core", "url": null }
c#, .net-core ISettingView, IConsoleMessage, IConsoleView (each in separate files) using BasicCodingConsole.ConsoleMessages; using BasicCodingConsole.ConsoleViews; namespace BasicCodingConsole.Views.SettingView; public interface ISettingView : IConsoleMessage, IConsoleView { } namespace BasicCodingConsole.ConsoleMessages; public interface IConsoleMessage { IMessaging StartMessage { get; } IMessaging EndMessage { get; } } namespace BasicCodingConsole.ConsoleViews; public interface IConsoleView { IView Display { get; } void Run(); } IView, View, IClearing and ClearingView (each in separate files) namespace BasicCodingConsole.ConsoleViews; public interface IView : IClearing, IResizing { } namespace BasicCodingConsole.ConsoleViews; public class View : IView { public void Clear() { IClearing clearingView = new ClearingView(); clearingView.Clear(); } public void Resize(int consoleWidth, int consoleHeight) { IResizing resizeView = new ResizingView(); resizeView.Resize(consoleWidth, consoleHeight); } } namespace BasicCodingConsole.ConsoleViews; public interface IClearing { void Clear(); } namespace BasicCodingConsole.ConsoleViews; public class ClearingView : IClearing { public void Clear() { Console.WriteLine($"Calling {nameof(ClearingView)}. Press ENTER to clear the view ..."); Console.ReadLine(); Console.Clear(); } } IMessaging and StartingView (each in separate files) namespace BasicCodingConsole.ConsoleMessages; public interface IMessaging { string CallingClass { get; } void Show(); } namespace BasicCodingConsole.ConsoleMessages; public class StartingView : IMessaging { public string CallingClass { get; } public StartingView(string callingClass) { CallingClass = callingClass; }
{ "domain": "codereview.stackexchange", "id": 44894, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net-core", "url": null }
c#, .net-core public StartingView(string callingClass) { CallingClass = callingClass; } public void Show() { string message = $"You have started the view: {CallingClass}"; Console.WriteLine(message); Console.WriteLine("=".PadLeft(message.Length, '=')); } } This is my updated structure. I am asking for some mentoring. Answer: General Observations When presenting multiple files of code it is much easier to follow when the file is presented in the following manner: filename code in file. Presenting multiple files like this is very difficult to review the code: ISettingView, IConsoleMessage, IConsoleView (each in separate files) using BasicCodingConsole.ConsoleMessages; using BasicCodingConsole.ConsoleViews; namespace BasicCodingConsole.Views.SettingView; public interface ISettingView : IConsoleMessage, IConsoleView { } namespace BasicCodingConsole.ConsoleMessages; public interface IConsoleMessage { IMessaging StartMessage { get; } IMessaging EndMessage { get; } } namespace BasicCodingConsole.ConsoleViews; public interface IConsoleView { IView Display { get; } void Run(); } We generally close questions on code review where we don't see the definitions of objects or methods that are used in the code. This question was closed once for that, there are still objects or interfaces that are used that are not defined, but this question needs a good answer. Unnecessary Interfaces It isn't clear that the interface IMainView or the interface ISettingView are necessary, since only once class is derived from each of these interfaces and those classes are not inherited. public class MainView : ViewBase, IConsoleMessage, IConsoleView { } public class SettingView : IConsoleMessage, IConsoleView { }
{ "domain": "codereview.stackexchange", "id": 44894, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net-core", "url": null }
c#, .net-core public class SettingView : IConsoleMessage, IConsoleView { } Use of Regions There is a lot of use of regions in the code. This is a feature of C#, but it isn't one I use because it tends to hide code that I need to see. Very few of the classes are large enough to require regions to be able to follow the implementation of the object. I generally don't collapse the methods in a class either. A place where regions obviously are not necessary is Person.cs. This class is very simple and does not fill the screen. If the file was 1000 lines of code and comments regions might possibly make sense (it would still be hiding important code). using BasicCodingLibrary.Enums; using System.Reflection; namespace BasicCodingLibrary.Models; /// <summary> /// This class is providing members to describe a <see cref="Person"/>. /// </summary> public class Person { #region ***** Property ***** /// <summary> /// The person's unique ID. /// </summary> public int Id { get; set; } = 0; /// <summary> /// The person's first name. /// </summary> public string FirstName { get; set; } = "default"; /// <summary> /// The person's last name. /// </summary> public string LastName { get; set; } = "default"; /// <summary> /// The person's gender. /// </summary> public Gender Gender { get; set; } = Gender.unknown; #endregion } Is the Code SOLID In the original version of this question you asked if you following the SOLID design principles.
{ "domain": "codereview.stackexchange", "id": 44894, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net-core", "url": null }
c#, .net-core The code does follow the Single Responsibility Principle. Based on code from the project that is not posted in this question, the Single Responsibility Principle (SRP) may have been over used, but that isn't completely clear. An example of the overuse of the SRP is in 2 files not presented in the question, Gender.cs and Person.cs. The enum in Gender.cs doesn't seem to be used anywhere in the code that excludes Person.cs so there is no reason to have the enum in a separate file. While there is inheritance of interfaces and classes, it isn't completely clear that the Open-closed Principle is being followed, since there doesn't seem to be any extensions of the classes in use. I don't see any substitution being performed. MainView inherits from ViewBase but there are no other classes that inherit from ViewBase so it isn't clear that this distinction is necessary. I suggest that you do some more research on this part of your question by using the links provided here: SOLID is 5 object orieneted design principles. SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable. This will help you design your objects and classes better.
{ "domain": "codereview.stackexchange", "id": 44894, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net-core", "url": null }
c#, .net-core The Single Responsibility Principle - A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class. The Open–closed Principle - states software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. The Liskov Substitution Principle - Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program. The Interface segregation principle - states that no client should be forced to depend on methods it does not use. The Dependency Inversion Principle - is a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details.
{ "domain": "codereview.stackexchange", "id": 44894, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net-core", "url": null }
c++, iterator Title: Random Access Iterator Implementation Question: (This is the Non-const version, I have to implement the const one too). Could someone please review this implementation? This is made for std::vector I'm unsure whether I respected all requirements for LegacyRandomAccessIterator; so if I'm missing something, please do let me know. namespace random_access { template<typename Type> class iterator { private: Type* m_iterator; public: using value_type = Type; using reference = value_type&; using pointer = value_type*; using iterator_category = std::random_access_iterator_tag; using difference_type = std::ptrdiff_t; //using iterator_concept = std::contiguous_iterator_tag; constexpr iterator(Type* iter = nullptr) : m_iterator{ iter } {}
{ "domain": "codereview.stackexchange", "id": 44895, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, iterator", "url": null }