body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I am trying to implement a greedy zip method in Haskell where it does not drop the elements, instead, it will use some default value. I appreciate any feedback to make it more compact.</p> <pre><code>zip' [-1] [] r = r zip' [] [-1] r = r zip' [] b r = zip' [-1] b r zip' a [] r = zip' a [-1] r zip' a b r = (xa, xb) : (zip' xsa xsb r) where (xa: xsa) = a (xb: xsb) = b main = do let l1 = [1, 2, 3] let l2 = [3, 4] print (zip' l1 l2 []) -- expected: [(1,3),(2,4),(3,-1)] </code></pre>
[]
[ { "body": "<p><code>r</code> is always <code>[]</code>. Simpler library functions can do some of the work.</p>\n\n<pre><code>zip' [] b = map (-1,) b\nzip' a [] = map (,-1) a\nzip' (x:xs) (y:ys) = (x, y) : zip' xs ys\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T01:11:01.870", "Id": "237597", "ParentId": "237525", "Score": "1" } } ]
{ "AcceptedAnswerId": "237597", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T00:32:20.710", "Id": "237525", "Score": "1", "Tags": [ "haskell" ], "Title": "Haskell creating a greedy zip function" }
237525
<p>I have a list [5,2,7,4,3,2,0,8, 9,100,99,98,97,93,92] i need out [100,99,98,97] but i am getting 4, 3, 2, 100, 99, 98, 97, 93, 92</p> <pre><code>`arr=[5,2,7,4,3,2,0,8, 9,100,99,98,97,93,92] z=[] l=[] for i in range(len(arr)-1): if(arr[i]==arr[i+1]+1): if(arr[i] not in z): z.append(arr[i]) if(arr[i+1] not in z): z.append(arr[i+1]) print(z)` </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T03:16:38.127", "Id": "465832", "Score": "0", "body": "Welcome to the Code Review StackExchange! Unfortunately, broken code is off-topic here. Please see the [Help Center](https://codereview.stackexchange.com/help/dont-ask) for more details." } ]
[ { "body": "<p>The problem with the algorithm is:\n1. there is no logic that recognizes the ending of the on-going consecutive decreasing sequence.\n2. there is no logic that compares candidate sequences and tracks the longer one. </p>\n\n<p>If we walk through the code, we can see it encounters a sequence of <code>4,3,2</code> starting from 4th iteration and then it encounters a sequence of <code>100,99,98,97</code>. So the output is expected. </p>\n\n<p>An example of working code:</p>\n\n<pre><code>arr=[5,2,7,4,3,2,0,8, 9,100,99,98,97,93,92]\nlongest = []\ncurrent = []\ni = 0\nif len(arr &lt; 2):\n print(arr)\n return\n\nwhile i &lt; len(arr)-1:\n current.append(arr[i])\n j = i + 1\n while j &lt; len(arr) and arr[i] == arr[j] + j-i:\n current.append(arr[j])\n j += 1\n\n i = j # start a new sequence at index j \n\n if len(current) &gt; len(longest):\n longest = current\n current = []\n\nprint(longest)\n</code></pre>\n\n<p>There are definitely better ways to implement this in idiomatic python but hopefully, the code above illustrates the algorithm. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T03:49:31.030", "Id": "237531", "ParentId": "237530", "Score": "1" } }, { "body": "<p>your algorithm is flawed. </p>\n\n<p>you need to reset the array when you start a new sequence. keep a record of the current longest sequence so you can work out which is longest</p>\n\n<pre><code>import copy\narr=[5,2,7,4,3,2,0,8,9,100,99,98,97,93,92]\nz = []\nl = []\n\nfor i in range(1, len(arr)):\n l.append (arr[i-1])\n print(arr[i-1])\n while( i &lt; len(arr) and arr[i-1] - 1 == arr[i]): \n l.append(arr[i]) \n print(arr[i])\n i=i+1\n if(len(l) &gt; len(z)): \n print(\"clear\") \n z = z.clear()\n z = copy.copy(l) \n l.clear()\nprint(z)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T04:08:41.347", "Id": "237533", "ParentId": "237530", "Score": "1" } } ]
{ "AcceptedAnswerId": "237533", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T02:57:53.523", "Id": "237530", "Score": "0", "Tags": [ "python", "python-3.x" ], "Title": "find the longest sequence of consecutive numbers in decreasing order" }
237530
<p>Below is code for handling events in SFML. It works by reading a text file containing a sequence of functions to be called when a given event is detected:</p> <p><strong>EventManager.hpp</strong></p> <pre><code>#pragma once #include &lt;SFML/Window.hpp&gt; #include &lt;SFML/Graphics.hpp&gt; #include &lt;vector&gt; #include &lt;unordered_map&gt; #include &lt;functional&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;iostream&gt; namespace AGE { enum class EventType { KeyDown = sf::Event::KeyPressed, KeyUp = sf::Event::KeyReleased, MButtonDown = sf::Event::MouseButtonPressed, MButtonUp = sf::Event::MouseButtonReleased, MouseWheel = sf::Event::MouseWheelMoved, WindowResized = sf::Event::Resized, GainedFocus = sf::Event::GainedFocus, LostFocus = sf::Event::LostFocus, MouseEntered = sf::Event::MouseEntered, MouseLeft = sf::Event::MouseLeft, Closed = sf::Event::Closed, TextEntered = sf::Event::TextEntered, Keyboard = sf::Event::Count + 1, Mouse, Joystick }; struct EventInfo { EventInfo() { this-&gt;code = 0; } EventInfo(int code) { this-&gt;code = code; } int code; }; using Events = std::vector&lt;std::pair&lt;EventType, EventInfo&gt;&gt;; struct EventDetails { EventDetails(const std::string&amp; binding_name) { this-&gt;binding_name = binding_name; Clear(); } void Clear() { this-&gt;size = { 0, 0 }; this-&gt;text_entered = { 0 }; this-&gt;mouse = { 0, 0 }; this-&gt;mouse_wheel_delta = { 0 }; this-&gt;key_code = { -1 }; } std::string binding_name; sf::Vector2i size; sf::Uint32 text_entered; sf::Vector2i mouse; int mouse_wheel_delta; int key_code; }; struct Binding { Binding(const std::string&amp; name) : details(name), name(name), event_count(0) {} void BindEvent(EventType type, EventInfo info = EventInfo()) { this-&gt;events.emplace_back(type, info); } EventDetails details; Events events; std::string name; int event_count; }; using Bindings = std::unordered_map&lt;std::string, Binding*&gt;; using Callbacks = std::unordered_map&lt;std::string, std::function&lt;void(EventDetails*)&gt;&gt;; class EventManager { public: EventManager(); ~EventManager(); bool AddBinding(Binding* binding); bool RemoveBinding(const std::string&amp; name); void HandleEvent(sf::Event&amp; event); void Update(); void SetFocus(const bool focus); template &lt;class T&gt; bool AddCallback(const std::string&amp; name, void(T::*function)(EventDetails*), T* class_instance) { auto func = std::bind(function, class_instance, std::placeholders::_1); return this-&gt;callbacks.emplace(name, func).second; } void RemoveCallback(const std::string&amp; name) { this-&gt;callbacks.erase(name); } private: void LoadBindings(); private: Callbacks callbacks; Bindings bindings; bool has_focus; }; } </code></pre> <p><strong>EventManager.cpp</strong></p> <pre><code>#include "EventManager.hpp" namespace AGE { EventManager::EventManager() : has_focus(true) { LoadBindings(); } EventManager::~EventManager() { for (auto&amp; itr : this-&gt;bindings) { delete itr.second; itr.second = nullptr; } } bool EventManager::AddBinding(Binding* binding) { if (this-&gt;bindings.find(binding-&gt;name) != this-&gt;bindings.end()) { return false; } return this-&gt;bindings.emplace(binding-&gt;name, binding).second; } bool EventManager::RemoveBinding(const std::string&amp; name) { auto itr = this-&gt;bindings.find(name); if (itr != this-&gt;bindings.end()) { delete itr-&gt;second; this-&gt;bindings.erase(itr); return true; } return false; } void EventManager::HandleEvent(sf::Event&amp; event) { for (auto&amp; b_itr : this-&gt;bindings) { Binding* binding = b_itr.second; for (auto&amp; e_itr : binding-&gt;events) { EventType event_type = static_cast&lt;EventType&gt;(event.type); if (e_itr.first != event_type) { continue; }; if ((event_type == EventType::KeyDown) || (event_type == EventType::KeyUp)) { if (e_itr.second.code == event.key.code) { ++(binding-&gt;event_count); break; } } else if ((event_type == EventType::MButtonDown) || (event_type == EventType::MButtonUp)) { if (e_itr.second.code == event.mouseButton.button) { binding-&gt;details.mouse.x = event.mouseButton.x; binding-&gt;details.mouse.y = event.mouseButton.y; ++(binding-&gt;event_count); break; } } else { if (event_type == EventType::MouseWheel) { binding-&gt;details.mouse_wheel_delta = event.mouseWheel.delta; } else if (event_type == EventType::WindowResized) { binding-&gt;details.size.x = event.size.width; binding-&gt;details.size.y = event.size.height; } else if (event_type == EventType::TextEntered) { binding-&gt;details.text_entered = event.text.unicode; } ++(binding-&gt;event_count); } } } } void EventManager::Update() { if (!this-&gt;has_focus) { return; }; for (auto&amp; b_itr : this-&gt;bindings) { Binding* binding = b_itr.second; for (auto&amp; e_itr : binding-&gt;events) { switch (e_itr.first) { default: break; case EventType::Keyboard: if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key(e_itr.second.code))) { ++(binding-&gt;event_count); } break; case EventType::Mouse: if (sf::Mouse::isButtonPressed(sf::Mouse::Button(e_itr.second.code))) { ++(binding-&gt;event_count); } break; } if (binding-&gt;events.size() == binding-&gt;event_count) { auto callback_itr = this-&gt;callbacks.find(binding-&gt;name); if (callback_itr != this-&gt;callbacks.end()) { callback_itr-&gt;second(&amp;binding-&gt;details); } } binding-&gt;event_count = 0; binding-&gt;details.Clear(); } } } void EventManager::SetFocus(const bool focus) { this-&gt;has_focus = focus; } void EventManager::LoadBindings() { const std::string deliminator = ":"; std::ifstream bindings; bindings.open("C:/dev/MyVSProjects/C++/Racer/Racer/Racer/src/Keys.cfg"); if (!bindings.is_open()) { std::cerr &lt;&lt; "Failed to open key file!" &lt;&lt; std::endl; return; } std::string line; while (std::getline(bindings, line)) { std::stringstream key_stream(line); std::string callback_name; key_stream &gt;&gt; callback_name; Binding* binding = new Binding(callback_name); while (!key_stream.eof()) { std::string key_value; key_stream &gt;&gt; key_value; int start = 0; int end = key_value.find(deliminator); if (end == std::string::npos) { delete binding; binding = nullptr; break; } EventType type = EventType(std::stoi(key_value.substr(start, end - start))); int code = std::stoi(key_value.substr(end + deliminator.length(), key_value.find(deliminator, end + deliminator.length()))); EventInfo event_info; event_info.code = code; binding-&gt;BindEvent(type, event_info); } if (!AddBinding(binding)) { delete binding; }; } bindings.close(); } } </code></pre> <p>Short example: (Keys.cfg then tells the code to call function "cout" when keybutton 89 (f5) is pressed)</p> <p><strong>Keys.cfg</strong></p> <pre><code>COUT 5:89 </code></pre> <p><strong>Main.cpp</strong></p> <pre><code>#include &lt;SFML/Graphics.hpp&gt; #include "EventManager.hpp" #include &lt;iostream&gt; class Test { public: Test() = default; void COUT(AGE::EventDetails* details) { std::cout &lt;&lt; "Test" &lt;&lt; std::endl; } }; int main() { Test test; sf::RenderWindow window(sf::VideoMode(800, 600), "Test"); AGE::EventManager event_manager; event_manager.AddCallback("COUT", &amp;Test::COUT, &amp;test); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::LostFocus) { event_manager.SetFocus(false); } else if (event.type == sf::Event::GainedFocus) { event_manager.SetFocus(true); } event_manager.HandleEvent(event); } event_manager.Update(); window.clear(); window.display(); } } </code></pre> <p>I would like any tips to improve the code in any way possible. Looking to learn!</p>
[]
[ { "body": "<p>Data modeling wise:</p>\n\n<ul>\n<li>The name <code>EventInfo</code> is ambiguous, especially when there is another class called <code>EventDetails</code>. So I am thinking about how to make their purposes more differentiable. It seems like the purpose of <code>EventInfo</code> and <code>EventType</code> is to create a composite key, which is used in <code>EventManager</code> to fork business logic. I would recommend creating a structure <code>EventClassifier</code> which has both event type and event code as member variables. <code>Binding</code> can have an unordered set of <code>EventClassifier</code>. </li>\n</ul>\n\n<p>Coding style-wise:</p>\n\n<ul>\n<li>prefer to use initialization list rather than assignment operator in the constructor. For instance: </li>\n</ul>\n\n<pre><code>EventInfo(int a_code)\n: code(a_code)\n{}\n</code></pre>\n\n<ul>\n<li>It is redundant to write <code>this-&gt;size</code> in function <code>void Clear()</code>. It can just be <code>size</code>.</li>\n<li>you can use structured bindings when iterating thru a map: <code>for (const auto&amp; [k,v] : bindg-&gt;events)</code>. the code will be more readable as you don't need to write things like <code>iter-&gt;second</code>. </li>\n</ul>\n\n<p>Some other things:</p>\n\n<ul>\n<li>in <code>EventManager</code> destructor, the code should check <code>if(itr.second)</code> before freeing the memory. </li>\n<li><code>EventManager::AddBinding</code> takes a raw pointer of <code>Binding</code>. This is unsafe because 1) EventManager will free the memory in <code>RemoveBinding</code>. so it assumed the address is on heap however there is no guarantee. 2) Caller of <code>EventManager::AddBinding</code> has access to the binding object and could have freed the memory. Then when EventManager tries to access it, the program will segfault. I would recommend changing the interface of <code>AddBinding(Binding* binding)</code> to <code>AddBinding(const std::string&amp; callback_name, EventType type, int event_code)</code>. Then EventManager has the ownership of <code>binding</code> objects exclusively. </li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T23:13:15.353", "Id": "237806", "ParentId": "237532", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T03:59:05.043", "Id": "237532", "Score": "1", "Tags": [ "c++", "sfml" ], "Title": "Event handler for SFML" }
237532
<p>My solution to the LeetCode's <a href="https://leetcode.com/problems/subtree-of-another-tree/" rel="nofollow noreferrer">Subtree of Another Tree</a> passes all the test cases, but the code feels and looks ugly. Would appreciate an advice on how to improve it.</p> <p>The problem:</p> <blockquote> <p>Given two non-empty binary trees <strong>s</strong> and <strong>t</strong>, check whether tree <strong>t</strong> has exactly the same structure and node values with a subtree of <strong>s</strong>. A subtree of <strong>s</strong> is a tree consists of a node in <strong>s</strong> and all of this node's descendants. The tree <strong>s</strong> could also be considered as a subtree of itself.</p> </blockquote> <p>Example:</p> <blockquote> <p>Given tree <strong>s</strong>:</p> <pre><code> 3 / \ 4 5 / \ 1 2 </code></pre> <p>Given tree <strong>t</strong>:</p> <pre><code> 4 / \ 1 2 </code></pre> <p>Return <strong>true</strong>, because <strong>t</strong> has the same structure and node values with a subtree of <strong>s</strong>.</p> </blockquote> <p>My solution:</p> <pre><code>class Solution { private: bool isSame(TreeNode* root_s, TreeNode* t) { if (!root_s &amp;&amp; !t) return true; if (root_s &amp;&amp; !t) return false; if (!root_s &amp;&amp; t) return false; if (root_s-&gt;val != t-&gt;val) return false; return isSame(root_s-&gt;left, t-&gt;left) &amp;&amp; isSame(root_s-&gt;right, t-&gt;right); } void preorder (TreeNode* s, TreeNode* t, bool&amp; is_subtree) { if (!s) return; if (s-&gt;val == t-&gt;val) { if (isSame(t,s)) { is_subtree = true; return; } } preorder (s-&gt;left, t, is_subtree); preorder (s-&gt;right, t, is_subtree); } public: bool isSubtree(TreeNode* s, TreeNode* t) { bool is_subtree = false; preorder (s, t, is_subtree); return is_subtree; } }; </code></pre> <p>For context, here's the definition of <code>TreeNode</code> given by LeetCode:</p> <pre><code>struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; </code></pre>
[]
[ { "body": "<p>Your code doesn't look that ugly! Here are some suggestions to make it better. Note that LeetCode makes significantly more mistakes than you when it comes to code quality; I have listed the suggestions for LeetCode-provided stuff too, so that you don't make the same mistakes when you are writing real code &mdash; you don't have to force LeetCode to accept them (i.e., some of them can be compromised for the purpose of passing their tests).</p>\n\n<h1>General design</h1>\n\n<p>The <code>Solution</code> class is very Java-style AFAIK, but it is not idiomatic in C++. It should be replaced by a namespace, or removed altogether. In C++, it is preferred to create a separate <code>Tree</code> class for the binary trees, instead of operating directly on the nodes. Also, the value type should be a template parameter for reusability.</p>\n\n<h1>Naming</h1>\n\n<p>In C++, functions and variables are generally named in <code>snake_case</code>, with <code>CamelCase</code> names reserved for classes.</p>\n\n<p>The name of the function is misleading &mdash; to me, <code>isSubtree(s, t)</code> means \"<code>s</code> is a subtree of <code>t</code>,\" rather than the reverse. <code>contains_subtree</code> may be better. The parameters <code>s</code> and <code>t</code> are also non-descriptive and thus unreadable; I recommend <code>tree</code> and <code>subtree</code>.</p>\n\n<p>The parameters to <code>isSame</code> (or maybe just <code>same</code>), on the other hand, can be named as simply as <code>tree_a</code> and <code>tree_b</code>, because the semantics is unambiguous.</p>\n\n<h1>Logic</h1>\n\n<p>(Note: the code snippets presented are intended to help you understand the review. They are not tested; in other words, they and may contain mistakes and are not guaranteed to work.)</p>\n\n<p>The logic of <code>same</code> can be simplified:</p>\n\n<ul>\n<li><p>if both arguments are non-null, then they are identical if and only if</p>\n\n<ul>\n<li><p>their values are equal; and</p></li>\n<li><p>their left subtrees are identical; and</p></li>\n<li><p>their right subtrees are identical;</p></li>\n</ul></li>\n<li><p>otherwise, they are identical if and only if they are both null.</p></li>\n</ul>\n\n\n\n<pre><code>bool same(TreeNode* tree_a, TreeNode* tree_b)\n{\n if (tree_a &amp;&amp; tree_b) {\n return tree_a-&gt;val == tree_b-&gt;val\n &amp;&amp; same(tree_a-&gt;left, tree_b-&gt;left)\n &amp;&amp; same(tree_a-&gt;right, tree_b-&gt;right);\n } else {\n return !tree_a &amp;&amp; !tree_b;\n }\n}\n</code></pre>\n\n<p>This presents your logic in a way that is (hopefully) more readable.</p>\n\n<p>Similarly,</p>\n\n<ul>\n<li><p>if <code>tree</code> is non-null, then <code>tree</code> contains <code>subtree</code> if and only if</p>\n\n<ul>\n<li><p><code>same(tree, subtree)</code>; or</p></li>\n<li><p><code>tree-&gt;left</code> contains <code>subtree</code>; or</p></li>\n<li><p><code>tree-&gt;right</code> contains <code>subtree</code>;</p></li>\n</ul></li>\n<li><p>otherwise, <code>tree</code> contains <code>subtree</code> if and only if <code>subtree</code> is null as well.</p></li>\n</ul>\n\n\n\n<pre><code>bool contains_subtree(TreeNode* tree, TreeNode* subtree)\n{\n if (tree) {\n return same(tree, subtree)\n || contains_subtree(tree-&gt;left, subtree)\n || contains_subtree(tree-&gt;right, subtree);\n } else {\n return !subtree;\n }\n}\n</code></pre>\n\n<p>This refactoring eliminates the unnatural non-local control flow (i.e., writing to the <code>bool&amp;</code> argument instead of using the return value). It also ensures that the function returns as soon as a match is found.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T18:07:56.487", "Id": "465917", "Score": "0", "body": "Thank you, this is very helpful!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T11:00:57.620", "Id": "237558", "ParentId": "237535", "Score": "2" } } ]
{ "AcceptedAnswerId": "237558", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T04:47:05.933", "Id": "237535", "Score": "3", "Tags": [ "c++", "binary-tree" ], "Title": "Leetcode: Subtree of Another Tree" }
237535
<p>Is the code below safe to create unique ids for objects?</p> <p>I will create new yoga classes and need to have a unique id for each class. I made this small piece of code to generate the id numbers.</p> <p>Regarding specifically the <code>uniqueIdCreatorHandler</code> <code>method</code>, would this solution incur in bad performance, or is it just far from elegant?</p> <p>what would you say?</p> <p>CodeSandBox <a href="https://codesandbox.io/embed/boring-cori-xeq2m?fontsize=14&amp;hidenavigation=1&amp;theme=dark" rel="nofollow noreferrer">here</a></p> <p>The code is also presented as per below:</p> <pre><code>import React from "react"; export default class App extends React.Component { state = { id: "", ids: [{ id: 7 }, { id: 14 }] }; uniqueIdCreatorHandler = () =&gt; { let ids = [...this.state.ids]; let highestId = 0; if (ids.length &gt; 0) { highestId = ids .map(value =&gt; { return value.id; }) .reduce((a, b) =&gt; { return Math.max(a, b); }); } let newId = highestId + 1; ids.push({ id: newId }); this.setState({ ids: ids }); }; idDeleterHanlder = currIndex =&gt; { let ids = this.state.ids; ids.splice(currIndex, 1); this.setState({ ids: ids }); }; render() { let ids = this.state.ids.map((id, index) =&gt; { return ( &lt;p onClick={() =&gt; this.idDeleterHanlder(index)} key={id.id}&gt; id:{id.id} &lt;/p&gt; ); }); return ( &lt;div className="App"&gt; &lt;button onClick={this.uniqueIdCreatorHandler}&gt;Push new id&lt;/button&gt; &lt;p&gt;all ids below:&lt;/p&gt; {ids} &lt;/div&gt; ); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T13:54:50.190", "Id": "465875", "Score": "1", "body": "If you delete the last index, and push a new one, it will re-use the same index. I would just keep the last created index as part of the state. The code will be much more elegant." } ]
[ { "body": "<p>I've noticed you have a common bug that often occurs in Javascript code called a <strong>race condition</strong>.</p>\n\n<p>If <code>uniqueIdCreatorHandler</code> is called again before a previous call finishes there is a race condition created because <code>state.ids</code> is replaced at the end of the call. </p>\n\n<p>If both calls happen at the same time they each generate a unique copy of the original <code>state.ids</code> then overwrite state <code>this.setState({ ids: ids });</code>. This causes the first change to <code>state.ids</code> to be forgotten.</p>\n\n<p><strong>This is a direct result caused by replacing state. <code>this.setState({ ids: ids });</code></strong></p>\n\n<p>As others have recommend I would simply keep a increment in state for new ids.</p>\n\n<p><em>Note: you can easily demonstrate this in your code by adding and calling this method</em></p>\n\n<pre><code>double = () =&gt; {\n this.uniqueIdCreatorHandler()\n this.uniqueIdCreatorHandler()\n}\n</code></pre>\n\n<p><em>Other comments</em>\nThere are small improvements you could make to your code like spreading the mapped ids into Math.max.</p>\n\n<p>I wouldn't worry too much about Javascript performance, focus on readability. Make variable names more verbose and add doc blocks to methods.</p>\n\n<p>One thing I like to see (which you have done) is the embrace of array methods. Although they may not be necessary here they are a strong indicator of comprehension.</p>\n\n<p>Keep it up!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T17:46:57.187", "Id": "465912", "Score": "0", "body": "Thanks so much for shedding some light into this humble piece of code. Regarding the asynchronous nature of ```Js``` I guess that I should somehow implement ```prevState``` ```arg``` once I set my state, correct? like: ```this.setState(prevState => ({id: prevState...do something})```" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T19:19:21.237", "Id": "465928", "Score": "0", "body": "For your use case you \"shouldn't\" run into any situations where pushing to the ids doesn't work. I would say it's something you should be aware of as a potential problem. From what I understand this is because React batches updates. So you would want to merge all of the changes into a single `setState()` or use Promises. *but that is probably over engineering at this point*" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T16:02:55.250", "Id": "237570", "ParentId": "237536", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T04:53:00.607", "Id": "237536", "Score": "3", "Tags": [ "javascript", "react.js" ], "Title": "Safe way of creating unique IDs" }
237536
<p>So I have a method that, after validation, generates a random password based on the length and characters provided. The UI uses check boxes to select using between lowercase and/or uppercase letters, numbers and special characters to populate the characters parameter. as well as the length of the password and the spacing between each character used (I.E. if character spacing is set to '10', the letter 'A', for example, can only be used again after another 10 unique characters are used first):</p> <p><a href="https://i.stack.imgur.com/6AyWh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6AyWh.png" alt="enter image description here"></a></p> <p>The Generator Method:</p> <pre><code> private string PasswordGeneration(string characters, int length) { var random = Factory.Random(); //Generates new Random() from Factory class. var availableCharacters = characters; //Preps the available characters with all characters passed. var output = string.Empty; var rule = ValidateRule(characters.Length); //Sets character rule to length of parameter "characters" if the unique character spacing is set higher than the number of available characters to use. for (var position = 0; position &lt; length; position++) //loop until we've met the password's desired length. { if (rule != 0 &amp;&amp; (characters.Length - availableCharacters.Length == rule)) //if a character rule is set &amp; if we've met the criteria of the number of unique characters asked for... { availableCharacters = characters.Where(c =&gt; !output.Substring((position - rule) + 1, rule - 1).Contains(c)).Aggregate(availableCharacters, (current, c) =&gt; current + (current.Contains(c) ? string.Empty : c.ToString())); //...we add back all characters for usage other than the last n characters used dictated by the unique character rule. } var character = availableCharacters[random.Next(availableCharacters.Length)]; //Grabs a random character from availableCharacters. availableCharacters = rule == 0 ? availableCharacters : availableCharacters.Replace(character.ToString(), string.Empty); //If a character rule is set, we remove the currently used character from availableCharacters. output += character; //Append "character" to output. } return output; } </code></pre> <p>The 'ValidateRule()' Method:</p> <pre><code> private int ValidateRule(int length) =&gt; length - _settings.IdenticalSpacing &gt; 0 ? _settings.IdenticalSpacing : length; </code></pre> <p>And for readability with what's happening with the LINQ expression within the if statement:</p> <pre><code>foreach(var c in characters)//...we iterate through the original set of characters... { if(output.Substring((position - rule) + 1, rule -1).Contains(c) == false)//...and check to see if the a specific range contains each character. If the range doesn't contain the current character... { foreach(var availableCharacter in availableCharacters)//...we iterate through our available characters to see if it doesn't already contains the current character... { if(!Equals(availableCharacter, c)) { availableCharacters += c; //...if not, we make the character available for use again. } } } } </code></pre> <p>As stated before, the characters and password length parameters are all validated before being passed to PasswordGeneration(), so I didn't add any null checking or checks for bad inputs other than for the character spacing rule. While everything works perfectly fine with no errors, I feel as if the code looks messy and of course a bit hard to read. I can't help but think there's a much more simple approach without a bunch of loops and conditions or long LINQ expressions. However, I would love to hear some feedback on what you all think and of course, how I can improve this.</p>
[]
[ { "body": "<p>Remove unnecessary comments:</p>\n\n<pre><code>var random = Factory.Random(); //Generates new Random() from Factory class.\n</code></pre>\n\n<p>It's obvious if you read the code.</p>\n\n<p>It's ok to break those lines</p>\n\n<pre><code>availableCharacters = characters\n .Where(c =&gt; !output.Substring((position - rule) + 1, rule - 1).Contains(c))\n .Aggregate(availableCharacters, \n (current, c) =&gt; (current.Contains(c) \n ? current \n : current + c.ToString()));\n</code></pre>\n\n<p>Makes it a bit more readable. But still all these +1 -1 does not look very bug safe.</p>\n\n<p>Here's my approach:</p>\n\n<pre><code>private string PasswordGeneration(string characters, int length, int characterSpacing)\n{\n var random = new Random();\n var randomList = new List&lt;int&gt;();\n var spacing = Math.Min(characterSpacing, characters.Length);\n // Generate indexes\n while(randomList.Count &lt; length) {\n var num = random.Next(0, characters.Length);\n var numNotInUse = randomList.LastIndexOf(num) == -1;\n var spacingOk = randomList.LastIndexOf(num) &lt; (randomList.Count - spacing);\n if (numNotInUse || spacingOk ) {\n randomList.Add(num);\n }\n }\n // Set password from indexes\n var password = string.Empty;\n randomList.ForEach(idx =&gt; password += characters.ElementAt(idx));\n return password;\n}\n</code></pre>\n\n<p>Simple is usually better. At least more readable :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T00:35:33.653", "Id": "465968", "Score": "1", "body": "It's funny, I was actually considering using an index based list before posting here, but got so hung up on the if's being a necessity, that I just couldn't grasp the concept. Very nice execution, simple and clean!\n\nOne thing I should point out though that while the Math.Min() works, it will hang if the character spacing and password length are set higher than the number available characters to use. However, that shows that it's another input to be validated prior to usage." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T07:07:15.107", "Id": "465993", "Score": "0", "body": "Yep `characters.Length - 1` works better. But it ought to throw an exception as it wont work as predicted. I'll leave that as an exercise ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T09:03:00.500", "Id": "237549", "ParentId": "237537", "Score": "1" } }, { "body": "<p>There are lots of ways to improve this hard-to-read code but all of them are unimportant compared to the fact that this is massively insecure against common attacks. <strong>You are implementing a component of a security system; you need to build a threat model and understand what you are doing</strong>. Implementing a security system is not a beginner task!</p>\n\n<p>An important rule to follow is <strong>never use System.Random for a security purpose</strong>.</p>\n\n<p>A random number generator needs to be <em>genuinely unpredictable</em> for it to be used in a security system that depends on unpredictability. <code>System.Random</code> is not <em>truly random</em>, and nor is it <em>crypto strength pseudo random</em>.</p>\n\n<p>Why does this matter? Because an attacker who knows <em>anything</em> about the system used to generate the passwords can make good guesses about what passwords it will generate, much better than chance. How does the attacker get information about the system? <strong>A generated password leaks information about the state of the system</strong>.</p>\n\n<p>That is, given a collection of passwords generated by this algorithm allows an attacker to determine the internal state of <code>System.Random</code> and then from that they can make good guesses as to all past and future passwords that will be generated. That's bad! The whole point of a randomly-generated password is to make it hard to guess.</p>\n\n<p>Use a crypto-strength PRNG instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T00:43:04.467", "Id": "465969", "Score": "0", "body": "I probably should of added that the Random class is being used merely as a proof of concept. In production code, I would use the RNGCryptoServiceProvider class instead of Random. Regardless, this is a very valid point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T00:47:13.543", "Id": "465970", "Score": "2", "body": "@ChrisP.Bacon: Though I get that, there are two kinds of secure code. There's \"secure code\" and then there is \"Security Code\" -- code that actually implements a security system. My attitude towards Security Code is **get it right at every stage** -- design, prototyping, implementation, testing, documentation and disaster recovery. It is far too easy for stuff from the prototype to accidentally make it into the product, so use best practices from the start." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T14:35:13.383", "Id": "466037", "Score": "0", "body": "@ChrisP.Bacon: In general, you should fix any known problems (even if the fixes reduce clarity or are unneeded for correctness) with your code before posting to CR. The main reason to follow this guideline is that it ensures that reviewers are not duplicating information that you already know; they'll instead spend their time coming up with improvements you did not think of. Also, production-ready code often has better context for reviewers to use. Finally, random people on the internet are going to use the Q&A as a starting point." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T20:20:49.530", "Id": "237583", "ParentId": "237537", "Score": "4" } } ]
{ "AcceptedAnswerId": "237549", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T05:50:53.920", "Id": "237537", "Score": "1", "Tags": [ "c#", "security" ], "Title": "C# Random Password Generation" }
237537
<p>Why am I fighting the compiler? - Wrote this, which works, but I feel like I'm breaking every rule in the book: </p> <pre><code>#[macro_use] extern crate lazy_static; use std::ffi::OsString; use std::path::PathBuf; use std::str::FromStr; use actix_rt; use actix_web::client::Client; use async_std::fs::File; use async_std::prelude::*; use http::uri::Uri; // Result&lt;OsString, (SendRequestError|std::core::convert::Infallible|actix_http::error::PayloadError) #[actix_rt::main] async fn download(uri: &amp;'static str, target_dir: &amp;'static str) -&gt; Result&lt;OsString, ()&gt; { let client = Client::default(); let uri = Uri::from_str(uri).unwrap(); // Create request builder and send request let response = client .get(&amp;uri) .header("User-Agent", "Actix-web") .send() .await; // &lt;- Send http request println!("Response: {:?}", response); let get_host = || uri.host().unwrap().to_owned(); let path = match &amp;uri.path_and_query() { Some(path_and_query) =&gt; { let p = path_and_query.path().to_owned(); if p == "/" { get_host() } else { p } } None =&gt; get_host(), }; let output_pathbuf = PathBuf::from_str(target_dir).unwrap().join(path); let output_file = output_pathbuf.as_os_str(); let mut file = File::create(output_file).await.unwrap(); file.write_all(&amp;response.unwrap().body().await.unwrap()) .await .unwrap(); // file.write_all(b"Hello, world!").await.unwrap(); return Ok(output_file.to_owned()); } #[cfg(test)] mod tests { use std::borrow::Borrow; // use std::env::temp_dir; use std::fs::create_dir_all; use std::path::PathBuf; use std::str::FromStr; use crate::download; fn temp_dir() -&gt; PathBuf { return PathBuf::from_str("/tmp").unwrap(); } lazy_static! { pub static ref TEMP_DIR: PathBuf = temp_dir().join(module_path!()); pub static ref TEMP_DIR_O: Option&lt;&amp;'static str&gt; = TEMP_DIR.to_str(); pub static ref TEMP_DIR_S: &amp;'static str = TEMP_DIR_O.unwrap(); } #[test] fn test_download() { if !TEMP_DIR.exists() { create_dir_all(TEMP_DIR.borrow() as &amp;PathBuf).unwrap(); } //let output_dir = download( "http://www.rust-lang.org", TEMP_DIR_S.borrow() as &amp;'static str, ) .unwrap(); //assert_eq!(output_dir, "foo") } } </code></pre> <p>Remarks:</p> <ol> <li>I understand that <code>unwrap()</code> is frowned upon, and should be replaced by error percolation (<code>?</code> sugar) and handled at the topmost level (that makes sense). Replacing the unwraps, and now it can return any of <code>SendRequestError|std::core::convert::Infallible|actix_http::error::PayloadError</code>. Should I <code>Box</code>/<code>dyn</code> a <code>std::Error</code>, create a big <code>failure</code> <code>enum</code>, or something cleaner?</li> <li>Not so happy with the types. I tried working with <code>AsRef&lt;PathBuf&gt;</code>, <code>Into&lt;Uri&gt;</code>, and variants thereof. Clearly that doesn't work.</li> <li>How do I get the <code>Result</code>?</li> <li>This is the first step in a multi-URL downloader, but I am worried about efficiency. Do I setup some sort of executor/reactor system atop async/await concepts?</li> </ol>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T06:49:12.840", "Id": "237539", "Score": "3", "Tags": [ "error-handling", "asynchronous", "rust", "http", "async-await" ], "Title": "HTTP download function in Rust (async/await)" }
237539
<p>Given the models below:</p> <pre><code>class Structure(Model): ... class StructureComponent(Model): ... structure = ForeignKey(Structure) parent_component = ForeignKey('self', null=True, ...) </code></pre> <p>Developer should synchronize with the database a list of trees:</p> <p>The sample of request data:</p> <pre><code>{ 'trees': [ { 'id': 1, 'name': 'root1', 'children': [ { 'id': null, # new child component, should be created as a child of component with id 1 'name': 'root1.1', 'children': [], }, ], }, { 'id': null, # new root component, should be created 'name': 'root2', 'children': [], }, # other components that are in the database but not listed here (in the request payload) should be deleted ], } </code></pre> <p>And this is the serializer to process the payload and sync with the database.</p> <pre><code>class StructureComponentTreeListSerializer(serializers.Serializer): trees = StructureComponentTreeSerializer(many=True) def __init__(self, *args, **kwargs): super(StructureComponentTreeListSerializer, self).__init__(*args, **kwargs) self.structure = self.context['structure'] self.component_type = self.context['component_type'] # create filtered queryset for further use self.filtered_queryset = ( StructureComponent .objects .filter( structure=self.structure, type=self.component_type, ) ) # queue to traverse trees using BST algorithm self.queue = deque() # list of components that should be updated(keys are levels in tree) self.updates = defaultdict(list) # list of components that should be created(keys are levels in tree) self.creates = defaultdict(list) # collect ids of final components and remove the rest self.exclude_pks = [] def save(self, validated_data): trees = validated_data['trees'] # queue root nodes for idx, tree in enumerate(trees): # assign unique id for getting matched as a parent in child nodes tree['_uuid'] = uuid.uuid4().hex # idx will be used to set the order_by field self.queue.append([tree, idx, 0, None]) self.traverse(*self.queue.popleft()) def traverse(self, node, order_by, level=0, parent=None): """ BST traverse :param node: dictionary with information about component id: None or int name: str _uuid: unique id :param order_by: the number used in ordering :param level: current level of tree :param parent: dictionary containing id of the parent component if any """ entity = StructureComponent( pk=node.get('id'), name=node.get('name', ''), structure=self.structure, type=self.component_type, order_by=order_by, ) entity._uuid = node.get('_uuid') if parent: entity.parent_component_id = parent.get('id') if node.get('id'): # append to updates list because we have the id self.updates[level].append(entity) # collect pks of remaining components self.exclude_pks.append(entity.pk) else: # append to creates list because we don't have the id self.creates[level].append(entity) if level + 1 &lt; self.max_depth: # we don't care about nodes below max_depth level for idx, child in enumerate(node.get('children', [])): # queue children and assign unique id for getting matched as a parent in child nodes child['_uuid'] = uuid.uuid4().hex # idx will be used to set the order_by field self.queue.append([child, idx, level + 1, node]) if len(self.queue): # get the next from queue(keeping it there) to detect level change _, _, next_level, _ = self.queue[0] if next_level != level: # sync db if we are moving down on level # before that we should have all primary keys of parents to be able to connect with children self.sync_db(level) # traverse over next from queue self.traverse(*self.queue.popleft()) else: # we still have non synchronized items(lowest levels of trees) so we should sync them too self.sync_db(level) # now we have all pks to exclude so we can delete components that are not exist in final trees self.clean_db() def sync_db(self, level): # update name and order_by fields based on level self.filtered_queryset.bulk_update((cmp for cmp in self.updates[level]), ['name', 'order_by']) # create new components components = StructureComponent.objects.bulk_create(self.creates[level]) for cmp, node in zip(components, self.creates[level]): # collect pks of remaining components self.exclude_pks.append(cmp.pk) for args in self.queue: # update parents in queue which are created during last sync if args[-1].get('_uuid') == node._uuid: # attach pk of newly created parent to child args[-1]['id'] = cmp.pk def clean_db(self): """ Remove all components except final ones that are collected in exclude_pks attribute. """ self.filtered_queryset.exclude(pk__in=self.exclude_pks).delete() </code></pre> <p>This serializer is a bit complicated compared with others in the project. And colleague asked if the author can make it more readable and even optimal if it's possible.</p> <p>Another case which will help you to understand it better:</p> <pre><code>{ 'trees': [ { 'id': 2, 'name': 'root2', 'children': [], }, ], } </code></pre> <p>The client will send this data as a second payload and the root component in the previous payload should be removed.</p>
[]
[ { "body": "<p>My suggestion is to broke the dict in smaller pieces something like:</p>\n\n<pre><code>node_root1_1 = { 'id': None, 'name': 'root1.1', 'children' : [] }\nnode_root1 = { 'id': 1, 'name': 'root1', 'children' : [ node_root1_1 ] }\nnode_root2 = { 'id': None, 'name': 'root2', 'children' : [] }\n\n'trees': [ node_root1, \n node_root2 ]\n</code></pre>\n\n<p>Bear in mind that work with this types of structs, nested dicts, lists and other types sometimes can be tricky and depends on the reader, hope you get the idea.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T09:22:32.237", "Id": "466002", "Score": "0", "body": "Sorry, but I didn't get it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T08:43:17.677", "Id": "237546", "ParentId": "237541", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T07:11:32.317", "Id": "237541", "Score": "1", "Tags": [ "python", "algorithm", "tree", "django" ], "Title": "Synchronize list of trees with DB using DRF serializer" }
237541
<p>I want to improve quality of this symfony rest endpoint (solid principle, Kiss, best practice...) Can you review my code please?</p> <p>Symfony controllController function that return json list of product</p> <pre><code>/** * @Route("/api/products/my_list/{number}", methods={"GET"}) * @param Security $security * @param BeamyAPI $beamyAPI * @param Request $request * @param ProductService $productService * @return string */ public function myList( Security $security, BeamyAPI $beamyAPI, Request $request, ProductService $productService, int $number = 20 ) { $productListUser = $this-&gt;em-&gt;getRepository(ProductAdmin::class) -&gt;findProductsUser( $security-&gt;getUser(), $number ); return new JsonResponse( $productListUser, Response::HTTP_OK ); } </code></pre> <p>Trait to format array response</p> <pre><code>Trait ArrayFormat { /** * format array for user product endpoint * * @param array $data * @return array */ public function formatUserProduct($product) : array { return [ 'id' =&gt; $product['id'], 'name' =&gt; $product['name'], 'notifications' =&gt; '', 'logo' =&gt; [ 'contentUrl' =&gt; $product['logo']['contentUrl'] ] ]; } } </code></pre> <p>Repository permit to get array of products list for one user </p> <pre><code>/** * get product list of user * * @param UserInterface $user * @param integer $number * @return array|null */ public function findProductsUser(UserInterface $user, int $number) :?array { $listProductUser = $this-&gt;em-&gt;getRepository(ProductAdmin::class)-&gt;findBy( ['user' =&gt; $user], ['product' =&gt; 'ASC'], $number ); $res = []; array_walk($listProductUser, function(&amp;$productUser){ $product = $this-&gt;productService-&gt;getProductInfo($productUser-&gt;getProduct()); $productUser = ArrayFormat::formatUserProduct($product); }); return $listProductUser; } </code></pre> <p>Thanks</p>
[]
[ { "body": "<pre><code>$productListUser = $this-&gt;em-&gt;getRepository(ProductAdmin::class)\n -&gt;findProductsUser(...\n</code></pre>\n\n<p>Than</p>\n\n<pre><code>public function findProductsUser(UserInterface $user, int $number) :?array\n {\n\n $listProductUser = $this-&gt;em-&gt;getRepository(ProductAdmin::class)-&gt;findBy(...\n</code></pre>\n\n<p>seems to me that <code>findProductsUser</code> is method of whatever is returned by <code>$em-&gt;getRepository(ProductAdmin::class)</code> why is that method retrieving itself from entity manager? Shouldn't it be just <code>$this-&gt;findBy(...</code>?</p>\n\n<p>Further, the responsibility of formatting the entity should not be done by the repository. You need to either wrap the repository with the formatter into another class, or do it in the controller. Also there is no reason why the formatter must be a trait. Make it a service and inject it to the entire controller through contructor if all methods of the controller need it, or have it injected in an action method, like you do with <code>Security</code>, <code>BeamAPI</code>, etc...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T08:41:10.413", "Id": "237545", "ParentId": "237542", "Score": "0" } } ]
{ "AcceptedAnswerId": "237545", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T07:27:27.677", "Id": "237542", "Score": "1", "Tags": [ "php", "rest", "doctrine", "symfony4" ], "Title": "Symfony rest endpoint for get a number products of one user" }
237542
<p>I'm trying to learn Javascript and I've set up a bill calculator. Most of the lines in the code are to deal with rounding. It has four main components:</p> <ol> <li>Allows you to enter the bill amount and tip percentage.</li> <li>Calculates the total bill divided by the number of guests.</li> <li>Calculates the total tip.</li> <li>Splits the bill by the number of guests.</li> </ol> <pre><code>billAmount = 134.93 const enterTipPercent = 10 const guests = ["Person1", "Person2", "Person3", "Person4"] const noOfGuests = guests.length; console.log('Chosen tip: ' + enterTipPercent + '%') function splitBill() { var split = billAmount / noOfGuests; var rounding = split.toFixed(2); var elseIf = rounding * noOfGuests; if (rounding == billAmount/noOfGuests) { console.log('Each person must pay: £' + rounding +' with no remainder'); } else if (elseIf * noOfGuests &gt; billAmount){ var roundDown = Math.floor(split*100) /100; var remainingAmount = billAmount-roundDown*noOfGuests; var roundedRemainder = remainingAmount.toFixed(2); console.log('Each person must pay: £' + roundDown +' with £' + roundedRemainder + ' remaining'); } } function calculateTip() { var tip = billAmount/100*enterTipPercent; var tipRound = tip.toFixed(2); return tipRound; } function splitTip() { if (calculateTip() * 10 == billAmount) { var tipShare = calculateTip(); var tipDivide = tipShare/noOfGuests; var tipRound = tipDivide.toFixed(2); console.log('Each person must tip: £' + tipRound); } else { var tipShare = calculateTip(); var tipDivide = tipShare/noOfGuests; var tipRound = Math.floor(tipDivide *100) /100; var tipremainder = calculateTip()-tipRound*noOfGuests; var tipRoundRemainder = tipremainder.toFixed(2); console.log('Each person must tip: £' + tipRound + ' with £' + tipRoundRemainder + ' remaining'); } } splitBill(); console.log('total tip £' + calculateTip()); splitTip();const </code></pre> <p>The code I've written works fine, but I'm sure this isn't the best, or most efficient way I could have done it. Does anyone have any advice on how I can improve?</p>
[]
[ { "body": "<p>Short review;</p>\n\n<ul>\n<li>Use a beautifier, the code is not properly indented or spaced out</li>\n<li>You use <code>var</code>, try to use <code>const</code> and <code>let</code></li>\n<li>The code already assigned <code>billAmount / noOfGuests</code> to <code>split</code>, so you can compare <code>rounding</code> and <code>split</code></li>\n<li>£ should probably be a single string constant</li>\n<li><code>elseIf</code> is a terrible variable name</li>\n<li><code>elseIf</code> is already multiplied by <code>noOfGuests</code>, why would you multiply it again in the <code>if</code> statement?</li>\n<li><code>billAmount</code> and <code>noOfGuests</code> should be parameters of <code>splitBill</code> and <code>splitTip</code></li>\n<li><code>tipremainder</code> should be <code>tipRemainder</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T18:07:27.817", "Id": "465916", "Score": "2", "body": "Emphasis on: Stop Using Var." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T13:04:31.347", "Id": "237562", "ParentId": "237543", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T08:19:39.923", "Id": "237543", "Score": "2", "Tags": [ "javascript" ], "Title": "Split the restaurant bill" }
237543
<p>I have done a clustering algorithm and represented the results in a pie chart as shown below. </p> <pre><code>fig, ax = plt.subplots(figsize=(20, 10), subplot_kw=dict(aspect="equal")) contents = [] for k,v in clusters.items(): indi= str(len(clusters[k])) + " users " + "Cluster_"+ str(k) contents.append(indi) #contents = ['23 users Cluster_0', '21 users Cluster_1'] data = [float(x.split()[0]) for x in contents] Cluster= [x.split()[-1] for x in contents] def func(pct, allvals): absolute = int(pct/100.*np.sum(allvals)) return "{:.0f}%\n({:d} users)".format(pct, absolute) wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data), textprops=dict(color="w")) ax.legend(wedges, Cluster, title="CLuster", loc="center left", bbox_to_anchor=(1, 0, 0.5, 1)) plt.setp(autotexts, size=10, weight="bold") ax.set_title("Distribution of users: A pie chart") </code></pre> <p>Even though the users are <strong>23 and 21</strong> in each cluster, the piechart shows <strong>22 and 20</strong>. This is due to the conversion to int and some float values are cut off in the function <strong>def func()</strong>. </p> <p><a href="https://i.stack.imgur.com/RM78s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RM78s.png" alt="enter image description here"></a></p> <p>But, to fix this I wrote the below code and it works: </p> <pre><code>def func(percentage, allvals): absolute = int(np.sum(allvals)) newV = (percentage/100)*absolute roundnewV = round(newV) intnewV = int(roundnewV) return "{:.0f}%\n({:d} users)".format(percentage, intnewV) </code></pre> <p>Is this a good way to save the original form of integer and not lose out any value?</p>
[]
[ { "body": "<p>You got yourself in trouble by using <code>plt.pie</code>, and especially the keyword argument <code>autopct</code>, beyond its intended use. </p>\n\n<p>The basic idea of the pie chart is to have the wedge labels outside the pie and perhaps percentages inside.</p>\n\n<p>You wanted the wedge label and percentage inside the pie and manipulated the <code>autopct</code> keyword with a function to achieve this. This involved cumbersome calculations from percentages to values you already know.</p>\n\n<p>Another solution could be to use the more simple <code>labels</code> keyword argument and change the resulting <code>texts</code> properties to be inside the pie instead outside, see code changes below:</p>\n\n<pre><code>contents = ['23 users Cluster_0', '21 users Cluster_1']\n\ndata = [int(x.split()[0]) for x in contents]\n\ndef pie_chart_labels(data):\n total = int(np.sum(data))\n percentages = [100.0 * x / total for x in data]\n fmt_str = \"{:.0f}%\\n({:d} users)\"\n return [fmt_str.format(p,i) for p,i in zip(percentages, data)]\n\nwedges, texts, = ax.pie(data, labels=pie_chart_labels(data))\n\n# shrink label positions to be inside the pie\nfor t in texts:\n x,y = t.get_position()\n t.set_x(0.5 * x)\n t.set_y(0.5 * y)\n\nplt.setp(texts, size=10, weight=\"bold\", color=\"w\", ha='center')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T10:55:35.797", "Id": "466009", "Score": "0", "body": "Thank you very much. Really appreciate for your time and effort. This piece of code looks more efficient. I tried to correct it multiple ways using `autopct ` but somehow ended up giving bad results." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T20:33:54.143", "Id": "237585", "ParentId": "237547", "Score": "2" } } ]
{ "AcceptedAnswerId": "237585", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T08:43:50.293", "Id": "237547", "Score": "3", "Tags": [ "python", "python-3.x", "integer", "floating-point", "matplotlib" ], "Title": "Plotting the integer values in text format in matplotlib piechart" }
237547
<p>So I'm writing a game emulator and would like some advice after finishing the networking. It is designed to accept multiple connections, and process messages from all of them.</p> <p>Here is just a brief introduction to the packets and how they are structured. <code>[lengthOfString:short][stringEncodedInUtf8:Byte[]]</code></p> <p>Let's start with the NetworkHandler - this class is responsible for accepting new connections and storing them in the collection.</p> <pre><code>public class NetworkHandler : IDisposable { private readonly TcpListener _listener; private readonly IList&lt;NetworkClient&gt; _clients; private readonly ClientPacketHandler _packetHandler; public NetworkHandler(TcpListener listener, IList&lt;NetworkClient&gt; clients, ClientPacketHandler packetHandler) { _listener = listener; _clients = clients; _packetHandler = packetHandler; } public void StartListener() { _listener.Start(); } public async Task ListenAsync() { while (true) { var tcpClient = await _listener.AcceptTcpClientAsync(); var networkClient = new NetworkClient(tcpClient, _packetHandler); _clients.Add(networkClient); networkClient.StartReceiving(); } } public void Dispose() { foreach (var client in _clients) { client.Dispose(); } _listener.Stop(); } } </code></pre> <p>Then we have the NetworkClient, I made this so NetworkHandler could stay small and to follow SRP - This class handles incoming data from the individual connection (client).</p> <pre><code>public class NetworkClient { private readonly TcpClient _tcpClient; private readonly NetworkStream _networkStream; private readonly ClientPacketHandler _packetHandler; public NetworkClient(TcpClient tcpClient, ClientPacketHandler packetHandler) { _tcpClient = tcpClient; _networkStream = tcpClient.GetStream(); _packetHandler = packetHandler; } public void StartReceiving() { Task.Run(ProcessDataAsync); } private async Task ProcessDataAsync() { while (true) { using var br = new BinaryReader(new MemoryStream(await GetBinaryDataAsync())); var messageLength = BinaryPrimitives.ReadInt32BigEndian(br.ReadBytes(4)); var packetData = br.ReadBytes(messageLength); using var br2 = new BinaryReader(new MemoryStream(packetData)); var packetId = BinaryPrimitives.ReadInt16BigEndian(br2.ReadBytes(2)); if (packetId == 26979) { await WriteToStreamAsync(Encoding.Default.GetBytes("&lt;?xml version=\"1.0\"?&gt;\r\n&lt;!DOCTYPE cross-domain-policy SYSTEM \"/xml/dtds/cross-domain-policy.dtd\"&gt;\r\n&lt;cross-domain-policy&gt;\r\n&lt;policy-file-request/&gt;&lt;allow-access-from domain=\"*\" to-ports=\"*\" /&gt;\r\n&lt;/cross-domain-policy&gt;\0)")); } else { if (!_packetHandler.TryGetPacket(packetId, out var packet)) { Console.WriteLine("Unhandled packet: " + packetId); return; } packet.Process(this, new ClientPacketReader(packetData)); } } } private async Task&lt;byte[]&gt; GetBinaryDataAsync() { var buffer = new byte[2048]; var memoryStream = new MemoryStream(); var bytesRead = await _networkStream.ReadAsync(buffer, 0, buffer.Length); while (bytesRead &gt; 0) { memoryStream.Write(buffer, 0, buffer.Length); bytesRead = await memoryStream.ReadAsync(buffer, 0, buffer.Length); } return memoryStream.ToArray(); } private async Task WriteToStreamAsync(byte[] data) { await _networkStream.WriteAsync(data, 0, data.Length); } public void Dispose() { _tcpClient.Dispose(); } } </code></pre> <p>ClientPacketHandler - fairly straight forward</p> <pre><code>public class ClientPacketHandler { private readonly Dictionary&lt;int, IClientPacket&gt; _packets; public ClientPacketHandler(Dictionary&lt;int, IClientPacket&gt; packets) { _packets = packets; } public bool TryGetPacket(int packetId, out IClientPacket packet) { return _packets.TryGetValue(packetId, out packet); } } </code></pre> <p>ClientPackerReader - this will be used to read data from the packet. I feel like this class could be improved by using some built in helper type?</p> <pre><code>public class ClientPacketReader { private readonly byte[] _packetData; private int _packetPosition; public ClientPacketReader(byte[] packetData) { _packetData = packetData ?? new byte[0]; } public string ReadString() =&gt; Encoding.Default.GetString(ReadFromLength()); private byte[] ReadFromLength() =&gt; ReadBytes(BinaryPrimitives.ReadInt16BigEndian(ReadBytes(2))); private byte[] ReadBytes(int bytes) { var data = new byte[bytes]; for (var i = 0; i &lt; bytes; i++) { data[i] = _packetData[_packetPosition++]; } return data; } } </code></pre> <p>Lastly I want to show you an example packet file</p> <pre><code>public class ExamplePacket : IClientPacket { public void Process(NetworkClient client, ClientPacketReader reader) { Console.WriteLine("Fetch packet data: " + reader.ReadString()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-10T11:43:36.720", "Id": "468044", "Score": "1", "body": "You can always remove your own question using the \"delete\" link under the question. However, please consider that even though this might not be relevant anymore to *you*, it might be relevant to some future reader. So unless there are privacy concerns or similar involved, consider leaving the question (and therefore also the answer) visible." } ]
[ { "body": "<p>I don't have enough reputation to leave a comment, but I highly recommend checking out NexusForever : <a href=\"https://github.com/NexusForever/NexusForever/\" rel=\"nofollow noreferrer\">https://github.com/NexusForever/NexusForever/</a></p>\n\n<p>It is also a game server emulator, and their implementation seems close to yours. It has been a great resource for me, and I hope it can help you too.</p>\n\n<p>I think your packets should only read the incoming data. \nProcessing can be done in a handler, which takes a Packet and a NetworkClient, so that your packets simply read data. The logic is then processed in another class/method. I say this because I see you pass NetworkClient in \"Process\". I have had the same type of system before, and it can become very unmaintainable.</p>\n\n<p>Your packet reader class seems fine, in most emulators I've seen, it is always implemented this way.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T15:09:27.627", "Id": "237703", "ParentId": "237554", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T09:41:16.023", "Id": "237554", "Score": "2", "Tags": [ "c#", "asynchronous", "networking" ], "Title": "Asynchronous TCP network server with a packet system" }
237554
<p>I'm working on a little endian machine and in my program I need to convert 2,3,4,5 or 8 bytes into network order before transmitting them over the network. I've written the following function which basically just reverses the bytes. I just wanted to make sure if it's logic is correct.</p> <pre><code> void convertLittleToBig(const uint8_t* in, uint8_t* out, const uint64_t&amp; sizeInBytes) { for(int i=0;i&lt;sizeInBytes;++i) out[i] = in[sizeInBytes-i-1]; } </code></pre> <p>The function assumes that <strong><code>'out'</code></strong> and <strong><code>'in'</code></strong> will be pointing at <strong><code>'sizeInBytes'</code></strong> memory. If I'm not wrong, I can use the same function to convert from network order into little endian. Basically big endian and little endian, are mirror images of each other in terms of their byte order as per my current understanding.</p> <p>Given below is a sample program:</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdint&gt; #include &lt;iostream&gt; using std::cin; //This function prints the raw bytes in memory. void printBytes(const uint8_t* p, const uint64_t size) { for(int i=0;i&lt;size;++i) printf("\nbyte[%d](%x)",i+1,p[i]); printf("\n"); } void convertLittleToBig(const uint8_t* in, uint8_t* out, const uint64_t&amp; sizeInBytes) { printf("\nCurrent representation\n"); printBytes(in,sizeInBytes); for(int i=0;i&lt;sizeInBytes;++i) out[i] = in[sizeInBytes-i-1]; printf("\nRepresentation after conversion\n"); printBytes(out,sizeInBytes); } int main() { uint64_t little; printf("\nEnter a number that you wish to convert into big endian: "); int64_t inp; cin&gt;&gt;inp; little=inp; uint64_t big; convertLittleToBig((uint8_t*)&amp;little,(uint8_t*)&amp;big,sizeof(big)); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T20:23:17.877", "Id": "465943", "Score": "0", "body": "There are standard libs for this: `htonl => host to network long` https://linux.die.net/man/3/htonl" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T08:44:23.943", "Id": "465999", "Score": "0", "body": "@MartinYork I have to convert 2,3,4,5 or 8 bytes." } ]
[ { "body": "<h1>Includes</h1>\n<p>We have included <code>&lt;iostream&gt;</code> twice, but missed <code>&lt;cstdio&gt;</code>.</p>\n<h1>Misspelt standard library identifiers</h1>\n<p><code>std::printf</code>, <code>std::uint8_t</code> and <code>std::uint64_t</code> are consistently misspelt. You might sometimes get away with this, as your standard library is allowed to add global-namespace versions of those identifiers; since it's not <em>required</em> to do so, you have a portability bug.</p>\n<h1>Use appropriate size type</h1>\n<p><code>std::size_t</code> is the appropriate type to use for the size of an object, rather than <code>std::uint64_t</code> (which could be unnecessarily big, or - theoretically, at least for now - too small).</p>\n<h1>Conversion function shouldn't have side-effects</h1>\n<p>The <code>printf()</code> calls within <code>convertLittleToBig</code> make it unusable in any serious program.</p>\n<h1>Consider a standard algorithm</h1>\n<p>The <code>&lt;algorithm&gt;</code> header provides a very useful <code>std::copy()</code> function we can use if we have a reverse iterator to copy from or to. We can get suitable iterators from <code>std::span</code> views onto the inputs (from C++20 onwards).</p>\n<h1>Avoid raw pointers</h1>\n<p>We could do better, using a template to accept values and return by value, inferring the size from the argument type:</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;span&gt;\n\ntemplate&lt;typename T&gt;\nT convertLittleToBig(const T&amp; val)\n{\n auto in = std::as_bytes(std::span(&amp;val, 1));\n T result;\n auto out = std::as_writable_bytes(std::span(&amp;result, 1));\n std::copy(in.rbegin(), in.rend(), out.begin());\n return result;\n}\n</code></pre>\n<p>That's much simpler - no counting needed, and the caller doesn't need to use <code>sizeof</code> (to work with odd-sized values, they need to be passed as arrays).</p>\n<p>This is how we'd use it in a simple test program:</p>\n<pre><code>#include &lt;cstddef&gt;\n#include &lt;cstdlib&gt;\n#include &lt;iomanip&gt;\n#include &lt;iostream&gt;\n#include &lt;sstream&gt;\n#include &lt;string&gt;\n \nstd::string to_hex(auto const&amp; val)\n{\n std::ostringstream oss;\n oss &lt;&lt; std::hex &lt;&lt; std::setfill('0');\n auto in = std::as_bytes(std::span(&amp;val, 1));\n for (auto c: in) {\n oss &lt;&lt; std::setw(2) &lt;&lt; std::to_integer&lt;unsigned int&gt;(c);\n }\n return oss.str();\n}\n\n// hex-print the value and its reversal\nvoid demo_endian_swap(auto const&amp; val)\n{\n std::cout &lt;&lt; to_hex(val) &lt;&lt; &quot; -&gt; &quot;\n &lt;&lt; to_hex(convertLittleToBig(val)) &lt;&lt; '\\n';\n}\n\n#include &lt;array&gt;\nint main() {\n // Demonstrate a selection of types\n demo_endian_swap(std::uint16_t{0x1234});\n demo_endian_swap(std::uint64_t{0x123456789abcde});\n demo_endian_swap(std::array&lt;unsigned char,5&gt;{1,2,3,4,5});\n //demo_endian_swap(&quot;abc&quot;); // Invalid - can't return an array\n //demo_endian_swap(std::string{&quot;abc&quot;}); // oops - reverses whole structure\n}\n</code></pre>\n<p>Example output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>3412 -&gt; 1234\ndebc9a7856341200 -&gt; 00123456789abcde\n0102030405 -&gt; 0504030201\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T13:48:20.193", "Id": "237565", "ParentId": "237557", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T10:05:10.633", "Id": "237557", "Score": "4", "Tags": [ "c++" ], "Title": "Function to convert little endian bytes into big endian" }
237557
<p>An abstract base class which derives from the <code>ObservableObject</code> (MvvmLight), implementing the <code>INotifyDataErrorInfo</code> interface. </p> <p>The model (exposed via the ViewModel) binds directly to the view, to avoid duplication of properties.</p> <p>A couple of notes:</p> <p>a) I chose the <code>HashSet&lt;string&gt;&gt;</code> to avoid duplicate errors, e.g. "<em>The number of allowed characters has been exceeded.</em>" on every keystroke when <code>UpdateSourceTrigger=PropertyChanged</code>.</p> <p>b) The <code>RaisePropertyChanged</code> of the MvvmLight's <code>ObservableObject</code> has been overridden to validate individual properties. </p> <p>c) The method <code>IsValidated()</code> validates the object and provides visual feedback to the user when e.g. the "Save" button has been pressed.</p> <pre><code>using GalaSoft.MvvmLight; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; namespace WPF.MVVM.UI.Data.Model.Base { public abstract class ValidatedObservableObject : ObservableObject, INotifyDataErrorInfo { private readonly IDictionary&lt;string, HashSet&lt;string&gt;&gt; _errors = new Dictionary&lt;string, HashSet&lt;string&gt;&gt;(); public bool HasErrors { get =&gt; _errors.Count &gt; 0; } public IEnumerable GetErrors(string propertyName) { if (string.IsNullOrEmpty(propertyName) || !_errors.ContainsKey(propertyName)) return null; return _errors[propertyName]; } public bool IsValidated() { var results = new List&lt;ValidationResult&gt;(); var valid = Validator.TryValidateObject(this, new ValidationContext(this), results, true); if (valid) return true; AppendOrUpdateErrors(results); return false; } public override void RaisePropertyChanged(string propertyName = null) { base.RaisePropertyChanged(propertyName); if (!string.IsNullOrEmpty(propertyName)) { ValidateProperty(propertyName); } } private void ValidateProperty(string propertyName) { var results = new List&lt;ValidationResult&gt;(); var valid = Validator.TryValidateProperty(GetType().GetProperty(propertyName)?.GetValue(this), new ValidationContext(this) { MemberName = propertyName }, results); if (valid) { RemoveFromErrors(propertyName); } else { AppendOrUpdateErrors(results); } } private void RemoveFromErrors(string propertyName) { if (string.IsNullOrEmpty(propertyName) || !_errors.ContainsKey(propertyName)) return; _errors.Remove(propertyName); RaiseErrorsChanged(propertyName); } private void AppendOrUpdateErrors(IReadOnlyCollection&lt;ValidationResult&gt; results) { if (results == null) return; foreach (var memberName in results.SelectMany(r =&gt; r.MemberNames).Distinct()) { var memberErrors = new HashSet&lt;string&gt;(results.Where(r =&gt; r.MemberNames.Contains(memberName)).Select(r =&gt; r.ErrorMessage)); if (_errors.ContainsKey(memberName)) { _errors[memberName] = memberErrors; } else { _errors.Add(memberName, memberErrors); } RaiseErrorsChanged(memberName); } } public event EventHandler&lt;DataErrorsChangedEventArgs&gt; ErrorsChanged; private void RaiseErrorsChanged(string propertyName) { ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName)); } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T11:11:54.307", "Id": "237559", "Score": "3", "Tags": [ "c#", "validation", "wpf", "mvvm" ], "Title": "WPF: An implementation of INotifyDataErrorInfo" }
237559
<p>Recently, I've received negative feedback of interview's test. They say that they need somebody with higher technical level, the quality of the task was not good enough.</p> <p>I upload it here, to request your knowledge and teach me how to improve it to improve my development skills around Google Maps and Marker placing.</p> <p>The prove requirements was:</p> <blockquote> <p>Make native call to ****, given a mark (lowerLeftLatLon=38.711046,-9.160096&amp;upperRightLatLon=38.739429,-9.137115) this call returns a list of different resources ( bikes, motorbikes, bus stations, metro stations,...). Once the call has been done, you must draw all the different resources into a GoogleMaps. We do not need anything sofisticate at UX level.</p> <p>What we want to see?</p> <p>Architecture</p> <p>Endpoint call</p> <p>Show makers at the map with Google Maps lib. Identify different resources according color given by companyZoneId</p> <p>Show in a new view the marker information</p> <p>Extra: if user move around map, refresh pois</p> </blockquote> <p>Here is the paste of my main activity:</p> <pre><code>class MapsActivity : AppCompatActivity(), OnMapReadyCallback { private lateinit var mMap: GoogleMap private var disposableCall: Disposable? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_maps) // Obtain the SupportMapFragment and get notified when the map is ready to be used. val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) } /** when map is ready, we can set: * starting bounds * request Pois (MapResources) * set map clicks and infowindow*/ override fun onMapReady(googleMap: GoogleMap) { mMap = googleMap val startBounds = LatLngBounds( LatLng(38.711046, -9.160096), LatLng(38.739429, -9.137115) ) mMap.setOnMapLoadedCallback { mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(startBounds, 17)) } /**EXTRA, unlock to update POIs when user change map bounds, but with requestResource, it can cause stress * it can be optimized with feats like: * - Don't redraw existing POIS * - If zoom out, group nearer POIS into one * - Delete POIS out of view * */ /* mMap.setOnCameraChangeListener { it as CameraPosition requestResources(mMap.projection.visibleRegion.latLngBounds) }*/ mMap.setInfoWindowAdapter( InfoWindowCustom(this) ) mMap.setOnInfoWindowClickListener { Toast.makeText(this, "wi!", Toast.LENGTH_SHORT).show() try { startActivity( ResourceDetailActivity.newInstance(this@MapsActivity, it.snippet) ) } catch (e: Exception) { Log.e("MAP", e.localizedMessage) } } requestResources(startBounds) } /** * Async call(RX) to get resources * if call is in progress (!disposed) we dispose it before create a new call */ private fun requestResources(bounds: LatLngBounds) { disposableCall?.apply { if (!this.isDisposed) dispose() } disposableCall = NetRepo().getMapResources(bounds.northeast, bounds.southwest) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onNext = { listOfResults -&gt; addResourcesFromList(listOfResults) }, onError = { Log.e("DisposeCall", "ERROR: ${it.localizedMessage}") } ) } /** call addMarker function for each item of received list*/ private fun addResourcesFromList(listOfResults: List&lt;MapResource&gt;) { for (item in listOfResults) { if (!existInMap(item)) { addMarker(item) } } } /** returns if item is already present in the markers*/ private fun existInMap(item: MapResource): Boolean { //TODO check if item is present in map, if it's present, it should not be repainted // we can manage this with marker hashmap, if it return the marker requested, it exists in the map return false } /** returns one BitmapDescriptor containing the marker icon tinted as param color*/ private fun getTintedMarker(color: Int): BitmapDescriptor? { val markerBitmap = BitmapFactory.decodeResource( resources, R.drawable.baseline_place_white_24 ) val resultBitmap = Bitmap.createBitmap( markerBitmap, 0, 0, markerBitmap.width - 1, markerBitmap.height - 1 ) val filter: ColorFilter = PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN) val markerPaint = Paint() markerPaint.colorFilter = filter val canvas = Canvas(resultBitmap) canvas.drawBitmap(resultBitmap, 0f, 0f, markerPaint) return BitmapDescriptorFactory.fromBitmap(resultBitmap) } /** returns one color for each different companyZoneId * it passes the value from 3 digits to 6 according: * colorValue = abc * newColorValue = aabbcc * to use it as parseable color * */ private fun colorOfItem(item: MapResource): Int { return item.companyZoneId?.let { var colorString = "#${item.companyZoneId}" colorString = colorString.replace( "#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])".toRegex(), "#$1$1$2$2$3$3" ) Color.parseColor(colorString) } ?: run { 0 } } /** Adds the marker to the map*/ private fun addMarker(item: MapResource) { val coordinates = LatLng(item.lat!!, item.lon!!) mMap.addMarker( MarkerOptions() .icon(getTintedMarker(colorOfItem(item))) .position(coordinates) .infoWindowAnchor(0.5f, -0.1f) .snippet(Gson().toJson(item)) ) } } </code></pre> <p>Also the InfoView:</p> <pre><code>class InfoWindowCustom(var context: Context) : InfoWindowAdapter { var inflater: LayoutInflater? = null override fun getInfoContents(marker: Marker): View? { inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val v = inflater!!.inflate(R.layout.view_mapinfoview, null) val llInfoWindow = v.findViewById(R.id.llInfoWindow) as LinearLayout Gson().fromJson&lt;MapResource&gt;(marker.snippet, MapResource::class.java)?.let { paintData(context, llInfoWindow, it) addOnClickInfo(llInfoWindow) } return v } private fun addOnClickInfo(llInfoWindow: LinearLayout) { val infoText = TextView(context) infoText.text = "Click me for more detail" infoText.setTextColor(Color.BLUE) infoText.setPadding(5, 5, 5, 5) llInfoWindow.addView(infoText) } override fun getInfoWindow(marker: Marker): View? { return null } } </code></pre> <p>And the Map resource object:</p> <pre><code>class MapResource { @SerializedName("id") @Expose var id: String? = null @SerializedName("name") @Expose var name: String? = null @SerializedName("scheduledArrival") @Expose var scheduledArrival: Int? = null @SerializedName("locationType") @Expose var locationType: Int? = null @SerializedName("companyZoneId") @Expose var companyZoneId: Int? = null @SerializedName("lat", alternate = ["y"]) @Expose var lat: Double? = null @SerializedName("lon", alternate = ["x"]) @Expose var lon: Double? = null @SerializedName("licencePlate") @Expose var licencePlate: String? = null @SerializedName("range") @Expose var range: Int? = null @SerializedName("batteryLevel") @Expose var batteryLevel: Int? = null @SerializedName("seats") @Expose var seats: Int? = null @SerializedName("model") @Expose var model: String? = null @SerializedName("resourceImageId") @Expose var resourceImageId: String? = null @SerializedName("pricePerMinuteParking") @Expose var pricePerMinuteParking: Double? = null @SerializedName("pricePerMinuteDriving") @Expose var pricePerMinuteDriving: Double? = null @SerializedName("realTimeData") @Expose var realTimeData: Boolean? = null @SerializedName("engineType") @Expose var engineType: String? = null @SerializedName("resourceType") @Expose var resourceType: String? = null @SerializedName("helmets") @Expose var helmets: Int? = null @SerializedName("station") @Expose var station: Boolean? = null @SerializedName("availableResources") @Expose var availableResources: Int? = null @SerializedName("spacesAvailable") @Expose var spacesAvailable: Int? = null @SerializedName("allowDropoff") @Expose var allowDropoff: Boolean? = null @SerializedName("bikesAvailable") @Expose var bikesAvailable: Int? = null } </code></pre> <p>You can find full code of the task <a href="https://github.com/darkngel82/MapAndMarkers" rel="nofollow noreferrer">here</a>.</p> <p>Also on ws package, I've added one text with the example response of the demo coordinates.</p> <p>Any help to improve this would be great, even after losing this job offer.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T13:21:26.813", "Id": "465869", "Score": "0", "body": "As I don't ave much time at this moment, just a quick remark:\nbreak up, break up, break up, break up, break up untill you're forced to stop.\nYou should seperate view, logic and data code. Therefor take a look at Android architecture components, mvp / mvvm or the mviCore library.\nAlso look into coroutines, if kotlin is expected." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T16:31:18.967", "Id": "465900", "Score": "0", "body": "Thanks for your quick response @tieskedh, can you expand your response a bit more?\nAfter read links you shared, I've seen the architecture used (or the no-architecture) is not the best one... but without a expanded experience in mvvm or mvi, it's not easy to understand." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T20:24:44.490", "Id": "465944", "Score": "1", "body": "Will extend answer later. For now: https://android.jlelse.eu/architecture-components-mvp-mvvm-237eaa831096" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T12:10:52.470", "Id": "237560", "Score": "2", "Tags": [ "interview-questions", "android", "rest", "kotlin" ], "Title": "ANDROID - Receive and manage markers in Google Maps" }
237560
<p>I have two classes <code>ExceptionLog</code> and <code>DebugLog</code></p> <pre><code>public class ExceptionLog { public static String StackTrace {get; set;} public static String ClassName {get; set;} public static String MethodName {get; set;} public static String LogType {get;set;} public static Exception ex {get;set;} public Static void Debug(Exception ex) { logType = 'EXCEPTION'; ex = ex; log(); } public Static void log() { try { extractException(); writeToObject(); } catch(Exception e) { //new ExceptionLog().Module('LogException').log(e); } } public static void extractException() { // Logic here } public static void writeToObject() { // data save to object logic here } } </code></pre> <p>and </p> <pre><code>public class DebugLog { public static String LogType {get;set;} public static String DebugMessage {get;set;} public Static void Debug(String message) { Debug(null, message); } public Static void Debug(LoggingLevel level, String message) { if(level != null ) { LogType = String.valueOf(level); } DebugMessage = message; log(); } public Static void log() { // Log logic here } } </code></pre> <p>What I want to achieve is, write a controller class that will make decision of which <code>debug</code> method needs to be called</p> <pre><code>public class Log { public void Debug(String message) { DebugLog.Debug(message); } public void Debug(loggingLevel loggingLevel, String message) { DebugLog.Debug(loggingLevel, message); } public void Debug(Exception ex) { ExceptionLog.Debug(ex); } } </code></pre> <p>That is, if I pass Exception in the debug method, it will call the <code>ExceptionLog.Debug(ex)</code> else it will call the debug method from <code>DebugLog</code> class.</p> <p>What should be the aprroach here ? </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T14:19:16.050", "Id": "237566", "Score": "1", "Tags": [ "object-oriented", "design-patterns", "salesforce-apex" ], "Title": "Design pattern for logger implementation" }
237566
<p>I had a 50 Gb text file (ca. 45 mln lines) and needed to extract about 1500 lines from it. I knew their indices, that is, line numbers. Those 1500 lines were spread across the whole file up to the very end. To accomplish this, I wrote a simple Perl script. It worked and was quite fast: it finished in about 4-5 minutes on a low-end "business" laptop (but with an SSD). </p> <p><strong>Question 1</strong>: Is the code sensible and well-written?<br> <strong>Question 2</strong>: Could the performance be improved somehow?</p> <pre class="lang-perl prettyprint-override"><code>#!/bin/perl # # Get lines from a file using line numbers from a second file # Syntax # getlinesfromfile.pl &lt;source-file&gt; &lt;index-file&gt; &lt;output-file&gt; # # Index file contains line numbers, one per line # Example: # # 1 # 5 # 17 # 73 # 31337 use strict; use warnings; my $version = "1.0.4"; my $date_released = "4 December 2019"; print "\nGet lines from file. Version $version released on $date_released\n"; my ($source_file, $idx_file, $output_file) = @ARGV; if (not defined $source_file or not defined $output_file or not defined $idx_file) { print "Parameters missing. Usage:\n\t$0 &lt;source_file&gt; &lt;idx_file&gt; &lt;output_file&gt;"; exit; } open(my $i_fh, '&lt;', $source_file) or die "FAILED to open '$source_file'!"; open(my $idx_fh, '&lt;', $idx_file) or die "FAILED to open '$idx_file'!"; open(my $o_fh, '&gt;', $output_file) or die "FAILED to open '$output_file'!"; # Read in indices $/ = "\r\n"; my %indices; while (my $line = &lt;$idx_fh&gt;) { chomp $line; $indices{$line} = 1; } close $idx_fh; my $count_indices = scalar keys %indices; my $msg_intro = &lt;&lt;"END"; Input filename: '$source_file' Index filename: '$idx_file' Output filename: '$output_file' Indices: $count_indices END print $msg_intro; my $lines_found = 0; my $lines_parsed = 0; $/ = "\n"; while (my $line = &lt;$i_fh&gt;) { chomp $line; $lines_parsed++; if (defined $indices{$lines_parsed}) { print $o_fh $line, "\r\n"; $lines_found++; } } close $o_fh; close $i_fh; print ("Parsed $lines_parsed lines, found $lines_found matches.\n"); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T14:47:14.527", "Id": "465882", "Score": "2", "body": "Use `$.` instead of `$lines_parsed`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T14:50:10.373", "Id": "465883", "Score": "3", "body": "For efficiency, after the highest index line is found, print and exit 0. No need to read the rest of the file. This is true if the highest index is frequently much less than the total number of lines, so it makes sense to spend the time on testing if we are done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T14:51:39.557", "Id": "465885", "Score": "1", "body": "Use somewhat more descriptive names for these vars, e.g., `$in_fh`, `$out_fh`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T14:53:20.270", "Id": "465886", "Score": "1", "body": "Make the filenadle stand out more, for readability: `print { $out_fh } $line, \"\\r\\n\";`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T17:41:51.387", "Id": "465909", "Score": "1", "body": "For performance, you might try transforming the indices into a simple sed program, and `exec`ing that. It's unlikely to make much difference, though, as most of your overhead is probably in the filesystem rather than in user-space." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-25T14:32:28.517", "Id": "469550", "Score": "1", "body": "Pffff @TimurShtatland \"For efficiency, after the highest index line is found, print and exit 0\" - this is so obvious, how could I have missed it? :) Thank you for pointing that out to me (and for the rest of the advices)!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-26T18:56:01.347", "Id": "469654", "Score": "0", "body": "print \"Parameters missing. Usage:\\n\\t$0 <source_file> <idx_file> <output_file>\"\\n;" } ]
[ { "body": "<p>I know this might be a one time task, however, if you want to create a reusable code, I would always put the line counting code in a \"continue\" block. It is more readable and safer for future enhancements. Somehow the line increment code \"finds itself\" pushed after a next statement...</p>\n\n<pre><code>while (my $line = &lt;$i_fh&gt;) {\n chomp $line;\n if (defined $indices{$lines_parsed}) {\n print $o_fh $line, \"\\r\\n\";\n $lines_found++;\n }\n} continue {\n $lines_parsed++;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-09T14:37:41.040", "Id": "242005", "ParentId": "237567", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T14:25:01.117", "Id": "237567", "Score": "4", "Tags": [ "perl" ], "Title": "Get specific lines from a huge text file" }
237567
<p>I'm looking to speed up an Rcpp function I have written. </p> <p>The function takes in a string called <code>vcfield</code>, which takes the format od <code>x:y:z</code>. This string has 3 fields if you separate it by the <code>:</code>. It takes an int <code>DSfield</code> which tells us the index (0 based) field from <code>vcfield</code> which is the dosage. Dosage is always one double value.</p> <p>It also takes in 2 <code>int</code>s called <code>aa</code> and <code>bb</code></p> <p>The program then returns the value of <code>abs[(aa + bb) - dosage]</code>.</p> <p>So calling <code>ReturnUncertainty("1/1:1.88:0,0.12,0.88", 1, 1, 1)</code> should return 0.12, as <code>abs[(1+1) - 1.88] = 0.12</code></p> <p>We should presume that the number of characters in the different fields of <code>vcfield</code> might vary. So it should be also be capable of taking a value like <code>"1/1/1/1:1.88999:0,0.12,0.88"</code>.</p> <pre><code>#include &lt;Rcpp.h&gt; #include &lt;bits/stdc++.h&gt; using namespace Rcpp; using namespace std; // [[Rcpp::export]] double ReturnUncertainty(String vcfield, int DSfield, int aa, int bb) { string stdfield = vcfield; vector &lt;string&gt; tokensMain; stringstream checkMain(stdfield); string intermediate; while (getline(checkMain, intermediate, ':')) { tokensMain.push_back(intermediate); } std::string DS = tokensMain[DSfield]; double DSf; std::istringstream(DS) &gt;&gt; DSf; double aaD = static_cast&lt;double&gt;(aa); double bbD = static_cast&lt;double&gt;(bb); double genoSum = aaD + bbD; return abs(genoSum - DSf); } </code></pre> <p><strong>QUESTION</strong>: As a total newbie to C++, I was wondering whether or not I am doing anything that is very inefficient / unecessary which might be slowing my code down?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T14:37:55.440", "Id": "465878", "Score": "0", "body": "Welcome to Code Review! How fast is your code and how fast do you need it to be?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T14:40:05.427", "Id": "465879", "Score": "1", "body": "Mm, it's hard to say because it is part of a much larger program. I guess I was more wondering, if I am doing anything very inefficient/unnecessary, which would slow the code down. If I am not, then that's great and I can move on! I will edit the question to be more clear." } ]
[ { "body": "<h1>Includes and <code>using namespace std;</code></h1>\n\n<p>You should not use <code>#include &lt;bits/stdc++.h&gt;</code> in any serious program, since this will pull in <a href=\"https://stackoverflow.com/a/25311198\"><em>all</em> standard library headers</a>.</p>\n\n<p>Together with <code>using namespace std;</code> this brings a high chance of causing headache, because of <a href=\"https://stackoverflow.com/q/1452721\">possible name collisions and ambiguities</a>.</p>\n\n<p>To get the standard library function you use, just include</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;sstream&gt;\n#include &lt;cmath&gt;\n</code></pre>\n\n<p>and better use the full-qualified name with leading <code>std::</code>.</p>\n\n<h1>The algorithm</h1>\n\n<p>Since you are only interested in a single position of the three possible tokens, there is no need to have a <code>std::vector</code> to store all of them.</p>\n\n<p>You can also stop parsing the string once you have found the value at the desired position.</p>\n\n<p>In the example below I've removed the Rcpp stuff, but I'm sure you'll be able to adapt it to your needs.</p>\n\n<p>It uses a range-based <code>for</code> loop, mostly stolen from the <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/getline\" rel=\"noreferrer\"><code>std::getline</code> documentation</a> with an additional counter variable to be able to abort early.</p>\n\n<p>If the approach using <code>std::stod</code> is not robust enough for all your cases, you could also switch back to your original implementation using <code>std::istringstream</code>.</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;sstream&gt;\n#include &lt;cmath&gt;\n\n#include &lt;iostream&gt; // only needed for main\n\ndouble ReturnUncertainty(std::string vcfield, int DSfield, int aa, int bb) \n{\n std::stringstream checkMain(vcfield);\n\n double dose = 0;\n int i = 0;\n for(std::string intermediate; std::getline(checkMain, intermediate, ':'); ++i) { \n if(i == DSfield) {\n dose = std::stod(intermediate);\n break;\n }\n }\n\n return std::fabs(aa + bb - dose);\n}\n\nint main() {\n std::cout &lt;&lt; ReturnUncertainty(\"1/1:1.88:0,0.12,0.88\", 1, 1, 1) &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>I have not measured the performance against your code, but I'm fairly confident that it would be faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T16:27:16.453", "Id": "465899", "Score": "0", "body": "This made the code about 20% quicker. Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T15:24:36.073", "Id": "237569", "ParentId": "237568", "Score": "5" } }, { "body": "<h2>Remove unnecessary steps</h2>\n\n<pre><code>for (int i = 0; i &lt; field_number - 1; ++i) \n{ /*read discard*/ }\ndouble value;\n// read the needed value now\n</code></pre>\n\n<p>This will make sure that it will not do unnecessary steps if the value needed is the very first one.</p>\n\n<h2>Do not copy around</h2>\n\n<p>I believe Rcpp would provide some way to access underlying <code>char*</code>. That can be used to construct <code>std::string_view</code>, or use the <code>char*</code> directly.</p>\n\n<h2>Use better standard library functions</h2>\n\n<p>My first candidate is famous (infamous) function called <code>std::from_chars</code>. It was accepted in C++17, but the support for that is only available with VC++'s standard library (I'm as surprised as you are, the reader, though getting FP parsing right is very hard). Basically it ignores all of the limitations of standard streams, from buffer structures to locales.</p>\n\n<p>The second candidate would be <code>std::strtod</code>, or some such. Notice that <code>std::stod</code> is not a good alternative, because it requires copying parts of the string.</p>\n\n<h2>Going beyond standard</h2>\n\n<p>One of the good options is <a href=\"https://github.com/fmtlib/fmt\" rel=\"noreferrer\">fmtlib</a>. It has convenient interface, and is actively developed. Part of it is event coming to standard library, but unfortunately not the one we are interested in.</p>\n\n<p>I'm not sure how faster it will get, but perhaps <a href=\"https://www.boost.org/doc/libs/1_72_0/libs/spirit/doc/html/index.html\" rel=\"noreferrer\">Boost.Spirit</a> may be a good candidate. It will certainly be strong spirits to your compiler.</p>\n\n<h2>Facts</h2>\n\n<p>Of course, the benchmarks will tell which way is better. May be everything I've told is heresy. </p>\n\n<h2>Alternative implementation</h2>\n\n<pre><code>#include &lt;charconv&gt;\n#include &lt;string_view&gt;\n#include &lt;cmath&gt;\n\ndouble strparse(std::string_view s, int field, int a, int b) {\n double candidates[3];\n auto format = std::chars_format::fixed;\n auto start_point = s.data();\n auto end_point = s.data() + s.size();\n switch (field) {\n case 0:\n start_point = std::from_chars(start_point, end_point, candidates[0], format);\n case 1:\n start_point = std::from_chars(start_point, end_point, candidates[1], format);\n case 2:\n start_point = std::from_chars(start_point, end_point, candidates[2], format);\n }\n\n double ad = a;\n double bd = b;\n return std::abs(ad + bd - candidates[field]);\n}\n</code></pre>\n\n<p>Well, here you have it. No copying around, manual loop unroll to prevent unnecessary steps, exact flags to maximize performance in standard library calls.</p>\n\n<p><a href=\"https://godbolt.org/z/x9jD3X\" rel=\"noreferrer\">Godbolt link</a>.</p>\n\n<p>Unfortunately I do not have convenient access to a windows machine to test the implementation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-28T14:57:09.573", "Id": "466994", "Score": "0", "body": "thanks - i couldn't get it to compile with c++17 - it throws: functions.cpp:134:24: error: ‘std::chars_format’ has not been declared\n\nalthough could possibly be an rcpp thing - do you know what's up?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-28T17:38:08.243", "Id": "467020", "Score": "0", "body": "@sahwahn, please reread my answer. It is written there. Also, it seems like I forgot to update the code in the answer, but the code in the godbolt link should be correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-28T17:43:38.240", "Id": "467021", "Score": "0", "body": "Oh I see - I should have been clearer that I need it to compile under gcc, not msvc. thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-28T17:47:40.050", "Id": "467022", "Score": "0", "body": "@sahwahn, that section was FYI. I’m pretty sure the support will come eventually. You might want to keep an eye out if performance is critical." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T18:24:09.613", "Id": "237573", "ParentId": "237568", "Score": "6" } } ]
{ "AcceptedAnswerId": "237569", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T14:33:37.977", "Id": "237568", "Score": "5", "Tags": [ "c++", "performance", "r", "rcpp" ], "Title": "Speeding up string splitting in Rcpp/Cpp" }
237568
<p>I have small (&lt;250 bytes) chunk of binary data, where I know that <em>almost</em> always, the first nibble is going to be zero <code>0</code>. For example, in hex:</p> <pre><code>01 02 03 04 0A 0B 0C 0D </code></pre> <p>I want to do some simple compression on this data. What I've decided to do is run length encoding, but I first need to get the data such that all the expected zeroes are next to each other. To do this, I need to do a swap of the nibbles from one side of the array to the other. For example, using the array above, I'd end up with the result of:</p> <pre><code>00 00 00 00 4A 3B 2C 1D </code></pre> <p>This would make for efficient RLE.</p> <p>Just to better illustrate, here's another example, this time without the zeroes in the array:</p> <pre><code>12 34 56 78 9A BC </code></pre> <p>After the "swap nibbles" algorithm:</p> <pre><code>1B 39 57 68 4A 2C </code></pre> <p>(And of course, running "swap nibbles" again reverses it, which is what I need.)</p> <p>I've worked up a JavaScript solution for this, but it "feels" overly tricky. I'd love for someone to take a look and let me know if they have any suggestions, or a completely different idea entirely. To enumerate my requirements:</p> <ul> <li>Most significant nibbles clustered with each other</li> <li>Algorithm must be reverisble</li> <li>Should work with an arbitrary amount of data, including odd numbers of bytes (but expected always be a small amount of data, under 1 KB)</li> </ul> <p>It is <em>not</em> a requirement that any solution use the exact same packing method I'm doing. Just as long as I get the the zeroes together, that's the main goal.</p> <h2>My Solution</h2> <pre><code>/** * Redo the bytes so that the data for the most significant nibbles are in * the first half of the array, and the least significant nibbles are in the * last half of the array. This makes for efficient packing when we know that * a lot of this data is going to be all zeroes. * @param {Uint8Array} data */ function swapNibbles(data) { const newData = new Uint8Array(data.length); for (let i=0; i&lt;data.length/2; i++) { // If odd number of bytes, and iterator is on the middle byte, just leave it if (i === (data.length - 1 - i)) { newData[i] = data[i]; } else { // Left Side of Array (most significant nibbles) newData[i] = ( // Most significant nibble of left byte (data[i] &amp; 0xF0) + // Most sigificant nibble of right byte, demoted by 4 bits ((data[data.length - 1 -i] &amp; 0xF0) &gt;&gt; 4) ); // Right Side of Array (least significant nibbles) newData[data.length - 1 - i] = ( // Least significant nibble of left byte, promited by 4 bits ((data[i] &amp; 0x0F) &lt;&lt; 4) + // Least significant nibble of right byte (data[data.length - 1 -i] &amp; 0x0F) ); } } return newData; } </code></pre> <p>Any feedback would be appreciated. Thanks!</p>
[]
[ { "body": "<p>I don't know too much about what you're trying to do (but it makes sense and I think I get it). </p>\n\n<p>Personally my feeling is that all you are missing is the right helper functions to make your code more transparent. I don't know how efficient this should be and hence if the overhead of function calls matters to you, but I am guessing no as otherwise you would have transformed the data in place I imagine.</p>\n\n<pre><code>/**\n * Redo the bytes so that the data for the most significant nibbles are in\n * the first half of the array, and the least significant nibbles are in the\n * last half of the array. This makes for efficient packing when we know that\n * a lot of this data is going to be all zeroes.\n * @param {Uint8Array} data\n */\nfunction swapNibblePairs(data) {\n const newData = new Uint8Array(data);\n for (let i = 0; i &lt; Math.floor(data.length / 2); i++) {\n const [hiNibbleLeft, loNibbleLeft] = getNibbles(data[i]);\n const [hiNibbleRight, loNibbleRight] = getNibbles(data[data.length - 1 - i]);\n\n newData[i] = byteFromNibbles(hiNibbleLeft, hiNibbleRight);\n newData[data.length - 1 - i] = byteFromNibbles(loNibbleLeft, loNibbleRight);\n }\n\n return newData;\n}\n\nfunction byteFromNibbles(hi, lo) {\n return (hi &lt;&lt; 4) | lo;\n}\n\nfunction getNibbles(byte) {\n return [(byte &gt;&gt; 4) &amp; 0x0f, byte &amp; 0x0f];\n}\n</code></pre>\n\n<p>The most important bit for me is it's now evident what the bytes you construct are, you take the two hi parts and join them, and take the two lo parts and join them.</p>\n\n<p>It also makes it evident in the code that this function is its own inverse which is nice.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T21:38:02.710", "Id": "237589", "ParentId": "237572", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T18:04:05.727", "Id": "237572", "Score": "3", "Tags": [ "javascript", "ecmascript-6", "bitwise", "binary" ], "Title": "Swapping Nibbles" }
237572
<p>This is a project I started a while ago, and still going. It is a text-based RPG written in Python. There are two files: <code>asathryne.py</code> (the main file) and <code>stuff.py</code> (a file with some functions for programs that I make; the game imports a couple of functions from it.) Thanks for looking over it!</p> <p><code>asathryne.py</code>:</p> <pre class="lang-py prettyprint-override"><code>from random import randint import simplejson import os from jsonpickle import encode, decode from stuff import cls, dialogue, num_input class Character(): def __init__(self, name, health, mana, lvl, strength, intelligence, agility, defence, weap, xp, abilities = [], inventory = [], gold = 0): self.name = name self.health = health self.mana = mana self.lvl = lvl self.strength = strength self.intelligence = intelligence self.agility = agility self.defence = defence self.weap = weap self.abilities = abilities self.inventory = inventory self.gold = gold self.xp = xp def view_stats(self): '''Used to display data about the character to the player''' cls() print(self) print(f'Level {self.lvl}') print(f'{self.xp} xp') print(f'{self.gold} Gold') print(f'Health - {self.health}') print(f'Mana - {self.mana}') print(f'Strength - {self.strength}') print(f'Intelligence - {self.intelligence}') print(f'Agility - {self.agility}') print(f'Defence - {self.defence}') print(f'Weapon - {self.weap} ({self.weap.damage[0]}-{self.weap.damage[1]} damage)') print(f'Abilities - {self.abilities}') print(f'Inventory - {self.inventory}') dialogue() def __repr__(self): return self.name def __str__(self): return self.name class PlayerCharacter(Character): def __init__(self, name, class_type, health, mana, lvl, strength, intelligence, agility, defence, weap = '', abilities = [], inventory = [], gold = 0, xp = 0): Character.__init__(self, name, health, mana, lvl, strength, intelligence, agility, defence, weap, xp, abilities, inventory, gold) self.progress = {'area': '', 'king_dialogue': False, 'gates_dialogue': False, 'gates_unlocked': False} self.class_type = class_type self.abi_points = 0 def view_stats(self): '''Used to display data about the player character to the player''' cls() print(self) print(f'Level {self.lvl} {self.class_type}') print(f'{self.gold} Gold') print(f'XP - {self.xp}/{(self.lvl + 2) ** 2}') print(f'{self.abi_points} ability points left') print(f'{self.health} Health') print(f'{self.mana} Mana') print(f'Strength - {self.strength}') print(f'Intelligence - {self.intelligence}') print(f'Agility - {self.agility}') print(f'Defence - {self.defence}') print(f'Weapon - {self.weap} ({self.weap.damage[0]}-{self.weap.damage[1]} damage)') print(f'Abilities - {self.abilities}') print(f'Inventory - {self.inventory}') dialogue() def build_char(self): '''Used in the beginning to build the player character''' while True: self.name = dialogue('What is your name, traveller?\n') if self.name != '': break else: print('You must have have a name in this realm.') while True: print('Choose a class.') for i, c in enumerate(classes): print(f'{i + 1}) {c}') class_pick = num_input() cls() for i, c in enumerate(classes): if class_pick == i + 1: dialogue(f'--- You chose the {c} class, which favors {c.stat}.\n') setattr(self, c.stat, getattr(self, c.stat) + 3) self.class_type = c self.inventory.append(c.weap) return print('--- Invalid choice') def equip(self, weapon): '''Used to equip a weapon''' if weapon in self.inventory: self.inventory.remove(weapon) self.weap = weapon dialogue(f'--- {weapon} has been equipped.') return True return False def item_remove(self, item): '''Used to remove an item from the player's inventory''' if item in self.inventory: dialogue(f'--- {item} has been removed from your inventory.\n') self.inventory.remove(item) return True return False def learn_ability(self): '''Used whenever the player character can learn a new ability; only used in lvl_up as of current''' def check_ab(abi, abl): for a in abl: if a.name == abi.name: return False return True ability_list = [abi for abi in self.abilities if abi.max_lvl &gt; abi.lvl] for abi in abilities: for stat in ['strength', 'intelligence', 'agility', 'defence']: if abi.stat == stat and getattr(self, stat) &gt;= abi.minimum_stat: if self.abilities == []: ability_list.append(abi) else: if check_ab(abi, self.abilities): ability_list.append(abi) if ability_list == []: dialogue('--- There are no avaliable abilities to learn/upgrade.\n') return False while True: print(f'--- You have {len(ability_list)} abilities to learn/upgrade.') for i, abi in enumerate(ability_list): print(f'{i + 1}) {abi} ({abi.lvl}/{abi.max_lvl}): {abi.desc}') choice = num_input() cls() if choice &gt; len(ability_list) or choice == 0: print('--- Invalid choice') continue for i, abi in enumerate(ability_list): if choice == i + 1: if abi.lvl == 0: dialogue(f'--- You have learned {abi}.\n') self.abilities.append(abi) else: dialogue(f'--- You have upgraded {abi}.\n') abi.lvl += 1 self.abi_points -= 1 return True def lvl_up(self): '''Whenever the player's xp reaches a certain point, they will level up''' cls() while self.xp &gt;= (self.lvl + 2) ** 2: self.xp -= (self.lvl + 2) ** 2 self.lvl += 1 self.health += 50 self.mana += 25 self.abi_points += 1 dialogue(f'--- You have leveled up to level {self.lvl}! Your power increases.\n') points = 3 while points &gt; 0: for stat in ['strength', 'intelligence', 'agility', 'defence']: current_stat = getattr(self, stat) upgrade = num_input(f'--- {stat.capitalize()}: {current_stat} ({points} points remaining) Add: ') if upgrade &gt; points: upgrade = points points -= upgrade setattr(self, stat, current_stat + upgrade) cls() if points == 0: break while self.abi_points &gt; 0: if not self.learn_ability(): break def save(self): '''Used to save player progress''' with open(f'{self.name}_player_data.txt', 'w') as file: file.write(encode(self)) def combat(self, enemy): '''Used whenever the player enters combat''' self.current_health = self.health self.current_mana = self.mana enemy.current_health = enemy.health enemy.current_mana = enemy.mana dialogue(f'You encountered {enemy}!') your_turn = True while True: if your_turn: print(f'{self}\nHealth - {self.current_health}/{self.health}\nMana - {self.current_mana}/{self.mana}\n') print(f'{enemy}\nHealth - {enemy.current_health}/{enemy.health}\nMana - {enemy.current_mana}/{enemy.mana}\n') print('1) Attack') print('2) Pass') choice = num_input() cls() if choice == 1: dialogue('You attack with your weapon!') if randint(1, 100) &lt; (self.agility / (self.agility + enemy.agility)) * 100: damage = int(self.strength / (self.strength + enemy.defence) * randint(*self.weap.damage)) dialogue(f'You hit {enemy} for {damage} damage!') enemy.current_health -= damage if enemy.current_health &lt;= 0: win = True break else: dialogue('You missed!') elif choice == 2: dialogue('You passed.') else: print('--- Invalid choice') continue your_turn = False else: dialogue(f'{enemy} attacks!') if randint(1, 100) &lt; (enemy.agility / (enemy.agility + self.agility)) * 100: damage = int(enemy.strength / (enemy.strength + self.defence) * randint(*enemy.weap.damage)) if damage &lt; 0: damage = 0 dialogue(f'{enemy} hit you for {damage} damage!') self.current_health -= damage if self.current_health &lt;= 0: win = False break else: dialogue('It missed!') your_turn = True if win: dialogue(f'You defeated {enemy}, and gained {enemy.xp} xp and {enemy.gold} gold!') self.xp += enemy.xp self.gold += enemy.gold return True else: dialogue('You perished.') return False class Class: def __init__(self, name, stat, weap): self.name = name self.stat = stat self.weap = weap def __repr__(self): return self.name def __str__(self): return self.name class Item: def __init__(self, name, value = 0, amount = 0, quest = False): self.name = name self.value = value self.amount = amount self.quest = quest def find(self, char): '''Used whenever the player character recieves this item''' char.inventory.append(self) dialogue(f'--- You have recieved {self} worth {self.value} gold, and it has been added to your inventory.\n') def __repr__(self): return self.name def __str__(self): return self.name class Weapon(Item): def __init__(self, name, damage, value = 0, amount = 0, quest = False): Item.__init__(self, name, value, amount) self.damage = damage class Ability: def __init__(self, name, desc, stat, minimum_stat, lvl = 0, max_lvl = 3): self.name = name self.desc = desc self.stat = stat self.lvl = lvl self.max_lvl = max_lvl self.minimum_stat = minimum_stat def __repr__(self): return self.name def __str__(self): return self.name class Location: def __init__(self, name, visit_func): self.visit_func = visit_func self.name = name def visit(self, player): '''Used whenever the player visits the location''' dialogue(f'--- You travel to {self}.') self.visit_func(player) def __repr__(self): return self.name def __str__(self): return self.name class Area(Location): def __init__(self, name, locations): self.name = name self.locations = locations def visit(self, player): '''Used whenever the player visits the area''' player.progress['area'] = self dialogue(f'--- You travel to {self}.') while True: print(self) for i, l in enumerate(self.locations): print(f'{i + 1}) {l}') print(f'{len(self.locations) + 1}) View Character') print(f'{len(self.locations) + 2}) Save') if player.xp &gt;= (player.lvl + 2) ** 2: print(f'{len(self.locations) + 3}) Level up!') choice = num_input() if choice == len(self.locations) + 1: player.view_stats() continue elif choice == len(self.locations) + 2: player.save() cls() print('Saved successfully!') continue elif choice == len(self.locations) + 3 and player.xp &gt;= (player.lvl + 2) ** 2: player.lvl_up() continue elif choice &gt; len(self.locations) or choice &lt;= 0: cls() print('--- Invalid choice') continue cls() self.locations[choice - 1].visit(player) class Shop(Location): def __init__(self, name, stock, greeting): self.name = name self.stock = stock self.greeting = greeting def visit(self, player): '''Used whenever the player visits the shop''' dialogue(f'--- You travel to {self}.') dialogue(self.greeting) while True: print(f'--- You have {player.gold} gold.') for i, item in enumerate(self.stock): print(f'{i + 1}) {item} - {item.value} gold') print(f'{len(self.stock) + 1}) Sell items') print(f'{len(self.stock) + 2}) Leave') choice = num_input() cls() if choice == len(self.stock) + 1: if player.inventory == []: print('--- error: inventory empty') continue while True: print(f'--- You have {player.gold} gold.') choice_inv = [i for i in player.inventory if not i.quest] for i, item in enumerate(choice_inv): print(f'{i + 1}) {item} - {int(item.value * 0.8)} gold') print(f'{len(choice_inv) + 1}) Back') choice = num_input() cls() if choice == len(choice_inv) + 1: break elif choice &gt; len(choice_inv) or choice &lt;= 0: print('--- Invalid choice') continue choice = choice_inv[choice - 1] player.gold += int(choice.value * 0.8) player.inventory.remove(choice) print(f'--- You sold a {choice} for {int(choice.value * 0.8)} gold.') continue elif choice == len(self.stock) + 2: return elif choice &gt; len(self.stock) or choice &lt;= 0: print('--- Invalid choice') continue choice = self.stock[choice - 1] if choice.value &gt; player.gold: print('--- Insufficient funds') continue player.gold -= choice.value player.inventory.append(choice) print(f'--- You bought a {choice} for {choice.value} gold.') class Slime(Character): pass ''' character health - How much damage the character can take before they perish mana - Determines the character's use of abilities lvl - Represents the character's power level strength - Determines the amount of damage the character deals with physical attacks intelligence - Determines the potency of the character's spells agility - Determines the accuracy of the character's attacks, and how often they dodge attacks defence - Determines how much damage the character take from physical attacks abilities - list of abilities the character can use in battle inventory - list of items the character carries xp - how much xp gained when slain gold - currency carried by the character player character class - determines what stat you favor; underdeveloped as of current xp - Gain XP in battle; when you have enough, you will go up one level and you will get to use your skill points. abi_points - If the player cannot learn abilities at the moment, they will recieve an ability point to use for later. ''' king_story = ( 'Very well. Go ahead and take a seat.', 'Now, Asathryne once was a kingdom filled with happiness and peace, ruled by Emperor Verandus.', 'Until one day, an evil never before seen, arrived in Asathryne and tore the realm apart, leaving nothing but a barren wasteland.', 'Sanctuary became the only thriving town left in the land.', 'The horrid evil killed the emperor and kidnapped his daughter, our future princess. She was one of the most powerful beings in Asathryne.', 'But this was twenty years ago. Much longer ago, when we had a fighting chance against the dark forces.', 'We have long waited for a courageous adventurer who would be worthy enough to venture into the depths of Asathryne and rescue us from this terror.') ''' Basically, here's how it goes: Princess is born to emperor, and they find out she's super magical and has immense powers. Emperor goes into deep cave. Or something. Or maybe some servant or adventerer goes. He discovers a book or something. The book contains dark magics. The emperor reads the book and becomes corrupted with the dark magics. He hears voices telling him to summon a bunch of dark creatures. He uses princess as a conduit to summon the army, fakes his own death, and travels to a mountain where nobody can find his daughter. Continues summoning army until they destroy asathryne. ''' axe = Weapon('Axe', (25, 50), 10) staff = Weapon('Staff', (25, 30), 10) bow = Weapon('Bow', (30, 35), 10) sword = Weapon('Sword', (35, 40), 10) sanctuary_key = Item('Sanctuary Key', quest = True) pot_health = Item('Health Potion', 20) pot_mana = Item('Mana Potion', 20) warrior = Class('Warrior', 'strength', axe) sorcerer = Class('Sorcerer', 'intelligence', staff) ranger = Class('Ranger', 'agility', bow) paladin = Class('Paladin', 'defence', sword) classes = [warrior, sorcerer, ranger, paladin] sanctuary_apothecary = Shop( name = 'Sanctuary Apothecary', stock = [pot_health, pot_mana], greeting = 'Welcome to the Apothecary! We have a variety of potions for sale. Take a look at what we have in stock.') sanctuary_blacksmith = Shop( name = 'Sanctuary Blacksmith', stock = [axe, staff, bow, sword], greeting = 'Hello there, traveller! You look like you could use a reliable weapon. Step into my shop and take a look at my many wares!') def sanctuary_gates_visit(player): if player.progress['gates_unlocked']: forest_of_mysteries.visit(player) return elif player.progress['king_dialogue']: dialogue('Asathryne Gatekeeper: Halt there, young - ') dialogue('Oh. You spoke with the King? I suppose my orders are to let you through then. Here, hand me the key.') while True: last_option = dialogue('1) Return to Sanctuary\n2) Unlock the gates\n') if last_option == '1': dialogue('Very well. Return to the town square, and come back here when you are ready.') return elif last_option == '2': player.item_remove(sanctuary_key) dialogue('--- You give the key to the gatekeeper. The gates open, revealing an expansive forest, teeming with otherworldly life.') dialogue('Good luck out there, traveller.') player.progress['gates_unlocked'] = True forest_of_mysteries.visit(player) return else: print('--- Invalid choice') dialogue('Asathryne Gatekeeper: Halt there, young traveller! There is a dangerous, dark evil behind these gates. I shall not let you pass, unless you have spoken with the King of Asathryne!') player.progress['gates_dialogue'] = True while True: option_gate = dialogue('Type \'go\' to go meet King Brand, or \'exit\' to return to the town square.\n').lower() if option_gate == 'go': sanctuary_kings_palace.visit(player) return elif option_gate == 'exit': cls() dialogue('--- You return to the town square.') return else: cls() gate_random = randint(1, 3) if gate_random == 1: dialogue('What are you waiting for? Go on!') elif gate_random == 2: dialogue('Don\'t think standing here will convince me to open this gate.') else: dialogue('Brand is waiting for you.') sanctuary_gates = Location('Sanctuary Gates', sanctuary_gates_visit) def sanctuary_kings_palace_visit(player): if player.progress['king_dialogue']: dialogue('King Brand: Hello, young traveller.') while True: king_story_repeat = dialogue('Do you wish to hear the story of Asathryne? (Y/N): ').lower() if king_story_repeat == 'y': for s in king_story: dialogue(s) return elif king_story_repeat == 'n': dialogue('Oh well, maybe for another day. Fare well, traveller!') return else: print('--- Invalid choice') dialogue(f'King Brand: At last, a brave {player.class_type} has arisen once more in this kingdom, here on a quest to save the kingdom of Asathryne from the dark evil that lies beyond the gates.') dialogue('Tell me young traveller, what do you seek from me?') while True: if player.progress['gates_dialogue']: option_1 = dialogue('1) I\'m here to learn about Asathryne\n2) The gate keeper has sent me to meet you\n') else: option_1 = dialogue('1) I\'m here to learn about Asathryne\n') if option_1 == '1': for s in king_story: dialogue(s) dialogue('You will be the one to free us from this crisis.') dialogue('Here, take this key; you will need it to open the gate into what remains of Asathryne.') sanctuary_key.find(player) dialogue('Fare well, young traveller.') player.progress['king_dialogue'] = True return elif option_1 == '2' and player.progress['gates_dialogue']: dialogue('Ah, the gate keeper. He forbids anyone entry to the rest of Asathryne, simply because he wants to protect them.') break else: print('--- Invalid choice') while True: option_2 = dialogue('Let me ask you a question, traveller. Would you like to hear the Story of Asathryne? (Y/N)\n').lower() if option_2 == 'n': dialogue('Very well, very well, let me see... it\'s here somewhere... ah! The Key to Asathryne. Take this, young traveller, and good luck!') sanctuary_key.find(player) player.progress['king_dialogue'] = True return elif option_2 == 'y': for s in king_story: dialogue(s) dialogue('You will be the one to free us from this crisis.') dialogue('Here, take this key; you will need it to open the gate into what remains of Asathryne.') sanctuary_key.find(player) dialogue('Fare well, young traveller.') player.progress['king_dialogue'] = True return else: print('--- Invalid choice') sanctuary_kings_palace = Location('Sanctuary King\'s Palace', sanctuary_kings_palace_visit) def forest_main_visit(player): player.combat(Slime( name = 'Green Slime', health = 50, mana = 0, lvl = 1, strength = 3, intelligence = 0, agility = 2, defence = 2, weap = Weapon('Slime', (30, 40)), gold = randint(3, 6), xp = randint(2, 3))) forest_main = Location('Forest Main', forest_main_visit) sanctuary = Area('Sanctuary', [sanctuary_gates, sanctuary_kings_palace, sanctuary_apothecary, sanctuary_blacksmith]) forest_of_mysteries = Area('Forest of Mysteries', [sanctuary, forest_main]) stun = Ability( name = 'Stun', desc = 'You swing with your weapon, with so much force that the enemy cannot use abilities for 2 turns.', stat = 'strength', minimum_stat = 8) fireball = Ability( name = 'Fireball', desc = 'You cast a fireball at your enemy, and on impact, it has a chance to burn the enemy.', stat = 'intelligence', minimum_stat = 8) sure_shot = Ability( name = 'Sure Shot', desc = 'You fire a well-aimed shot from your bow, which can\'t miss, and deals critical damage.', stat = 'agility', minimum_stat = 8) protection = Ability( name = 'Protection', desc = 'You summon a magical wall of protection, which prevents half of the damage dealt to you for 3 turns.', stat = 'defence', minimum_stat = 8) abilities = [stun, fireball, sure_shot, protection] def main(): cls() while True: print('&gt;&gt;&gt; Asathryne &lt;&lt;&lt;') print('1) New game\n2) Load game') choice = num_input() cls() if choice == 1: player = PlayerCharacter( name = '', class_type = '', health = 50, mana = 25, lvl = 0, strength = 5, intelligence = 5, agility = 5, defence = 5, xp = 4, gold = 50) player.build_char() if dialogue('--- Type \'skip\' to skip the tutorial, or press enter to continue\n') == 'skip': player.equip(player.class_type.weap) player.lvl_up() else: dialogue(f'Welcome to The Realm of Asathryne, {player}. A kingdom filled with adventure and danger, with much in store for those brave enough to explore it. Of course, nothing a {player.class_type} such as yourself can\'t handle.') dialogue('Oh, of course! Allow me to introduce myself. My name is Kanron, your advisor.') dialogue(f'You can\'t just go wandering off into Asathryne without a weapon. Every {player.class_type} needs a {player.class_type.weap}!') player.equip(player.class_type.weap) dialogue('Before you go venturing off into the depths of this realm, you must first master some basic skills.') dialogue('Your stats determine your performance in battle, and the abilities you can learn.') dialogue('There are 4 main stats: Strength, Intelligence, Agility, and Defense.') while True: learn_more = dialogue('Do you want to learn more about stats? (Y/N)\n').lower() if learn_more == 'y': dialogue('Strength increases the amount of damage you deal with physical attacks.') dialogue('Intelligence increases the potency of your spells.') dialogue('Agility determines the accuracy of your attacks, and how often you dodge attacks.') dialogue('Defense determines how much damage you take from physical attacks.') dialogue('Your mana determines your use of abilities.') dialogue('Your health determines how much damage you can take before you perish.') break elif learn_more == 'n': break else: print('--- Invalid choice') dialogue('Let\'s talk about your level.') dialogue('Your level represents how powerful you are, and determines the level of your enemies; when you go up a level, you will recieve 3 skill points to spend on any of the 4 stats, and 1 ability point to learn/upgrade abilities. Additionally, your health and mana will automatically increase.') dialogue('You can gain XP (experience points) in battle; when you have enough, you\'ll go up one level and get to use your skill points.') dialogue('Let\'s upgrade your stats. For your class, you recieve an extra 3 skill points in the stat that your class favors, and you will recieve 1 level up.') player.lvl_up() dialogue('Great job! Now that you have learned the basics, it is time you start your journey into the Realm of Asathryne.') sanctuary.visit(player) elif choice == 2: saves = [] for file in os.listdir(os.fsencode(os.getcwd())): filename = os.fsdecode(file) if 'player_data' in filename: with open(filename, 'r') as file: saves.append(decode(file.read())) if saves == []: print('No saves found') continue while True: print('Choose your character.') for i, s in enumerate(saves): print(f'{i + 1}) {s.name} - Level {s.lvl} {s.class_type}') choice = num_input() cls() if choice &lt;= 0 or choice &gt; len(saves): print('--- Invalid choice') continue player = saves[choice - 1] player.progress['area'].visit(player) elif choice == 0 or choice &gt; 2: print('--- Invalid choice') if __name__ == '__main__': main() </code></pre> <p><code>stuff.py</code>:</p> <pre class="lang-py prettyprint-override"><code>import os #a shorter version of system('cls') def cls(): os.system("cls" if os.name == "nt" else "clear") #Like input, but only accepts numbers; returns number in integer form, or 0 if the input is not a number def num_input(string=""): x = input(string) if x.isdigit(): return int(x) else: return 0 #Like input, but clears after the input is taken def dialogue(string=""): x = input(string) cls() return x </code></pre> <h1>Gameplay</h1> <p>The game uses presents a list of options to the player each time they can take an action; it starts out by making a new game or loading an old save. You then build your character, pick your class, and set your stats and first ability (abilities have no use yet; <em>possible recommendations for implementation?</em>). It then gives a tutorial, and puts you into the starting area, where you can progress through the story. The second area allows you to fight green slime to gain gold and xp, which you can use to buy items (also useless) and level up, respectively.</p> <h1>Issues</h1> <ul> <li>Some features have no use (abilities and items)</li> <li>Option lists are repeated</li> </ul> <p>Anything to improve my code would be greatly appreciated.</p>
[]
[ { "body": "<h1><code>asathryne.py</code></h1>\n\n<h1><code>PlayerCharacter.learn_ability.check_ab</code></h1>\n\n<p>This helper function can be reduced to one line:</p>\n\n<pre><code>def check_ab(abi, abl):\n return any(a.name == abi.name for a in abl)\n</code></pre>\n\n<p>The <a href=\"https://docs.python.org/3/library/functions.html#any\" rel=\"nofollow noreferrer\"><code>any</code></a> returns <code>True</code> if any of the values passed by the iterator are true. In this case, if <code>aname == abi.name</code> results in a <code>True</code> value, then the function will return <code>True</code>. I've provided a link to the built in function if my wording was too confusing.</p>\n\n<h1>Reserved variable names</h1>\n\n<p><a href=\"https://stackoverflow.com/questions/4613000/what-is-the-cls-variable-used-for-in-python-classes\"><code>cls</code></a> is a reserved name in python. You can use it, but it's a convention to only use it to reference the first argument to class methods. I would suggest renaming that method to <code>clear_screen</code> or <code>clear_console</code>.</p>\n\n<h1>Using <code>super</code></h1>\n\n<p>It's more common to use <a href=\"https://www.pythonforbeginners.com/super/working-python-super-function\" rel=\"nofollow noreferrer\"><code>super</code></a> when calling a superclasses constructor. It makes it clear that you're referencing a super class, and you don't have to pass <code>self</code>. Have a look:</p>\n\n<pre><code>class Weapon(Item):\n\n def __init__(self, name, damage, value=0, amount=0, quest=False):\n\n super().__init__(name, value, amount)\n self.damage = damage\n</code></pre>\n\n<h1>Default parameter spacing</h1>\n\n<p>When passing or assigning default parameters, there is no space before or after the <code>=</code>. Look above for an example of that.</p>\n\n<hr>\n\n<h1><code>stuff.py</code></h1>\n\n<h1>One line functions</h1>\n\n<p>Even when a function has only one line, you should still indent it. It keeps you conforming to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>, and makes your code style consistent.</p>\n\n<h1><code>num_input</code></h1>\n\n<p>This function can be reduced to two lines:</p>\n\n<pre><code>def num_input(string=\"\"):\n x = input(string)\n return int(x) if x.isdigit() else 0\n</code></pre>\n\n<p>Makes your code looks a little nicer, as has less overall code.</p>\n\n<h1>Indentation</h1>\n\n<p>You were consistent with your indentation in your main file, but make sure that you indent <strong>4</strong> spaces.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T19:44:54.243", "Id": "465930", "Score": "1", "body": "Thank you; the `any()` function was helpful, but I had to replace it with `all()`, since none of the conditions can be `False`. That's why I `return False` before `True`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T20:02:49.677", "Id": "465933", "Score": "0", "body": "@Apple Ah, I missed that. Good call. You could also use `not any(...)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T21:20:28.500", "Id": "465959", "Score": "0", "body": "Well, `not any()` would just be worse; if you had a list of all `False`, you would need `False` but it would return `True`; if you had a list of all `True`, you would need `True` but it would return `False`; the only case it would work is if you had a mix of both conditions, in which case it would return `False`. In other words, `all()` != `not any()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T23:08:49.610", "Id": "465966", "Score": "0", "body": "@Apple Wow, I didn't see it that way. I guess even as a reviewer I can still learn a thing or two!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T19:22:40.450", "Id": "237576", "ParentId": "237574", "Score": "3" } }, { "body": "<h1>isdigit()</h1>\n\n<p><a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=isdigit#str.isdigit\" rel=\"nofollow noreferrer\"><code>str.isdigit()</code></a> does not do what you think it does. <code>\"1²³4\".isdigit()</code> returns <code>True</code> because all the character in the string look like digits, despite some of them being superscripts. You want the <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=isdigit#str.isdecimal\" rel=\"nofollow noreferrer\"><code>str.isdecimal()</code></a> function, which returns <code>True</code> if all the characters are in the set of the 10 decimal characters (ie, base-10).</p>\n\n<h1>Dictionaries</h1>\n\n<p>You should be using dictionaries.</p>\n\n<p>The character's stats, for instance, should be in <code>self.stat</code>, initialized with:</p>\n\n<pre><code>self.stat = { 'strength': strength,\n 'intelligence': intelligence,\n 'agility': agility,\n 'defence': defence,\n }\n</code></pre>\n\n<p>Then opposed to writing code <code>getattr(self, stat)</code>, you would code <code>self.stat[stat]</code>. In particular:</p>\n\n<pre><code> for stat in ['strength', 'intelligence', 'agility', 'defence']: \n if abi.stat == stat and getattr(self, stat) &gt;= abi.minimum_stat:\n</code></pre>\n\n<p>should be coded:</p>\n\n<pre><code> if self.stat[abi.stat] &gt;= abi.minimum_stat:\n</code></pre>\n\n<p>No need to loop over all stats, looking for the correct one. You know what the correct stat is: <code>abi.stat</code>. Just use it.</p>\n\n<p>When you do want to iterate over them, instead of:</p>\n\n<pre><code> for stat in ['strength', 'intelligence', 'agility', 'defence']:\n current_stat = getattr(self, stat)\n upgrade = num_input(f'--- {stat.capitalize()}: {current_stat} ({points} points remaining) Add: ')\n</code></pre>\n\n<p>you could write:</p>\n\n<pre><code> for stat in self.stat:\n current_stat = self.stat[stat]\n upgrade = num_input(f'--- {stat.capitalize()}: {current_stat} ({points} points remaining) Add: ')\n</code></pre>\n\n<p>or even:</p>\n\n<pre><code> for stat, current_stat in self.stat.items():\n upgrade = num_input(f'--- {stat.capitalize()}: {current_stat} ({points} points remaining) Add: ')\n</code></pre>\n\n<p>As of Python 3.7, (and CPython 3.6 implementation) dictionary order is guaranteed to be insertion order, so your stats will stay in the order you expect.</p>\n\n<hr>\n\n<p>Similarly, <code>self.abilities</code> should not be a list, it should be a dictionary. Then instead of this code:</p>\n\n<pre><code> if self.abilities == []:\n ability_list.append(abi)\n else:\n if check_ab(abi, self.abilities):\n ability_list.append(abi)\n</code></pre>\n\n<p>You can get rid of the <code>check_ab</code> function, and simply have:</p>\n\n<pre><code> if abi.name not in self.abilities:\n ability_list.append(abi)\n</code></pre>\n\n<h1>Enumeration</h1>\n\n<pre><code> for i, abi in enumerate(ability_list):\n print(f'{i + 1}) {abi} ({abi.lvl}/{abi.max_lvl}): {abi.desc}')\n choice = num_input()\n cls()\n if choice &gt; len(ability_list) or choice == 0:\n print('--- Invalid choice')\n continue\n for i, abi in enumerate(ability_list):\n if choice == i + 1:\n</code></pre>\n\n<p>The <a href=\"https://docs.python.org/3/library/functions.html?highlight=enumerate#enumerate\" rel=\"nofollow noreferrer\"><code>enumerate(iterable, start=0)</code></a> by default starts at zero, but it doesn't have to. You could easily make it start at 1, eliminating the need for all those <code>+ 1</code> calculations.</p>\n\n<pre><code> for i, abi in enumerate(ability_list, 1):\n print(f'{i}) {abi} ({abi.lvl}/{abi.max_lvl}): {abi.desc}')\n choice = num_input()\n cls()\n if choice &gt; len(ability_list) or choice == 0:\n print('--- Invalid choice')\n continue\n for i, abi in enumerate(ability_list, 1):\n if choice == i:\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T05:02:13.703", "Id": "237604", "ParentId": "237574", "Score": "3" } } ]
{ "AcceptedAnswerId": "237576", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T18:32:12.047", "Id": "237574", "Score": "5", "Tags": [ "python", "python-3.x", "game" ], "Title": "Asathryne - A Python RPG" }
237574
<p>I posted <a href="/q/237148">the first part of this game</a> earlier, and now I finished the second part.</p> <p>From the first part we just had to have a random value to get the cards, and the bet always stayed at $25. For the second part the user could choose their bet, enter 0 to quit the game completely, and just hit enter to default to 25 on their first round, or can stay with their bet from the previous round.</p> <p>My code is super messy and very long. I know it can be cleared up and made much shorter as I've seen people with around 70 lines of code.</p> <pre><code>import random def main(): restart = True bank_balance = 1000 player_name = input("Please enter your name: ") #Default bet user_bet=25 while restart: print (f"Welcome {player_name}, your bank balance is ${bank_balance} ") bet = input_bet(user_bet, bank_balance) #Returned value from input_bet to stop the program if (bet == -10): break win_lose = play_hand(player_name, bet) bank_balance+=win_lose print(f'Your bank balance: ${bank_balance}') def input_bet(bet, money): correct = False while not correct: if (money &lt;=0): print('You ran out of money') return -10 str_bet=input("Bet? (0 to quit, press 'Enter' to stay at $25) ") if (str_bet == ''): print(f'Staying at ${bet}') return bet try: enough_money = False while not enough_money: bet=int(str_bet) if (bet &gt; money): print('not enough money') str_bet=input("Bet? (0 to quit, press 'Enter' to stay at $25) ") bet=int(str_bet) if (bet &lt; 0): print('Enter a number greater than 0') str_bet=input("Bet? (0 to quit, press 'Enter' to stay at $25) ") bet=int(str_bet) elif (bet == 0): return 0 elif (bet &lt;= money): print(f'Betting ${bet}') enough_money=True return bet correct = True except ValueError: print('Please enter a whole number') def play_hand(name, bet): player= [] dealer= [] play_again = True dealer.append(random.randint(1, 11)) player.extend([random.randint(1, 11), random.randint(1, 11)]) print ('The dealer received card of value', *dealer) print(name, 'received cards of value', player[0], 'and', player[-1]) print(f'Dealer total is {sum(dealer)}') print(f"{name}'s total is {sum(player)}", '\n') stay = False bust = False while (sum(player) &lt;= 21 and stay == False and play_again == True): hors= input(f"Type 'h' to hit and 's' to stay ") if (hors == 'h'): new_card= random.randint(1, 11) player.append(new_card) print(f'{name} pulled a {new_card}') print(f'Dealer total is {sum(dealer)}') print(f"{name}'s cards are", *player) print(f"{name}'s total is {sum(player)}", '\n') elif (hors == 's'): stay=True print('stay') if (sum(player) &gt; 21 ): bust = True print('You busted!') return -bet while (stay == True and sum(dealer) &lt; 17 and bust == False and play_again == True): dealer.append(random.randint(1, 11)) print('The dealers cards are', *dealer) print('The dealers total is', sum(dealer), '\n') if (sum(dealer) &lt;= 21 and sum(dealer) &gt; sum(player)): print("The dealer wins!") return -bet elif (sum(player) &lt;= 21 and sum(player) &gt; sum(dealer)): print("You win!") return bet if (sum(dealer) &gt; 21): print ('You win! The dealer busted!') return bet if (sum(dealer) == sum(player)): print('Its a Tie! ') return 0 main() </code></pre>
[]
[ { "body": "<h1>Indentation</h1>\n\n<p>You should indent <strong>4</strong> spaces. Here's the <a href=\"https://www.python.org/dev/peps/pep-0008/#indentation\" rel=\"nofollow noreferrer\">PEP 8</a> guidelines on this.</p>\n\n<h1>Equality</h1>\n\n<p>Instead of</p>\n\n<blockquote>\n<pre><code>while (sum(player) &lt;= 21 and stay == False and play_again == True):\n</code></pre>\n</blockquote>\n\n<p>do this</p>\n\n<pre><code>while(sum(player) &lt;= 21 and not stay and play_again):\n</code></pre>\n\n<p>You don't need to <code>== True/False</code>, as those variables will equate to those boolean values already within the statement. This applies to other parts of your program as well.</p>\n\n<h1>Operator spacing</h1>\n\n<p>There should be a space before and after every operator (<code>+</code> <code>-</code> <code>*</code> <code>/</code> <code>=</code>, etc.) in your program. This increases readability and makes your code look nicer.</p>\n\n<h1>Unnecessary parentheses</h1>\n\n<p>You don't need parentheses around simple <code>if</code> statements, unless you're trying to group specific conditions with each other. But something like this:</p>\n\n<blockquote>\n<pre><code>if (str_bet == ''):\n</code></pre>\n</blockquote>\n\n<p>should just be this</p>\n\n<pre><code>if str_bet == '':\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T19:37:20.823", "Id": "237579", "ParentId": "237577", "Score": "4" } }, { "body": "<blockquote>\n<pre><code>if (sum(dealer) &lt;= 21 and sum(dealer) &gt; sum(player)):\n print(\"The dealer wins!\")\n return -bet\n</code></pre>\n</blockquote>\n\n<p>A cool Python trick is that you can write:</p>\n\n<pre><code>if (sum(player) &lt; sum(dealer) &lt;= 21):\n print(\"The dealer wins!\")\n return -bet\n</code></pre>\n\n<p>With the same meaning as above, but more natural.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>\"Bet? (0 to quit, press 'Enter' to stay at $25) \"\n</code></pre>\n</blockquote>\n\n<p>Is repeated 3 times, save it and reuse for easier changing of the message in the future:</p>\n\n<pre><code>ASK_BET = \"Bet? (0 to quit, press 'Enter' to stay at $25) \"\n....\n\nstr_bet=input(ASK_BET) \n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> if (bet == -10):\n break\n\n win_lose = play_hand(player_name, bet)\n bank_balance+=win_lose\n\n print(f'Your bank balance: ${bank_balance}')\n\ndef input_bet(bet, money):\n correct = False\n while not correct:\n if (money &lt;=0):\n print('You ran out of money')\n return -10\n</code></pre>\n</blockquote>\n\n<p>you are using -10 as a special signal \"flag\" value, you should use <code>None</code> instead.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> correct = False\n while not correct:\n</code></pre>\n</blockquote>\n\n<p>You can just use <code>while True</code> and <code>break</code> or <code>return</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T19:45:47.323", "Id": "237581", "ParentId": "237577", "Score": "4" } }, { "body": "<p>The first thing I noticed was that <code>while</code> loop in <code>play_hand()</code>. It has too many conditions. I'd just do <code>while True:</code> and then exit with a <code>break</code>.</p>\n\n<p>You can do something similar in the other loop as well. This will make it so you don't have to repeat yourself so often and will significantly clean up your code.</p>\n\n<p>Also there's a few other things you can do: You can simplify your dealer's code by just having the dealer get to 17 immediately instead of drawing one and then waiting until the player ended their turn.</p>\n\n<p>You should move your over-21 check into the main <code>while</code> loop. And get rid of that <code>bust</code> variable, there's no need for it.</p>\n\n<p>And there's no need for a <code>new_card</code> variable. Just check the end of the list of the player's cards.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T23:51:46.530", "Id": "237594", "ParentId": "237577", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T19:23:10.927", "Id": "237577", "Score": "3", "Tags": [ "python" ], "Title": "Part 2 of blackjack game" }
237577
<p>I wrote a program that is able to perform calculations with matrices:</p> <p><strong>main.cpp</strong> (Just for test purposes)</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include "matrix.hpp" int main() { std::cout &lt;&lt; "Width (matrix 1):\n"; int width = getDimension(); std::cout &lt;&lt; "Height (matrix 1):\n"; int height = getDimension(); std::vector&lt;std::vector&lt;double&gt;&gt; matrix(height, std::vector&lt;double&gt; (width)); //Now, the user has to enter the matrix line by line, seperated by commas for(int i = 1; i &lt;= height; i++) { getUserInput(matrix, i, width); } //Output printMatrix(matrix); std::cout &lt;&lt; "\n"; std::cout &lt;&lt; "Determinant is " &lt;&lt; getDeterminant(matrix) &lt;&lt; "\n"; std::cout &lt;&lt; "\nMatrix * Matrix =\n"; printMatrix(getMultiplication(matrix, matrix)); std::cout &lt;&lt; "\nTransposed Matrix:\n"; printMatrix(getTranspose(matrix)); std::cout &lt;&lt; "\nCofactor-Matrix:\n"; printMatrix(getCofactor(matrix)); std::cout &lt;&lt; "\nInverse-Matrix:\n"; printMatrix(getInverse(matrix)); return 0; } </code></pre> <p><strong>matrix.cpp</strong> (responsible for the actual calculations)</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;math.h&gt; #include &lt;iomanip&gt; #include &lt;stdexcept&gt; #include "matrix.hpp" //Bareiss-Algorithm with O(n^3); not Laplace-expansion with O(n!) double getDeterminant(std::vector&lt;std::vector&lt;double&gt;&gt; vect) { for(int i = 0; i &lt; vect.size(); i++) { for(int j = i + 1; j &lt; vect.size(); j++) { for(int k = i + 1; k &lt; vect.size(); k++) { vect[j][k] = vect[j][k] * vect[i][i] - vect[j][i] * vect[i][k]; if(i != 0) { vect[j][k] /= vect[i - 1][i - 1]; } } } } return vect[vect.size() - 1][vect.size() - 1]; } //O(n^3) - much faster isn't possible std::vector&lt;std::vector&lt;double&gt;&gt; getMultiplication(const std::vector&lt;std::vector&lt;double&gt;&gt; matrix1, const std::vector&lt;std::vector&lt;double&gt;&gt; matrix2) { if(matrix1[0].size() != matrix2.size()) { throw std::runtime_error("Matrices cannot be multiplicated"); } int height1 = matrix1.size(); int width2 = matrix2[0].size(); int height2 = matrix2.size(); std::vector&lt;std::vector&lt;double&gt;&gt; solution(height1, std::vector&lt;double&gt; (width2)); //Formula for matrix-multiplication for(int i = 0; i &lt; height1; i++) { for(int k = 0; k &lt; width2; k++) { for(int j = 0; j &lt; height2; j++) { solution[i][k] = matrix1[i][j] * matrix2[j][k]; } } } return solution; } //O(n^2) - faster is not possible; std::vector&lt;std::vector&lt;double&gt;&gt; getTranspose(const std::vector&lt;std::vector&lt;double&gt;&gt; matrix1) { //Transpose-matrix: height = width(matrix), width = height(matrix) std::vector&lt;std::vector&lt;double&gt;&gt; solution(matrix1[0].size(), std::vector&lt;double&gt; (matrix1.size())); //Filling solution-matrix for(size_t i = 0; i &lt; matrix1.size(); i++) { for(size_t j = 0; j &lt; matrix1[0].size(); j++) { solution[j][i] = matrix1[i][j]; } } return solution; } std::vector&lt;std::vector&lt;double&gt;&gt; getCofactor(const std::vector&lt;std::vector&lt;double&gt;&gt; vect) { if(vect.size() != vect[0].size()) { throw std::runtime_error("Matrix is not quadratic"); } std::vector&lt;std::vector&lt;double&gt;&gt; solution(vect.size(), std::vector&lt;double&gt; (vect.size())); std::vector&lt;std::vector&lt;double&gt;&gt; subVect(vect.size() - 1, std::vector&lt;double&gt; (vect.size() - 1)); for(std::size_t i = 0; i &lt; vect.size(); i++) { for(std::size_t j = 0; j &lt; vect[0].size(); j++) { int p = 0; for(size_t x = 0; x &lt; vect.size(); x++) { if(x == i) { continue; } int q = 0; for(size_t y = 0; y &lt; vect.size(); y++) { if(y == j) { continue; } subVect[p][q] = vect[x][y]; q++; } p++; } solution[i][j] = pow(-1, i + j) * getDeterminant(subVect); } } return solution; } std::vector&lt;std::vector&lt;double&gt;&gt; getInverse(const std::vector&lt;std::vector&lt;double&gt;&gt; vect) { double det = getDeterminant(vect); if(det == 0) { throw std::runtime_error("Determinant is 0"); } std::vector&lt;std::vector&lt;double&gt;&gt; solution(vect.size(), std::vector&lt;double&gt; (vect.size())); solution = getTranspose(getCofactor(vect)); for(size_t i = 0; i &lt; vect.size(); i++) { for(size_t j = 0; j &lt; vect.size(); j++) { solution[i][j] *= (1/det); } } return solution; } int getDimension() { int dimension; std::cout &lt;&lt; "Please enter dimension of Matrix: "; std::cin &gt;&gt; dimension; std::cout &lt;&lt; "\n"; if(dimension &lt; 0 || std::cin.fail()) { std::cin.clear(); std::cin.ignore(); std::cout &lt;&lt; "ERROR: Dimension cannot be &lt; 0.\n"; return getDimension(); } return dimension; } void printMatrix(const std::vector&lt;std::vector&lt;double&gt;&gt; vect) { for(std::size_t i = 0; i &lt; vect.size(); i++) { for(std::size_t j = 0; j &lt; vect[0].size(); j++) { std::cout &lt;&lt; std::setw(8) &lt;&lt; vect[i][j] &lt;&lt; " "; } std::cout &lt;&lt; "\n"; } } void getUserInput(std::vector&lt;std::vector&lt;double&gt;&gt;&amp; vect, int i, int dimension) { std::string str = ""; std::cout &lt;&lt; "Enter line " &lt;&lt; i &lt;&lt; " only seperated by commas: "; std::cin &gt;&gt; str; std::cout &lt;&lt; "\n"; str = str + ','; std::string number = ""; int count = 0; for(std::size_t k = 0; k &lt; str.length(); k++) { if(str[k] != ',') { number = number + str[k]; } else if(count &lt; dimension) { if(number.find_first_not_of("0123456789.-") != std::string::npos) { std::cout &lt;&lt; "ERROR: Not only numbers entered.\n"; getUserInput(vect, i, dimension); break; } else if(number.find_first_not_of("0123456789-.") == std::string::npos) { vect[i - 1][count] = std::stod(number); number = ""; count++; } else { std::cout &lt;&lt; "ERROR: Not enough numbers entered.\n"; getUserInput(vect, i, dimension); break; } } else { std::cout &lt;&lt; "ERROR: Too many numbers entered.\n"; getUserInput(vect, i, dimension); break; } } } </code></pre> <p><strong>matrix.hpp</strong></p> <pre><code>#ifndef MATRIX_HPP #define MATRIX_HPP #include &lt;vector&gt; double getDeterminant(const std::vector&lt;std::vector&lt;double&gt;&gt; vect); std::vector&lt;std::vector&lt;double&gt;&gt; getMultiplication(const std::vector&lt;std::vector&lt;double&gt;&gt; matrix1, const std::vector&lt;std::vector&lt;double&gt;&gt; matrix2); std::vector&lt;std::vector&lt;double&gt;&gt; getTranspose(const std::vector&lt;std::vector&lt;double&gt;&gt; matrix1); std::vector&lt;std::vector&lt;double&gt;&gt; getCofactor(const std::vector&lt;std::vector&lt;double&gt;&gt; vect); std::vector&lt;std::vector&lt;double&gt;&gt; getInverse(const std::vector&lt;std::vector&lt;double&gt;&gt; vect); int getDimension(); void printMatrix(const std::vector&lt;std::vector&lt;double&gt;&gt; vect); void getUserInput(std::vector&lt;std::vector&lt;double&gt;&gt;&amp; vect, int i, int dimension); #endif </code></pre> <p>My questions:</p> <ul> <li>What's the runtime (O-notation) of <code>getCofactor()</code> and <code>getInverse()</code>?</li> <li>Are there more efficient ways to do this tasks?</li> <li>How to generally improve the code?</li> </ul>
[]
[ { "body": "<h1>Create a <code>class Matrix</code></h1>\n\n<p>Instead of having a vector of vectors, and have global functions that manipulate those, create a <code>class Matrix</code> and add member functions to it to manipulate matrices. You should probably also create overloads for arithmetic operations, so you can write things like <code>auto matrix3 = matrix1 + matrix2;</code></p>\n\n<p>Have a look at <a href=\"https://stackoverflow.com/questions/1380371/what-are-the-most-widely-used-c-vector-matrix-math-linear-algebra-libraries-a\">existing C++ matrix libraries</a> to see what is possible.</p>\n\n<h1>Complexity of <code>getCofactor()</code> and <code>getInverse()</code></h1>\n\n<p>In <code>getCofactor()</code>, you have four nested <code>for</code>-loops that only skip iterations if <code>x == i</code> or <code>y == j</code>, so that would make it O(N^4). However, you are calling <code>getDeterminant()</code> inside the second outer-most loop on a subvector of size (N-1)^2, so that would make it O(N^2 * (N-1)^3) = O(N^5).</p>\n\n<p>In <code>getInverse()</code>, the complexity is dominated by the call to <code>getCofactor()</code>, so it is also O(N^5). This is really bad for large matrices, since the Gauss-Jordan method which you should learn in first year Mathematics studies is just O(N^3).</p>\n\n<p>Wikipedia has a <a href=\"https://en.wikipedia.org/wiki/Computational_complexity_of_mathematical_operations#Matrix_algebra\" rel=\"nofollow noreferrer\">list of matrix algebra algorithm</a> complexities that you can check to see what is possible. Note however that the best looking algorithms with weird exponents are probably hard to implement and might actually be much less efficient for small matrices than the simpler algorithms. The best algorithm for you therefore depends on what sizes of matrices your programs are going to work with.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T22:26:54.283", "Id": "465965", "Score": "0", "body": "Thanks for your reply. I just noticed that the getDeterminant-function sometimes returns \"-nan\". What does that mean? How can I fix it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T06:37:38.573", "Id": "465990", "Score": "0", "body": "A [nan](https://en.wikipedia.org/wiki/NaN) is most likely the result of a floating point division by zero." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T21:50:48.867", "Id": "237590", "ParentId": "237578", "Score": "2" } } ]
{ "AcceptedAnswerId": "237590", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T19:27:55.283", "Id": "237578", "Score": "1", "Tags": [ "c++", "matrix", "mathematics" ], "Title": "C++ matrix calculator" }
237578
<p>For my programming class, at the start of the semester before we learned about object oriented coding, I was supposed to make a small program that searches through a bunch of files, being graded on useability.</p> <pre class="lang-py prettyprint-override"><code>from os import walk from time import time SEPARATORS = (" ", "-", "_", ":", "|", "~") REMOVABLES = (".", ",", ";", "(", ")", "[", "]", "{", "}", "!", "?", "'", '"', "&lt;", "&gt;", "/", "`") def inputs() -&gt; [str, int]: """Takes the constraints from the user for the search""" term = input("Please enter your search term: ").lower() # Asks for the number of results the the user would like to see, and makes sure it is an int while True: try: result_count = int(input("How many results would you like to find: ")) break except ValueError: print("Please enter only a whole number") return term, result_count def data_to_dictionary() -&gt; dict: """Turns the raw data in the text files into a dict""" data = {} # Creates a list of all the file names in the specified folder, # then opens those files and put the name and data of those files in a dict for path, path_name, files in walk("Data"): for file_name in files: with open(".\\Data\\" + file_name) as file: file_data = file.read() data[file_name[:-4]] = file_data # The [:-4] is to remove the .txt extension return data def word_matcher(term, data: dict, results: list, result_count: int) -&gt; list: """Main search loop""" # If there is only one term, look through it once if type(term) == str: for data_item in data: # If the term is in one of the titles, add to results if term in data_item.lower() and data_item not in results: results.append(data_item) if result_count &gt; len(results): for data_item in data: # If the term is in content of a document, and the document has not already been added, add to results if term in data[data_item].lower() and data_item not in results: results.append(data_item) elif type(term) == list: for each_term in term: for data_item in data: # If the term is in one of the titles, add to results if each_term in data_item.lower() and data_item not in results: results.append(data_item) for data_item in data: # If the term is in content of a document, and the document has not already been added, add to results if each_term in data[data_item].lower() and data_item not in results: results.append(data_item) # Should never run else: print("Something went very wrong, please restart.") while True: pass return results def word_splitter(term: str): """Splits the term""" # Removes items that may clog the search for item in REMOVABLES: while item in term: term = term.replace(item, "") # If there are things that separates words in the term, separate them for item in SEPARATORS: if item in term: term = term.split(item) # If there is empty str items in the list, remove them if type(term) == list: for item in term: if item == "": term.remove(item) return term def result_print(result_list: list, result_count: int, search_start_time: float): print("") # All of these are for spacing alone # If no results are found, loop until user closes program if not result_list: print("No Results Found") while True: pass # Removes results, so that it is only the number of results the user specified result_list = result_list[0:result_count] # Prints out all the results one line at a time for item in enumerate(result_list): print(f"{item[0] + 1}: {item[1]}") print("") print(f"It took {round((time() - search_start_time), 1)} seconds to find these results.") print("") while True: try: result_choice = int(input("Which file would you like to open. Put the number by its name: ")) print("") with open(f".\\Data\\{result_list[result_choice - 1]}.txt") as file: print(file.read()) print("") # If the user does not want to look at another article, break our of the loop, allowing the function to end if (input("Would you like to open another article? (Y/N): ").lower()) == "n": break # If the input provided by the user is not a number, or a possible number, repeat the code except (ValueError, IndexError): print("Please only enter a number that is listed next to the file names.") print("") results = [] term, result_count = inputs() data = data_to_dictionary() search_start_time = time() results = word_matcher(term, data, results, result_count) # Only does secondary check if max results has not been found if len(results) &lt; result_count: term = word_splitter(term) new_results = word_matcher(term, data, results, result_count) result_print(results, result_count, search_start_time) </code></pre> <p>This program searches through a bunch randomly chosen (and some not randomly chosen) Wikipedia articles that I hand copied the title and intro paragraph from. </p> <p>This is my first time making something that feels like it should be made more efficient. I don't know any efficiency techniques, so any advice there would be great. If you do add anything in this vein that are important things that I know about, please link some documentation for it.</p> <p>Also, this is my first time touching <code>os</code> and dictionaries so if my implementation of <code>walk()</code> and <code>data</code> might not be the best.</p> <p>Finally is there any problems with the general layout of the code or any other small things, like places were I should follow general practices if I don't?</p> <p><a href="https://github.com/K00lmans/Search-Engine/tree/11029868e731ac826f0a47018428e8c166e4ae88" rel="nofollow noreferrer">Full code + files hear</a></p> <p>Last night right after I finished the code, I watched <a href="https://www.youtube.com/watch?v=RGuJga2Gl_k" rel="nofollow noreferrer">this video</a> and now the codes purpose feels really silly. ¯ \ _ (ツ) _ / ¯</p>
[]
[ { "body": "<p>Looks pretty good to me! I liked that you used type hints.</p>\n\n<p>A few tips:</p>\n\n<ul>\n<li>The library <code>pathlib</code> is very good for path manipulation. You'll still need <code>os.walk</code> in this case, but you can use it to get the full filepath, just the filename, the stem (filename without extension) or the suffix (extension alone). I use it a lot.</li>\n<li>You could use <a href=\"https://docs.python.org/2/library/re.html#re.sub\" rel=\"nofollow noreferrer\"><code>re.sub</code></a> to take care of the separators and the removables. It might take some time to learn about regular expressions (short: regex), but it's worth the effort.</li>\n<li>It's good practice to use <code>isinstance(object, type)</code> instead of <code>type(object) == type</code>.</li>\n<li>It's also good practice to put the code in the bottom under <code>def(main)</code> and call <code>main()</code> under <code>if __name__ == \"__main__\"</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T05:49:53.027", "Id": "466102", "Score": "1", "body": "OP used type hints incorrectly. Instead of `-> [type1, type2]` it should have been `from typing import Tuple, Dict` and `-> Tuple[type1, type2]` and `Dict[keytype, valuetype]` instead of `-> dict`. Type hinting is usually pretty boring grunt work but this should still be pointed out" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T09:29:30.417", "Id": "237617", "ParentId": "237582", "Score": "2" } }, { "body": "<h2>Naming</h2>\n\n<p>Function names usually read nicely as verbs, since they \"do\" stuff. So <code>word_splitter()</code> might be a good name for a class, some reusable thing that splits words, but as a function it reads more descriptively as <code>split_word()</code> or <code>split_term()</code> (or maybe <code>tokenize_term()</code>). Similarly, <code>result_print()</code> reads more smoothly as <code>print_results()</code>. It's a command, it's <em>doing</em> something. <code>data_to_dictionary()</code> is ok, but <code>load_data()</code> or <code>load_index()</code> are more descriptive.</p>\n\n<p>Also, generally, lists don't need \"list\" in the name. Parameters like <code>result_list: list</code>, especially with type annotations, usually imply that they are a list if they are plural, like <code>results: list</code>.</p>\n\n<h2>Optimizations</h2>\n\n<ul>\n<li>In <code>word_matcher()</code>, you repeatedly call <code>.lower()</code> on the contents of each document. Since you're only printing titles, not document contents, you could convert each document's text to lowercase once during the initial loading, and then not need to do so during the query/ies. This is appealing because the document contents are almost certainly much longer than your search queries, so cutting out extra loops is nice.</li>\n</ul>\n\n<h2>Code</h2>\n\n<p><code>word_matcher()</code></p>\n\n<ul>\n<li><p>Notice how the behaviour for when <code>term</code> is a string vs a list is identical, aside from the loop. If you make sure it's always a list, by starting the function with</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if isinstance(term, basestring):\n term = [term]\n</code></pre>\n\n<p>then you only need to handle the list-looping case, and can remove the first if-branch.</p>\n\n<p>Alternatively, you could make <code>word_matcher()</code> only take in single terms, and move the looping into the calling function.</p>\n\n<p>Either way, it would be nice for both readability and future maintenance to remove that duplication.</p></li>\n<li><p>Generally <code>isinstance()</code> is preferable over a direct comparison with <code>type()</code>, because it will play nicely with inheritance. This doesn't matter for this program, because you're not subclassing <code>str</code> or anything like that, but it's nice in general.</p></li>\n</ul>\n\n<hr>\n\n<p><code>result_print()</code></p>\n\n<ul>\n<li><pre><code>for item in enumerate(result_list):\n print(f\"{item[0] + 1}: {item[1]}\")\n</code></pre>\n\nColloquially, this would use unpacking:\n\n<pre><code>for index, result in enumerate(result_list):\n print(f\"{index + 1}: {result}\")\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p><code>data_to_dictionary()</code></p>\n\n<ul>\n<li>This is fine. If you have many thousands of files (or it takes more than a second or two to load), you could consider using a <a href=\"https://docs.python.org/3/library/concurrent.futures.html\" rel=\"nofollow noreferrer\">ThreadPoolExecutor</a> to read the data files concurrently using multiple threads.</li>\n</ul>\n\n<hr>\n\n<pre><code> # If no results are found, loop until user closes program\n if not result_list:\n print(\"No Results Found\")\n while True:\n pass\n</code></pre>\n\n<p>Looping infinitely with <code>while True: pass</code> is just going to heat up the room by occupying a CPU. If there is nothing more to do, quit. The user will notice. Use <code>sys.exit()</code> in a quick script like this, or return from the function.</p>\n\n<hr>\n\n<h2>Considerations</h2>\n\n<h3>Ranking / Relevance</h3>\n\n<p>This is a search tool. If the volume of indexed data grows, you may want to order the results by some kind of measure of relevance, so that users can find their stuff more effectively. Maybe a match in the title is worth 3x more than a match in the body. Maybe when the term contains multiple words, results matching all of the term words are scored higher (and shown before) results matching just one word.</p>\n\n<p>Search is a big field with endless optimizations. If this is interesting, check out <em>Relevant Search</em> by Turnbull and Berryman (2016), or stuff about search engine indexing and natural language processing.</p>\n\n<h3>Indexing</h3>\n\n<p>Right now, a search needs you to iterate through your entire index. At the cost of increased upfront processing time, and memory usage, you could do some pre-processing, and construct some more efficient indexes for faster searches.</p>\n\n<p>Your <code>data</code> dict is a mapping of document name → contents. You could make an <em>inverted index</em> of term → document name, effectively pre-computing the results of any search term. Here is a simple example, you might also want to store things like the number of times the term appears in the document, to weigh into rankings:</p>\n\n<pre><code>from collections import defaultdict\nimport itertools, typing\n\ndef make_inverted_index(data: typing.Dict[str, str]) -&gt; typing.Dict[str, typing.Set[str]]:\n terms = defaultdict(set)\n\n for doc_name, contents in data.items():\n body = [contents.lower()]\n for sep in SEPARATORS:\n body = list(itertools.chain.from_iterable(s.split(sep) for s in body)\n for term in body:\n terms[term].add(doc_name)\n\n return terms\n</code></pre>\n\n<p>and then, during queries, you can easily check if the query term is a key in the inverted index dict, without scanning all the contents.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T19:18:40.943", "Id": "466488", "Score": "0", "body": "Can I not just use \"str\" instead of \"basestring\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T19:26:07.237", "Id": "466490", "Score": "0", "body": "Also, it currently has some light sorting, were if the term is in the title it comes first and then if the whole term is found before it is split it comes first." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T10:03:18.690", "Id": "237620", "ParentId": "237582", "Score": "3" } } ]
{ "AcceptedAnswerId": "237620", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T20:06:35.420", "Id": "237582", "Score": "4", "Tags": [ "python", "performance", "beginner", "python-3.x", "search" ], "Title": "Search engine that looks through files" }
237582
<p>It's a web application. It should provide a service for entering data. Data is then evaluated and uses itself another service.</p> <p>It was part of an interview process where I was given that task to solve. The feedback was that it was not sufficient and I got rejected. <strong>But I don't know what exactly they don't like</strong>. Could you please review it and give me improvement suggestions, please?</p> <p>pom.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;2.2.4.RELEASE&lt;/version&gt; &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;groupId&gt;de.interview.fizzbuzz&lt;/groupId&gt; &lt;artifactId&gt;demo&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;name&gt;demo&lt;/name&gt; &lt;description&gt;Demo project for Spring Boot&lt;/description&gt; &lt;properties&gt; &lt;java.version&gt;1.8&lt;/java.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.h2database&lt;/groupId&gt; &lt;artifactId&gt;h2&lt;/artifactId&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.projectlombok&lt;/groupId&gt; &lt;artifactId&gt;lombok&lt;/artifactId&gt; &lt;optional&gt;true&lt;/optional&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;org.junit.vintage&lt;/groupId&gt; &lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit-dep&lt;/artifactId&gt; &lt;version&gt;4.8.2&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>Controller</p> <pre><code>package de.interview.fizzbuzz.demo.controller; import de.interview.fizzbuzz.demo.model.FizzBuzzInput; import de.interview.fizzbuzz.demo.model.FizzBuzzOutput; import de.interview.fizzbuzz.demo.model.WorldClock; import lombok.NoArgsConstructor; import lombok.NonNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import javax.validation.Valid; import java.util.Collection; import java.util.SortedMap; import java.util.TreeMap; @NoArgsConstructor @RestController @RequestMapping("/api") public class FizzBuzzController { private final Logger log = LoggerFactory.getLogger(FizzBuzzController.class); private SortedMap&lt;Integer, FizzBuzzOutput&gt; fizzBuzzOutputsRepo = new TreeMap&lt;Integer, FizzBuzzOutput&gt;(); @GetMapping("/allFizzBuzzItems") public Collection&lt;FizzBuzzOutput&gt; allFizzBuzzItems() { System.out.println(fizzBuzzOutputsRepo.values()); return fizzBuzzOutputsRepo.values(); } @PutMapping("/fizzbuzz") public void createFizzBuzzItem(@Valid @RequestBody @NonNull FizzBuzzInput fizzBuzzInput) { Integer input = Integer.parseInt(fizzBuzzInput.getValue()); if (input &lt;= 0) { return; } String value = BusinessLogic.fizzBuzzOf(Integer.parseInt(fizzBuzzInput.getValue())); String timestamp = getTimestampFrom("http://worldclockapi.com/api/json/cet/now"); FizzBuzzOutput fizzBuzzOutput = new FizzBuzzOutput(input, value, timestamp); fizzBuzzOutputsRepo.put(input, fizzBuzzOutput); } // delete all @DeleteMapping("/fizzbuzz/all") public void deleteAllFizzBuzzItems() { fizzBuzzOutputsRepo.clear(); } public String getTimestampFrom(String serviceURL) { RestTemplate restTemplate = new RestTemplate(); WorldClock result = restTemplate.getForObject(serviceURL, WorldClock.class); return result.getCurrentDateTime(); } } </code></pre> <p>The whole project: <a href="https://github.com/kodingreview/1" rel="nofollow noreferrer">https://github.com/kodingreview/1</a></p>
[]
[ { "body": "<ul>\n<li><code>fizzBuzzOutputsRepo</code> is an in-memory map and there is no data persistence. So if the web server crashes, then there will be data loss. </li>\n<li>Even if data persistence is out of scope for the interview question, by default a web server works in a multi-user environment. However, there is no synchronization method to protect the data integrity of <code>fizzBuzzOutputsRepo</code>. The simplest way is to use <code>syncronize</code> keyword when declaring <code>fizzBuzzOutputsRepo</code>. </li>\n<li>Java has <code>java.time.LocalDateTime</code> library which can give you the current system clock time. It does seem like an overly heavy approach to make an HTTP request to some external endpoint to just get current date time. Because that introduces complexity such as managing outgoing HTTP connection pool, dealing with upstream connection timeout etc. </li>\n<li>From API design perspective, the common practice is to version the API and use the resource name in URL: \nFor instance <code>api/v1/fizzbuzz/</code> is the common part of the route. For GET and DELETE, <code>api/v1/fizzbuzz/{fizzbuzz_id}/</code> means operating on a single resource while <code>api/v1/fizzbuzz/</code> means operating on all resources. Although it is generally not good practice to support operation on all resources because as the amount of data increases, it puts increasing demand on a single web server and other parts of the stack such as the database that stores the data. </li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T03:22:42.973", "Id": "237600", "ParentId": "237584", "Score": "6" } }, { "body": "<p>From API design perspective let me pitch in</p>\n\n<ol>\n<li>Have a base path and then have the resource name in the\ncorresponding request mapping.\n\n<ul>\n<li>Base path /api </li>\n<li>version /v1 </li>\n<li>request mapping /fizzBuzz</li>\n</ul></li>\n<li>Add HTTP status code in response. As simple as 200 for OK and 400 Bad request should be fine for a sample API. Further reading: <a href=\"https://httpstatuses.com/\" rel=\"nofollow noreferrer\">HTTP status LIST</a></li>\n<li><p>Add <a href=\"https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api\" rel=\"nofollow noreferrer\">Swagger Docs</a> it's pretty straightforward too.</p>\n\n<p>Maybe once your API is up then you can further improve them using the next steps</p></li>\n<li>Adding Custom Exception.</li>\n<li>Following <a href=\"https://martinfowler.com/articles/richardsonMaturityModel.html\" rel=\"nofollow noreferrer\">RMM</a> for API design improvement.</li>\n<li>Adding Comments for code quality :-).</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T07:25:34.793", "Id": "237611", "ParentId": "237584", "Score": "5" } }, { "body": "<h1>PUT vs. POST</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>@PutMapping(\"/fizzbuzz\")\npublic void createFizzBuzzItem(...)\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT\" rel=\"nofollow noreferrer\"><code>PUT</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST\" rel=\"nofollow noreferrer\"><code>POST</code></a> can be used to create new resources.</p>\n\n<p>The difference is that <code>PUT</code> is <a href=\"https://en.wikipedia.org/wiki/Idempotence\" rel=\"nofollow noreferrer\">idempotent</a> which means:</p>\n\n<blockquote>\n <p>calling it once or several times successively has the same effect</p>\n</blockquote>\n\n<p>But your fizzbuzz implementation has a time stemp that gets updated:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>FizzBuzzOutput fizzBuzzOutput = new FizzBuzzOutput(input, value, timestamp);\n</code></pre>\n</blockquote>\n\n<p>This is the reason why <code>createFizzBuzzItem</code> is not idempotent and should be a <code>POST</code> instead of <code>PUT</code>.</p>\n\n<hr>\n\n<h1>The Controller</h1>\n\n<p>The <code>FizzBuzzController</code> looks like it is the heart of the application: </p>\n\n<ul>\n<li>it stores data</li>\n<li>has some logic</li>\n</ul>\n\n<p>A <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">controller</a> only receives user input, validates it and let the model operate on the incoming data.</p>\n\n<p>You already did a good job in <code>createFizzBuzzItem</code> where the input gets validated by <code>if (input &lt;= 0)</code> and then the business logic does some work via <code>BusinessLogic.fizzBuzzOf(...)</code>.</p>\n\n<p>But since the controller persist data beside the controlling part (what violates the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>) some business logic is needed inside the controller like:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>FizzBuzzOutput fizzBuzzOutput = new FizzBuzzOutput(input, value, timestamp);\nfizzBuzzOutputsRepo.put(input, fizzBuzzOutput);\n</code></pre>\n \n <pre class=\"lang-java prettyprint-override\"><code>fizzBuzzOutputsRepo.clear();\n</code></pre>\n \n <pre class=\"lang-java prettyprint-override\"><code>return fizzBuzzOutputsRepo.values();\n</code></pre>\n</blockquote>\n\n<p>The controller should know nothing about the persistence and <a href=\"https://stackoverflow.com/a/1015853/8339141\">should only ask the model (<code>BusinessLogic</code>) for data</a>, like:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@PutMapping(\"/fizzbuzz\")\npublic void createFizzBuzzItem(@Valid @RequestBody @NonNull FizzBuzzInput fizzBuzzInput) {\n Integer input = Integer.parseInt(fizzBuzzInput.getValue());\n if (input &lt;= 0) {\n return;\n }\n\n return BusinessLogic.fizzBuzzOf(Integer.parseInt(fizzBuzzInput.getValue());\n}\n</code></pre>\n\n<pre class=\"lang-java prettyprint-override\"><code>@DeleteMapping(\"/fizzbuzz\")\npublic void deleteAllFizzBuzzItems() {\n BusinessLogic.deleteAll();\n}\n</code></pre>\n\n<hr>\n\n<h1>Data Access Object</h1>\n\n<p><a href=\"https://www.quora.com/How-do-you-apply-chunking-to-learning-programming?share=1\" rel=\"nofollow noreferrer\">Human work with abstractions</a> and naming is a good way to abstract by chunking thinks.</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public void createFizzBuzzItem(@Valid @RequestBody @NonNull FizzBuzzInput fizzBuzzInput)\n</code></pre>\n \n <pre class=\"lang-java prettyprint-override\"><code>FizzBuzzOutput fizzBuzzOutput = new FizzBuzzOutput(input, value, timestamp);\n</code></pre>\n</blockquote>\n\n<p>First what I like is that you think about in- and output. But there is already a known abstraction for in- and output and this is the <a href=\"https://en.wikipedia.org/wiki/Data_access_object\" rel=\"nofollow noreferrer\">Data Access Object (DTO)</a>. The bad with the naming <code>fizzBuzzInput</code> and <code>fizzBuzzOutput</code> is that a reader of your code does not know if this are DTOs and have to verify it by scroll through the code what makes reading code more difficult than only working with abstractions.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public void createFizzBuzzItem(@Valid @RequestBody @NonNull CreateDTO dto)\n</code></pre>\n\n<hr>\n\n<h1>Naming</h1>\n\n<p>Additional your naming is redundant. When I search for the word <em>fizzbuzz</em> inside the controller I get more than 20 results back.</p>\n\n<p>It's suffices naming the class <code>FizzBuzzController</code> and from there you know by the context of the class that you deal with <em>fizzbuzz</em>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class FizzBuzzController {\n\n // ..\n\n // @...\n public Collection&lt;FizzBuzzOutput&gt; findAll() { /* ... */ }\n\n // @...\n public void create(@Valid @RequestBody @NonNull CreateDTO dto) {/* ... */ }\n\n // @...\n public void deleteAll() { /*...*/ }\n}\n</code></pre>\n\n<hr>\n\n<h1>A Service</h1>\n\n<p>Its common case to append the class that holdes the business logic with <code>Service</code> as a suffix like: <code>FizzBuzzService</code>. A service takes a dto and returns a dto.</p>\n\n<p>For instance inside <code>createFizzBuzzItem</code>:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>String value = BusinessLogic.fizzBuzzOf(Integer.parseInt(fizzBuzzInput.getValue()));\n</code></pre>\n</blockquote>\n\n<pre class=\"lang-java prettyprint-override\"><code>String value = fizzBuzzService.craeteBy(dto);\n</code></pre>\n\n<hr>\n\n<h1>Duplication</h1>\n\n<p>Code duplication can lead to code that is <a href=\"https://stackoverflow.com/a/4226299/8339141\">hard to maintain</a>.</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>Integer.parseInt(fizzBuzzInput.getValue())\n</code></pre>\n</blockquote>\n\n<p>This line of code is two times inside <code>createFizzBuzzItem</code>.</p>\n\n<p>Additional I do not understand why you have to parse it. Can't <code>FizzBuzzInput</code> holdes a integer instead of a string value like:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>class FizzBuzzIput {\n final int value;\n}\n</code></pre>\n\n<hr>\n\n<h1>Unused Code</h1>\n\n<p>The <code>log</code> gets never used and could be deleted if you do not want to log something.</p>\n\n<hr>\n\n<h1>Example</h1>\n\n<p>A refactoring could look like</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@RequestMapping(\"/api/fizzbuzz\")\n@RestController\npublic class FizzBuzzController {\n\n private final FizzBuzzService service = new FizzBuzzService();\n\n @GetMapping\n public Collection&lt;SavedDTO&gt; findAll() {\n return service.findAll();\n }\n\n @PostMapping\n public ... createFizzBuzzItem(@Valid @RequestBody @NonNull CreateDTO dto) {\n if (dto.value &lt;= 0) {\n // HTTP Bad Request (400)\n // accepts only values that are greater 0\n }\n\n return service.createBy(dto);\n }\n\n @DeleteMapping\n public ... deleteAll() {\n service.deleteAll();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T08:22:52.697", "Id": "237612", "ParentId": "237584", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T20:28:58.567", "Id": "237584", "Score": "1", "Tags": [ "java", "rest", "spring", "maven" ], "Title": "Spring boot application web service" }
237584
<p>I am trying to implement <a href="https://arxiv.org/pdf/1712.04604" rel="nofollow noreferrer">Deep Quaternion Networks</a>. I was able to implement the batch normalization technique. But it requires a lot of GPU memory. Is there any way I can optimize the code provided below?</p> <pre class="lang-py prettyprint-override"><code> class MyQuaternionBatchNorm2d(torch.nn.Module): def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True): super(MyQuaternionBatchNorm2d, self).__init__() self.num_features = num_features self.qnum_features = num_features//4 self.eps = eps self.momentum = momentum self.affine = affine self.track_running_stats = track_running_stats if self.affine: self.weight = torch.nn.Parameter(torch.Tensor(self.qnum_features, 10)) self.bias = torch.nn.Parameter(torch.Tensor(num_features)) else: self.register_parameter('weight', None) self.register_parameter('bias', None) if self.track_running_stats: self.register_buffer('running_mean', torch.zeros(self.qnum_features,4)) self.register_buffer('running_covar', torch.zeros(self.qnum_features,10)) self.running_covar[:,0] = 1/ np.sqrt(4) self.running_covar[:,1] = 1/ np.sqrt(4) self.running_covar[:,2] = 1/ np.sqrt(4) self.running_covar[:,3] = 1/ np.sqrt(4) self.register_buffer('num_batches_tracked', torch.tensor(0, dtype=torch.long)) else: self.register_buffer('running_mean',None) self.register_buffer('running_covar', None) self.register_parameter('num_batches_tracked', None) self.reset_parameters() def reset_running_stats(self): if self.track_running_stats: self.running_mean.zero_() self.running_covar.zero_() self.running_covar[:,0] = 1/ np.sqrt(4) self.running_covar[:,1] = 1/ np.sqrt(4) self.running_covar[:,2] = 1/ np.sqrt(4) self.running_covar[:,3] = 1/ np.sqrt(4) self.num_batches_tracked.zero_() def reset_parameters(self): self.reset_running_stats() if self.affine: torch.nn.init.zeros_(self.weight) torch.nn.init.constant_(self.weight[:,0], 1/ np.sqrt(4)) torch.nn.init.constant_(self.weight[:,4], 1/ np.sqrt(4)) torch.nn.init.constant_(self.weight[:,7], 1/ np.sqrt(4)) torch.nn.init.constant_(self.weight[:,9], 1/ np.sqrt(4)) torch.nn.init.zeros_(self.bias) def _check_input_dim(self, input): if input.dim() != 4: raise ValueError('expected 4D input (got {}D input)' .format(input.dim())) @staticmethod def _decomposition_v1(r,i,j,k,Vrr, Vri, Vrj, Vrk, Vii, Vij, Vik, Vjj, Vjk, Vkk): Wrr = torch.sqrt(Vrr) Wri = (1.0 / Wrr) * (Vri) Wii = torch.sqrt((Vii - (Wri.pow(2)))) Wrj = (1.0 / Wrr) * (Vrj) Wij = (1.0 / Wii) * (Vij - (Wri*Wrj)) Wjj = torch.sqrt((Vjj - (Wij.pow(2) + Wrj.pow(2)))) Wrk = (1.0 / Wrr) * (Vrk) Wik = (1.0 / Wii) * (Vik - (Wri*Wrk)) Wjk = (1.0 / Wjj) * (Vjk - (Wij*Wik + Wrj*Wrk)) Wkk = torch.sqrt((Vkk - (Wjk.pow(2) + Wik.pow(2) + Wrk.pow(2)))) cat_W_1 = torch.cat([Wrr, Wri, Wrj, Wrk]) cat_W_2 = torch.cat([Wri,Wii, Wij, Wik]) cat_W_3 = torch.cat([Wrj, Wij, Wjj, Wjk]) cat_W_4 = torch.cat([Wrk, Wik, Wjk, Wkk]) output = cat_W_1[None,:,None,None] * r.repeat(1,4,1,1) + cat_W_2[None,:,None,None] * i.repeat(1,4,1,1) \ + cat_W_3[None,:,None,None] * j.repeat(1,4,1,1) + cat_W_4[None,:,None,None] * k.repeat(1,4,1,1) return output def forward(self, input): self._check_input_dim(input) r,i,j,k = torch.chunk(input, 4, dim=1) exponential_average_factor = 0.0 if self.training and self.track_running_stats: if self.num_batches_tracked is not None: self.num_batches_tracked += 1 if self.momentum is None: # use cumulative moving average exponential_average_factor = 1.0 / float(self.num_batches_tracked) else: # use exponential moving average exponential_average_factor = self.momentum # calculate running estimates if self.training: mean_r, mean_i, mean_j, mean_k = r.mean([0, 2, 3]),i.mean([0, 2, 3]),j.mean([0, 2, 3]),k.mean([0, 2, 3]) n = input.numel() / input.size(1) mean = torch.stack((mean_r, mean_i, mean_j, mean_k), dim=1) # update running mean with torch.no_grad(): self.running_mean = exponential_average_factor * mean + (1 - exponential_average_factor) * self.running_mean r = r-mean_r[None, :, None, None] i = i-mean_i[None, :, None, None] j = j-mean_j[None, :, None, None] k = k-mean_k[None, :, None, None] Vrr = (r.pow(2).mean([0, 2, 3])) + self.eps Vii = (i.pow(2).mean([0, 2, 3])) + self.eps Vjj = (j.pow(2).mean([0, 2, 3])) + self.eps Vkk = (k.pow(2).mean([0, 2, 3])) + self.eps Vri = ((r*i).mean([0, 2, 3])) Vrj = ((r*j).mean([0, 2, 3])) Vrk = ((r*k).mean([0, 2, 3])) Vij = ((i*j).mean([0, 2, 3])) Vik = ((i*k).mean([0, 2, 3])) Vjk = ((j*k).mean([0, 2, 3])) with torch.no_grad(): self.running_covar[:,0] = exponential_average_factor * Vrr * n / (n - 1) + (1 - exponential_average_factor) * self.running_covar[:,0] self.running_covar[:,1] = exponential_average_factor * Vii * n / (n - 1) + (1 - exponential_average_factor) * self.running_covar[:,1] self.running_covar[:,2] = exponential_average_factor * Vjj * n / (n - 1) + (1 - exponential_average_factor) * self.running_covar[:,2] self.running_covar[:,3] = exponential_average_factor * Vkk * n / (n - 1) + (1 - exponential_average_factor) * self.running_covar[:,3] self.running_covar[:,4] = exponential_average_factor * Vri * n / (n - 1) + (1 - exponential_average_factor) * self.running_covar[:,4] self.running_covar[:,5] = exponential_average_factor * Vrj * n / (n - 1) + (1 - exponential_average_factor) * self.running_covar[:,5] self.running_covar[:,6] = exponential_average_factor * Vrk * n / (n - 1) + (1 - exponential_average_factor) * self.running_covar[:,6] self.running_covar[:,7] = exponential_average_factor * Vij * n / (n - 1) + (1 - exponential_average_factor) * self.running_covar[:,7] self.running_covar[:,8] = exponential_average_factor * Vik * n / (n - 1) + (1 - exponential_average_factor) * self.running_covar[:,8] self.running_covar[:,9] = exponential_average_factor * Vjk * n / (n - 1) + (1 - exponential_average_factor) * self.running_covar[:,9] else: mean = self.running_mean Vrr = self.running_covar[:,0]+self.eps Vii = self.running_covar[:,1]+self.eps Vjj = self.running_covar[:,2]+self.eps Vkk = self.running_covar[:,3]+self.eps Vri = self.running_covar[:,4]+self.eps Vrj = self.running_covar[:,5]+self.eps Vrk = self.running_covar[:,6]+self.eps Vij = self.running_covar[:,7]+self.eps Vik = self.running_covar[:,8]+self.eps Vjk = self.running_covar[:,9]+self.eps r = r-mean[None,:,0,None,None] i = i-mean[None,:,1,None,None] j = j-mean[None,:,2,None,None] k = k-mean[None,:,3,None,None] # standardized_output input = self._decomposition_v1(r,i,j,k, Vrr, Vri, Vrj, Vrk, Vii, Vij, Vik, Vjj, Vjk, Vkk) if self.affine: r,i,j,k = torch.chunk(input, 4, dim=1) cat_gamma_1 = torch.cat([self.weight[:,0], self.weight[:,1], self.weight[:,2], self.weight[:,3]]) cat_gamma_2 = torch.cat([self.weight[:,1], self.weight[:,4], self.weight[:,5], self.weight[:,6]]) cat_gamma_3 = torch.cat([self.weight[:,2], self.weight[:,5], self.weight[:,7], self.weight[:,8]]) cat_gamma_4 = torch.cat([self.weight[:,3], self.weight[:,6], self.weight[:,8], self.weight[:,9]]) input = cat_gamma_1[None,:,None,None] * r.repeat(1,4,1,1) \ + cat_gamma_2[None,:,None,None] * i.repeat(1,4,1,1) \ + cat_gamma_3[None,:,None,None] * j.repeat(1,4,1,1) \ + cat_gamma_4[None,:,None,None] * k.repeat(1,4,1,1) \ + self.bias[None, :, None, None] return input </code></pre> <p>I will explain the forward section. So the basic formula for batch normalization is <code>x* = (x - E[x]) / sqrt(var(x))</code>, where <code>x*</code> is the new value of a single component, <code>E[x]</code> is its mean within a batch and <code>var(x)</code> is its variance within a batch.</p> <p>However, as it is quaternion batch normalization,it has 4 parts <code>r</code> which is the real part and <code>i, j, and k</code>, are the imaginary part.</p> <p>The equation extends to <code>x* = W(x - E[x]) / (var(x))</code>. <code>W</code> is one of the matrices from the Cholesky decomposition of <code>V^-1</code> where <code>V</code> is the variance.In the code,<code>E[x]</code> is computed using the <code>mean</code> variable. V is computed in <code>Vxy</code> and <code>V^-1</code> i.e. <code>W</code> is computed in the <code>_decomposition_v1</code> function. This is applied to the input.</p> <p>Finally, that formula further extends to <code>x** = gamma * x* + beta</code>, where <code>x**</code> is the final normalized value. <code>gamma</code> i.e. <code>cat_gamma_x</code> and <code>beta</code> i.e. <code>self.beta</code> are learned per layer.</p> <p>Note: The num_features need to be in multiples of 4.</p> <p>Thank you, Shreyas</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T21:17:01.420", "Id": "465955", "Score": "0", "body": "Please tell us more about what the code is actually supposed to accomplish. Can you summarize the goal of the code? Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T03:28:21.113", "Id": "465981", "Score": "2", "body": "I edited the question. Please take a look and let me know if you need more information. Thank you." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T20:54:01.770", "Id": "237586", "Score": "3", "Tags": [ "python", "performance", "memory-optimization", "pytorch" ], "Title": "Batch normalization code optimization?" }
237586
<p>I'm doing some code review and I saw something like the following:</p> <pre class="lang-cpp prettyprint-override"><code>std::ifstream dataFile(filename); if (dataFile.is_open()) { std::deque&lt;std::string&gt; lines; std::string line, line_batch; while (std::getline(dataFile, line)) { if (!line.empty()) lines.push_back(line); } dataFile.close(); for (size_t i = 0; i &lt; lines.size();) { if (i &lt; MAX_BATCH_SIZE) { line_batch += "{" + lines.at(i) + "},"; i++; } </code></pre> <p>I'm thinking that having many small strings (1000 lines equating to around 3000 strings) that will be concatenated together, that it would be beneficial to calculate the final string size ahead of time, reserve it and then do a concatenation using <code>string::append</code> as this would reduce fragmentation, reallocation and increase speed (the last one I don't <em>think</em> would be that big of a deal).</p> <p>A read in line would, at a guess, be between 10-1000 characters. Max size of <code>line_batch</code> should be under 20MB. The application can get pretty big during execution. Big enough to force us to move from a 32 to a 64 bit memory scheme. The amount of times that this will happen depends on the user's environment, but if I were to guess, maybe between 0 and 100 times in a session. Could be more.</p> <p>I'm a little on the fence on this. Am I being too nit picky? Is the added complexity worth it? If it matters, we're compiling with VS2019, though I don't think we're using it as a fully compliant c++17 compiler.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T00:17:48.203", "Id": "465967", "Score": "0", "body": "Do you need advice on how to benchmark it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T08:08:42.170", "Id": "465997", "Score": "2", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T12:38:03.457", "Id": "466027", "Score": "0", "body": "The code presented is a small fragment, there is not enough code here to do a review." } ]
[ { "body": "<p>This question is a bit too general. And I believe you are nitpicking but not for the reason you mentioned.</p>\n\n<p>In the code it first reads all 1000+ lines and stores them into a deque. Each line is a potential allocation and deque also allocates linearly in the number of objects (one allocation for each 4k bytes and each strings takes 32 bytes... surely these numbers depend on platform and implementation and it works differently for large objects). Wouldn't that be a much much bigger source of memory fragmentation than just resizing 10 times one poor big string? IIRC string's capacity is in increased via the same policy as vectors, i.e., exponentially - thus it is just a few resizes.</p>\n\n<p>I find the issue of storing the string as separate entities to be a much bigger problem than the big string. To deal with it, one needs to read each line and process it immediately (put it into the batchline and hopefully getline will reuse reserved data). At least I hope its enough. In this case one cannot figure out the final size of the string batch without reading the file twice... and nobody wants that. So you can either increase its size by appending or reserve at the start its maximal size and add elements till it hits the capacity and then forward it. Ofc, there is a small nuance of dealing with extra large strings bigger than the reserved size - but it is never too hard to fix. Just make sure you deal with it.</p>\n\n<p>Disclaimer: I don't fully understand what brings more problems to memory fragmentation - it might be that deleting those strings at the end fixes most problems but if it so then why worry about the <code>batch_string</code>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T20:45:01.230", "Id": "466074", "Score": "0", "body": "Hmmmm. You're right. The many small strings being read in is a bigger problem for fragmentation. I was actually considering more the use of the `operator+`, where it would generate an unnecessary string object. Reading in the file as one string and then breaking it up into lines (either with a vector of ranges or finding when needed) would be a better approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T12:35:00.960", "Id": "466138", "Score": "0", "body": "@Adrian implemented allocation strategies and what affects fragmentation more- is a tricky question. In my expirience reusing the same variable for quick temporary allocations is totally fin, almost as good as resereving reusing same allocation. It is surely platform dependent, tho. In this case compiler should be capable of optimizing away unnecessary copying and allocations with the `+` operator - but does it actually do it? It's a mystery. Generally, if you want to be safe from fragmentation issues consider using C++17 polymorphic allocator in your codebase. It should be the true fix." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T17:15:46.857", "Id": "237649", "ParentId": "237592", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T22:18:27.943", "Id": "237592", "Score": "1", "Tags": [ "c++", "strings", "c++17" ], "Title": "Better to use string concatenation using std::string::operator+() or std::string::reserve() and std::string::append()?" }
237592
<p>I am a beginner in programming, started about 2 months ago with Java, changing careers from law.</p> <p>I have recently applied for an internship but was denied because I failed to do the pre-interview test right.</p> <p>One of the tasks was to keep deleting 3 consecutive same integers from the array until the list is either empty or has no 3 consecutive same numbers. The assignment can be found <a href="https://drive.google.com/file/d/1MDMZRYPhVI_V0cwFZWk7mkaapgi0sljK/view" rel="nofollow noreferrer">here</a>.</p> <p>Below a description of the task with examples:</p> <blockquote> <p>Three brothers walk into a bar. All the beverages are placed in one line at the long bar table. The size of each glass is represented in an array of integers, glasses. The brothers will drink a round if they can find 3 consecutive glasses of the same size. The barman removes the empty glasses from the table immediately after each round. Find the maximum number of rounds the three brothers can drink.</p> <p>For glasses = [1, 1, 2, 3, 3, 3, 2, 2, 1, 1], the output should be brothersInTheBar(glasses) = 3. The brothers can start with a round of size 3, then after the glasses are cleared, a round of size 2 can be formed, followed by a round of size 1. One glass will be left at the table.</p> <p>For glasses = [1, 1, 2, 1, 2, 2, 1, 1], the output should be brothersInTheBar(glasses) = 0. There are no 3 consecutive glasses of the same size.</p> </blockquote> <p>This is my code:</p> <pre class="lang-java prettyprint-override"><code> public int brothersInTheBar(int[] glasses){ if(glasses.length&lt;=2) return 0; ArrayList&lt;Integer&gt; glassesAsList = new ArrayList&lt;Integer&gt;(); Arrays.stream(glasses).forEach(i -&gt; glassesAsList.add(i)); int counter=0; for (int x=0;x&lt;glassesAsList.size()-2;++x){ if(glassesAsList.get(x) == glassesAsList.get(x+1) &amp;&amp; glassesAsList.get(x) == glassesAsList.get(x+2)){ glassesAsList.remove(x); glassesAsList.remove(x); glassesAsList.remove(x); counter++; x=-1; } if(glassesAsList.isEmpty()) break; } return counter; } </code></pre> <p>I sent the email back asking what I did wrong, so I can improve in the future. The response from the company only said that I have to look more into algorithm complexity and that my code is inefficient.</p> <p>So my question is how to improve my algorithm and what is wrong with it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T06:51:02.870", "Id": "465991", "Score": "1", "body": "[Originally posted at Stack Overflow](https://stackoverflow.com/q/60309657/1014587)" } ]
[ { "body": "<p>I'm not that good with java so I'll just say what I understand.</p>\n\n<p>In my opinion what you could have done is instead of copying to another array you could have just checked the original array and if you didn't find the the number to be consecutive just add it to the new array. </p>\n\n<p>We need to check the whole array so that is gonna take <span class=\"math-container\">$$\\mathcal{O}(n)$$</span> time. Copying the whole array would be more costly in my opinion.</p>\n\n<p>If you are looking to improve your understanding of algorithm I would recommend these books 'Introduction to Algorithm' or 'Algorithm design'.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T00:40:52.607", "Id": "237596", "ParentId": "237593", "Score": "2" } }, { "body": "<p><code>Remove(x)</code> deletes the element and then shifts every element up so it alone is an O(n) operation making your entire algorithm O(n^2). I actually wrote a <code>removeAtFast(x)</code> which swaps the item being removed and the last element then removes the last element normally. But you can't do this because it messes up the ordering.</p>\n\n<p>I'd create a new array like what Pure Evil suggested. Just go through the elements and if you find 3 consecutive numbers skip 3 ahead and continue copying.</p>\n\n<p>Edit: Also it would appear your code would fail the first example given in the assignment.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T01:22:32.137", "Id": "237598", "ParentId": "237593", "Score": "3" } }, { "body": "<p>Welcome to Code Review. I'm starting from this declaration:</p>\n\n<blockquote>\n<pre><code>ArrayList&lt;Integer&gt; glassesAsList = new ArrayList&lt;Integer&gt;();\n</code></pre>\n</blockquote>\n\n<p>Better use declare it as a <code>List</code> and not <code>ArrayList</code>:</p>\n\n<pre><code>List&lt;Integer&gt; glassesAsList = new ArrayList&lt;Integer&gt;();\n</code></pre>\n\n<p>Here the main problem of your code:</p>\n\n<pre><code>for (int x=0;x&lt;glassesAsList.size()-2;++x){\n if(glassesAsList.get(x) == glassesAsList.get(x+1) &amp;&amp; glassesAsList.get(x) == glassesAsList.get(x+2)){\n glassesAsList.remove(x);\n glassesAsList.remove(x);\n glassesAsList.remove(x);\n counter++;\n x=-1;\n }\n if(glassesAsList.isEmpty())\n break;\n}\n</code></pre>\n\n<p>You're iterating over a list and the operation is generally safe unless as in your case the loop contains a <code>remove</code> operation, because when you remove an element from a list all the elements at the right of it will be shifted and then all their indexes are changed by 1. One option to avoid the problem is use an iterator like below:</p>\n\n<pre><code>while (it.hasNext()) {\n Integer i = it.next();\n it.remove();\n //other instructions, I saved the value of the list element in the variable i\n}\n</code></pre>\n\n<p>Due to the task, for me one list is not enough to solve it, you have to create another <code>helper</code> list where to store elements for comparisons with the current element <code>i</code> in the original list, below the full code of the class:</p>\n\n<pre><code>public class Rounds {\n\n public static int brothersInTheBar(int[] glasses) {\n if (glasses.length &lt; 3) {\n return 0;\n }\n int rounds = 0;\n List&lt;Integer&gt; helper = new ArrayList&lt;Integer&gt;();\n List&lt;Integer&gt; glassesAsList = new ArrayList&lt;Integer&gt;();\n Arrays.stream(glasses).forEach(i -&gt; glassesAsList.add(i));\n Iterator&lt;Integer&gt; it = glassesAsList.iterator();\n while (it.hasNext()) {\n Integer i = it.next();\n it.remove();\n int size = helper.size();\n if (size &gt;= 2 &amp;&amp; helper.get(size - 1) == i &amp;&amp; helper.get(size - 2) == i) {\n helper.remove(size - 1);\n helper.remove(size - 2);\n ++rounds;\n } else { \n helper.add(i);\n }\n }\n\n return rounds;\n }\n\n public static void main(String[] args) {\n System.out.println(brothersInTheBar(new int[] {1, 1, 2, 3, 3, 3, 2, 2, 1, 1}));\n System.out.println(brothersInTheBar(new int[] {1, 1, 2, 1, 2, 2, 1, 1}));\n\n }\n\n}\n</code></pre>\n\n<p>The comparison will be between the last two elements of <code>helper</code> list and your element <code>i</code> in the loop, if all three are equals the last two elements will be deleted and rounds will be increment by 1, otherwise you will add the element <code>i</code> in the <code>helper</code> list. </p>\n\n<p>Note : probably it is possible a solution that uses a list iterator (or perhaps a couple) and combinating it or them with the list, checks the two elements before the current and delete them together without an helper list.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T16:45:12.850", "Id": "466048", "Score": "1", "body": "`glassesAsList` should be `glasses` since hungarian notation is not common in java. since that name is already taken you could simply refer to them as `collection` or rename the input parameter as `int[] rawGlasses` - very nice review +1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T17:52:13.773", "Id": "466050", "Score": "1", "body": "@MartinFrank Nice point, I haven't noticed it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T09:54:14.867", "Id": "237618", "ParentId": "237593", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T23:43:27.313", "Id": "237593", "Score": "3", "Tags": [ "java" ], "Title": "Deleting three consecutive numbers in an array" }
237593
<p>As I mentioned in my bio, I do not code for a living and too old to switch careers but I do enjoy it as a hobby and I am trying to get better. Also trying to get my teenage son more interested. Anyhow, the code below does want I want it to but I am looking for tips to improve it. Any advice would be much appreciated before I add more to it with High Score tables and more functionality.</p> <pre><code>import random weapons = ["Sword", "Spell", "Fire"] shields = ["Armour", "Magic", "Water"] class Player: def __init__(self, name): self.name = name self.health = 100 self.weapon = 0 self.shield = 0 def damage(self): points = random.randint(10, 35) self.health -= points def selectWeapon(self): choice = int(input("Choose your weapon 1-Sword, 2-Spell or 3-Fire: ")) self.weapon = choice - 1 def selectShield(self): choice = int(input("Choose your shield 1-Armour, 2-Magic or 3-Water: ")) self.shield = choice - 1 # Child class of player with override methods for weapon # and shield selection class AiPlayer(Player): def __init__(self,name): super().__init__(name) def selectWeapon(self): choice = random.randint(1, 3) self.weapon = choice - 1 def selectShield(self): choice = random.randint(1, 3) self.shield = choice - 1 class Game: def __init__(self): self.gameOver = False self.round = 0 def newRound(self): self.round += 1 print("\n*** Round: %d ***\n" %(self.round)) # Check if either or both Players is below zero health def checkWin(self, player, opponent): if player.health &lt; 1 and opponent.health &gt; 0: self.gameOver = True print("You Lose") elif opponent.health &lt; 1 and player.health &gt; 0: self.gameOver = True print("You Win") elif player.health &lt; 1 and ai.health &lt; 1: self.gameOver = True print("*** Draw ***") def displayResult(self, player, opponent): print("%s used a %s, %s used a %s Shield\n" %(player.name, weapons[player.weapon], opponent.name, shields[opponent.shield])) print("%s caused damage to %s\n" %(player.name, opponent.name)) def takeTurn(self, player, opponent): # Decision Array # # Armour| Magic | Water # ______|________|_______ # Sword: False | True | True # Spell: True | False | True # Fire : True | True | False decisionArray = [[False, True, True], [True, False, True], [True, True, False]] if decisionArray[player.weapon][opponent.shield]: opponent.damage() currentGame.displayResult(player, opponent) else: print("\n%s used a %s, %s used a %s Shield" %(player.name, weapons[player.weapon], opponent.name, shields[opponent.shield])) print("%s blocked %s's attack - No Damage" %(opponent.name, player.name)) # Setup Game Objects currentGame = Game() human = Player("Mark") ai = AiPlayer("Computer") players = [human, ai] # Main Game Loop while not currentGame.gameOver: for player in players: player.selectWeapon() player.selectShield() currentGame.newRound() currentGame.takeTurn(human, ai) currentGame.takeTurn(ai, human) print("%s's health = %d" %(human.name, human.health)) print("%s's health = %d" %(ai.name, ai.health)) currentGame.checkWin(human, ai) </code></pre>
[]
[ { "body": "<h1>f-strings</h1>\n\n<p>Beginning with Python 3.6, there is a friendlier way of formatting strings. Instead of using <code>\"format string\" % (tuple_of_args)</code> where the argument and the format codes are separated by significant distance, the arguments are embedded in the string itself, surrounded by <code>{}</code>'s. The string itself is prefixed with an <code>f</code>.</p>\n\n<p>For example, instead of:</p>\n\n<pre><code> print(\"\\n*** Round: %d ***\\n\" %(self.round))\n</code></pre>\n\n<p>you can write:</p>\n\n<pre><code> print(f\"\\n*** Round: {self.round} ***\\n\")\n</code></pre>\n\n<h1>Enumerations</h1>\n\n<p>This code doesn't convey a lot of meaning by itself. It needs to be described by your 7 comment lines.</p>\n\n<pre><code> decisionArray = [[False, True, True], [True, False, True], [True, True, False]]\n</code></pre>\n\n<p>Some of the problem stems from indices having semantic meaning. For example, 1 is Magic. But 1 is also Spell. Confusing.</p>\n\n<p>Let's make what is happening a lot clearer. Let's define enumerations for our weapons and shields:</p>\n\n<pre><code>from enum import Enum\n\nWeapon = Enum(\"Weapon\", \"Sword, Spell, Fire\")\nShield = Enum(\"Shield\", \"Armour, Magic, Water\")\n</code></pre>\n\n<p>Now we have <code>Weapon.Sword</code>, <code>Weapon.Spell</code>, and <code>Weapon.Fire</code>, which conveniently have values 1, 2 and 3 respectively. We also have <code>Shield.Armour</code>, <code>Shield.Magic</code> and <code>Shield.Water</code>, also with values 1, 2, and 3.</p>\n\n<p>When we have our player select their <code>choice</code> of weapon, we use to store it as the number 0, 1 or 2:</p>\n\n<pre><code> self.weapon = choice - 1\n</code></pre>\n\n<p>but now we can store an actual enumeration object, like <code>Weapon.Fire</code> directly. Conveniently, passing the value 1, 2, or 3 to <code>Weapon(...)</code> will return the corresponding enumeration object:</p>\n\n<pre><code> self.weapon = Weapon(choice)\n</code></pre>\n\n<p>Similarly, we can store our shield <code>choice</code> as a <code>Shield</code> enumeration object:</p>\n\n<pre><code> self.shield = Shield(choice)\n</code></pre>\n\n<p>The AI is similar, but instead of <code>randint</code>, we can use <code>choice</code> and select a random <code>Weapon</code> and random <code>Shield</code>:</p>\n\n<pre><code> self.weapon = random.choice(list(Weapon))\n self.shield = random.choice(list(Shield))\n</code></pre>\n\n<p>But how about that <code>decisionArray</code>? First of all, that is a lousy name. What does \"decision array\" mean? A <code>Shield</code> will block one (or perhaps more) <code>Weapon</code> attacks. Let's add a <code>.blocks</code> attribute to our <code>Shield</code> objects:</p>\n\n<pre><code>Shield.Armour.blocks = { Weapon.Sword }\nShield.Magic.blocks = { Weapon.Spell }\nShield.Water.blocks = { Weapon.Fire }\n</code></pre>\n\n<p>(I'm using a <code>set()</code>, so more that one <code>Weapon</code> can be added. For example, <code>Shield.Magic</code> could block both <code>{ Weapon.Spell, Weapon.Fire }</code> ... after all, it's <strong>MAGIC</strong>! Feel free to experiment.)</p>\n\n<p>What would the <code>takeTurn</code> method now look like?</p>\n\n<pre><code>def takeTurn(self, player, opponent):\n\n if player.weapon not in opponent.shield.blocks:\n # apply damage\n else:\n # damage was blocked\n</code></pre>\n\n<p>That's pretty straight forward; no table required. If the weapon is not in the set of things the shield blocks, we apply damage.</p>\n\n<h1>PEP-8</h1>\n\n<p><a href=\"https://lmgtfy.com/?q=pep+8&amp;s=d\" rel=\"noreferrer\">PEP 8</a> is a Style Guide for Python. It describes things all Python programs should conform to, such as:</p>\n\n<ul>\n<li>variables and function names should be <code>snake_case</code> not <code>mixedCase</code>.</li>\n</ul>\n\n<h1>Updated Code</h1>\n\n<pre><code>import random\nfrom enum import Enum\n\nWeapon = Enum(\"Weapon\", \"Sword, Spell, Fire\")\nShield = Enum(\"Shield\", \"Armour, Magic, Water\")\n\nShield.Armour.blocks = { Weapon.Sword }\nShield.Magic.blocks = { Weapon.Spell }\nShield.Water.blocks = { Weapon.Fire }\n\nclass Player:\n def __init__(self, name):\n self.name = name\n self.health = 100\n self.weapon = None\n self.shield = None\n\n def damage(self):\n points = random.randint(10, 35)\n self.health -= points\n\n def select_weapon(self):\n weapons = [f\"{weapon.value}-{weapon.name}\" for weapon in Weapon]\n weapons = \", \".join(weapons[:-1]) + \" or \" + weapons[-1]\n choice = int(input(f\"Choose your weapon {weapons}: \"))\n self.weapon = Weapon(choice)\n\n def select_shield(self):\n shields = [f\"{shield.value}-{shield.name}\" for shield in Shield]\n shields = \", \".join(shields[:-1]) + \" or \" + shields[-1]\n choice = int(input(f\"Choose your shield {shields}: \"))\n self.shield = Shield(choice)\n\nclass AiPlayer(Player):\n\n def select_weapon(self):\n self.weapon = random.choice(list(Weapon))\n\n def select_shield(self):\n self.shield = random.choice(list(Shield))\n\nclass Game:\n def __init__(self):\n self.game_over = False\n self.round = 0\n\n def new_round(self):\n self.round += 1\n print(f\"\\n*** Round: {self.round} ***\\n\") \n\n # Check if either or both Players is below zero health\n def check_win(self, player, opponent):\n if player.health &lt; 1 and opponent.health &gt; 0:\n self.game_over = True\n print(\"You Lose\")\n elif opponent.health &lt; 1 and player.health &gt; 0:\n self.game_over = True\n print(\"You Win\")\n elif player.health &lt; 1 and ai.health &lt; 1:\n self.game_over = True\n print(\"*** Draw ***\")\n\n\n def display_result(self, player, opponent):\n print(f\"{player.name} used a {player.weapon.name}, {opponent.name} used a {opponent.shield.name} Shield\\n\")\n print(f\"{player.name} caused damage to {opponent.name}\\n\")\n\n def take_turn(self, player, opponent):\n\n if player.weapon not in opponent.shield.blocks:\n opponent.damage()\n current_game.display_result(player, opponent)\n else:\n print(f\"{player.name} used a {player.weapon.name}, {opponent.name} used a {opponent.shield.name} Shield\\n\")\n print(f\"{opponent.name} blocked {player.name}'s attack - No Damage\")\n\n# Setup Game Objects\ncurrent_game = Game()\nhuman = Player(\"Mark\")\nai = AiPlayer(\"Computer\")\n\nplayers = [human, ai]\n\n# Main Game Loop\nwhile not current_game.game_over:\n for player in players:\n player.select_weapon()\n player.select_shield()\n current_game.new_round()\n current_game.take_turn(human, ai)\n current_game.take_turn(ai, human)\n print(f\"{human.name}'s health = {human.health}\")\n print(f\"{ai.name}'s health = {ai.health}\")\n current_game.check_win(human, ai)\n</code></pre>\n\n<p>Notice in this code, if you added additional weapons and/or shields, nothing need be changed other than the <code>Enum(...)</code> declarations and the <code>.blocks = {}</code> lines. The code itself creates the \"1-Armour, 2-Magic or 3-Water\" type choice strings, and will properly work with more than 3 choices.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T14:07:23.413", "Id": "466035", "Score": "3", "body": "This is awesome thanks very much for all the feedback. It's funny..... The snake case mixed case thing I did read PEP-8, started changing everything to snake case then changed it back. I will stick with the PEP-8 recommendations for future though." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T06:21:03.017", "Id": "237608", "ParentId": "237601", "Score": "22" } }, { "body": "<p>To add to @AJNeufeld's answer, <code>select_weapon</code> and <code>select_shield</code> should probably validate their input. Those two functions could be refactored to remove duplicate code.</p>\n\n<pre><code>def select_enum(enum_class):\n items = [f\"{item.value}-{item.name}\" for item in enum_class]\n items = \", \".join(items[:-1]) + \" or \" + items[-1]\n\n valid_values = set(item.value for item in enum_class)\n\n while True:\n choice = int(input(f\"Choose your {enum_class.__name__.lower()}: {items}\"))\n if choice in valid_values:\n break\n\n print(f\"'{choice}' is not a valid selection. Please try again.\")\n\n return enum_class(choice)\n\n\ndef select_weapon(self):\n self.weapon = self.select_enum(Weapon)\n\n\ndef select_shield(self):\n self.shield = self.select_enum(Shield)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T01:12:07.683", "Id": "466231", "Score": "0", "body": "Thank you for your suggestion, much appreciated. I will add it in once I get it straight in my head what each line is doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T01:23:29.533", "Id": "466232", "Score": "0", "body": "Okay I get it I was confused by the enum_class.__name__.lower(). I think it is returning the name of module so either Weapon or Shield so that the code works for both selections. Thank you. Learning some cool new code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T01:28:18.790", "Id": "466233", "Score": "1", "body": "@CelestialMark, you got it. Every class has a `__name__` attribute, that is the name of the class. There are several handy \"dunder\" attributes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T06:45:39.360", "Id": "466239", "Score": "0", "body": "Nice addition. If you are validating input, however, you should go further. Add a `try: ... except ValueError:` to catch non-integer input, like `\"quit\"`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T18:55:14.393", "Id": "237713", "ParentId": "237601", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T03:30:03.970", "Id": "237601", "Score": "12", "Tags": [ "python", "beginner", "python-3.x", "game" ], "Title": "Simple Python turn based battle game" }
237601
<p>I am currently trying to implement an extensible way to create commands that can be sent to some type of executor. In my case, there would be two of them (server and client). As I posted <a href="https://stackoverflow.com/questions/60162484/calling-a-derived-class-method-from-the-parent-class-same-method">here</a>, I had a hard time developping my idea, but it finally came through something usable, but a bit complex in my opinion.</p> <p>I am thus looking for advice, and maybe ideas that could make this code better!</p> <p>There is a working example at the last file for anyone wondering*.</p> <h1>protocol.hpp</h1> <pre class="lang-cpp prettyprint-override"><code>#ifndef PROTOCOL_HPP_ #define PROTOCOL_HPP_ #include &lt;cstdint&gt; #include &lt;vector&gt; #include &lt;memory&gt; #define MAX_COMMAND_BODY_LENGTH 512 namespace nw { class command_base { public: using id = uint8_t; using buffer = std::vector&lt;uint8_t&gt;; static constexpr size_t header_length{sizeof(id)}; static constexpr size_t max_body_length{MAX_COMMAND_BODY_LENGTH}; protected: // We don't want to instanciate this class ~command_base() {} }; template&lt;class Executor&gt; class command: public command_base { public: using executor_t = Executor; using pointer = std::unique_ptr&lt;command&gt;; // This one has to be specialized later (when creating the executors) enum class command_t: id; command() = delete; explicit command(id); static pointer unserialize(buffer); buffer const serialize() const; virtual void execute(executor_t&amp;) = 0; protected: id id_; buffer const serialize_header() const; // implementations will need to define this, // depending on the member variables of the // subclass. virtual buffer const serialize_body() const = 0; private: static pointer do_make_command( id const, buffer::const_iterator, buffer::const_iterator ); }; } // namespace nw #include "protocol.ipp" #endif // PROTOCOL_HPP_ </code></pre> <h1>protocol.ipp</h1> <pre class="lang-cpp prettyprint-override"><code>#include &lt;stdexcept&gt; #include &lt;algorithm&gt; #include &lt;cstring&gt; // memcpy namespace nw { template&lt;class T&gt; command&lt;T&gt;::command(id id): id_(id) {} template&lt;class T&gt; command&lt;T&gt;::pointer command&lt;T&gt;::unserialize(buffer buffer) { auto it{buffer.cbegin()}; if (std::distance(it, buffer.cend()) &gt; header_length + max_body_length) { throw std::invalid_argument( "command::unserialize: buffer is too long." ); } command::id id; std::copy(it, it + sizeof(id), &amp;id); it += sizeof(id); return std::move(do_make_command(id, it, buffer.cend())); } template&lt;class T&gt; command_base::buffer const command&lt;T&gt;::serialize() const { buffer header{serialize_header()}; buffer body{serialize_body()}; if (body.size() &gt; max_body_length) { throw std::invalid_argument("command::serialize: buffer is too long."); } // Join the two buffers into one buffer res; res.resize(header.size() + body.size()); auto it{res.begin()}; std::copy(header.cbegin(), header.cend(), it); it += header.size(); std::copy(body.cbegin(), body.cend(), it); return res; } template&lt;class T&gt; command_base::buffer const command&lt;T&gt;::serialize_header() const { buffer buff(header_length); auto it{buff.begin()}; std::memcpy(&amp;*it, &amp;id_, sizeof(id_)); it += sizeof(id_); // Normally not necessary, but better safe than sorry buff.shrink_to_fit(); return buff; } template&lt;class T&gt; command&lt;T&gt;::pointer command&lt;T&gt;::do_make_command( id const id, buffer::const_iterator beg, buffer::const_iterator end ) { switch(static_cast&lt;command_t&gt;(id)) { default: throw std::invalid_argument( "command::unserialize: Unknown server command ID." ); } } } // namespace nw </code></pre> <h1>command_example.cpp</h1> <pre class="lang-cpp prettyprint-override"><code>#include "protocol.hpp" #include &lt;iostream&gt; #include &lt;string&gt; namespace nw { // Create an executor that can handle the commandsthat are gonna be implemented // (could be a server or a client, for example) class MyExecutor { public: // This one doesn't do much.... void print(std::string msg) { std::cout &lt;&lt; msg &lt;&lt; std::endl; } }; // We need to specify what commands are gonna be usable from that executor // We thus specialize the command template with the enum template&lt;&gt; enum class command&lt;MyExecutor&gt;::command_t: command_base::id {MessageCommand}; // We define a simple command that prints a message through the executor class MessageCommand: public command&lt;MyExecutor&gt; { public: // First, we need to construct the command, we assign its ID, // then do stuff with the buffer (here it only contains a string, // that we store directly in a variable. It is EXTREMELY important // that we have at least this constructor with this signature, // since it's the one used by unserialize MessageCommand(buffer::const_iterator b, buffer::const_iterator e): command(static_cast&lt;id&gt;(command_t::MessageCommand)), msg(b, e) {} // Feel free to make other constructors MessageCommand(std::string s): command(static_cast&lt;id&gt;(command_t::MessageCommand)), msg(s) {} // Simple execute function virtual void execute(MyExecutor&amp; e) { e.print(msg); } protected: // finally, we need to create the body serializing method. // This one is easy, since it can directly store the only // variable it holds virtual buffer const serialize_body() const { return buffer(msg.cbegin(), msg.cend()); } std::string msg; }; // This I'm really not sure... How do I define the specialized // do_make_command method??? // That way seems too verbose. I guess I will only have to // do that twice (Server/Client) so it doesn't really matter // added later: I could probably just directly make do_make_command virtual, // and implement it completely.Some repeated code but whatever I guess. template&lt;&gt; command&lt;MyExecutor&gt;::pointer command&lt;MyExecutor&gt;::do_make_command( id const id, buffer::const_iterator beg, buffer::const_iterator end ) { // This is always the same thing, we just add new cases // when adding new commands... This is the part I like the least. // Could maybe make a Macro to add cases??? But Macros are baaad :( switch(static_cast&lt;command_t&gt;(id)) { case command_t::MessageCommand: return pointer( new MessageCommand(beg, end) ); default: throw std::invalid_argument( "command::unserialize: Unknown MyExecutor command ID: " + std::to_string(id) ); } } } // namespace nw // Now it's super easy to use! int main() { using namespace nw; // Instanciate executor MyExecutor exec; // Create some commands std::string my_message{"Hello!"}; MessageCommand my_command(my_message); std::cout &lt;&lt; "Executing from the manually constructed command:\n"; my_command.execute(exec); // Can serialize/unserialize to be sent through some stream/socket, // for example. std::cout &lt;&lt; "\nExecuting from serialized then unserialized command:\n"; command&lt;MyExecutor&gt;::pointer c{ command&lt;MyExecutor&gt;::unserialize( my_command.serialize() ) }; c-&gt;execute(exec); return 0; } </code></pre> <p>Basically, having to specialize the enum template seems a bit verbose... Could I instead have a second template argument which is an enum when defining command?</p> <pre class="lang-cpp prettyprint-override"><code>template&lt;class Executor, class Enum&gt; class command { // ... }; </code></pre> <p>Is there anything else that I could do to improve this design?</p> <p>NB: This is the start of my first real <em>more ambitious</em> project in C++, so if there is any cue about my style/things I do wrong, I am open to criticism</p> <p>Thank you!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T18:04:27.317", "Id": "466188", "Score": "0", "body": "I don't get how your code will work ... every template instantiation of command<T> defines its own enum class command_t, then the 'id_' in each command<T> will always be 0, right? Or am I missing something here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T18:11:56.087", "Id": "466190", "Score": "0", "body": "You can see in the third code block how it works. The commands implemented from `command` call `command`'s constructor with the good id from the enum (which btw I moved to the Executor class instead of specializing the template, made more sense)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T19:45:21.550", "Id": "466202", "Score": "0", "body": "could you create another command class, print out the value of its 'id_' and include it in your example code? That'll make it easier to understand the way how id works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T20:38:31.053", "Id": "466209", "Score": "0", "body": "I mean the id_ of my command here would be `command<MyExecutor>::command_t::MessageCommand` (or `MyExecutor::command_t::MessgeCommand>` in my new version) which would probably be 0 here" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T21:06:58.087", "Id": "466214", "Score": "0", "body": "but if you add another command command<MyOtherExecutor>, as well as MyOtherCommand class, the id_ of this command would be MyOtherExecutor::command_t::MyOtherCommand, which would still be 0 (since it's defined as a separate enum). Is this what you would expect?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T21:08:52.297", "Id": "466215", "Score": "0", "body": "Yes, this is okay because when intercepting a command, you specify what executor is expected (`command<EXECUTOR>::unserialize(...)` so it doesn't matter" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T22:58:36.627", "Id": "466222", "Score": "0", "body": "OK. I *kind of* understand the point of id now -- presumably you'll have more enum values under command<MyExecutor>::command_t: ```enum class command<MyExecutor>::command_t: command_base::id {MessageCommand, AnotherMessageCommand, AThirdMessageCommand, etc};```. Given your usage of passing commands between client/server, your design is overly engineered. Unless you give some description of your other ambitious use cases, you don't really need those templates, base class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T23:01:10.397", "Id": "466223", "Score": "0", "body": "I will definetely need something like this, there will be a lot of different server instances with different APIs and I need something extensible and reusable. But my question was more about the code here and what it does than what it's gonna be used for :p" } ]
[ { "body": "<blockquote>\n<pre><code>using id = uint8_t;\nusing buffer = std::vector&lt;uint8_t&gt;;\n\nstatic constexpr size_t header_length{sizeof(id)};\nstatic constexpr size_t max_body_length{MAX_COMMAND_BODY_LENGTH};\n</code></pre>\n</blockquote>\n\n<p>Misspelt <code>std::uint8_t</code> and <code>std::size_t</code> here - that's a lurking portability bug (you're getting away with this because your current compiler is exercising its option to declare global-namespace copies of standard identifiers, but will fail on compilers that don't do that).</p>\n\n<p><code>command_base</code> is intended to be a base class, so its destructor should be <strong><code>virtual</code></strong>.</p>\n\n<p>Given that <code>buffer</code> is a <code>std::vector</code> and <code>it</code> is <code>buffer.cbegin()</code>, we can replace <code>std::distance(it, buffer.cend())</code> with a simple <code>buffer.size()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T18:14:02.793", "Id": "466192", "Score": "0", "body": "Thank you! What I don't understand is the size_t you're refering too. Should I cast max_command_body?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T08:42:50.683", "Id": "466407", "Score": "0", "body": "No cast is needed; just change `size_t` to the correct `std::size_t`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T10:40:50.603", "Id": "237622", "ParentId": "237605", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T05:03:58.520", "Id": "237605", "Score": "2", "Tags": [ "c++", "object-oriented", "design-patterns", "template", "networking" ], "Title": "Serializable and extensible API implementing the Command Design Pattern" }
237605
<p>I'm working on an application that counts the number of employees in each department.</p> <p>Here's my code:</p> <pre><code>SELECT count(case when (JS_TITLE = 'Accounting')then 1 end)as Accounting, count(case when (JS_TITLE = 'Management')then 1 end)as Management, count(case when(JS_TITLE = 'Marketing')then 1 end )as Marketing, count(case when(JS_TITLE = 'HR')then 1 end)as HR FROM EMP LEFT JOIN JOB_STATUS ON EMP.JS_REF = JOB_STATUS.JS_REF </code></pre> <p>but the thing is, the user may add a new department. </p> <p>Is there a better way to make this static code more dynamic?</p>
[]
[ { "body": "<p>You can use a <code>GROUP BY</code> clause to group by <code>JS_TITLE</code>, then you must transpose the record into a column matrix:</p>\n\n<pre><code>SELECT \n JS_TITLE, \n count(EMP.JS_REF)\nFROM EMP\nLEFT JOIN JOB_STATUS ON EMP.JS_REF = JOB_STATUS.JS_REF\nGROUP BY JS_TITLE\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T08:24:31.767", "Id": "237613", "ParentId": "237610", "Score": "1" } } ]
{ "AcceptedAnswerId": "237613", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T07:16:39.443", "Id": "237610", "Score": "1", "Tags": [ "sql", "dynamic-programming" ], "Title": "Dynamic SQL query for count data" }
237610
<p>The following script reads a set of SIDs inside firewall rules and uses them to set ACL rules in a folder.</p> <p>The question is: Is this syntax ok or is there better ways to write this script, considering powershell syntax features? (by the way, this code works)</p> <pre><code>param([Parameter(Mandatory)]$foldername) $result="" (Get-NetFirewallRule | Where-Object { ($_.Direction -eq "Outbound") -and ($_.DisplayName -like "*appcontainer*")}) | %{ ($_ | Get-NetFirewallApplicationFilter) | %{ $acl = Get-Acl $foldername $sec= New-Object System.Security.Principal.SecurityIdentifier($_.Package) $AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($sec,"FullControl",(1 -bor 2),0, "Allow") $acl.SetAccessRule($AccessRule) $acl | Set-Acl $foldername } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T11:21:16.437", "Id": "466013", "Score": "0", "body": "nope! [*grin*] **_[1] never use aliases or short names in a script that will be shared or reused._** why? code is READ far more often than written, so make it easy to read. **_[2] use consistent_ indents._** your indentation makes it needlessly unclear where each stage begins and ends. see **_[1]_** for why. **_[3] you need comments describing the purpose of the code._** again, someone who reads your code next month [perhaps you] needs some sort of idea as to the intent of your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T12:21:14.583", "Id": "466021", "Score": "1", "body": "@Lee_Dailey If you're writing a review, the answer section is much more appropriate for that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T12:25:48.060", "Id": "466024", "Score": "0", "body": "@Mast - my comment doesn't seem up to \"Answer\" levels. it is mostly restating the PoSh best practice & style github stuff. do you think it worthy of being an \"Answer\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T12:27:00.353", "Id": "466025", "Score": "1", "body": "@Lee_Dailey Well, it's a good start of an answer. Flesh it out a bit and you got something worthy of the answer box, absolutely." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T15:02:48.020", "Id": "466044", "Score": "0", "body": "@Mast - done ... thank you for the nudge! [*grin*]" } ]
[ { "body": "<p>nope! [grin] </p>\n\n<p>this is almost entirely about style, not performance. you will note that most points are about readability ... the following line is quite true ... </p>\n\n<p><strong><em>better readability gives better understanding gives better maintainability.</em></strong> </p>\n\n<p>[1] never use aliases or short names in a script that will be shared or reused<br>\nwhy? code is READ far more often than written, so make it easy to read. </p>\n\n<p>[2] use consistent indents<br>\nyour indentation makes it needlessly unclear where each stage begins and ends. see [1] for why that is important. </p>\n\n<p>[3] you need comments describing the purpose of the code<br>\nagain, someone who reads your code next month [perhaps you] needs some sort of idea as to the intent of your code. </p>\n\n<p>[4] avoid long lines<br>\nyou have two lines that run well off to the right. since PoSh <em>knows</em> that things like pipe symbols WILL be followed by more stuff, you can wrap after such. that also applies to commas, open parens, and other such \"more to come\" items. </p>\n\n<p>why bother? once again, it is about <em>reading</em>. there is a reason why most wide-format publications to use multiple columns ... people tend to read more comfortably when the lines require minimal side-to-side eye movement. that works out to about 80 to 100 chars per line. </p>\n\n<p>make use of the <em>vertical</em> space you have available. folks scan vertically somewhat more easily than horizontally. </p>\n\n<p>[5] use consistent variable case<br>\nyou use <code>lowercase</code> and <code>PascalCase</code>. try to stick with ONE such style ... and <code>PascalCase</code> is the one usually recommended. </p>\n\n<p>[6] read the officially referenced <em>unofficial</em> style &amp; best practices guide<br>\nthis ... </p>\n\n<p>PoshCode/PowerShellPracticeAndStyle: The Unofficial PowerShell Best Practices and Style Guide<br>\n— <a href=\"https://github.com/PoshCode/PowerShellPracticeAndStyle\" rel=\"nofollow noreferrer\">https://github.com/PoshCode/PowerShellPracticeAndStyle</a> </p>\n\n<p>[7] remove unused code<br>\nyou define <code>$Result</code> ... but never use it. i would remove that. </p>\n\n<p>[8] define the type for your parameter<br>\nyour <code>$FolderName</code> parameter type is not defined. i suspect it is <code>[string]</code>, tho. </p>\n\n<p>[9] avoid sending things across a pipe if you can<br>\nyou send <code>$_</code> to <code>Get-NetFirewallApplicationFilter</code> via a pipe. pipeline ops are slower than direct ops &amp; it looks like you could call that out by using the parameter name directly. </p>\n\n<hr>\n\n<p>here's how i would rework your code layout ... </p>\n\n<pre><code>Param (\n [Parameter(\n Mandatory)]\n [string]\n $FolderName\n )\n\nGet-NetFirewallRule |\n Where-Object {\n $_.Direction -eq \"Outbound\" -and\n $_.DisplayName -like \"*appcontainer*\"\n } |\n ForEach-Object {\n # i wonder if the next two lines could be done as \n # Get-NetFirewallApplicationFilter -AssociatedNetFirewallRule $_\n $_ |\n Get-NetFirewallApplicationFilter | \n ForEach-Object {\n $Acl = Get-Acl $FolderName\n $Sec= New-Object System.Security.Principal.SecurityIdentifier($_.Package)\n $AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule(\n $Sec,\n \"FullControl\",\n (1 -bor 2),\n 0,\n \"Allow\"\n )\n $Acl.SetAccessRule($AccessRule)\n $Acl |\n Set-Acl $FolderName\n } # end 2nd FE-O\n } # end 1st FE-O\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T15:02:21.727", "Id": "237639", "ParentId": "237621", "Score": "3" } } ]
{ "AcceptedAnswerId": "237639", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T10:37:58.683", "Id": "237621", "Score": "2", "Tags": [ "powershell" ], "Title": "Read SIDs and set ACLs" }
237621
<p>I created a simple log-in system in Java for a project. Security isn't a concern here, hence the plaintext password, but I'm interested in how I can improve the quality of my code. Everything seems to work but it just feels like messy code.</p> <pre><code>public boolean logIn(String name, String password) { if (getLoggedInUser() != null) { throw new IllegalArgumentException("You are already logged in"); } boolean login = false; for (User user: getUsers()) { if (user.toString().equals(name) &amp;&amp; user.getPassword().equals(password)) { loggedInUser = user; login = true; } } if (!login) //what if the username + password combo is not correct { for (User user: getUsers()) { if (user.toString().equals(name)) { throw new IllegalArgumentException("Your password is incorrect"); } } throw new IllegalArgumentException("Your username is incorrect"); } return login; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T22:19:26.880", "Id": "466087", "Score": "0", "body": "Hello, this question is off-topic, since the code is not compiling; I suggest that you read the [What topics can I ask about here?(https://codereview.stackexchange.com/help/on-topic) `Code Review aims to help improve working code. If you are trying to figure out why your program crashes or produces a wrong result, ask on Stack Overflow instead. Code Review is also not the place to ask for implementing new features.`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T00:21:57.640", "Id": "466094", "Score": "1", "body": "@Doi9t I didn't see anything obvious that would stop this from compiling, could you expand on what problem I missed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T00:33:42.183", "Id": "466095", "Score": "1", "body": "@forsvarir Missing `getLoggedInUser` and `getUsers` methods, `User` object, ect." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T05:38:20.687", "Id": "466101", "Score": "1", "body": "@Doi9t whilst complete, compilable code is easier to review, and can result in more in depth answers, I don't believe it's explicitly required. Possibly out of date meta: https://codereview.meta.stackexchange.com/a/6372/4203" } ]
[ { "body": "<p>Putting security to the side...</p>\n\n<p>A few points</p>\n\n<ul>\n<li><p>When you find what you're looking for in a loop, you can exit / return. In your case, rather than <code>login = true</code>, you could just <code>return true;</code>.</p></li>\n<li><p>You function returns <code>login</code>, however <code>login</code> is only ever <code>true</code> when it is returned. The function should be <code>void</code>, or return something meaningful, such as the logged in user.</p></li>\n<li><p>You're searching through the list twice, once to find the matching user/password and then again to find a matching user so that you can tell them their password is wrong. Really, you only need to search the collection for the user. If it's not there, the name is wrong. If it is, then check the password and either they got it wrong, or they're logged in.</p></li>\n<li><p>I'm not sure <code>IllegalArgument</code> is the right exception for this situation. I think of it as something to use if you're passing -1 to a method that expects a positive number. An argument should either be wrong, or right whereas in your code the same arguments could result in an exception or not, depending on what the user has set their password to.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T11:53:37.777", "Id": "466015", "Score": "0", "body": "Thanks for the feedback. Which exception type would be better for this situation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T12:05:39.060", "Id": "466018", "Score": "1", "body": "Something tailored to the situation, so for example https://docs.oracle.com/javase/7/docs/api/javax/security/auth/login/FailedLoginException.html seems like one to consider." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T11:37:48.673", "Id": "237628", "ParentId": "237623", "Score": "1" } }, { "body": "<h2><code>toString()</code> instead of <code>getName()</code></h2>\n\n<p>i think you can improve with your validation on names/passwords</p>\n\n<blockquote>\n <p><code>user.toString().equals(name)</code> and <code>user.getPassword().equals(password)</code></p>\n</blockquote>\n\n<p>i would put this not into the <code>isLoginValid</code> context but more back to your <code>User</code> class (single responsibility - since the <code>User</code> knows its name and can provide information if a given name matches to it's own name)</p>\n\n<p>provide a method for that purpose:</p>\n\n<pre><code>class User {\n\n ...\n public boolean isNameMatching(String name){...} \n public boolean isPasswordMatching(String password){...}\n\n}\n</code></pre>\n\n<p>alternatively it might be useful to provide a validation method using both parameters</p>\n\n<p>if that is too much effort you should <em>at least</em> avoid using the <code>toString()</code> to get the users name.</p>\n\n<h2>just an addOn</h2>\n\n<p><a href=\"https://codereview.stackexchange.com/users/4203/forsvarir\">forsvarir</a> already pointed out some good advices, so this is just a small addOn...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T16:00:51.893", "Id": "237643", "ParentId": "237623", "Score": "1" } }, { "body": "<h1>The Algorithm</h1>\n\n<p>The method <code>logIn</code> can be chunked into small steps:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public boolean logIn(String name, String password) {\n\n if( /* user is logged in already? */)\n\n for (/* every user */)\n if ( /* has name and password */)\n\n if (/* no match found */)\n for (/* every user */)\n if ( /* can find user with the given name? */ )\n}\n</code></pre>\n</blockquote>\n\n<p>The logic is more complex than it has to be. The algorithm searches twice if a <code>user</code> with the <code>name</code> exists. A simpler algorithm could look like:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public boolean logIn(String name, String password) {\n User user = // find user by its name\n\n if (/* no user found */)\n\n if (user.isLoggedIn)\n\n return user.hasPassword(password) \n}\n</code></pre>\n\n<hr>\n\n<h1>Data Structure</h1>\n\n<p>The method <code>getUsers()</code> looks like it returns a <code>List</code>. Since it is a list and you do not know at which index a concrete user is saved you have to search for the user.</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>for (User user: getUsers())\n{\n if (user.toString().equals(name))\n</code></pre>\n</blockquote>\n\n<p>To check that a user with <code>name</code> does not exists you have to loop through the hole list and this could take some time if you have many users! This is also known as <a href=\"https://en.wikipedia.org/wiki/Time_complexity#Table_of_common_time_complexities\" rel=\"nofollow noreferrer\"><span class=\"math-container\">\\$O(n)\\$</span></a> which is a indicator for the time complexity a algorithm can have.</p>\n\n<p>It would be much more performant if we could get a user directly without to search it which would be a time complexity of <span class=\"math-container\">\\$O(1)\\$</span>.</p>\n\n<p>We can archive this goal by using a <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html\" rel=\"nofollow noreferrer\"><code>Map</code></a> instead of a <code>List</code>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Map&lt;String, User&gt; nameByUser = new HashMap&lt;&gt;();\n\nnameByUser.put(\"TomZ\", new User(\"TomZ\", \"aPassw0rt\"));\n// ..insert some more users\n\nUser user = nameByUser.get(\"TomZ\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T07:28:43.920", "Id": "237685", "ParentId": "237623", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T10:50:32.047", "Id": "237623", "Score": "5", "Tags": [ "java", "authentication" ], "Title": "A simple Java login system" }
237623
<p>I'm working on <a href="https://github.com/RMPR/atbswp" rel="nofollow noreferrer">a multiplatform open source clone of tinytask</a>, specifically on the play/stop feature.</p> <p>Now, it looks like:</p> <pre><code> def on_press(self, key): if not self.recording: return False b = time.perf_counter() self.capture.append(f"time.sleep ({b - self.last_time})") self.last_time = b try: self.capture.append(f"pyautogui.keyDown({repr(key.char)})") except AttributeError: if key == keyboard.Key.alt: if platform.system() == "Darwin": self.capture.append(f"pyautogui.keyDown('option')") else: self.capture.append(f"pyautogui.keyDown('alt')") ################################################## #### I cut here because it's a bit repetitive #### ################################################## else: self.capture.append(f"### {key} is not supported yet") </code></pre> <pre><code> def on_release(self, key): if not self.recording: return False #self.count_perf() if key == keyboard.Key.alt: if platform.system() == "Darwin": self.capture.append(f"pyautogui.keyUp('option')") else: self.capture.append(f"pyautogui.keyUp('alt')") ################################################## #### I cut here because it's a bit repetitive #### ################################################## else: self.capture.append(f"pyautogui.keyUp({repr(key)})") </code></pre> <p>In order to make the play feature as library-agnostic (possibly to add the option later to change the backend) as possible, I refactored with the following function:</p> <pre class="lang-py prettyprint-override"><code> def write_keyboard_action(self, engine="pyautogui", move="", key=""): """ Append keyboard actions to the class variable capture Keyword Arguments: - engine: the module which will be used for the replay - move: keyDown | keyUp - key: The key pressed """ suffix = "(" + repr(key) + ")" if move == "keyDown": # Corner case: Multiple successive keyDown if move + suffix in self._capture[-1]: move = 'press' self._capture[-1] = engine + "." + move + suffix self._capture.append(engine + "." + move + suffix) </code></pre> <p>To have something like:</p> <pre><code> def on_release(self, key): if not self.recording: return False if key == keyboard.Key.alt: if platform.system() == "Darwin": self.write_keyboard_action(move='keyUp', key='option') else: self.write_keyboard_action(move='keyUp', key='alt') ################################################## #### I cut here because it's a bit repetitive #### ################################################## else: self.write_keyboard_action(move='keyUp', key=key) </code></pre> <pre><code> def on_press(self, key): if not self.recording: return False b = time.perf_counter() timeout = int(b - self.last_time) if timeout &gt; 0: self._capture.append(f"time.sleep({timeout})") self.last_time = b try: # Ignore presses on Fn key if key.char: self.write_keyboard_action(move='keyDown', key=key.char) except AttributeError: if key == keyboard.Key.alt: if platform.system() == "Darwin": self.write_keyboard_action(move="keyDown", key='option') else: self.write_keyboard_action(move="keyDown", key='alt') ################################################## #### I cut here because it's a bit repetitive #### ################################################## else: self._capture.append(f"### {key} is not supported yet") </code></pre> <p>But I have the feeling that something better than this is possible. Any suggestion ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T12:18:08.997", "Id": "466019", "Score": "0", "body": "Your title should explain what your code does, not what you want done to it. PS: AlexV should have made that part of their edit..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T12:23:01.690", "Id": "466023", "Score": "0", "body": "What does your code do? Make that the title." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T11:07:10.113", "Id": "237625", "Score": "0", "Tags": [ "python", "python-3.x", "wxpython" ], "Title": "Translate keyboard inputs to corresponding actions in pyautogui" }
237625
<p>I just recently got into c# and Unity coding, and would like to put this algorithm and code up for review to check how I'm doing. I've only been working by myself, so it would be interesting to hear how my code design and style could be improved. The task is like so:</p> <p>There's a 3D cubical grid (<code>stateGrid</code>) containing voxels that are either 1 or 0. It is stored as a flattened array. If multiple 1-voxels are neighboring eachother, they form an island together.</p> <p>I want to detect islands smaller than a given size (<code>blobMin</code>), and convert those to 0's. The function returns the voxels that are part of islands up for deletion. </p> <p>Checking if voxel is in an island is implemented with a breadth-first-search within the Walker function.</p> <p>Performance is quite important, since the cube can be of size 64 or even bigger, and I think there's a bunch to gain still algorithmically. </p> <p>Here's my code:</p> <pre><code>using System.Collections.Generic; using UnityEngine; public class IslandRemove{ private int mapSize; private int mapCubeSize; private float[] state; private float[] result; private int index; private int connectCount; private int blobMin; private HashSet&lt;Vector3Int&gt; history; private Queue&lt;Vector3Int&gt; queue; private int blobSz; public IslandRemove(int mapSize, int mapCubeSize, int blobMin){ this.mapSize = mapSize; this.mapCubeSize = mapCubeSize; this.blobMin = blobMin; result = new float[mapCubeSize]; } private int getIdx(Vector3Int v){ return v.z * mapSize * mapSize + v.y * mapSize + v.x; } private void ProcessNode(Vector3Int newVect){ // if not already in history if (!history.Contains(newVect)){ blobSz++; // add node to queue for later check queue.Enqueue(newVect); // mark node as counted so we don't count again, or check its connections history.Add(newVect); } } private bool walker(int x, int y, int z){ blobSz = 0; queue = new Queue&lt;Vector3Int&gt;(); history = new HashSet&lt;Vector3Int&gt;(); ProcessNode(new Vector3Int(x, y, z)); // queue start position var loopcount = 0; while (blobSz &lt; blobMin){ loopcount++; var node = queue.Dequeue(); var idx = getIdx(node); // check edges if (node.x != 0){ // edge x- if ((int)state[idx - 1] == 1) ProcessNode(new Vector3Int(node.x - 1, node.y, node.z)); } if (node.x != mapSize - 1){ // edge x+ if ((int) state[idx + 1] == 1) ProcessNode(new Vector3Int(node.x + 1, node.y, node.z)); } if (node.y != 0){ // edge y- if ((int) state[idx - mapSize] == 1) ProcessNode(new Vector3Int(node.x, node.y-1, node.z)); } if (node.y != mapSize - 1){ // edge y+ if ((int) state[idx + mapSize] == 1) ProcessNode(new Vector3Int(node.x, node.y+1, node.z)); } if (node.z != 0){ // edge z- if ((int) state[idx - mapSize*mapSize] == 1){ ProcessNode(new Vector3Int(node.x, node.y, node.z-1)); } } if (node.z != mapSize - 1){ // edge z+ if ((int) state[idx + mapSize*mapSize] == 1) ProcessNode(new Vector3Int(node.x, node.y, node.z+1)); } if (queue.Count == 0){ return true; // add to removelist } } return false; // target is reached, don't add to removelist } public List&lt;Vector3Int&gt; IslandRemover(float[] stateGrid){ state = stateGrid; var remove = new List&lt;Vector3Int&gt;(); var removeThis = false; var lastOneWasOne = false; // start with false // iterate through cube for (int z = 0; z &lt; mapSize; z++){ for (int y = 0; y &lt; mapSize; y++){ for (int x = 0; x &lt; mapSize; x++){ var idx = z * mapSize * mapSize + y * mapSize + x; if ((int) state[idx] == 1 &amp;&amp; !lastOneWasOne){ removeThis = walker(x, y, z); if (removeThis) remove.Add(new Vector3Int(x,y,z)); else{ lastOneWasOne = true; } } else{ lastOneWasOne = false; } if ((int)state[idx] == 0){ lastOneWasOne = false; } } } } return remove; } } </code></pre> <p>Thank you in advance!</p>
[]
[ { "body": "<blockquote>\n<pre><code>private int mapSize;\nprivate int mapCubeSize;\nprivate float[] state;\nprivate float[] result;\nprivate int index;\nprivate int connectCount;\nprivate int blobMin;\n</code></pre>\n</blockquote>\n\n<p>You should clean up unused members: <code>mapCubeSize</code>, <code>result</code>, <code>index</code> and <code>connectCount</code> are unused.</p>\n\n<hr>\n\n<p>Be consistent with your naming: methods and properties of a class are named with <code>PascalCase</code>, while fields are named with <code>camelCase</code> (e.g. <code>walker()</code> should be <code>Walker()</code> (BTW: <code>walker()</code> is a strange and mysterious name saying nothing about its behavior))</p>\n\n<hr>\n\n<blockquote>\n<pre><code>private HashSet&lt;Vector3Int&gt; history;\nprivate Queue&lt;Vector3Int&gt; queue;\nprivate int blobSz;\n</code></pre>\n</blockquote>\n\n<p>These members represent partial states inside <code>walker()</code>. I don't like them to be class members. Instead you could provide them as parameters to <code>ProcessNode()</code>, or you could define <code>ProcessNode()</code> as a nested method inside <code>walker()</code>:</p>\n\n<pre><code>private bool walker(int x, int y, int z)\n{\n\n int blobSz = 0;\n Queue&lt;Vector3Int&gt; queue = new Queue&lt;Vector3Int&gt;();\n HashSet&lt;Vector3Int&gt; history = new HashSet&lt;Vector3Int&gt;();\n ProcessNode(new Vector3Int(x, y, z)); // queue start position\n var loopcount = 0;\n\n void ProcessNode(Vector3Int newVect)\n {\n // if not already in history\n if (!history.Contains(newVect))\n {\n blobSz++;\n // add node to queue for later check\n queue.Enqueue(newVect);\n // mark node as counted so we don't count again, or check its connections\n history.Add(newVect);\n }\n }\n\n while (blobSz &lt; blobMin)\n {\n loopcount++;\n var node = queue.Dequeue();\n var idx = getIdx(node);\n ...\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>private void ProcessNode(Vector3Int newVect){\n // if not already in history\n if (!history.Contains(newVect)){\n blobSz++;\n // add node to queue for later check\n queue.Enqueue(newVect);\n // mark node as counted so we don't count again, or check its connections\n history.Add(newVect);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>The <code>HashSet&lt;T&gt;.Add()</code> method returns a <code>bool</code> indicating if the value was added (<code>true</code>) or already present. You can use that to simplify <code>ProcessNode()</code>:</p>\n\n<pre><code> void ProcessNode(Vector3Int newVect)\n {\n // if not already in history\n if (history.Add(newVect))\n {\n blobSz++;\n // add node to queue for later check\n queue.Enqueue(newVect);\n }\n }\n</code></pre>\n\n<hr>\n\n<p>All the calls to <code>ProcessNode()</code> creates a new <code>Vector3Int</code> instance from coordinates (x, y, z). Consider to change its signature to: <code>ProcessNode(int x, int y, int z)</code> and then create the vector inside <code>ProcessNode(...)</code> instead:</p>\n\n<pre><code>ProcessNode(int x, int y, int z)\n{\n newVect = new Vector3Int(x, y, z);\n ...\n}\n</code></pre>\n\n<hr>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code> // check edges\n if (node.x != 0)\n { // edge x-\n if ((int)state[idx - 1] == 1)\n ProcessNode(new Vector3Int(node.x - 1, node.y, node.z));\n }\n</code></pre>\n</blockquote>\n\n<p>I think, I would prefer:</p>\n\n<pre><code> // check edges (x-)\n if (node.x != 0 &amp;&amp; (int)state[idx - 1] == 1)\n { \n ProcessNode(new Vector3Int(node.x - 1, node.y, node.z));\n }\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> removeThis = walker(x, y, z);\n if (removeThis)\n</code></pre>\n</blockquote>\n\n<p>You only use <code>removeThis</code> once, so no need to define it as a variable:</p>\n\n<pre><code>if (walker(x, y, z))\n ...\n</code></pre>\n\n<p>is clear enough.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T16:41:42.640", "Id": "466047", "Score": "0", "body": "Woah, I learned a lot! Also gained a speedup it seems, maybe because of not creating so many Vector3Int() variables after changing to ProcessNode(int x, int y, int z). Many thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T15:46:10.913", "Id": "237641", "ParentId": "237626", "Score": "2" } } ]
{ "AcceptedAnswerId": "237641", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T11:07:21.617", "Id": "237626", "Score": "2", "Tags": [ "c#", "unity3d" ], "Title": "detecting isolated voxel-blob in 3D cube with breadth first search" }
237626
<p>I just got started with Python. I created some code, and I want to know what more experienced devs think about it. What can I do better? What to avoid?</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Graphs - Calculate expression or draws a graph from given equation. This is a conversion of my old program created at college at 2002y. Just to learn python at 2020y. """ import re import operator import math import matplotlib.pyplot as plt DEC_PLACES = 3 #number of decimal places after rounding FUNCTIONS = { 'sin': lambda x:math.sin(math.radians(x)), 'cos': lambda x:math.cos(math.radians(x)), 'tan': lambda x:math.tan(math.radians(x)), 'ln': lambda x:math.log(x), } OPERS = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv, '^': operator.pow, } OP_PRIO = { '(':0, '+':1, '-':1, ')':1, '*':2, '/':2, '^':3, } NUM_MATCH = re.compile( '(?:[1-9][0-9]*|0)' '(?:[.][0-9]+)?' ) FUN_MATCH = re.compile( '(?:[a-z]{2,}[(])' ) def checkBrackets(sFun): """ Function checks brackets in string i: string with function r: 0 -&gt; brackets failure / 1 -&gt; brackets ok """ wynik = 0 # int result of scan if "(" or ")" in sFun: for x in sFun: if x == "(": wynik += 1 continue elif x == ")": wynik -= 1 continue if(wynik != 0): wynik = 0 else: wynik = 1 return wynik def analizeOperations(sFun): """ Function checks if there are two operators one after the other i: string with function r: true if ok / false when err """ ok = True # returning var sFun.replace(" ","") for i in range(len(sFun)): if sFun[i] in OPERS: if i&gt;=1: if sFun[i-1] in OPERS: #two opers side by side ok = False break return ok def analizeOpAfterCB(sFun): """ Function checks if there is operator after closing bracket i: string with function r: true if ok / false when err """ ok = True # returning var sFun.replace(" ","") for i in range(len(sFun)): if sFun[i] == ")" and (i+1)&lt;len(sFun): if sFun[i+1] != ")": if not sFun[i+1] in OPERS: #missing operator after closing bracket ok = False break return ok def toRPN(sFun,x_val): """ Function convert infix string to RPN i: string with function infix x_val: value for x variable r: RPN[] """ stos = [] #stack wyjscie = [] #exit string index = 0 while index &lt; len(sFun): expr = sFun[index:] is_num = NUM_MATCH.match(expr) is_fun = FUN_MATCH.match(expr) if is_num: #if num put on wyjscie num = is_num.group(0) wyjscie.append(float(num)) index += len(num) continue if is_fun: #if function put on stos fun = is_fun.group(0) fun = fun[:-1] #remove "(" if fun in FUNCTIONS: stos.append(fun) index += len(fun) continue else: raise("Błąd! Nieznana funkcja.") if sFun[index] == "(": #if "(" put on stos stos.append(sFun[index]) index += 1 continue if sFun[index] == ")": for i in range(len(stos)-1,0,-1): #if ")" move all operands till "(" to wyjscie LIFO if stos[i] == "(": del stos[i] if stos[i-1] in FUNCTIONS: wyjscie.append(stos[i-1]) del stos[i-1] break else: wyjscie.append(stos[i]) del stos[i] index += 1 continue if sFun[index].lower() == "x": #insert x value on wyjscie wyjscie.append(float(x_val)) index += 1 continue if sFun[index] in OPERS: if index == 0: #if this is first char of string insert 0.0 before it wyjscie.append(0.0) elif sFun[index-1] == "(": wyjscie.append(0.0) #if operator is after openning bracket insert 0.0 before it if not stos: #if stos is empty insert operator stos.append(sFun[index]) index += 1 continue if OP_PRIO[sFun[index]] &gt; OP_PRIO[stos[-1]]: #if oper in sFun has higher prio add it to stos stos.append(sFun[index]) index += 1 continue else: while len(stos): #if oper in sFun has prio &lt;= oper in stos #move all opers from stos to wyjscie with prio &gt;= oper if (OP_PRIO[stos[-1]]&gt;OP_PRIO[sFun[index]] or ( OP_PRIO[stos[-1]] == (OP_PRIO[sFun[index]] and OP_PRIO[sFun[index]]&lt;3) ) ): wyjscie.append(stos[-1]) del stos[-1] else: break stos.append(sFun[index]) index += 1 # move stos to wyjscie LIFO while len(stos): if stos[-1] not in ["(",")",]: wyjscie.append(stos[-1]) del stos[-1] return wyjscie def evalExpr(sFun, x_val = 1): """ Function evaluate RPN string i: string with function infix x_val: value for x variable r: value """ stos = [] #stack #check string if not checkBrackets(sFun): raise SyntaxError("The expression have unclosed brackets!") elif not analizeOperations(sFun): raise SyntaxError("The expression have incorrectly written operators!") elif not analizeOpAfterCB(sFun): raise SyntaxError("Missing operator after closing bracket!") else: sRPN = toRPN(sFun,x_val) while len(sRPN): if isinstance(sRPN[0],float): stos.append(sRPN[0]) del sRPN[0] continue if sRPN[0] in OPERS: func = OPERS[sRPN[0]] #get function for oper val = func(stos[-2],stos[-1]) del stos[-2:] #remove used vals from stos del sRPN[0] stos.append(val) continue if sRPN[0] in FUNCTIONS: func = FUNCTIONS[sRPN[0]] #get function val = func(stos[-1]) del stos[-1] #remove used vals from stos del sRPN[0] stos.append(val) continue return round(stos[0],DEC_PLACES) #return rounded result def showHelp(): print("Allowed operators and functions:") print("+-*/^") print("sin, cos, tan, ln") print("You can enter arithmetic expressions like:") print("2*(3-4)^2") print("2*sin(30-4*2)") print("or functions like:") print("2*x^2+3*x+1") print("2*sin(x)*x+1") def main(): expr = input("Enter an arithmetic expression (type help for info):") if expr.lower() == "help": showHelp() exit() if "x" in expr: option = input("Expression cotains 'x' variable, enter 'r' for range or 'v' for value:") while option.lower() != 'r' and option.lower() != 'v': option = input("Expression cotains 'x' variable, enter 'r' for range or 'v' for value:") if option == 'v': x_val = '' while not isinstance(x_val,float): try: x_val = float(input("Enter x value:")) except: print("That was no valid number.") print("{0} = {1}".format(expr,evalExpr(expr,x_val))) else: x_val = '' x_start = '' x_end = '' x_step = '' while (not isinstance(x_start,float) and not isinstance(x_end,float) and not isinstance(x_step,float) ): try: x_start, x_end, x_step = map(float,input("Enter start value, end value and step for range (eg.: 0,5,1): ").split(",")) except: print("That was no valid number.") #make a graph x = [] y = [] #calculating values i = x_start while i &lt;= x_end: x.append(i) y.append(evalExpr(expr, i)) i += x_step # plotting the points plt.plot(x, y) # naming the x axis plt.xlabel('x') # naming the y axis plt.ylabel('f(x)') # giving a title to my graph expr += F"\n in range {x_start} to {x_end} step {x_step}" plt.title(expr) # function to show the plot plt.show() else: print("{0} = {1}".format(expr,evalExpr(expr))) if __name__ == "__main__": main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T12:37:35.553", "Id": "466026", "Score": "1", "body": "Welcome to Code Review! Can you provide us more information about the purpose of the code (what made you write it) and in what Python version you wrote it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T12:44:54.193", "Id": "466030", "Score": "1", "body": "Thanks! I was using python 3.8. I want to learn python, and I was thinking that coding something is better that just follow some tutorials. That's why I try to write something I was made earlier in c++." } ]
[ { "body": "<p>Since you mention that this was originally C++ code, well it shows.</p>\n\n<p>First, style. Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It recommends writing <code>if condition</code> instead of <code>if(condition)</code> and using <code>lower_case</code> instead of <code>camelCase</code> for variables and functions.</p>\n\n<p>You should also have a look at the standard library and <a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"nofollow noreferrer\">this excellent blog post about better looping</a>. You can also directly return the result of e.g. a boolean expression. Here are how I might write some of your functions:</p>\n\n<pre><code>def check_brackets(s):\n \"\"\"\n Function checks brackets in string\n s: string with function\n returns: 0 -&gt; brackets failure / 1 -&gt; brackets ok \n \"\"\"\n\n open_brackets = 0\n for c in s:\n if c == \"(\":\n open_brackets += 1\n elif c == \")\":\n if open_brackets:\n open_brackets -= 1\n else:\n return False\n return open_brackets == 0\n</code></pre>\n\n<p>Note that this will not be fooled by e.g. <code>\")(\"</code>, in contrast to your code.</p>\n\n<pre><code>from itertools import groupby\n\ndef analyze_operations(s):\n \"\"\"\n Function checks if there are two operators one after the other\n s: string with function\n returns: true if ok / false when err\n \"\"\"\n s = s.replace(\" \",\"\") # need to actually assign it, it is not in-place\n is_oper = map(lambda x: x in OPERS, s)\n return all(len(list(group)) == 1 for x, group in groupby(is_oper) if x)\n</code></pre>\n\n<p>Note that <code>str.replace</code> is not an in-place operation. So it does not do anything unless you assign the result to a variable. But since this seems to appear in many of your functions, you might want to do that in the calling code and not in every function.</p>\n\n<pre><code>from itertools import tee\n\ndef pairwise(iterable):\n \"s -&gt; (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = tee(iterable)\n next(b, None)\n return zip(a, b)\n\ndef analyze_op_after_CB(s):\n \"\"\"\n Function checks if there is operator after closing bracket\n s: string with function\n returns: true if ok / false when err\n \"\"\"\n for c1, c2 in pairwise(s.replace(\" \",\"\")):\n if (c1 == \")\" \n and c2 not in OPERS \n and c2 != \")\"):\n return False\n return True\n</code></pre>\n\n<p>The <code>pairwise</code> function is a recipe from the <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"nofollow noreferrer\"><code>itertools</code></a> module.</p>\n\n<pre><code>def eval_expr(s, x_val=1):\n \"\"\"\n Function evaluate RPN string \n s: string with function infix \n x_val: value for x variable\n r: value\n \"\"\"\n s = s.replace(\" \", \"\")\n if not check_brackets(s):\n raise SyntaxError(\"The expression have unclosed brackets!\")\n elif not analyze_operations(s): \n raise SyntaxError(\"The expression have incorrectly written operators!\")\n elif not analyze_op_after_CB(s):\n raise SyntaxError(\"Missing operator after closing bracket!\")\n\n stack = []\n for x in to_RPN(s, x_val):\n if isinstance(x, float):\n stack.append(x)\n elif x in OPERS:\n b, a = stack.pop(), stack.pop()\n stack.append(OPERS[x](a, b))\n elif x in FUNCTIONS:\n stack.append(FUNCTIONS[x](stack.pop()))\n if len(stack) != 1:\n raise SyntaxError(\"More than one value remains on stack\")\n return round(stack[0], DEC_PLACES) #return rounded result\n</code></pre>\n\n<p>The hardest part is of course to rewrite the conversion to the reverse polish notation, so I will leave that for now :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T09:21:39.907", "Id": "466120", "Score": "0", "body": "Thanks for answer. Could you explain why use pairwise instead of for loop?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T09:37:07.103", "Id": "466122", "Score": "1", "body": "@Arek Because pairwise does what it says, iterating over pairs. No need for range checking, special casing the end, explicit indexing (which does not work with all iterables)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T11:03:51.413", "Id": "466128", "Score": "0", "body": "I don't understand what exactly do your version function analyze_operations(s) but it fails with: 12+2*(3*4+10/5)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T11:11:55.600", "Id": "466129", "Score": "0", "body": "@Arek: Fixed. It was failing because it determined that there were more than one non-operations in a row (which is fine of course, but I was not filtering for it). Thanks for the other edits!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T16:36:06.620", "Id": "237646", "ParentId": "237632", "Score": "6" } }, { "body": "<p>This looks like a interesting program.</p>\n\n<h1>General</h1>\n\n<p>It took me a while (a few seconds) to figure out the meaning of\n\"i:\" and \"r:\" in the docstrings, perhaps \"parameters\" and \n\"returns\" are more clear.</p>\n\n<h1>function checkBrackets</h1>\n\n<p>I do not see the use of the <code>continue</code>'s in this case, the if-then\nstatement will finish anyway quickly.</p>\n\n<p>I do not understand the variable name <code>wynik</code>, this will have to do with\nlanguages i think seeing <code>raise(\"Błąd! Nieznana funkcja.\")</code> later on.</p>\n\n<p>I think the return value should be a bool and</p>\n\n<pre><code>if(wynik != 0): wynik = 0\nelse: wynik = 1\nreturn wynik\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>return wynik == 0\n</code></pre>\n\n<h1>function analizeOperations</h1>\n\n<p>This method could be better named <code>checkNoAdjacientOperators</code></p>\n\n<p>The replace method is not <em>inplace</em>, instead it returns a modified\nstring, so</p>\n\n<pre><code>sFun.replace(\" \",\"\")\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>sFun = sFun.replace(\" \",\"\")\n</code></pre>\n\n<p>If the first character is an operator the functions checks the character with index -1, which results in a check for the last character, this is not what you want, so</p>\n\n<pre><code>for i in range(len(sFun)):\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>for i in range(1, len(sFun)):\n</code></pre>\n\n<p>The variable <code>ok</code> can be skipped by changing</p>\n\n<pre><code> ok = False\n break\n</code></pre>\n\n<p>with</p>\n\n<pre><code> return False\n</code></pre>\n\n<p>and the final return statement with <code>return True</code> (although\n<em>no multiple returns</em> evangilists might protest).</p>\n\n<h1>function analizeOpAfterCB</h1>\n\n<p>Same remarks as for method <code>analizeOperations</code>.</p>\n\n<h1>function toRPN</h1>\n\n<p>too much to handle for me now...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T23:49:02.480", "Id": "466093", "Score": "0", "body": "`checkNoAdjacientOperators`: I prefer the *adjacent* spelling :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T17:05:24.963", "Id": "237647", "ParentId": "237632", "Score": "4" } } ]
{ "AcceptedAnswerId": "237646", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T12:16:25.890", "Id": "237632", "Score": "5", "Tags": [ "python", "python-3.x", "parsing", "math-expression-eval" ], "Title": "Evaluating arithmetic expressions and plotting graphs" }
237632
<p>I am just learning Vuejs and I am implementing it in a 'legacy' environment where jQuery, Bootstrap 3, among other libraries are loaded by default. In my implementation I try to keep it simple with certain functionality built in. My codepen is stripped of a few things such as some fetch calls and related things, so static data is loaded in. I recognize that some libraries conflict, such as Bootstrap 3 styling of select lists styling with Vuetify select component styling, so I am trying to figure out how to use the 'A-la-carte' functionality of Vuetify, to only import the Data Table component, so any input on that would be appreciated. </p> <p>Functionality built-in:</p> <ul> <li>A helper can only be assigned to one driver at a time, so the list of available helpers changes dynamically</li> <li>Changes are only temporarily saved until the 'save' button is clicked</li> </ul> <p>I would like for my code to be as clean, elegant, and efficient as possible so any feedback for achieving that would be appreciated. Additionally, I would like to follow best practices. </p> <p>Here is my codepen: <a href="https://codepen.io/betapup/pen/oNgOmPz" rel="nofollow noreferrer">https://codepen.io/betapup/pen/oNgOmPz</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { /** * Load and initialize the Module Object */ var getUrl = window.location; var baseUrl = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.split("/")[1]; console.log(baseUrl); var dataLoadApp = new Vue({ el: "#DispatchList", vuetify: new Vuetify(), data: function() { return { search: "", singleSelect: false, selected: [], loading: false, headers: [ { text: "Dispatch No", value: "DPA_SYS_NR", class: "col-xs-1" }, { text: "Route No.", value: "RTE_LST_SYS_NR", class: "col-xs-1" }, { text: "Route Name", value: "RTE_NA", class: "col-xs-1" }, { text: "Operation Date", value: "dpa_opr_dt", class: "col-xs-1" }, { text: "Driver", value: "driver", class: "col-xs-2" }, { text: "Helper", value: "helper", class: "col-xs-2" }, { text: "Start Time", value: "HPR_STT_TM" }, { text: "Meeting Location", value: "meetingloc", class: "col-xs-2" }, { text: "Edit", value: "edit", class: "col-xs-2" } ], dispatchList: [ { RTE_NA: "32D", HPR_CTY_TE: "LAKE FOREST", MTG_CTY_NA: "MISSIOJ VIEJO ", HPR_FST_NA: "THOMAS", MTG_ST_CD: "CA", MTG_SYS_NR: "234996", RTE_LST_SYS_NR: "37021433", MTG_AD_TE: "27000 CROWN VALLEY ", DPA_SYS_NR: "23652016", CEL_PHN_NR_TE: "949-422-8235", MTG_ZIP_CD: "92691 ", HPR_EMP_SYS_NR: "72057596757396015", MTG_NA: "MISISON VIEJO MALL - 27000 CROWN VALLEY ", DPA_OPR_DT: "December, 02 2019 00:00:00", DVR_FST_NA: "EDGAR", MTG_TE: "MISISON VIEJO MALL", DVR_EMP_SYS_NR: "72057599595327456", DVR_LST_NA: "Viper ", HPR_ZIP_TE: "92630", HPR_LST_NA: "Tiger", HPR_STT_TM: "10.5", isEditable: false, updating: false, unsavedEdit: { HPR_EMP_SYS_NR: 0, MTG_SYS_NR: 0 } }, { RTE_NA: "22B", HPR_CTY_TE: "LAGUNA NIGUEL", MTG_CTY_NA: "ALISO VIEJO", HPR_FST_NA: "FRANK", MTG_ST_CD: "CA", MTG_SYS_NR: "234948", RTE_LST_SYS_NR: "37021042", MTG_AD_TE: "22 BROOKLINE", DPA_SYS_NR: "23652017", CEL_PHN_NR_TE: "949-212-1104", MTG_ZIP_CD: "92656 ", HPR_EMP_SYS_NR: "72057607295908652", MTG_NA: "33D McD - 22 BROOKLINE", DPA_OPR_DT: "December, 02 2019 00:00:00", DVR_FST_NA: "MARK", MTG_TE: "33D McD", DVR_EMP_SYS_NR: "72057596755776331", DVR_LST_NA: "Cat ", HPR_ZIP_TE: "92677", HPR_LST_NA: "Gecko", HPR_STT_TM: "11", isEditable: false, updating: false, unsavedEdit: { HPR_EMP_SYS_NR: 0, MTG_SYS_NR: 0 } }, { RTE_NA: "85C", HPR_CTY_TE: "", MTG_CTY_NA: "SAN CLEMENTE", HPR_FST_NA: "CARLOS", MTG_ST_CD: "CA", MTG_SYS_NR: "234956", RTE_LST_SYS_NR: "37021043", MTG_AD_TE: "638 CAMINO DE LOS MARES", DPA_SYS_NR: "23652018", CEL_PHN_NR_TE: "858-263-6437", MTG_ZIP_CD: "92672", HPR_EMP_SYS_NR: "72057607569786758", MTG_NA: "76B McD STORE LOS MARES - 638 CAMINO DE LOS MARES", DPA_OPR_DT: "December, 02 2019 00:00:00", DVR_FST_NA: "DANNY", MTG_TE: "76B McD STORE LOS MARES", DVR_EMP_SYS_NR: "72057596757396156", DVR_LST_NA: "Leopard ", HPR_ZIP_TE: " ", HPR_LST_NA: "Mouse", HPR_STT_TM: "11", isEditable: false, updating: false, unsavedEdit: { HPR_EMP_SYS_NR: 0, MTG_SYS_NR: 0 } }, { RTE_NA: "58C", HPR_CTY_TE: "MISSION VIEJO ", MTG_CTY_NA: "LAGUNA NIGUEL", HPR_FST_NA: "CHRISTIAN", MTG_ST_CD: "CA", MTG_SYS_NR: "234973", RTE_LST_SYS_NR: "37021045", MTG_AD_TE: "30120 TOWN CENTER", DPA_SYS_NR: "23652019", CEL_PHN_NR_TE: "0000000000", MTG_ZIP_CD: "92677 ", HPR_EMP_SYS_NR: "72057604790204638", MTG_NA: "82A BALLPARK PIZZA - 30120 TOWN CENTER", DPA_OPR_DT: "December, 02 2019 00:00:00", DVR_FST_NA: "FRANCISCO", MTG_TE: "82A BALLPARK PIZZA", DVR_EMP_SYS_NR: "72057596757442558", DVR_LST_NA: "Hippo ", HPR_ZIP_TE: "92691", HPR_LST_NA: "Aligator", HPR_STT_TM: "11.5", isEditable: false, updating: false, unsavedEdit: { HPR_EMP_SYS_NR: 0, MTG_SYS_NR: 0 } }, { RTE_NA: "21E", HPR_CTY_TE: "", MTG_CTY_NA: "", HPR_FST_NA: "", MTG_ST_CD: "", MTG_SYS_NR: "0", RTE_LST_SYS_NR: "37021047", MTG_AD_TE: "", DPA_SYS_NR: "23652021", CEL_PHN_NR_TE: "", MTG_ZIP_CD: "", HPR_EMP_SYS_NR: "0", MTG_NA: " NONE", DPA_OPR_DT: "December, 02 2019 00:00:00", DVR_FST_NA: "AARON", MTG_TE: "", DVR_EMP_SYS_NR: "72057599394692259", DVR_LST_NA: "Sheep ", HPR_ZIP_TE: "", HPR_LST_NA: " NONE", HPR_STT_TM: "0", isEditable: false, updating: false, unsavedEdit: { HPR_EMP_SYS_NR: 0, MTG_SYS_NR: 0 } } ], helpers: [ { EMP_ID_NR: "", CEL_PHN_NR_TE: "", HPR_CTY_TE: "", HPR_EMP_SYS_NR: "0", HPR_FST_NA: "", HPR_ZIP_TE: "", HPR_LST_NA: " NONE", HPR_STT_TM: "0", assigned: true }, { EMP_ID_NR: "", CEL_PHN_NR_TE: "949-940-6656", HPR_CTY_TE: "Mission Viejo", HPR_EMP_SYS_NR: "72057596755718987", HPR_FST_NA: "MICHAEL", HPR_ZIP_TE: " ", HPR_LST_NA: "Caribou", HPR_STT_TM: "10.5", assigned: true }, { EMP_ID_NR: "", CEL_PHN_NR_TE: "949-422-8235", HPR_CTY_TE: "LAKE FOREST", HPR_EMP_SYS_NR: "72057596757396015", HPR_FST_NA: "THOMAS", HPR_ZIP_TE: 92630, HPR_LST_NA: "Tiger", HPR_STT_TM: "10.5", assigned: true }, { EMP_ID_NR: "", CEL_PHN_NR_TE: "949-903-6797", HPR_CTY_TE: "", HPR_EMP_SYS_NR: "72057599664221092", HPR_FST_NA: "CARLOS", HPR_ZIP_TE: " ", HPR_LST_NA: "Raccoon", HPR_STT_TM: "10.5", assigned: false }, { EMP_ID_NR: "", CEL_PHN_NR_TE: "714-381-8800", HPR_CTY_TE: "MISSION VIEJO", HPR_EMP_SYS_NR: "72057601806790785", HPR_FST_NA: "LOUIE", HPR_ZIP_TE: 92691, HPR_LST_NA: "Lemur", HPR_STT_TM: "10.5", assigned: false }, { EMP_ID_NR: "", CEL_PHN_NR_TE: "0000000000", HPR_CTY_TE: "MISSION VIEJO ", HPR_EMP_SYS_NR: "72057604790204638", HPR_FST_NA: "CHRISTIAN", HPR_ZIP_TE: 92691, HPR_LST_NA: "Aligator", HPR_STT_TM: "11.5", assigned: true }, { EMP_ID_NR: "", CEL_PHN_NR_TE: "7142926373", HPR_CTY_TE: "HUNTINGTON BEACH ", HPR_EMP_SYS_NR: "72057604998433690", HPR_FST_NA: "KYLE", HPR_ZIP_TE: 92647, HPR_LST_NA: "Dog", HPR_STT_TM: "11", assigned: false }, { EMP_ID_NR: "", CEL_PHN_NR_TE: "949-456-3705", HPR_CTY_TE: "MISSION VIEJO ", HPR_EMP_SYS_NR: "72057606938145111", HPR_FST_NA: "AARON", HPR_ZIP_TE: 92691, HPR_LST_NA: "Kangaroo", HPR_STT_TM: "11", assigned: false }, { EMP_ID_NR: "", CEL_PHN_NR_TE: "949-212-1104", HPR_CTY_TE: "LAGUNA NIGUEL ", HPR_EMP_SYS_NR: "72057607295908652", HPR_FST_NA: "FRANK", HPR_ZIP_TE: 92677, HPR_LST_NA: "Gecko", HPR_STT_TM: "11", assigned: false }, { EMP_ID_NR: "", CEL_PHN_NR_TE: "9495994286", HPR_CTY_TE: "MISSION VIEJO ", HPR_EMP_SYS_NR: "72057607368946249", HPR_FST_NA: "RYAN", HPR_ZIP_TE: 92692, HPR_LST_NA: "Jackal", HPR_STT_TM: "11.5", assigned: false }, { EMP_ID_NR: "", CEL_PHN_NR_TE: "858-263-6437", HPR_CTY_TE: "", HPR_EMP_SYS_NR: "72057607569786758", HPR_FST_NA: "CARLOS", HPR_ZIP_TE: " ", HPR_LST_NA: "Mouse", HPR_STT_TM: "11", assigned: true }, { EMP_ID_NR: "", CEL_PHN_NR_TE: "949-374-9030", HPR_CTY_TE: "", HPR_EMP_SYS_NR: "72057609580449451", HPR_FST_NA: "JUDE", HPR_ZIP_TE: " ", HPR_LST_NA: "Badger", HPR_STT_TM: "11", assigned: true }, { EMP_ID_NR: "", CEL_PHN_NR_TE: "949-942-9190", HPR_CTY_TE: "", HPR_EMP_SYS_NR: "72057609582686402", HPR_FST_NA: "DANTE", HPR_ZIP_TE: " ", HPR_LST_NA: "Toucan", HPR_STT_TM: "11", assigned: false }, { EMP_ID_NR: "", CEL_PHN_NR_TE: "530-718-0175", HPR_CTY_TE: "LAGUNA NIGUEL", HPR_EMP_SYS_NR: "72057609648129924", HPR_FST_NA: "MICAH", HPR_ZIP_TE: " ", HPR_LST_NA: "Sea Otter", HPR_STT_TM: "11", assigned: true } ], meetingLocs: [ { MTG_ZIP_CD: "", MTG_CTY_NA: "", MTG_NA: " NONE", MTG_TE: "", MTG_ST_CD: "", MTG_SYS_NR: "0", MTG_AD_TE: "" }, { MTG_ZIP_CD: "92691 ", MTG_CTY_NA: "MISSIOJ VIEJO ", MTG_NA: "MISISON VIEJO MALL - 27000 CROWN VALLEY ", MTG_TE: "MISISON VIEJO MALL", MTG_ST_CD: "CA", MTG_SYS_NR: "234940", MTG_AD_TE: "27000 CROWN VALLEY " }, { MTG_ZIP_CD: "92692 ", MTG_CTY_NA: "MISSION VIEJO", MTG_NA: "CANYON CREST ESToucanS - 22300 CANYON CREST DRIVE", MTG_TE: "CANYON CREST ESToucanS", MTG_ST_CD: "CA", MTG_SYS_NR: "234942", MTG_AD_TE: "22300 CANYON CREST DRIVE" }, { MTG_ZIP_CD: "92656 ", MTG_CTY_NA: "ALISO VIEJO", MTG_NA: "33D McD - 22 BROOKLINE", MTG_TE: "33D McD", MTG_ST_CD: "CA", MTG_SYS_NR: "234948", MTG_AD_TE: "22 BROOKLINE" }, { MTG_ZIP_CD: "92672 ", MTG_CTY_NA: "SAN CLEMENTE", MTG_NA: "76B McD STORE LOS MARES - 638 CAMINO DE LOS MARES", MTG_TE: "76B McD STORE LOS MARES", MTG_ST_CD: "CA", MTG_SYS_NR: "234956", MTG_AD_TE: "638 CAMINO DE LOS MARES" }, { MTG_ZIP_CD: "92677 ", MTG_CTY_NA: "LAGUNA NIGUEL", MTG_NA: "80C McD STORE (MARINA HILLS) - 30251 GOLDEN LANTERN", MTG_TE: "80C McD STORE (MARINA HILLS)", MTG_ST_CD: "CA", MTG_SYS_NR: "234957", MTG_AD_TE: "30251 GOLDEN LANTERN" }, { MTG_ZIP_CD: "92679 ", MTG_CTY_NA: "LADERA RANCH", MTG_NA: "21B WAGON WHEEL SPORTS PARK - SPORTS PARK", MTG_TE: "21B WAGON WHEEL SPORTS PARK", MTG_ST_CD: "CA", MTG_SYS_NR: "234963", MTG_AD_TE: "SPORTS PARK" }, { MTG_ZIP_CD: "92692 ", MTG_CTY_NA: "LADERA RANCH", MTG_NA: "21F BURGER KING - 27702 CROWN VALLEY PARKWAY", MTG_TE: "21F BURGER KING", MTG_ST_CD: "CA", MTG_SYS_NR: "234967", MTG_AD_TE: "27702 CROWN VALLEY PARKWAY" }, { MTG_ZIP_CD: "92677 ", MTG_CTY_NA: "LAGUNA NIGUEL", MTG_NA: "82A BALLPARK PIZZA - 30120 TOWN CENTER", MTG_TE: "82A BALLPARK PIZZA", MTG_ST_CD: "CA", MTG_SYS_NR: "234973", MTG_AD_TE: "30120 TOWN CENTER" }, { MTG_ZIP_CD: "92677 ", MTG_CTY_NA: "LAGUNA NIGUEL", MTG_NA: "82C ALBERTSONS LAG NIGUEL - 29941 ALICIA PARKWAY", MTG_TE: "82C ALBERTSONS LAG NIGUEL", MTG_ST_CD: "CA", MTG_SYS_NR: "234976", MTG_AD_TE: "29941 ALICIA PARKWAY" }, { MTG_ZIP_CD: "", MTG_CTY_NA: "DANA POINT", MTG_NA: "25D ALBERTSONS - 33601 DEL OBISPO/STONEHILL", MTG_TE: "25D ALBERTSONS", MTG_ST_CD: " ", MTG_SYS_NR: "234984", MTG_AD_TE: "33601 DEL OBISPO/STONEHILL" }, { MTG_ZIP_CD: "92692 ", MTG_CTY_NA: "MISSION VIEJO", MTG_NA: "CASA DEL SOL POD - CASTA DEL SOL", MTG_TE: "CASA DEL SOL POD", MTG_ST_CD: "CA", MTG_SYS_NR: "234996", MTG_AD_TE: "CASTA DEL SOL" }, { MTG_ZIP_CD: "92694 ", MTG_CTY_NA: "MSSION VIEJO", MTG_NA: "21D -McD STORE ANTONIO - 27762 ANTONIO PKWY", MTG_TE: "21D -McD STORE ANTONIO", MTG_ST_CD: "CA", MTG_SYS_NR: "235010", MTG_AD_TE: "27762 ANTONIO PKWY" }, { MTG_ZIP_CD: " ", MTG_CTY_NA: "LADERA RANCH", MTG_NA: "21C SHELL - OSO/ANTONIO", MTG_TE: "21C SHELL", MTG_ST_CD: "CA", MTG_SYS_NR: "235013", MTG_AD_TE: "OSO/ANTONIO" }, { MTG_ZIP_CD: "92637", MTG_CTY_NA: "LAGUNA WOODS", MTG_NA: "ARAGON - 24232 CALLE ARAGON, LAGUNA WOODS LAGUNA WOODS, CA 92637", MTG_TE: "ARAGON", MTG_ST_CD: "CA", MTG_SYS_NR: "240897", MTG_AD_TE: "24232 CALLE ARAGON, LAGUNA WOODS LAGUNA WOODS, CA 92637" } ], tempEdit: [] }; }, created: function() {}, methods: { shortDate(longDate) { var d = new Date(longDate); return d.toLocaleDateString("en-US"); }, helperIsAssigned(helperSysNr) { return this.dispatchList.some( dispatchObj =&gt; dispatchObj.HPR_EMP_SYS_NR == helperSysNr ); }, makeEditable(dispatchObj) { let dispatchItem = this.dispatchList[ this.dispatchList.indexOf(dispatchObj) ]; dispatchItem.unsavedEdit["HPR_EMP_SYS_NR"] = dispatchItem["HPR_EMP_SYS_NR"]; dispatchItem.unsavedEdit["MTG_SYS_NR"] = dispatchItem["MTG_SYS_NR"]; dispatchItem["isEditable"] = true; }, cancelEditable(dispatchObj) { let dispatchItem = this.dispatchList[ this.dispatchList.indexOf(dispatchObj) ]; dispatchItem["isEditable"] = false; dispatchItem.unsavedEdit["HPR_EMP_SYS_NR"] = 0; dispatchItem.unsavedEdit["MTG_SYS_NR"] = 0; }, saveDispatchItem(dispatchObj) { let dispatchItem = this.dispatchList[ this.dispatchList.indexOf(dispatchObj) ]; dispatchItem["updating"] = true; dispatchItem["isEditable"] = false; dispatchItem["HPR_EMP_SYS_NR"] = dispatchItem.unsavedEdit["HPR_EMP_SYS_NR"]; dispatchItem["MTG_SYS_NR"] = dispatchItem.unsavedEdit["MTG_SYS_NR"]; let helperEmpSysNr = dispatchItem["HPR_EMP_SYS_NR"]; var helperObj = this.helpers.find( ({ HPR_EMP_SYS_NR }) =&gt; HPR_EMP_SYS_NR === helperEmpSysNr ); dispatchItem = Object.assign(dispatchItem, helperObj); let meetingSysNr = dispatchItem["MTG_SYS_NR"]; var meetingLocObj = this.meetingLocs.find( ({ MTG_SYS_NR }) =&gt; MTG_SYS_NR === meetingSysNr ); dispatchItem = Object.assign(dispatchItem, meetingLocObj); }, setHelper(e, dispatchIndex) { let dispatchObj = this.dispatchList[dispatchIndex]; const helperObj = this.helpers.find( helper =&gt; helper.HPR_EMP_SYS_NR == e.target.value ); helperObj["assigned"] = true; let currHelper = this.helpers.find( helper =&gt; helper.HPR_EMP_SYS_NR == dispatchObj["HPR_EMP_SYS_NR"] ); currHelper["assigned"] = false; } } }); }); </code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/&gt; &lt;link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet"/&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/vuetify/2.1.7/vuetify.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"&gt;&lt;/script&gt; &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8" /&gt; &lt;title&gt;CodePen - Vuetify Data Table Template Test&lt;/title&gt; &lt;link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" /&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- partial:index.partial.html --&gt; &lt;div id="DispatchList"&gt; &lt;v-app&gt; &lt;v-container&gt; &lt;v-card&gt; &lt;v-card-title&gt; Assign Helper List &lt;v-spacer&gt;&lt;/v-spacer&gt; &lt;/v-card-title&gt; &lt;v-data-table v-model="selected" :headers="headers" :items="dispatchList" item-key="DPA_SYS_NR" :loading="loading" loading-text="Loading... Please wait" &gt; &lt;template v-slot:item.DPA_OPR_DT="{ item }"&gt; &lt;span&gt; {{ shortDate(item["DPA_OPR_DT"]) }} &lt;/span&gt; &lt;/template&gt; &lt;template v-slot:item.driver="{ item }"&gt; &lt;span&gt; {{ item["DVR_FST_NA"] + " " + item["DVR_LST_NA"] }} &lt;/span&gt; &lt;/template&gt; &lt;template v-slot:item.helper="{ item }"&gt; &lt;span v-if="item['isEditable'] === false"&gt; {{ item["HPR_FST_NA"] + " " + item["HPR_LST_NA"] }} &lt;/span&gt; &lt;select v-else @change="setHelper($event, dispatchList.indexOf(item))" class="form-control" v-model="item.unsavedEdit['HPR_EMP_SYS_NR']" &gt; &lt;option v-for="helper in helpers" v-show="item['HPR_EMP_SYS_NR'] == helper['HPR_EMP_SYS_NR'] ? !helper['assigned'] : !helper['assigned']" :value="helper['HPR_EMP_SYS_NR']" &gt; {{ helper["HPR_FST_NA"] + " " + helper["HPR_LST_NA"] }} &lt;/option&gt; &lt;/select&gt; &lt;/template&gt; &lt;template v-slot:item.meetingloc="{ item }"&gt; &lt;span v-if="item['isEditable'] === false"&gt; {{ item["MTG_NA"] }} &lt;/span&gt; &lt;select v-else class="form-control" v-model="item.unsavedEdit['MTG_SYS_NR']"&gt; &lt;option v-for="meetLoc in meetingLocs" :value="meetLoc['MTG_SYS_NR']" &gt; {{ meetLoc['MTG_NA'] }} &lt;/option&gt; &lt;/select&gt; &lt;/template&gt; &lt;template v-slot:item.edit="{ item }"&gt; &lt;button v-if="item['isEditable'] === false" class="btn btn-default" title="Edit Dispatch Item" @click="makeEditable(item)" &gt; &lt;span class="glyphicon glyphicon-edit"&gt;&lt;/span&gt; &lt;/button&gt; &lt;span v-else&gt; &lt;button class="btn btn-danger" title="Cancel Edit" @click="cancelEditable(item)" &gt; &lt;span class="glyphicon glyphicon-remove"&gt;&lt;/span&gt; &lt;/button&gt; &lt;button class="btn btn-primary" title="Save Dispatch Item" @click="saveDispatchItem(item)" &gt; &lt;span class="glyphicon glyphicon-check"&gt;&lt;/span&gt; &lt;/button&gt; &lt;/span&gt; &lt;/template&gt; &lt;/v-data-table&gt; &lt;/v-card&gt; &lt;/v-container&gt; &lt;/v-app&gt; &lt;/div&gt; &lt;!-- partial --&gt; &lt;script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"&gt;&lt;/script&gt; &lt;script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;script src="./script.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T13:19:18.390", "Id": "237633", "Score": "1", "Tags": [ "vue.js" ], "Title": "Editable Data Table for Assigning Helpers to Drivers" }
237633
<p>I am looking to optimise my solution of the 'SMS problem', i.e splitting a String into chunks of the same size without splitting words.</p> <p>I did a recursion and am looking for ways to optimise that code, or a more efficient algorithm. In my solution spaces are left at the beginning of each chunk, this is voluntary.</p> <p>Here is the code:</p> <pre><code>var exampleTxt = `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.`; function getIndexOfLastSpace(msg, nthChar) { var curMsg = msg.substring(0, nthChar); console.log(curMsg.lastIndexOf(" ")); return curMsg.lastIndexOf(" "); } function getMessagesNumber (msg) { if (msg.length &lt; 1) { return 0; } else if (msg.length &gt; 1 &amp; msg.length &lt; 153) { return 1; } else { var messages = []; while (msg.length &gt; 0) { var chunk; // Last message if (msg.length &lt;= 153) { chunk = msg; } else { var lastSpaceIndex = getIndexOfLastSpace(msg, 153); chunk = msg.substring(0, lastSpaceIndex); } messages.push(chunk); msg = msg.replace(chunk, ''); } return messages.length; } } console.log(getMessagesNumber(exampleTxt)); </code></pre> <p>Also am I write in thinking that the complexity of this algorithm is O(n) ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T01:44:35.540", "Id": "466099", "Score": "0", "body": "It would be better to slice the message rather than replace, you know exactly what msg.replace will do, it will slice off the first chunk.length elements of msg. This is significantly faster. Yes your algorithm is O(n) which is as good as you can get for this scenario" } ]
[ { "body": "<p>Firstly, great implementation. Getting the maximum amount of characters for the next chunk, finding the last space in that and then using it to get the correct chunk is fast and works well.\nOther ideas that spring to mind would be to split the string into words first and rebuild with a loop, but I think this would be slower.</p>\n\n<p>Yes this is O(n) - the solution's speed is proportional to the amount of input passed.</p>\n\n<p>Your solution is a loop, not a recursion. A recursive solution would be a function which calls itself. If you want to see this style, let me know and I can post it.</p>\n\n<p>Some improvements:</p>\n\n<ul>\n<li>You don't need to wrap the <code>exampleTxt</code> variable in backticks. This creates a template literal, which is unnecessary here - you can just use normal quotes.</li>\n<li>Running the function with a 1 character string causes it to run the while loop, instead of returning early.</li>\n<li>You can simplify the levels of nesting in the <code>if ... else</code> by returning early. If one of the <code>return</code>s is triggered then nothing after it will be run.</li>\n</ul>\n\n<pre><code>if (msg.length &lt; 1) {\n return 0;\n}\n\nif (msg.length &gt;= 1 &amp; msg.length &lt; 153) {\n return 1;\n}\n\n// while loop\n\nreturn messages.length;\n</code></pre>\n\n<ul>\n<li>In the <code>else if</code> you have <code>&amp;</code> (Bitwise AND) instead of <code>&amp;&amp;</code> (Logical AND).</li>\n<li>Your <code>while</code> loop mutates the state of the <code>msg</code> variable. Mutation can lead to hard to find bugs - clone the string first (<code>remainingMsg = msg</code>) and use that in the loop instead.</li>\n<li>It's not necessary to have the <code>getIndexOfLastSpace</code> function separate. You can use something like this:</li>\n</ul>\n\n<pre><code>var nextChunk = msg.substring(0, 153);\nnextChunk = nextChunk.substring(0, nextChunk.lastIndexOf(' '));\n</code></pre>\n\n<ul>\n<li>To make the function more reusable you could return the message chunks directly instead of the length. The user can then call <code>.length</code> on the returned value if that's all they want.</li>\n<li>You could also pass the chunk length into the function as a parameter, so that it can handle chunking to any length.</li>\n<li>If using the point above, setting some standard values as <code>const</code>s is a good practice.</li>\n</ul>\n\n<pre><code>const SMS_MESSAGE_MAX_LENGTH = 153;\n// ...\ngetMessagesNumber(msg, SMS_MESSAGE_MAX_LENGTH);\n</code></pre>\n\n<ul>\n<li>For a higher level abstraction you could use a curryable function to create new functions with specific chunk lengths. I've used ES5 format as that's how the question was asked.</li>\n</ul>\n\n<pre><code>var chunk = function(chunkLength) {\n return (function splitChunks (message) {\n // ...\n });\n};\n\nvar chunkSmsMessage = chunk(153);\nchunkSmsMessage('Lorem ipsum...');\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T01:41:13.383", "Id": "237671", "ParentId": "237634", "Score": "0" } } ]
{ "AcceptedAnswerId": "237671", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T13:21:10.573", "Id": "237634", "Score": "0", "Tags": [ "javascript" ], "Title": "Optimising String split into chunks of fixed size" }
237634
<p>So I wrote this <code>class template</code> for a custom container. Basically, it stores elements and their occurences. When an element is pushed into the container, if it already exists, all it does is increment its counter.</p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &lt;map&gt; #include &lt;string&gt; // // Template class for a tocc, or Thing Occurence Counter Container // template &lt;class T&gt; class tocc { public: tocc(); // // Increments the count of that item or creates a new pair if it doesn't exist // void push(const T&amp; item) { // If no the item isn't found, create new pair with a count of 1 if(_tocc.find(item) == _tocc.end()) _tocc.insert(std::pair&lt;T, long int&gt;(item, 1)); else _tocc.at(item)++; } // // Decrements the count of that item and erases it if the count reaches 0 // void pop(const T&amp; item) { // If the item is found if(_tocc.find(item) != _tocc.end()) (_tocc.at(item) &lt;= 1) ? _tocc.erase(item) : _tocc.at(item)--; // Do nothing if the item isn't found } // // Gets the count of a particular item // Returns the count if the item exists, 0 otherwise // long int getCount(const T&amp; item) { if(_tocc.find(item) == _tocc.end()) return 0; return _tocc.at(item); } // // Returns true if the item is present in the map, false otherwise // bool contains(const T&amp; item) { return _tocc.find(item) != _tocc.end(); } private: std::map&lt;T, long int&gt; _tocc; }; </code></pre> <p>Here I put all the whole code in a single "file" for simplicity's sake, though I know it is best practice to separate files into headers and source files (which I normally do). </p> <p>I'd like to know what can be improved about this implementation.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T13:33:34.677", "Id": "466031", "Score": "0", "body": "Since we're implementing a `std::multiset`, perhaps we should use the same public interface? That would make it easier to switch between this class and the standard one." } ]
[ { "body": "<h1>The rules of five/three/zero</h1>\n\n<p>Usually, the existence of a single constructor indicates that the others should get implemented too (or explicitly forbidden/deleted). This is called the <a href=\"https://en.cppreference.com/w/cpp/language/rule_of_three\" rel=\"nofollow noreferrer\">rule of five (or three, depending on the standard)</a>. However, there is only one member in your class, <code>_tocc</code>, and it has well-defined constructors for all the usual cases.</p>\n\n<p>Here, we should follow the rule of <em>zero</em>: declare and define no constructors at all, as the default constructors will do the right thing. See also <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-zero\" rel=\"nofollow noreferrer\">CppCoreGuidelines C.20</a>.</p>\n\n<h1>Use already known data</h1>\n\n<p>While there is no bug in your code, there are some optimization flaws. Let's have a look at <code>tocc&lt;int&gt;::push</code>, compiled via <code>gcc 9.2 -S -O3</code> (<a href=\"https://godbolt.org/z/WF_Bk9\" rel=\"nofollow noreferrer\">CompilerExplorer</a>; I had to <code>[[gnu::noinline]]</code> to keep the assembly sane).</p>\n\n<pre><code>tocc&lt;int&gt;::push(int const&amp;):\n sub rsp, 24\n mov rdx, QWORD PTR [rdi+16]\n mov ecx, DWORD PTR [rsi]\n test rdx, rdx\n je .L31\n lea r8, [rdi+8]\n mov rax, rdx\n mov rsi, r8\n jmp .L32\n.L48:\n mov rsi, rax\n mov rax, QWORD PTR [rax+16]\n test rax, rax\n je .L33\n.L32:\n cmp DWORD PTR [rax+32], ecx\n jge .L48\n mov rax, QWORD PTR [rax+24]\n test rax, rax\n jne .L32\n.L33:\n cmp rsi, r8\n je .L31\n cmp DWORD PTR [rsi+32], ecx\n jg .L31\n mov rax, r8\n jmp .L36\n.L50:\n mov rax, rdx\n mov rdx, QWORD PTR [rdx+16]\n test rdx, rdx\n je .L49\n.L36:\n cmp ecx, DWORD PTR [rdx+32]\n jle .L50\n mov rdx, QWORD PTR [rdx+24]\n test rdx, rdx\n jne .L36\n.L49:\n cmp r8, rax\n je .L41\n cmp ecx, DWORD PTR [rax+32]\n jl .L41\n add QWORD PTR [rax+40], 1\n add rsp, 24\n ret\n.L31:\n mov rsi, rsp\n mov DWORD PTR [rsp], ecx\n mov QWORD PTR [rsp+8], 1\n call std::pair&lt;std::_Rb_tree_iterator&lt;std::pair&lt;int const, long&gt; &gt;, bool&gt; std::_Rb_tree&lt;int, std::pair&lt;int const, long&gt;, std::_Select1st&lt;std::pair&lt;int const, long&gt; &gt;, std::less&lt;int&gt;, std::allocator&lt;std::pair&lt;int const, long&gt; &gt; &gt;::_M_emplace_unique&lt;std::pair&lt;int, long&gt; &gt;(std::pair&lt;int, long&gt;&amp;&amp;)\n add rsp, 24\n ret\n.L41:\n mov edi, OFFSET FLAT:.LC0\n call std::__throw_out_of_range(char const*)\n</code></pre>\n\n<p>That's a lot of conditional jumps. 11 jumps depend on <code>test</code> or <code>cmp</code>. However, we only have a single comparison. What happens here?</p>\n\n<p>Well, first of all, a call to <code>map&lt;T&gt;::at</code> isn't free. It always has some additional boundary check, which prevents us from undefined behaviour but exchanges this boon for some additional code and an potential exception.</p>\n\n<p>However, if we're in the second branch in <code>push</code>, then we already <em>know that there is an element</em>! After all, we <em>found it beforehand</em>:</p>\n\n<pre><code>void push(const T&amp; item)\n{\n if(_tocc.find(item) == _tocc.end()) \n _tocc.insert(std::pair&lt;T, long int&gt;(item, 1));\n else\n _tocc.at(item)++; // find() did not return end()!\n}\n</code></pre>\n\n<p>Instead of <code>at</code>, we should use the iterator for several reasons:</p>\n\n<ul>\n<li>we already have the element at hand,</li>\n<li>we're guaranteed to have an element, so the boundary check in <code>at()</code> is not necessary,</li>\n<li>we don't need to search the element a second time and therefore stay <span class=\"math-container\">\\$\\mathcal O(1)\\$</span> instead of <span class=\"math-container\">\\$\\mathcal O(\\log n)\\$</span></li>\n</ul>\n\n<p>So let's use the iterator instead and let's replace <code>std::pair&lt;T, long int&gt;</code> with <code>std::make_pair</code> while we're at it:</p>\n\n<pre><code>void push(const T&amp; item)\n{\n const auto it = _tocc.find(item);\n if(it == _tocc.end()) { \n _tocc.insert(std::make_pair(item, 1));\n } else {\n it-&gt;second++;\n }\n}\n</code></pre>\n\n<p>What's the new assembly?</p>\n\n<pre><code>tocc&lt;int&gt;::push(int const&amp;):\n mov rax, QWORD PTR [rdi+16]\n mov edx, DWORD PTR [rsi]\n test rax, rax\n je .L31\n lea rsi, [rdi+8]\n mov rcx, rsi\n jmp .L32\n.L44:\n mov rcx, rax\n mov rax, QWORD PTR [rax+16]\n test rax, rax\n je .L33\n.L32:\n cmp DWORD PTR [rax+32], edx\n jge .L44\n mov rax, QWORD PTR [rax+24]\n test rax, rax\n jne .L32\n.L33:\n cmp rsi, rcx\n je .L31\n cmp DWORD PTR [rcx+32], edx\n jle .L36\n.L31:\n sub rsp, 24\n lea rsi, [rsp+8]\n mov DWORD PTR [rsp+8], edx\n mov DWORD PTR [rsp+12], 1\n call std::pair&lt;std::_Rb_tree_iterator&lt;std::pair&lt;int const, long&gt; &gt;, bool&gt; std::_Rb_tree&lt;int, std::pair&lt;int const, long&gt;, std::_Select1st&lt;std::pair&lt;int const, long&gt; &gt;, std::less&lt;int&gt;, std::allocator&lt;std::pair&lt;int const, long&gt; &gt; &gt;::_M_emplace_unique&lt;std::pair&lt;int, int&gt; &gt;(std::pair&lt;int, int&gt;&amp;&amp;)\n add rsp, 24\n ret\n.L36:\n add QWORD PTR [rcx+40], 1\n ret\n</code></pre>\n\n<p>Only 6 conditional jumps, only ~55% the original amount. However, keep in mind that the reduction of asm instructions was <em>not</em> the goal of this section. Instead, we re-used already known values and didn't repeat ourselves (only <em>one</em> <code>find()</code> call).</p>\n\n<p>The same holds for <code>pop()</code>'s usage of <code>map::erase()</code>, which can also take an iterator instead of a <code>Key</code>, but that's left as an exercise.</p>\n\n<h1>Documentation and (internal) comments</h1>\n\n<p>Good job on the comments! However, keep in mind that <a href=\"http://www.doxygen.nl/manual/docblocks.html\" rel=\"nofollow noreferrer\">Doxygen</a> and other programs use special syntax to discern documentation comments and implementation comments. </p>\n\n<h1>Naming</h1>\n\n<p>The sole member of our class almost has the same name as your class. This makes it somewhat confusing, as we use <code>_tocc</code> to actually implement <code>tocc</code>. Naming is hard, though, and I cannot come up with a nicer name; <code>counter</code>, <code>key_counter</code> or <code>key_counter_map</code> don't have the same ring to it, although the latter is the most descriptive variant.</p>\n\n<h1>Interface</h1>\n\n<p>At the moment, a user must know the name of all items in the <code>tocc</code> to check their count afterwards. An iterator interface would be tremendously helpful.</p>\n\n<p>We could even reuse <code>std::map::const_iterator</code>, if you only want constant iteration:</p>\n\n<pre><code>using iterator_type = std::map&lt;T, long int&gt;::iterator_type;\n\niterator_type begin() { return _tocc.begin(); }\n...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T19:34:16.950", "Id": "237654", "ParentId": "237635", "Score": "4" } }, { "body": "<p>Your <code>push</code> class has a big chunk of code and does two lookups in the map. It can be replaced with one line of code:</p>\n\n<pre><code>++_tocc[item];\n</code></pre>\n\n<p>since <code>operator[]</code> will add a key/value pair if it does not exist, and default initialize the value (0 in the case of <code>long int</code>).</p>\n\n<p><code>pop</code> will do three lookups if the item is found. This can be reduced to one by saving the result of the <code>_tocc.find</code> call and using the returned iterator in four places.</p>\n\n<p><code>getCount</code> will do two lookups, and can also save the result of the <code>find</code> call and use the iterator.</p>\n\n<p>Neither<code>getCount</code> nor <code>contains</code> modify the <code>tocc</code> object, so they should be declared <code>const</code> member functions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T20:52:19.537", "Id": "237661", "ParentId": "237635", "Score": "2" } } ]
{ "AcceptedAnswerId": "237654", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T13:22:23.287", "Id": "237635", "Score": "1", "Tags": [ "c++", "template", "collections" ], "Title": "Class template, custom container" }
237635
<p>I am writing a small application to get commits between two tags from different env (apple, banana) and write the result into a csv file. For security, I have to replace some sensitive information with alfa, beta and application banana key words. The application is running fine from my local machine. Please help me to review the code.</p> <p>Steps for application:</p> <ol> <li>Look for git tag visit env URL (alfa tag, beta tag)</li> <li>Run command line interface to retrieve git log between two tags to get all commit info</li> <li>Run GitHub command line interface to retrieve PR information by issue number</li> <li>Generate a csv file</li> </ol> <pre><code>#file directory: ~/main.py import urllib.request import re import coloredlogs, logging import json import pandas as pd import subprocess from configs.config import ConfigPrivate from env_enum import * from utilities import core from typing import Dict, List logger = logging.getLogger(__name__) SEPARATOR = '[^^^]' coloredlogs.install(level=logging.DEBUG, logger=logger, fmt='%(asctime)s %(message)s') def isMatched(tag): return len(set(tag.values())) == 1 class GitApp: pr_url = 'repos/&lt;owner&gt;/&lt;repos&gt;/issues' jira_url = '&lt;jira_link&gt;/browse' csv_title = ['col1', 'col2', 'col3', 'col4', 'col5', 'col6', 'col7', 'col8', 'col9'] def __init__(self, application, config, alfa_tag, beta_tag): self.app_type = application self.config = config self.alfa_tag = alfa_tag self.beta_tag = beta_tag def get_git_log(self) -&gt; List[str]: path = f'{self.config["project_dirs"]}/apps/{AppFullNameEnum[self.app_type].value}' cmd = f'git log {self.alfa_tag}..{self.beta_tag} --pretty=format:%h{SEPARATOR}%an' \ f'{SEPARATOR}%s' \ f'{SEPARATOR}%cd --date=short -- .' with core.pushd(path): try: log_info = subprocess.check_output(cmd, shell=True, bufsize=1, universal_newlines=True) return self.parse_logs_csv(log_info.split('\n')) except subprocess.CalledProcessError as e: logger.warning(e) logger.info(f'You may need to update repo {path} by git pull') exit() def parse_logs_csv(self, logs_info: List[str]) -&gt; List[str]: logs = [i.split(SEPARATOR) for i in logs_info] logs_sets = list() for i, log in enumerate(logs): log_detail = dict(col1=log[0], col2=log[1], col3=log[2], col4=log[3]) issue = re.findall(r'\(#\d+\)', log[2]) issue_num = issue.pop()[2:-1] try: cmd = f'hub api {self.pr_url}/{issue_num}' loginfo = subprocess.check_output(cmd, shell=True, bufsize=1, universal_newlines=True) logs = json.loads(loginfo) qa_tag = re.findall(r'\[[Qq][Aa]:\s*(\w+)\s*\]', logs['body']) jira = re.findall(r'\[\s*(\w+-\d+)\s*\]', logs['title']) or re.findall(r'\[\s*(\w+-\d+)\s*\]', logs['body']) log_detail['col5'] = logs['html_url'] log_detail['col6'] = f'{self.jira_url}/{jira.pop()}' if jira else '' log_detail['col7'] = qa_tag.pop() if qa_tag else 'Ignore' log_detail['col8'] = 'Verify' if 'verify' == log_detail['qa_tag'].lower() else 'skip' logs_sets.append( [log_detail['col1'], log_detail['col2'], log_detail['col3'], log_detail['col4'], log_detail['col5'], log_detail['col6'], log_detail['col7'], log_detail['col8'], '']) except subprocess.CalledProcessError as e: logger.warning(e) exit() return logs_sets def generator_csv_file(self, logs: List[List[str]], filename: str): df = pd.DataFrame(logs, columns=self.csv_title) core.df_to_csv(df, filename) class Applications: def __init__(self, app, config=ConfigPrivate().data): self.config = config self.app_type = AppEnum[app] self.url = self.generator_url() self.tag = self.generator_tag() self.git_logs = self.generator_git_log() def generator_url(self) -&gt; Dict[EnvEnum, str]: return {env: f'http://{URLPrefixEnum[env.name]}.com/{URLPosfixEnum[self.app_type.name]}' for env in EnvEnum} def generator_tag(self) -&gt; Dict[EnvEnum, str]: if (EnvEnum.alfa not in self.url) or (EnvEnum.beta not in self.url): logger.critical(f'Cannt find URL to get tag. Program Exits') tag = dict() for env in EnvEnum: with core.closing(urllib.request.urlopen(self.url[env])) as response: page = response.read().decode('utf-8') pattern = r'[\/(]eks-\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\w{7}[\/)]' t = re.findall(pattern, page) tag[env] = f'{AppFullNameEnum[self.app_type.name].value}/{t.pop()[1:-1]}' tagmsg = f'{EnvEnum.alfa.value} tag: {tag[EnvEnum.alfa]}---{EnvEnum.beta.value} tag: {tag[EnvEnum.beta]}' if isMatched(tag): logger.info(f'{tagmsg} matched. Nothing need to be vetted. Program exits') exit() logger.info(f'{tagmsg}') return tag def generator_git_log(self): git_app = GitApp(self.app_type.name, self.config, self.tag[EnvEnum.alfa], self.tag[EnvEnum.beta]) return git_app.get_git_log() def generator_csv_file(self): from datetime import datetime now = datetime.now() git_app = GitApp(self.app_type.name, self.config, self.tag[EnvEnum.alfa], self.tag[EnvEnum.beta]) git_app.generator_csv_file(self.git_logs, f'~/Desktop/{now.strftime("%Y_%m_%d_%H_%M_%S")}_' f'{AppFullNameEnum[self.app_type.name].value}.csv') def main(): apple = Applications('apple') apple.generator_csv_file() banana = Applications('banana') banana.generator_csv_file() if __name__ == '__main__': main() #file path: ~/configs/config.py import os import yaml class ConfigPrivate: """Provides configuration information.""" DEFAULT_CONFIG_DIR = os.path.abspath(os.path.dirname(__file__)) DEFAULT_CONFIG_FILE = "conf.yaml" def __init__(self, config_path=None): """Initialize a configuration from a conf directory and conf file.""" super(ConfigPrivate, self).__init__() failsafe_path = "/etc/config/{}.conf.yaml".format(self.DEFAULT_CONFIG_FILE) if config_path: path = config_path else: path = os.path.join(self.DEFAULT_CONFIG_DIR, self.DEFAULT_CONFIG_FILE) if not os.path.isfile(path): path = failsafe_path with open(path, 'r') as f: self.data = yaml.load(f, Loader=yaml.FullLoader) #file path: ~/utilities/core.py from contextlib import contextmanager import os import pandas as pd def df_to_csv(data_frame: pd.DataFrame, f_name: str): data_frame.to_csv(f_name, encoding='utf-8', index=False) @contextmanager def closing(thing): try: yield thing finally: thing.close() @contextmanager def pushd(new_dir): old_dir = os.getcwd() os.chdir(new_dir) try: yield finally: os.chdir(old_dir) #file path: ~/env_enum.py from enum import Enum class AppEnum(Enum): apple = 'apple' banana = 'banana' class AppFullNameEnum(Enum): apple = 'apple_fullname' banana = 'banana_fullname' class EnvEnum(Enum): alfa = 'alfa' beta = 'beta' class URLPrefixEnum(Enum): alfa = 'alfa' beta = 'beta' def __str__(self): return self.value class URLPosfixEnum(Enum): apple = 'apple_pos_url' banana = 'banana_pos_url' def __str__(self): return self.value </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T15:56:59.423", "Id": "237642", "Score": "2", "Tags": [ "python", "python-3.x", "csv", "git" ], "Title": "application to get git commit and write data into csv file" }
237642
<p>I know there is a better way to do the following but I havent had any luck trying to clean it up. </p> <p>This is for a table of messages where the user can click a row, <code>message-head</code>, which will display the <code>message-body-hidden</code> to the user as well as change the class of <code>message-head</code> to <code>message-head-active</code>. It will also change the fontawesome icon. Along with that, any rows that are currently being displayed or are <code>-active</code> will be reverted back to their defaults.</p> <p>How could I clean this up or more easily perform the same tasks?</p> <pre><code>$("table").on("click", "tr.message-head", function () { var active = $(this) active.toggleClass('message-head-active') if($("i",this).hasClass("fa-envelope-open")){ $("i",this).removeClass("fa-envelope-open") $("i",this).addClass("fa-envelope") }else{ $("i",this).removeClass("fa-envelope") $("i",this).addClass("fa-envelope-open") } var showMe = active.next().find('.message-body-hidden') showMe.toggle() $("tr.message-head-active").not(active).removeClass('message-head-active') $("tr.message-head-active").not(active).addClass('message-head') $("tr.message-head").not(active).find('i').removeClass("fa-envelope-open") $("tr.message-head").not(active).find('i').addClass("fa-envelope") $("td.message-body-hidden").not(showMe).hide() }) </code></pre>
[]
[ { "body": "<p>Move your revert all logic to the top of the function to avoid having to exclude the newly active item.</p>\n\n<p>Use a stateful class such as <code>.is-active</code> instead of <code>message-head-active</code>. Means you only have to toggle 1 class rather than 2.</p>\n\n<p><code>toggleClass</code> accepts multiple arguments so you can toggle the FontAwesome classes in one line. This also removes the need for the <code>hasClass</code> check.</p>\n\n<p>Store the result of <code>$(\"tr.message-head-active\")</code> to a variable and reuse it when reverting the header and the icon.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T02:05:50.300", "Id": "237672", "ParentId": "237645", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T16:14:30.493", "Id": "237645", "Score": "2", "Tags": [ "jquery" ], "Title": "JQuery Class and Display Toggling" }
237645
<p>My solution to <a href="https://leetcode.com/problems/most-frequent-subtree-sum/" rel="nofollow noreferrer">LeetCode problem Most Frequent Subtree Sum</a> works, but I have several questions regarding the code. I am also looking for an advice on how to improve the code.</p> <blockquote> <p><strong>Problem:</strong></p> <p>Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.</p> <p><strong>Example 1</strong></p> <pre><code> 5 / \ 2 -3 </code></pre> <p>return [2, -3, 4], since all the values happen only once, return all of them in any order</p> <p><strong>Example 2</strong></p> <pre><code> 5 / \ 2 -5 </code></pre> <p>return [2], since 2 happens twice, however -5 only occur once</p> </blockquote> <p><strong>My questions:</strong></p> <ol> <li><p>The function <code>get_sums_freqs</code> returns an <code>int</code>, but when I call it, I do not assign the result to anything: <code>get_sums_freqs (root, sum_freqs);</code>. Is it ok to do it this way? </p></li> <li><p>For some reason, it feels like a bad style to me to initialize the hash map <code>unordered_map&lt;int, int&gt; sum_freqs;</code> in one function and then pass it to another function to fill it out. Is there a better way to do it? Or is this a correct way?</p></li> </ol> <p><strong>My solution:</strong></p> <pre><code>vector&lt;int&gt; find_frequent_tree_sum(TreeNode* root) { // Collect freqs of sums into map unordered_map&lt;int, int&gt; sum_freqs; get_sums_freqs (root, sum_freqs); // Get the max freq int max_freq = 0; unordered_map&lt;int, int&gt;::iterator it; for (it = sum_freqs.begin(); it != sum_freqs.end(); ++it) { max_freq = max(max_freq, it-&gt;second); } // Collect all the values, which freq == max_freq vector&lt;int&gt; res; //unordered_map&lt;int, int&gt;::iterator it; for (it = sum_freqs.begin(); it != sum_freqs.end(); ++it) { if (it-&gt;second == max_freq) { res.push_back(it-&gt;first); } } return res; } int get_sums_freqs (TreeNode* root, unordered_map&lt;int, int&gt;&amp; sum_freqs) { if (root) { int curr_sum = root-&gt;val + get_sums_freqs (root-&gt;left, sum_freqs) + get_sums_freqs (root-&gt;right, sum_freqs); sum_freqs[curr_sum]++; return curr_sum; } else { return 0; } } </code></pre> <p>For context, here's the definition of TreeNode given by LeetCode:</p> <pre><code>struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T01:41:52.723", "Id": "466098", "Score": "0", "body": "What you do makes me uneasy. I understand it is essentially a programming competition and hence speed is of greater value than usual. But I think it is not much slower, and much nicer to define a function which takes a tree to the tree of partial sums. Then define a function which takes a tree and counts the occurences of each value, then compose these two functions. Of course what would be really nice is if you used constructs that made it such that this composition by the time it was compiled reduced down to just doing the single traversal (but idk how this looks in C++)." } ]
[ { "body": "<blockquote>\n <p>The function <code>get_sums_freqs</code> returns an <code>int</code>, but when I call it, I do not assign the result to anything: <code>get_sums_freqs (root, sum_freqs);</code>. Is it ok to do it this way? </p>\n</blockquote>\n\n<p>Your uneasiness here probably arises from the difference between a <code>Tree</code> and a <code>TreeNode</code>. A <code>TreeNode</code> is an internal tree detail, which should be hidden from the user of the <code>Tree</code>. I should be able to pass an <code>Tree</code> object to some function, and have it add some number of nodes to the <code>Tree</code>. If I pass an <code>nullptr</code> as the <code>TreeNode * root</code>, the caller can't modify <em>my</em> tree. Similarly, if two entities are supposed to share access to a <code>Tree</code>, that is fine as long as the <code>TreeNode *root</code> contains at least one node. But you can't share a common empty <code>Tree</code>; instead you have two <code>nullptr</code> ... which are not \"shareable\".</p>\n\n<pre><code>class Tree {\n TreeNode *root;\n int num_nodes;\n int max_depth;\n}\n</code></pre>\n\n<p>Now we have a <code>Tree</code> object, which can be shared ... even if it is an empty tree. As a bonus, our <code>Tree</code> can hold meta-information about the tree, such as the number of nodes in the tree, the maximum depth of the tree, and so on.</p>\n\n<p>The LeetCode challenge is promoting a broken tree model, by using a <code>TreeNode *</code> to represent a tree. It works, but it has issues; I wouldn't want to see it used in a professional \"Project\".</p>\n\n<p>I prefer not to walk into <code>nullptr</code> nodes. Imagine:</p>\n\n<pre><code>void TreeNode::get_sums_freqs(unordered_map&lt;int, int&gt;&amp; sum_freqs) { ... }\n</code></pre>\n\n<p>Now, you would be calling <code>TreeNode::get_sums_freqs()</code> with a <code>nullptr</code> for <code>this</code>, which is bad.</p>\n\n<p>Instead:</p>\n\n<pre><code>int get_sums_freqs(TreeNode* node, unordered_map&lt;int, int&gt;&amp; sum_freqs) {\n\n int curr_sum = root-&gt;val;\n\n if (node-&gt;left)\n curr_sum += get_sums_freqs(node-&gt;left, sum_freqs);\n if (node-&gt;right)\n curr_sum += get_sums_freqs(node-&gt;right, sum_freqs);\n\n sum_freqs[curr_sum]++;\n\n return curr_sum;\n}\n</code></pre>\n\n<p>Note we are calling the current node <code>node</code>, instead of <code>root</code>. We need to start off the search at the root of the tree, which is a little different:</p>\n\n<pre><code>void tree_get_sums_freqs(Tree* tree, unordered_map&lt;int, int&gt; &amp;sum_freqs) {\n if (tree-&gt;root) {\n root_sum = get_sums_freqs(tree-&gt;root, sum_freqs);\n sum_freqs[root_sum]++;\n }\n}\n</code></pre>\n\n<p>No <code>root_sum</code> needs to be returned from this top-level.</p>\n\n<p>Of course, since LeetCode doesn't define their trees this way, you have your odd, unused return value.</p>\n\n<blockquote>\n <p>For some reason, it feels like a bad style to me to initialize the hash map <code>unordered_map&lt;int, int&gt; sum_freqs;</code> in one function and then pass it to another function to fill it out. Is there a better way to do it? Or is this a correct way?</p>\n</blockquote>\n\n<p>This is fine. It is a visitor pattern. You create an accumulator object, and visit every node of your structure with it, to accumulate the results.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T23:54:05.493", "Id": "237669", "ParentId": "237648", "Score": "3" } } ]
{ "AcceptedAnswerId": "237669", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T17:07:14.660", "Id": "237648", "Score": "3", "Tags": [ "c++", "programming-challenge", "tree", "binary-tree" ], "Title": "LeetCode: Most Frequent Subtree Sum" }
237648
<p>I'm doing some code revision and I'm looking at this portion of my <code>Worksheet_Change()</code> event:</p> <pre><code>If Target.Address = "$A$4" Or _ Target.Address = "$A$7" Or _ Target.Address = "$A$10" Or _ Target.Address = "$B$21" Or _ Target.Address = "$B$22" Or _ Target.Address = "$B$23" Or _ Target.Address = "$B$24" Or _ Target.Address = "$B$25" Or _ Target.Address = "$B$26" Or _ Target.Address = "$B$33" Or _ Target.Address = "$B$35" Then </code></pre> <p>I'm considering using <code>Union()</code> and <code>Intersect()</code> to determine if my <code>Target.Address</code> is within the range - would this be a better solution than what I have above? I don't like the idea of losing readability, but I also want to keep things clean and concise.</p> <p>EDIT: Here's my entire <code>Worksheet_Change()</code> event - have at it! Please disregard the clinical verbiage. This is all for 1 worksheet where I have several cells that can be changed. These cells reference categories, start times and end times. Based on category selection or the start date and end date, data validation is changed on another worksheet.</p> <p>A good portion of this code manipulates a single chart that displays all of the employee data side by side. There's also an average line, a standard deviation line, and a special criteria line that may or may not be displayed on the chart. Additionally, certain locations can be filtered out from the chart based on the values in cells B12 through B26 (Show or Hide).</p> <p>The individual bars on the graph are colored based on which location an employee belongs to. Also, n values are added as additional data points on the graph.</p> <p>I'll also add that there are additional subroutines that are called in here, but they serve another purpose (they're used to create assessment reports). One also populates a listbox with employee initials that are out of range, to which a user can click them and be brought to a chart breaking down their numbers by week/month/year.</p> <p>Here's what the worksheet looks like, with some private information blocked out:</p> <p><a href="https://i.stack.imgur.com/pY8oT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pY8oT.png" alt="img1"></a></p> <pre><code>Option Explicit Option Compare Text Dim catcol As Long, topnum As Long, botnum As Long, individual As Long, i As Long, j As Long, seriescount As Long Dim title As String, averageformula As String, nvalueformula As String, nvaluetext As String, sdformula As String Dim updatecharts As Boolean, yaxisnumerical As Boolean Dim overallstats As Worksheet, datapulloverall As Worksheet, indivstats As Worksheet Dim cht As Chart Dim chtObj As ChartObject Private Sub Worksheet_Change(ByVal Target As Range) Set overallstats = ThisWorkbook.Worksheets("Overall Statistics") Set datapulloverall = ThisWorkbook.Worksheets("Data Pull - Overall") Set chtObj = overallstats.ChartObjects("Chart 1") Set cht = chtObj.Chart 'Category change If Target.Address = "$A$4" Or _ Target.Address = "$A$7" Or _ Target.Address = "$A$10" Or _ Target.Address = "$B$21" Or _ Target.Address = "$B$22" Or _ Target.Address = "$B$23" Or _ Target.Address = "$B$24" Or _ Target.Address = "$B$25" Or _ Target.Address = "$B$26" Or _ Target.Address = "$B$33" Or _ Target.Address = "$B$35" Then 'Check previous value hidden in columns near the change cell - if it's the same value, don't run the script. If Target.Address = "$A$4" And Target.Value = overallstats.Cells(5, 1).Value Then Exit Sub If Target.Address = "$A$7" And Target.Value = overallstats.Cells(8, 1).Value Then Exit Sub If Target.Address = "$A$10" And Target.Value = overallstats.Cells(11, 1).Value Then Exit Sub If Target.Address = "$B$33" And Target.Value = overallstats.Cells(34, 2).Value Then Exit Sub If Target.Address = "$B$35" And Target.Value = overallstats.Cells(36, 2).Value Then Exit Sub Application.EnableEvents = False 'On Error GoTo ErroredOut Application.ScreenUpdating = False updatecharts = True overallstats.Unprotect "pw" Select Case overallstats.Cells(4, 1).Value Case "ICSI Fert Rate" individual = 3 title = "ICSI Scientist" nvaluetext = "Total # ICSI'd" Case "IVF FR/Sperm Processor" individual = 4 title = "Sperm Processor" nvaluetext = "Total # Mature Oocytes" Case "Necrotic Rate/ICSI Embryologist" individual = 3 title = "ICSI Scientist" nvaluetext = "Total # Mature Oocytes" Case "Necrotic Rate/Fert Assessor" individual = 5 title = "Fert Assessor" nvaluetext = "Total # Mature Oocytes" Case "IVF FR/Fert Assessor" individual = 5 title = "Fert Assessor" nvaluetext = "Total # Mature Oocytes" Case "Ectopic Rate/Transfer Scientist" individual = 8 title = "Transfer Scientist" nvaluetext = "Total # Embryo Transfers" Case "PR/UT Embryologist" individual = 8 title = "UT Embryologist" nvaluetext = "Total # Embryo Transfers" Case "PR/Thaw Embryologist" individual = 10 title = "Thaw Embryologist" nvaluetext = "Total # Embryo Transfers" Case "PR/Freeze Embryologist" individual = 9 title = "Freeze Embryologist" nvaluetext = "Total # Embryo Transfers" Case "PR/Biopsy Embryologist" individual = 13 title = "Biopsy Embryologist" nvaluetext = "Total # Embryo Transfers" Case "Average # Eggs/Scientist" individual = 7 title = "Scientist" yaxisnumerical = True nvaluetext = "Total # Retrievals" Case "Survival rate by thaw" individual = 10 title = "Thaw Scientist" nvaluetext = "Total # Embryos Thawed" Case "Survival rate by freeze (cryo date)" individual = 9 title = "Cryo Scientist" nvaluetext = "Total # Embryos Thawed" Case "Survival rate by freeze (thaw date)" individual = 9 title = "Cryo Scientist" nvaluetext = "Total # Embryos Thawed" Case "Not recovered rate by thaw" individual = 10 title = "Thaw Scientist" nvaluetext = "Total # Embryos Thawed" Case "Not recovered rate by freeze" individual = 9 title = "Cryo Scientist" nvaluetext = "Total # Embryos Thawed" Case "No result biopsy rate" individual = 11 title = "No Result BX Tech" nvaluetext = "Total # Embryos Biopsied" Case "Damaged during biopsy rate" individual = 12 title = "Lysed Embryo Tech" nvaluetext = "Total # Embryos Biopsied" Case "Usable Blast/ICSI Embryologist" individual = 3 title = "ICSI Embryologist" nvaluetext = "Total # ICSI Ferts" End Select overallstats.Cells(16, 1).Value = nvaluetext overallstats.Protect "pw" End If If updatecharts = True Then 'Repopulate the individuals lists on x-axis based on date Call PopulateDataPullOverallValidation overallstats.Unprotect "pw" catcol = datapulloverall.Rows(1).Find(What:=overallstats.Cells(4, 1).Value).Column averageformula = Replace(datapulloverall.Cells(2, catcol).Formula, "$" &amp; ColumnLetter(individual) &amp; "2", """*""") sdformula = Replace(Left(Split(datapulloverall.Cells(2, catcol).Formula, "/")(1), Len(Split(datapulloverall.Cells(2, catcol).Formula, "/")(1)) - 3), "$" &amp; ColumnLetter(individual) &amp; "2", """*""") 'Update average column on Data Pull - Overall - NOT DYNAMIC row range datapulloverall.Range("AG2:AG50").Formula = averageformula 'Change to whole numbers for average eggs retrieved, otherwise leave as percentage If overallstats.Cells(4, 1).Value = "Average # Eggs/Scientist" Then datapulloverall.Range("AG2:AG50").NumberFormat = "0.00" datapulloverall.Range("AJ2:AJ50").NumberFormat = "0.00" Else datapulloverall.Range("AG2:AG50").NumberFormat = "0.00%" datapulloverall.Range("AJ2:AJ50").NumberFormat = "0.00%" End If 'Update the adjusted average column on Data Pull - Overall - NOT DYNAMIC row range If overallstats.Cells(4, 1).Value = "ICSI Fert Rate" Then datapulloverall.Range("AJ2:AJ50").Value = datapulloverall.Range("AG2").Value - (datapulloverall.Range("AG2").Value * 0.05) overallstats.Range("A33").Value = "Calc 5% below mean" ElseIf overallstats.Cells(4, 1).Value = "PR/UT Embryologist" Then datapulloverall.Range("AJ2:AJ50").Value = datapulloverall.Range("AG2").Value - (datapulloverall.Range("AG2").Value * 0.1) overallstats.Range("A33").Value = "Calc 10% below mean" ElseIf overallstats.Cells(4, 1).Value = "Necrotic Rate/ICSI Embryologist" Then datapulloverall.Range("AJ2:AJ50").Value = datapulloverall.Range("AG2").Value + (datapulloverall.Range("AG2").Value * 0.1) overallstats.Range("A33").Value = "Calc 10% above mean" ElseIf overallstats.Cells(4, 1).Value = "Survival rate by thaw" Or _ overallstats.Cells(4, 1).Value = "Survival rate by freeze (thaw date)" Or _ overallstats.Cells(4, 1).Value = "Survival rate by freeze (cryo date)" Then datapulloverall.Range("AJ2:AJ50").Value = 0.97 overallstats.Range("A33").Value = "97% static" ElseIf overallstats.Cells(4, 1).Value = "No result biopsy rate" Then datapulloverall.Range("AJ2:AJ50").Value = 0.04 overallstats.Range("A33").Value = "4% static" ElseIf overallstats.Cells(4, 1).Value = "IVF FR/Sperm Processor" Then datapulloverall.Range("AJ2:AJ50").Value = datapulloverall.Range("AG2").Value - (datapulloverall.Range("AG2").Value * 0.1) overallstats.Range("A33").Value = "Calc 10% below mean" ElseIf overallstats.Cells(4, 1).Value = "Necrotic Rate/Fert Assessor" Then datapulloverall.Range("AJ2:AJ50").Value = 0.04 overallstats.Range("A33").Value = "4% static" ElseIf overallstats.Cells(4, 1).Value = "IVF FR/Fert Assessor" Then datapulloverall.Range("AJ2:AJ50").Value = datapulloverall.Range("AG2").Value - (datapulloverall.Range("AG2").Value * 0.1) overallstats.Range("A33").Value = "Calc 10% below mean" ElseIf overallstats.Cells(4, 1).Value = "Ectopic Rate/Transfer Scientist" Then datapulloverall.Range("AJ2:AJ50").Value = datapulloverall.Range("AG2").Value + (datapulloverall.Range("AG2").Value * 0.1) overallstats.Range("A33").Value = "Calc 10% above mean" ElseIf overallstats.Cells(4, 1).Value = "PR/Thaw Embryologist" Then datapulloverall.Range("AJ2:AJ50").Value = datapulloverall.Range("AG2").Value - (datapulloverall.Range("AG2").Value * 0.1) overallstats.Range("A33").Value = "Calc 10% below mean" ElseIf overallstats.Cells(4, 1).Value = "PR/Freeze Embryologist" Then datapulloverall.Range("AJ2:AJ50").Value = datapulloverall.Range("AG2").Value - (datapulloverall.Range("AG2").Value * 0.1) overallstats.Range("A33").Value = "Calc 10% below mean" ElseIf overallstats.Cells(4, 1).Value = "PR/Biopsy Embryologist" Then datapulloverall.Range("AJ2:AJ50").Value = datapulloverall.Range("AG2").Value - (datapulloverall.Range("AG2").Value * 0.1) overallstats.Range("A33").Value = "Calc 10% below mean" ElseIf overallstats.Cells(4, 1).Value = "Not recovered rate by thaw" Then datapulloverall.Range("AJ2:AJ50").Value = datapulloverall.Range("AG2").Value * 2 overallstats.Range("A33").Value = "Above 2 x mean" ElseIf overallstats.Cells(4, 1).Value = "Not recovered rate by freeze" Then datapulloverall.Range("AJ2:AJ50").Value = datapulloverall.Range("AG2").Value * 2 overallstats.Range("A33").Value = "Above 2 x mean" ElseIf overallstats.Cells(4, 1).Value = "Not recovered rate by freeze" Then datapulloverall.Range("AJ2:AJ50").Value = datapulloverall.Range("AG2").Value * 2 overallstats.Range("A33").Value = "Above 2 x mean" ElseIf overallstats.Cells(4, 1).Value = "Damaged during biopsy rate" Then datapulloverall.Range("AJ2:AJ50").Value = 0.005 overallstats.Range("A33").Value = "0.5% static" ElseIf overallstats.Cells(4, 1).Value = "Usable Blast/ICSI Embryologist" Then datapulloverall.Range("AJ2:AJ50").Value = datapulloverall.Range("AG2").Value - (datapulloverall.Range("AG2").Value * 0.1) overallstats.Range("A33").Value = "Calc 10% below mean" Else datapulloverall.Range("AJ2:AJ50").Value = datapulloverall.Range("AG2").Value - 0.1 overallstats.Range("A33").Value = "-0.1" End If 'Update standard deviation column on Data Pull - Overall - NOT DYNAMIC row range datapulloverall.Range("AI2:AI50").Formula = "=IFERROR(MAX(AG2" &amp; overallstats.Cells(35, 1).Value &amp; "*SQRT(AG2*(1-AG2)/" &amp; sdformula &amp; ")),0)" For i = 2 To 50 nvalueformula = Left(Split(datapulloverall.Cells(i, catcol).Formula, "/")(1), Len(Split(datapulloverall.Cells(i, catcol).Formula, "/")(1)) - 3) datapulloverall.Range("AH" &amp; i).Formula = "=""n: "" &amp; " &amp; nvalueformula Next i topnum = 2 botnum = datapulloverall.Cells(datapulloverall.Rows.Count, individual).End(xlUp).Row With cht On Error Resume Next .FullSeriesCollection(4).Delete .FullSeriesCollection(3).Delete .FullSeriesCollection(2).Delete .FullSeriesCollection(1).Delete On Error GoTo 0 'Add the main series .SeriesCollection.NewSeries .FullSeriesCollection(1).Name = "=""" &amp; overallstats.Cells(4, 1).Value &amp; """" .FullSeriesCollection(1).Values = "='Data Pull - Overall'!$" &amp; ColumnLetter(catcol) &amp; "$" &amp; topnum &amp; ":$" &amp; ColumnLetter(catcol) &amp; "$" &amp; botnum .FullSeriesCollection(1).XValues = "='Data Pull - Overall'!$" &amp; ColumnLetter(individual) &amp; "$" &amp; topnum &amp; ":$" &amp; ColumnLetter(individual) &amp; "$" &amp; botnum .Axes(xlCategory, xlPrimary).AxisTitle.Text = title .SeriesCollection(1).HasDataLabels = True 'This line causing errors for whatever reason, 7-25-19 On Error Resume Next .SeriesCollection(1).DataLabels.Format.TextFrame2.TextRange.InsertChartField msoChartFieldRange, "='Data Pull - Overall'!$AH$2:$AH$" &amp; botnum, 0 On Error GoTo 0 .SeriesCollection(1).DataLabels.ShowRange = True .SeriesCollection(1).DataLabels.Separator = "" &amp; Chr(13) &amp; "" 'Add an average line .SeriesCollection.NewSeries .FullSeriesCollection(2).Name = "=""Average""" .FullSeriesCollection(2).Values = "='Data Pull - Overall'!$AG$2:$AG$" &amp; datapulloverall.Cells(datapulloverall.Rows.Count, individual).End(xlUp).Row .FullSeriesCollection(2).ChartType = xlLine .FullSeriesCollection(2).Format.Line.ForeColor.RGB = RGB(255, 0, 0) On Error Resume Next .FullSeriesCollection(2).DataLabels.ShowValue = False On Error GoTo 0 .FullSeriesCollection(2).Format.Line.Weight = 2 seriescount = 2 If overallstats.Cells(35, 2).Value = "Show" Then 'Add a SD line seriescount = seriescount + 1 .SeriesCollection.NewSeries .FullSeriesCollection(seriescount).Name = "=""Standard Deviation""" .FullSeriesCollection(seriescount).Values = "='Data Pull - Overall'!$AI$2:$AI$" &amp; datapulloverall.Cells(datapulloverall.Rows.Count, individual).End(xlUp).Row .FullSeriesCollection(seriescount).ChartType = xlLine .FullSeriesCollection(seriescount).Format.Line.ForeColor.RGB = RGB(128, 0, 128) End If On Error Resume Next .FullSeriesCollection(seriescount).DataLabels.ShowValue = False On Error GoTo 0 .FullSeriesCollection(seriescount).Format.Line.Weight = 2 If overallstats.Cells(33, 2).Value = "Show" Then 'Add an average minus 10 percent line seriescount = seriescount + 1 .SeriesCollection.NewSeries .FullSeriesCollection(seriescount).Name = "=""Average Minus 10""" .FullSeriesCollection(seriescount).Values = "='Data Pull - Overall'!$AJ$2:$AJ$" &amp; datapulloverall.Cells(datapulloverall.Rows.Count, individual).End(xlUp).Row .FullSeriesCollection(seriescount).ChartType = xlLine .FullSeriesCollection(seriescount).Format.Line.ForeColor.RGB = RGB(175, 0, 175) End If On Error Resume Next .FullSeriesCollection(seriescount).DataLabels.ShowValue = False On Error GoTo 0 .FullSeriesCollection(seriescount).Format.Line.Weight = 2 'The following adjusts the minimum and maximum values on the y-axis so we can better view the data If yaxisnumerical = False Then .Axes(xlValue).MinimumScale = 0 .Axes(xlValue).MaximumScale = 1 If overallstats.Cells(4, 1).Value = "Damaged during biopsy rate" Or _ overallstats.Cells(4, 1).Value = "Necrotic Rate/Fert Assessor" Then .Axes(xlValue).MinimumScale = 0 .Axes(xlValue).MaximumScale = 0.05 ElseIf InStr(overallstats.Cells(4, 1).Value, "Not recovered rate") Then .Axes(xlValue).MinimumScale = 0 .Axes(xlValue).MaximumScale = 0.1 ElseIf overallstats.Cells(4, 1).Value = "No result biopsy rate" Or _ overallstats.Cells(4, 1).Value = "Necrotic Rate/ICSI Embryologist" Then .Axes(xlValue).MinimumScale = 0 .Axes(xlValue).MaximumScale = 0.15 ElseIf InStr(overallstats.Cells(4, 1).Value, "Survival rate") Then .Axes(xlValue).MinimumScale = 0.9 .Axes(xlValue).MaximumScale = 1 ElseIf overallstats.Cells(4, 1).Value = "Ectopic Rate/Transfer Scientist" Then .Axes(xlValue).MinimumScale = 0 .Axes(xlValue).MaximumScale = 0.13 Else .Axes(xlValue).MinimumScale = 0 .Axes(xlValue).MaximumScale = 1 End If .Axes(xlValue).TickLabels.NumberFormat = "0.0%" .Axes(xlValue, xlPrimary).AxisTitle.Text = "Rate" Else .Axes(xlValue).MinimumScale = 0 .Axes(xlValue).MaximumScale = 35 .Axes(xlValue).TickLabels.NumberFormat = "0" .Axes(xlValue, xlPrimary).AxisTitle.Text = "Average # Eggs Retrieved" End If 'Color code bars based on satellite location Dim xvaluesarr As Variant Dim xval As Variant Dim j As Long xvaluesarr = .SeriesCollection(1).XValues j = 1 For Each xval In xvaluesarr .FullSeriesCollection(1).Points(j).Format.Fill.Visible = msoTrue 'Location 1 If xval = "AEF" Or xval = "KMJ" Or xval = "RGR" Then .FullSeriesCollection(1).Points(j).Format.Fill.ForeColor.RGB = RGB(0, 176, 80) 'Location 2 ElseIf xval = "MLF" Or xval = "BAS" Then 'Removed CP - not on the initials list from Marianne .FullSeriesCollection(1).Points(j).Format.Fill.ForeColor.RGB = RGB(192, 0, 0) 'Location 3 ElseIf xval = "CJT" Or xval = "RXS" Then 'Removed KH - not on the initials list from Marianne .FullSeriesCollection(1).Points(j).Format.Fill.ForeColor.RGB = RGB(225, 153, 0) 'Location 4 ElseIf xval = "TLL" Or xval = "LMH" Then .FullSeriesCollection(1).Points(j).Format.Fill.ForeColor.RGB = RGB(112, 48, 160) 'Location 5 ElseIf xval = "MJA" Or xval = "ADB" Then 'Removed AW - not on initials list from Marianne .FullSeriesCollection(1).Points(j).Format.Fill.ForeColor.RGB = RGB(45, 239, 239) 'Anyone else Else .FullSeriesCollection(1).Points(j).Format.Fill.ForeColor.RGB = RGB(11, 0, 228) End If .FullSeriesCollection(1).Points(j).Format.Fill.Solid j = j + 1 Next xval Dim mystr As String 'Get N Value mystr = "=" &amp; Replace(Left(Split(datapulloverall.Cells(2, catcol).Formula, "/")(1), Len(Split(datapulloverall.Cells(2, catcol).Formula, "/")(1)) - 3), "$" &amp; ColumnLetter(individual) &amp; "2", """*""") mystr = Replace(Replace(mystr, "$A$2", "'Data Pull - Overall'!A2"), "$B$2", "'Data Pull - Overall'!B2") overallstats.Cells(17, 1).Value = mystr updatecharts = False yaxisnumerical = False If overallstats.Cells(38, 22).Value &lt;&gt; "Presentation Mode" Then Call PopulateBottomTable End If Call PopulateOutofRangeInitials End With If Target.Address = "$A$4" Then overallstats.Cells(5, 1).Value = Target.Value If Target.Address = "$A$7" Then overallstats.Cells(8, 1).Value = Target.Value If Target.Address = "$A$10" Then overallstats.Cells(11, 1).Value = Target.Value If Target.Address = "$B$33" Then overallstats.Cells(34, 2).Value = Target.Value If Target.Address = "$B$35" Then overallstats.Cells(36, 2).Value = Target.Value 'Update the cell that says what the chart is displaying overallstats.Cells(8, 22).Value = Application.WorksheetFunction.VLookup(overallstats.Cells(4, 1).Value, ThisWorkbook.Worksheets("Data Validation").Range("N:Q"), 4, False) overallstats.Protect "pw" End If If overallstats.Cells(38, 22).Value = "Presentation Mode" Then Application.ScreenUpdating = True Application.EnableEvents = True End If Exit Sub ErroredOut: overallstats.Protect "pw" Debug.Print Err.Number Debug.Print Err.Description Application.ScreenUpdating = True Application.EnableEvents = True End Sub Function ColumnLetter(colnum As Long) As String ColumnLetter = Split(Cells(1, colnum).Address, "$")(1) End Function </code></pre>
[]
[ { "body": "<p>I'll answer your question on the best practice for checking multiple cells in a <code>Worksheet_Change</code> event, but I have some other comments that will hopefully help as well.</p>\n\n<ul>\n<li>The \"best practice\" I have used in <code>Worksheet_Change</code> events is to use the <code>Intersect</code> function. If you just make this a habit, then your code will be consistent (even if you're only checking a single cell). </li>\n</ul>\n\n<p>Because you have multiple cells on the worksheet to monitor, you want to compare the <code>Target</code> to a range. If the range is contiguous, then the check can be pretty straightforward:</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal target As Range)\n If Not Intersect(target, Range(\"A1:D25\") Is Nothing Then\n '--- respond to what changed here\n End If\nEnd Sub\n</code></pre>\n\n<p>Your situation is a bit trickier because you have multiple, non-contiguous cells to check. So for this I would create a function (in a separate module) that creates a single range (<code>Union</code>) for all the cells you need to monitor. That function looks like this:</p>\n\n<pre><code>Public Function DefinedWatchArea() As Range\n With Sheet1\n Set DefinedWatchArea = Union(.Range(\"$A$4\"), _\n .Range(\"$A$7\"), _\n .Range(\"$A$10\"), _\n .Range(\"$B$21\"), _\n .Range(\"$B$22\"), _\n .Range(\"$B$23\"), _\n .Range(\"$B$24\"), _\n .Range(\"$B$25\"), _\n .Range(\"$B$25\"), _\n .Range(\"$B$33\"), _\n .Range(\"$B$35\"))\n End With\nEnd Function\n</code></pre>\n\n<p>Note that the function must specify the worksheet, whereas the <code>Worksheet_Change</code> sub can rely on the currently active sheet to be the default (i.e. you don't need the dot <code>.</code> in front of <code>Range</code> in the <code>Worksheet_Change</code> sub). A function like this also makes it easier if you ever need to add or change the different cells to check.</p>\n\n<p>So now the change event sub for you would be:</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal target As Range)\n If Not Intersect(target, DefinedWatchArea()) Is Nothing Then\n If Not ValuesHaveChanged(target) Then\n UpdateStatsAndCharts\n End If\n End If\nEnd Sub\n</code></pre>\n\n<ul>\n<li>My next point is a guide for writing Excel event handlers such as this one. If the actions you need to take are anything more than a couple lines, it's best to create separate subs or functions in a separate code module. There are a couple reasons for this: the code is more easily re-used if it's in a code module, and it greatly simplifies the logic in the handler itself. Your <code>Worksheet_Change</code> sub is very long, and should be separated into multiple methods anyway.</li>\n</ul>\n\n<p>So let's look at my <code>ValuesHaveChanged</code> function. You need to check the value in several cells. Since it seemed that you may need to add more cells to check in the future, I've created a \"value map\" (in a <code>Dictionary</code>) that links the changed target cell address with a cell on your <code>overallStatus</code> worksheet. This map is created like this:</p>\n\n<pre><code>Public Function DefinedValueMap() As Dictionary\n Dim map As Dictionary\n Set map = New Dictionary\n With map\n .Add \"$A$4\", Array(5, 1)\n .Add \"$A$7\", Array(8, 1)\n .Add \"$A$10\", Array(11, 1)\n .Add \"$B$22\", Array(34, 2)\n .Add \"$B$35\", Array(36, 2)\n End With\n Set DefinedValueMap = map\nEnd Function\n</code></pre>\n\n<p>Of course, this makes it easier to change your map without changing the other logic since the map assignments are isolated in this single function.</p>\n\n<p>Now back in the <code>Worksheet_Change</code> sub when you call <code>ValuesHaveChanged</code>, it calls this function:</p>\n\n<pre><code>Public Function ValuesHaveChanged(ByRef target As Range) As Boolean\n Dim overallStats As Worksheet\n Set overallStats = ThisWorkbook.Worksheets(\"Overall Statistics\")\n\n Dim valueMap As Dictionary\n Set valueMap = DefinedValueMap()\n\n If valueMap.Exists(target.Address) Then\n Dim rowcol As Variant\n rowcol = valueMap(target.Address)\n If target.Value &lt;&gt; overallStats.Cells(rowcol(0), rowcol(1)).Value Then\n ValuesHaveChanged = False\n End If\n End If\nEnd Function\n</code></pre>\n\n<p>Creating a map in this fashion gets you out of a very long and confusing <code>If</code> statement or <code>Select Case</code> statement and keeps the logic cleaner and shorter.</p>\n\n<ul>\n<li>The same logic applies to the rest of your original code. Separate it out into logic sections that make it easier to follow. In my example of <code>UpdateStatsAndCharts</code>, I'm also creating another map for the statistics data and using that to assign some variables. </li>\n</ul>\n\n<p>I'm leaving the rest of the code for you to refactor along the same lines.</p>\n\n<pre><code> Public Function DefinedStatMap() As Dictionary\n Dim map As Dictionary\n Set map = New Dictionary\n With map\n '--- array item is (individual, title, nvaluetext)\n .Add \"ICSI Fert Rate\", Array(3, \"ICSI Scientist\", \"Total # ICSI'd\")\n .Add \"IVF FR/Sperm Processor\", Array(4, \"Sperm Processor\", \"Total # Mature Oocytes\")\n .Add \"Necrotic Rate/ICSI Embryologist\", Array(3, \"ICSI Scientist\", \"Total # Mature Oocytes\")\n .Add \"Necrotic Rate/Fert Assessor\", Array(5, \"Fert Assessor\", \"Total # Mature Oocytes\")\n .Add \"IVF FR/Fert Assessor\", Array(5, \"Fert Assessor\", \"Total # Mature Oocytes\")\n ' add all the others ...\n End With\n Set DefinedStatMap = map\nEnd Function\n\nPublic Sub UpdateStatsAndCharts()\n AppUpdates flagEnables:=False\n\n Dim statMap As Dictionary\n Set statMap = DefinedStatMap()\n\n Dim overallStats As Worksheet\n Set overallStats = ThisWorkbook.Worksheets(\"Overall Statistics\")\n\n Dim individual As Long\n Dim title As String\n Dim nvaluetext As String\n With overallStats\n If statMap.Exists(.Cells(4, 1).Value) Then\n Dim itemData As Variant\n itemData = statMap(.Cells(4, 1).Value)\n individual = itemData(0)\n title = itemData(1)\n nvaluetext = itemData(2)\n Else\n '--- what do you do if the value is not defined??\n MsgBox \"some kind of error!\"\n Exit Sub\n End If\n\n 'Repopulate the individuals lists on x-axis based on date\n Call PopulateDataPullOverallValidation\n\n '--- continue with the rest of your business logic...\n End With\n\n AppUpdates flagEnables:=True\nEnd Sub\n\nPublic Sub AppUpdates(ByVal flagEnables As Boolean)\n With Application\n .EnableEvents = flagEnables\n .ScreenUpdating = flagEnables\n End With\n\n Dim overallStats As Worksheet\n Set overallStats = ThisWorkbook.Worksheets(\"Overall Statistics\")\n If flagEnables Then\n overallStats.Protect \"bivf\"\n Else\n overallStats.Unprotect \"bivf\"\n End If\nEnd Sub\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T22:50:06.337", "Id": "237668", "ParentId": "237651", "Score": "3" } } ]
{ "AcceptedAnswerId": "237668", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T18:13:00.363", "Id": "237651", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "Best practice when checking multiple addresses for a Worksheet_Change() event?" }
237651
<p>Okay all you Linux/shell folks out there. This is my first shell script (2nd if you count "Hello World") and would appreciate some feedback. </p> <p>Basically, I need to test whether <code>htop</code> is installed; if it is, then move on; if it is not, then install it. If the user is root then just do it, and if not, sudo and install it. I have "borrowed" code from here to stitch this together. It works in my test environment. I would like to know:</p> <p>What did I miss? What other variables do I need to account for? Are there better ways to go about this?</p> <pre><code>if ! [ -x "$(command -v htop)" ]; then # set the var SUDO to "" (blank) SUDO="" # if the user ID is not 0 (root is 0) if [ $EUID != "0" ] ; then # set the var SUDO to "sudo" SUDO="sudo" fi # Let the user know it is not installed &amp; then install it, using sudo if not root echo 'Error: htop is not installed.' &amp;&amp; $SUDO apt install htop &gt;&amp;1 # exit the script exit 0 fi </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T21:42:46.337", "Id": "471704", "Score": "0", "body": "It's probably better, from a principle-of-least-surprise standpoint, to simply fail with an error message telling the user what to run, rather than running it for them. It's somewhat invasive to invoke `sudo` for a user if they haven't explicitly granted it (by running the script via `sudo` in the first place), and it's possible the user would prefer a different installation mechanism, such as compiling from source." } ]
[ { "body": "<p>Overall it's fine. My suggestions would be:</p>\n\n<ol>\n<li>Fix the indenting.</li>\n<li>If you find the comments helpful, great. Otherwise, consider saying \"why\" and not \"what\", e.g. <code># set the var SUDO to \"\" (blank)</code> -> <code># This will be used as a prefix to run a command as root</code></li>\n<li>You can alternatively consider checking if the command exists by running it: <code>if htop --version &gt; /dev/null 2&gt;&amp;1</code>. This does not discriminate against aliases, functions and builtins.</li>\n<li>Prefer user lowercase variable names to avoid conflicting with existing environment variables. <code>SUDO=\"sudo\"</code> is ok since <code>SUDO</code> isn't in use, but if you had tried the same with <code>PWD=\"pwd\"</code> or <code>SHELL=\"sh\"</code> you could have gotten some odd side effects. </li>\n<li>Use <code>echo 'Error: htop is not installed.' &gt;&amp;2</code> to write the error message to stderr</li>\n<li>The <code>&gt;&amp;1</code> aka <code>1&gt;&amp;1</code> is redundant: it just redirects the FD to where it's already going. </li>\n<li>It's generally considered rude to install packages without asking the user. A more canonical approach is to simply exit with an error saying that <code>htop</code> is missing and leave it to the user to install it (this also avoids tying the script to Ubuntu/Mint). </li>\n<li>If you continue when <code>htop</code> exists, why is the script exiting after installing <code>htop</code>? If it's to handle installation failures due to bad password or full disk, you should probably handle that explicitly.</li>\n<li>You can use <code>exit</code> aka <code>exit $?</code> to exit with the status of the previous command, so that if the installation failed, you don't claim that the script ran successfully.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T21:34:42.057", "Id": "466083", "Score": "0", "body": "Thank you. 1. Got it. 2. Its just there for me as i learn - so i can go back and remember what i was doing. But point taken. Thanks. 3. Got it. 4. good point. thanks. 5. Got it. 6. Got it. 7. This is purely for me, but i understand and appreciate the feedback. 8. That is really all i was trying to do in this script. 9. Got it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T19:49:18.873", "Id": "237656", "ParentId": "237652", "Score": "8" } }, { "body": "<p>In addition to the excellent <a href=\"/a/237656/75307\">answer by that other guy</a>:</p>\n\n<ol>\n<li><p>It's a good idea to start the script with a <em>shebang</em> specifying which interpreter to run. In this case, we're not using any Bash features not present in standard POSIX shell, so we can write</p>\n\n<pre><code>#!/bin/sh\n</code></pre></li>\n<li><p>Consider setting the flags <code>-u</code> (using unset variables is an error) and <code>-e</code> (exit when commands fail and are not otherwise tested):</p>\n\n<pre><code>set -eu\n</code></pre></li>\n<li><p>It's unusual to follow <code>echo</code> with <code>&amp;&amp;</code> - we're not depending on its success, so just use <code>;</code>.</p></li>\n<li><p>Don't exit with status 0 (success) when <code>apt</code> fails. The easy way to return its exit value is to replace the shell process using <code>exec</code>, like this:</p>\n\n<pre><code>exec $SUDO apt install htop\n# this line not reached\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T21:32:11.893", "Id": "466082", "Score": "0", "body": "Thank you. \n1. yes i just left that out when i pasted it in. \n2. I need to dig in to this and i am not sure i understand. \n3. Got it. \n4. Got it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T09:14:57.887", "Id": "466119", "Score": "0", "body": "For item 2, obviously read the manual, but also look at [BashFAQ/105](https://mywiki.wooledge.org/BashFAQ/105) for some pitfalls. Some argue that the pitfalls make `set -e` useless; I disagree, but add that it needs to be well understood to be effective and useful." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T20:36:33.170", "Id": "237659", "ParentId": "237652", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T19:12:44.367", "Id": "237652", "Score": "6", "Tags": [ "bash", "linux", "shell" ], "Title": "Test to see if installed and if not, install it" }
237652
<p>This is my first ever Python program. It checks every frame of a video file with Tesseract then uses OCR to recognise numbers in that frame and prints it to the console.</p> <pre><code>import pytesseract import os import cv2 import openpyxl from numpy import interp import numpy as np # Video URL TEST_VID = cv2.VideoCapture("VET2.mp4") READING, IMG = TEST_VID.read() # Frame Number INDEX = 0 # Colours black = [0, 0, 0] while READING: TEST_VID.set(1, INDEX) READING, IMG = TEST_VID.read() RET, FRAME = TEST_VID.read() # If I want to print images # print("new frame: ", READING) # if not RET: # break # # Assign a name for the file # NAME = "./image_frames/frame" + str(INDEX) + ".png" # # Assign the print statement # print("Extracting frames..." + NAME) # cv2.imwrite(NAME, FRAME) pixel = FRAME[2100, 1800] # If a pixel is black, use these values if np.all(pixel == black): # Image coordinates [y1:y2, x1:x2] speed = FRAME[2775:2883, 1199:1486] rpm = FRAME[2948:3014, 1190:1500] gear = FRAME[3187:3248, 1359:1415] # Tesseract directory pytesseract.pytesseract.tesseract_cmd = ( r"C:\Program Files\Tesseract-OCR\tesseract.exe" ) # Print KPH to console print( "Speed = " + pytesseract.image_to_string( speed, lang="formula1", config="--psm 7 -c tessedit_char_whitelist=0123456789", ) ) # cv2.imshow("speed", speed) # cv2.waitKey(0) # Print RPM to console print( "RPM = " + pytesseract.image_to_string( rpm, lang="formula1", config="--psm 7 -c tessedit_char_whitelist=0123456789", ) ) # cv2.imshow("rpm", rpm) # cv2.waitKey(0) # Print Gear to console print( "Gear = " + pytesseract.image_to_string( gear, lang="formula1", config="--psm 7 -c tessedit_char_whitelist=0123456789", ) ) # cv2.imshow("gear", gear) # cv2.waitKey(0) print(INDEX) INDEX += 1 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T19:25:34.017", "Id": "466066", "Score": "1", "body": "What version of python is this written in?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T19:26:27.357", "Id": "466067", "Score": "0", "body": "@Linny Python 3.7.3" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T22:40:11.850", "Id": "466090", "Score": "1", "body": "Welcome to Code Review! I rephrased your title to better follow the guidelines in [How do I ask a good question?](/help/how-to-ask) from the Help Center. An expressive title makes your question more appealing to reviewers." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T19:21:41.310", "Id": "237653", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "opencv" ], "Title": "Print numbers from video frames to console using pytesseract" }
237653
<p>I am using the following code within the footer of my test site. I am using WordPress and Advanced Custom Fields</p> <p>The intention is:</p> <ul> <li><p>To display the HTML container <code>.social-media--icons</code> if any of the fields contain content within the CMS. </p></li> <li><p>Then, within the container <code>.social-media--icons</code>, display the relevant icon and <code>href</code> if that field is filled.</p></li> </ul> <p>I have included <code>strlen(trim($twitter)) &gt; 0</code> as I understand this will detect if the field only has spaces.</p> <p>I appear to have this working locally and performing the above tasks. I am looking to find out if there is a clearer, optmisied method of performing these tasks</p> <pre><code>&lt;div class="site-info"&gt; &lt;a id="toTopButton" href="#pageTop" class="to-top-button"&gt;&lt;img src="&lt;?php echo get_template_directory_uri(); ?&gt;/svg/arrow.svg" alt="Up Arrow"&gt;&lt;/a&gt; &lt;p&gt;&amp;copy; &lt;?php echo date('Y'); ?&gt;&lt;/p&gt; &lt;?php $facebook = get_field('facebook', 'option'); $twitter = get_field('twitter', 'option'); $instagram = get_field('instagram', 'option'); ?&gt; &lt;?php if(isset($facebook) &amp;&amp; strlen(trim($facebook)) &gt; 0 || isset($twitter) &amp;&amp; strlen(trim($twitter)) &gt; 0 || isset($instagram) &amp;&amp; strlen(trim($instagram)) &gt; 0): ?&gt; &lt;div class="social-media--icons"&gt; &lt;?php if(isset($facebook) &amp;&amp; strlen(trim($facebook)) &gt; 0): ?&gt; &lt;a class="social-link ie9" href="&lt;?php echo $facebook; ?&gt;" target="_blank" rel="noopener"&gt; &lt;img src="&lt;?php echo get_template_directory_uri(); ?&gt;/svg/facebook.svg" alt="Facebook Icon"&gt; &lt;/a&gt; &lt;?php endif; ?&gt; &lt;?php if(isset($twitter) &amp;&amp; strlen(trim($twitter)) &gt; 0): ?&gt; &lt;a class="social-link ie9" href="&lt;?php echo $twitter; ?&gt;" target="_blank" rel="noopener"&gt; &lt;img src="&lt;?php echo get_template_directory_uri(); ?&gt;/svg/twitter.svg" alt="Twitter Icon"&gt; &lt;/a&gt; &lt;?php endif; ?&gt; &lt;?php if(isset($instagram) &amp;&amp; strlen(trim($instagram)) &gt; 0): ?&gt; &lt;a class="social-link ie9" href="&lt;?php echo $instagram; ?&gt;" target="_blank" rel="noopener"&gt; &lt;img src="&lt;?php echo get_template_directory_uri(); ?&gt;/svg/instagram.svg" alt="Instagram Icon"&gt; &lt;/a&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;/div&gt; </code></pre>
[]
[ { "body": "<p>Oh yes, I recommend some DRYing principles here. Don't ask php to do the same thing over and over for the same result in a loop -- execute those tasks, just once, before entering the loop.</p>\n\n<p>Rather than repeating whole portions of mark up only to change a few values, create a lookup array of the social networks that you want to cycle through and only replace those values in a reusable piece of the dom.</p>\n\n<p>The social variables are always going to be \"set\", because they are unconditionally declared when <code>get_field()</code> is called. There is no point in <code>isset()</code>.</p>\n\n<p>If there are any qualifying socials, then the parent <code>&lt;div&gt;</code> will enclose all qualifying <code>&lt;a&gt;</code>-tagged-wrapped <code>&lt;img&gt;</code>s.</p>\n\n<p>This ALSO makes it easy for you to scale your application. In case you ever want to add more socials in the future, just add a new element to <code>$socials</code> (assuming all of the other data is consistent) and you won't need to touch any part of the processing code.</p>\n\n<p>Code: (<a href=\"https://3v4l.org/f1Utl\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>$socials = ['facebook', 'twitter', 'instagram'];\n$templateDirectory = get_template_directory_uri();\nforeach ($socials as $social) {\n $socialHref = trim(get_field($social, 'option'));\n if (strlen($socialHref)) {\n $socialLinks[] = sprintf(\n '&lt;a class=\"social-link ie9\" href=\"%s\" target=\"_blank\" rel=\"noopener\"&gt;\n &lt;img src=\"%s/svg/%s.svg\" alt=\"%s Icon\"&gt;\n &lt;/a&gt;',\n $socialHref, $templateDirectory, $social, ucfirst($social)\n );\n }\n}\nif (isset($socialLinks)) {\n echo '&lt;div class=\"social-media--icons\"&gt;' , implode(' ', $socialLinks) , '&lt;/div&gt;';\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>&lt;div class=\"social-media--icons\"&gt;\n &lt;a class=\"social-link ie9\" href=\"blah-facebook-blah\" target=\"_blank\" rel=\"noopener\"&gt;&lt;img src=\"https://example.com/svg/facebook.svg\" alt=\"Facebook Icon\"&gt;&lt;/a&gt;\n &lt;a class=\"social-link ie9\" href=\"blah-twitter-blah\" target=\"_blank\" rel=\"noopener\"&gt;&lt;img src=\"https://example.com/svg/twitter.svg\" alt=\"Twitter Icon\"&gt;&lt;/a&gt;\n &lt;a class=\"social-link ie9\" href=\"blah-instagram-blah\" target=\"_blank\" rel=\"noopener\"&gt;&lt;img src=\"https://example.com/svg/instagram.svg\" alt=\"Instagram Icon\"&gt;&lt;/a&gt;\n&lt;/div&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T22:41:12.607", "Id": "237667", "ParentId": "237657", "Score": "2" } } ]
{ "AcceptedAnswerId": "237667", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T19:56:52.610", "Id": "237657", "Score": "2", "Tags": [ "php", "wordpress" ], "Title": "Display content if form field is filled - Do not display if field is empty" }
237657
<p>There has been <a href="https://github.com/dotnet/csharplang/issues/35" rel="nofollow noreferrer">ongoing concern</a> about the question of awaiting a task that could possibly be null, as when using null-coalescing operators. Consider the following:</p> <pre><code>var response = await turnContext?.SendActivityAsync("I am a bot"); </code></pre> <p>That will throw a run-time exception when <code>Instance</code> is null, as seen in questions like this: <a href="https://stackoverflow.com/questions/33592547/c-sharp-error-with-null-conditional-operator-and-await/33592569">https://stackoverflow.com/questions/33592547/c-sharp-error-with-null-conditional-operator-and-await/33592569</a></p> <p>Furthermore, if you use a <code>ConfiguredTaskAwaitable&lt;T&gt;</code> then the code won't even compile because it will be converted to a nullable struct that has no <code>GetAwaiter</code>:</p> <pre><code>var response = await turnContext?.SendActivityAsync("I am a bot").ConfigureAwait(false); </code></pre> <p>This can be made to compile by wrapping the null chain in parentheses so that <code>ConfigureAwait</code> remains a value type, but this will still cause null reference exceptions:</p> <pre><code>var response = await (turnContext?.SendActivityAsync("I am a bot")).ConfigureAwait(false); </code></pre> <p>To solve this issue, I've created an extension method to automatically check for nulls:</p> <pre><code>public static ConfiguredTaskAwaitable&lt;T&gt; CoalesceAwait&lt;T&gt;( this Task&lt;T&gt; task, bool continueOnCapturedContext = false) =&gt; (task ?? Task.FromResult&lt;T&gt;(default)).ConfigureAwait(continueOnCapturedContext); </code></pre> <p>This can be used in place of <code>ConfigureAwait</code>, and as a bonus I've made sure to have <code>continueOnCapturedContext</code> be false by default:</p> <pre><code>var response = await (turnContext?.SendActivityAsync("I am a bot")).CoalesceAwait(); </code></pre> <p>The only problem is that you still need to wrap the null chain in parentheses which can be sort of awkward. I look forward to seeing if this is useful to anyone or if anyone has any other feedback.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T20:54:35.340", "Id": "466075", "Score": "0", "body": "If you want to give an explanation for your downvotes, a website exists for that purpose: https://idownvotedbecau.se/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T21:24:30.793", "Id": "466079", "Score": "3", "body": "1) I didn't downvote. 2) I didn't know that site supported Code Review. 3) Your question is attracting votes to close for missing review context. 4) While I'm far from fluent in C# .NET, I could understand why people would want more context here. There's a good base, you ran into a problem and found a fix which you want reviewed, but it still looks like a snippet. Hypothetical even, something we [don't handle very well](//codereview.meta.stackexchange.com/q/1709). Perhaps providing an actual usage example in a piece of code you actually use would help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T22:09:56.537", "Id": "466084", "Score": "0", "body": "@Mast - That's good information, thanks. I thought I had provided enough context by explaining that the problem is universal to async/await, and explaining the details of my project would be lengthy and irrelevant in a post that's already a good length. In any case, I've updated my code samples so they don't look like pseudocode. Also, can you explain what you mean when you say \"I didn't know that site supported Code Review\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T22:12:10.020", "Id": "466085", "Score": "1", "body": "The good stuff is frequently downvoted on here, Kyle. Thanks for this useful bit." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T20:14:10.940", "Id": "237658", "Score": "1", "Tags": [ "c#", ".net", "async-await", "extension-methods", "null" ], "Title": "Extension method: Task<T>.CoalesceAwait" }
237658
<p>A simple design for task scheduling using the following classes/interfaces.</p> <pre><code>/// &lt;summary&gt; /// Represents an executable action. /// &lt;/summary&gt; public interface IExecutableTask { Task ExecuteAsync(); } /// &lt;summary&gt; /// A task which can be planned for execution. /// &lt;/summary&gt; public interface IPlannedTask : IExecutableTask { TimeSpan? GetExecutionDelay( DateTimeOffset? lastExecutedAt ); DateTimeOffset? GetExecutionTime( DateTimeOffset? lastExecutedAt ); } /// &lt;summary&gt; /// A task which can be scheduled to run periodically. /// &lt;/summary&gt; public interface IPeriodicTask : IPlannedTask { TimeSpan Frequency { get; } } /// &lt;summary&gt; /// A task which can be planned to run at specific times of the day. /// &lt;/summary&gt; public interface IScheduledTask : IPlannedTask { IReadOnlyList&lt;TimeSpan&gt; ExecutionTimes { get; } } </code></pre> <p>And as for the execution mechanism</p> <pre><code>public class PlannedTaskRegistration { public PlannedTaskRegistration( IPlannedTask task, Timer timer ) { Task = task; Timer = timer; } public IPlannedTask Task { get; set; } public Timer Timer { get; set; } public DateTimeOffset? LastExecutedAt { get; set; } public DateTimeOffset? NextExecutionAt { get; set; } public bool IsExecuting { get; set; } } public class TaskManager { private readonly List&lt;PlannedTaskRegistration&gt; _registrations = new List&lt;PlannedTaskRegistration&gt;(); private readonly object _lock = new object(); public bool IsEnabled { get; private set; } public void Add( IPlannedTask task ) { var registration = new PlannedTaskRegistration(task, null!); var timer = new Timer(TimerTick, registration, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); registration.Timer = timer; lock( _lock ) { _registrations.Add(registration); RescheduleTask(registration, false); } } public void Start() { lock( _lock ) { if( IsEnabled ) { return; } IsEnabled = true; foreach( var registration in _registrations.ToList() ) { RescheduleTask(registration, false); } } } public void Stop() { lock( _lock ) { if( !IsEnabled ) { return; } IsEnabled = false; foreach( var registration in _registrations ) { RescheduleTask(registration, false); } } } private async void TimerTick( object state ) { var registration = (PlannedTaskRegistration)state; try { lock( registration ) { if( registration.IsExecuting ) { return; } registration.IsExecuting = true; } registration.Timer.Change(Timeout.Infinite, Timeout.Infinite); await registration.Task.ExecuteAsync(); } catch { // catch/log exceptions } finally { // reschedule the task lock( _lock ) { RescheduleTask(registration, true); } } } private void RescheduleTask( PlannedTaskRegistration registration, bool isPostExecutionCall ) { lock( registration ) { if( registration.IsExecuting &amp;&amp; !isPostExecutionCall ) { // the task is executing right now, do not reschedule return; } var now = DateTimeOffset.Now; if( isPostExecutionCall ) { registration.LastExecutedAt = now; } if( IsEnabled ) { var executionDelay = registration.Task.GetExecutionDelay(now); if( executionDelay is null ) { _registrations.Remove(registration); } else { registration.NextExecutionAt = now.Add(executionDelay.Value); registration.Timer.Change(executionDelay.Value, Timeout.InfiniteTimeSpan); registration.IsExecuting = false; } } else { registration.NextExecutionAt = null; registration.Timer.Change(Timeout.Infinite, Timeout.Infinite); } } } } </code></pre> <p>This design allows the planning of two types of tasks that appear in the system</p> <ul> <li>Periodic tasks that should execute with a given frequency, no matter the time of day (e.g. deferred mail sending)</li> <li>Scheduled tasks that should execute at certain times of the day (e.g. system clean-ups at 3 am)</li> </ul> <p>Few of my observations/concerns</p> <ol> <li>I <code>lock</code> the whole collection processing, but I believe the time spent in the locked region is not excessive, plus I remove elements from the list. Lastly, I think it's very plausible given the use case for the class tip-toeing around locks could worsen performance (not too many tasks executing and their intersections are improbable).</li> <li>I think this design should protect me from unwanted multi-executions by, e.g. rapidly starting/stopping the <code>TaskManager</code>.</li> <li>I'm aware that stopping/starting the <code>TaskManager</code> while a task is running won't restart the task immediately and will reschedule it according to the "previous" schedule once it's done.</li> </ol> <p>Can you spot any bugs/possible edge-case unwanted behaviours? Any other flaws, such as unclear naming, etc.?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T20:51:38.863", "Id": "237660", "Score": "2", "Tags": [ "c#", "scheduled-tasks" ], "Title": "Task scheduling" }
237660
<p>I created a small sample project using <a href="https://github.com/ghostdogpr/caliban" rel="nofollow noreferrer">caliban</a>, <a href="https://github.com/akka/akka" rel="nofollow noreferrer">akka-persistence</a> and <a href="https://github.com/zio/zio" rel="nofollow noreferrer">ZIO</a>. I'm not really happy with the wiring code:</p> <pre class="lang-scala prettyprint-override"><code> implicit val defaultRuntime: DefaultRuntime = new DefaultRuntime {} val counter = context.spawn(Counter("counter"), "counter") val service: CounterService = defaultRuntime.unsafeRun(CounterService.make(counter, scheduler, timeout)) val graphQl = GraphQlApi(service) val routes = HttpRoutes(context.system, graphQl.interpreter) val serverBinding: Future[Http.ServerBinding] = Http()(untypedSystem).bindAndHandle(routes.counterRoutes(ec, defaultRuntime), "localhost", port) </code></pre> <p>The <code>CounterService</code> is wrapping the ask-calls to the persistent actor in a <code>zio.Task</code>:</p> <pre class="lang-scala prettyprint-override"><code>class CounterService(counter: ActorRef[Counter.Command], scheduler: Scheduler, timeout: Timeout) { implicit val s: Scheduler = scheduler implicit val t: Timeout = timeout def getCounter: Task[Counter.Count] = { ZIO.fromFuture { ec =&gt; counter ? GetCount } } } object CounterService { def make(countManager: ActorRef[Counter.Command], scheduler: Scheduler, timeout: Timeout): UIO[CounterService] = { for { manager &lt;- ZIO.succeed(countManager) } yield new CounterService(manager, scheduler, timeout) } } </code></pre> <p>For creating the <code>Routes</code> I need to pass the <code>GraphQLInterpreter</code>, the <code>ExecutionContext</code> and the <code>zio.Runtime</code>:</p> <pre class="lang-scala prettyprint-override"><code>case class HttpRoutes(system: ActorSystem[Nothing], interpreter: GraphQLInterpreter[zio.ZEnv, _]) { def counterRoutes(ec: ExecutionContext, runtime: Runtime[zio.ZEnv]): Route = { path("graphql") { AkkaHttpAdapter.makeHttpService(interpreter)(ec, runtime) } } } </code></pre> <p>The project compiles and I can execute graphql requests just fine. But I'm not satisfied (nor experienced) with wiring these libraries together. To me it feels like there is space for improvement on how to wire up these libraries but I'm kinda stuck.</p> <p>Does anyone has some input on this vague question? Any other advice/feedback to my code is much appreciated as well :)</p> <p>Full project source code can be found here: <a href="https://github.com/TobiasPfeifer/caliban-akka-persistence/blob/master/README.md" rel="nofollow noreferrer">link to github project</a></p>
[]
[ { "body": "<p>I think you did a pretty good job overall.</p>\n\n<p>You can simplify your code by making <code>CounterService.make</code> not return an effect since you only call <code>ZIO.succeed</code> in it. <code>make</code> can return directly a <code>CounterService</code> and that way no need to call <code>unsafeRun</code> in your main app.</p>\n\n<p>I also think that the <code>HttpRoutes</code> class is not really necessary since it only has a single method <code>counterRoutes</code> that you call once. You could just put this function inside an object and ditch the intermediate class. The values that are already implicit (execution context, runtime) can be passed implicitly as well.</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>def counterRoutes(interpreter: GraphQLInterpreter[zio.ZEnv, _])(\n implicit ec: ExecutionContext, runtime: Runtime[zio.ZEnv]): Route = {\n path(\"graphql\") {\n AkkaHttpAdapter.makeHttpService(interpreter)\n }\n }\n\nroutes.counterRoutes(graphQl.interpreter)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T18:10:24.163", "Id": "466189", "Score": "0", "body": "Thanks for your input. I've applied the changes you suggested. There is one more question regarding the `zio.Runtime`: For larger projects, should I create a `Runtime` that provides my services to the `GraphQLInterpreter` for dependency injection?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T01:00:49.363", "Id": "466230", "Score": "0", "body": "Yes, that is correct. You need a Runtime for whatever environment R you require in your interpreter. \n\nBy the way I just realized that you could reduce the code a bit more because Caliban accepts Futures directly in your schema, so you don’t need to wrap them all in Task. But if you’re interested I encourage you to also try a full ZIO version (without Akka), you’ll find it even shorter." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T14:30:45.980", "Id": "237700", "ParentId": "237662", "Score": "2" } } ]
{ "AcceptedAnswerId": "237700", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T20:58:51.320", "Id": "237662", "Score": "2", "Tags": [ "scala", "akka", "scalaz" ], "Title": "Integrating caliban, ZIO and Akka" }
237662
<blockquote> <p>Couple of items to make note of first:</p> <ul> <li>Some of the code is inherited the other has been refactored by me. The procedures that have an underscore in them I am still working on refactoring.</li> <li>I am still working through naming cells that I feel need to be named.</li> <li>This code below was re-factored once with help from @TinMan on <a href="https://codereview.stackexchange.com/questions/232999/inherited-code-worksheet-change-event-code">This Post</a></li> </ul> </blockquote> <p>All of the code below works and I dont have any real performance issues with it, but the issue I am running into is structuring the procedures to be easier to maintain and I fear that I am actually making the code harder to maintain.</p> <p>The long and short of this code is it looks to see what forms to create and the data to populate those forms with based on certain information being entered that are in the first 9 rows of Sheet1(Data Entry) and a few other cells. The code for populating the actual forms is not my concern; only the organization of the code and the use of the procedures I have created.</p> <p><strong>Class Module</strong></p> <pre><code>'WireCustInfo Class Option Explicit Public cust_Name As String Public cust_Address As String Public cust_CityStateZip As String Public cust_Zip As String Public cust_HomePhone As String Public cust_CellPhone As String Public cust_Phone As String Public cust_BSA As String Public TableName As String Public ErrNumber As Long Public Property Get CustomerName() As String CustomerName = cust_Name End Property Public Property Let CustomerName(value As String) CustomerName = value End Property Public Property Get CustomerAddress() As String CustomerAddress = cust_Address End Property Public Property Let CustomerAddres(value As String) CustomerAddress = value End Property Public Property Get CustomerCityStateZip() As String CustomerCityStateZip = cust_CityStateZip End Property Public Property Let CustomerCityStateZip(value As String) CustomerCityStateZip = value End Property Public Property Get CustomerZip() As String CustomerZip = cust_Zip End Property Public Property Let CustomerZip(value As String) CustomerZip = value End Property Public Property Get CustomerHomePhone() As String CustomerHomePhone = cust_HomePhone End Property Public Property Let CustomerHomePhone(value As String) CustomerHomePhone = value End Property Public Property Get CustomerCellPhone() As String CustomerCellPhone = cust_CellPhone End Property Public Property Let CustomerCellPhone(value As String) CustomerCellPhone = value End Property Public Property Get CustomerBSA() As String CustomerBSA = cust_BSA End Property Public Property Let CustomerBSA(value As String) CustomerBSA = value End Property </code></pre> <p><strong>Constant Variables (saved in their own standard module)</strong></p> <pre><code>Public Const CONNECTIONSTRING As String = Redacted for public viewing Public Const BRANSON As String = &quot;bhschlp8.jhadat842.cfmast cfmast&quot; Public Const CHARLOTTE As String = &quot;cncttp08.jhadat842.cfmast cfmast&quot; Public Const CONNECTIONERROR As Long = -2147467259 Public Const RECURRINGOUTGOINGIDMETHOD = &quot;The customer must have a Wire Transfer Agreement on file.&quot; &amp; _ &quot;The Customer must be physically present to establish a Recurring Request.&quot; Public Const OUTGOINGIDMETHOD = &quot;If the customer has a Wire Transfer Agreement on file, &quot; &amp; _ &quot;then we must use the Code Word/Pass Phrase/PIN listed in the agreement (unless the request was made in person).&quot; Public Const RECURRINGWORKBOOK As String = &quot;L:\Operations\Wire Transfers\Recurring Requests.xlsx&quot; Public DATAENTRY As Worksheet </code></pre> <p><strong>Sheet1 Object</strong></p> <pre><code>Option Explicit Private Sub RecuringList_Click() Workbooks.Open RECURRINGWORKBOOK End Sub Private Sub Worksheet_Change(ByVal Target As Range) Application.ScreenUpdating = False Application.EnableEvents = False '******************************************************* 'For ease of code maintenance the following procedures * 'that start with &quot;Entry&quot; and CreateAgreementRecurring * 'are in the ChangeFormatEvents Module. * '******************************************************* Select Case Target.Address Case Is = &quot;$B$4&quot; 'deIncWire EntryB4 Case Is = &quot;$B$5&quot; 'deOutgoingWireDDALoan EntryB5 Case Is = &quot;$B$6&quot; 'deOutgoingLoan EntryB6 Case Is = &quot;$B$7&quot; 'deOutgoingCM EntryB7 Case Is = &quot;$B$8&quot; 'deOutgoingBrokered EntryB8 Case Is = &quot;$B$9&quot; 'deOutgoingInternal EntryB9 Case Is = &quot;$B$10&quot;, &quot;$B$11&quot; 'deNewTransferAgreement, deNewRecurringRequest Hide_All With DATAENTRY If Not .Range(&quot;deNewTransferAgreement&quot;).value = vbNullString Then CreateAgreementRecurring CreateNewAgreement:=True, CreateRecurringRequest:=False End If If Not .Range(&quot;deNewRecurringRequest&quot;).value = vbNullString Then CreateAgreementRecurring CreateNewAgreement:=False, CreateRecurringRequest:=True End If If Not .Range(&quot;deNewTransferAgreement&quot;).value = vbNullString And Not .Range(&quot;deNewRecurringRequest&quot;).value = vbNullString Then CreateAgreementRecurring CreateNewAgreement:=True, CreateRecurringRequest:=True End If End With Dim wireTypeIs As String, CIFNum As String Case Is = &quot;$B$103&quot; If DATAENTRY.Range(&quot;B103&quot;) &lt;&gt; vbNullString Then CIFNum = DATAENTRY.Range(&quot;B103&quot;).value wireTypeIs = &quot;Incoming&quot; CIFGrab CIFNumber:=CIFNum, WireType:=wireTypeIs Else DATAENTRY.Range(&quot;B104:B107&quot;) = vbNullString End If Case Is = &quot;$B$205&quot; EntryB205 Case Is = &quot;$B$206&quot; If DATAENTRY.Range(&quot;B206&quot;).value &lt;&gt; vbNullString Then CIFNum = DATAENTRY.Range(&quot;B206&quot;).value wireTypeIs = &quot;OutGoingDDALoan&quot; CIFGrab CIFNumber:=CIFNum, WireType:=wireTypeIs Else DATAENTRY.Range(&quot;B207:B211&quot;) = vbNullString End If Case Is = &quot;$B$227&quot; EntryB227 Case Is = &quot;$B$269&quot; EntryB269 Case Is = &quot;$B$306&quot; EntryB306 Case Is = &quot;$B$307&quot; If DATAENTRY.Range(&quot;B307&quot;) &lt;&gt; vbNullString Then CIFNum = DATAENTRY.Range(&quot;B307&quot;).value wireTypeIs = &quot;OutGoingLoan&quot; CIFGrab CIFNumber:=CIFNum, WireType:=wireTypeIs Else DATAENTRY.Range(&quot;B308:B312&quot;) = vbNullString End If Case Is = &quot;$B$331&quot; EntryB331 Case Is = &quot;$B$373&quot; EntryB373 Case Is = &quot;$B$406&quot; EntryB406 Case Is = &quot;$B$407&quot; If DATAENTRY.Range(&quot;B407&quot;) &lt;&gt; vbNullString Then CIFNum = DATAENTRY.Range(&quot;B407&quot;).value wireTypeIs = &quot;OutGoingCM&quot; CIFGrab CIFNumber:=CIFNum, WireType:=wireTypeIs Else DATAENTRY.Range(&quot;B408:B411&quot;) = vbNullString End If Case Is = &quot;$B$425&quot; EntryB425 Case Is = &quot;$B$506&quot; If DATAENTRY.Range(&quot;B507&quot;) &lt;&gt; vbNullString Then CIFNum = DATAENTRY.Range(&quot;B507&quot;).value wireTypeIs = &quot;OutGoingBrokered&quot; CIFGrab CIFNumber:=CIFNum, WireType:=wireTypeIs Else DATAENTRY.Range(&quot;B507:B510&quot;) = vbNullString End If Case Is = &quot;$B$610&quot; EntryB610 Case Is = &quot;$B$5004&quot; EntryB5004 Case Is = &quot;$B$5105&quot; If DATAENTRY.Range(&quot;B5105&quot;) &lt;&gt; vbNullString Then CIFNum = DATAENTRY.Range(&quot;B5105&quot;).value wireTypeIs = &quot;Recurring&quot; CIFGrab CIFNumber:=CIFNum, WireType:=wireTypeIs Else DATAENTRY.Range(&quot;B5106:B5110&quot;) = vbNullString End If Case Is = &quot;$B$5118&quot; EntryB5118 End Select Application.ScreenUpdating = True Application.EnableEvents = True End Sub </code></pre> <p><strong>Procedures (Stored in Different Standard Modules)</strong></p> <pre><code>Option Explicit Dim Unique_Identifier As String Dim Wire_Type As String Public Sub EntryB4() With DATAENTRY Hide_All Select Case .Range(&quot;B4&quot;) Case Is &lt;&gt; &quot;&quot; .Range(&quot;A100:A199&quot;).EntireRow.Hidden = False .Range(&quot;B101&quot;).Select .Range(&quot;B5&quot;) = &quot;&quot; Case Else .Range(&quot;B5&quot;).Select End Select End With Sheet5.Visible = xlSheetVisible 'Confirmation-Incoming End Sub Public Sub EntryB5() With DATAENTRY Hide_All If Not .Range(&quot;B5&quot;) = vbNullString Then Select Case IsNumeric(.Range(&quot;B5&quot;)) Case Is = False .Range(&quot;A200:A211&quot;).EntireRow.Hidden = False .Range(&quot;A216:A227&quot;).EntireRow.Hidden = False .Range(&quot;C220&quot;) = OUTGOINGIDMETHOD .Range(&quot;B201&quot;).Select With ThisWorkbook Sheet7.Visible = xlSheetVisible 'Checklist Sheet4.Visible = xlSheetVisible 'Confirmation-Outgoing-1 Sheet2.Visible = xlSheetVisible 'Wire Transfer Request-1 End With Case Is = True CIFGrab CIFNumber:=.Range(&quot;B206&quot;).value, WireType:=&quot;OutGoingDDALoan&quot; .Range(&quot;A200:A220&quot;).EntireRow.Hidden = False .Range(&quot;A222,A226:A282&quot;).EntireRow.Hidden = False .Range(&quot;C220&quot;) = RECURRINGOUTGOINGIDMETHOD Unique_Identifier = .Range(&quot;B5&quot;).value Wire_Type = &quot;Deposit/Loan&quot; Call Find_Recurring(Unique_Identifier, Wire_Type) Sheet7.Visible = xlSheetVisible 'Checklist Sheet4.Visible = xlSheetVisible 'Confirmation-Outgoing-1 Sheet2.Visible = xlSheetVisible 'Wire Transfer Request-1 End Select Else Hide_All .Range(&quot;B6&quot;).Select End If End With End Sub Public Sub EntryB6() Hide_All With DATAENTRY If Not .Range(&quot;B6&quot;) = vbNullString Then Select Case IsNumeric(.Range(&quot;B6&quot;).Value2) Case Is = False .Range(&quot;A300:A312&quot;).EntireRow.Hidden = False .Range(&quot;A317:A331&quot;).EntireRow.Hidden = False .Range(&quot;B301&quot;).Select With ThisWorkbook Sheet3.Visible = xlSheetVisible 'Checklist-Loan Closing Sheet12.Visible = xlSheetVisible 'Confirmation-Outgoing-2 Sheet11.Visible = xlSheetVisible 'Wire Transfer Request-2 End With Case Is = True CIFGrab CIFNumber:=.Range(&quot;B307&quot;).value, WireType:=&quot;OutGoingLoan&quot; '.Range(&quot;A218:A220,A222:A223&quot;).EntireRow.Hidden = False .Range(&quot;A301:A312,A317:A319:A339&quot;).EntireRow.Hidden = False .Range(&quot;C220&quot;) = RECURRINGOUTGOINGIDMETHOD Unique_Identifier = .Range(&quot;B6&quot;).value Wire_Type = &quot;Loan Closing&quot; Call Find_Recurring(Unique_Identifier, Wire_Type) Sheet7.Visible = xlSheetVisible 'Checklist Sheet13.Visible = xlSheetVisible 'Wire Transfer Request - Brokered-Internet End Select .Range(&quot;B7&quot;).Select End If End With End Sub Public Sub EntryB7() Hide_All With DATAENTRY Select Case .Range(&quot;B7&quot;) Case Is &lt;&gt; &quot;&quot; .Range(&quot;A400:A412&quot;).EntireRow.Hidden = False .Range(&quot;A415:A499&quot;).EntireRow.Hidden = False .Range(&quot;B401&quot;).Select With ThisWorkbook Sheet9.Visible = xlSheetVisible 'Checklist-Cash Management Sheet14.Visible = xlSheetVisible 'Confirmation-Outgoing-3 End With Case Else Range(&quot;B8&quot;).Select End Select End With End Sub Public Sub EntryB8() Hide_All With DATAENTRY If Not .Range(&quot;B8&quot;) = vbNullString Then Select Case IsNumeric(.Range(&quot;B8&quot;).Value2) Case Is = False .Range(&quot;A500:A599&quot;).EntireRow.Hidden = False .Range(&quot;B501&quot;).Select With ThisWorkbook Sheet13.Visible = xlSheetVisible 'Wire Transfer Request - Brokered-Internet End With Case Else .Range(&quot;A218:A220,A222:A223&quot;).EntireRow.Hidden = False .Range(&quot;A501:A543&quot;).EntireRow.Hidden = False .Range(&quot;C220&quot;) = RECURRINGOUTGOINGIDMETHOD Unique_Identifier = .Range(&quot;B8&quot;).value Wire_Type = &quot;Brokered&quot; Call Find_Recurring(Unique_Identifier, Wire_Type) Sheet7.Visible = xlSheetVisible 'Checklist Sheet13.Visible = xlSheetVisible 'Wire Transfer Request - Brokered-Internet End Select Else Hide_All .Range(&quot;B9&quot;).Select End If End With End Sub Public Sub EntryB9() Hide_All With DATAENTRY If Not .Range(&quot;B9&quot;) = &quot;&quot; Then Select Case IsNumeric(.Range(&quot;B9&quot;)) Case Is = False .Range(&quot;A600:A610&quot;).EntireRow.Hidden = False .Range(&quot;B601&quot;).Select Sheet8.Visible = xlSheetVisible 'Checklist-Internal Case Is = True .Range(&quot;A222,A223&quot;).EntireRow.Hidden = False .Range(&quot;A600:A699&quot;).EntireRow.Hidden = False Unique_Identifier = Range(&quot;B9&quot;).value Wire_Type = &quot;Internal&quot; Call Find_Recurring(Unique_Identifier, Wire_Type) End Select Else Hide_All Range(&quot;B10&quot;).Select End If End With End Sub Public Sub EntryB205() With DATAENTRY Select Case LCase$(.Range(&quot;B205&quot;)) Case Is = &quot;yes&quot; .Rows(&quot;212:215&quot;).Hidden = False Case Else .Rows(&quot;212:215&quot;).Hidden = True .Range(&quot;B206&quot;).Select End Select End With End Sub Public Sub EntryB227() With DATAENTRY Select Case LCase$(.Range(&quot;B227&quot;)) Case Is = &quot;domestic&quot; .Range(&quot;A222:A243&quot;).EntireRow.Hidden = False .Range(&quot;A267:A299&quot;).EntireRow.Hidden = False .Range(&quot;A244:A266&quot;).EntireRow.Hidden = True .Range(&quot;B229&quot;).Select Case Is = &quot;international&quot; .Range(&quot;A244:A299&quot;).EntireRow.Hidden = False .Range(&quot;A228:A243&quot;).EntireRow.Hidden = True .Range(&quot;B245&quot;).Select Case Is &lt;&gt; &quot;international&quot;, &quot;domestic&quot; .Range(&quot;A228:A299&quot;).EntireRow.Hidden = True .Range(&quot;B227&quot;).Select End Select End With End Sub Public Sub EntryB269() With DATAENTRY Select Case LCase$(.Range(&quot;B269&quot;)) Case Is = &quot;yes&quot; Sheets(&quot;Wire Transfer Agreement&quot;).Visible = True .Range(&quot;A5000:A5099&quot;).EntireRow.Hidden = False .Range(&quot;B282:B299&quot;).EntireRow.Hidden = True Application.ScreenUpdating = True .Range(&quot;B5001&quot;).Select Case Else Sheets(&quot;Wire Transfer Agreement&quot;).Visible = False .Range(&quot;A5000:A5099&quot;).EntireRow.Hidden = True .Range(&quot;B281:B299&quot;).EntireRow.Hidden = False .Range(&quot;B270&quot;).Select End Select End With End Sub Public Sub EntryB306() With DATAENTRY Select Case LCase$(.Range(&quot;B306&quot;)) Case Is = &quot;yes&quot; .Range(&quot;A313:A316,A331&quot;).EntireRow.Hidden = False Case Else .Range(&quot;A313:A316&quot;).EntireRow.Hidden = True .Range(&quot;A331&quot;).EntireRow.Hidden = False .Range(&quot;B307&quot;).Select End Select End With End Sub Public Sub EntryB331() With DATAENTRY Select Case LCase$(.Range(&quot;B331&quot;)) Case Is = &quot;domestic&quot; .Range(&quot;A332:A347&quot;).EntireRow.Hidden = False .Range(&quot;A370:A399&quot;).EntireRow.Hidden = False .Range(&quot;A348:A369&quot;).EntireRow.Hidden = True .Range(&quot;B331&quot;).Select Case Is = &quot;international&quot; .Range(&quot;A347:A399&quot;).EntireRow.Hidden = False .Range(&quot;A332:A346&quot;).EntireRow.Hidden = True .Range(&quot;B349&quot;).Select Case Is &lt;&gt; &quot;domestic&quot;, &quot;international&quot; .Range(&quot;A332:A399&quot;).EntireRow.Hidden = True .Range(&quot;B331&quot;).Select End Select End With End Sub Public Sub EntryB373() With DATAENTRY Select Case LCase$(.Range(&quot;B373&quot;)) Case Is = &quot;yes&quot; Sheets(&quot;Wire Transfer Agreement&quot;).Visible = True .Range(&quot;A5000:A5099&quot;).EntireRow.Hidden = False .Range(&quot;B383:B399&quot;).EntireRow.Hidden = True Application.ScreenUpdating = True .Range(&quot;B5001&quot;).Select Case Else Sheets(&quot;Wire Transfer Agreement&quot;).Visible = False .Range(&quot;A5000:A5099&quot;).EntireRow.Hidden = True .Range(&quot;B383:B399&quot;).EntireRow.Hidden = False .Range(&quot;B374&quot;).Select End Select End With End Sub Public Sub EntryB406() With DATAENTRY Select Case LCase$(.Range(&quot;B406&quot;)) Case Is = &quot;yes&quot; .Range(&quot;A412:A413&quot;).EntireRow.Hidden = False Case Else .Range(&quot;A412:A413&quot;).EntireRow.Hidden = True .Range(&quot;B407&quot;).Select End Select End With End Sub Public Sub EntryB425() With DATAENTRY Select Case LCase$(.Range(&quot;B425&quot;)) Case Is = &quot;yes&quot; .Range(&quot;A430:A431&quot;).EntireRow.Hidden = False Case Else .Range(&quot;A430:A431&quot;).EntireRow.Hidden = True .Range(&quot;B426&quot;).Select End Select End With End Sub Public Sub EntryB610() With DATAENTRY Select Case LCase$(.Range(&quot;B610&quot;)) Case Is = &quot;domestic&quot; .Range(&quot;A611:A625&quot;).EntireRow.Hidden = False .Range(&quot;A648:A699&quot;).EntireRow.Hidden = False .Range(&quot;A626:A647&quot;).EntireRow.Hidden = True .Range(&quot;B612&quot;).Select Case Is = &quot;international&quot; .Range(&quot;A626:A699&quot;).EntireRow.Hidden = False .Range(&quot;A611:A625&quot;).EntireRow.Hidden = True .Range(&quot;B627&quot;).Select Case Is &lt;&gt; &quot;international&quot;, &quot;domestic&quot; .Range(&quot;A611:A699&quot;).EntireRow.Hidden = True .Range(&quot;B610&quot;).Select End Select End With End Sub Public Sub EntryB5004() With DATAENTRY .Range(&quot;A5005:A5011&quot;).EntireRow.Hidden = True .Range(&quot;B5004&quot;).Select Select Case LCase$(.Range(&quot;B5004&quot;)) Case Is = &quot;entity&quot; .Range(&quot;A5007:A5011&quot;).EntireRow.Hidden = False .Range(&quot;B5007&quot;).Select Case Is = &quot;individual(s)&quot; .Range(&quot;A5005:A5006&quot;).EntireRow.Hidden = False .Range(&quot;B5005&quot;).Select End Select End With End Sub Public Sub EntryB5104() With DATAENTRY .Range(&quot;A5111:A5114&quot;).EntireRow.Hidden = True .Range(&quot;B5105&quot;).Select Select Case LCase$(.Range(&quot;B5104&quot;)) Case Is = &quot;yes&quot; .Range(&quot;A5111:A5114&quot;).EntireRow.Hidden = False .Range(&quot;B5105&quot;).Select Case Is = &quot;no&quot; .Range(&quot;A5111:A5114&quot;).EntireRow.Hidden = True .Range(&quot;B5105&quot;).Select End Select End With End Sub Public Sub EntryB5118() With DATAENTRY Select Case LCase$(.Range(&quot;B5118&quot;)) Case Is = &quot;domestic&quot; .Range(&quot;A5119:A5131&quot;).EntireRow.Hidden = False .Range(&quot;A5132:A5199&quot;).EntireRow.Hidden = True .Range(&quot;A5150&quot;).EntireRow.Hidden = False .Range(&quot;B5120&quot;).Select Case Is = &quot;international&quot; .Range(&quot;A5119:A5131&quot;).EntireRow.Hidden = True .Range(&quot;A5132:A5149&quot;).EntireRow.Hidden = False .Range(&quot;A5151:A5199&quot;).EntireRow.Hidden = True .Range(&quot;B5133&quot;).Select Case Is &lt;&gt; &quot;international&quot;, &quot;domestic&quot; .Range(&quot;A5119:A5199&quot;).EntireRow.Hidden = True .Range(&quot;B5118&quot;).Select End Select End With End Sub Public Sub CreateAgreementRecurring(ByVal CreateNewAgreement As Boolean, ByVal CreateRecurringRequest As Boolean) If CreateNewAgreement And CreateRecurringRequest = False Then Sheet6.Visible = xlSheetVisible 'Wire Transfer Agreement With DATAENTRY .Range(&quot;A5000:A5099&quot;).EntireRow.Hidden = False '.Range(&quot;A5005:A5011&quot;).EntireRow.Hidden = True .Range(&quot;B5001&quot;).Select End With End If If CreateNewAgreement = False And CreateRecurringRequest Then Sheet18.Visible = xlSheetVisible 'Recurring Wire Transfer Request With DATAENTRY .Range(&quot;B218:B225&quot;).EntireRow.Hidden = False .Range(&quot;C220&quot;) = RECURRINGOUTGOINGIDMETHOD .Range(&quot;A5100:A5118&quot;).EntireRow.Hidden = False '.Range(&quot;A5111:A5114&quot;).EntireRow.Hidden = True .Range(&quot;A5087:A5099&quot;).EntireRow.Hidden = True .Range(&quot;B5101&quot;).Select Sheet7.Visible = xlSheetVisible 'Checklist End With End If If CreateNewAgreement And CreateRecurringRequest Then Sheet6.Visible = xlSheetVisible 'Wire Transfer Agreement Sheet18.Visible = xlSheetVisible 'Recurring Wire Transfer Request With DATAENTRY .Range(&quot;C220&quot;) = RECURRINGOUTGOINGIDMETHOD .Range(&quot;A5000:A5099&quot;).EntireRow.Hidden = False '.Range(&quot;A5005:A5011&quot;).EntireRow.Hidden = True .Range(&quot;B5001&quot;).Select .Range(&quot;A5100:A5118&quot;).EntireRow.Hidden = False '.Range(&quot;A5111:A5114&quot;).EntireRow.Hidden = True .Range(&quot;A5087:A5099&quot;).EntireRow.Hidden = True '.Range(&quot;B5101&quot;).Select Sheet7.Visible = xlSheetVisible 'Checklist End With End If End Sub </code></pre> <pre><code>Option Explicit Public Sub CIFGrab(ByVal CIFNumber As String, WireType As String) Dim tDBGrabRecord As WireCustInfo Set tDBGrabRecord = getCIFDBGrabTestRecord(Array(BRANSON, CHARLOTTE), CIFNumber) If tDBGrabRecord Is Nothing Then MsgBox &quot;Failed to get record&quot;, vbExclamation Else Select Case WireType Case Is = &quot;Incoming&quot; With DATAENTRY .Range(&quot;B104&quot;) = tDBGrabRecord.CustomerName .Range(&quot;B105&quot;) = tDBGrabRecord.CustomerAddress .Range(&quot;B107&quot;) = tDBGrabRecord.CustomerCityStateZip End With Case Is = &quot;OutGoingDDALoan&quot; With DATAENTRY .Range(&quot;B207&quot;) = tDBGrabRecord.CustomerName .Range(&quot;B208&quot;) = tDBGrabRecord.CustomerAddress .Range(&quot;B209&quot;) = tDBGrabRecord.CustomerCityStateZip If tDBGrabRecord.CustomerHomePhone = 0 Or tDBGrabRecord.CustomerHomePhone = &quot;&quot; Then .Range(&quot;B210&quot;) = Format(tDBGrabRecord.CustomerCellPhone, &quot;(###) ###-####&quot;) ElseIf tDBGrabRecord.CustomerCellPhone = 0 Then .Range(&quot;B210&quot;) = Format(tDBGrabRecord.CustomerHomePhone, &quot;(###) ###-####&quot;) ElseIf tDBGrabRecord.CustomerHomePhone = 0 And tDBGrabRecord.CustomerCellPhone = 0 Then .Range(&quot;B210&quot;) = vbNullString End If .Range(&quot;B211&quot;) = tDBGrabRecord.CustomerBSA End With Case Is = &quot;OutGoingLoan&quot; With DATAENTRY .Range(&quot;B308&quot;) = tDBGrabRecord.CustomerName .Range(&quot;B309&quot;) = tDBGrabRecord.CustomerAddress .Range(&quot;B310&quot;) = tDBGrabRecord.CustomerCityStateZip If tDBGrabRecord.CustomerHomePhone = 0 Then .Range(&quot;B311&quot;) = Format(tDBGrabRecord.CustomerCellPhone, &quot;(###) ###-####&quot;) ElseIf tDBGrabRecord.CustomerCellPhone = 0 Then .Range(&quot;B311&quot;) = Format(tDBGrabRecord.CustomerHomePhone, &quot;(###) ###-####&quot;) ElseIf tDBGrabRecord.CustomerHomePhone = 0 And tDBGrabRecord.CustomerCellPhone = 0 Then .Range(&quot;B311&quot;) = vbNullString End If .Range(&quot;B312&quot;) = tDBGrabRecord.CustomerBSA End With Case Is = &quot;OutGoingCM&quot; With DATAENTRY .Range(&quot;B408&quot;) = tDBGrabRecord.CustomerName .Range(&quot;B409&quot;) = tDBGrabRecord.CustomerAddress .Range(&quot;B410&quot;) = tDBGrabRecord.CustomerCityStateZip If tDBGrabRecord.CustomerHomePhone = 0 Then .Range(&quot;B411&quot;) = Format(tDBGrabRecord.CustomerCellPhone, &quot;(###) ###-####&quot;) ElseIf tDBGrabRecord.CustomerCellPhone = 0 Then .Range(&quot;B411&quot;) = Format(tDBGrabRecord.CustomerHomePhone, &quot;(###) ###-####&quot;) ElseIf tDBGrabRecord.CustomerHomePhone = 0 And tDBGrabRecord.CustomerCellPhone = 0 Then .Range(&quot;B411&quot;) = vbNullString End If .Range(&quot;B412&quot;) = tDBGrabRecord.CustomerBSA End With Case Is = &quot;OutGoingBrokered&quot; With DATAENTRY .Range(&quot;B507&quot;) = tDBGrabRecord.CustomerName .Range(&quot;B508&quot;) = tDBGrabRecord.CustomerAddress .Range(&quot;B509&quot;) = tDBGrabRecord.CustomerCityStateZip If tDBGrabRecord.CustomerHomePhone = 0 Then .Range(&quot;B510&quot;) = Format(tDBGrabRecord.CustomerCellPhone, &quot;(###) ###-####&quot;) ElseIf tDBGrabRecord.CustomerCellPhone = 0 Then .Range(&quot;B510&quot;) = Format(tDBGrabRecord.CustomerHomePhone, &quot;(###) ###-####&quot;) ElseIf tDBGrabRecord.CustomerHomePhone = 0 And tDBGrabRecord.CustomerCellPhone = 0 Then .Range(&quot;B510&quot;) = vbNullString End If End With Case Is = &quot;Recurring&quot; With DATAENTRY .Range(&quot;B5106&quot;) = tDBGrabRecord.CustomerName .Range(&quot;B5107&quot;) = tDBGrabRecord.CustomerAddress .Range(&quot;B5108&quot;) = tDBGrabRecord.CustomerCityStateZip If tDBGrabRecord.CustomerHomePhone = 0 Then .Range(&quot;B5109&quot;) = Format(tDBGrabRecord.CustomerCellPhone, &quot;(###) ###-####&quot;) ElseIf tDBGrabRecord.CustomerCellPhone = 0 Then .Range(&quot;B5109&quot;) = Format(tDBGrabRecord.CustomerHomePhone, &quot;(###) ###-####&quot;) ElseIf tDBGrabRecord.CustomerHomePhone = 0 And tDBGrabRecord.CustomerCellPhone = 0 Then .Range(&quot;B5109&quot;) = vbNullString End If .Range(&quot;B5110&quot;) = tDBGrabRecord.CustomerBSA End With End Select 'PopulateCIFBasedOnTheWireType wireTypeIs:=WireType End If End Sub Private Function getCIFDBGrabTestRecord(arrNames, ByVal CustNum As String) As WireCustInfo Dim conn As New ADODB.Connection Dim rs As New ADODB.Recordset Dim SQL As String, nm, okSQL As Boolean Dim tDBGrabRecord As WireCustInfo conn.Open CONNECTIONSTRING For Each nm In arrNames SQL = getCIFDBGrabSQL(CStr(nm), CustNum) On Error Resume Next rs.Open SQL, conn If Err.Number = 0 Then okSQL = True On Error GoTo 0 If okSQL Then If Not rs.EOF Then Set tDBGrabRecord = New WireCustInfo With tDBGrabRecord .cust_Name = Trim(rs.Fields(0).value) .cust_Address = Trim(rs.Fields(1).value) .cust_CityStateZip = Trim(rs.Fields(2).value) .cust_HomePhone = Trim(rs.Fields(3).value) .cust_CellPhone = Trim(rs.Fields(4).value) .cust_BSA = Trim(rs.Fields(5).value) End With End If Exit For End If Next nm If rs.State = adStateOpen Then rs.Close If conn.State = adStateOpen Then conn.Close Set getCIFDBGrabTestRecord = tDBGrabRecord End Function Private Function getCIFDBGrabSQL(ByVal TableName As String, ByVal CIF As String) As String Dim SelectClause As String, _ FromClause As String, _ WhereClause As String SelectClause = GetSelectClause FromClause = &quot;FROM &quot; &amp; TableName WhereClause = &quot;WHERE cfcif# = '&quot; &amp; CIF &amp; &quot;'&quot; getCIFDBGrabSQL = SelectClause &amp; vbNewLine &amp; FromClause &amp; vbNewLine &amp; WhereClause 'Debug.Print getCIFDBGrabSQL End Function Private Function GetSelectClause() As String Const Delimiter As String = vbNewLine Dim list As Object Set list = CreateObject(&quot;System.Collections.ArrayList&quot;) With list .Add &quot;SELECT cfna1,&quot; .Add &quot;COALESCE(NULLIF(RTRIM(LTRIM(cfpfa1))|| ' '|| RTRIM(LTRIM(cfpfa2)), ''),RTRIM(LTRIM(cfna2))|| ' ' || RTRIM(LTRIM(cfna3))),&quot; .Add &quot;RTRIM(LTRIM(cfcity)) || ', ' || RTRIM(LTRIM(cfstat)) || ', ' || RTRIM(LTRIM(LEFT(cfzip,5))),&quot; .Add &quot;cfhpho,&quot; .Add &quot;cfcel1,&quot; .Add &quot;cfudsc6&quot; End With GetSelectClause = Join(list.ToArray, Delimiter) End Function </code></pre> <pre><code>Option Explicit Public Sub Hide_All() 'Used a Loop through the worksheet code names instead of identifying the sheets individually. 'Helps use less memory and also if the &quot;Sheet Name&quot; is ever changed 'by a user the code wont break. Range(&quot;A12:A9999&quot;).EntireRow.Hidden = True Dim sh As Worksheet Dim i As Integer For i = 2 To 15 For Each sh In ThisWorkbook.Worksheets If sh.CodeName = &quot;Sheet&quot; &amp; i Then sh.Visible = xlSheetHidden Next sh Next i Sheet18.Visible = xlSheetHidden End Sub Public Sub Find_Recurring(ByVal Unique_Identifier As String, Wire_Type As String) Dim srcWB As Workbook, destWB As Workbook Dim srcWS As Worksheet, destWS As Worksheet Dim FoundCell As Range Dim Row As Long Set srcWB = Workbooks.Open(RECURRINGWORKBOOK) Select Case Wire_Type Case Is = &quot;Deposit/Loan&quot;, &quot;Brokered&quot;, &quot;Loan Closing&quot; Set srcWS = srcWB.Sheets(&quot;Recurring Requests&quot;) Case Is = &quot;Internal&quot; Set srcWS = srcWB.Sheets(&quot;Internal Requests&quot;) End Select Set destWB = ThisWorkbook Set destWS = destWB.Sheets(&quot;Data Entry&quot;) Set FoundCell = srcWS.Range(&quot;A:A&quot;).Find(What:=Unique_Identifier) If Not FoundCell Is Nothing Then Row = FoundCell.Row 'Deposit account/loan account (post closing) (Cell B5) If Wire_Type = &quot;Deposit/Loan&quot; Then destWS.Range(&quot;A222:A243&quot;).EntireRow.Hidden = False destWS.Range(&quot;A267:A299&quot;).EntireRow.Hidden = False destWS.Range(&quot;A244:A266&quot;).EntireRow.Hidden = True destWS.Range(&quot;B206&quot;) = srcWS.Cells(Row, 5) 'CIF NUmber 'destWS.Range(&quot;B507&quot;) = srcWS.Cells(Row, 6) 'Name 'destWS.Range(&quot;B508&quot;) = srcWS.Cells(Row, 7) 'Address 'destWS.Range(&quot;B509&quot;) = srcWS.Cells(Row, 8) 'City State Zip 'destWS.Range(&quot;B510&quot;) = srcWS.Cells(Row, 9) 'Telephone Number destWS.Range(&quot;B216&quot;) = srcWS.Cells(Row, 15) 'Customer Account Number destWS.Range(&quot;B217&quot;) = srcWS.Cells(Row, 16) 'Account Number to Fund Wire destWS.Range(&quot;B227&quot;) = srcWS.Cells(Row, 17) 'Domestic/International Select Case LCase$(srcWS.Cells(Row, 17)) 'THIS HANDLES FINANCIAL INSTITUTION INFO FOR RECURRING INFO FOR DOMESTIC WIRES Case Is = &quot;domestic&quot; destWS.Range(&quot;B229&quot;) = srcWS.Cells(Row, 19) 'Financial Institution Name destWS.Range(&quot;B230&quot;) = srcWS.Cells(Row, 20) 'Routing ABA Number destWS.Range(&quot;B231&quot;) = srcWS.Cells(Row, 21) 'Financial Institution Phone Number destWS.Range(&quot;B232&quot;) = srcWS.Cells(Row, 22) 'Financial Institution Address destWS.Range(&quot;B233&quot;) = srcWS.Cells(Row, 23) 'Beneficiary Name destWS.Range(&quot;B234&quot;) = srcWS.Cells(Row, 24) 'Beneficiary Account Number destWS.Range(&quot;B235&quot;) = srcWS.Cells(Row, 25) 'Beneficiary Physical Address destWS.Range(&quot;B237&quot;) = srcWS.Cells(Row, 27) 'Intermediary Financial Institution Name destWS.Range(&quot;B238&quot;) = srcWS.Cells(Row, 28) 'Intermediary Financial ABA/Routing Number destWS.Range(&quot;B239&quot;) = srcWS.Cells(Row, 29) 'Intermediary Address destWS.Range(&quot;B240&quot;) = srcWS.Cells(Row, 30) 'Intermediary Account Number Case Is = &quot;international&quot; End Select '*********THIS WILL ALL BE HANDLED IN THE CODE SEGMENT ABOVE***** 'Hide domestic/international data-input rows as applicable 'Select Case LCase$(destWS.Range(&quot;B227&quot;)) ' Case Is = &quot;domestic&quot; ' Range(&quot;A222:A243&quot;).EntireRow.Hidden = False ' Range(&quot;A267:A299&quot;).EntireRow.Hidden = False ' Range(&quot;A244:A266&quot;).EntireRow.Hidden = True ' Range(&quot;B201&quot;).Select ' Case Is = &quot;international&quot; ' Range(&quot;A244:A299&quot;).EntireRow.Hidden = False ' Range(&quot;A228:A243&quot;).EntireRow.Hidden = True ' Range(&quot;B201&quot;).Select ' Case Is &lt;&gt; &quot;international&quot;, &quot;domestic&quot; ' Range(&quot;A228:A299&quot;).EntireRow.Hidden = True ' Range(&quot;B201&quot;).Select 'End Select ElseIf Wire_Type = &quot;Brokered&quot; Then destWS.Range(&quot;B502:B533&quot;).ClearContents destWS.Range(&quot;B506&quot;) = srcWS.Cells(Row, 5) 'CIF NUmber 'destWS.Range(&quot;B507&quot;) = srcWS.Cells(Row, 6) 'Name 'destWS.Range(&quot;B508&quot;) = srcWS.Cells(Row, 7) 'Address 'destWS.Range(&quot;B509&quot;) = srcWS.Cells(Row, 8) 'City State Zip 'destWS.Range(&quot;B510&quot;) = srcWS.Cells(Row, 9) 'Telephone Number destWS.Range(&quot;B511&quot;) = srcWS.Cells(Row, 16) 'Account Number to Fund Wire destWS.Range(&quot;B514&quot;) = srcWS.Cells(Row, 19) 'Financial Institution Name destWS.Range(&quot;B515&quot;) = srcWS.Cells(Row, 20) 'Routing ABA Number destWS.Range(&quot;B516&quot;) = srcWS.Cells(Row, 21) 'Financial Institution Phone Number destWS.Range(&quot;B517&quot;) = srcWS.Cells(Row, 22) 'Financial Institution Address destWS.Range(&quot;B518&quot;) = srcWS.Cells(Row, 23) 'Beneficiary Name destWS.Range(&quot;B519&quot;) = srcWS.Cells(Row, 24) 'Beneficiary Account Number destWS.Range(&quot;B520&quot;) = srcWS.Cells(Row, 25) 'Beneficiary Physical Address destWS.Range(&quot;B522&quot;) = srcWS.Cells(Row, 27) 'Intermediary Financial Institution Name destWS.Range(&quot;B523&quot;) = srcWS.Cells(Row, 28) 'Intermediary Financial ABA/Routing Number destWS.Range(&quot;B524&quot;) = srcWS.Cells(Row, 29) 'Intermediary Financial ABA/Routing Number destWS.Range(&quot;B525&quot;) = srcWS.Cells(Row, 30) 'Intermediary Account Number srcWB.Close True ElseIf Wire_Type = &quot;Loan Closing&quot; Then destWS.Range(&quot;B322&quot;) = &quot;Recipient is title company that is closing the sender's home purchase/refi.&quot; destWS.Range(&quot;B331&quot;) = &quot;Domestic&quot; destWS.Range(&quot;B333&quot;) = srcWS.Cells(Row, 19) 'Financial Institution Name destWS.Range(&quot;B334&quot;) = srcWS.Cells(Row, 20) 'Routing ABA Number destWS.Range(&quot;B336&quot;) = srcWS.Cells(Row, 22) 'Financial Institution Address destWS.Range(&quot;B337&quot;) = srcWS.Cells(Row, 23) 'Beneficiary Name destWS.Range(&quot;B338&quot;) = srcWS.Cells(Row, 24) 'Beneficiary Account Number destWS.Range(&quot;B339&quot;) = srcWS.Cells(Row, 25) 'Beneficiary Physical Address srcWB.Close True 'NEED TO REFACTOR THIS LIKE THE CODE ABOVE YET 'Internal Wire (Cell B9) ElseIf Wire_Type = &quot;Internal&quot; Then destWB.Activate destWS.Range(&quot;B601:B699&quot;).Select Selection.ClearContents srcWB.Activate srcWS.Activate srcWS.Range(srcWS.Cells(Row, 2), srcWS.Cells(Row, 6)).Select Selection.Copy destWB.Activate destWS.Range(&quot;B604&quot;).Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=True srcWB.Activate srcWS.Range(srcWS.Cells(Row, 7), srcWS.Cells(Row, 7)).Select Selection.Copy destWB.Activate destWS.Range(&quot;B610&quot;).Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=True srcWB.Activate srcWS.Range(srcWS.Cells(Row, 9), srcWS.Cells(Row, 20)).Select Selection.Copy destWB.Activate destWS.Range(&quot;B612&quot;).Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=True srcWB.Activate srcWS.Range(srcWS.Cells(Row, 22), srcWS.Cells(Row, 38)).Select Selection.Copy destWB.Activate destWS.Range(&quot;B627&quot;).Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=True srcWB.Activate srcWS.Range(srcWS.Cells(Row, 39), srcWS.Cells(Row, 40)).Select Selection.Copy destWB.Activate destWS.Range(&quot;B649&quot;).Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=True Windows(&quot;Recurring Requests.xlsx&quot;).Activate ActiveWorkbook.Close ' Windows(&quot;Wire Transfer Forms.xlsm&quot;).Activate 'Hide domestic/international data-input rows as applicable Select Case LCase(Range(&quot;B610&quot;)) Case Is = &quot;domestic&quot; Range(&quot;A611:A625&quot;).EntireRow.Hidden = False Range(&quot;A648:A699&quot;).EntireRow.Hidden = False Range(&quot;A626:A647&quot;).EntireRow.Hidden = True Range(&quot;B612&quot;).Select Case Is = &quot;international&quot; Range(&quot;A626:A699&quot;).EntireRow.Hidden = False Range(&quot;A611:A625&quot;).EntireRow.Hidden = True Range(&quot;B627&quot;).Select Case Is &lt;&gt; &quot;international&quot;, &quot;domestic&quot; Range(&quot;A611:A699&quot;).EntireRow.Hidden = True Range(&quot;B610&quot;).Select End Select Else Windows(&quot;Recurring Requests.xlsx&quot;).Activate ActiveWorkbook.Close End If End If End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T15:50:31.557", "Id": "466177", "Score": "1", "body": "If all the variables in your `WireCustInfo` class are `Public` -- and you are not manipulating the values going in or out of the object -- then you don't need all the `Get` and `Let` properties for each variable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T15:52:23.433", "Id": "466178", "Score": "0", "body": "@PeterT Thats good to know. I will remove the `Get` and `Let` Properties." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T08:14:52.243", "Id": "466250", "Score": "1", "body": "@PeterT suggestion should be: Make the property backing fields`Private`! Best practice seems to be Mathieu's [this-pattern](https://rubberduckvba.wordpress.com/2018/04/25/private-this-as-tsomething/). @OP [The Macro Recorder Curse](https://rubberduckvba.wordpress.com/2019/06/30/the-macro-recorder-curse/) can be cured ,) [OOP Battleship Part 1: The Patterns](https://rubberduckvba.wordpress.com/2018/08/28/oop-battleship-part-1-the-patterns/) may be a good start to VBA-OOP. Try the [Rubberduck](https://rubberduckvba.wordpress.com/2019/12/22/hello-rubberduck-2-5-0/) Add-In." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T20:12:03.530", "Id": "466315", "Score": "0", "body": "@ComputerVersteher I'm also good with all property backing fields being private - that is my own habit in fact. However there are some cases when I really just need a a structured object to hold some unmodified data that I will just keep it all `Public`. It's a philosophical debate over variables that do not need any checks or grooming if they should always be exposed via `Property` methods and I appreciate both sides of the argument." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T21:03:25.927", "Id": "466320", "Score": "0", "body": "@PeterT Maybe if you know what you're doing: But OOP novices like OP or me, not always know and a property is safe. Btw, what are your benefits? Less typing? A property explicit states his pürpose, a global var not. And you noticed the beautyness of the`this`UDT?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T13:55:28.123", "Id": "466440", "Score": "0", "body": "@ComputerVersteher thank you for the additional information. As much as I'd love to use RubberDuck I am not allowed to on my work computer (Ive asked numerous times)." } ]
[ { "body": "<p>You include <code>Option Explicit</code> :+1 for that alone.</p>\n\n<hr>\n\n<p><code>Range</code> without any explicit worksheet implicitly is working off of whatever worksheet happens-to-be-active-at-the-time-that-code-is-executed. This will eventually blow up on you. Always qualify your <code>Range</code>s with a worksheet IE <code>Sheet1.Range(\"...\")</code> so there is no doubt as to what sheet you're referring to.</p>\n\n<hr>\n\n<p>You have a typo in <code>Public Property Let CustomerAddres(value As String)</code>. You're missing the second <code>s</code></p>\n\n<hr>\n\n<p>Within <code>Public Sub EntryB5</code> you have <code>Sheet7.Visible = xlSheetVisible 'Checklist</code>. That comment is a signpost. That signpost says \"Rename your worksheet objects so this comment can go away.\". Display the Project Explorer from the View menu>Project Explorer (Hotkey: <code>Ctrl+R</code>), select Sheet7 from the Project Explorer and then displaying the Properties Window (Hotkey: <code>F4</code>). The first item in the properties window is (Name) which is actually the <a href=\"https://docs.microsoft.com/en-us/office/vba/api/excel.worksheet.codename\" rel=\"nofollow noreferrer\">Worksheet.CodeName property</a>. Name it something appropriate. I've used <code>ChecklistWorksheet</code> which changes your original code</p>\n\n<pre><code>Sheet7.Visible = xlSheetVisible 'Checklist\n</code></pre>\n\n<p>to</p>\n\n<pre><code>ChecklistWorksheet.Visible = xlSheetVisible\n</code></pre>\n\n<p>Absolutely no need for the comment any longer. Strive to make your code be self documenting. What the code is doing should immediately be apparent. <em>If</em> there's a need to describe <em>why</em> something is coded in a particular way <em>that</em> then warrants a comment. An example of this would be explaining why you're using <code>CreateObject(\"System.Collections.ArrayList\")</code>.</p>\n\n<hr>\n\n<p>Public variables. I say stick them in a module that's named <code>PublicVariables</code>. Then whenever one of these variables is used, qualify it with the module name. Again in <code>EntryB5</code> you have DATAENTRY</p>\n\n<pre><code>With DATAENTRY\n</code></pre>\n\n<p>when qualified with the module name you have</p>\n\n<pre><code>With PublicVariables.DATAENTRY\n</code></pre>\n\n<p>Now when future-you or another code (could be you 6 months from now) sees this line it's immediately apparent where this variable is coming from.</p>\n\n<hr>\n\n<p>Module level variables. As was already mentioned in the comments the <a href=\"http://rubberduckvba.com/\" rel=\"nofollow noreferrer\">Rubberduck</a> (RD) add-in has an inspection for this <a href=\"http://rubberduckvba.com/Inspections/Details/ModuleScopeDimKeyword\" rel=\"nofollow noreferrer\">ModuleScopeDimKeyword</a></p>\n\n<blockquote>\n <p>Private module variables should be declared using the 'Private' keyword. While 'Dim' is also legal, it should preferably be restricted to declarations of procedure-scoped local variables, for consistency, since public module variables are declared with the 'Public' keyword.</p>\n</blockquote>\n\n<p>***Disclosure: I'm a contributing member. Just a tad biased in favor of it.</p>\n\n<hr>\n\n<p>You already stated the names with underscores in them are inherited code you're working through. That being said <code>_</code> are used as part of the <a href=\"https://docs.microsoft.com/en-us/office/vba/Language/Reference/User-Interface-Help/implements-statement\" rel=\"nofollow noreferrer\">Implements statement</a> for implementing an interface and bringing it to your attention.</p>\n\n<p>I saw a few parameters <code>Wire_Type</code> that use underscores. camelCase is typical for VBA parameters and local variables whereas PascalCase is used for Sub/Function (member) names. This would result in <code>wireType</code> as a replacement.</p>\n\n<hr>\n\n<p>Your sub <code>Hide_All</code> has a loop within a loop. I prefer having the worksheet CodeNames in a table on a worksheet. That worksheet, whose CodeName was updated to <code>HideSheetsLookup</code>, has a ListObject containing the sheets you want to hide. It also has a function, shown below, that can be called to check whether a sheet should be hidden. The <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/me-keyword\" rel=\"nofollow noreferrer\">Me keyword</a> returns a reference to the sheet that code is written for.</p>\n\n<pre><code>Public Function ShouldBeHidden(ByVal worksheetCodeName As String) As Boolean\n Dim foundCell As Range\n Set foundCell = Me.ListObjects(\"HideSheetTable\").DataBodyRange.Find(What:=worksheetCodeName, LookAt:=XlLookAt.xlWhole)\n\n ShouldBeHidden = Not foundCell Is Nothing\nEnd Function\n</code></pre>\n\n<p>That function is then called as below.</p>\n\n<pre><code>For Each sh In ThisWorkbook.Worksheets\n sh.Visible = Not HideSheetsLookup.ShouldBeHidden(sh.CodeName)\nNext sh\n</code></pre>\n\n<p>This edit changes the original code from a quadratic O(n^2) to a linear O(n).</p>\n\n<p>The table works off the Workheet.CodeName and also won't break if/when a user renames the Worksheet.Name.</p>\n\n<hr>\n\n<p>Within <code>EntryB7</code> and a few others you have a <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/with-statement\" rel=\"nofollow noreferrer\">With statement</a> that's not doing anything. Remove those with blocks.</p>\n\n<pre><code>With ThisWorkbook\n Sheet9.Visible = xlSheetVisible 'Checklist-Cash Management\n Sheet14.Visible = xlSheetVisible 'Confirmation-Outgoing-3\nEnd With\n</code></pre>\n\n<hr>\n\n<p>Static cell ranges. <code>PublicVariables.DATAENTRY.Range(\"B4\")</code> may not always be in cell B4. If you add a insert/delete a row above or a column to the left those cells will shift causing those static addresses to no longer do what you want/expect it to. Use named ranges instead because they'll shift with without issue.</p>\n\n<p>Another benefit of this is it helps aid in code self documenting itself. \"B4\" has no meaning whereas a descriptive name like <code>Range(\"CustomerName\")</code> is infinitely better.</p>\n\n<hr>\n\n<p>Using Line continuation <code>_</code> as part of a single Dim statement is a code smell. Dim each variable on its own line just before you use it. Because they are already within a dedicated function <code>getCIFDBGrabSQL</code> it won't matter having 3 extra lines.</p>\n\n<hr>\n\n<p>Implicitly accessing default members. The code below is implicitly accessing the [_Default] member.</p>\n\n<pre><code>Dim foo As String\nfoo = Sheet1.Range(\"A1\")\n</code></pre>\n\n<p>Fully qualify your member calls to make it explicitly clear what you're accessing. This way you unambiguously show what you want.</p>\n\n<pre><code>foo = Sheet1.Range(\"A1\").Value2\n</code></pre>\n\n<hr>\n\n<p>Copy paste coding. <code>CIFGrab</code> has duplicated code for <code>Case Is = \"OutGoingLoan\"</code> and <code>Case Is = \"OutGoingCM\"</code>. Possibly others but I'm not going to compare every single group. You're assigning values to ranges and by paramaterizing a Sub you reduce redundant code.</p>\n\n<pre><code>Private Sub AssignValuesTo(ByVal customer As WireCustInfo, _\n ByVal customerName As Range, _\n ByVal customerAddress As Range, _\n ByVal customerCityStateZip As Range, _\n ByVal customerPhoneNumber As Range, _\n ByVal customerBSA As Range)\n customerName.Value2 = customer.customerName\n customerAddress.Value2 = customer.customerAddress\n customerCityStateZip.Value2 = customer.customerCityStateZip\n\n Const PhoneFormat As String = \"(###) ###-####\"\n If customer.customerHomePhone = 0 Then\n customerPhoneNumber.Value2 = Format(customer.customerCellPhone, PhoneFormat)\n ElseIf customer.customerCellPhone = 0 Then\n customerPhoneNumber.Value2 = Format(customer.customerHomePhone, PhoneFormat)\n Else\n customerPhoneNumber.Value2 = vbNullString\n End If\n\n customerBSA.Value2 = customer.customerBSA\nEnd Sub\n</code></pre>\n\n<p>Now has a call site as below.</p>\n\n<pre><code>Case Is = \"OutGoingLoan\"\n With PublicVariables.DATAENTRY\n AssignValuesTo tDBGrabRecord, .Range(\"308\"), .Range(\"309\"), .Range(\"310\"), .Range(\"311\"), .Range(\"312\")\n End With\nCase Is = \"OutGoingCM\"\n With PublicVariables.DATAENTRY\n AssignValuesTo tDBGrabRecord, .Range(\"408\"), .Range(\"409\"), .Range(\"410\"), .Range(\"411\"), .Range(\"412\")\n End With\n</code></pre>\n\n<hr>\n\n<p>Create dedicated Subs. The wire type that's Deposit or Loan</p>\n\n<pre><code>If Wire_Type = \"Deposit/Loan\" Then\n destWS.Range(\"A222:A243\").EntireRow.Hidden = False\n destWS.Range(\"A267:A299\").EntireRow.Hidden = False\n destWS.Range(\"A244:A266\").EntireRow.Hidden = True\n destWS.Range(\"B206\") = srcWS.Cells(Row, 5) 'CIF NUmber\n 'destWS.Range(\"B507\") = srcWS.Cells(Row, 6) 'Name\n 'destWS.Range(\"B508\") = srcWS.Cells(Row, 7) 'Address\n 'destWS.Range(\"B509\") = srcWS.Cells(Row, 8) 'City State Zip\n 'destWS.Range(\"B510\") = srcWS.Cells(Row, 9) 'Telephone Number\n destWS.Range(\"B216\") = srcWS.Cells(Row, 15) 'Customer Account Number\n destWS.Range(\"B217\") = srcWS.Cells(Row, 16) 'Account Number to Fund Wire\n destWS.Range(\"B227\") = srcWS.Cells(Row, 17) 'Domestic/International\n Select Case LCase$(srcWS.Cells(Row, 17))\n 'THIS HANDLES FINANCIAL INSTITUTION INFO FOR RECURRING INFO FOR DOMESTIC WIRES\n Case Is = \"domestic\"\n destWS.Range(\"B229\") = srcWS.Cells(Row, 19) 'Financial Institution Name\n destWS.Range(\"B230\") = srcWS.Cells(Row, 20) 'Routing ABA Number\n destWS.Range(\"B231\") = srcWS.Cells(Row, 21) 'Financial Institution Phone Number\n destWS.Range(\"B232\") = srcWS.Cells(Row, 22) 'Financial Institution Address\n destWS.Range(\"B233\") = srcWS.Cells(Row, 23) 'Beneficiary Name\n destWS.Range(\"B234\") = srcWS.Cells(Row, 24) 'Beneficiary Account Number\n destWS.Range(\"B235\") = srcWS.Cells(Row, 25) 'Beneficiary Physical Address\n destWS.Range(\"B237\") = srcWS.Cells(Row, 27) 'Intermediary Financial Institution Name\n destWS.Range(\"B238\") = srcWS.Cells(Row, 28) 'Intermediary Financial ABA/Routing Number\n destWS.Range(\"B239\") = srcWS.Cells(Row, 29) 'Intermediary Address\n destWS.Range(\"B240\") = srcWS.Cells(Row, 30) 'Intermediary Account Number\n Case Is = \"international\"\n End Select\n</code></pre>\n\n<p>Can be refactored to something similar to what's below.</p>\n\n<pre><code>Private Sub DepositOrLoanWireType(ByVal hideEntireRowOfCells As Range, _\n ByVal displayEntireRowOfCells As Range, _\n ByVal destWS As Worksheet, _\n ByVal srcWS As Worksheet, _\n ByVal sourceRow As Long)\n displayEntireRowOfCells.EntireRow.Hidden = False\n hideEntireRowOfCells.EntireRow.Hidden = True\n\n 'Figure out logic to supply ranges on destination worksheet\n destWS.Range(\"B206\").Value2 = srcWS.Range(\"CIFNumber\").Value2\n destWS.Range(\"B216\").Value2 = srcWS.Range(\"CustomerAccountNumber\").Value2\n destWS.Range(\"B217\").Value2 = srcWS.Range(\"AccountNumberToFundWire\").Value2\n destWS.Range(\"B227\").Value2 = srcWS.Range(\"DomesticOrInternational\").Value2\n\n 'THIS HANDLES FINANCIAL INSTITUTION INFO FOR RECURRING INFO FOR DOMESTIC WIRES\n If LCase$(srcWS.Cells(sourceRow, 17).value) = \"domestic\" Then\n destWS.Range(\"B229\").Value2 = srcWS.Range(\"FinancialInstution\").Value2\n destWS.Range(\"B230\").Value2 = srcWS.Range(\"RoutingABANumber\").Value2\n destWS.Range(\"B231\").Value2 = srcWS.Range(\"FinancialInstitutionPhoneNumber\").Value2\n destWS.Range(\"B232\").Value2 = srcWS.Range(\"FinancialInstitutionAddress\")\n destWS.Range(\"B233\").Value2 = srcWS.Range(\"BeneficiaryName\").Value2\n destWS.Range(\"B234\").Value2 = srcWS.Range(\"eneficiaryAccountNumber\").Value2\n destWS.Range(\"B235\").Value2 = srcWS.Range(\"BeneficiaryPhysicalAddress\").Value2\n destWS.Range(\"B237\").Value2 = srcWS.Range(\"IntermediaryFinancialInstitutionName\").Value2\n destWS.Range(\"B238\").Value2 = srcWS.Range(\"IntermediaryFinancialABARoutingNumber\").Value2\n destWS.Range(\"B239\").Value2 = srcWS.Range(\"IntermediaryAddress\").Value2\n destWS.Range(\"B240\").Value2 = srcWS.Range(\"IntermediaryAccountNumber\").Value2\n End If\nEnd Sub\n</code></pre>\n\n<p>Which is now called as below.</p>\n\n<pre><code>If wireType = \"Deposit/Loan\" Then\n DepositOrLoanWireType destWS.Range(\"A244:A266\"), _\n Union(destWS.Range(\"A222:A243\"), destWS.Range(\"A267:A299\")), _\n destWS, _\n srcWS, _\n foundCell.Row\n\n</code></pre>\n\n<p>By repeating this process you end up with a much higher viewpoint (abstraction level) when looking at the code. You care about <em>what it's doing</em>, not <em>how it's being done</em>. Naming these Subs appropriately will do this for you. You won't be getting lost in any details as you review the main high level idea. If you <em>do</em> need to know how things are being done, <em>then</em> you can look into those subs.</p>\n\n<hr>\n\n<p>Within <code>InternalWireType</code> you have <code>Foo.Select</code> immediately followed by <code>Selection.Bar</code>. You rarely need to actually select whatever it is. Shorten it by putting them directly together.</p>\n\n<pre><code>destWS.Range(\"B601:B699\").Select\nSelection.ClearContents\n</code></pre>\n\n<p>shortens to</p>\n\n<pre><code>destWS.Range(\"B601:B699\").ClearContents\n</code></pre>\n\n<p>The same goes for</p>\n\n<pre><code>srcWS.Range(srcWS.Cells(sourceRow, 2), srcWS.Cells(sourceRow, 6)).Copy\ndestWB.Activate\ndestWS.Range(\"B604\").Select\nSelection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True\n</code></pre>\n\n<p>which becomes</p>\n\n<pre><code>srcWS.Range(srcWS.Cells(sourceRow, 2), srcWS.Cells(sourceRow, 6)).Copy\ndestWS.Range(\"B604\").PasteSpecial Paste:=xlPasteValues, Transpose:=True\n</code></pre>\n\n<hr>\n\n<p>The use of a private helper type as a backing field for classes simplifies things, a lot. Below is how I implemented it and greatly simplifies things. Use properties even if they do nothing other than grab the backing field. It may seem like a redundant process but once you need validation logic before assigning to the backing field or retrieving it's value then you'll be glad you did.</p>\n\n<pre><code>Option Explicit\n\nPrivate Type THelper\n Name As String\n Address As String\n CityStateZip As String\n Zip As String\n HomePhone As String\n CellPhone As String\n Phone As String\n BSA As String\n TableName As String\n ErrNumber As Long\nEnd Type\n\nPrivate this As THelper\n\nPublic Property Get Name() As String\n Name = this.Name\nEnd Property\n\nPublic Property Let Name(value As String)\n Name = value\nEnd Property\n\nPublic Property Get Address() As String\n Address = this.Address\nEnd Property\n\nPublic Property Let Address(value As String)\n Address = value\nEnd Property\n\nPublic Property Get CityStateZip() As String\n CityStateZip = this.CityStateZip\nEnd Property\n\nPublic Property Let CityStateZip(value As String)\n CityStateZip = value\nEnd Property\n\nPublic Property Get Zip() As String\n Zip = this.Zip\nEnd Property\n\nPublic Property Let Zip(value As String)\n Zip = value\nEnd Property\n\nPublic Property Get HomePhone() As String\n HomePhone = this.HomePhone\nEnd Property\n\nPublic Property Let HomePhone(value As String)\n HomePhone = value\nEnd Property\n\nPublic Property Get CellPhone() As String\n CellPhone = this.CellPhone\nEnd Property\n\nPublic Property Let CellPhone(value As String)\n CellPhone = value\nEnd Property\n\nPublic Property Get BSA() As String\n BSA = this.BSA\nEnd Property\n\nPublic Property Let BSA(value As String)\n BSA = value\nEnd Property\n</code></pre>\n\n<hr>\n\n<p>There's more that can be done but this enough for now.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T18:17:54.840", "Id": "466476", "Score": "0", "body": "Thank you. I have a lot of reading and research to do based on this answer, but your explanations really help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T23:37:42.267", "Id": "466513", "Score": "1", "body": "Minor note; be consistent in use of `Value/Value2`: `If LCase$(srcWS.Cells(sourceRow, 17).value) = \"domestic\" Then\n destWS.Range(\"B229\").Value2 = srcWS.Range(\"FinancialInstution\").Value2`; for this I'd probably use `Value` all over because it won't make a difference execution-wise and it's perhaps marginally more self documenting than having to justify use of `Value2`. But that's nothing, fab answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T14:52:04.973", "Id": "466582", "Score": "0", "body": "Quick question. Where did `HideSheetsLookup` in `sh.Visible = Not HideSheetsLookup.ShouldBeHidden(sh.CodeName)` come from?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-26T20:33:54.577", "Id": "466759", "Score": "0", "body": "`HideSheetsLookup` is the CodeName for a Worksheet object that has the Table (ListObject) which contains all the CodeNames in the workbook you want to have hidden. Edited my answer to be clearer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T09:42:11.623", "Id": "237775", "ParentId": "237663", "Score": "14" } } ]
{ "AcceptedAnswerId": "237775", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T21:01:44.003", "Id": "237663", "Score": "8", "Tags": [ "vba", "excel" ], "Title": "Data entry of Information" }
237663
<p>I have the following code in my <a href="https://github.com/schuelermine/Install-Steam-Locomotive" rel="nofollow noreferrer">project</a> that installs linux <code>sl</code> on Windows using PowerShell. Is there anything you'd improve about this?</p> <pre><code>param([String]$Profile, [Switch]$Help, [Switch]$Force) $ErrorMessages = @() $Payload = " # &lt;Code inserted by Install-Steam-Locomotive&gt; function Steam-Locomotive {wsl sl -e} function Steam-Locomotive-Force {wsl sl} # &lt;/&gt; " $HelpText = "This script helps you use the tremendous `"sl`" program in Windows PowerShell. Simply download the .ps1 file and execute it. If the script finishes successfully, you can type Steam-Locomotive in PS to start the interruptable `"sl -e`". Use Steam-Locomotive-Force to prevent interruption (`"sl`"). Example: PS C:\Users\User\Downloads\&gt; .\Install-Steam-Locomotive.ps1 -Profile $PROFILE " if ($Help) { Write-Output $HelpText exit } if (!(Get-Command -Name "wsl" -CommandType "Application" -ErrorAction SilentlyContinue)) { $ErrorMessages += @("You don't have WSL installed. Cannot continue.") } if (!$Profile) { $ErrorMessages += @("Please supply your profile location under -Profile. Cannot continue.") if (Get-Content $Profile -ErrorAction SilentlyContinue | Select-String "Steam-Locomotive") { $ErrorMessages += @("Your profile seems to already contain something called `"Steam-Locomotive`". Use -Force to continue anyways.") } } if ((Get-Command -Name "Steam-Locomotive" -ErrorAction SilentlyContinue) -and !$Force) { $ErrorMessages += @("It seems a command named `"Steam-Locomotive`" is already installed. Use -Force to continue anyways.") } if ($ErrorMessages) { Write-Output $ErrorMessages exit } if (!(wsl command -v sl)) { Write-Output "First, install SL." wsl sudo apt install sl } if (wsl command -v sl) { Add-Content $Profile $Payload Write-Output "Done!" } if (!(wsl command -v sl)) { Write-Output "Failed installing wsl." exit } Write-Output "Success!" </code></pre> <p>EDIT: I had an error in this script. The fixed version is up on the project page.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T21:19:13.213", "Id": "466078", "Score": "0", "body": "When I read the code, I thought that `wsl` would be the Windows version of `sl`. Nice confusion. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T21:27:26.727", "Id": "466080", "Score": "0", "body": "Who or what is `sl`? `Set-Location` is already built-in. Is that the bloody steam locomotive that shows up when using `ls` by mistake in a Windows environment? I usually fix that by actually installing `ls`..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T21:28:21.390", "Id": "466081", "Score": "1", "body": "I'd recommend you [edit] the title to describe/summarize the purpose of the code, as strongly suggested by the watermark in the title textbox. As it stands, any [tag:powershell] question could have that title - and without \"powershell\" in the title, literally *any on-topic post* on this site could have that title." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T15:20:58.153", "Id": "466176", "Score": "0", "body": "@Mast It's the locomotive that shows up when you type `sl` in linux... if you have it installed. This is if you want the animation in PowerShell." } ]
[ { "body": "<ul>\n<li>Use the <a href=\"https://gist.github.com/9to5IT/9620683\" rel=\"nofollow noreferrer\">script template</a> for documentation</li>\n<li>Use a <a href=\"https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_cmdletbindingattribute?view=powershell-7\" rel=\"nofollow noreferrer\">cmdlet binding</a> for parameter\nvalidation and help text</li>\n<li>Personally, I run with $ErrorActionPreference = \"Stop\"</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T22:14:14.913", "Id": "237665", "ParentId": "237664", "Score": "2" } } ]
{ "AcceptedAnswerId": "237665", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T21:08:52.503", "Id": "237664", "Score": "3", "Tags": [ "powershell" ], "Title": "Is this powershell code to install the linux sl command to PowerShell good?" }
237664
<p>I'm implementing a PAKE-protocol as a university project and one step of the protocol involves sending encrypted data from a key created via a hash function (I'm using SHA-256). I want to use AES/GCM but do not have an IV so I'm using HKDF to expand the key into an IV and key with the following implementation:</p> <pre><code>import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.generators.HKDFBytesGenerator; import org.bouncycastle.crypto.params.HKDFParameters; import org.bouncycastle.util.Arrays; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; public class AesGcmSymmetricCipher { public static final String CIPHER_ALGORITHM = "AES/GCM/NoPadding"; public static final int GCM_TAG_BITS = 128; public static final int IV_BYTES = 12; public static final int KEY_BYTES = 32; // AES-256 private final Cipher cipher; public AesGcmSymmetricCipher() throws NoSuchPaddingException, NoSuchAlgorithmException { this.cipher = Cipher.getInstance(CIPHER_ALGORITHM); } public byte[] encrypt(byte[] key, byte[] clearData) throws InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { var spec = expandKeys(key); cipher.init(Cipher.ENCRYPT_MODE, spec.getKeySpec(), spec.getParameterSpec()); return cipher.doFinal(clearData); } public byte[] decrypt(byte[] key, byte[] cipherData) throws InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { var spec = expandKeys(key); cipher.init(Cipher.DECRYPT_MODE, spec.getKeySpec(), spec.getParameterSpec()); return cipher.doFinal(cipherData); } public String getAlgorithm() { return "AES-256/GCM/NoPadding using HKDF"; } private KeyedMaterial expandKeys(byte[] initialKey) { var iv = new byte[IV_BYTES]; var key = new byte[KEY_BYTES]; var digest = new SHA256Digest(); var kdf = new HKDFBytesGenerator(digest); var parameters = new HKDFParameters(initialKey, null, null); kdf.init(parameters); kdf.generateBytes(iv, 0, IV_BYTES); kdf.generateBytes(key, 0, KEY_BYTES); var gcmParameters = new GCMParameterSpec(GCM_TAG_BITS, iv); var keySpec = new SecretKeySpec(key, CIPHER_ALGORITHM); Arrays.clear(iv); Arrays.clear(key); return new KeyedMaterial(gcmParameters, keySpec); } private static class KeyedMaterial { private final GCMParameterSpec parameterSpec; private final SecretKeySpec keySpec; public KeyedMaterial(GCMParameterSpec parameterSpec, SecretKeySpec keySpec) { this.parameterSpec = parameterSpec; this.keySpec = keySpec; } public GCMParameterSpec getParameterSpec() { return parameterSpec; } public SecretKeySpec getKeySpec() { return keySpec; } } } </code></pre> <p>I'm interested in feedback especially from a security perspective, if relevant the initial key passed to <code>encrypt</code>/<code>decrypt</code> is ephemeral and will only be used once for encryption and once for decryption.</p>
[]
[ { "body": "<p>First of all, thank you for using my Bouncy Castle additions:</p>\n\n<blockquote>\n <p>Maarten Bodewes initial implementation of HKDF and NIST SP 800-108 MAC based KDF functions.</p>\n</blockquote>\n\n<h2>Design review:</h2>\n\n<p>You are trying to emulate Java's Cipher class. However, I don't think this is such a good idea if your <code>encrypt</code> methods and is so much different. The <code>Cipher</code> class in Java is reusable for the same key (and, unfortunately, same IV) and this one is clearly not. I would not try this hard. Better make this class more specific to the use case and <em>avoid generic wrapper classes</em>.</p>\n\n<p>In itself, you may wonder if combining the key derivation and cipher is a good idea. You're removing the <code>update</code> functionality, for instance. This is less of a problem if this is for a specific use case.</p>\n\n<h2>Code review:</h2>\n\n<pre><code>public class AesGcmSymmetricCipher {\n</code></pre>\n\n<p>Better made final.</p>\n\n<p>The name doesn't fully capture what the class is about. <code>Symmetric</code> is already captured by <code>Aes</code>. The key derivation part is missing on the other hand.</p>\n\n<pre><code>public static final int KEY_BYTES = 32; // AES-256\n</code></pre>\n\n<p>I generally use <code>256 / Byte.SIZE</code> so it is clear where the 32 comes from, that way you don't need the comment.</p>\n\n<pre><code>public byte[] encrypt(byte[] key, byte[] clearData) throws InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {\n</code></pre>\n\n<p><code>clearData</code> is generally called <code>plaintext</code> or simply <code>message</code> within the crypto community.</p>\n\n<p>Other users will probably wonder what happened with the IV or nonce and where to insert it.</p>\n\n<pre><code>Arrays.clear(iv);\nArrays.clear(key);\n</code></pre>\n\n<p>Beware that Oracle made a huge mistakes by making the actual <strong>keys</strong> in software impossible to destroy. You can do this and fool yourself. It's great that you thought of this though - you're not in the wrong here.</p>\n\n<pre><code>return \"AES-256/GCM/NoPadding using HKDF\";\n</code></pre>\n\n<p>Nice but it doesn't capture all the little details - how is the IV calculated, for instance - so it doesn't seem to be of much use. You cannot specify it to anybody and they will know how to implement it.</p>\n\n<hr>\n\n<p>Otherwise the class and design seems spot on to me, so well done.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T07:21:07.867", "Id": "466104", "Score": "0", "body": "Just to stay fair: the crypto API is so old that it was probably Sun who made the design mistake, not Oracle." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T10:54:28.047", "Id": "466126", "Score": "0", "body": "I'm aware that the `Array.clear(...)` does not really clear the keys (I use them after the clear) and wondered when `SecreteKeySpec` clears its private data or if I forgot to do this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T10:55:56.710", "Id": "466127", "Score": "0", "body": "\"You're removing the `update` functionality, for instance\"\nI actually tried to implement it with update and varargs, but then the tag-verification always failed and through some googleing I found that there is apparently something wrong if you don't use `doFinal(data)` in GCM mode." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T12:30:15.573", "Id": "466135", "Score": "0", "body": "@RolandIllig I don't know, the [`Destroyable`](https://docs.oracle.com/javase/8/docs/api/javax/security/auth/Destroyable.html#destroy--) interface is a late addition that was only introduced in version 8 - it's relatively new. Of course, before that it was missing entirely, so there is that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T12:34:00.307", "Id": "466137", "Score": "0", "body": "@recke96 Yeah, no, it is always multiple `update()` calls followed by a `doFinal`, even for other modes (CBC mode only removed padding within one of the overloaded `doFinal` methods for instance.." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T05:11:11.050", "Id": "237680", "ParentId": "237670", "Score": "2" } } ]
{ "AcceptedAnswerId": "237680", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T01:33:48.133", "Id": "237670", "Score": "2", "Tags": [ "java", "cryptography", "aes" ], "Title": "Java Cryptography AES/GCM/NoPadding without IV" }
237670
<p>I'm developing a small C# Unity application to display stereoscopic images as part of a wider research study.</p> <p>Since the experiment consists of unique stages (Start, during a trial, between trials, and End), I decided to use the State Design Pattern to make a State Machine for code readability.</p> <p>The program design is based on a 'Model', with the model having 'Metadata' (about the participant) and a Queue of 'Trials', with each trial having several data fields.</p> <h3><code>/Experiment/Model.cs</code></h3> <pre><code>namespace Experiment { public struct Metadata { public string Id; public string Age; public string OriginalImageDirectory; public override string ToString() =&gt; $"# {Id}\n# {Age}\n# {OriginalImageDirectory}"; } public struct Trial { public string ImageName; public IReadOnlyList&lt;Stereoscopic3DImage&gt; ImageAssets; public Point Origin; public bool Flickers; } public struct Result { public string ImageName; public Point Origin; public bool CorrectResponse; public override string ToString() =&gt; $"{ImageName}, {Origin.X}, {Origin.Y}, {CorrectResponse.ToString()}"; } public class Model { public readonly Metadata Metadata; public readonly Queue&lt;Trial&gt; Trials; public Model(IReadOnlyList&lt;string&gt; configurationFileRows) { // ... Trials = new Queue&lt;Trial&gt;(Utils.ParseTrialsFrom(Metadata, configurationFileRows.Skip(3))); } } } </code></pre> <h3><code>/Experiment/StateManager.cs</code></h3> <pre><code>namespace Experiment { public class StateContext { public interface IState { void OnStateEnter(); void OnStateContinue(StateContext context); void OnStateExit(); } private IState currentState; public IState CurrentState { get =&gt; currentState; set { if (currentState != null) { currentState.OnStateExit(); } currentState = value; currentState.OnStateEnter(); } } public void Update() =&gt; CurrentState.OnStateContinue(this); } } </code></pre> <h3><code>/Experiment/TrialState.cs</code></h3> <p>(For the sake of brevity, I'll omit the other three <code>*State.cs</code> files)</p> <pre><code>namespace Experiment { class TrialState : StateContext.IState { private float flickerTimer; private float trialTimer; private readonly Model model; private Trial trial; private readonly VR3DMediaViewer viewer; private readonly GameObject textField; private int index; public TrialState(Model model, GameObject viewer, GameObject textField) { this.model = model; this.viewer = viewer.GetComponent&lt;VR3DMediaViewer&gt;(); this.textField = textField; } public void OnStateEnter() { viewer.gameObject.SetActive(true); trial = model.Trials.Dequeue(); viewer.SetNewImage(trial.ImageAssets[index]); flickerTimer = 0.0f; trialTimer = 0.0f; } public void OnStateContinue(StateContext context) { Contract.Requires(viewer.gameObject.activeSelf); // ... if (affirmativePressed || rejectivePressed) { // ... if (model.Trials.Count == 0) { context.CurrentState = new EndState(); } else { OnStateEnter(); } return; } if (trialTimer &gt;= Controller.TrialDuration) { context.CurrentState = new BetweenTrialsState(model, trial, viewer.gameObject, textField); return; } // ... } public void OnStateExit() { viewer.gameObject.SetActive(false); } } } </code></pre> <h3><code>/Controller.cs</code></h3> <pre><code>public class Controller : MonoBehaviour { public static StreamWriter StreamWriter; private StateContext stateContext; // MARK: GameObjects public GameObject textField; public GameObject viewer; // Start is called before the first frame update void Start() { // ... (initialization) stateContext.CurrentState = new StartState(model, textField, viewer); } // Update is called once per frame void Update() { stateContext.Update(); } [ContractInvariantMethod] protected void ObjectInvariant() { Contract.Invariant(textField.activeSelf != viewer.activeSelf); } } </code></pre> <hr> <p>Any feedback on the software design of my program and/or my implementation of the State Pattern would be appreciated, thanks.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T08:34:23.970", "Id": "466116", "Score": "2", "body": "I'd suggest to add `{ get; set; }` accessors in `Model.cs` and `Controller.cs`: public fields aren't commonly used, public properties are. If you want your fields to appear in the inspector, use `private` and `[SerializeField]` attribute. Nesting of the interface `IState` seems a bit strange to me as well: [MSDN documentation](https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/nested-types) asvices against it. Apart from that, everything seems fine." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T02:12:58.093", "Id": "237673", "Score": "1", "Tags": [ "c#", "design-patterns", "gui", "unity3d", "state-machine" ], "Title": "Simple Unity program for a research experiment" }
237673
<p>I would like some help on making my solution more functional. At present, I rely heavily on using indexes in my map functions. I am also seeking general feedback and advice, thanks.</p> <pre><code>export const getMatrixColumns = (a: number[][]) =&gt; { return a[0].length; }; export const getMatrixRows = (a: number[][]) =&gt; { return a.length; }; export const matricesAreValid = (a: number[][], b: number[][]) =&gt; { return getMatrixColumns(a) === getMatrixRows(b); }; export const generateEmptyMatrix = (rows: number, cols: number) =&gt; { return [...Array(rows)].fill(0).map(() =&gt; [...Array(cols)].fill(0)); }; export const dotProduct = (a: number[], b: number[]) =&gt; { return a.map((value, i) =&gt; value * b[i]).reduce((acc, val) =&gt; acc + val, 0); }; export const multiplyMatrices = (a: number[][], b: number[][]) =&gt; { if (matricesAreValid(a, b)) { const rows = getMatrixRows(a); const cols = getMatrixColumns(b); return generateEmptyMatrix(rows, cols).map((resultRow, i) =&gt; resultRow.map((element: number, j: number) =&gt; { const column = b.map(row =&gt; row[j]); const row = a[i]; return dotProduct(row, column); }) ); } }; </code></pre>
[]
[ { "body": "<h1>Concise Function Body</h1>\n\n<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Function_body\" rel=\"nofollow noreferrer\">function body of an arrow function</a> can be concise.</p>\n\n<p>For instance can <code>getMatrixColumns</code> shorten to</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>export const getMatrixColumns = (a: number[][]) =&gt; a[0].length;\n</code></pre>\n\n<hr>\n\n<h1>Method Name</h1>\n\n<p>The method names <code>getMatrixColumns</code> and <code>getMatrixRows</code> let me expect that the the methods return a <code>number[]</code> instead of a <code>number</code>. </p>\n\n<p>A better fit are <code>getMatrixColumnLength</code> and <code>getMatrixRowLength</code>.</p>\n\n<hr>\n\n<h1>Redundant Method Names</h1>\n\n<p>Each method name expect <code>dotProduct</code> contains some how the word <em>matrix</em>.</p>\n\n<p>It is sufficient if the methods are grouped in a <code>Matrix</code> module and have names like:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>// in matrix.js\n\nexport const columnLenghtOf = (a: number[][]) =&gt; \n a[0].length;\n\nexport const rowLengthOf = (a: number[][]) =&gt; \n a.length;\n\nexport const areValid = (a: number[][], b: number[][]) =&gt;\n columnLenghtOf(a) === columnLenghtOf(b);\n\n/* ... */\n</code></pre>\n\n<hr>\n\n<h1>Type Alias</h1>\n\n<p><code>Matrix</code> could be a <a href=\"https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases\" rel=\"nofollow noreferrer\">type alias</a> for <code>number[][]</code>:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>// in matrix.js\n\ntype Matrix = number[][]\n\nexport const columnLenghtOf = (a: Matrix) =&gt; \n a[0].length;\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T17:34:55.343", "Id": "238490", "ParentId": "237674", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T02:14:36.593", "Id": "237674", "Score": "3", "Tags": [ "typescript" ], "Title": "Matrix Multiplication in Typescript" }
237674
<p>I always want to improve my code by refactoring but when I've to work with complicated function that have many thing to do . How can I refactoring them. </p> <p>Here is my data for example I get data from request</p> <p>My DB structure look like this</p> <pre><code> DB id PK blog int date_end string date_start string employee_id FK [ by table employee ] total_time_in_hr int value int //my data req = { data: [ { blog: 1, date_end: "19-02-2020", date_start: "19-02-2020", employee_id: [2290,3], work_id: 1, total_time_in_hr: 10, value: 5100 } ] }; </code></pre> <p>First I've to loop my <code>data</code> then I've to loop again in my <code>employee_id</code> and insert them into DB</p> <pre><code>//looop data async store({ request, response }) { const data = req.data await Promise.all( data.map(async (getData, i) =&gt; { const empId = getData.employee_id; const workId = getData.work_id; let date_start = getData.date_start; let date_end = getData.date_end; const value = getData.value; date_start = moment(date_start, "DD-MM-YYYY").format( "YYYY-MM-DD" ); date_start = moment(date_end, "DD-MM-YYYY").format( "YYYY-MM-DD" ); await Promise.all( empId.map(async (empId, i) =&gt; { //insert to my DB const storeData = new MyDB(); storeData.employee_id = empId; storeData.work_id = workId; storeData.value = value; storeData.date_start = date_start; storeData.date_end = date_end; storeData.status = 3; storeData.group_name = groupName; await storeData.save(); // insert to my Log DB const createLog = new MyDBLog(); createLog.my_db_id = storeData.id; createLog.value = value; createLog.msg = 'somthing'; createLog.status = 3; createLog.total_time = 0; await createLog.save(); //this part in my work I've to make json and insert it to another DB const data = { work_id: workId, blog: getData.blog, total_time: getData.total_time_in_hr, my_db_id: storeData.id }; const store = await AnotherDB.create(data); }) ); return { workId, value }; }) ).then(async data =&gt; { //update last Value await Promise.all( data.map(async ({ workId, value }) =&gt; { const updateTotalAssign = await AssignWork.query() .where("work_id", workId) .update({ total_value: value }); }) ); }); return response.status(200).json({ status: 200, success: true, message: "success" }); } </code></pre> <p>As you see my code are very mess up How to refactoring function and clean code this kind of function</p>
[]
[ { "body": "<p>A low-hanging fruit will be defining some interfaces of datastores such as <code>MyDB</code> so that some details can be hidden from the controller code. For instance:</p>\n\n<pre><code> const storeData = new MyDB();\n storeData.employee_id = empId;\n storeData.work_id = workId;\n storeData.value = value;\n storeData.date_start = date_start;\n storeData.date_end = date_end;\n storeData.status = 3;\n storeData.group_name = groupName;\n await storeData.save();\n</code></pre>\n\n<p>can be refactored to something like:</p>\n\n<pre><code> MyDBBuilder\n .with(getData)\n .withStatus(3)\n .withGroupName(groupName)\n .save();\n</code></pre>\n\n<p>The complexity comes from the fact that it takes 4 steps to complete this business transaction. Unless there is a way to redefine data schema, all we can do here is to encapsulate the complexity and not expose it in the controller code. \nIn some cases, it might be appropriate to have all the db operations in some stored procedure, if you are not concerned with portability. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T04:30:45.150", "Id": "237731", "ParentId": "237679", "Score": "2" } } ]
{ "AcceptedAnswerId": "237731", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T04:47:29.063", "Id": "237679", "Score": "0", "Tags": [ "javascript", "node.js", "database" ], "Title": "How to refactoring function when I've to do many things in one function" }
237679
<h2>Purpose of the code:</h2> <p>I have 3 Excel files to deal with. Those file have already been filtered or hidden because the content is very large. And I only need part of the content for every excel files.</p> <p>I don't want to open every file and worksheets in order to copy the desired range.</p> <p>I want to write a code to combine every filtered or hidden cells and put those cells to a brand new workbook.</p> <h2>Steps of the code:</h2> <ol> <li><p>Combine every filtered or hidden cells of all worksheets for every excel files.</p> </li> <li><p>Create a new empty single-worksheet workbook.</p> </li> <li><p>Put all cells of Step 1 into Step 2.</p> </li> </ol> <h2>Problem of the code:</h2> <ol> <li>Running too slow</li> </ol> <pre><code>import openpyxl import os import glob path = os.getcwd() data=[] x=input('name:') + '.xlsx' target_xls = os.path.join(path,x) for file in glob.glob(path+'\*.*'): if file.endswith((&quot;.xlsx&quot;)): wb = openpyxl.load_workbook(file, data_only=True) for sheet in wb.worksheets: for j in range(2, sheet.max_row+1 ): for i in range(1,sheet.max_column+1): ihidden = sheet.row_dimensions[j].hidden # Row Visibility True / False svalue = sheet.cell(column=i,row=j).value if ihidden == True: shidden = &quot;HIDDEN&quot; else: shidden = &quot;VISIBLE&quot; data.append(svalue) WP= openpyxl.Workbook() ws = WP.active ws.title = &quot;Sheet1&quot; x=sheet.max_column new_list = [data[i:i+x] for i in range(0, len(data), x)] for elem in new_list: ws.append(elem) WP.save(target_xls) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T07:15:39.913", "Id": "466103", "Score": "3", "body": "What is the purpose of the program? What are you trying to do? Please add this information to your question, as it will make things easier for the answerers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T08:04:26.023", "Id": "466107", "Score": "1", "body": "I wanna merge every cells of all excel file in the folder and generate a new workbook. Put those cells there. But I only wanna retrieve visible cells. The target file is already filtered or hidden. However, although my code works, it went very slow. I guess it's because I use too many for loops?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T08:10:44.567", "Id": "466108", "Score": "1", "body": "Since it's a multi-file operation it's never going to be very fast, but I'm sure it can be optimized. What kind of data size are we talking about anyway? Hundreds of files with hundreds of columns and thousands of rows?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T08:20:07.200", "Id": "466113", "Score": "0", "body": "I understand it's a multi-file operation. I tried to perform the code on three different excel files. (Total size: 4.5 MB). It turned out to take me 500 sec to complete. I think I would only use it to process some files no larger than 40 MB in total." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T09:54:02.500", "Id": "466124", "Score": "0", "body": "@Mast Could you please give me some advise?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T11:20:08.503", "Id": "466131", "Score": "0", "body": "Welcome to Code Review! This question lacks any indication of what the code is intended to achieve. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T13:36:17.953", "Id": "466145", "Score": "0", "body": "You answered what the code is doing in a comment, could you please put that into the question body possibly with a little more detail? That would make this an excelent question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T09:54:07.817", "Id": "466259", "Score": "0", "body": "@TobySpeight\nThank you! I have edit my post again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T09:54:45.093", "Id": "466260", "Score": "0", "body": "@pacmaninbw Thank you! Now I have did that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T09:55:20.940", "Id": "466261", "Score": "0", "body": "@MJ713 Thank you! I have explained that on my post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T08:45:00.940", "Id": "466408", "Score": "0", "body": "I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T11:12:16.157", "Id": "466420", "Score": "0", "body": "providing a file with some sample data and its expected outcome can help too. It doesn't need to be as large as your original data, and can contain random numbers or text, but the operation should be the same" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T13:24:18.137", "Id": "466561", "Score": "0", "body": "I'm feel very surprised for you all. Everyone can't understand what I meant exactly. The only thing you do is to change title and state concern precisely and yelling it's not clear enough. Do you guys(Engineers) really understand nothing about my concern? OK, no advise and no help. I would tell my friends and this forum is not a good place for someone who can speak or read the meaning. Ban my account and IP please. That's the only thing you nerds who only live on keyboards do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T13:25:09.673", "Id": "466563", "Score": "0", "body": "Oh, by the way, I have figured it out the optimization problem without giving some sample data. haha" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T06:07:05.110", "Id": "237681", "Score": "4", "Tags": [ "python", "performance", "python-3.x", "excel" ], "Title": "Combine filtered or hidden cells" }
237681
<p>After a lot of browsing and experimenting I have managed to achieve to read excel file as a Dataframe, apply some style to it and export it to html. My main concern is that the highlight_max function looks a bit redundant. The rows I want to highlight are already predetermined and are not just simply minimum or maximum. I tried to do it with list comprehension but it did not work. Is it possible to return the style value with just one line?</p> <pre><code>import pandas as pd def highlight_max(s): truth = [] for i in (df.index): truth.append(i in [634, 636, 638, 640, 642, 644, 648, 649, 650, 651, 656]) return ['background-color: yellow' if v else '' for v in truth] df = pd.read_excel('N:\Temp\filename.xlsx', index_col=False) df.reset_index(drop=True, inplace=True) html = df.style.set_table_styles([{'selector': 'th,td', 'props': [('border-style','solid'), ('border-width','1px')]}]).apply(highlight_max).hide_index().render(index=False) with open('N://temp//test.html', 'w') as f: f.write(html) </code></pre>
[]
[ { "body": "<p>Your <code>highlight_max</code> function can be simplified a bit by passing the rows to mark as an argument (possibly with a default value), and putting it all into a list comprehension right away:</p>\n\n<pre><code>def highlight_max(column, to_mark): \n return ['background-color: yellow' if i in to_mark else '' for i in column.index]\n</code></pre>\n\n<p>Note that this takes the actual <code>column</code> as input. Yours took the <code>df</code> from the global scope, disregarding the input, which means that all things you did before the <code>apply</code> will probably be ignored.</p>\n\n<p>Use it like this:</p>\n\n<pre><code>ROWS = {634, 636, 638, 640, 642, 644, 648, 649, 650, 651, 656}\n\nif __name__ == \"__main__\":\n df = pd.read_excel('N:\\Temp\\filename.xlsx', index_col=False) \n df.reset_index(drop=True, inplace=True)\n styles = [{'selector': 'th,td',\n 'props': [('border-style','solid'), ('border-width','1px')]}]\n html = df.style.set_table_styles(styles)\\\n .apply(highlight_max, to_mark=ROWS)\\\n .hide_index()\\\n .render(index=False)\n\n with open('N://temp//test.html', 'w') as f:\n f.write(html)\n</code></pre>\n\n<p>I also made <code>ROWS</code> a <code>set</code> instead of a <code>list</code> for faster checking of <code>in</code> (not that it matters too much for such a small list, but it will if it gets bigger), used a style that makes the long chain of functions for <code>html</code> easier to read IMO, used the fact that any additional parameters passed to <code>apply</code> are passed along to the function to pass the rows to mark and wrapped the main code under a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script without it running.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T10:17:35.523", "Id": "237689", "ParentId": "237686", "Score": "1" } } ]
{ "AcceptedAnswerId": "237689", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T07:58:21.503", "Id": "237686", "Score": "1", "Tags": [ "python", "pandas" ], "Title": "Reduce the redundancy in my pandas highlight function" }
237686
<ol> <li><p>For the question, I had a pretty messy solution so I would like some advice on how to better use Java to make the code a bit cleaner.</p> </li> <li><p>Also, a semi-hack that I did that I'm not proud of is checking if <code>words.length == 0</code> at the beginning and returning <code>0</code> if so, so that I can initialize <code>int longestSeen = 1</code> (if there exists a word, the smallest chain must be at least 1).</p> <p>In reality, if we haven't processed the graph to find the longest chain, we should have <code>int longestSeen = 0</code>. My solution only adds to the adjacency list <code>adjList</code> if there exists a relation (e.g. 'ab' -&gt; 'abc'), so for the case where there are no chains and every word is a lone island, I'm not checking for the longest chain length at all and am basically just straight up returning <code>1</code>. This makes sense and would be more time efficient than initializing the <code>adjList</code> with all the words, but it feels hack-y to me.</p> </li> <li><p>I had <code>int[] longestChain</code> outside of the longestStrChain method and I'm not sure how to get around this.</p> </li> </ol> <p><strong>Problem:</strong> <a href="https://leetcode.com/problems/longest-string-chain/" rel="nofollow noreferrer">https://leetcode.com/problems/longest-string-chain/</a></p> <p>Given a list of words, each word consists of English lowercase letters.</p> <p>Let's say <code>word1</code> is a predecessor of <code>word2</code> if and only if we can add exactly one letter anywhere in <code>word1</code> to make it equal to <code>word2.</code> For example, <code>&quot;abc&quot;</code> is a predecessor of <code>&quot;abac&quot;.</code></p> <p>A word chain is a sequence of words <code>[word_1, word_2, ..., word_k]</code> with <code>k &gt;= 1</code>, where <code>word_1</code> is a predecessor of <code>word_2</code>, <code>word_2</code> is a predecessor of <code>word_3</code>, and so on.</p> <p>Return the longest possible length of a word chain with words chosen from the given list of <code>words</code>.</p> <p><strong>Example:</strong></p> <pre><code>Input: [&quot;a&quot;,&quot;b&quot;,&quot;ba&quot;,&quot;bca&quot;,&quot;bda&quot;,&quot;bdca&quot;] Output: 4 Explanation: one of the longest word chain is &quot;a&quot;,&quot;ba&quot;,&quot;bda&quot;,&quot;bdca&quot;. </code></pre> <p><strong>Solution:</strong></p> <pre><code>class Solution { int[] longestChain; // memoization for longest chain length for fromKey vertex public int longestStrChain(String[] words) { if (words.length == 0) { return 0; } Map&lt;String, Integer&gt; wordToIndex = new HashMap&lt;&gt;(words.length); Map&lt;Integer, List&lt;Integer&gt;&gt; adjList = new HashMap&lt;&gt;(words.length); longestChain = new int[words.length]; for (int i = 0; i &lt; words.length; i++) { wordToIndex.put(words[i], i); } for (String word : wordToIndex.keySet()) { for (int i = 0; i &lt; word.length(); i++) { String curr = word.substring(0, i) + word.substring(i+1, word.length()); // take one char out at a time for each word and see if it's part of words[] if (wordToIndex.keySet().contains(curr)) { int fromKey = wordToIndex.get(curr); int toKey = wordToIndex.get(word); if (adjList.keySet().contains(fromKey)) { List&lt;Integer&gt; vertices = adjList.get(fromKey); vertices.add(toKey); adjList.replace(fromKey, vertices); } else { adjList.put(fromKey, new ArrayList&lt;Integer&gt;(Arrays.asList(toKey))); } } } } int longestSeen = 1; // longest string chain so far for (Integer fromVertexIdx : adjList.keySet()) { longestSeen = Math.max(longestSeen, getChainLength(fromVertexIdx, adjList)); } return longestSeen; } private int getChainLength(int fromVertexIdx, Map&lt;Integer, List&lt;Integer&gt;&gt; adjList) { if (longestChain[fromVertexIdx] &gt; 0) { return longestChain[fromVertexIdx]; } longestChain[fromVertexIdx] = 1; // min string length is 1 (vertex contains no edges) if (adjList.keySet().contains(fromVertexIdx)) { for (Integer edge : adjList.get(fromVertexIdx)) { longestChain[fromVertexIdx] = Math.max(longestChain[fromVertexIdx], getChainLength(edge, adjList)+1); } } return longestChain[fromVertexIdx]; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T14:27:51.107", "Id": "466156", "Score": "0", "body": "Code doesn't compile for `Arrays.asList(toKey)`..." } ]
[ { "body": "<h2>Data Design</h2>\n\n<p>your major flaw is your poor data design. As described in the question you have </p>\n\n<ol>\n<li><strong>find out when one word is a predecessor of another</strong></li>\n<li><strong>A word chain is a sequence of words, where one word is a predecessor of another</strong></li>\n</ol>\n\n<h2>1. find out when one word is a predecessor of another</h2>\n\n<p>this describes an algorithm on how to find out if one word is a predecessor of another. you should provide <strong>at least one method</strong> that does only this and only this:</p>\n\n<pre><code>private final String word;\n\npublic boolean isPredecessor(String predecessor) {\n if (predecessor == null) {\n return false;\n }\n if (predecessor.length() != word.length() + 1) {\n return false;\n }\n if(predecessor.length() == 1){\n return true;\n }\n boolean breakReached = false;\n int breakIndex = 0;\n for (int index = 0; index &lt; word.length(); index++) {\n if (word.charAt(index) != predecessor.charAt(index)) {\n breakReached = true;\n breakIndex = index;\n break;\n }\n }\n for (int index = breakIndex; index &lt; word.length(); index++) {\n if (breakReached &amp;&amp; word.charAt(index) != predecessor.charAt(index+1)) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>compare letter by letter and if you come to <strong>one breaking difference</strong> you continue with index+1 - if all other match, then we have a predecessor. You iterate only once over the whole word.</p>\n\n<p><a href=\"https://i.stack.imgur.com/7Avj7.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7Avj7.jpg\" alt=\"enter image description here\"></a></p>\n\n<h2>2. A word chain is a sequence of words, where one word is a predecessor of another</h2>\n\n<p>that leads to the following data structure where you can store a word and its predecessors. Such a data structure makes the code very clearly to read later.</p>\n\n<pre><code>public class Predecessor {\n\n private final String word;\n private final List&lt;Predecessor&gt; predecessors = new ArrayList&lt;&gt;();\n\n public Predecessor(String word){\n this.word = word;\n }\n\n public void addPredecessor(Predecessor predecessor){\n predecessors.add(predecessor);\n }\n\n\n public List&lt;Predecessor&gt; getPathToRoot(){\n List&lt;Predecessor&gt; path = new ArrayList&lt;&gt;();\n if(!predecessors.isEmpty()){\n path.add(this);\n path.addAll(predecessors.get(0).getPathToRoot());\n }\n return path;\n }\n\n public boolean isPredecessor(String predecessor) {...}\n\n @Override\n public String toString(){\n if (!predecessors.isEmpty()){\n return \"['\"+word + \"'-&gt;'\"+predecessors.get(0).word+\"']\";\n }\n return \"['\"+word + \"']\";\n }\n\n}\n</code></pre>\n\n<h2>applied output</h2>\n\n<p>the algorithm with these applied methods and data structure would be fairly clear:</p>\n\n<pre><code>public int longestStrChain(String[] words) {\n\n //create predecessor list \n List&lt;Predecessor&gt; predecessors = new ArrayList&lt;&gt;();\n for(String word: words){\n Predecessor newOne = new Predecessor(word);\n predecessors.add(newOne);\n for(Predecessor predecessor: predecessors){\n if(predecessor.isPredecessor(word)){\n predecessor.addPredecessor(newOne);\n predecessors.add(newOne);\n break;\n }\n }\n }\n\n //find out the longest one\n List&lt;Predecessor&gt; candidate = null;\n int depth = 0;\n for(Predecessor predecessor: predecessors){\n List&lt;Predecessor&gt; path = predecessor.getPathToRoot();\n if (path.size() &gt; depth){\n depth = path.size();\n candidate = path;\n }\n }\n\n System.out.println(candidate);\n return candidate.size();\n}\n</code></pre>\n\n<h2>notes</h2>\n\n<p>since the data structure provide information <em>from a --> to b</em> it's result is -1 to the original size </p>\n\n<blockquote>\n <p>[a --> ba] , [ba --> bca] , [bca --> bdca]</p>\n</blockquote>\n\n<h2>notes</h2>\n\n<p>since we don't care which predecessor we choose (<code>predecessors.get(0)</code>) it's a bit unpredictable which word chain we get. - but we're guaranteed to find one longest!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T14:20:15.863", "Id": "466152", "Score": "1", "body": "k think it's called *primitive obsession* when you prefer primitive datatype `Map<String, Integer>` over a proper data type." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T14:54:00.217", "Id": "466169", "Score": "1", "body": "That should be `isSuccessor()` the way you wrote it. The predecessor is the *smaller of the words*, and you compare to `#word + 1`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T15:09:53.620", "Id": "466173", "Score": "1", "body": "Or make that `Predecessor.isPredecessorOf(String successor)` I guess." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T15:16:13.710", "Id": "466175", "Score": "1", "body": "This design is a ton better, but it really requires its own code review, to be honest." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T16:17:52.330", "Id": "466182", "Score": "0", "body": "@Maarten Bodewes you are absolutely right. Here is even more code review to do than on the original question. I should have sticked with a more minimal answer, where I only point out the flaw of the design..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T16:20:48.603", "Id": "466184", "Score": "1", "body": "Something that really got me, even though it is very minimal, is `breakReached = true;` -> after the loop, if no break is reached, then the last character only differs, right? So success & stop! (but I upvoted for the design, because the errors don't invalidate it)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T16:24:34.007", "Id": "466185", "Score": "0", "body": "Very nice @Maarten Bodewes... Honestly I was quite a bit eager when I wrote my answer. The missing data type just pained me, so I shot and asked afterwards... Stupid me..." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T14:11:16.637", "Id": "237698", "ParentId": "237687", "Score": "3" } }, { "body": "<p>As a speedup, I was expecting some sorting to be performed on size; I'm a bit surprised to only see maps in this regard. HashMaps behave well, but I wonder how much faster it would be if the size was taken care of <em>before</em> trying to find stuff by comparison (of hashes or values).</p>\n\n<p>One problem I have with your solution in general is the naming of the variables. Yes, an <code>index</code> is an <code>index</code> and a <code>vertice</code> is a <code>vertice</code>. But an index <em>of what?</em>. It doesn't help if you then throw everything on one heap; one method with a single helper method. The method goes 4 deep and contains other branches as well.</p>\n\n<pre><code>class Solution {\n</code></pre>\n\n<p>Ah, yes, that's of course not a good distinguishing class name.</p>\n\n<pre><code>int[] longestChain; // memoization for longest chain length for fromKey vertex\n</code></pre>\n\n<p>That doesn't seem right to me, just forward it using a parameter, but don't use fields unless necessary (e.g. this makes the function not-thread safe, while accomplishing nothing). Furthermore, in Java you don't declare anything until you're prepared to initialize it.</p>\n\n<pre><code>if (words.length == 0) {\n return 0;\n}\n</code></pre>\n\n<p>Using a special case for zero is nothing to be ashamed of. Zero is such a special number that the Romans didn't even have a representation of it. However, it does make sense to check if your algorithm doesn't run even if you have a zero (does it?).</p>\n\n<pre><code>Map&lt;Integer, List&lt;Integer&gt;&gt; adjList = new HashMap&lt;&gt;(words.length);\n</code></pre>\n\n<p>To a new developer it is entirely unclear what <code>adjList</code> means here.</p>\n\n<pre><code>for (int i = 0; i &lt; words.length; i++) {\n wordToIndex.put(words[i], i);\n}\n</code></pre>\n\n<p>This should be performed in a separate method, so that you get the least amount of loops (and don't use <code>i</code> to mean separate things).</p>\n\n<pre><code> String curr = word.substring(0, i) + word.substring(i+1, word.length()); // take one char out at a time for each word and see if it's part of words[]\n</code></pre>\n\n<p>What about <code>smallerWord</code> or similar as name instead of <code>curr</code>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T16:18:45.357", "Id": "466183", "Score": "0", "body": "Thank you that you had also an eye on my answer! +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T14:38:29.290", "Id": "237701", "ParentId": "237687", "Score": "4" } } ]
{ "AcceptedAnswerId": "237701", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T08:00:18.253", "Id": "237687", "Score": "3", "Tags": [ "java", "programming-challenge", "graph", "dynamic-programming" ], "Title": "LeetCode: Longest String Chain (Java)" }
237687
<p>I made a BigInt class that supports almost all functions an <code>int</code> would.</p> <p>The code seems too bulky and there might be a few bugs lurking here and there.<br> I would like to simplify my code as much as possible and increase performance.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;algorithm&gt; class BigInt { public: bool neg = false; std::string number = "0"; BigInt(){} BigInt(const BigInt&amp; other){ this -&gt; neg = other.neg; this -&gt; number = other.number; } BigInt(int number){ if(number &lt; 0){ this -&gt; neg = true; number *= -1; } if(number == 0){ this -&gt; number = "0"; return; } this -&gt; number = ""; while(number &gt; 0){ this -&gt; number += (number % 10) + '0'; number /= 10; } } BigInt(long long int number){ if(number &lt; 0){ this -&gt; neg = true; number *= -1; } if(number == 0){ this -&gt; number = "0"; return; } this -&gt; number = ""; while(number &gt; 0){ this -&gt; number += (number % 10) + '0'; number /= 10; } } BigInt(unsigned long long int number){ if(number &lt; 0){ this -&gt; neg = true; number *= -1; } if(number == 0){ this -&gt; number = "0"; return; } this -&gt; number = ""; while(number &gt; 0){ this -&gt; number += (number % 10) + '0'; number /= 10; } } BigInt(const char *number){ std::string number_(number); *(this) = number_; } BigInt(std::string number){ while(number[0] == '-'){ this -&gt; neg = !this -&gt; neg; number.erase(0, 1); } reverse(number.begin(), number.end()); while(number.size() &gt; 1 &amp;&amp; number[number.size() - 1] == '0') number.erase(number.size() - 1, number.size()); if(number == "") number = "0"; this -&gt; number = number; if(number == "0") this -&gt; neg = false; } friend bool operator == (BigInt first, BigInt second){ return first.number == second.number &amp;&amp; second.neg == first.neg; } friend bool operator != (BigInt first, BigInt second){ return !(first == second); } friend bool operator &lt; (BigInt first, BigInt second){ if(first.neg &amp;&amp; !second.neg) return true; if(!first.neg &amp;&amp; second.neg) return false; if(first.neg &amp;&amp; second.neg){ first.neg = false; second.neg = false; return first &gt; second; } if((first.number).size() &lt; (second.number).size()) return true; if((first.number).size() &gt; (second.number).size()) return false; std::string temp1 = first.number; reverse(temp1.begin(), temp1.end()); std::string temp2 = second.number; reverse(temp2.begin(), temp2.end()); for(unsigned int i = 0; i &lt; temp1.size(); i++) if(temp1[i] &lt; temp2[i]) return true; else if(temp1[i] &gt; temp2[i]) return false; return false; } friend bool operator &lt;= (BigInt first, BigInt second){ return (first == second) || (first &lt; second); } friend bool operator &gt; (BigInt first, BigInt second){ if(!first.neg &amp;&amp; second.neg) return true; if(first.neg &amp;&amp; !second.neg) return false; if(first.neg &amp;&amp; second.neg){ first.neg = false; second.neg = false; return first &lt; second; } if((first.number).size() &gt; (second.number).size()) return true; if((first.number).size() &lt; (second.number).size()) return false; std::string temp1 = first.number; reverse(temp1.begin(), temp1.end()); std::string temp2 = second.number; reverse(temp2.begin(), temp2.end()); for(unsigned int i = 0; i &lt; temp1.size(); i++) if(temp1[i] &gt; temp2[i]) return true; else if(temp1[i] &lt; temp2[i]) return false; return false; } friend bool operator &gt;= (BigInt first, BigInt second){ return (first == second) || (first &gt; second); } void operator = (unsigned long long int number){ if(number &lt; 0){ this -&gt; neg = true; number *= -1; } this -&gt; number = ""; while(number &gt; 0){ this -&gt; number += (number % 10) + '0'; number /= 10; } } friend std::istream&amp; operator &gt;&gt; (std::istream&amp; in, BigInt &amp;bigint){ std::string number; in &gt;&gt; number; bigint.neg = false; while(number[0] == '-'){ bigint.neg = !bigint.neg; number.erase(0, 1); } reverse(number.begin(), number.end()); while(number.size() &gt; 1 &amp;&amp; number[number.size() - 1] == '0') number.erase(number.size() - 1, number.size()); bigint.number = number; if(number == "0") bigint.neg = false; return in; } friend std::ostream&amp; operator &lt;&lt; (std::ostream&amp; out, const BigInt &amp;bigint){ std::string number = bigint.number; reverse(number.begin(), number.end()); if(bigint.neg) number = '-' + number; out &lt;&lt; number; return out; } friend void swap(BigInt &amp;first, BigInt &amp;second){ BigInt temp(first); first = second; second = temp; } friend BigInt abs(BigInt bigint){ bigint.neg = false; return bigint; } friend BigInt operator + (BigInt first, BigInt second){ bool neg = false; if(!first.neg &amp;&amp; second.neg){ second.neg = false; return first - second; } if(first.neg &amp;&amp; !second.neg){ first.neg = false; return second - first; } if(first.neg &amp;&amp; second.neg){ neg = true; first.neg = second.neg = false; } int n = first.number.size(); int m = second.number.size(); int carry = 0; std::string result; for(int i = 0; i &lt; std::max(n, m); i++){ int add = carry; if(i &lt; n) add += first.number[i] - '0'; if(i &lt; m) add += second.number[i] - '0'; carry = add / 10; result += add % 10 + '0'; } if(carry != 0) result += carry + '0'; reverse(result.begin(), result.end()); BigInt result_(result); result_.neg = neg; return result_; } friend BigInt operator + (BigInt bigint){ return bigint; } friend BigInt operator - (BigInt first, BigInt second){ if(second.neg){ second.neg = false; return first + second; } if(first.neg){ second.neg = true; return first + second; } bool neg = false; if(first &lt; abs(second)){ neg = true; swap(first, second); first = abs(first); } int n = first.number.size(); int m = second.number.size(); int carry = 0; std::string result; for(int i = 0; i &lt; std::max(n, m); i++){ int add = carry; if(i &lt; n) add += first.number[i] - '0'; if(i &lt; m) add -= second.number[i] - '0'; if(add &lt; 0){ carry = -1; result += add + 10 + '0'; } else { carry = 0; result += add + '0'; } } reverse(result.begin(), result.end()); BigInt result_(result); result_.neg = neg; return result_; } friend BigInt operator - (BigInt second){ BigInt first("0"); return first - second; } friend BigInt operator * (BigInt first, BigInt second){ bool neg = first.neg != second.neg; first.neg = false; second.neg = false; int n = first.number.size(); int m = second.number.size(); BigInt result_; for(int i = 0; i &lt; n; i++){ int carry = 0; std::string result; for(int j = 0; j &lt; i; j++) result += '0'; for(int j = 0; j &lt; m; j++){ int add = carry + (first.number[i] - '0') * (second.number[j] - '0'); carry = add / 10; result += add % 10 + '0'; } if(carry != 0) result += carry + '0'; reverse(result.begin(), result.end()); BigInt current(result); result_ += current; } result_.neg = neg; return result_; } friend BigInt operator / (BigInt first, BigInt second){ if(second == "0") throw "Division with 0"; bool neg = first.neg != second.neg; first.neg = false; second.neg = false; BigInt quotient; int i = first.size() - 1; BigInt current(first.number[i] - '0'); --i; while(true){ BigInt result = current; bool l = false; while(result &lt; second &amp;&amp; i &gt;= 0){ result = result * 10 + (first.number[i--] - '0'); if(l) quotient *= 10; l = true; } int c = 0; BigInt result_(result); while(result_ &gt;= second){ result_ -= second; c++; } quotient = quotient * 10 + c; current = result_; if(i &lt; 0) break; } quotient.neg = neg; return quotient; } friend BigInt operator % (BigInt first, BigInt second){ if(second == "0") throw "Modulo with 0"; first.neg = false; second.neg = false; int i = first.size() - 1; BigInt current(first.number[i] - '0'); --i; while(true){ BigInt result = current; while(result &lt; second &amp;&amp; i &gt;= 0) result = result * 10 + (first.number[i--] - '0'); int c = 0; BigInt result_(result); while(result_ &gt;= second){ result_ -= second; c++; } current = result_; if(i &lt; 0) break; } current.neg = second.neg; return current; } friend BigInt pow(BigInt x, BigInt y, BigInt mod = 0){ if(mod != 0) x %= mod; BigInt res = 1; while(y != 0){ if(y % 2 == 1){ res *= x; if(mod != 0) res %= mod; } x *= x; if(mod != 0) x %= mod; y /= 2; } return res; } friend BigInt operator &amp; (BigInt first_, BigInt second_){ std::string first = first_.int_to_base(2); std::string second = second_.int_to_base(2); unsigned int n = std::min(first.size(), second.size()); reverse(first.begin(), first.end()); reverse(second.begin(), second.end()); std::string result(n, '~'); for(unsigned int i = 0; i &lt; n; i++){ if(first[i] == '1' &amp;&amp; second[i] == '1') result[i] = '1'; else result[i] = '0'; } reverse(result.begin(), result.end()); return BigInt().base_to_int(result, 2); } friend BigInt operator | (BigInt first_, BigInt second_){ std::string first = first_.int_to_base(2); std::string second = second_.int_to_base(2); unsigned int n = std::max(first.size(), second.size()); reverse(first.begin(), first.end()); reverse(second.begin(), second.end()); std::string result(n, '~'); for(unsigned int i = 0; i &lt; n; i++){ if(first.size() &lt;= i || second.size() &lt;= i){ if(first.size() &gt; i) result[i] = first[i]; if(second.size() &gt; i) result[i] = second[i]; continue; } if(first[i] == '1' || second[i] == '1') result[i] = '1'; else result[i] = '0'; } reverse(result.begin(), result.end()); return BigInt().base_to_int(result, 2); } friend BigInt operator ^ (BigInt first_, BigInt second_){ std::string first = first_.int_to_base(2); std::string second = second_.int_to_base(2); unsigned int n = std::max(first.size(), second.size()); reverse(first.begin(), first.end()); reverse(second.begin(), second.end()); std::string result(n, '~'); for(unsigned int i = 0; i &lt; n; i++){ if(first.size() &lt;= i || second.size() &lt;= i){ if(first.size() &gt; i){ if(first[i] == '0') result[i] = '0'; else result[i] = '1'; } if(second.size() &gt; i){ if(second[i] == '0') result[i] = '0'; else result[i] = '1'; } continue; } if(first[i] == second[i]) result[i] = '0'; else result[i] = '1'; } reverse(result.begin(), result.end()); return BigInt().base_to_int(result, 2); } friend BigInt operator &lt;&lt; (BigInt first, BigInt second){ BigInt x = pow(2, second); return first * x; } friend BigInt operator &gt;&gt; (BigInt first, BigInt second){ BigInt x = pow(2, second); return first / x; } int to_int(BigInt bigint){ int n = 0; for(int i = bigint.number.size() - 1; i &gt;= 0; i--) n = (n * 10) + (bigint.number[i] - '0'); return n; } std::string int_to_base(int base){ std::string result; BigInt bigint(*this); while(bigint &gt; 0){ BigInt r = bigint % base; if(r &gt;= 10) result += (char)(to_int(r / 10) + 'A'); else result += (char)(to_int(r) + '0'); bigint /= base; } reverse(result.begin(), result.end()); return result; } BigInt base_to_int(std::string str, int base){ BigInt result; for(unsigned int i = 0; i &lt; str.size(); i++){ BigInt add; if('0' &lt;= str[i] &amp;&amp; str[i] &lt;= '9') add += str[i] - '0'; else add += (str[i] - 'A') + 10; result = result * base + add; } return result; } int size(){ return this -&gt; number.size(); } void operator ++ (){*(this) = *(this) + 1;} void operator -- (){*(this) = *(this) - 1;} void operator += (BigInt bigint){*(this) = *(this) + bigint;} void operator -= (BigInt bigint){*(this) = *(this) - bigint;} void operator *= (BigInt bigint){*(this) = *(this) * bigint;} void operator /= (BigInt bigint){*(this) = *(this) / bigint;} void operator %= (BigInt bigint){*(this) = *(this) % bigint;} void operator &amp;= (BigInt bigint){*(this) = *(this) &amp; bigint;} void operator |= (BigInt bigint){*(this) = *(this) | bigint;} void operator ^= (BigInt bigint){*(this) = *(this) ^ bigint;} void operator &lt;&lt;= (BigInt bigint){*(this) = *(this) &lt;&lt; bigint;} void operator &gt;&gt;= (BigInt bigint){*(this) = *(this) &gt;&gt; bigint;} }; </code></pre> <p>If I'm missing any functions, please point it out!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T12:59:56.147", "Id": "466139", "Score": "0", "body": "It's unusual to have so many version tags. If you intend this to compile on all versions from C++11 to C++17, I don't think you really need to mention C++14 - that should be implied by [tag:c++11] [tag:c++17]. Are you explicitly excluding C++20?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T13:05:20.870", "Id": "466142", "Score": "0", "body": "@TobySpeight Good point, I've edited the tags. I don't know much about C++20, so I excluded it, but I do intend this program to work for c++ versions from 11 to 17." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T14:22:46.180", "Id": "466154", "Score": "1", "body": "Using the Visual Studio 2019 C++ compiler this doesn't compile, for some reason it is trying to use the `pow` function defined in `<cmath>` rather than the `pow` function defined in the code. Note, this line indicates that the BigInt type doesn't exist which is probably causing the other error `friend BigInt pow(BigInt x, BigInt y, BigInt mod = 0) {`\n`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T14:30:51.247", "Id": "466158", "Score": "0", "body": "@pacmaninbw Could you please tell me the version of your compiler?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T14:38:09.217", "Id": "466161", "Score": "0", "body": "Should be C++17" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T14:40:44.633", "Id": "466163", "Score": "0", "body": "The code works perfectly fine here: https://www.onlinegdb.com/online_c++_compiler (The language is C++ by default, please change it to C++17 in the Top Right corner)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T14:43:07.027", "Id": "466165", "Score": "0", "body": "Sorry, I don't use online compilers. I use released compilers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T14:43:24.203", "Id": "466167", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/104750/discussion-between-srivaths-and-pacmaninbw)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T04:58:14.087", "Id": "466236", "Score": "2", "body": "Hi Srivaths. I have rolled back your last edit. Please don't change or add to the code in your question after you have received answers. See [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T10:44:38.077", "Id": "466265", "Score": "0", "body": "@L.F. Thanks! Didn't know that!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T20:18:30.707", "Id": "466316", "Score": "1", "body": "@pacmaninbw and Srivaths: https://godbolt.org/ has various versions of MSVC installed, including recent ones. My understanding is that it's literally the same compiler that Microsoft releases, and Microsoft itself actually maintains the VMs that run MSVC for the Godbolt compiler explorer. Skepticism is fair for some online compilers, including Godbolt (e.g. for their Linux GCC versions, sometimes those are using different headers than would normally come with that GCC). But I think MSVC should be consistent with a desktop install." } ]
[ { "body": "<p>We use <code>std::string</code> without including <code>&lt;string&gt;</code> - a possible portability bug.</p>\n\n<p>Representation as a string of <code>char</code> isn't very compact, so we're quite wasteful of space for large numbers.</p>\n\n<p>The modifying operators (<code>++</code>, <code>*=</code>, etc) all return <code>void</code>, but it's normal and expected that they return a reference to <code>*this</code> (act like the integers).</p>\n\n<p>It's suspect to have a copy-constructor but no copy-assignment operator. In this case, the copy constructor adds no value and should be removed, allowing the compiler to generate default copy and move operations.</p>\n\n<p><s>Some more that can be removed: we could get away with constructors taking <code>std::intmax_t</code> and <code>std::uintmax_t</code> and removing those that accept shorter integers. Standard integer promotion would then work for us.</s></p>\n\n<p>It's probably not worth accepting <code>const char*</code>, given the implicit conversion to <code>std::string</code>.</p>\n\n<p>Consider making some or all of the constructors <code>explicit</code>. Certainly the construction from string should be explicit.</p>\n\n<p>In <code>BigInt(std::string number)</code>, consider that it's more efficient to remove characters from the end of <code>std::string</code>, so reverse it before counting <code>-</code> signs (and we can use <code>s.back()</code> to access the last character more readably than <code>s[s.size() - 1]</code>).</p>\n\n<p>There's no need to sprinkle <code>this-&gt;</code> all over the place - that's just visual clutter. I would recommend renaming either the member or the parameter to many methods so that they are not both called <code>number</code>.</p>\n\n<p>This comparison is never true:</p>\n\n<blockquote>\n<pre><code>BigInt(unsigned long long int number){\n if(number &lt; 0){\n</code></pre>\n</blockquote>\n\n<p>An unsigned type is never less than 0. This is likely a symptom that you're compiling without a good set of warnings; I'm using <code>g++ -Wall -Wextra -Wpedantic -Warray-bounds -Weffc++</code>.</p>\n\n<p>There's a more subtle issue here:</p>\n\n<blockquote>\n<pre><code>BigInt(long long int number){\n if(number &lt; 0){\n this -&gt; neg = true;\n number *= -1;\n }\n</code></pre>\n</blockquote>\n\n<p>On most systems, <code>LLONG_MIN</code> is less than <code>-LLONG_MAX</code>, meaning that there's at least one value that doesn't become positive when multiplied by <code>-1</code>.</p>\n\n<p>Comparison operators should take <code>const</code> references, rather than needlessly copying:</p>\n\n<pre><code>friend bool operator == (const BigInt&amp; first, const BigInt&amp; second){\n return first.number == second.number &amp;&amp; second.neg == first.neg;\n}\n</code></pre>\n\n<p>And it's normal to make them member functions rather than friends if they need access to the object's private members:</p>\n\n<pre><code>bool operator==(const BigInt&amp; other) const\n{\n return number == other.number &amp;&amp; neg == other.neg;\n}\n</code></pre>\n\n<p>The inequality operators are somewhat inefficient - there's no need to re-implement <code>std::string::operator&lt;()</code> in there. In fact, if we use <code>&lt;algorithm&gt;</code>, we don't need to make copies of the strings to reverse them; just use reverse iterators instead:</p>\n\n<pre><code>bool operator&lt;(const BigInt&amp; other) const\n{\n if (neg != other.neg) {\n return neg;\n }\n if (neg) {\n // TODO: avoid making copies here\n return -other &lt; *this;\n }\n\n if (number.size() != other.number.size()) {\n return number.size() &lt; other.number.size();\n }\n\n return std::lexicographical_compare(number.rbegin(), number.rend(),\n other.number.rbegin(), other.number.rend());\n}\n</code></pre>\n\n<p>We don't need to duplicate this logic to implement <code>operator&gt;()</code>:</p>\n\n<pre><code>bool operator&gt;(const BigInt&amp; other) const\n{\n return other &lt; *this;\n}\n\nbool operator&gt;=(const BigInt&amp; other) const\n{\n return other &lt;= *this;\n}\n</code></pre>\n\n<p>The streaming-in operator, <code>&gt;&gt;</code> re-does much work that's done in the constructor. Here's a simpler version, that removes the duplication:</p>\n\n<pre><code>friend std::istream&amp; operator&gt;&gt;(std::istream&amp; in, BigInt &amp;bigint)\n{\n std::string number;\n in &gt;&gt; number;\n bigint = std::move(number);\n return in;\n}\n</code></pre>\n\n<p>We don't need to use a temporary in <code>swap()</code> (and what we have is similar what <code>std::swap()</code> would give us for free, except copying instead of moving). Here's a more memory-efficient version:</p>\n\n<pre><code>void swap(BigInt &amp;other)\n{\n std::swap(neg, other.neg);\n std::swap(number, other.number);\n}\n</code></pre>\n\n<p>It's more usual to implement <code>+</code> in terms of <code>+=</code>, rather than the other way around. Again, that reduces the amount of temporary memory needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T16:29:27.050", "Id": "466186", "Score": "0", "body": "How do I resolve the `LONG_MIN` or `INT_MIN` problem? A great answer by the way!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T19:11:07.213", "Id": "466198", "Score": "1", "body": "@Srivaths Instead of doing the integer -> string conversion yourself, use `std::to_string` :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T19:12:44.627", "Id": "466199", "Score": "0", "body": "@Rakete1111 Thanks a lot! I didn't even know a function `to_string` existed!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T20:48:42.870", "Id": "466211", "Score": "0", "body": "I think there's a bug for your `operator<()`: when both operands are negative, `number.size()` and `lexicographical_compare` results should be inverted (because `number` holds the absolute value). `return neg != (number.size() < other.number.size());` should do the trick for the former, but the latter needs a distinction for the equality case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T05:01:13.777", "Id": "466237", "Score": "3", "body": "\"And it's normal to make them member functions rather than friends if they need access to the object's private members:\" Are you sure? Now `1 == BigInt(1)` doesn't compile (until C++20)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T20:27:42.363", "Id": "466317", "Score": "2", "body": "@Srivaths: To fix the 2's complement most-negative-number problem, make your absolute-value result unsigned. `unsigned long long val = 0ULL - x` is I think formally safe from signed-overflow UB, and definitely safe in practice. (`-x` might technically have signed overflow before conversion to unsigned). Don't multiply by -1, that's just silly. Although compilers will optimize it away." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T16:51:32.170", "Id": "466358", "Score": "1", "body": "_\"Some more that can be removed: we could get away with constructors taking std::intmax_t and std::uintmax_t and removing those that accept shorter integers.\"_ — This will result in [the problem of ambiguous overload](https://gcc.godbolt.org/z/p2gzX9)." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T15:03:02.913", "Id": "237702", "ParentId": "237690", "Score": "20" } }, { "body": "<p>These constructors are basically the same:</p>\n\n<pre><code>BigInt(int number)\nBigInt(long long int number)\nBigInt(unsigned long long int number)\n</code></pre>\n\n<p>So why not templatize them so you only have to write them once:</p>\n\n<pre><code>template&lt;typename I&gt;\nBigInt(I number)\n</code></pre>\n\n<p>If you are worried about non integer types you can add a constraint to make sure that I is always integers.</p>\n\n<pre><code>template&lt;typename I&gt;\nrequire std::is_integer&lt;I&gt; // C++20\nBigInt(I number)\n</code></pre>\n\n<p>or </p>\n\n<pre><code>template&lt;typename I, typename = std::enable_if_t&lt;std::is_integral&lt;I&gt;::value&gt;&gt;\nBigInt(I number)\n</code></pre>\n\n<p>Manually converting to a string:</p>\n\n<pre><code> while(number &gt; 0){\n this -&gt; number += (number % 10) + '0';\n number /= 10;\n }\n</code></pre>\n\n<p>Seems like a lot of work:</p>\n\n<pre><code> // This also works for zero.\n this-&gt;number = std::to_string(number);\n</code></pre>\n\n<p>You can then check the first character for '-' to set the negative flag (and then remove it).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T00:20:15.700", "Id": "466227", "Score": "0", "body": "or `typename std::enable_if<std::is_integral<I>::value, bool>::type = true`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T21:48:29.203", "Id": "237722", "ParentId": "237690", "Score": "7" } }, { "body": "<p>You are using a <code>string</code> as the underlying data structure. \nIt's wasteful in memory (using 10 possible values out of 256). \nIt's also <strong>super-slow</strong>, unless your primary use of <code>BigInt</code> is to print its decimal representation.</p>\n\n<p>You should have chosen something like</p>\n\n<pre><code>class BigInt {\n long number;\n std::vector&lt;unsigned long&gt; extra; // for when number overflows\n};\n</code></pre>\n\n<p>Discussing the rest kinda doesn't make sense in light of this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T20:05:45.533", "Id": "237756", "ParentId": "237690", "Score": "8" } }, { "body": "<p><strong>Using a power-of-10 base for extended precision is unusual, and only a good choice for specific use-cases</strong> (like if you mostly want to convert to decimal strings, or if multiplying / dividing by 10 is a major part of your workload).</p>\n\n<p><strong>Choosing 10^1 specifically wastes more than half the bits in a <code>char</code>, and leads to a huge amount of operations for large numbers.</strong> log2(10) = 3.3 useful bits of data per char. But <code>char</code> is typically (and at least) 8-bit in C++. You could have used base 100 in char elements. (Then conversion to an ASCII string would convert each chunk to 2 decimal digits, with one normal-sized division per chunk.)</p>\n\n<p>Even if you were to choose base 10, you likely don't want to store as actual ASCII; your number isn't ready-to-print anyway so you have the worst of both worlds: overhead during each step, and you still have to reverse (and maybe print a leading <code>-</code>) to produce a std::string in printing order. You could add <code>'0'</code> during the reversal. (And do <code>out &lt;&lt; '-'</code> instead of prepending it to a potentially-long string.) The one advantage of std::string over std::vector is that common implementations store the string bytes within the object for small strings, instead of as a separate allocation.</p>\n\n<p>(Related: <a href=\"https://stackoverflow.com/questions/61165307/vectorize-random-init-and-print-for-bigint-with-decimal-digit-array-with-avx2/61181913#61181913\">Vectorize random init and print for BigInt with decimal digit array, with AVX2?</a> has C with Intel intrinsics for a cache-blocked byte-reverse of an array into a tmp buf for <code>fwrite</code>, and for converting a vectorized xorshift128+ PRNG result to a vector of decimal digits. That part was an interesting problem to manually vectorize, but actual BigInt math ops can't easily be vectorized with SIMD. See @Mysticial's answer on <a href=\"https://stackoverflow.com/q/8866973\">Can long integer routines benefit from SSE?</a> for some techniques that do work.)</p>\n\n<hr>\n\n<p><strong>A more sensible choice if you still care about easy / fast conversion to decimal is base <code>10^9</code> in <code>uint32_t</code> chunks.</strong> I used that in x86 asm for a code golf challenge of <a href=\"https://codegolf.stackexchange.com/questions/133618/extreme-fibonacci\">printing the first 1000 digits of Fibonacci(10^9)</a> ; as the number got big, I could discard the least-significant 9 decimal digits by dropping one chunk, effectively dividing by 10^9 with a right shift by 1 chunk.</p>\n\n<p>Conversion to a decimal string can convert each chunk separately to 9 digits (including leading zeros), avoiding division of the entire BigInt by 10. And letting you start with the most-significant chunk to get digit-groups in printing order.</p>\n\n<p><strong>Other than memory bandwidth / cache footprint, <code>+</code> between <code>uint32_t</code> integers costs about the same as (or less than) <code>+</code> between <code>unsigned char</code>,</strong> the way you're using it in a loop. (i.e. where it compiles to a normal <code>add</code> instruction instead of optimizing into part of something else.) <strong>Getting ~30 result bits for the same price as 3.3 bits is a huge win.</strong></p>\n\n<hr>\n\n<p><strong>You might want to take a look at how <a href=\"https://gmplib.org/\" rel=\"noreferrer\">GMP (the GNU MultiPrecision library)</a> is implemented.</strong> Mostly with hand-written asm for the lowest levels, making efficient carry in/out easier, but with <em>binary</em> chunks (aka limbs) of the widest type the machine can do efficiently. (That's often <code>unsigned long int</code>). They do have pure C fallback implementations of everything, for platforms where they don't have asm.</p>\n\n<hr>\n\n<p>And/or you might want to look at how the CPython interpreter implements extended precision; <strong>without the benefit of asm to do carry in/out to a chunk that uses the full range of a type, it's easier to use chunks of base <code>2^30</code>.</strong> Using <code>uint_least32_t</code> is probably a good idea; it's guaranteed to be large enough to hold values up to 2^30. (And will typically be an efficient size like <code>unsigned int</code>, although you might consider loading array elements into local temporaries of <code>uint_fast32_t</code> inside your loop. Or not; some x86-64 implementations unwisely make <code>uint_fast32_t</code> a 64-bit type. You'll need a 64-bit type anyway for multiply and divide, though).</p>\n\n<p>(You don't want to use a type that could potentially be 64-bit if you're only using 30 bits; that would waste more than half the space instead of just a couple bits.) CPython also has a fallback to using 15-bit chunks; I wouldn't bother with that especially for a toy implementation.</p>\n\n<p>For multiply, <code>full_result = x * (unsigned long long)y;</code> doesn't lose any bits. If your compiler has <code>unsigned __int128</code>, using 64-bit chunks means half as many chunks, taking better advantage of 64-bit machines.</p>\n\n<p>For addition, you just do the add normally, then <code>sum &amp; ((1UL&lt;&lt;30) - 1)</code> to modulo this limb, and <code>sum &gt;&gt; 30</code> to get the carry-in for the next limb.</p>\n\n<ul>\n<li><a href=\"https://rushter.com/blog/python-integer-implementation/\" rel=\"noreferrer\">https://rushter.com/blog/python-integer-implementation/</a></li>\n<li><a href=\"https://hg.python.org/cpython/file/db842f730432/Include/longintrepr.h#l10\" rel=\"noreferrer\">https://hg.python.org/cpython/file/db842f730432/Include/longintrepr.h#l10</a> has useful comments, too.</li>\n</ul>\n\n<p>Unlike CPython, you probably don't need special fast-paths for single-limb integers. Unless you expect people to use your class for numbers that are <em>usually</em> small but can be big.</p>\n\n<hr>\n\n<p>And BTW, your divide and modulo algorithms are really bad. For a narrow (single-limb) divisor, you can use the remainder of one division as the high half of the dividend for the next lower limb. You don't need repeated subtraction. There are lots of assembly-language questions on Stack Overflow about how to implement large divisions in terms of a 2N / N => N-bit division. (C++ of course doesn't have that, just use a 2N bit type and let your compiler (fail to) optimize it.)</p>\n\n<p>(The general case of extended-precision division is hard, though, where the divisor is multiple limbs. Yet another reason to use large limbs so more divisors can be single-limb.)</p>\n\n<p>Also, when you do <code>% 2</code> as part of some other algorithm, you should just be looking at the low bit of the lowest limb!! For divisors that are factors of your base (2 and 5 for your case for base 10), you only need to look at the low limb. Numbers that end with an even digit are divisible by 2. Numbers that end with 0 or 5 are divisible by 5.</p>\n\n<p>What should be checking a single bit in your multiply loop instead becomes a huge copy and iterate over the whole BigInt.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T23:40:05.877", "Id": "237764", "ParentId": "237690", "Score": "13" } } ]
{ "AcceptedAnswerId": "237702", "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T10:39:14.580", "Id": "237690", "Score": "15", "Tags": [ "c++", "c++11", "c++17", "bigint" ], "Title": "BigInt class in C++" }
237690
<p>I am working on an object detection API implemented in Tensorflow 1.14 and OpenCV 4.1, where my task is to recognize personal protection equipment (PPE) worn by workers at various construction site gates.</p> <p>We are using RTSP streams, where I am already using threading to minimize latency, but still some times the stream crashes. So I decided to restart the whole python script every <code>n</code> times of detection to prevent the whole thing crashing because of corrupted frames and so on, but Tensorflow is very slow with the loading of inference graph and such for the first time (for me it's ~20 seconds), which is unacceptable to wait for the workers to get inside the site at the gate. So now I am considering to just stop and then restart JUST the RTSP stream with OpenCV, which constantly feeds the inference machinery with frames for executing object detection on them.</p> <p>Now I have not found any helpful threads on this topic, so that is why I am writing it here.</p> <p>My code:</p> <pre class="lang-py prettyprint-override"><code>from threading import Thread import cv2, time import numpy as np import os import six.moves.urllib as urllib import sys import tarfile from threading import Thread import tensorflow as tf import tensorflow.contrib.tensorrt as trt import zipfile from distutils.version import StrictVersion from collections import defaultdict from io import StringIO from object_detection.utils import ops as utils_ops import streamlit as st import imageio import shutil from PIL import Image, ImageDraw os.environ['TF_CPP_MIN_LOG_LEVEL']='2' TF_CUDNN_USE_AUTOTUNE=0 if StrictVersion(tf.__version__) &lt; StrictVersion('1.9.0'): raise ImportError('Please upgrade your TensorFlow installation to v1.9.* or later!') from object_detection.utils import label_map_util from object_detection.utils import visualization_utils as vis_util MODEL_NAME = './object_detection/inference_Strabag_2020_01_20_100k_mefelelo' modeln = "inference_Strabag_2020_01_20_100k_mefelelo" PATH_TO_FROZEN_GRAPH = MODEL_NAME + '/frozen_inference_graph.pb' PATH_TO_LABELS = './object_detection/training/labelmap.pbtxt' savedir1 = "/home/dome/web/html/" #savedir2 ="/var/www/html/" image_store1 = 0 image_store2 = 0 detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True) with detection_graph.as_default(): with tf.Session(config=tf.ConfigProto(gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.35))) as sess: # Get handles to input and output tensors ops = tf.get_default_graph().get_operations() all_tensor_names = {output.name for op in ops for output in op.outputs} tensor_dict = {} for key in ['num_detections', 'detection_boxes', 'detection_scores','detection_classes', 'detection_masks']: tensor_name = key + ':0' if tensor_name in all_tensor_names: tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(tensor_name) global detected_counter1 global detected_counter2 global PASS_score1 global NOPASS_score1 global PASS_score2 global NOPASS_score2 global scoresumCounter1 global scoresumCounter2 global PASS_score_tmp global NOPASS_score_tmp global detection_index global detboxesAreaTMP1 global detboxesAreaTMP2 global imagesgif1 global imagesgif2 resized_width = 426 resized_height = 240 rtsp_Url = 'not public' frameST = st.empty() def run_inference_for_single_image(image, graph): if 'detection_masks' in tensor_dict: # The following processing is only for single image detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0]) detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0]) # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size. real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32) detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1]) detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1]) detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks( detection_masks, detection_boxes, image.shape[0], image.shape[1]) detection_masks_reframed = tf.cast( tf.greater(detection_masks_reframed, 0.5), tf.uint8) # Follow the convention by adding back the batch dimension tensor_dict['detection_masks'] = tf.expand_dims( detection_masks_reframed, 0) image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0') # Run inference output_dict = sess.run(tensor_dict, feed_dict={image_tensor: np.expand_dims(image, 0)}) # all outputs are float32 numpy arrays, so convert types as appropriate output_dict['num_detections'] = int(output_dict['num_detections'][0]) output_dict['detection_classes'] = output_dict[ 'detection_classes'][0].astype(np.uint8) output_dict['detection_boxes'] = output_dict['detection_boxes'][0] output_dict['detection_scores'] = output_dict['detection_scores'][0] if 'detection_masks' in output_dict: output_dict['detection_masks'] = output_dict['detection_masks'][0] return output_dict detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True) global_def_tmp = 0 class VideoStreamWidget(object): detected_counter1 = 0 detected_counter2 = 0 PASS_score1 = 0 NOPASS_score1 = 0 PASS_score2 = 0 NOPASS_score2 = 0 scoresumCounter1=0 scoresumCounter2=0 PASS_score_tmp =0 NOPASS_score_tmp=0 detection_index = 0 detboxesAreaTMP1 = [] detboxesAreaTMP2 = [] image_store1 = [] image_store2 = [] imagesgif1 = [] imagesgif2 = [] def __init__(self, src=rtsp_Url): # Create a VideoCapture object #self.pipline_r = 'rtspsrc location='+rtsp_Url+' ! decodebin ! videoconvert ! appsink' self.capture = cv2.VideoCapture(src) self.capture.set(cv2.CAP_PROP_BUFFERSIZE, 1) self.capture.set(cv2.CAP_PROP_FPS, 4) self.capture.set(cv2.CAP_PROP_FRAME_WIDTH,resized_width) self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT,resized_height) self.FPS = 1/4 self.FPS_MS = int(self.FPS * 1000) # Start the thread to read frames from the video stream self.thread = Thread(target=self.update, args=()) self.thread.daemon = True self.thread.start() self.counter = 0 self.counter2=0 self.status = False def update(self): # Read the next frame from the stream in a different thread while True: if self.capture.isOpened(): #capture_buffer = np.empty(shape=(resized_width, resized_height, 3), dtype=np.uint8) (self.status, self.frame) = self.capture.read() self.frame = cv2.resize(self.frame,(resized_width,resized_height)) #print(self.status) #time.sleep(self.FPS) def show_frame(self): # Display frames in main program if self.counter == 0 : #print(self.counter) global detected_counter1 global detected_counter2 global PASS_score1 global NOPASS_score1 global PASS_score2 global NOPASS_score2 global scoresumCounter1 global scoresumCounter2 global PASS_score_tmp global NOPASS_score_tmp global detection_index global detboxesAreaTMP1 global detboxesAreaTMP2 global out1 global out2 global fourcc global image_store1 global image_store2 global imagesgif1 global imagesgif2 global end_time1 global start_time1 detected_counter1 = 0 detected_counter2 = 0 PASS_score1 = 0 NOPASS_score1 = 0 PASS_score2 = 0 NOPASS_score2 = 0 scoresumCounter1=0 scoresumCounter2=0 PASS_score_tmp =0 NOPASS_score_tmp=0 detection_index = 0 detboxesAreaTMP1 = [] detboxesAreaTMP2 = [] image_store1 = [] image_store2 = [] imagesgif1 = [] imagesgif2 = [] start_time1 = 0 end_time1 = 0 self.counter = 1 if self.status: start_time = time.time() if detected_counter1 == 0: #out1 = cv2.VideoWriter(savedir1+'cegled-villa1-vidiTMP.mp4',fourcc, 4.0, (resized_width, resized_height)) imagesgif1 = [] if detected_counter2 == 0: #out2 = cv2.VideoWriter(savedir1+'cegled-villa2-vidiTMP.mp4',fourcc, 4.0, (resized_width, resized_height)) imagesgif2 = [] #frameST.image(self.frame, channels="BGR") image_np = cv2.resize(self.frame,(resized_width,resized_height)) image_origi = image_np image_np_expanded = np.expand_dims(image_np, axis=0) image_origi_expanded = np.expand_dims(image_origi, axis=0) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0') detection_scores = detection_graph.get_tensor_by_name('detection_scores:0') detection_classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') (detection_boxes, detection_scores, detection_classes, num_detections) = sess.run( [detection_boxes, detection_scores, detection_classes, num_detections], feed_dict={image_tensor: image_np_expanded}) detection_boxes = np.asarray(detection_boxes) detection_classes = np.asarray(detection_classes) detection_scores = np.asarray(detection_scores) #print(end_time-start_time) ARO = 0.5 scoreThreshold = 0.8 scoresum1 = 0 scoresum2 = 0 avg_count = 8 thresh = 0.1 detboxesArea1 = [[0 for i in range(8)] for i in range(10)] detboxesArea2 = [[0 for i in range(8)] for i in range(10)] if detected_counter1==0: detboxesAreaTMP1 = [[0 for i in range(7)] for i in range(avg_count+2)] image_store1 = [0]*(avg_count+2) if detected_counter2==0: detboxesAreaTMP2 = [[0 for i in range(7)] for i in range(avg_count+2)] image_store2 = [0]*(avg_count+2) for k in range(10): if detection_scores[0][k] &gt;scoreThreshold and resized_width*detection_boxes[0][k][1]&gt;=resized_width/2.0- resized_width*0.1 : detboxesArea1[k][0] = (resized_height*(detection_boxes[0][k][2]-detection_boxes[0][k][0])*resized_width*(detection_boxes[0][k][3]-detection_boxes[0][k][1])) detboxesArea1[k][1] = k detboxesArea1[k][2] = resized_width*detection_boxes[0][k][1] #xmin detboxesArea1[k][3] = resized_height*detection_boxes[0][k][0] #ymin detboxesArea1[k][4] = resized_width*detection_boxes[0][k][3] #xmax detboxesArea1[k][5] = resized_height*detection_boxes[0][k][2] #ymax detboxesArea1[k][6] = int(detection_classes[0][k]) detboxesArea1[k][7] = detection_scores[0][k] if detection_scores[0][k] &gt;scoreThreshold and resized_width*detection_boxes[0][k][3]&lt;resized_width/2.0+resized_width*0.1 : detboxesArea2[k][0] = (resized_height*(detection_boxes[0][k][2]-detection_boxes[0][k][0])*resized_width*(detection_boxes[0][k][3]-detection_boxes[0][k][1])) detboxesArea2[k][1] = k detboxesArea2[k][2] = resized_width*detection_boxes[0][k][1] detboxesArea2[k][3] = resized_height*detection_boxes[0][k][0] detboxesArea2[k][4] = resized_width*detection_boxes[0][k][3] detboxesArea2[k][5] = resized_height*detection_boxes[0][k][2] detboxesArea2[k][6] = int(detection_classes[0][k]) detboxesArea2[k][7] = detection_scores[0][k] detboxesArea1 = sorted(detboxesArea1,reverse=True) detboxesArea2 = sorted(detboxesArea2,reverse=True) if detboxesArea1[0][3] &gt; 0.05*resized_height and detboxesArea1[0][0] &gt;0 : detboxesAreaTMP1[detected_counter1][0] = detboxesArea1[0][0] detboxesAreaTMP1[detected_counter1][1] = detboxesArea1[0][2] #xmin detboxesAreaTMP1[detected_counter1][2] = detboxesArea1[0][3] #ymin detboxesAreaTMP1[detected_counter1][3] = detboxesArea1[0][4] #xmax detboxesAreaTMP1[detected_counter1][4] = detboxesArea1[0][5] #ymax detboxesAreaTMP1[detected_counter1][5] = detected_counter1 image_store1[detected_counter1] = image_np detbox1Switch = 1 if detboxesArea2[0][3] &gt; 0.05*resized_height and detboxesArea2[0][0] &gt;0: detboxesAreaTMP2[detected_counter2][0] = detboxesArea2[0][0] detboxesAreaTMP2[detected_counter2][1] = detboxesArea2[0][2] detboxesAreaTMP2[detected_counter2][2] = detboxesArea2[0][3] detboxesAreaTMP2[detected_counter2][3] = detboxesArea2[0][4] detboxesAreaTMP2[detected_counter2][4] = detboxesArea2[0][5] detboxesAreaTMP2[detected_counter2][5] = detected_counter2 image_store2[detected_counter2] = image_origi detbox2Switch = 1 if detboxesArea1[0][6] == 1 : PASS_score1 += detboxesArea1[0][7] scoresum1 += detboxesArea1[0][7] cv2.rectangle(image_np, (int(detboxesArea1[0][2]),int(detboxesArea1[0][3])),(int(detboxesArea1[0][4]),int(detboxesArea1[0][5])), (37,200,37), 8) elif detboxesArea1[0][6] == 2: NOPASS_score1 += detboxesArea1[0][7] scoresum1 += detboxesArea1[0][7] cv2.rectangle(image_np, (int(detboxesArea1[0][2]),int(detboxesArea1[0][3])),(int(detboxesArea1[0][4]),int(detboxesArea1[0][5])), (60,29,200), 8) if detboxesArea2[0][6] == 1 : PASS_score2 += detboxesArea2[0][7] scoresum2 += detboxesArea2[0][7] cv2.rectangle(image_origi, (int(detboxesArea2[0][2]),int(detboxesArea2[0][3])),(int(detboxesArea2[0][4]),int(detboxesArea2[0][5])), (37,200,37), 8) elif detboxesArea2[0][6] == 2: NOPASS_score2 += detboxesArea2[0][7] scoresum2 += detboxesArea2[0][7] cv2.rectangle(image_origi, (int(detboxesArea2[0][2]),int(detboxesArea2[0][3])),(int(detboxesArea2[0][4]),int(detboxesArea2[0][5])), (60,29,200), 8) # Expand dimensions since the model expects images to have shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) image_origi_expanded = np.expand_dims(image_origi, axis=0) detected_counter1+=1 detected_counter2+=1 # Visualization of the results of a detection. ''' vis_util.visualize_boxes_and_labels_on_image_array( image_np, np.squeeze(detection_boxes[0]), np.squeeze(detection_classes[0]).astype(np.int32), np.squeeze(detection_scores[0]), category_index, instance_masks=output_dict.get('detection_masks'), use_normalized_coordinates=True, line_thickness=8) ''' #cv2.namedWindow('object_detection') #cv2.imshow('object_detection',image_np) if scoresum1 == 0: scoresumCounter1+=1 if scoresum2 == 0: scoresumCounter2+=1 if detected_counter1==avg_count and (avg_count-scoresumCounter1)&gt;=int(avg_count/4.0): timeframe = time.time() detboxesAreaTMP1 = sorted(detboxesAreaTMP1,reverse=True) if (PASS_score1)/(avg_count-scoresumCounter1) &gt;= (NOPASS_score1)/(avg_count-scoresumCounter1): cv2.rectangle(image_store1[detboxesAreaTMP1[0][5]], (int(detboxesAreaTMP1[0][1]),int(detboxesAreaTMP1[0][2])),(int(detboxesAreaTMP1[0][3]),int(detboxesAreaTMP1[0][4])), (37,152,37), 8) cv2.rectangle(image_store1[detboxesAreaTMP1[0][5]], (int(resized_width/2.0)+5,5),(resized_width-5,resized_height-5), (0,255,0), 8) start_time1 = time.time() cv2.imwrite(savedir1+"cegled-villa1.jpg", image_store1[detboxesAreaTMP1[0][5]]) os.system('php-cgi -f /home/dome/web/html/_iras.php passed=1 device_id=cegled-villa1') else: cv2.rectangle(image_store1[detboxesAreaTMP1[0][5]], (int(detboxesAreaTMP1[0][1]),int(detboxesAreaTMP1[0][2])),(int(detboxesAreaTMP1[0][3]),int(detboxesAreaTMP1[0][4])), (60,29,182), 8) cv2.rectangle(image_store1[detboxesAreaTMP1[0][5]], (int(resized_width/2.0)+5,5),(resized_width-5,resized_height-5), (0,0,255), 8) cv2.imwrite(savedir1+"cegled-villa1.jpg", image_store1[detboxesAreaTMP1[0][5]]) os.system('php-cgi -f /home/dome/web/html/_iras.php passed=0 device_id=cegled-villa1') PASS_score1 = 0 NOPASS_score1 = 0 detboxesAreaTMP1 = [] detected_counter1 = 0 scoresumCounter1 = 0 if detected_counter2==avg_count and (avg_count-scoresumCounter2)&gt;=int(avg_count/4.0): timeframe = time.time() detboxesAreaTMP2 = sorted(detboxesAreaTMP2,reverse=True) if (PASS_score2)/(avg_count-scoresumCounter2) &gt;= (NOPASS_score2)/(avg_count-scoresumCounter2): cv2.rectangle(image_store2[detboxesAreaTMP2[0][5]], (int(detboxesAreaTMP2[0][1]),int(detboxesAreaTMP2[0][2])),(int(detboxesAreaTMP2[0][3]),int(detboxesAreaTMP2[0][4])), (0,50,0), 8) cv2.rectangle(image_store2[detboxesAreaTMP2[0][5]], (5,5),(int(resized_width/2.0)-5,resized_height-5), (0,255,0), 8) cv2.imwrite(savedir1+"cegled-villa2.jpg", image_store2[detboxesAreaTMP2[0][5]]) os.system('php-cgi -f /home/dome/web/html/_iras.php passed=1 device_id=cegled-villa2') else: cv2.rectangle(image_store2[detboxesAreaTMP2[0][5]], (int(detboxesAreaTMP2[0][1]),int(detboxesAreaTMP2[0][2])),(int(detboxesAreaTMP2[0][3]),int(detboxesAreaTMP2[0][4])), (0,0,50), 8) cv2.rectangle(image_store2[detboxesAreaTMP2[0][5]], (5,5),(int(resized_width/2.0)-5,resized_height-5), (0,0,255), 8) cv2.imwrite(savedir1+"cegled-villa2.jpg", image_store2[detboxesAreaTMP2[0][5]]) os.system('php-cgi -f /home/dome/web/html/_iras.php passed=0 device_id=cegled-villa2') detected_counter2=0 scoresumCounter2 = 0 PASS_score2 = 0 NOPASS_score2 = 0 detboxesAreaTMP2 = [] if (detected_counter1==avg_count and (avg_count-scoresumCounter1)&lt;int(avg_count/4.0)) and (avg_count-scoresumCounter1)&gt;0 : PASS_score1 = 0 NOPASS_score1 = 0 detected_counter1=0 scoresumCounter1 = 0 detboxesAreaTMP1 = [] try: cv2.rectangle(image_store1[detboxesAreaTMP1[0][5]], (int(detboxesAreaTMP1[0][1]),int(detboxesAreaTMP1[0][2])),(int(detboxesAreaTMP1[0][3]),int(detboxesAreaTMP1[0][4])), (60,29,182), 8) cv2.rectangle(image_store1[detboxesAreaTMP1[0][5]], (int(resized_width/2.0)+5,5),(resized_width-5,resized_height-5), (0,0,255), 8) cv2.imwrite(savedir1+"cegled-villa1.jpg", image_store1[detboxesAreaTMP1[0][5]]) except IndexError: cv2.imwrite(savedir1+"cegled-villa1.jpg", image_np) os.system('php-cgi -f /home/dome/web/html/_iras.php passed=0 device_id=cegled-villa1') if (detected_counter2==avg_count and (avg_count-scoresumCounter2)&lt;int(avg_count/4.0)) and (avg_count-scoresumCounter2)&gt;0: PASS_score2 = 0 NOPASS_score2 = 0 detected_counter2=0 scoresumCounter2 = 0 detboxesAreaTMP2 = [] try: cv2.rectangle(image_store2[detboxesAreaTMP2[0][5]], (int(detboxesAreaTMP2[0][1]),int(detboxesAreaTMP2[0][2])),(int(detboxesAreaTMP2[0][3]),int(detboxesAreaTMP2[0][4])), (0,0,50), 8) cv2.rectangle(image_store2[detboxesAreaTMP2[0][5]], (5,5),(int(resized_width/2.0)-5,resized_height-5), (0,0,255), 8) cv2.imwrite(savedir1+"cegled-villa2.jpg", image_store2[detboxesAreaTMP2[0][5]]) except IndexError: cv2.imwrite(savedir1+"cegled-villa2.jpg", image_np) os.system('php-cgi -f /home/dome/web/html/_iras.php passed=0 device_id=cegled-villa2') if detected_counter1 == avg_count and (avg_count-scoresumCounter1)==0: detected_counter1 = 0 PASS_score1 = 0 NOPASS_score1 = 0 detected_counter1=0 scoresumCounter1 = 0 detboxesAreaTMP1 = [] if detected_counter2 == avg_count and (avg_count-scoresumCounter2)==0: detected_counter2 = 0 PASS_score2 = 0 NOPASS_score2 = 0 detected_counter2=0 scoresumCounter2 = 0 detboxesAreaTMP2 = [] #cv2.namedWindow('object_detection') end_time = time.time() del image_origi del image_np # Press Q on keyboard to stop recording key = cv2.waitKey(2) if key == ord('q'): self.capture.release() cv2.destroyAllWindows() exit(1) if __name__ == '__main__': stream_link = 'your stream link!' video_stream_widget = VideoStreamWidget(rtsp_Url) with detection_graph.as_default(): with tf.Session(config=tf.ConfigProto(gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.6))) as sess: # Get handles to input and output tensors ops = tf.get_default_graph().get_operations() all_tensor_names = {output.name for op in ops for output in op.outputs} tensor_dict = {} for key in ['num_detections', 'detection_boxes', 'detection_scores','detection_classes', 'detection_masks']: tensor_name = key + ':0' if tensor_name in all_tensor_names: tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(tensor_name) resfresherCounter = 0 imagesgif1 = [] imagesgif2 = [] while True: resfresherCounter+=1 try: video_stream_widget.show_frame() except cv2.error as e: print(e) detected_counter1 = 0 detected_counter2 = 0 continue </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T10:54:54.753", "Id": "237691", "Score": "3", "Tags": [ "python", "stream", "machine-learning", "opencv", "tensorflow" ], "Title": "PPE object detection with tensorflow and opencv with rtsp streams" }
237691
<p>I wrote the following code to generate a series of barcodes given a CSV with a list of ISBNs in the first column and titles in the second, using the <a href="https://pypi.org/project/python-barcode/" rel="noreferrer">python-barcode</a> library (which itself requires pillow to generate PNGs and JPGs). I am fairly new with Python and have had little formal training, and so would be interested in any and all feedback regarding functionality, formatting, and anything else I might be missing.</p> <pre class="lang-py prettyprint-override"><code>import os import csv import barcode from barcode.writer import ImageWriter def create_code_png(isbn,title): """Creates barcode, gives ISBN and title""" isbn13 = barcode.get_barcode_class('ean13') return isbn13(isbn, writer = ImageWriter()) def remove_forbidden(string_in): """Removes characters forbidden from windows file names from a string""" forbidden_chars = ":;&lt;&gt;\"\\/?*|." return "".join([char for char in string_in if char not in forbidden_chars]) def codes_from_csv(list_location,destination_folder): """Creates PNG Barcodes from a csv, placing them in a given folder""" with open(list_location, newline='') as csvfile: os.chdir(destination_folder) for row in csv.reader(csvfile, dialect='excel'): code = create_code_png(isbn:=row[0],title:=remove_forbidden(row[1])) code.save(isbn + " " + title) if __name__ == "__main__": codes_from_csv("P:\\barcodes.csv","E:\\Barcodes") </code></pre>
[]
[ { "body": "<p>All in all your code looks quite good, it even has documentation! It's interesting to see assignment expressions in actual use, though I have yet to decide if I'm a fan of them. But of course Code Review would not be Code Review if there was nothing to nitpick about ;-)</p>\n\n<p>As per <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8</a>, </p>\n\n<blockquote>\n<pre><code>isbn13(isbn, writer = ImageWriter())\n</code></pre>\n</blockquote>\n\n<p>should be</p>\n\n<pre><code>isbn13(isbn, writer=ImageWriter())\n</code></pre>\n\n<p>whereas</p>\n\n<blockquote>\n<pre><code>code = create_code_png(isbn:=row[0],title:=remove_forbidden(row[1]))\n</code></pre>\n</blockquote>\n\n<p>should be </p>\n\n<pre><code>code = create_code_png(isbn:=row[0], title:=remove_forbidden(row[1]))\n</code></pre>\n\n<p>We have a <a href=\"https://codereview.meta.stackexchange.com/a/5252/92478\">little list here on Code Review Meta</a> where you'll find a few tools that can help you to enforce a consistent style, even in larger projects.</p>\n\n<p>Apart from that, you could use <a href=\"https://docs.python.org/3/library/stdtypes.html#str.maketrans\" rel=\"noreferrer\"><code>str.maketrans/str.translate</code></a> in <code>remove_forbidden</code>:</p>\n\n<pre><code># somewhere earlier\nFORBIDDEN_SYMBOLS = str.maketrans({letter: \"\" for letter in \":;&lt;&gt;\\\"\\\\/?*|.\"})\n\ndef remove_forbidden(string_in):\n \"\"\"Removes characters forbidden from windows file names from a string\"\"\"\n return string_in.translate(FORBIDDEN_SYMBOLS)\n</code></pre>\n\n<pre class=\"lang-none prettyprint-override\"><code>this_is_asuperfancyfilename\n</code></pre>\n\n<p>By keeping <code>FORBIDDEN_SYMBOLS</code> somewhere outside the function, e.g. as a script level constant, this will be a little bit faster than your original implementation.</p>\n\n<p>If you want to include even more shiny Python features in addition to assignment expressions, maybe also have a look at <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"noreferrer\">f-strings</a> (3.6+) and <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"noreferrer\">type annotations</a> (3.5+).</p>\n\n<p>I also would not use <code>os.chdir</code> but instead build a full path using either <a href=\"https://docs.python.org/3/library/os.path.html\" rel=\"noreferrer\"><code>os.path.join</code></a> (the old way) or <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"noreferrer\">the Pathlib module</a> (the new way).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T14:21:44.800", "Id": "466153", "Score": "1", "body": "I think I'm starting to become less of a fan of assignment expressions, now that I see what kind of (potential) bugs they enable, see my answer :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T13:42:49.137", "Id": "237695", "ParentId": "237693", "Score": "6" } }, { "body": "<p>Since I think this is worth more than just a comment on another answer, in your <code>codes_from_csv</code> you are (ab)using the new walrus operator. Assignment expressions are not the right thing to do here. What they do is assign local variables (outside of the function!), and then the values of those local variables (but not their names) are passed by position to the function.</p>\n\n<p>A small example of how this can lead to unexpected results:</p>\n\n<pre><code>def f(a, b):\n return a // b\n\n# Normal positional arguments, order matters\nf(3, 1)\n# 3\nf(1, 3)\n# 0\n\n# Keyword arguments, order does not matter, only name\nf(a=3, b=1)\n# 3\nf(b=1, a=3)\n# 3\n\n# Using the walrus operator, variables are assigned,\n# but are passed as positional arguments.\n# The names of the (external) variables do not matter to the function!\nf(a:=3, b:=1)\n# 3\nf(b:=1, a:=3)\n# 0\n</code></pre>\n\n<p>In other words the last example is equivalent to:</p>\n\n<pre><code>b = 1\na = 3\nf(b, a)\n# 0\n</code></pre>\n\n<p>This might be what you want, but since you are using the names of the arguments of the function, it probably isn't. In your code it just so happens to work because you use the same order as in the function definition. This might be a source of bugs at some future point, which could be very hard to find!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T14:28:56.263", "Id": "466157", "Score": "3", "body": "[But it gets worse:](https://tio.run/##K6gsycjPM7YoKPr/PyU1TSFNI1FHIUnTiksBCIpSS0qL8hQSFfT1FZK4uAqKMvNKNNI0kmw1Eq1sDTV1FBJtNZKsbI01NTWhkmDN//8DAA) `f(b=(a:=1), a=(b:=3))` :-D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T20:32:56.257", "Id": "466208", "Score": "0", "body": "this doesn't feel particularly more confusing than a = 1\nb = 3\nf(b=a, a=b)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T14:15:04.613", "Id": "237699", "ParentId": "237693", "Score": "8" } } ]
{ "AcceptedAnswerId": "237695", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T11:42:44.783", "Id": "237693", "Score": "9", "Tags": [ "python", "python-3.x", "image" ], "Title": "Generating PNG barcodes from a CSV" }
237693
<p>I'm still a beginner so any pointers to make this code more professional/production ready are appreciated. The tokens and database connections have been anonymized. The script is working, its goal is to copy prices from one database and push them via api into another database. This data is monthly price data that usually arrives early in the month. So march prices arrive somewhere early march, but usually not on the first. They are then supposed to be pushed to the destination database via rest api. </p> <p>The catch is that we never know when the prices arrive in the source database, so the idea is to run this script daily via task scheduler and only push the data to the destination database once when they arrive, but we have to make sure that the data is not pushed twice and duplicates are created. I achieved this by only pushing when the data is in the source database, but not yet in the destination databse via IF check.</p> <p>I feel like this code is not very pythonic and lacking some possible error catchings for it to be ran automatically on a daily basis. Any pointers are appreciated.</p> <pre class="lang-py prettyprint-override"><code>import json import pandas as pd import pyodbc import sqlalchemy import datetime import sys import requests import pdb import pymysql #RPA API Connector target_url = "exampleurl" target_token = "exampletoken" target_headers = {"AUTH-TOKEN": target_token, "Content-Type": "application/json"} #Store todays date in variable now = datetime.datetime.now() #connecting to source DB def connect_mssqlserver(): engine_stmt = ("mssql+pyodbc://@server/database?driver=SQL+Server") engine = sqlalchemy.create_engine(engine_stmt) engine.connect() return engine #connect to destination DB def connect_mysqlserver(): engine_stmt = ('mysql+pymysql://user:password@server:host/database') engine = sqlalchemy.create_engine(engine_stmt) engine.connect() return engine def create_df(query, engine): #save table to df df = pd.read_sql(query, engine) return df #store source data in df source_df = create_df("SELECT * FROM PriceMonthly", connect_mssqlserver()) #Some dataframe modification to fit destination format source_df = source_df[source_df.Year == now.year] source_df['Tax'].fillna(0, inplace=True) source_df['Year'] = source_df['ImportFileName'].str[0:4].astype(int) source_df['Month'] = source_df['ImportFileName'].str[4:6].astype(int) #store destination table in dataframe dest_df = create_df("SELECT * FROM prices", connect_mysqlserver()) #Filter both dataframes by current year and month source_df = source_df[(source_df.Year == now.year) &amp; (source_df.Month == now.month)] dest_df = dest_df[(dest_df.Year == now.year) &amp; (dest_df.Month == now.month)] #Logic to check if data is in source and not yet in destination, only then push via api if source_df.empty == False and dest_df.empty == True: print('Data will be pushed') data = source_df.to_json(orient = "records") data = json.loads(data) #This loop is used for chunking as API times out when pushing a lot of data at the same time url = 'price' j = 0 i = 400 length = len(data) while j &lt;= length: print(j,i) data2 = data[j:i] target_response = requests.put(target_url + url + "/json", json=data2, headers=target_headers) assert target_response.status_code == 200, f"{target_url + url} -&gt; Expected 200, but received {target_response.status_code}" j = i i = i+400 elif dest_df.empty == False: print("Data Already At Destination") elif source_df.empty == True: print("No Data In Source") else: print("issue") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T19:43:52.837", "Id": "466201", "Score": "0", "body": "I see a `pdb` import at the top, don't think you need that" } ]
[ { "body": "<p>A few notes on your code above:</p>\n\n<ul>\n<li><code>connect_mssqlserver</code> and <code>connect_mysqlserver</code> could be condensed to a single 'connect' function that takes a <code>conn_str</code> arg to be used in <code>create_engine</code>.</li>\n<li>I believe <code>create_df</code> seems to be unnecessary at this point. If the process for creating the df involves more than just calling <code>read_sql</code> in the future, then I would opt for moving that logic into a separate function.</li>\n<li>nitpick: I would change <code>source_df.empty == False</code> and the following <code>True</code> check to just <code>not source.empty and dest_df.empty</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T08:38:07.640", "Id": "466406", "Score": "0", "body": "Thanks for the input I will adapt these changes :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T20:03:59.257", "Id": "237718", "ParentId": "237694", "Score": "2" } } ]
{ "AcceptedAnswerId": "237718", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T12:27:39.000", "Id": "237694", "Score": "4", "Tags": [ "python", "python-3.x", "sql", "api", "rest" ], "Title": "Script to push data from one database via api to another" }
237694
<p>I previously submitted my code for a HugeInt class <a href="https://codereview.stackexchange.com/questions/236843/huge-integer-class-using-base-232-was-256-follow-up">here.</a> That version lacked a long division implementation.</p> <p>I have now implemented (long) division using Donald Knuth's algorithm D, following the code that appeared in Hacker's Delight fairly closely. Since the algorithm relies on some a priori non-obvious facts and its implementation details are sometimes subtle (signed/unsigned implicit conversions, for example), I have annotated the code in <code>unsigned_divide()</code> quite heavily. (I would appreciate opinion on whether I have done too much, perhaps interrupting "algorithmic flow".) I have checked the new function <code>unsigned_divide()</code> quite extensively, and it seems to work correctly, but there are a lot of integers!</p> <p>I would appreciate a review of the code (given below) with a view to improving its performance and to see if there is perhaps a special/edge case I have overlooked (apart from division by 0, which is purposefully not checked). I include below simple driver code for testing division specifically.</p> <p>The full code can be found at <a href="https://github.com/Richard-Mace/huge-integer-class" rel="noreferrer"><a href="https://github.com/Richard-Mace/huge-integer-class" rel="noreferrer">https://github.com/Richard-Mace/huge-integer-class</a></a> and contains a few minor improvements since the last iteration (based on many good suggestions I received here), and some pruning of redundant functions.</p> <p>Thank you in advance for your time and assistance.</p> <p>Code from HugeInt.cpp: (header file below)</p> <pre><code>/** * friend binary operator / * * Return the quotient of two HugeInt numbers. Uses utility function * unsigned_divide, which employs Donald Knuth's long division algorithm. See * comments on implicit conversion before * HugeInt operator+(const HugeInt&amp;, const HugeInt&amp;) above, which are * applicable here also. * * @param a * @param b * @return */ HugeInt operator/(const HugeInt&amp; a, const HugeInt&amp; b) { if (a &lt; 0) { if (b &lt; 0) { return unsigned_divide(-a, -b, nullptr); } else { return -unsigned_divide(-a, b, nullptr); } } else { if (b &lt; 0) { return -unsigned_divide(a, -b, nullptr); } else { return unsigned_divide(a, b, nullptr); } } } /** * friend binary operator % * * Return the remainder from the division of two HugeInt numbers. Uses utility * function unsigned_divide. Adheres to the C/C++ convention that the sign of * the remainder is the same as the sign of the dividend. See comments on * implicit conversion before HugeInt operator+(const HugeInt&amp;, const HugeInt&amp;) * above, which are applicable here also. * * @param a * @param b * @return */ HugeInt operator%(const HugeInt&amp; a, const HugeInt&amp; b) { HugeInt remainder; if (a &lt; 0) { if (b &lt; 0) { unsigned_divide(-a, -b, &amp;remainder); return -remainder; } else { unsigned_divide(-a, b, &amp;remainder); return -remainder; } } else { if (b &lt; 0) { unsigned_divide(a, -b, &amp;remainder); return remainder; } else { unsigned_divide(a, b, &amp;remainder); return remainder; } } } /** * unsigned_divide: (private utility function) * * Unsigned division of a by b giving quotient q = [a/b] and remainder r, such * that * a = q * b + r, where 0 &lt;= r &lt; b. * * Dividend a is assumed non-negative (a &gt;= 0) and divisor b is positive * definite (b &gt; 0). If the number of base-2^32 digits in b is 1, then short * division is used. Otherwise Donald Knuth's Algorithm D is used. * * The implementation of Knuth's algorithm here is very similar to that which * appears in the book Hacker's Delight by Henry S. Warren, but borrows some * ideas from janmr's blog entry (to which credit is duly given): * * https://janmr.com/blog/2014/04/basic-multiple-precision-long-division/ * * If remainder is not a nullptr, then the remainder r is returned in space * allocated by the caller. * * WARNING: no checks on the validity of a and b are made for performance * reasons. * * @param a * @param b * @return */ HugeInt unsigned_divide(const HugeInt&amp; a, const HugeInt&amp; b, HugeInt* const remainder) { HugeInt dividend{a}; HugeInt divisor{b}; // Determine the number of base-2^32 digits in dividend and divisor. int n{HugeInt::numDigits_}; for ( ; n &gt; 0 &amp;&amp; divisor.digits_[n - 1] == 0; --n); int m{HugeInt::numDigits_}; for ( ; m &gt; 0 &amp;&amp; dividend.digits_[m - 1] == 0; --m); // Technically, m can equal 0 here, if 'a' (the dividend) = 0. This is no // problem as it will be caught and handled by CASE 1 below. // CASE 1: m &lt; n =&gt; quotient = 0; remainder = dividend. HugeInt quotient; if (m &lt; n) { if (remainder != nullptr) { if (*remainder != 0) { *remainder == 0LL; } for (int i = 0; i &lt; m; ++i) { remainder-&gt;digits_[i] = dividend.digits_[i]; } } return quotient; } // CASE 2: Divisor has only one base-2^32 digit (n = 1). Do a short // division and return. if (n &lt; 2) { std::uint64_t partial{0}; for (int i = m - 1 ; i &gt;= 0; --i) { partial = HugeInt::base_ * partial + static_cast&lt;std::uint64_t&gt;(dividend.digits_[i]); quotient.digits_[i] = static_cast&lt;std::uint32_t&gt;(partial / divisor.digits_[0]); partial %= divisor.digits_[0]; } if (remainder != nullptr) { if (*remainder != 0) { *remainder == 0LL; } remainder-&gt;digits_[0] = partial; } return quotient; } // CASE 3: m &gt;= n and the number of digits, n, in the divisor is &gt;= 2. // Proceed with long division using Donald Knuth's Algorithm D. // // Determine power-of-two normalisation factor, d = 2^shifts, necessary for // d * divisor.digits[n-1] &gt;= base_ / 2. int shifts{0}; std::uint32_t vn{divisor.digits_[n - 1]}; while (vn &lt; (HugeInt::base_ &gt;&gt; 1)) { vn &lt;&lt;= 1; ++shifts; } // Scale the divisor and dividend by factor d, using shifts for efficiency. // This scaling does not affect the quotient, but it ensures that // q_k &lt;= qhat &lt;= q_k + 2 (see later). for (int i = n - 1; i &gt; 0; --i) { divisor.digits_[i] = (divisor.digits_[i] &lt;&lt; shifts) | (static_cast&lt;std::uint64_t&gt;(divisor.digits_[i - 1]) &gt;&gt; (32 - shifts)); } divisor.digits_[0] = divisor.digits_[0] &lt;&lt; shifts; // Prepend a (m+1)'th zero-value digit to the dividend, then shift. dividend.digits_[m] = static_cast&lt;std::uint64_t&gt;(dividend.digits_[m - 1]) &gt;&gt; (32 - shifts); for (int i = m - 1; i &gt; 0; --i) { dividend.digits_[i] = (dividend.digits_[i] &lt;&lt; shifts) | (static_cast&lt;std::uint64_t&gt;(dividend.digits_[i - 1]) &gt;&gt; (32 - shifts)); } dividend.digits_[0] = dividend.digits_[0] &lt;&lt; shifts; // Do the long division using the primary school algorithm, estimating // partial quotients with a two most significant digit approximation for // the dividend and a single most significant digit approximation for the // divisor. for (int k = m - n; k &gt;= 0; --k) { std::uint64_t rhat = dividend.digits_[k + n] * HugeInt::base_ + static_cast&lt;std::uint64_t&gt;(dividend.digits_[k + n - 1]); std::uint64_t qhat = rhat / divisor.digits_[n - 1]; rhat %= divisor.digits_[n - 1]; // Digit q_k estimated by qhat must satisfy 0 &lt;= q_k &lt;= base_ - 1. // If too large, decrement and adjust remainder rhat accordingly. if (qhat == HugeInt::base_) { qhat -= 1; rhat += divisor.digits_[n - 1]; } // Compare with a "second order" approximation to the partial quotient. // If this comparison indicates that qhat overestimates, decrement, // adjust remainder rhat and repeat. while (rhat &lt; HugeInt::base_ &amp;&amp; (qhat * divisor.digits_[n - 2] &gt; HugeInt::base_ * rhat + dividend.digits_[k + n - 2])) { qhat -= 1; rhat += divisor.digits_[n - 1]; } // We have an estimate qhat for the true digit q_k that satisfies // q_k &lt;= qhat &lt;= q_k + 1. Calculate the corresponding remainder // (a_{k+n} ... a_{k}) - qhat * (b_{n-1}...b_{0}) for this partial // quotient, storing the result in digits a_{k+n}... a_{k} of the // dividend. Care is taken with the carries. The overwritten digits // accrue, and eventually become, the complete remainder. std::int64_t carry{0}; // signed; carry &gt; 0, borrow &lt; 0 std::int64_t widedigit; // signed for (int i = 0; i &lt; n; ++i) { std::uint64_t product = static_cast&lt;std::uint32_t&gt;(qhat) * static_cast&lt;std::uint64_t&gt;(divisor.digits_[i]); widedigit = (dividend.digits_[k + i] + carry) - (product &amp; 0xffffffffLL); dividend.digits_[k + i] = widedigit; // assigns 2^32-complement // if widedigit &lt; 0 carry = (widedigit &gt;&gt; 32) - (product &gt;&gt; 32); } widedigit = dividend.digits_[k + n] + carry; dividend.digits_[k + n] = widedigit; // 2^32-complement if // widedigit &lt; 0 // Accept and store the tentative quotient digit. quotient.digits_[k] = qhat; // However, since q_k &lt;= qhat &lt;= q_k + 1, either we have the correct // digit, or we need to decrement. To resolve this, check if there was // a borrow on determining the final k + n digit of the remainder. If // no, we have q_k = qhat and we are done. Otherwise, qhat = q_k + 1, // and we need to decrement and add the divisor to digits k + n ... k // of the dividend (now the remainder). if (widedigit &lt; 0) { quotient.digits_[k] -= 1; widedigit = 0; for (int i = 0; i &lt; n; ++i) { widedigit += static_cast&lt;std::uint64_t&gt;(dividend.digits_[k + i]) + divisor.digits_[i]; dividend.digits_[k + i] = widedigit; widedigit &gt;&gt;= 32; } dividend.digits_[k + n] += carry; } } /* end main loop over k */ // We are done. Return the remainder? if (remainder != nullptr) { if (*remainder != 0) { *remainder == 0LL; } // Denormalise dividend, which now contains the full remainder // (stored in n - 1 digits). for (int i = 0; i &lt; n - 1; ++i) { remainder-&gt;digits_[i] = (dividend.digits_[i] &gt;&gt; shifts) | (static_cast&lt;std::uint64_t&gt;(dividend.digits_[i + 1]) &lt;&lt; (32 - shifts)); } remainder-&gt;digits_[n - 1] = dividend.digits_[n - 1] &gt;&gt; shifts; } return quotient; } </code></pre> <p>HugeInt.h:</p> <pre><code>/* * HugeInt.h * * Definition of the huge integer class * Richard Mace, February, 2020 * * RADIX 2^32 VERSION * * Huge integers are represented as N-digit arrays of uint32_t types, where * each uint32_t value represents a base-2^32 digit. By default N = 300, which * corresponds to a maximum of 2890 decimal digits. Each uint32_t contains * a single base-2^32 digit in the range 0 &lt;= digit &lt;= 2^32 - 1. If `index' * represents the index of the array of uint32_t digits[N], * i.e., 0 &lt;= index &lt;= N - 1, and 'value' represents the power of 2^32 * corresponding to the radix 2^32 digit at 'index', then we have the following * correspondence: * * index |...... | 4 | 3 | 2 | 1 | 0 | * ----------------------------------------------------------------------- * value |...... | (2^32)^4 | (2^32)^3 | (2^32)^2 | (2^32)^1 | (2^32)^0 | * * The physical layout of the uint32_t array in memory is: * * uint32_t digits[N] = {digits[0], digits[1], digits[2], digits[3], ... } * * which means that the units (2^32)^0 appear first in memory, while the power * (2^32)^(N-1) appears last. This LITTLE ENDIAN storage represents the * number in memory in the REVERSE order of the way we write decimal numbers, * but is convenient. * * Negative integers are represented by their radix complement. With the * base 2^32 implementation here, we represent negative integers by their base * 2^32 complement. With this convention the range of * non-negative integers is: * 0 &lt;= x &lt;= (2^32)^N/2 - 1 * The range of base 2^32 integers CORRESPONDING to negative values in the * base 2^32 complement scheme is: * (2^32)^N/2 &lt;= x &lt;= (2^32)^N - 1 * So -1 corresponds to (2^32)^N - 1, -2 corresponds to (2^32)^N - 2, and so on. * * The complete range of integers represented by a HugeInt using radix * complement is: * * -(2^32)^N/2 &lt;= x &lt;= (2^32)^N/2 - 1 */ #ifndef HUGEINT_H #define HUGEINT_H #include &lt;string&gt; #include &lt;iosfwd&gt; namespace iota { class HugeInt { public: HugeInt() = default; HugeInt(long long int); // conversion constructor from long long int explicit HugeInt(const char* const); // conversion constructor from C string HugeInt(const HugeInt&amp;); // copy/conversion constructor // assignment operator const HugeInt&amp; operator=(const HugeInt&amp;); // unary minus operator HugeInt operator-() const; // conversion to long double explicit operator long double() const; // basic arithmetic friend HugeInt operator+(const HugeInt&amp;, const HugeInt&amp;); friend HugeInt operator-(const HugeInt&amp;, const HugeInt&amp;); friend HugeInt operator*(const HugeInt&amp;, const HugeInt&amp;); friend HugeInt operator/(const HugeInt&amp;, const HugeInt&amp;); friend HugeInt operator%(const HugeInt&amp;, const HugeInt&amp;); // increment and decrement operators HugeInt&amp; operator+=(const HugeInt&amp;); HugeInt&amp; operator-=(const HugeInt&amp;); HugeInt&amp; operator*=(const HugeInt&amp;); HugeInt&amp; operator/=(const HugeInt&amp;); HugeInt&amp; operator%=(const HugeInt&amp;); HugeInt&amp; operator++(); // prefix HugeInt operator++(int); // postfix HugeInt&amp; operator--(); // prefix HugeInt operator--(int); // postfix // relational operators friend bool operator==(const HugeInt&amp;, const HugeInt&amp;); friend bool operator!=(const HugeInt&amp;, const HugeInt&amp;); friend bool operator&lt;(const HugeInt&amp;, const HugeInt&amp;); friend bool operator&gt;(const HugeInt&amp;, const HugeInt&amp;); friend bool operator&lt;=(const HugeInt&amp;, const HugeInt&amp;); friend bool operator&gt;=(const HugeInt&amp;, const HugeInt&amp;); // input/output std::string toRawString() const; std::string toDecimalString() const; friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp;, const HugeInt&amp;); friend std::istream&amp; operator&gt;&gt;(std::istream&amp;, HugeInt&amp;); // informational int numDecimalDigits() const; static HugeInt getMinimum(); static HugeInt getMaximum(); private: static const std::size_t numDigits_{300}; // max. no. base 2^32 digits static const std::uint64_t base_{1ULL &lt;&lt; 32}; // 2^32, for convenience std::uint32_t digits_[numDigits_]{0}; // base 2^32 digits // private utility functions bool isZero() const; bool isNegative() const; HugeInt&amp; radixComplement(); HugeInt shortMultiply(std::uint32_t) const; HugeInt shortDivide(std::uint32_t, std::uint32_t* const) const; friend HugeInt unsigned_divide(const HugeInt&amp;, const HugeInt&amp;, HugeInt* const); HugeInt&amp; shiftLeftDigits(int); }; } /* namespace iota */ #endif /* HUGEINT_H */ </code></pre> <p>Some rough test code:</p> <pre><code>/* * Some simple tests of the HugeInt division algorithm. * * February 2020. */ #include "HugeInt.h" #include &lt;iostream&gt; #include &lt;string&gt; // Calculate n! // iota::HugeInt factorial_iterative(const iota::HugeInt&amp; n) { iota::HugeInt result{1LL}; if (n == 0LL) { return result; } for (iota::HugeInt i = n; i &gt;= 1; --i) { result *= i; } return result; } // Calculate the n'th Fibonacci number // iota::HugeInt fibonacci_iterative(const iota::HugeInt&amp; n) { const iota::HugeInt zero; const iota::HugeInt one{1LL}; if ((n == zero) || (n == one)) { return n; } iota::HugeInt retval; iota::HugeInt fib_nm1 = one; iota::HugeInt fib_nm2 = zero; for (iota::HugeInt i = 2; i &lt;= n; ++i) { retval = fib_nm1 + fib_nm2; fib_nm2 = fib_nm1; fib_nm1 = retval; } return retval; } // // Return the nth Fermat number. (n &gt;= 1) // // Fermat(n) = 2^(2n) + 1. // // iota::HugeInt fermat_number(long int n) { long long int exponent = (1LL &lt;&lt; n); iota::HugeInt retval{2LL}; for (long long int i = 1; i &lt; exponent; ++i) { retval *= 2LL; } return retval + 1LL; } // Check the results of a division by computing // // check = quotient * divisor + remainder // // and verifying that check == dividend. // void check_division(std::string case_name, iota::HugeInt dividend, iota::HugeInt divisor) { iota::HugeInt quotient = dividend / divisor; iota::HugeInt remainder = dividend % divisor; iota::HugeInt check = quotient * divisor + remainder; std::cout &lt;&lt; "TESTING " &lt;&lt; case_name &lt;&lt; " -----------------------------------------------------------------------\n\n"; std::cout &lt;&lt; '\t' &lt;&lt; dividend &lt;&lt; " / " &lt;&lt; divisor &lt;&lt; '\n'; std::cout &lt;&lt; "\tquotient = " &lt;&lt; quotient &lt;&lt; '\n'; std::cout &lt;&lt; "\tremainder = " &lt;&lt; remainder &lt;&lt; '\n'; if (check != dividend) { std::cout &lt;&lt; "\nERROR: " &lt;&lt; case_name &lt;&lt; " failure!\n\n"; } else { std::cout &lt;&lt; "\nPASS: " &lt;&lt; case_name &lt;&lt; " succeeded!\n\n"; } } int main() { // zero divisor //////////////////////////////////////////////////////////// iota::HugeInt dividend; iota::HugeInt divisor{"123456789098765432101234567890"}; check_division("zero dividend (1)", dividend, divisor); check_division("zero dividend (2)", dividend, -divisor); ///short division ////////////////////////////////////////////////////////// dividend = static_cast&lt;iota::HugeInt&gt;("31415926123456789098765432101234567890987654321"); divisor = (1ULL &lt;&lt; 32) - 1LL; check_division("short division (1)", dividend, divisor); check_division("short division (2)", dividend, -divisor); check_division("short division (3)", -dividend, divisor); check_division("short division (4)", -dividend, -divisor); // long division /////////////////////////////////////////////////////////// dividend = static_cast&lt;iota::HugeInt&gt;("314159261234567890987654321012345678909876543210987657878726353557575751098"); divisor = static_cast&lt;iota::HugeInt&gt;("9086565656538783989846661928745638291028749009092778710909291"); check_division("long division (1)", dividend, divisor); check_division("long division (2)", dividend, -divisor); check_division("long division (3)", -dividend, divisor); check_division("long division (4)", -dividend, -divisor); // some fun (use a wide terminal) ////////////////////////////////////////// dividend = factorial_iterative(1000LL); divisor = fibonacci_iterative(10000LL); check_division("fun 1 division (1)", dividend, divisor); check_division("fun 1 division (2)", dividend, -divisor); check_division("fun 1 division (3)", -dividend, divisor); check_division("fun 1 division (4)", -dividend, -divisor); // some more fun dividend = factorial_iterative(1100LL); divisor = fibonacci_iterative(13000LL); check_division("fun 2 division (1)", dividend, divisor); check_division("fun 2 division (2)", dividend, -divisor); check_division("fun 2 division (3)", -dividend, divisor); check_division("fun 2 division (4)", -dividend, -divisor); // fermat test: This choice of dividend and divisor turns out to be a (very) // rare case where we have to correct for an over-borrow in unsigned_divide // by decrementing qhat and giving divisor to the remainder. dividend = fermat_number(9LL); divisor = static_cast&lt;iota::HugeInt&gt;("7455602825647884208337395736200454000000170665201"); check_division("special case", dividend, divisor); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T15:59:14.600", "Id": "466179", "Score": "1", "body": "Sorry I don't have time to review right now, but one quick observation: it may be a good idea to provide a `divmod()` function that returns a tuple `{quotient,remainder}` in a single operation, for code that needs both values. That can save repeating the calculation. It's probably just a thin wrapper around `unsigned_divide` as `/` and `%` are." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T16:15:09.417", "Id": "466181", "Score": "0", "body": "Agreed. I was just thinking about this while doing some mind-numbing testing. Thanks!" } ]
[ { "body": "<h1>About the comments</h1>\n\n<p>Some of the comments in your code are very nice. For example, when explaining the different cases in <code>unsigned_divide()</code>. However, avoid comments that are just literal repetitions of the code just below. There are some borderline cases of that in your code, such as:</p>\n\n<pre><code>// Accept and store the tentative quotient digit.\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>// Prepend a (m+1)'th zero-value digit to the dividend, then shift.\n</code></pre>\n\n<p>Also, if a block of code can be replaced by a call to a function with a descriptive name, that can then avoid needing a comment.</p>\n\n<h1>Add a description to <code>@param</code> and <code>@return</code> values</h1>\n\n<p>It takes little effort to write an actual description for the parameters and return value in the Doxygen comments, and it will make the resulting documentation better. For example, in the documentation for <code>operator/</code>, write:</p>\n\n<pre><code> * @param a Left hand side of the division.\n * @param b Right hand side of the division.\n * @return Returns a / b.\n</code></pre>\n\n<p>Also remember to document all parameters, for example I se no <code>@param remainder</code> in the documentation of <code>unsigned_divide()</code>. You can turn on warnings in Doxygen, so it will tell you if you forgot to document all parameters of each function for example.</p>\n\n<h1>Consider splitting off parts of <code>unsigned_divide()</code> into separate functions</h1>\n\n<p>This function is quite long, and could perhaps be split into separate functions.\nFor example, the three cases could be separated, and in the third case, the actual long division algorithm could be put into its own function as well.</p>\n\n<h1>Consider adding a user-defined literal operator</h1>\n\n<p>You could add a <a href=\"https://en.cppreference.com/w/cpp/language/user_literal\" rel=\"nofollow noreferrer\">user-defined literal</a> operator that just wraps the conversion constructor, so it becomes easy to write a literal <code>HugeInt</code> in code that uses this class. For example:</p>\n\n<pre><code>HugeInt operator \"\" _huge(unsigned long long value) {\n return HugeInt(value);\n}\n\nHugeInt operator \"\" _huge(const char *text) {\n return HugeInt(text);\n}\n</code></pre>\n\n<p>And then you could write:</p>\n\n<pre><code>HugeInt the_answer = 6_huge * \"7\"_huge;\n</code></pre>\n\n<h1>Consider using <code>std::vector&lt;uint32_t&gt;</code> to store the digits</h1>\n\n<p>One issue I see with this class, which will impact performance as well, is that you allocate a static array of 1200 bytes to hold the digits. This wastes a lot of memory for smaller numbers, and will obviously fail when the numbers grow large enough to exceed this size.</p>\n\n<p>There are several reasons why this can have negative effect on performance, even though it seems at first that a static array has none of the overhead of a <code>std::vector</code>. However, if you have many <code>HugeInt</code>s (maybe you have an array of them), you are using a lot of memory that has to be paged in. Also, stack space could be limited, and when doing calculations it's quite normal to have several variables on the stack, so just having 4 <code>HugeInt</code>s would already consume 2 pages. This becomes a real problem when you have some recursive algorithm: the total stack usage is then the deepest recursion level times the memory used by a single iteration.</p>\n\n<p>The large size can also negatively impact memory layout, making it harder for the CPU's caches and prefetcher. Consider a function that starts with:</p>\n\n<pre><code>void somefunc(...) {\n int x;\n HugeInt y;\n int z;\n ...\n</code></pre>\n\n<p>There is likely a huge gap between <code>z</code> and <code>x</code> in the above code fragment.</p>\n\n<p>I think it's likely in real use cases that a significant fraction of <code>HugeInt</code>s will actually only hold small values. It might be worthwhile to investigate if some kind of vector container with <a href=\"https://stackoverflow.com/questions/2178281/small-string-optimization-for-vector\">small size optimization</a> could be used. This would keep small <code>HugeInt</code>s fast, and for the large ones, the time taken by operations on them will dwarf the performance loss of the indirection of a dynamic allocation of the digits.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T09:02:28.213", "Id": "466254", "Score": "0", "body": "Thank you for your comprehensive and encouraging review with many good ideas. I shall respond in more detail when I have looked more carefully at your suggestions. Regarding the use of int arrays versus std::vector, the HugeInt size is fixed, so that it is easy to implement radix complement signed arithmetic. I made the conscious decision not to use a standard container for performance reasons. I do understand your argument and thank you for the idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T09:44:19.337", "Id": "466257", "Score": "0", "body": "Just a quick follow up. Thank you for your excellent idea of suggesting a literal operator. I wasn't aware of this, which has been available since C++ 11, I think. I shall definitely make those changes and make all the constructors explicit. A very valuable suggestion -- thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T11:31:21.940", "Id": "466271", "Score": "0", "body": "You could still use a variable size container to store the digits, and keep using radix complement signed arithmetic. You just have to perform [sign-extension](https://en.wikipedia.org/wiki/Sign_extension) when increasing the size of the vector." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T12:57:47.847", "Id": "466353", "Score": "0", "body": "Thanks for the pointer on sign extension. I shall look into this on my next iteration." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T23:10:13.083", "Id": "237725", "ParentId": "237704", "Score": "4" } } ]
{ "AcceptedAnswerId": "237725", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T15:09:53.267", "Id": "237704", "Score": "5", "Tags": [ "c++", "integer" ], "Title": "HugeInt division using base 2^32 implementation" }
237704
<p>After running my C-brute-forcer for two days on a 25x25 sudoku, I decided to re-write in Java so that it would solve it in an acceptable time frame. The idea: Make smart fields that contain all possible values for that field, and then let the bute-forcer only loop through these, hopefully reducing the time.</p> <p>After some head-scratching, I came up with this:</p> <p>Main:</p> <pre><code>import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class SudokuMain { public static void main(String[] args) { String[] dims = null; String fields = null; File file = new File("./io/sudoku6"); try (BufferedReader buf = new BufferedReader(new FileReader(file))) { dims = buf.readLine().split(" "); fields = buf.readLine(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } if (dims.length != 3) { throw new IllegalArgumentException("Invalid info header!"); } int w = Integer.parseInt(dims[0]); int h = Integer.parseInt(dims[1]); int size = Integer.parseInt(dims[2]); if (fields.length() != size * size * 2) { throw new IllegalArgumentException( String.format("Invalid sudoku! Expected length %s, got %s.\n", size * size * 2, fields.length())); } Sudoku sudoku = new Sudoku(w, h, size, fields); SudokuSolver.solve(sudoku); } } </code></pre> <p>Sudoku:</p> <pre><code> public class Sudoku { private Field fields[]; public int fWidth, fHeight, size; public Sudoku(int w, int h, int size, String raw) { this.fWidth = w; this.fHeight = h; this.size = size; fields = new Field[size * size]; try { for (int i = 0; i &lt; size * size; i++) { int num = Integer.parseInt(raw.substring(0, 2)); fields[i] = new Field(num, size); raw = raw.substring(2); } } catch (NumberFormatException e) { throw new IllegalArgumentException("Sudoku contains non-number characters!"); } } public Field getFieldAt(int x, int y) { return fields[y * size + x]; } public int getValueAt(int x, int y) { return fields[y * size + x].value; } public void setValueAt(int x, int y, int val) { fields[y * size + x].value = val; } private int[] getRow(int row) { int[] res = new int[size]; for (int i = 0; i &lt; size; i++) { res[i] = fields[i + row * size].value; } return res; } private int[] getCol(int col) { int[] res = new int[size]; for (int i = 0; i &lt; size; i++) { res[i] = fields[col + i * size].value; } return res; } public boolean isValid() { for (int y = 0; y &lt; this.size; y++) { int[] values = new int[size + 1]; for (int i : this.getRow(y)) { if (values[i] != 0) { return false; } else { values[i] = i; } } } for (int x = 0; x &lt; this.size; x++) { int[] values = new int[size + 1]; for (int i : this.getCol(x)) { if (values[i] != 0) { return false; } else { values[i] = i; } } } for (int yf = 0; yf &lt; this.size; yf+=fHeight) { for (int xf = 0; xf &lt; this.size; xf+=fWidth) { int[] values = new int[size + 1]; for (int i : this.getBox(xf, yf)) { if (values[i] != 0) { return false; } else { values[i] = i; } } } } return true; } private int[] getBox(int xf, int yf) { int[] res = new int[size]; int i = 0; for (int y = 0; y &lt; fHeight; y++) { for (int x = 0; x &lt; fWidth; x++) { res[i] = fields[(y + yf) * size + (x+xf)].value; i++; } } return res; } public void print() { for (int a = 0; a &lt; size * 3 + (size / fWidth) + 1; a++) { System.out.print('-'); } System.out.println(); for (int j = 0; j &lt; size; j++) { for (int i = 0; i &lt; size; i++) { if (i % fWidth == 0) { System.out.print('|'); } System.out.printf("%3d", fields[j * size + i].value); } System.out.print('|'); System.out.println(); if (j % fHeight == fHeight - 1) { for (int a = 0; a &lt; (size * 3) + (size / fWidth) + 1; a++) { System.out.print('-'); } System.out.println(); } } System.out.println(); } } </code></pre> <p>Field:</p> <pre><code>public class Field { public int value; private int possible[]; public Field(int val, int size) { this.value = val; possible = new int[size + 1]; for (int i = 0; i &lt;= size; i++) { possible[i] = i; } } public void removePossible(int[] nums) { for (int num : nums) possible[num] = 0; } public int setIfOnePossible() { if (value != 0) { return 0; } int found = -1; for (int i = 1; i &lt; possible.length; i++) { if (possible[i] != 0) { if (found == -1) { found = i; } else { return 0; } } } this.value = found; return 1; } public boolean isPossible(int n) { return possible[n] != 0; } public int countPossible() { int res = 0; if (value != 0) { return 0; } for (int i : possible) { if (i != 0) { res++; } } return res; } } </code></pre> <p>SudokuSolver:</p> <pre><code>public class SudokuSolver { private static int tries; public static void solve(Sudoku s) { s.print(); long then = System.currentTimeMillis(); presolve(s); if (recsolve(s) &amp;&amp; s.isValid()) { s.print(); long mstime = System.currentTimeMillis() - then; int min = (int) (mstime / 1000 / 60 % 60); int sec = (int) (mstime / 1000 % 60); long ms = mstime - (min * 60 * 1000) - (sec * 1000); System.out.printf("Took %d min, %d s, %d ms\n", min, sec, ms); System.out.printf("%d tries.\n", tries); } } private static boolean recsolve(Sudoku s) { for (int y = 0; y &lt; s.size; y++) { for (int x = 0; x &lt; s.size; x++) { Field f = s.getFieldAt(x, y); if (f.value == 0) { for (int n = 1; n &lt;= s.size; n++) { if (f.isPossible(n)) { tries++; s.setValueAt(x, y, n); if (s.isValid() &amp;&amp; recsolve(s)) { return true; } } } s.setValueAt(x, y, 0); return false; } } } return true; } private static void presolve(Sudoku s) { int possBefore = 0; for (int y = 0; y &lt; s.size; y++) { for (int x = 0; x &lt; s.size; x++) { possBefore += s.getFieldAt(x, y).countPossible(); } } int set = 0; do { for (int y = 0; y &lt; s.size; y++) { int[] found = new int[s.size + 1]; for (int x = 0; x &lt; s.size; x++) { int value = s.getValueAt(x, y); found[value] = value; } for (int i = 0; i &lt; s.size; i++) { s.getFieldAt(i, y).removePossible(found); } } for (int x = 0; x &lt; s.size; x++) { int[] found = new int[s.size + 1]; for (int y = 0; y &lt; s.size; y++) { int value = s.getValueAt(x, y); found[value] = value; } for (int i = 0; i &lt; s.size; i++) { s.getFieldAt(x, i).removePossible(found); } } for (int yf = 0; yf &lt; s.size; yf += s.fHeight) { for (int xf = 0; xf &lt; s.size; xf += s.fWidth) { int[] found = new int[s.size + 1]; for (int y = 0; y &lt; s.fHeight; y++) { for (int x = 0; x &lt; s.fWidth; x++) { int value = s.getValueAt(xf + x, yf + y); found[value] = value; } } for (int y = 0; y &lt; s.fHeight; y++) { for (int x = 0; x &lt; s.fWidth; x++) { s.getFieldAt(xf + x, yf + y).removePossible(found); } } } } set = 0; for (int y = 0; y &lt; s.size; y++) { for (int x = 0; x &lt; s.size; x++) { set += s.getFieldAt(x, y).setIfOnePossible(); } } } while (set != 0); int possAfter = 0; for (int y = 0; y &lt; s.size; y++) { for (int x = 0; x &lt; s.size; x++) { possAfter += s.getFieldAt(x, y).countPossible(); } } System.out.printf("Excluded %s possible values for fields. (before %s, now %s)\n", possBefore - possAfter, possBefore, possAfter); } } </code></pre> <p>This happens to be >5 seconds faster than the C program on a 12x12 sudoku like this one:</p> <pre><code>4 3 12 000000000001000000000312030001000000121006000000000002120403000000000700001000081200000007000600000705000002000300000400000000090000000711030010050009110700000002000000000600000200010000051200001200020000000408001100000200000000070803110000000000030912000000040002100400000000030000000000 </code></pre> <p>(I haven't tested the 25x25 yet.)</p> <p>EDIT: Removed two test-cases</p>
[]
[ { "body": "<p>Your <code>recsolve</code> method changes a value in the grid, then validates the entire puzzle, recursing if it's valid or aborting if that change broke the puzzle. However, changing one number only impacts three things. The column/row for the value that's been changed and the box that contains it. A change to the top left box isn't going to impact if the bottom right box is valid, so there's not point testing it. Providing an overload of the <code>isValid</code> method that takes in the coodinates of the changed cell can result in a significant speed improvement.</p>\n\n<p>The recursive call in <code>recsolve</code> becomes:</p>\n\n<pre><code>if (s.isValid(x,y) &amp;&amp; recsolve(s)) {\n</code></pre>\n\n<p>And <code>isValid</code> would look something like:</p>\n\n<pre><code>public boolean isValid(int changedX, int changedY) {\n int boxChangedX = changedX - changedX % fWidth;\n int boxChangedY = changedY - changedY % fHeight;\n\n return isValidSet(getRow(changedY))\n &amp;&amp; isValidSet(getCol(changedX))\n &amp;&amp; isValidSet(getBox(boxChangedX, boxChangedY));\n}\n</code></pre>\n\n<p>Note, I've extracted a common function, which checks if the values returned from <code>getRow</code>, <code>getCol</code> or <code>getBox</code> contain a valid set of values..</p>\n\n<pre><code>private boolean isValidSet(int[] knownData) {\n int[] values = new int[size + 1];\n for (int i : knownData) {\n if (values[i] != 0) {\n return false;\n }\n values[i] = i;\n }\n return true;\n}\n</code></pre>\n\n<p><strong>Other thoughts</strong></p>\n\n<ul>\n<li>Give parameter variables descriptive names, they're often expanded by intellisense... <code>Sudoku(int w, int h, int size, String raw)</code>, <code>w</code> could be <code>width</code>. Variable naming in general could be more expressive.</li>\n<li>We don't tend to prefix <code>this.</code> unless there's a name clash, so just <code>fWidth = w;</code> is fine...</li>\n<li><p>When an <code>if</code> always returns, you don't need to have an <code>else</code>. So, rather than:</p>\n\n<blockquote>\n<pre><code>if (values[i] != 0) {\n return false;\n} else {\n values[i] = i;\n}\n</code></pre>\n</blockquote>\n\n<p>Prefer:</p>\n\n<pre><code>if (values[i] != 0) {\n return false;\n}\nvalues[i] = i;\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T13:55:08.783", "Id": "237836", "ParentId": "237706", "Score": "2" } }, { "body": "<p>This code looks largely OK to me. I've written a Sudoku resolver myself, mainly to test my coding skills on the then new Collection framework (which again, shows my age).</p>\n\n<p>A few remarks then:</p>\n\n<ul>\n<li>The rows, columns and blocks can be seen as \"groups\". That way it would even be possible to allow Sudoku's with different or additional groups.</li>\n<li>I don't know the speed of my Sudoku for 12 x 12, but I do know that it ran in 0.2 seconds on my dual core core 2 based IBM cheapo thinkpad for 9 x 9. And that was basically the startup time of the VM.</li>\n<li>I used a two step guessing -> simple reduction of possible values for each \"group\", and then taking a guess. So if possible I would run <code>presolve</code> not only at the start, but also after each guess. There are many tricks that can be used to be able to \"guess\" better, but most of them seem to slow down the guessing really (I played fair and looked up the tricks after getting it running).</li>\n</ul>\n\n<p>As for the code:</p>\n\n<ul>\n<li><p>the parameters of the Sudoku <code>w</code>, <code>h</code>, <code>size</code> / <code>fields</code> all seem related. Only use those that are really required. Isn't <code>size = w * h</code>?</p></li>\n<li><p>The Field class is a bit weird. It has a special field for <code>value</code> and it is unclear if that is needed. It uses <code>0</code> as special value. For such a special value I would use a constant (e.g. <code>NOT_POSSIBLE = 0</code>) and document the use. Furthermore, it seems to rely on external calls to <code>setIfOnePossible</code> to get into the next valid state. I can remember I used <code>Set&lt;Integer&gt;</code> instead, with no significant issues (but then, my goal was to test the collection classes). <code>setIfOnePossible</code> returns a value, but that's not clear from the name.</p></li>\n<li><code>public boolean isValid()</code> has side effects. A method that is called <code>isValid</code> should not contain any side effects, so it is really important that you rename the method.</li>\n<li><code>raw = raw.substring(2)</code> generally we frown upon using <code>substring</code> in loops. What about <a href=\"https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/Integer.html#parseInt(java.lang.CharSequence,int,int,int)\" rel=\"nofollow noreferrer\">the longer <code>parseInt</code></a> method or a regular expression using <code>Matcher.find()</code>?</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-27T18:35:47.390", "Id": "238057", "ParentId": "237706", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T15:21:05.893", "Id": "237706", "Score": "2", "Tags": [ "java", "performance", "recursion", "sudoku" ], "Title": "\"Smart\" sudoku brute-forcer" }
237706
<p>This part of my code is taking 30 minutes to multiple 300 RGB and Depth images pixel by pixel. How can I reduce this time? This is just a part of big code but this taking lot of time.</p> <pre><code>def depth_to_xyz_and_rgb(uu, vv, dep): # t1.tic() # get z value in meters pcz = dep.getpixel((uu, vv)) if pcz == 60: return pcx = (uu - cx_d) * pcz / fx_d pcy = ((vv - cy_d) * pcz / fy_d) # apply extrinsic calibration P3D = np.array([pcx, pcy, pcz]) P3Dp = np.dot(RR, P3D) - TT # rgb indexes that P3D should match uup = (P3Dp[0] * fx_rgb / P3Dp[2] + cx_rgb) vvp = (P3Dp[1] * fy_rgb / P3Dp[2] + cy_rgb) # t1.toc() # return a point in point cloud and its corresponding color indices return P3D, uup, vvp </code></pre> <p>Sample images.</p> <p><a href="https://i.stack.imgur.com/j9ZYS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j9ZYS.png" alt="Color_image"></a> <a href="https://i.stack.imgur.com/V853H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V853H.png" alt="Depth_image"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T17:27:32.140", "Id": "466187", "Score": "1", "body": "For code review you want to post all the code. For a question on time issue with your code maybe you want to post on Stack Overflow instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T18:25:51.673", "Id": "466193", "Score": "2", "body": "What version of python is this written in? Can you also fix your indentation, as the `return` statement is outside the function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-26T07:49:32.877", "Id": "466672", "Score": "0", "body": "With the current indentation the code doesn't make sense. Please fix the indentation and, while you're at it, consider posting a bigger part of the code to make it easier on the reviewers. Can you tell us more about the variables used as well? Those variable names probably make sense to you, but less so for everyone else reading them. Can you share the expected output of 1 of the sample images?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T16:01:30.533", "Id": "237707", "Score": "1", "Tags": [ "python", "performance", "matrix" ], "Title": "Reduction of time for matrix multiplication of pixels" }
237707
<p>I have started programming a couple of months ago and have recently applied for an internship. One of the assignments was to create a console application, the assignment can be seen here - > <a href="https://drive.google.com/open?id=1h6x_SzF4wmIBJwleoa1ND9CQzGbARiz5" rel="nofollow noreferrer">HERE</a></p> <p>My implementation is this:</p> <p>I have created an abstract class called DiscountCard which holds all the info, getters and setters, and has one abstract method of calculateDiscountRate.</p> <pre><code>public abstract class DiscountCard { private String owner; private int turnover; private int purchaseValue; private double discountRate; public DiscountCard(int turnOver, int purchaseValue){ setTurnover(turnOver); setPurchaseValue(purchaseValue); } abstract void calculateDiscountRate(); public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public int getTurnover() { return turnover; } public void setTurnover(int turnOver) { if(turnOver&gt;=0) { this.turnover = turnOver; }else{ System.out.println("Turnover can't be less than 0."); } } public int getPurchaseValue() { return purchaseValue; } public void setPurchaseValue(int purchaseValue) { if(purchaseValue&gt;=0) { this.purchaseValue = purchaseValue; }else{ System.out.println("Purchase value can't be less than 0."); } } public void setDiscountRate(double discountRate) { this.discountRate = discountRate; } public double getDiscountRate() { return discountRate; } } </code></pre> <p>Then, there are 3 Card classes (Bronze,Silver,Gold) which implement the above class and override its abstract method:</p> <pre><code> package com.test.DiscountCards; public class GoldDiscountCard extends DiscountCard { public GoldDiscountCard(int turnOver, int purchaseValue){ super(turnOver,purchaseValue); calculateDiscountRate(); } @Override void calculateDiscountRate() { setDiscountRate(2); setDiscountRate(getTurnover()/100 + getDiscountRate()); if(getDiscountRate()&gt;10){ setDiscountRate(10); } } } </code></pre> <p>Next is the StoreCalculator Class which takes an instance of DiscountCard class and calculates the discount and total.</p> <pre><code>package com.test; import com.practice.DiscountCards.DiscountCard; public class StoreCalculator { private DiscountCard discountCard; public StoreCalculator(DiscountCard discountCard){ this.discountCard = discountCard; } public double calculateDiscount(){ return discountCard.getPurchaseValue() * discountCard.getDiscountRate()/100; } public double calculateTotal(){ return discountCard.getPurchaseValue() - calculateDiscount(); } } </code></pre> <p>And at last i have a class that takes the info from DiscountCard class and Calculator class and prints it to a console.</p> <pre><code>import com.test.DiscountCards.DiscountCard; public class PayDesk { public static void print(DiscountCard discountCard){ StoreCalculator calculator = new StoreCalculator(discountCard); System.out.println("Purchase value: $"+ discountCard.getPurchaseValue() ); System.out.println("Discount rate: "+ discountCard.getDiscountRate()+"%" ); System.out.println("Discount: $"+ calculator.calculateDiscount() ); System.out.println("Total: $"+ calculator.calculateTotal()); } } </code></pre> <p>My question is if this code implements OOP and is there something i should improve. I have send this code for a review to a company, i just want to know if there can be an improvement so i can learn more.</p>
[]
[ { "body": "<p>The OO part seems to be OK when it comes to the type inheritance and the choice of an abstract class.</p>\n\n<h1>Code review.</h1>\n\n<h2>For the abstract class</h2>\n\n<pre><code>public DiscountCard(int turnOver, int purchaseValue){\n</code></pre>\n\n<p>This is a public constructor for a class that cannot be instantiated, consider <code>protected</code> instead. It also contains a <code>turnOver</code>, but that's specific to an owner it seems to me. So that doesn't make sense without the <code>owner</code> string. Similarly, I don't think the card is <em>specific to one particular purchase</em>. The card is applied on a particular purchase.</p>\n\n<pre><code> setTurnover(turnOver);\n setPurchaseValue(purchaseValue);\n</code></pre>\n\n<p>Generally you'd set the fields directly, instead of calling the public methods. Calling methods can be dangerous, especially if they can be overridden.</p>\n\n<pre><code>abstract void calculateDiscountRate();\n</code></pre>\n\n<p>For what? That depends on <code>purchaseValue</code> but that should not depend on any class fields, as already established.</p>\n\n<pre><code>public String getOwner() {\n return owner;\n}\n</code></pre>\n\n<p>Here you make a classic mistake: never leave your objects in an invalid state. As the owner may not be set, this method could return <code>null</code>.</p>\n\n<pre><code>public void setOwner(String owner) {\n this.owner = owner;\n}\n</code></pre>\n\n<p>No. If the <strong>holder</strong> of the card can change then this would be in the model, and I don't see that. Generally cards are <strong>personalized</strong> and are therefore not transferable (at least from the payment desk's point of view).</p>\n\n<pre><code>public void setTurnover(int turnOver) {\n if(turnOver&gt;=0) {\n this.turnover = turnOver;\n }else{\n System.out.println(\"Turnover can't be less than 0.\");\n }\n}\n</code></pre>\n\n<p>The turnover may actually be negative if the customer decided to return. In this kind of situations it is important to perform a reality check: what could happen. Furthermore, I guess that this should be called after each period of time (it's for the \"previous month\" according to the instructions. So call it, say, <code>setTurnoverOfLastMonth()</code> or something similar.</p>\n\n<pre><code>public void setDiscountRate(double discountRate) {\n this.discountRate = discountRate;\n}\n</code></pre>\n\n<p>Is that really a public call, you override the discount rate? Seems to me that you'd have to switch cards for that.</p>\n\n<h2>For the gold card:</h2>\n\n<pre><code>calculateDiscountRate();\n</code></pre>\n\n<p>By now you should have noticed that there are more rates possible, you are still trying to get along with one.</p>\n\n<pre><code>setDiscountRate(2);\n\nsetDiscountRate(getTurnover()/100 + getDiscountRate());\n</code></pre>\n\n<p>And you aren't just overwriting the single discount rate in the second call?</p>\n\n<pre><code>if(getDiscountRate()&gt;10){\n setDiscountRate(10);\n}\n</code></pre>\n\n<p>Leukoplast patching ain't gonna help, son.</p>\n\n<h2>For the store calculator</h2>\n\n<p>Where are the purchases? In the card?</p>\n\n<p>I'd expect something like:</p>\n\n<pre><code>public Payment calculateResult(double purchaseValue);\n</code></pre>\n\n<p>Where the <code>Payment</code> contains all the details (card used, discount percentage, discount value and of course the final price).</p>\n\n<p>Note too that the examples have a purchase value with <code>.00</code> behind it. Somehow that indicates to me that every cent is appreciated (and you store as an <code>int</code> - which is actually fine <strong>if it means cents</strong>). </p>\n\n<h2>For the PayDesk</h2>\n\n<p>Just prints out stuff. Maybe correct, maybe it isn't, but just printing the bill is not what I was expecting. Probably can be merged with the <code>StoreCalculator</code> although I like the fact that you've created a separate calculator. That would certainly be a good idea for a more complicated <code>PayDesk</code> class.</p>\n\n<hr>\n\n<p>Beware: it says in your requirements: \"create instances with sample data as shown in Example outputs section;\"</p>\n\n<p>Now I don't personally think that the purchase should ever be part of the card data, but if it is stated this way I'd almost include it myself as a field.</p>\n\n<hr>\n\n<p>Very non-nerdy of me, but I'd include a welcoming message for the card holder (Thank you for your purchase, ). Your GOLD CARD discount is: ... Etc... This would show your employer that you can act outside what is basic development.</p>\n\n<p>And probably I'd also welcome non-card holders to make a purchase.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T03:04:21.460", "Id": "466234", "Score": "0", "body": "Thanks a lot! Your answer is very helpful. One thing i am not sure i quite understand, about setting the DiscountRate. Should i set it directly in a constructor of a child card class and get rid of the setter?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T16:48:29.260", "Id": "466297", "Score": "0", "body": "I don't think you should talk about *one* discount rate if you read the assignment carefully. Any information that is required to *calculate* the discount rate should be set when it becomes available. But it is known for the different cards even *before* they are constructed, right? This information could just be codified or placed - preferably - in a constant or two - three - four." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T01:28:43.087", "Id": "237728", "ParentId": "237709", "Score": "4" } } ]
{ "AcceptedAnswerId": "237728", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T18:33:03.380", "Id": "237709", "Score": "3", "Tags": [ "java", "object-oriented", "console" ], "Title": "Discount card reduction calculator" }
237709
<p><a href="https://codereview.stackexchange.com/questions/237122/a-first-hangman-game-in-c/237139?noredirect=1#comment466136_237139">Here</a> I already asked for tips, and I wrote another hangman game with the tips I got.</p> <p>My questions are: is <code>int game()</code> doing too many things that I should split further into smaller functions?</p> <p>And how to avoid those nested while-loops? Or are they ok for what I intend (to make it possible to replay the game without executing it more than once)?</p> <p>The code:</p> <pre><code>/* Name of the program: Hangman Purpose of the program: This is a game. Who wrote this code and when: Jan Wollert, 20.02.2020 Version number: 2.0 Assumed user input: All lower case English characters */ #include &lt;iostream&gt; // required for outputting text on screen and for reading the user's input #include &lt;string&gt; // needed for string operations #include &lt;fstream&gt; // needed for checking if file exists; #include &lt;random&gt; // needed for a (pseudo)random word each time #include &lt;streambuf&gt; // needed for loading a file to a string #include &lt;limits&gt; // used for the "Press Enter to continue"-message #include&lt;bits/stdc++.h&gt; // needed for random word from a string #include &lt;utility&gt; // needed for a random word from a string const std::string version_number = "V2.0"; const std::string screen_clear_string = std::string (50, '\n'); // self explanatory void press_enter_to_continue() { std::cout &lt;&lt; "Press ENTER to continue... " &lt;&lt; std::flush; std::cin.ignore( std::numeric_limits &lt;std::streamsize&gt; ::max(), '\n' ); } // function that acts as a screen clear void screen_clear() { std::cout &lt;&lt; screen_clear_string; } // function that checks if a file exists bool fexists(std::string file_name) { std::ifstream ifile(file_name); return (bool)ifile; } // function that loads a file to a string std::string load_file_to_string(std::string file_name) { std::string string_from_file=""; if(fexists(file_name)) { std::ifstream t(file_name); t.seekg(0, std::ios::end); string_from_file.reserve(t.tellg()); t.seekg(0, std::ios::beg); string_from_file.assign((std::istreambuf_iterator&lt;char&gt;(t)), std::istreambuf_iterator&lt;char&gt;()); } else { string_from_file="1"; } return string_from_file; } // choosing a random line from a string std::string random_word_from_string(std::string input) { static auto gen = std::mt19937{std::random_device{}()}; std::string random_word=""; std::string word=""; std::stringstream iss(input); auto count = 0u; while (iss &gt;&gt; word) { if (std::uniform_int_distribution{0u,count++}(gen) == 0) { random_word = word; } } return random_word; } // function for determining if a char is in a string bool is_inside(const std::string &amp; str, char c) { return str.find(c) != std::string::npos; } // function for determining if a character is in the alphabet bool is_alpha(char c) { if (isalpha(c)==0) { return 1; } else { return 0; } } // game function int game() { std::string dictionary=load_file_to_string("wordlist.txt"); // check if the file opening has succeeded otherwise end the function if (dictionary=="1") { std::cout &lt;&lt; "Please make sure that wordlist.txt is in the same directory as this program!\n"; return 1; } std::cout &lt;&lt; screen_clear_string &lt;&lt; "Welcome to Hangman "&lt;&lt; version_number &lt;&lt; "!\n"; press_enter_to_continue(); screen_clear(); // initializing variables char another_game='y'; std::string secret_word=""; std::string guessed_word=""; std::string guessed_letters=""; char letter=' '; int fails=0; // replay the game with a different word if you want, that's why the while-loop while (another_game=='y') { // making the state clean after a finished game secret_word=random_word_from_string(dictionary); guessed_word=std::string(secret_word.length(),'_'); fails=0; guessed_letters=""; // the actual game while(guessed_word!=secret_word &amp;&amp; fails&lt;10) { screen_clear(); letter='_'; std::cout &lt;&lt; guessed_word &lt;&lt; "\n"; std::cout &lt;&lt; "Guess a letter.\n"; std::cout &lt;&lt; "Already guessed letters: " &lt;&lt; guessed_letters &lt;&lt; " Remaining tries: " &lt;&lt; 10-fails&lt;&lt; "\n"; while (!isalpha(letter) || is_inside(guessed_letters, letter) ) { std::cin &gt;&gt; letter; std::cin.clear(); std::cin.ignore( std::numeric_limits &lt;std::streamsize&gt; ::max(), '\n' ); } if(is_inside(secret_word,letter)) { for(unsigned int i=0; i&lt;secret_word.length(); ++i) { if (letter==secret_word.at(i)) { guessed_word.at(i)=letter; } } } else { guessed_letters+=letter; fails++; } } if(guessed_word==secret_word) { std::cout &lt;&lt; "Congratulations, the word was indeed " &lt;&lt; guessed_word &lt;&lt; "\n"; } else { std::cout &lt;&lt; "Sorry, you lose, the word was " &lt;&lt; secret_word &lt;&lt; "\n"; } std::cout &lt;&lt; "Another game? (y/n)\n"; std::cin &gt;&gt; another_game; } return 0; } int main() { game(); return 0; } </code></pre> <p>The wordlist.txt contains this words with this format:</p> <pre><code>wordone wordtwo wordthree wordn </code></pre> <p>This is compiled with <code>-std=c++17</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T19:49:49.347", "Id": "466203", "Score": "0", "body": "_\"And how to avoid those nested while-loops?\"_ `goto` maybe? Well, that's a joke ;-) Why do you believe these are bad?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T19:53:35.720", "Id": "466204", "Score": "0", "body": "@πάνταῥεῖ I read in a book that those generally produce troubles. BUT are neccessary sometimes, I just wonder if mine are neccessary or if it could be written better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T19:56:36.123", "Id": "466205", "Score": "2", "body": "_\"I read in a book that those generally produce troubles.\"_ That's nonsense. Nested loops aren't generally produce trobles. If these are needed, they are needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T19:59:06.267", "Id": "466206", "Score": "0", "body": "@πάνταῥεῖ ah, ok." } ]
[ { "body": "<h1>Splitting up <code>game()</code></h1>\n\n<blockquote>\n <p>My questions are: is <code>int game()</code> doing too many things that I should split further into smaller functions?</p>\n</blockquote>\n\n<p>You can definitely split up <code>game()</code> into more functions. There is no hard rule for when to split up a function. There are some rules of thumb, like if a function is more than one screen big or more than say 30 lines. However, the best way is to find blocks of code that are either very generic and could be reused elsewhere (you already do that with <code>press_enter_to_continue()</code> and <code>clear_screen()</code>), or blocks of code that can stand on their own. For example, most of the code inside the outer <code>while</code>-loop in <code>game()</code> deals with handling a single game of hangman. You could move it to its own function, so the <code>while</code>-loop is reduced to:</p>\n\n<pre><code>while (another_game == 'y')\n{\n do_one_game();\n\n std::cout &lt;&lt; \"Another game? (y/n)\\n\";\n std::cin &gt;&gt; another_game;\n}\n</code></pre>\n\n<p>This makes the function <code>game()</code> much smaller, and it is now much easier to see from a quick glance that it is repeating games until the user wants to stop.</p>\n\n<p>Another great candidate for getting its own function is the inner-most <code>while</code>-loop. It basically reads characters until you enter a letter that hasn't already been guessed. You could create a function for it like so:</p>\n\n<pre><code>char get_guess(const std::string &amp;guessed_letters)\n{\n char letter;\n\n do {\n std::cin &gt;&gt; letter;\n std::cin.clear();\n std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\\n');\n } while (!isalpha(letter) || is_inside(guessed_letters, letter));\n\n return letter;\n}\n</code></pre>\n\n<p>You could also create a function for filling in a guessed letter at the right places in the <code>guessed_word</code> string.</p>\n\n<h1>Avoiding nested loops</h1>\n\n<blockquote>\n <p>And how to avoid those nested while-loops? Or are they ok for what I intend (to make it possible to replay the game without executing it more than once)?</p>\n</blockquote>\n\n<p>There is nothing wrong with nesting loops. In many cases, it's the right thing to do. However, as shown above, in your case you can easily reduce one level of nesting by creating a function <code>do_one_game()</code> that contains all the code inside the outer loop,\nand another one by creating <code>get_guess()</code>.</p>\n\n<h1>Consider using <code>std::getline()</code> to read input</h1>\n\n<p>You are jumping through hoops to read single characters and then ignoring everything until a newline character. It might be simpler to use <code>[std::getline()</code>]<a href=\"https://en.cppreference.com/w/cpp/string/basic_string/getline\" rel=\"nofollow noreferrer\">1</a>; this function reads a whole line into a <code>std::string</code>. For example, you could then write:</p>\n\n<pre><code>std::string guess;\nstd::getline(std::cin, guess);\nletter = guess[0];\n</code></pre>\n\n<p>Note that if something happens to the input, <code>std::getline()</code> might return an empty string. It's always good to add some error checking to ensure you got valid input. With <code>std::getline()</code>, you can do it like so:</p>\n\n<pre><code>if (!std::getline(std::cin, guess))\n{\n // handle error here\n}\n</code></pre>\n\n<h1>Use C++17's <code>std::filesystem</code> if possible</h1>\n\n<p>C++17 introduced the <a href=\"https://en.cppreference.com/w/cpp/filesystem\" rel=\"nofollow noreferrer\">filesystem library</a> that makes it easier to perform operations on files and directories. In order to check if a file exists, you can use <a href=\"https://en.cppreference.com/w/cpp/filesystem/exists\" rel=\"nofollow noreferrer\"><code>std::filesystem::exists(file_name)</code></a>.</p>\n\n<p>However, your function <code>fexists()</code> is not necessary at all. It opens a file, and if it succeeds you open it again. That is rather silly. Why not just unconditionally open the file in <code>load_file_to_string()</code>, and do the error checking there? It would look like:</p>\n\n<pre><code>std::ifstream t(file_name);\n\nif (t.good())\n{\n // read file here\n}\n</code></pre>\n\n<p>Also note that checking whether a file exists is no guarantee that you can actually succesfully read the whole file. In general you should check that the state of the <code>std::ifstream</code> is still OK after reading the contents of the file.</p>\n\n<h1>Don't write useless functions</h1>\n\n<p>You wrote <code>is_alpha()</code>, which just calls <code>isalpha(c)</code> and returns its result. You are not using this function at all, and even if you did, you could just have called <code>isalpha()</code> instead. You should remove this function.</p>\n\n<h1>Use exceptions or explicit error codes to return errors from functions</h1>\n\n<p>Your function <code>load_file_to_string()</code> returns the string <code>\"1\"</code> if it couldn't find the file. However, you could actually create a file <code>wordlist.txt</code> that just contains the text <code>\"1\"</code>. You would still get the error message in this case, which would not be correct. Avoid situations like this where you can have confusion between valid and invalid return values.</p>\n\n<p>Either use exceptions to return an error, like so:</p>\n\n<pre><code>#include &lt;stdexcept&gt;\n\nstd::string load_file_to_string(const std::string &amp;filename)\n{\n ...\n if (error)\n {\n throw std::runtime_error(\"Could not open wordlist file\");\n }\n}\n</code></pre>\n\n<p>Or make sure the function has clearly separated return values for the string and the error status. One option would be to just return a <code>bool</code> to indicate the status, and pass a non-const reference to the string to be filled in with the word list:</p>\n\n<pre><code>bool load_file_to_string(const std::string &amp;filename, std::string &amp;string_from_file)\n{\n ...\n if (error)\n {\n return false;\n }\n ...\n return true;\n}\n</code></pre>\n\n<p>Or use <a href=\"https://en.cppreference.com/w/cpp/utility/optional\" rel=\"nofollow noreferrer\"><code>std::optional</code></a> to combine the information into a single return value:</p>\n\n<pre><code>#include &lt;optional&gt;\n\nstd::optional&lt;std::string&gt; load_file_to_string(const std::string &amp;filename)\n{\n ...\n if (error)\n {\n return {};\n }\n ...\n return string_from_file;\n}\n</code></pre>\n\n<p>And this is how you use the latter:</p>\n\n<pre><code>auto dictionary = load_file_to_string(\"wordlist.txt\");\n\nif (!dictionary)\n{\n std::cerr &lt;&lt; \"Please make sure that wordlist.txt is in the same directory as this program!\\n\";\n return 1;\n}\n...\nsecret_word = random_word_from_string(*dictionary);\n</code></pre>\n\n<h1>Use consistent code formatting</h1>\n\n<p>You are not very consistent in formatting your source code; sometimes there are spaces around operators and between <code>if</code> and <code>(</code>, sometimes not. I recommend always adding the spaces; it makes the code easier to read. This is a matter of taste, however it is always good to be at least consistent. You don't have to go over the code yourself and correct every small issue: there are code formatting tools that can do it for you. Perhaps the editor you are using to write the source code can already do it, otherwise there are <a href=\"https://stackoverflow.com/questions/841075/best-c-code-formatter-beautifier\">stand-alone code formatters</a> you can use.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T22:11:02.317", "Id": "237724", "ParentId": "237716", "Score": "3" } } ]
{ "AcceptedAnswerId": "237724", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T19:45:54.330", "Id": "237716", "Score": "1", "Tags": [ "c++", "c++17", "hangman" ], "Title": "My second hangman game (Hangman in C++), how to avoid nested while-loops? How to stick to the SRP?" }
237716
<p>I am trying to identify and print pairs of 4 digit palindromes that sum up to a 5 digit palindrome. </p> <p>This is what I have so far</p> <pre class="lang-py prettyprint-override"><code>def isPalindrome(x): return str(x)==str(x)[::-1] palindrome = [x for x in range(1000, 10000) if isPalindrome(x)] for x in palindrome: for y in palindrome: if (9999 &lt; x+y &lt; 100000) and isPalindrome(x+y): print(x, y, x+y) </code></pre> <p>I am estimating the time complexity for this to be O(n^2),because I am traversing the list twice. Is it possible to improve on this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T16:38:25.370", "Id": "466295", "Score": "0", "body": "Welcome to code review where we review working code and provide tips on how to improve that code. Is this code working as expected? When you say `This is what I have so far` it indicates that the code is not complete and therefore off-topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T16:52:21.197", "Id": "466301", "Score": "0", "body": "The code is functional. But I don't think it is as efficient as it could be." } ]
[ { "body": "<p>Two opportunities for optimization that suggest themselves to me:</p>\n\n<ol>\n<li><p>Seems like you should be able to produce an exhaustive list of 4-digit palindromes by taking every 2-digit number and then appending its mirror to it, rather than having to iterate through every 4-digit number and throw most of them out. That would let you build your palindrome list in about one-hundredth the time (you'll be iterating over 90 two-digit numbers instead of 9000 four-digit numbers in that first loop).</p></li>\n<li><p>A lot of the sums you're checking will be too small (i.e. they'll be 4 digits); none will be too big (9999+9999=19998). You can minimize the work you do on those sums by iterating from largest to smallest and breaking the inner loop once the sum gets too small.</p></li>\n</ol>\n\n<p>An alternative to the nested for loops would be using one of the <code>itertools</code> functions to generate all the combinations as a set of tuples, but I don't <em>think</em> that'd get you any performance wins.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T21:13:11.500", "Id": "466216", "Score": "1", "body": "so something like `palindrome = [int(str(x)+str(x)[::-1] for x in range(10,99)]` to generate the list of palindromes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T21:23:42.710", "Id": "466219", "Score": "0", "body": "`range(10,100)` I think, but yarp" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T21:26:06.657", "Id": "466220", "Score": "0", "body": "For replacing nested for loops, i tried it with `iter = itertools.combinations_with_replacement(palindrome, 2)` but looping through it`for x,y in iter:` I get half the number of results as before. Am I missing something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T23:42:29.360", "Id": "466225", "Score": "0", "body": "Are the ones you're missing flipped versions of ones you already have?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T16:51:22.650", "Id": "466299", "Score": "0", "body": "That's possibly what's happening. Thank you for pointing me in the right direction" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T21:03:07.240", "Id": "237720", "ParentId": "237717", "Score": "3" } }, { "body": "<p>Instead of using the <em>isPalindrome</em> function to determine if x + y is a length five palindrome, you can create the set of all length five palindromes in the range [10000, 20000) and check for set membership instead. Use the efficient method suggested by Sam Stafford to generate them.</p>\n\n<p>This does not change the time complexity, but should be faster.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T15:06:48.763", "Id": "237781", "ParentId": "237717", "Score": "3" } } ]
{ "AcceptedAnswerId": "237720", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T20:01:27.707", "Id": "237717", "Score": "0", "Tags": [ "python", "performance", "python-3.x", "complexity" ], "Title": "Python: Find pairs of numeric palindromes that sum up to another palindrome" }
237717
<p>I wrote a simple <strong>bash script</strong> in order to batch convert Markdown files via <code>pandoc</code> and it is working for me. But I have the feeling the code is dirty. Could you help me improve it?</p> <pre><code>#!/bin/bash rm -r out; mkdir out for f in src/*.md do filename=$(basename "$f") filename="${filename%.*}" echo "Processing $filename" pandoc "$f" -o "out/$filename.epub" pandoc "$f" -o "out/$filename.pdf" done </code></pre>
[]
[ { "body": "<h1>overall and good stuff</h1>\n\n<p>This is pretty good. I definitely wouldn't call the code dirty. Good stuff:</p>\n\n<ul>\n<li>The indentation is good</li>\n<li>putting double quotes around variable substitutions is a best practice</li>\n<li>using <code>$()</code> for command substitution is the best practice also</li>\n<li>the <code>#!</code> is good</li>\n<li>providing meaningful output to the user is nice</li>\n<li>the variable names are ok</li>\n</ul>\n\n<h1>suggestions</h1>\n\n<ul>\n<li>I get putting <code>rm -r out; mkdir out</code> on one line sounds good because they're related, but it doesn't help the readability here. If you want to tie them together so that the <code>mkdir</code> doesn't run unless <code>rm</code> succeeds then you could do <code>rm -r out &amp;&amp; mkdir out</code>. Otherwise I'd put them on two lines. Breaking up things with blank lines, as you've already done, is enough to make clear which things belong together.</li>\n<li><code>for f in src/*.md</code> certainly works most of the time, but will break if there's any white space in a filename. Fixing this involves <a href=\"https://unix.stackexchange.com/a/321757/79839\">using find</a>. <a href=\"https://unix.stackexchange.com/a/9499/79839\">This answer</a> is part of a duped question, but it may be a bit easier to follow.</li>\n<li>Having <code>f</code> and <code>filename</code> as variables is a bit confusing. For something this short it is pretty harmless which is why I said they were ok above. If you want to tweak this <code>f</code> might make more sense as <code>fullpath</code> or <code>fqfn</code>. And <code>filename</code> might be better as <code>basename</code> or <code>base</code>.</li>\n<li>add <code>if ! which pandoc</code>... near the top to catch if <code>pandoc</code> is missing.</li>\n</ul>\n\n<pre><code>if ! which pandoc &gt; /dev/null; then\n echo you need pandoc\n exit 1\nfi\n</code></pre>\n\n<h1>further reading</h1>\n\n<ul>\n<li><a href=\"https://www.shellcheck.net/\" rel=\"nofollow noreferrer\">shellcheck</a> is handy. You can run it locally or in your CI pipeline or manually paste something into their site.</li>\n<li><a href=\"https://sap1ens.com/blog/2017/07/01/bash-scripting-best-practices/\" rel=\"nofollow noreferrer\">bash best practices by Yaroslav Tkachenko</a> is a nice quick read on bash best practices.</li>\n<li><a href=\"https://google.github.io/styleguide/shellguide.html\" rel=\"nofollow noreferrer\">google shell style guide</a> is even more in-depth with best practices.</li>\n<li><a href=\"https://stackoverflow.com/a/21613044/2002471\">env is good for portability</a> but this is rarely an issue with <code>bash</code>. It might become a more current problem if Apple dumps bash after <a href=\"https://www.theverge.com/2019/6/4/18651872/apple-macos-catalina-zsh-bash-shell-replacement-features\" rel=\"nofollow noreferrer\">adopting zsh as the default</a>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T06:56:33.193", "Id": "466241", "Score": "0", "body": "\"for f in src/*.md certainly works most of the time, but will break if there's any white space in a filename.\" -- nope, not true, this is perfectly fine!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T09:33:22.037", "Id": "467691", "Score": "0", "body": "Don't use `which` unless is also a buitlin to the shell that you're using. It does not know builtins, functions and alias." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T23:42:11.253", "Id": "237726", "ParentId": "237721", "Score": "2" } } ]
{ "AcceptedAnswerId": "237726", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T21:12:22.463", "Id": "237721", "Score": "3", "Tags": [ "bash" ], "Title": "Pandoc batch conversion" }
237721
<p>So i code stuff for my <strong>fx-cg50 calculator's micropython</strong> as I'm an a level student and a python beginner, and i need help pointing out the bugs and some programming tips to further improve my code, and i can't use sympy or numpy since they cant fit in my calculator's measly 16 MB so i have to make everything from scratch: <strong>disclaimer</strong>, my code can't factor expressions by completing the square, so if you guys have any idea about how i could get started tell me, i was planning on using my program to begin with to get a factored quadratic expression anyways, and move on from there.</p> <p>and can anyone tell me what level my code is at, relatively for reference sake.</p> <pre><code>from math import sqrt, pi, isclose, gcd print("ax+by+c=0") def gcd_2(a, b): while b: a, b = b, a % b return a def fraction(a): factor = 0 while True: factor += 1 a_rounded = int(round(a*factor)) if isclose(a*factor, a_rounded, abs_tol=0.01): text = ("{}/{}".format(a_rounded, factor)) return text def simplify_fraction(numer, denom): if denom == 0: return "Division by 0 - result undefined" # Remove greatest common divisor: common_divisor = gcd_2(numer, denom) (reduced_num, reduced_den) = (numer / common_divisor, denom / common_divisor) # Note that reduced_den &gt; 0 as documented in the gcd function. if common_divisor == 1: return (numer, denom) else: # Bunch of nonsense to make sure denominator is negative if possible if (reduced_den &gt; denom): if (reduced_den * reduced_num &lt; 0): return (-reduced_num, -reduced_den) else: return (reduced_num, reduced_den) else: return (reduced_num, reduced_den) def quadratic_function(a, b, c): a_original, b_original, c_original = a, b, c if b ** 2 - 4 * a * c &gt;= 0: negative_factor = False if a &lt; 0: negative_factor = True # checks if gcf can be applied to simplify the quadratic expression b_divisible_by_a = (b % a == 0) c_divisible_by_a = (c % a == 0) check_divisible = (b_divisible_by_a and c_divisible_by_a) a_is_one = (a == (a/a)) if negative_factor: gcf = -int(gcd(int(-a), gcd(int(-b), int(-c)))) b, c, a = -b, -c, -a if a_is_one or (check_divisible is False): gcf = "" elif check_divisible and (a_is_one is False): if negative_factor is False: gcf = int(gcd(int(-a), gcd(int(-b), int(-c)))) b, c, a = b/a, c/a, a/a x1 = (-b + sqrt(b ** 2 - 4 * a * c)) / (2 * a) x2 = (-b - sqrt(b ** 2 - 4 * a * c)) / (2 * a) # Added a "-" to these next 2 values because they would be moved to the other side of the equation mult1 = -x1 * a mult2 = -x2 * a (num1, den1) = simplify_fraction(a, mult1) (num2, den2) = simplify_fraction(a, mult2) if (num1 &gt; a) or (num2 &gt; a): # simplify fraction will make too large of num and denom to try to make a sqrt work print("No factorization") c =(b/2)**2 else: # Getting ready to make the print look nice if (den1 &gt; 0): sign1 = "+" else: sign1 = "" if (den2 &gt; 0): sign2 = "+" else: sign2 = "" print("The Factored Form is:\n{}({}x{}{})({}x{}{})".format(gcf, int(num1), sign1, int(den1), int(num2), sign2,int(den2))) else: # if the part under the sqrt is negative, you have a solution with i print("Solutions are imaginary") return while True: try: stop_flag = 0 stop_or_continue = "" a = float(eval(input("insert a: ").replace("pi", str(pi)))) b = float(eval(input("insert b: ").replace("pi", str(pi)))) c = float(eval(input("insert c: ").replace("pi", str(pi)))) quadratic_function(a, b, c) discriminant = b ** 2 - 4 * a * c if discriminant == 0: x_one = (-b + sqrt(b ** 2 - 4 * a * c)) / (2 * a) # x_one if eval(fraction(x_one)) % 1 == 0: print("x1 is : ", x_one) else: print("x1 is : ", fraction(x_one)) if discriminant &gt; 0: x_one = (-b + sqrt(b ** 2 - 4 * a * c)) / (2 * a) # x_one if eval(fraction(x_one)) % 1 == 0: print("x1 is : ", x_one) else: print("x1 is : ", fraction(x_one)) x_two = (-b - sqrt(b ** 2 - 4 * a * c)) / (2 * a) # x_two if eval(fraction(x_two)) % 1 == 0: print("x2 is : ", x_two) else: print("x2 is : ", fraction(x_two)) if discriminant &lt; 0: pass while stop_or_continue != "a" or "b": stop_or_continue = input("Stop?: ") if stop_or_continue == "a": stop_flag = 1 break if stop_or_continue == "b": stop_flag = 0 break if stop_flag == 1: break except ValueError: pass </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T00:04:12.370", "Id": "466226", "Score": "0", "body": "You say quadratic, but the expression you print `ax + by + c = 0` is linear." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T09:49:01.963", "Id": "466258", "Score": "0", "body": "@AJNeufeld ahh sorry thats a small mistake but the code is for quadratic really" } ]
[ { "body": "<h1>Repetition</h1>\n\n<p>You write:</p>\n\n<pre><code>discriminant = b ** 2 - 4 * a * c\n</code></pre>\n\n<p>followed by:</p>\n\n<pre><code> if discriminant == 0:\n x_one = (-b + sqrt(b ** 2 - 4 * a * c)) / (2 * a) # x_one\n ...\n if discriminant &gt; 0:\n x_one = (-b + sqrt(b ** 2 - 4 * a * c)) / (2 * a) # x_one\n ...\n x_two = (-b - sqrt(b ** 2 - 4 * a * c)) / (2 * a) # x_two\n ...\n</code></pre>\n\n<p>Any reason why you don't use <code>sort(discriminant)</code>?</p>\n\n<p>This continues in <code>quadratic_function</code>, with:</p>\n\n<pre><code>if b ** 2 - 4 * a * c &gt;= 0:\n ...\n x1 = (-b + sqrt(b ** 2 - 4 * a * c)) / (2 * a)\n x2 = (-b - sqrt(b ** 2 - 4 * a * c)) / (2 * a)\n</code></pre>\n\n<h1>Repetition (reprise)</h1>\n\n<pre><code> a = float(eval(input(\"insert a: \").replace(\"pi\", str(pi))))\n b = float(eval(input(\"insert b: \").replace(\"pi\", str(pi))))\n c = float(eval(input(\"insert c: \").replace(\"pi\", str(pi))))\n</code></pre>\n\n<p>Looks like you could use a common function here:</p>\n\n<pre><code>def query_float(prompt):\n return float(eval(input(prompt).replace(\"pi\", str(pi))))\n\n a = query_float(\"insert a: \")\n b = query_float(\"insert b: \")\n c = query_float(\"insert c: \")\n</code></pre>\n\n<h1>Repetition (reprise, reprised)</h1>\n\n<pre><code> if eval(fraction(x_one)) % 1 == 0:\n print(\"x1 is : \", x_one)\n else:\n print(\"x1 is : \", fraction(x_one))\n</code></pre>\n\n<p>This block of code appears 3 times (once with <code>x_two</code>). In the process of executing the block, it calls <code>fraction(x_one)</code>, which is a time-consuming search function, looping through up to 100 divisors, trying to find one that works. Then, the resulting fraction expression is evaluated, and if it is not an integer, <code>fraction(x_one)</code> is again called, despite having been already computed moments earlier!</p>\n\n<p>If <code>fraction()</code> simply returned the \"value\", instead of \"value/1\", when <code>factor == 1</code>, then the caller would simply:</p>\n\n<pre><code> print(\"x1 is : \", fraction(x_one))\n</code></pre>\n\n<h1>Stop or Continue</h1>\n\n<p>It is unclear why the user would answer <code>\"a\"</code> or <code>\"b\"</code> to the question <code>input(\"Stop?: \")</code>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T23:44:55.847", "Id": "466639", "Score": "0", "body": "ahh its because ill be inputting everything from a calculator and a and b are right beside each other." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T19:59:37.910", "Id": "237854", "ParentId": "237723", "Score": "2" } }, { "body": "<p>This type of program, can really use OOP, it will help maintain it much better, by making classes for designated functions, and the pi replacer function can be a part of it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T17:36:54.107", "Id": "480971", "Score": "1", "body": "I would be helpful if you could show some examples of how this might be transformed to OOP." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T17:17:51.617", "Id": "244958", "ParentId": "237723", "Score": "0" } } ]
{ "AcceptedAnswerId": "237854", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T21:48:38.170", "Id": "237723", "Score": "4", "Tags": [ "python", "python-3.x", "mathematics" ], "Title": "Factoring and solving a quadratic polynomial" }
237723
<p>I have an Entry that I want to give a red outline when the entry is empty. I'm using SyncFusion's <code>SFTextInputLayout</code> for my Entry and it has a property <code>HasError</code> that once it's set to true, it'll automatically highlight my entire in Red.</p> <p>Here is the following XAML code for <code>SFTextInputLayout</code></p> <pre><code> &lt;inputLayout:SfTextInputLayout Grid.Column="0" Hint="Phone Number" ContainerType="{StaticResource RepairOrderContainerType}" HasError="{Binding IsPhoneNumberError}" FocusedColor="{StaticResource AccentColor}" VerticalOptions="Center" HorizontalOptions="Start"&gt; &lt;Entry Keyboard="Telephone" Style="{StaticResource TextInputStyle}" Text="{Binding PhoneNumber}"/&gt; &lt;/inputLayout:SfTextInputLayout&gt; </code></pre> <p>As you can see, I have two bindings that handles the text of the entry and another one to check if it has an error or not.</p> <p>While this solution works, it will get redundant pretty soon as the number of my entry fields grow. For every entry field I have, I need another boolean to cover its Error property as shown below. </p> <pre><code> private string _phoneNumber; public string PhoneNumber { get =&gt; _phoneNumber; set { IsPhoneNumberError = string.IsNullOrWhiteSpace(value) ? true : false; this.RaiseAndSetIfChanged(ref _phoneNumber, _phoneNumber); } } private bool _isPhoneNumberError = false; public bool IsPhoneNumberError { get =&gt; _isPhoneNumberError; set { this.RaiseAndSetIfChanged(ref _isPhoneNumberError, value); } } </code></pre> <p>I'm wondering how to simplify this code?</p>
[]
[ { "body": "<p>You could have a collection of ValueConverters which would validate your TextInputs' strings. For example one could be a PhoneNumberValidator or PhoneToBoolConverter (example names there). This way HasError would bind to <code>HasError=\"{Binding PhoneNumber, Converter={StaticResource PhoneNumberValidator}}\"</code>. Converters are handy and you can reuse them in multiple places around your code if they are declared in your <code>App.xaml.cs</code> for example. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T11:59:23.347", "Id": "474044", "Score": "0", "body": "Welcome to CR SE; you're off to a good start!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T12:01:52.373", "Id": "474045", "Score": "0", "body": "Cheers @ShapeOfMatter" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T08:52:12.797", "Id": "241542", "ParentId": "237727", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T00:22:37.287", "Id": "237727", "Score": "1", "Tags": [ "c#", "validation", "xamarin" ], "Title": "Entry Validation in Xamarin.Forms" }
237727
<p>Here's <a href="https://www.hackerearth.com/practice/algorithms/string-algorithm/basics-of-string-manipulation/practice-problems/algorithm/aliceandstrings-9da62aa7/" rel="nofollow noreferrer">Alice and Strings</a>, a programming challenge on hackerearth:</p> <blockquote> <p>Two strings <span class="math-container">\$A\$</span> and <span class="math-container">\$B\$</span> comprising of lower case English letters are compatible if they are equal or can be made equal by following this step <strong>any number of times</strong>:</p> <ul> <li>Select a prefix from the string <span class="math-container">\$A\$</span> (possibly empty), and increase the alphabetical value of all the characters in the prefix by the same valid amount. For example if the string is <code>xyz</code> and we select the prefix <code>xy</code> then we can convert it to <code>yz</code> by increasing the alphabetical value by 1. But if we select the prefix <code>xyz</code> then we cannot increase the alphabetical value.</li> </ul> <p>Your task is to determine if given strings <span class="math-container">\$A\$</span> and <span class="math-container">\$B\$</span> are compatible.</p> <h3>Input format</h3> <p>First line: String <span class="math-container">\$A\$</span> </p> <p>Next line: String <span class="math-container">\$B\$</span></p> <h3>Output format</h3> <p>For each test case, print <code>YES</code> if string <span class="math-container">\$A\$</span> can be converted to string <span class="math-container">\$B\$</span>, otherwise print <code>NO</code>.</p> <h3>Constraints</h3> <p><span class="math-container">$$ \DeclareMathOperator{\len}{len} 1 \leq \len(A) \leq 1\,000\,000 \\ 1 \leq \len(B) \leq 1\,000\,000 \\ $$</span></p> </blockquote> <p>Can you please review my solution to it? Please comment on any aspect to improve such as readability, comment usage, further improvements on speed/memory usage, etc.</p> <pre><code>/* HackerEarth https://www.hackerearth.com/practice/algorithms/string-algorithm/basics-of-string-manipulation/practice-problems/algorithm/aliceandstrings-9da62aa7/ */ #include &lt;iostream&gt; /* Recusrsively checks if string A can be converted to B by incrementing the prefixes: eg: A = abaca B = cdbda [step 1]bcbda (prefix abac incremented by 1) [step 2]bc[b]da cd[b]da (don't take bcb as a prefix because b is already matched) [step 3]cdbda -----&gt; so convertible (incrementing prefix bc) */ bool transformable(std::string&amp; A, std::string&amp; B, int last_index) { if (A.compare(0, last_index, B, 0, last_index) == 0) { return true; } else { if (A[last_index] == B[last_index]) { return transformable(A, B, --last_index); } else { if (A[last_index] &gt; B[last_index]) { return false; } else { while(A[last_index] != B[last_index]) { for(int i = 0; i &lt;= last_index; i++) { A[i] += ('b' - 'a'); } } return transformable(A, B, --last_index); } } } } int main() { std::string A; std::string B; std::cin &gt;&gt; A &gt;&gt; B; if (A.length() != B.length()) { std::cout &lt;&lt; "NO" &lt;&lt; std::endl; return 0; } if (transformable(A, B, A.length() - 1)) std::cout &lt;&lt; "YES" &lt;&lt; std::endl; else std::cout &lt;&lt; "NO" &lt;&lt; std::endl; return 0; } </code></pre>
[]
[ { "body": "<h1>Code review</h1>\n\n<p>In general, the code looks nice and follows consistent styles. Some small observations:</p>\n\n<ul>\n<li><p>Missing <code>#include &lt;string&gt;</code>.</p></li>\n<li><p>Avoid <code>std::endl</code> when <code>\\n</code> suffices. <code>std::endl</code> flushes the buffer, while <code>\\n</code> does not. Unnecessary flushing can cause performance degradation. See <a href=\"https://stackoverflow.com/q/213907/9716597\"><code>std::endl</code> vs <code>\\n</code></a>. Use</p>\n\n<pre><code>std::cout &lt;&lt; \"YES\\n\";\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>std::cout &lt;&lt; \"YES\" &lt;&lt; std::endl;\n</code></pre>\n\n<p>unless flushing is a requirement from the website (I hope not).</p></li>\n<li><p>Since we are depending on lowercase letters being continuously encoded anyway, <code>'B' - 'A'</code> is just <code>1</code>. And <code>A[i] += 1</code> becomes <code>++A[i]</code>.</p></li>\n</ul>\n\n<h1>Better algorithm</h1>\n\n<p>That said, the logic of the code is overly convoluted. The many levels of nested control statements make it hard to follow the code. There is a much simpler algorithm to do it: to determine whether <code>A</code> is transformable into <code>B</code>,</p>\n\n<ul>\n<li><p>take the differences between the corresponding positions <code>B[i] - A[i]</code>;</p></li>\n<li><p>form a sequence out of these differences;</p></li>\n<li><p>append the sequence by 0 (to prevent cases like <code>bbbbb =&gt; aaaaa</code>);</p></li>\n<li><p>test if this sequence is sorted in non-ascending order.</p></li>\n</ul>\n\n<p>For example:</p>\n\n<ul>\n<li><p>for <code>A = \"abcde\"</code>, <code>B = \"ccdde\"</code>, the sequence of differences is <code>21100</code>, so the transformation is possible (<code>abcde =&gt; bcdde =&gt; ccdde</code>);</p></li>\n<li><p>for <code>A = \"abcde\"</code>, <code>B = \"bbcce\"</code>, the sequence of differences is <code>10010</code>, so the transformation is impossible (try it).</p></li>\n</ul>\n\n<p>Here's (roughly) how I would put everything together:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;functional&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;string_view&gt;\n#include &lt;vector&gt;\n\nbool transformable(std::string_view a, std::string_view b)\n{\n if (a.size() != b.size()) {\n return false;\n }\n std::vector&lt;int&gt; diff_sequence(a.size() + 1);\n std::transform(b.begin(), b.end(), a.begin(), diff_sequence.begin(), std::minus&lt;&gt;{});\n diff_sequence.back() = 0;\n return std::is_sorted(diff_sequence.begin(), diff_sequence.end(), std::greater&lt;&gt;{});\n}\n\nint main()\n{\n std::string A;\n std::string B;\n\n std::cin &gt;&gt; A &gt;&gt; B;\n\n if (transformable(A, B)) {\n std::cout &lt;&lt; \"YES\\n\";\n } else {\n std::cout &lt;&lt; \"NO\\n\";\n }\n}\n</code></pre>\n\n<p>(<a href=\"https://wandbox.org/permlink/vFagC0QSsVQHprIc\" rel=\"noreferrer\">live demo</a>)</p>\n\n<p>(Replace <code>std::string_view</code> with <code>const std::string&amp;</code> and remove the <code>#include &lt;string_view&gt;</code> if C++17 is not available, which IIRC is the case with competitive programming sites.)</p>\n\n<p>The <code>transformable</code> function can be simplified with the <a href=\"https://ericniebler.github.io/range-v3/index.html\" rel=\"noreferrer\">range-v3 library</a>:</p>\n\n<pre><code>namespace views = ranges::views;\n\nbool transformable(std::string_view a, std::string_view b)\n{\n return ranges::is_sorted(\n views::concat(\n views::transform(b, a, std::minus&lt;&gt;{}),\n views::single(0)\n ), std::greater&lt;&gt;{});\n}\n</code></pre>\n\n<p>(<a href=\"https://wandbox.org/permlink/GlfRzk9f32hinqnq\" rel=\"noreferrer\">live demo</a>)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T05:31:16.443", "Id": "237734", "ParentId": "237732", "Score": "5" } } ]
{ "AcceptedAnswerId": "237734", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T04:59:03.990", "Id": "237732", "Score": "4", "Tags": [ "c++", "algorithm", "programming-challenge", "strings" ], "Title": "Determining whether a string is transformable into another by repetitively increasing its prefixes alphabetically" }
237732
<p>This is my A-Star implementation for a 2D space of nodes but allowing to specifically set connections between nodes because my usecase does not have points tied to a grid (however for clarification reasons, the sample data down there does form a 3x3 grid with non-diagonal connections).</p> <p><strong>So basically it is A-Star on a graph with using euclidean distance as weights for moving between nodes, I believe.</strong></p> <pre><code> #include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;vector&gt; #include &lt;set&gt; #include &lt;cmath&gt; #include &lt;string&gt; #include &lt;limits&gt; struct Point { Point(int x = 0, int y = 0) : x(x), y(y) {}; bool operator ==(const Point&amp; o) const { return o.x == x &amp;&amp; o.y == y; } int DistTo(Point &amp; other) const { return(std::sqrt(std::pow(other.x - x, 2) + std::pow(other.y - y, 2))); }; int x, y; void Print(std::string name) const { std::cout &lt;&lt; name &lt;&lt; " x: " &lt;&lt; x &lt;&lt; " y: " &lt;&lt; y &lt;&lt; std::endl; } }; struct Node { Node(Point position = Point(), Node * parent = nullptr) : position(position), parent(parent) {}; Point position; int dist_to_start = 0; int total_dist = INT_MAX; std::shared_ptr&lt;Node&gt; parent; std::shared_ptr&lt; std::vector&lt;Node&gt; &gt; connections{ new std::vector&lt;Node&gt; }; bool operator ==(const Node&amp; o) const { return (o.position.x == position.x) &amp;&amp; (o.position.y == position.y); } bool operator &lt;(const Node&amp; o) const { return (total_dist &lt; o.total_dist); } void AddConnection(Node subnode) { connections-&gt;push_back(subnode); } }; std::vector&lt;Point&gt; Astar(Point &amp; start_pos, Point &amp; end_pos, std::vector&lt;Node&gt; all_nodes) { // Find the start and end nodes Node start_node; Node end_node; for (Node &amp; node : all_nodes) { if (node.position == end_pos) // start and end swaped here because A-Star traces from end to start start_node = node; if (node.position == start_pos) end_node = node; } std::vector&lt;Point&gt; found_path; // Output path std::set&lt;Node&gt; open_list; // Using set to be ordered std::vector&lt;Point&gt; closed_list; open_list.emplace(start_node); while (!open_list.empty()) { // Use node with lowest total_dist (the set is always sorted) Node current_node = *open_list.begin(); // Remove smallest and add to closed list open_list.erase(open_list.begin()); closed_list.push_back(current_node.position); // Found the goal if (current_node.position == end_node.position) { // Found the goal Node * parent = &amp;current_node; // Jump from parent to parent to trace back while (parent != nullptr) { found_path.push_back(parent-&gt;position); parent = parent-&gt;parent.get(); } return(found_path); } for (Node&amp; node : *current_node.connections) { Node child(node); child.parent.reset(new Node(current_node)); // Child is on the closed list if (std::find_if(closed_list.begin(), closed_list.end(), [&amp;child](Point &amp; pt) { return(pt == child.position); }) != closed_list.end()) continue; // Create the total_dist, dist_to_start, and heurist_dist_to_end values for the new subnode // Calculated the total distance to the start by adding the distance from the subnode to the current node. // Note: This distance could be precomputed and just held together with the "connections" child.dist_to_start = current_node.dist_to_start + child.position.DistTo(current_node.position); // Total cost is the sum of past distance and the heuristic (which assumes just line-of-flight) child.total_dist = child.dist_to_start + child.position.SqrDistTo(end_node.position); // Child is already in the open list if (std::find_if(open_list.begin(), open_list.end(), [&amp;child](const Node &amp; node) { return((node == child) &amp;&amp; (child.dist_to_start &gt; node.dist_to_start)); }) != open_list.end()) continue; // Add the child to the open list open_list.emplace(child); } } return(found_path); } </code></pre> <p>Main method with test data (forms a 3x3 grid with non-diagonal connections):</p> <pre><code> int main() { std::vector&lt;Node&gt; all_nodes; // Nodes Node nd_0_0{ Point{0,0} }; Node nd_1_0{ Point{1,0} }; Node nd_2_0{ Point{2,0} }; Node nd_0_1{ Point{0,1} }; Node nd_1_1{ Point{1,1} }; Node nd_2_1{ Point{2,1} }; Node nd_0_2{ Point{0,2} }; Node nd_1_2{ Point{1,2} }; Node nd_2_2{ Point{2,2} }; // Connections nd_0_0.AddConnection(nd_1_0); nd_0_0.AddConnection(nd_0_1); nd_1_0.AddConnection(nd_0_0); nd_1_0.AddConnection(nd_2_0); nd_1_0.AddConnection(nd_1_1); nd_2_0.AddConnection(nd_1_0); nd_2_0.AddConnection(nd_2_1); nd_0_1.AddConnection(nd_0_0); nd_0_1.AddConnection(nd_1_1); nd_0_1.AddConnection(nd_0_2); nd_1_1.AddConnection(nd_0_1); nd_1_1.AddConnection(nd_1_0); nd_1_1.AddConnection(nd_2_1); nd_1_1.AddConnection(nd_1_2); nd_2_1.AddConnection(nd_2_0); nd_2_1.AddConnection(nd_1_1); nd_2_1.AddConnection(nd_2_2); nd_0_2.AddConnection(nd_0_1); nd_0_2.AddConnection(nd_1_2); nd_1_2.AddConnection(nd_0_2); nd_1_2.AddConnection(nd_2_2); nd_1_2.AddConnection(nd_1_1); nd_2_2.AddConnection(nd_1_2); nd_2_2.AddConnection(nd_2_1); all_nodes.push_back(nd_0_0); all_nodes.push_back(nd_1_0); all_nodes.push_back(nd_2_0); all_nodes.push_back(nd_0_1); all_nodes.push_back(nd_1_1); all_nodes.push_back(nd_2_1); all_nodes.push_back(nd_0_2); all_nodes.push_back(nd_1_2); all_nodes.push_back(nd_2_2); Point start_pos{ 0, 0 }; Point end_pos{ 2, 2 }; auto path = Astar(start_pos, end_pos, all_nodes); if (path.empty()) std::cout &lt;&lt; "No path :( \n"; else { std::cout &lt;&lt; "Path found :) \n"; std::for_each(path.begin(), path.end(), [](const Point &amp; pt) { pt.Print("Move to: "); }); } } </code></pre> <p>Output:</p> <blockquote> <p>Path found :)<br> Move to: x: 0 y: 0<br> Move to: x: 0 y: 1<br> Move to: x: 0 y: 2<br> Move to: x: 1 y: 2<br> Move to: x: 2 y: 2</p> </blockquote> <p>What would you suggest for improvements? Huge thanks in advance!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T08:43:46.960", "Id": "466252", "Score": "0", "body": "`#include \"pch.h\"` is irrelevant. That only works with the MSVC compiler." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T16:13:03.510", "Id": "466287", "Score": "0", "body": "@πάνταῥεῖ Of course, that was project specific." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T16:17:02.857", "Id": "466288", "Score": "0", "body": "Better remove it then, or add a MSVC tag explicitely." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T16:20:13.637", "Id": "466290", "Score": "0", "body": "Have removed it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T05:26:23.067", "Id": "466403", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<h1>Use <code>hypot()</code></h1>\n\n<p>C has a standard library function to calculate the hypothenuse of a right-angled triangle. You can use it to calculate a distance this way:</p>\n\n<pre><code>int DistTo(Point &amp; other) const {\n return std::hypot(other.x - x, other.y - y);\n}\n</code></pre>\n\n<h1>Prefer <code>'\\n'</code> instead of <code>std::endl</code></h1>\n\n<p>Prefer using <code>'\\n'</code> to end a line. <code>std::endl</code> is equivalent to <code>'\\n'</code> plus a flush of the output buffer. Flushing unnecessarily can lead to bad performance.</p>\n\n<h1>Overload <code>operator&lt;&lt;</code> to add support for printing in your own classes</h1>\n\n<p>It's always nicer if you can make your classes work like existing types in the standard library. This includes printing them. Instead of having to call a member function named <code>Print()</code>, it's much nicer if you could just write:</p>\n\n<pre><code>Point pt;\n...\nstd::cout &lt;&lt; \"Move to: \" &lt;&lt; pt &lt;&lt; '\\n';\n</code></pre>\n\n<p>To do this, you need to add an <code>operator&lt;&lt;</code> overload outside the class. To make it able to access your class's private members, declare it as a friend, like so:</p>\n\n<pre><code>struct Point {\n ...\n friend std::ostream &amp;operator&lt;&lt;(ostream &amp;os, const Point &amp;point);\n};\n\nstd::ostream &amp;operator&lt;&lt;(ostream &amp;os, const Point &amp;point) {\n os &lt;&lt; '(' &lt;&lt; point.x &lt;&lt; \", \" &lt;&lt; point.y &lt;&lt; ')';\n}\n</code></pre>\n\n<p>Your class doesn't have private member variables, so the <code>friend</code> declaration is not necessary, but it doesn't hurt either.</p>\n\n<h1>Wrong use <code>std::shared_ptr</code> for <code>connections</code></h1>\n\n<p>Each <code>Node</code> can have connections to multiple other nodes. If you want to use <code>std::shared_ptr</code> to ensure proper ownership tracking, then <code>connections</code> must be a <code>std::vector</code> of <code>std::shared_ptr&lt;Node&gt;</code>s, not a <code>std::shared_ptr</code> of a <code>std::vector&lt;Node&gt;</code>. Otherwise, only the list structure itself is tracked. This is particularly important because copying a <code>Node</code> in your case no longer copies the list of connections, but just shares a reference to a single list.</p>\n\n<p>Related to this:</p>\n\n<h1>Make the constructor of <code>Node</code> take a <code>std::shared_ptr&lt;Node&gt; parent</code></h1>\n\n<p>Your constructor of <code>class Node</code> takes a raw pointer to a parent node, and then stores it into a <code>std::shared_ptr&lt;Node&gt;</code>. This is problematic, because you can write the following code:</p>\n\n<pre><code>Node child;\n\n{\n Node parent;\n child = Node({}, &amp;parent); // child.parent points to parent\n} // lifetime of parent ends here, child.parent is now invalid\n</code></pre>\n\n<p>You have to ensure you have a <code>std::shared_ptr</code> of the parent node before calling the constructor of the child. Change the constructor to:</p>\n\n<pre><code>Node(Point position = {}, std::shared_ptr&lt;Node&gt; parent = {}): position(position), parent(parent) {};\n</code></pre>\n\n<p>Of course, this means you need to have shared pointers from the very start. So <code>Astar()</code> should get a vector of shared pointers:</p>\n\n<pre><code>std::vector&lt;Point&gt; Astar(Point &amp;start_pos, Point &amp;end_pos, const std::vector&lt;std::shared_ptr&lt;Node&gt;&gt; &amp;all_nodes)\n{\n std::shared_ptr&lt;Node&gt; start_node;\n std::shared_ptr&lt;Node&gt; end_node;\n\n for (auto &amp;node: all_nodes)\n {\n ...\n }\n ...\n}\n</code></pre>\n\n<p>If you want to avoid this, then alternatively:</p>\n\n<h1>Consider adding a <code>class Graph</code> that owns the <code>Node</code>s</h1>\n\n<p>To avoid having to use <code>std::shared_ptr</code> everywhere, but to ensure pointers to parent nodes are always valid, consider adding a <code>class Graph</code> that manages the collection of <code>Node</code>s. Internally, it could just use a <code>std::vector&lt;Node&gt;</code> to store the nodes; you just have to make sure that when you add and remove nodes from a <code>Graph</code>, that connections and parent/child relationships have been properly deleted beforehand.</p>\n\n<p>If you have a <code>class Graph</code>, you can make <code>Astar()</code> a member function of it. It would look like:</p>\n\n<pre><code>class Graph {\n std::vector&lt;Node&gt; nodes;\n\npublic:\n Node &amp;AddNode(Point position) {\n nodes.emplace_back(position);\n return nodes.back();\n }\n\n void AddConnection(Node &amp;a, Node &amp;b) {\n a.AddConnection(b);\n }\n\n ...\n\n std::vector&lt;Point&gt; Astar(Point &amp; start_pos, Point &amp; end_pos);\n};\n\nstd::vector&lt;Point&gt; Graph::Astar(Point &amp; start_pos, Point &amp; end_pos)\n{\n // Find the start and end nodes\n Node start_node;\n Node end_node;\n\n for (auto &amp;node: nodes)\n {\n ...\n }\n\n ...\n}\n</code></pre>\n\n<h1>Make <code>Astar()</code> take start and end <code>Node</code>s instead of <code>Point</code>s</h1>\n\n<p>Instead of telling <code>Astar()</code> the start and end position, why not tell it the start and end <code>Node</code>s to use? This avoids having to scan the whole list of nodes to find the ones matching the given positions, and avoids potential issues if a given position matches zero or more than one <code>Node</code>. So:</p>\n\n<pre><code>std::vector&lt;Point&gt; Astar(Node &amp;start_node, Node &amp;end_node, std::vector&lt;Node&gt; all_nodes);\n</code></pre>\n\n<h1>Avoid copying variables unnecessarily</h1>\n\n<p>There's a lot of copying going on in your code, that might not be necessary. In particular, instead of making copies of <code>Node</code>s all the time, it might be more efficient to just keep references or pointers to the elements of <code>all_nodes</code>.</p>\n\n<p>Note that some information from the A* algorithm is stored in <code>struct Node</code>. So if you do use references/pointers instead of copies, then you have to ensure only one thread is running <code>Astar()</code> on a given vector of <code>Node</code>s at any time.</p>\n\n<h1>Use <code>std::any_of()</code> instead of <code>std::find_if()</code> if you only need a boolean result</h1>\n\n<p>To check if a child is on the closed list, you can use <code>std::any_of()</code> instead of <code>std::find_if()</code>:</p>\n\n<pre><code>if (std::any_of(closed_list.begin(), closed_list.end(), [&amp;child](Point &amp; pt){return pt == child.position);}))\n continue;\n</code></pre>\n\n<p>This saves a bit of typing. The same goes for checking if a child is on the closed list.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T00:25:01.533", "Id": "237768", "ParentId": "237735", "Score": "2" } }, { "body": "<blockquote>\n<pre><code>std::vector&lt;Point&gt; closed_list;\n</code></pre>\n</blockquote>\n\n<p>There are two operations that are applied to <code>closed_list</code>:</p>\n\n<ol>\n<li>Add a point.</li>\n<li>Check whether a given point is already in the list.</li>\n</ol>\n\n<p>A <code>vector</code> can do that job, but there are other data structures that are meant to support that kind of use case, for example <code>std::unordered_set</code> (or an open-addressing variant thereof, which sadly isn't in <code>std</code>).</p>\n\n<blockquote>\n<pre><code>// Total cost is the sum of past distance and the heuristic (which assumes just line-of-flight)\nchild.total_dist = child.dist_to_start + child.position.SqrDistTo(end_node.position);\n</code></pre>\n</blockquote>\n\n<p>What is <code>SqrDistTo</code>? I didn't see the definition. If it does what it sounds like it would do, namely computing the distance squared (skipping the square root), then it is <a href=\"http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html#euclidean-distance-squared\" rel=\"nofollow noreferrer\">wrong</a>: the heuristic distance can be larger than the actual distance which is a direct violation of the condition that A* places on the heuristic. Some \"tactical overestimation\" is sometimes acceptable despite being technically wrong, but squared distance overestimates by an unlimited amount, getting worse and worse for longer distances. If it does something else, or is just \"filler\" and not representative of the real code, maybe this point of feedback does not apply.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T19:16:43.907", "Id": "466371", "Score": "0", "body": "Thank you very much for this addition! Am already using an unordered set in the course of implementing G. Sliepen's suggestions. That link about squared distance was very helpful. Indeed I switched to the squared variant because on my tiny test it gave the same result. Had edited that accidentally into the code of the starting post when fixing a comment.. will revert that so the posted code compiles again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T19:06:16.827", "Id": "237795", "ParentId": "237735", "Score": "2" } } ]
{ "AcceptedAnswerId": "237768", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T05:48:46.927", "Id": "237735", "Score": "2", "Tags": [ "c++", "pathfinding", "a-star" ], "Title": "A-Star for 2D Graph (not grid)" }
237735
<p>I'm fairly new to programming and this is the 2nd thing I've done in python.</p> <p>This code creates a /Tiles directory in the folder where the script is ran, then it makes an X (8) number of folders inside of /Tiles. </p> <p>Inside of those 8 folders it makes a Y number of subfolders and downloads Z number of images per Y folder. </p> <p>Y and Z are the same number but change depending on the X folder. </p> <p>X folder 0 contains 2^0 Y folders and 2^0 Z images per Y folder.</p> <p>Next X folder 2^1, etc until 8 folders or 2^7.</p> <p>Any general or python specific advice for a newbie? </p> <p>Also, any design advice?</p> <p>I was thinking of having a loading bar of some sorts because it's ~20k images and was looking into this <a href="https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console">https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console</a> </p> <p>But in the end decided I just want to finish this up since I was done with the main functionality. </p> <p>[..] means the code is on the same line but I made a new one for the purposes of reading here without scrolling.</p> <p>Thanks. </p> <pre><code>import os import urllib.request import ctypes print ("This script will download map tiles from [Redacted link]") print ("The further it gets the more time it will take to fill the current folder.") print ("Because the number of images increases exponentially.") print ("You can check the progress by going into the latest folder.") print ("When it is done the taskbar icon will flash and prompt you to close the window.") # stores current directory path = os.getcwd() print ("The current working directory is {}.".format(path) + "\n") # adds the names of the new directory to be created path += "/Tiles/" # defines the access rights access_rights = 0o755 # creates the tiles directory try: os.mkdir(path, access_rights) except OSError: print ("Creation of the tiles directory {} failed.".format(path)) else: print ("All files will be downloaded to {}.".format(path)) # for testing: # print ("Successfully created the tiles directory {}".format(path)) # number of x subfolders x_folders = 8 # number of y subfolders and z images - different folders have a [..] # different number of subfolders amd images yz_array = [2**0, 2**1, 2**2, 2**3, 2**4, 2**5, 2**6, 2**7] # main loop # creates the x directories for x in range(x_folders): try: os.mkdir("{}/{}".format(path,x), access_rights) except OSError: print ("Failed to create the X directory - {}.".format(x)) break except: print("Something went wrong creating X folders.") break else: print("Downloading images to {}{}.".format(path,x)) # creates the y directories for y in range(yz_array[x]): try: os.mkdir("{}/{}/{}".format(path,x,y), access_rights) except OSError: print ("Failed to create the Y directory - {}.".format(y)) break except: print("Something went wrong creating Y folders.") break else: pass # downloads z images for z in range(yz_array[x]): try: urllib.request.urlretrieve("[Redacted link] [..]/{}/{}/{}.png" \ .format(x,y,z), "{}/{}/{}/{}.png".format(path,x,y,z)) except: print("Something went wrong downloading Z images.") break else: pass print("Successfully filled folder {}{}.".format(path,x) + "\n") print("Finished running.") ctypes.windll.user32.FlashWindow(ctypes.windll.kernel32. [..]GetConsoleWindow(),True) # flashes the taskbar icon print("Press Enter to close") input("\n") </code></pre>
[]
[ { "body": "<p>Cool python exercise! And a nice job.<br>\nI'm going to assume you are using python3. There are some points of improvement:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/10660443/7501501\">Multiline strings</a>: In python you can create a string with more than one line using <code>\"\"\"</code> so you an put all of the printing in the beginning of your program in one print statement.</li>\n<li><a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\">Pathlib</a>: There is a library called pathlib which allows you to create multi platform path objects. Try to use it instead of concatenating strings yourself.</li>\n<li>Constants in capitals: Is <code>access_rights</code> a constant? Write it in capital letters if so (It's a normal naming convention).</li>\n<li>String formatting: You can use <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\"><code>fstrings</code></a> instead of <code>format</code>, it looks much nicer and more readable (to me). So <code>\"Downloading images to {}{}.\".format(path,x)</code> can now be <code>f\"Downloading images to {path}{x}.\"</code>.</li>\n<li>List comprehension: you can create the <code>yz_array</code> using list comprehension, it is a bit complicated but it will look like: <code>[2 ** x for x in range(8)]</code> - will get the same result!</li>\n<li>Meaningful variable names: instead of <code>x</code> even use <code>x_index</code>.</li>\n<li>Meaningful exceptions: Using <a href=\"https://stackoverflow.com/questions/18982610/difference-between-except-and-except-exception-as-e-in-python\"><code>Exception as e</code></a> you can print the system error, giving the user more information.</li>\n<li>Logical error: Notice that even if there was an error in the file creation process you will still print \"Successfully filled folder\" which is not true. Add a boolean variable to prevent that.</li>\n<li>Multi Platform compatibility: You are probably using <code>windows</code>, but on other <code>os</code> your code will crush, by adding another <code>try - catch</code> you can prevent that. You can also try and find the <code>os</code> and create a matching case for windows.</li>\n</ul>\n\n<p>Maybe:</p>\n\n<ul>\n<li>Functions: You can use functions to avoid the indentations.</li>\n<li>Spaces: According to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\"><code>PEP8</code></a> you should add a space after a <code>,</code> and you should not add space after a print statement.</li>\n<li>Use type annotation: (Last but this one is my personal favourite) When your code gets complicated and you start to use function - Do not forget to read about <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\"><code>type annotations</code></a>.</li>\n</ul>\n\n<p>Overall - greate code, nicely written.<br>\nGood luck and Have fun!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T22:28:40.270", "Id": "466507", "Score": "0", "body": "Appreciate the response! I'll look into all the suggestions and make adjustments. Thanks a lot." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T21:11:27.523", "Id": "237801", "ParentId": "237737", "Score": "4" } } ]
{ "AcceptedAnswerId": "237801", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T06:09:12.940", "Id": "237737", "Score": "2", "Tags": [ "python" ], "Title": "Python - Downloading map tiles" }
237737
<p><strong>Purpose of the code:</strong></p> <p>Let's say I have 3 excel files to deal with. </p> <p>Those file have already been filtered or hidden because the content is very large. And I only need part of the content for every excel files.</p> <p>I don't want to open every file and worksheets in order to copy the desired range.</p> <p>I want to write a code to combine every filtered or hidden cells and put those cells to a brand new workbook.</p> <p><strong>Steps of the code:</strong></p> <p>1.Combine every filtered or hidden cells of all worksheets for every excel files.</p> <p>2.Create a new empty single-worksheet workbook.</p> <p>3.Put all cells of Step 1 into Step 2.</p> <p><strong>Problem of the code:</strong></p> <p>1.Running too slow. Maybe there are too many <code>for</code> loops?</p> <pre><code>import openpyxl import os import glob path = os.getcwd() data=[] x=input('name:') + '.xlsx' target_xls = os.path.join(path,x) for file in glob.glob(path+'\*.*'): if file.endswith((".xlsx")): wb = openpyxl.load_workbook(file, data_only=True) for sheet in wb.worksheets: for j in range(2, sheet.max_row+1 ): for i in range(1,sheet.max_column+1): ihidden = sheet.row_dimensions[j].hidden # Row Visibility True / False svalue = sheet.cell(column=i,row=j).value if ihidden == True: shidden = "HIDDEN" else: shidden = "VISIBLE" data.append(svalue) WP= openpyxl.Workbook() ws = WP.active ws.title = "Sheet1" x=sheet.max_column new_list = [data[i:i+x] for i in range(0, len(data), x)] for elem in new_list: ws.append(elem) WP.save(target_xls) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T10:52:21.920", "Id": "466266", "Score": "0", "body": "I do have a deja vú it seems. Didnt you ask that a few hours before? Please be patient about getting answers here." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T10:00:32.843", "Id": "237740", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "excel" ], "Title": "Optimizing the openpyxl program" }
237740
<p>I am new to C. I tried to make a bank management console application. I want some one to review it for advice to enhance and develop my coding skills.</p> <p>This is what the program does with the inputs:</p> <ul> <li><code>1</code> add an account</li> <li><code>2</code> search for a specific account </li> <li><code>3</code> modify a specific account </li> <li><code>4</code> delete a specific account</li> </ul> <hr> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;stdbool.h&gt; //part of declaration of the types typedef struct date { int j,m,a;//j:day/m:month/a:year }date; typedef struct cus //cus:client { char name[50],prenom[50],adr[50],tel[50];//adr: adresse/prenom:name/name:family name int f;// f:ID date datec;//date:date of birth }cus; typedef struct { int ic,solde;//ic:ID_Client/solde:how much money in the account char tc;//tc:Type_Compte bool b;//b:Bloqed or opened }account; cus t[10];//cus is for costumer account v[10]; //part of the functions or procedures //part of search functions and procedures int msearchclient() { cus cuss; int d=32,k,*a,p; printf("enter the ID of the costumer:"); scanf("%d" ,&amp;cuss.f); for(int i=0;i&lt;10;i++) { if(cuss.f==t[i].f) { k=1; printf("\n"); printf("\t\tFOUND\n\n"); a=&amp;t[i].f; p=*a; } } if(k!=1) printf("\t\tNOT FOUND\n\n"); return p; } void mshowclient() { int d=32,a=msearchclient(); for(int i=0;i&lt;10;i++) { if(a==t[i].f) { printf("|FULL Name\t\t|ID\t\t|Adresse\t\t|Telphone Number\t\t|Date of Birth\n"); printf("|%s%c%s \t\t|%d\t\t|%s\t\t|%s\t\t|%d/%d/%d\n" ,t[i].name,d,t[i].prenom,t[i].f,t[i].adr,t[i].tel,t[i].datec.j,t[i].datec.m,t[i].datec.a); } } } int msearchaccount() { account accountt; int k,*a,p; printf("enter the ID of account:"); scanf("%d" ,&amp;accountt.ic); for(int i=0;i&lt;10;i++) { if(accountt.ic==v[i].ic) { k=1; printf("\n"); printf("\t\tFOUND\n\n"); a=&amp;v[i].ic; p=*a; } } if(k!=1) printf("\t\tNOT FOUND\n\n"); return p; } void mshowaccount() { int a=msearchaccount(); for(int i=0;i&lt;10;i++) { if(a==v[i].ic) { printf("|Account ID\t\t|Type of account\t\t|Balance\t\t|Account Opened(1) or closed(0)\n"); printf("|%d\t\t|%c\t\t|%d\t\t|%d\n" ,v[i].ic,v[i].tc,v[i].solde,v[i].b); } } } void msearch() { int x; printf("\n\n"); printf("Do you want search :\n=&gt;&gt;(1)the client \n=&gt;&gt;(2)the account \n=&gt;&gt;(3)Account and client informations \n=&gt;&gt;(4)Back \n=&gt;&gt;"); scanf("%d" ,&amp;x); switch (x) { case 1: { msearchclient(); }break; case 2: { msearchaccount(); }break; case 3: { mshowclient(); mshowaccount(); }break; case 4: { MENU(); }break; default :{printf("enter another number please\n");msearch();} } } //part of delete function void mdelete() { account accountt; cus cuss; int x; printf("\n\n"); printf("Do you want delete :\n=&gt;&gt;the client (1)\n=&gt;&gt;the account (2)\n=&gt;&gt;Back (3)\n=&gt;&gt;"); scanf("%d" ,&amp;x); switch (x) { case 1: { printf("enter the id of the client:"); scanf("%d" ,&amp;cuss.f); int k; for(int i=0;i&lt;10;i++) { if(cuss.f==t[i].f) { t[i].name[50]=NULL; t[i].prenom[50]=NULL; t[i].datec.a=NULL; t[i].datec.j=NULL; t[i].datec.m=NULL; t[i].adr[50]=NULL; t[i].tel[50]=NULL; k=1; } } int i,d=32; if(k==1) printf("GOOD we deleted it"); }break; case 2: { printf("enter the id of the account:"); scanf("%d" ,&amp;accountt.ic); int k; for(int i=0;i&lt;10;i++) { if(accountt.ic==v[i].ic) { v[i].ic=NULL; v[i].solde=NULL; v[i].tc=NULL; v[i].b=NULL; k=1; } } if(k==1) printf("GOOD we deleted it"); }break; case 3: { MENU(); } default :{printf("enter another number please\n");mdelete();} } } //part of modify functions and prosedures void mmmenuodify() { int n; account accountt; printf("\n"); printf("what do you want to modify in the account:\n"); printf("\n\n"); printf("1- the amount of money\n"); printf("2- the type of the account\n"); printf("3- the id of account\n"); printf("4- Blocking the account\n"); printf("5- Extract the money\n"); printf("6- Deposite the money\n"); printf("7- Back\n"); printf("\n=&gt;&gt;"); scanf("%d",&amp;n); switch (n) { case 1: { printf("enter the new amount of money"); scanf("%d" ,&amp;accountt.solde); for(int i=0;i&lt;10;i++) { if(msearchaccount()==v[i].ic) { v[i].solde=accountt.solde; msearchaccount(); } } msearchaccount(); }break; case 2: { printf("enter the new type:"); scanf("%c" ,&amp;accountt.tc); for(int i=0;i&lt;10;i++) { if(msearchaccount()==v[i].ic) v[i].tc=accountt.tc; } }break; case 3: { printf("enter the new id of account:"); scanf("%d" ,&amp;accountt.ic); for(int i=0;i&lt;10;i++) { if(msearchaccount()==v[i].ic) v[i].ic=accountt.ic; } }break; case 4: { int n; printf("enter the number:\n=&gt;&gt;(0) for blocking the account\n=&gt;&gt;(1) for opening he account\n=&gt;&gt;"); scanf("%d" ,&amp;n); if(n==0) { for(int i=0;i&lt;10;i++) { if(msearchaccount()==v[i].ic) v[i].b=0; } } else if(n==1) { for(int i=0;i&lt;10;i++) { if(msearchaccount()==v[i].ic) v[i].b=1; } } } case 5: { printf("enter how much do you want to take:"); scanf("%d" ,&amp;accountt.solde); for(int i=0;i&lt;10;i++) { if(msearchaccount()==v[i].ic) { if(v[i].solde&gt;0) v[i].solde=v[i].solde-accountt.solde; else { printf("you can't take money because you don't have money in the account"); break; } } } }break; case 6: { printf("enter how much do you want to deposite:"); scanf("%d" ,&amp;accountt.solde); for(int i=0;i&lt;10;i++) { if(msearchaccount()==v[i].ic) v[i].solde=v[i].solde+accountt.solde; } }break; case 7: { printf("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;\n"); MENU(); }break; default: {printf("enter new number");mmmenuodify();} } } void mmodify() { mmmenuodify(); } //part of create function void mcreate() { int x; printf("\n"); printf("how many costumers you want to add:"); scanf("%d" ,&amp;x); //FILE *pr=fopen("tahiro.txt" ,"w+"); for(int i=0;i&lt;x;i++) { printf("enter the full name:" ); scanf("%s %s" ,&amp;t[i].prenom,&amp;t[i].name);//when you enter the full name you have to make space between the name and family name and in the same family name no spaces printf("enter thier ID:"); scanf("%d" ,&amp;t[i].f); printf("enter the date of birth:"); scanf("%d/%d/%d" ,&amp;t[i].datec.j,&amp;t[i].datec.m,&amp;t[i].datec.a); printf("enter the telephone number:"); scanf("%d" ,&amp;t[i].tel); printf("enter Adresse please:"); scanf("%s" ,&amp;t[i].adr); printf("\n\n"); printf("Now for the account informations"); printf("\n\n"); printf("enter the account ID please:"); scanf("%d" ,&amp;v[i].ic); int a=2020-t[i].datec.a; if(a&gt;=18) { printf("------------------------------\n"); printf("Enter the type of the account:\n=&gt;&gt;'P' for particular account\n=&gt;&gt;'C' for commercial\n"); getchar(); scanf("%c",&amp;v[i].tc); printf("------------------------------\n"); } else if(a&gt;0&amp;&amp;a&lt;18) v[i].tc='M'; printf("enter the amount of money:"); scanf("%d" ,&amp;v[i].solde); printf("Block or Not:"); scanf("%d" ,&amp;v[i].b); //fprintf(pr,"%s\t\t%s\t\t%d\t\t%d\t\t%s\t\t%d/%d/%d\t\t%c\n" ,t[i].name,t[i].prenom,t[i].f,t[i].tel,t[i].adr,t[i].datec.j,t[i].datec.m,t[i].datec.a,v[i].tc); if(x&gt;1) { printf("do you want to continue(Y/N):\n=&gt;&gt;"); if(getchar()=='N'||getchar()=='n') break; } printf("\n\n"); } //fclose(pr); } //part of menu function void MENU() { int n; printf("\t\tHELLO AND WELCOME"); printf("\n\n\n"); printf("1-Add an account\n"); printf("2-Find an account\n"); printf("3-Modify an account\n"); printf("4-Delete an account\n"); printf("\n\n\n"); printf("chosse the number for the service:"); scanf("%d" ,&amp;n); printf("\n"); switch (n) { case 1: { printf("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;\n"); mcreate(); printf("\n\n\n"); printf("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;\n"); MENU(); }break; case 2: { printf("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;\n"); msearch(); printf("\n\n\n"); printf("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;\n"); MENU(); }break; case 3: { printf("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;\n"); mmodify(); printf("\n\n\n"); printf("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;\n"); MENU(); }break; case 4: { printf("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;\n"); mdelete(); printf("\n\n\n"); printf("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;\n"); MENU(); }break; } } //main part void main() { system("color 0A"); MENU(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T11:43:52.893", "Id": "466273", "Score": "0", "body": "_@Taher Rezzag_ Unfortunately your code [doesn't even compile](http://coliru.stacked-crooked.com/a/027c01be31d24bde). Fix that first please before coming back here to ask about improvements. (BTW use the word _customer_ please, a [_costumer_](https://en.wikipedia.org/wiki/Costumer) is something completely different)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T14:40:15.103", "Id": "466283", "Score": "0", "body": "@πάντα ῥεῖ Are you compiling with C++ or C? I get \n\"warning: implicit declaration of function 'MENU' [-Wimplicit-function-declaration]\", you got \"error: 'MENU' was not declared in this scope\", yet with file named \"main.cpp\", I am suspicious the of what compiler was used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T15:34:11.813", "Id": "466286", "Score": "0", "body": "@chux As you can clearly see at the link, I was compiling with the following command: `gcc main.cpp` without any further specific options. The compiler used was `gcc`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T16:18:14.557", "Id": "466289", "Score": "1", "body": "@chux-ReinstateMonica I'm using CLion on top of Visual Studio 2019 and it doesn't compile. Among other error messages some of the scanfs are using a numeric format to read strings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T17:47:50.120", "Id": "466306", "Score": "1", "body": "@pacmaninbw I am unfamiliar with \"CLion on top of Visual Studio 2019\". Does that constitute a C compilation? My C compilation gave many warnings, yet no errors. What error did you receive? \"scanfs are using a numeric format to read strings.\" is certainly bad beginner code, yet is not an _error_, but UB. Of course many do compile with warnings treated as errors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T18:08:12.437", "Id": "466307", "Score": "0", "body": "@πάνταῥεῖ As gcc with `gcc main.cpp` can compile that code as C++ (something that was not clear to me as I rarely use gcc with *.cpp files - but researched it now), it looks like the error you see is a C++ one so [comment](https://codereview.stackexchange.com/questions/237741/console-application-for-bank-management/237747#comment466273_237741) does not match the C tag of the post. When compiling with C, OP's code can compile without warnings. Unfortunately even with modest warning levels, many warnings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T19:03:32.280", "Id": "466308", "Score": "0", "body": "@chux-ReinstateMonica It is primarily the Visual Studio C compiler, Jet Brains CLion provides an alternate IDE and uses CMake rather than Visual Studio Project files. CLion can also be used with Clang and gcc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T20:09:31.673", "Id": "466314", "Score": "0", "body": "@chux-ReinstateMonica Unfortunately I can't tell coliru to use `main.c` instead of `main.cpp`." } ]
[ { "body": "<p>You are omitting to pass parameters to functions, that code will never compile.</p>\n\n<p>For example:\nThe function <code>int msearchclient()</code> use the array <code>t[i]</code> but you never pass it as an argument. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T12:46:52.907", "Id": "466276", "Score": "0", "body": "_\"You are omitting to pass parameters to functions, that code will never compile.\"_ That's nonsense. `cus t[10];` is a global variable definition. Thus it would be accessible from any function body. Also don't answer _off-topic_ questions here please." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T14:42:19.523", "Id": "466284", "Score": "0", "body": "no it would the function use the array t[10] with out declaring the parameters because i did't work with files to store data so i declared the array t[10] as const so i can work with it when i ever i want" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T16:22:26.817", "Id": "466291", "Score": "1", "body": "@πάνταῥεῖ He doesn't have enough points to see VTC. The answer should be `don't use global variables` rather than it won't compile." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T12:24:28.797", "Id": "237742", "ParentId": "237741", "Score": "-2" } }, { "body": "<blockquote>\n <p>or advice to enhance and develop my coding skills.</p>\n</blockquote>\n\n<p><strong>Enable all warnings</strong></p>\n\n<p>I received many with \"gcc -std=c11 -O0 -g3 -pedantic -Wall -Wextra -Wconversion -c -fmessage-length=0 \". See list below.</p>\n\n<p>Save time and let the automatic checking of a good well enabled compiler provide you feedback.</p>\n\n<p><strong>Weak input</strong></p>\n\n<p>All input is through <code>scanf()</code>. That consistency is <em>good</em>, yet <code>scanf()</code> is very difficult to use and handle unexpected input. Use <code>fgets()</code> to read a <em>line</em> of user input into a <em>string</em>. Then parse the <em>string</em>.</p>\n\n<p><strong>Classic missing space with %c</strong></p>\n\n<p>Code's usage of <code>scanf()</code> leaves the <KBD>Enter</KBD> or <code>'\\n'</code> in <code>stdin</code>. The <code>\"%c\"</code> in <code>scanf(\"%c\", &amp;accountt.tc);</code>, unlike <code>\"%s\" and \"%d\"</code>, does not consume and toss leading white space. When case 2 is not used first, <code>scanf(\"%c\"</code> will read a <code>'\\n'</code>.</p>\n\n<pre><code> // scanf(\"%c\", &amp;accountt.tc);\n scanf(\" %c\", &amp;accountt.tc);\n</code></pre>\n\n<p><strong>Check return values of input</strong></p>\n\n<p>The return value of <code>scanf()</code> is not checked.</p>\n\n<p><strong>Cope with names better</strong></p>\n\n<p>Real names can have spaces in the first name. Real names can have spaces in the last name. Real names can exceed 49 letters.</p>\n\n<p><strong>Use width limits with %s</strong></p>\n\n<p>Do not use <code>%s</code> without a width. <code>%s</code> --> <code>%49s</code> for code's <code>name[50]</code>.</p>\n\n<p><strong>Avoid (naked) magic numbers</strong></p>\n\n<p>Example: Instead of <code>name[50]</code></p>\n\n<pre><code>#define NAME_MAX_SIZE 50\n\nchar name[NAME_MAX_SIZE];\n</code></pre>\n\n<p><strong>Auto formatting</strong></p>\n\n<p>Many coding environments have an <em>auto formatter</em>. Post code is unnecessarily difficult to read. Improve format with tools - do not waste time doing it manually.</p>\n\n<p><strong>Spell checker</strong></p>\n\n<p>Deposite --> Deposit</p>\n\n<hr>\n\n<pre><code>../test.c:34:7: warning: unused variable 'd' [-Wunused-variable]\n int d = 32, k, *a, p;\n ^\n../test.c: In function 'msearch':\n../test.c:132:7: warning: implicit declaration of function 'MENU' [-Wimplicit-function-declaration]\n MENU();\n ^~~~\n../test.c: In function 'mdelete':\n../test.c:168:25: warning: assignment makes integer from pointer without a cast [-Wint-conversion]\n t[i].name[50] = NULL;\n ^\n../test.c:169:27: warning: assignment makes integer from pointer without a cast [-Wint-conversion]\n t[i].prenom[50] = NULL;\n ^\n../test.c:170:24: warning: assignment makes integer from pointer without a cast [-Wint-conversion]\n t[i].datec.a = NULL;\n ^\n../test.c:171:24: warning: assignment makes integer from pointer without a cast [-Wint-conversion]\n t[i].datec.j = NULL;\n ^\n../test.c:172:24: warning: assignment makes integer from pointer without a cast [-Wint-conversion]\n t[i].datec.m = NULL;\n ^\n../test.c:173:24: warning: assignment makes integer from pointer without a cast [-Wint-conversion]\n t[i].adr[50] = NULL;\n ^\n../test.c:174:24: warning: assignment makes integer from pointer without a cast [-Wint-conversion]\n t[i].tel[50] = NULL;\n ^\n../test.c:178:14: warning: unused variable 'd' [-Wunused-variable]\n int i, d = 32;\n ^\n../test.c:178:11: warning: unused variable 'i' [-Wunused-variable]\n int i, d = 32;\n ^\n../test.c:194:19: warning: assignment makes integer from pointer without a cast [-Wint-conversion]\n v[i].ic = NULL;\n ^\n../test.c:195:22: warning: assignment makes integer from pointer without a cast [-Wint-conversion]\n v[i].solde = NULL;\n ^\n../test.c:196:19: warning: assignment makes integer from pointer without a cast [-Wint-conversion]\n v[i].tc = NULL;\n ^\n../test.c: In function 'mcreate':\n../test.c:362:13: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[50]' [-Wformat=]\n scanf(\"%s %s\", &amp;t[i].prenom, &amp;t[i].name); //when you enter the full name you have to make space between the name and family name and in the same family name no spaces\n ~^ ~~~~~~~~~~~~\n../test.c:362:16: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'char (*)[50]' [-Wformat=]\n scanf(\"%s %s\", &amp;t[i].prenom, &amp;t[i].name); //when you enter the full name you have to make space between the name and family name and in the same family name no spaces\n ~^ ~~~~~~~~~~\n../test.c:371:13: warning: format '%d' expects argument of type 'int *', but argument 2 has type 'char (*)[50]' [-Wformat=]\n scanf(\"%d\", &amp;t[i].tel);\n ~^ ~~~~~~~~~\n../test.c:374:13: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[50]' [-Wformat=]\n scanf(\"%s\", &amp;t[i].adr);\n ~^ ~~~~~~~~~\n../test.c:401:13: warning: format '%d' expects argument of type 'int *', but argument 2 has type '_Bool *' [-Wformat=]\n scanf(\"%d\", &amp;v[i].b);\n ~^ ~~~~~~~\n../test.c: At top level:\n../test.c:418:6: warning: conflicting types for 'MENU'\n void MENU() {\n ^~~~\n../test.c:132:7: note: previous implicit declaration of 'MENU' was here\n MENU();\n ^~~~\n../test.c:472:6: warning: return type of 'main' is not 'int' [-Wmain]\n void main() {\n ^~~~\n../test.c: In function 'mdelete':\n../test.c:208:7: warning: this statement may fall through [-Wimplicit-fallthrough=]\n MENU();\n ^~~~~~\n../test.c:210:5: note: here\n default: {\n ^~~~~~~\n../test.c: In function 'mmmenuodify':\n../test.c:275:13: warning: this statement may fall through [-Wimplicit-fallthrough=]\n case 4: {\n ^\n../test.c:298:5: note: here\n case 5: {\n ^~~~\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T19:05:39.843", "Id": "466309", "Score": "0", "body": "There are 2 VTC, one of those may have been a DV." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T11:37:22.297", "Id": "466349", "Score": "0", "body": "thanks for everyone how gived me advices to enhance my coding skills it was nice to ask people like you ." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T15:06:51.160", "Id": "237747", "ParentId": "237741", "Score": "3" } } ]
{ "AcceptedAnswerId": "237747", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T11:03:27.727", "Id": "237741", "Score": "2", "Tags": [ "beginner", "c", "programming-challenge" ], "Title": "Console application for bank management" }
237741
<p>I have built a small roguelike in JS using minimal frameworks (Tho I am using one library for things like FOV, map generation and a few other small things) </p> <p>This is my first 'real' project that was done by only me without following any real tutorials, and because of this, I'm feeling like a lot of the things i'm doing might not be totally correct, or the best way to accomplish such things.. My biggest fear is picking up bad habits just because they 'work' or it was easy for me to implement but isn't the correct way</p> <p>I had a lot of questions, and more so wanted general advice about my use of classes, whether I should be more general with them, stuff like that</p> <p>Currently, I have 3 files, my Game.js which has my game <em>object</em> and the initialization stuff, and then I also have a monster.js class, which uses an entity ID in the constructor in order to determine what kind of monster it is, and then act accordingly</p> <p>And finally, I have a player.js which handles anything player-related, his movements, actions, inventory, etc</p> <p>I'll include those here</p> <p><strong>Game.JS</strong></p> <pre class="lang-js prettyprint-override"><code>//Imports -- All objects from the game import { Player } from "./objects/player.js"; import { Monster } from "./objects/monster.js"; //ROT.RNG.setSeed(); // Game object which has two functions (init, getDisplay), init creates a display, getDisplay is called to return said display export const Game = { display: null, level: 1, textDisplay: null, scheduler: null, notifications: [], invSlots: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"], digger: null, mapGen: null, //used for map generation map: {}, fov: null, enemyChar: ["k", "d", "t", "g"], enemys: [], freeSpace: [], items: [ //Starting items pool, things you can randomly spawn with { name: "Short Sword", dmg: 2, equipped: false }, // All items are like this, if item is equipped:true, we calc damage for it { name: "worn leather leggings", armor: 2, equipped: false, slot: "legs" }, { name: "worn leather chestpiece", armor: 3, equipped: false, slot: "chest" }, { name: "worn leather helm", armor: 1, equipped: false, slot: "head" }, { name: "hand-me-down Mace", dmg: 2, equipped: false, slot: "hand" }, { name: "broken training Sword", dmg: 1, equipped: false, slot: "hand" }, ], loot: [ //Loot to be dropped by mobs or found in chests { name: "golden crown", armor: 2, equipped: false, slot: "head" }, { name: "leather leggings", armor: 4, equipped: false, slot: "legs" }, { name: "long sword", dmg: 4, equipped: false, slot: "hand" }, { name: "leather chestpiece", armor: 5, equipped: false, slot: "chest" }, { name: "leather helm", armor: 4, equipped: false, slot: "head" }, { name: "steel chestpiece", armor: 8, equipped: false, slot: "chest" }, { name: "steel leggings", armor: 6, equipped: false, slot: "legs" }, { name: "steel mace", dmg: 3, equipped: false, slot: "hand" }, { name: "emerald ring", armor: 1, equipped: false, slot: "finger" }, ], rooms: null, room: null, engine: null, roomDebug: [], //End of variable declaration init: function () { this.display = new ROT.Display({ fontSize: 18 }); this.textDisplay = new ROT.Display({ width: 35, height: 20 }); //Dedicated display specifically for text notifications in-game this.fov = new ROT.FOV.PreciseShadowcasting(Game.shadowCast); this.scheduler = new ROT.Scheduler.Simple(); this.engine = new ROT.Engine(this.scheduler); document.getElementById("gameContainer").appendChild(Game.getDisplay().getContainer()); //Push display to the body of the page document.getElementById("gameContainer").appendChild(Game.textDisplay.getContainer()); levelSpawn(); Game.createMap(); Game.spawnEnemies(); Game.scheduler.add(player, true) for (let i = 0; i &lt; Game.enemys.length; i++) { Game.scheduler.add(Game.enemys[i], true); } this.engine.start(); },//END OF DISPLAY GENERATION getDisplay: function () { return this.display; }, //END OF DISPLAY RETURN FUNCTION createMap: function () { // debugger; //Generate a map for use in this specific dungeon this.digger = new ROT.Map.Digger(); //Width x Height //Digger callback function let diggerCallback = function (x, y, value) { if (value) { return; } //Not storing walls? let key = x + "," + y; Game.freeSpace.push(key); this.map[key] = "."; } this.digger.create(diggerCallback.bind(this)); //Draw entire map from players point of view Game.drawWholeMap(); Game.drawRooms(); }, //END OF MAP CREATION spawnEnemies: () =&gt; { //Random function for generating some enemies for (let i = 0; i &lt; Game.enemys.length; i++) { console.log("ENEMY ARRAY ", Game.enemys); let spawnRoom = Game.rooms[Math.floor(Math.random() * Math.floor(Game.rooms.length))]; Game.enemys[i].x = spawnRoom.getCenter()[0]; Game.enemys[i].y = spawnRoom.getCenter()[1]; } Game.spawnLoot(); Game.spawnStairs(); }, //END OF Mob spawn logic spawnLoot: () =&gt; { let spawnRoom = Game.rooms[Math.floor(Math.random() * Game.rooms.length)]; for (let i = 0; i &lt; Game.level * 1.25; i++) { let rndx = Math.floor(Math.random() * spawnRoom._x2); let rndy = Math.floor(Math.random() * spawnRoom._y2); while (rndx &lt; spawnRoom.x1 &amp;&amp; rndx &gt; spawnRoom.x2 - 1) { rndx = Math.floor(Math.random() * spawnRoom._x2); } while (rndy &lt; spawnRoom.y1 &amp;&amp; rndy &gt; spawnRoom.y2 - 1) { rndy = Math.floor(Math.random() * spawnRoom._y2); } let pos = rndx + "," + rndy; Game.map[pos] = "*"; console.log("ROOMS ARE LIKE SO ", Game.rooms); } }, spawnStairs: () =&gt; { let spawnRoom = Game.rooms[Math.floor(Math.random() * Game.rooms.length)]; let pos = spawnRoom.getCenter()[0] + "," + spawnRoom.getCenter()[1]; Game.map[pos] = "&gt;"; console.log("STAIRS AT ", pos); Game.createSpawn(); }, //End of stair spawning logic drawWholeMap: function () { Game.display.clear(); //Simulates actual FOV by clearing any non-seen tiles, this can be removed Game.fov.compute(player.x, player.y, 10, function (x, y, r, visibility) { //Draw only what is visable let pos = x + "," + y; let ch = (Game.map[pos]); //If the key shows up in enemies let bgColor = (Game.map[pos] ? "#d3d3d3" : "#2b2d2f"); let fgColor = "#FFF" //Set basic fg color to white switch (Game.map[pos]) { case "&gt;": fgColor = "#585858";//Is it stairs? Draw as grey, etc break; case "*": fgColor = "#FF0" break; case "%": fgColor = "#FFF"; bgColor = "#F00"; break; case ",": fgColor = "#F00"; bgColor = "#d3d3d3"; break; } Game.display.draw(x, y, ch, fgColor, bgColor); for (let i = 0; i &lt; Game.enemys.length; i++) { if (x == Game.enemys[i].x &amp;&amp; y == Game.enemys[i].y) { console.log("WE SEE THE ENEMY, ") Game.display.draw(Game.enemys[i].x, Game.enemys[i].y, Game.enemys[i].sprite, Game.enemys[i].color, bgColor); } } }); Game.display.draw(player.x, player.y, player.sprite, "#ff0", ""); //Draw player }, // END OF MAP GEN drawDoor: function (x, y) { Game.display.draw(x, y, "+", "red", ""); }, //END OF DRAW DOORS FUNCTION drawRooms: function () { //Function is pretty clear, we're drawing rooms themselves here, and printing to console the room positions this.rooms = Game.digger.getRooms(); for (let i = 0; i &lt; this.rooms.length; i++) { this.room = this.rooms[i]; //this.room.getDoors(this.drawDoor); } }, //END OF DRAWROOMS FUNCTION createSpawn: function () { let spawnRoom = this.rooms[Math.floor(Math.random() * Math.floor(this.rooms.length))]; console.log("Here is where your player will spawn ", spawnRoom.getCenter()); player.x = spawnRoom.getCenter()[0]; //First value returned player.y = spawnRoom.getCenter()[1]; //Second value returned console.log("Player position: ", player.x, player.y); Game.drawWholeMap(); }, //END OF SPAWN CREATION //We need to rename this to drawInventory, as well as clean up some of the conditionals and the name of the input variables informPlayer: (text) =&gt; { Game.textDisplay.clear(); //Clear the information screen if (Array.isArray(text)) { //If the item passed in is an array, it's the players inventory for (let i = 0; i &lt; text.length; i++) { let item = text[i]; Game.textDisplay.drawText(0, 0, "Your Inventory "); let string = Game.invSlots[i] + ") " + text[i].name; if (text[i].equipped) { string += "%b{green} e"; } Game.textDisplay.drawText(0, i + 1, string); } Game.textDisplay.drawText(0, player.inventory.length + 3, "Press any key to equip or unequip"); Game.drawStatus(); //Otherwise, print string as normal } else { Game.textDisplay.drawText(0, 0, text); } }, //END OF archaic TEXT/NOTIFY SYSTEM shadowCast: (x, y) =&gt; { //Function for use in FOV computations let pos = x + "," + y; switch (Game.map[pos]) { case ".": return true; case "&gt;": return true; case "*": return true; case "%": return true; case ",": return true; default: return false; } }, //New and improved messaging function. The idea here is to read off a continual list of information strings. //We will read an array of strings, for each item we will increase Y draw by 1 so that it continues down the screen // If we expand Y to the maximum screendepth of displayText.options.height - 1, clear all the notifications but the last //We will also have the status of the player drawn in a seperate function notify: (text) =&gt; { Game.textDisplay.clear(); //Loop through notifications for (let i = 0; i &lt; text.length; i++) { //Display each notification with increasing y Game.textDisplay.drawText(0, i, text[i]); if (i == Game.textDisplay._options.height - 2) { Game.notifications.splice(0, Game.notifications.length - 1); } } Game.drawStatus(); }, drawStatus: () =&gt; { Game.textDisplay.drawText(0, Game.textDisplay._options.height - 1, "Health: %c{green}" + player.health + "%c{white} Damage: %c{red}" + player.dmg + "%c{white} Armor: %c{yellow}" + player.armor); }, resetGame: () =&gt; { Game.map = {}; Game.enemys.splice(0, Game.enemys.length); Game.engine = null; Game.scheduler.clear(); Game.display.clear(); let page = document.getElementById("gameContainer"); page.innerHTML = ""; Game.init(); } } // END OF GAME OBJECT ITSELF //First-run initialization, create player, add a starter item to his inventory, set it to 'equipped' // Create player object, give him starting items, set the starting items to 'equipped' and add their values to our own var player = new Player(0, 0, '\u263A', [Game.items[Math.floor(Math.random() * Game.items.length)]], Game.enemys); //Set initial inventory for (let i = 0; i &lt; player.inventory.length; i++) { player.inventory[i].equipped = true; if (player.inventory[i].dmg) { player.dmg += player.inventory[i].dmg; } if (player.inventory[i].armor) { player.armor += player.inventory[i].armor; } } function levelSpawn() { //TODO: Expand this function into a much more robust version that can spawn more enemies let spawnAmount = Math.floor(Math.random() * Game.level + 1); let en = [1, 2, 3]; for(let i = 0; i &lt; spawnAmount; i++) { //Spawn enemies Game.enemys.push(new Monster(en[Math.floor(Math.random() * en.length)], 0, 0, player)); } } //The logic of game start sequence //Game.init() =&gt; Game.createMap(); //Game.createMap() =&gt; Game.drawWholeMap(); //DrawWholeMap() =&gt; DrawRooms() //This.drawRooms() //this.levelSpawn() =&gt; this.spawnEnemies() //this.spawnEnemies() =&gt; this.spawnStairs(); //this.spawnStairs =&gt; this.createSpawn(); //Initialize game Game.init(); //Create display player.draw(); Game.drawStatus(); console.log("ENTIRE GAME ENTITY ", Game.map); </code></pre> <p><strong>Monster Class</strong></p> <pre class="lang-js prettyprint-override"><code>import { Game } from "../game.js"; /* New Monster class that represents any and all monsters we may spawn, will continue to get larger as we add more monsters Currently, monsters use an 'entity ID' system, where you call the id of the monster you're looking to spawn inside the constructor. This makes it easy to randomize the monster spawns and get unique sets of enemies each time simply add monsters inside the switch statements, which determine movement type/speed. Eventually we should also adjust cone of influence for all monsters */ //Monster ID Keys // 1 == kobold // 2 == goblin // 3 == witch export class Monster { constructor(id, x, y, player) { this.id = id; this.x = x; this.y = y; this.px = 0; this.py = 0; this.sprite = ""; this.health = 5; //We can change this to also maybe represent level? Still have to figure out levels this.path = []; this.player = player; this.astar = null; this.self = this; this.dmg = 2; this.name = ""; this.color = "" switch(this.id) { //Change monster name dependant on ID provided case 1: this.name = "kobold"; this.sprite = "k"; this.color = "#F00"; break; case 2: this.name = "goblin"; this.sprite = "g"; this.color = "#0F0"; break; case 3: this.name = "witch"; this.sprite = "w"; this.color = "#AF007F"; break; //More as needed } } act() { Game.engine.lock(); if(this.health &lt; 1) { // Char is dead, do no more let pos = this.x+","+this.y; let index = Game.enemys.indexOf(this); Game.map[pos] = "%"; Game.scheduler.remove(this); Game.enemys.splice(index, 1); Game.engine.unlock(); return; } var passableCallback = function (x, y) { //This callback will return true if the positon exists within our game map //add portion that makes it so enemies cannot stand on-top of eachother, and will instead 'swarm' let pos = x+","+y; if(Game.map[pos]) { //If the game position exists in the map for(let i = 0; i &lt; Game.enemys.length; i++) { //Loop through enemies, if the enemy does NOT equal the entity checking, it checks position with other enemies if(Game.enemys[i] != this.self) { return(pos in Game.map); } else if(Game.enemys[i].x == x &amp;&amp; Game.enemys[i].y == y) { return false; } } } } switch(this.id) { // Monster movement designation, you can change topology here case 1: //Is kobold, 4 topology this.astar = new ROT.Path.AStar(this.player.x, this.player.y, passableCallback, { topology: 4 }); break; case 2: //is goblin, 8 topology this.astar = new ROT.Path.AStar(this.player.x, this.player.y, passableCallback, { topology: 8 }); break; case 3: //Witch, 8 topology this.astar = new ROT.Path.AStar(this.player.x, this.player.y, passableCallback, { topology: 8}); break; //More to come } var pathCallback = (x, y) =&gt; { this.path.push([x, y]); } this.path = []; this.astar.compute(this.x, this.y, pathCallback); console.log("Astar computation complete"); this.path.shift(); //Remove existing position if (this.path.length == 1) { //Attack player //Roll for attack let roll = Math.floor(ROT.RNG.getUniform() * 6); if(roll &gt;= 3) { this.player.health -= this.dmg; Game.notifications.push("a " + this.name + " lunges at you! It connects dealing " + this.dmg +" damage\n\n"); Game.notify(Game.notifications); Game.engine.unlock(); this.draw(); return; }else { Game.notifications.push("a " + this.name + " swings at you! But misses\n\n"); Game.notify(Game.notifications); Game.engine.unlock(); this.draw(); return; } } if (this.path.length &lt; 10) { let x = this.path[0][0]; let y = this.path[0][1]; // let pos = this.x + "," + this.y; // Game.map[pos] = "."; // this.x = x; // this.y = y; // pos = this.x + "," + this.y; // Game.map[pos] = this.sprite; this.x = x; this.y = y; this.draw(); } Game.engine.unlock(); } draw() { Game.drawWholeMap(); // Game.display.draw(this.x, this.y, this.sprite, this.color); } damage(amount, crit) { //I have started using a different naming convention here, where the first letter is the data-type. (iBloodLocation is an integer) this.health -= amount; let iBloodLocation = Math.floor(Math.random() * 1); let sBloodPos = ""; let sBX = this.x += iBloodLocation; let sBY = this.y += iBloodLocation; sBloodPos = sBX + "," + sBY; console.error("BLOOD POS ", sBloodPos); Game.map[sBloodPos] = ","; Game.drawWholeMap(); if(crit) { //make arm } } } </code></pre> <p><strong>Player Class</strong></p> <pre class="lang-js prettyprint-override"><code>import { Game } from "../game.js" export class Player { event = (e) =&gt; this.handleEvent(e); constructor(x, y, art, inv, enemys) { this.x = x; this.y = y; this.armor = 1; this.dmg = 1; this.sprite = art; this.health = 100; this.enemys = enemys; this.inventory = inv; //Array of objects with their own functions } act() { Game.engine.lock(); window.addEventListener("keydown", this.event); } draw() { Game.drawWholeMap(); //Game.display.draw(this.x, this.y, this.sprite, "#ff0"); } equipItem(code) { let keyMap = {}; keyMap[65] = "0"; keyMap[66] = "1"; keyMap[67] = "2"; keyMap[68] = "3"; keyMap[69] = "4"; keyMap[70] = "5"; //Player is wanting to do something with his inventory most likely let invItem = this.inventory[Number(keyMap[code])]; //Time to re-write this to ensure that we also double check the equipped item slot to ensure you can't equip two items! if (!invItem.equipped) { //If item is not currently equipped for(let i = 0; i &lt; this.inventory.length; i++) { if(this.inventory[i].slot == invItem.slot) { if(this.inventory[i].equipped) { this.inventory[i].equipped = false; if(this.inventory[i].armor) this.armor -= this.inventory[i].armor; if(this.inventory[i].dmg) this.dmg -= this.inventory[i].dmg; } } } if (invItem.dmg) { this.dmg += invItem.dmg; } if (invItem.armor) { this.armor += invItem.armor } invItem.equipped = !invItem.equipped; Game.informPlayer(this.inventory); return; } else { if (invItem.dmg) { this.dmg -= invItem.dmg; } if (invItem.armor) { this.armor -= invItem.armor } invItem.equipped = !invItem.equipped; Game.informPlayer(this.inventory); return; } } handleEvent(e) { //Process the users input let keyMap = {}; keyMap[38] = 0; keyMap[33] = 1; keyMap[39] = 2; keyMap[34] = 3; keyMap[40] = 4; keyMap[35] = 5; keyMap[37] = 6; keyMap[36] = 7; //Keys for item usage keyMap[65] = "0"; keyMap[66] = "1"; keyMap[67] = "2"; keyMap[68] = "3"; keyMap[69] = "4"; keyMap[70] = "5"; let code = e.keyCode; if (code == 76) this.look(); if (code &gt;= 65 &amp;&amp; code &lt; 70) { this.equipItem(code); } if(code == 190) { //Player is trying to go down stairs let pos = this.x+","+this.y; if(Game.map[pos] == "&gt;") { //Player is standing on stairs, move them to a new dungeon, add 1 to level (depth) Game.level++; Game.resetGame(); } return; } if (code == 73) { Game.informPlayer(this.inventory); // Read out inventory } if (code == 191) {//Player has hit question mark Game.informPlayer("Welcome to the help section! List of commands:\n \n Up Arrow: Move up \n Down Arrow: Move down \n Left Arrow: Move Left \n Right Arrow: Move right \n L: Pick up item \n I: Inventory"); } if (!(code in keyMap)) { return; } let diff = ROT.DIRS[8][keyMap[code]]; console.log(ROT.DIRS[8][keyMap[code]], " ROT DIRS KEY"); let newX = this.x + diff[0]; let newY = this.y + diff[1]; let newKey = newX + "," + newY; // if (!(newKey in Game.map)) { return; } /* cannot move in this direction */ if (!(newKey in Game.map)) { return; }; console.log("Calculating if hit", this.enemys); //We've hit an enemy, let's figure out which one let parts = newKey.split(","); for (let i = 0; i &lt; this.enemys.length; i++) { if (parts[0] == this.enemys[i].x &amp;&amp; parts[1] == this.enemys[i].y) { //Roll a dice for fairness let roll = Math.floor(ROT.RNG.getUniform() * 6); if (roll &gt;= 3) { //Deduct damage from this entity Game.notifications.push("You swing at the " + this.enemys[i].name + " and hit! Dealing " + this.dmg + " damage"); Game.notify(Game.notifications); //this.enemys[i].health -= this.dmg; this.enemys[i].damage(this.dmg, false); Game.engine.unlock(); return; } else { Game.notifications.push("You swing at the " + this.enemys[i].name + " and miss!"); Game.notify(Game.notifications); Game.engine.unlock(); return; } } } console.log("Current NewX values ", newX, newY); Game.display.draw(this.x, this.y, Game.map[this.x + "," + this.y]); this.x = newX; this.y = newY; this.draw(); window.removeEventListener("keydown", this.event); Game.engine.unlock(); } look() { //Method for checking the ground for items, picking up loose items, looting corpses, chests, etc. //Here we'll define some stuff for making sure that corpses are removed (Or changed to a different look?) let pos = this.x + "," + this.y; //Players position turned into a string, for use in Game.map[] switch(Game.map[pos]) { //Switch because it becomes an ez jump table, incase we have lots of looting options case "%": //Is corpse //Do we get loot? Let's roll a dice for this let roll = Math.floor(Math.random() * 6); if(roll &gt;= 3) { let loot = Game.loot[Math.floor(Math.random() * Game.loot.length)]; Game.informPlayer("You picked up " + loot.name); this.inventory.push(loot); Game.map[pos] = "."; } else { Game.informPlayer("You found nothing when looking the corpse.."); Game.map[pos] = "."; } break; case "*": //Loot box let loot = Game.loot[Math.floor(Math.random() * Game.loot.length)]; Game.informPlayer("You picked up " + loot.name); this.inventory.push(loot); Game.map[pos] = "."; break; } } } </code></pre> <p>I know there's quite a bit here, and it's probably mostly a mess that isn't quite understandable -- I appreciate all of your guys time in order to steer me in the right directions</p> <p>Should I be using Inheritance? Like, if something is moveable it should have a moveable class? It feels like I'd have a class for everything in this way, one for attacking or looking or speaking</p> <p>Or am I thinking about this wrong?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T15:39:44.017", "Id": "237749", "Score": "1", "Tags": [ "javascript", "game" ], "Title": "Questions about class structure, inheritance, etc -- Simple Rougelike in JS" }
237749
<p>I've tried to implement parallel MergeSort in C++, that also tracks how many comparisons it's made and how many threads it uses:</p> <pre><code>#include &lt;cmath&gt; #include &lt;ctime&gt; #include &lt;mutex&gt; #include &lt;thread&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; int *original_array,*auxiliary_array; std::mutex protector_of_the_global_counter; int global_counter=0; std::mutex protector_of_the_thread_counter; int number_of_threads=0; template&lt;typename T&gt; class Counting_Comparator { private: bool was_allocated; int *local_counter; public: Counting_Comparator() { was_allocated=true; local_counter=new int(0); } Counting_Comparator(int *init) { was_allocated=false; local_counter=init; } int get_count() {return *local_counter;} bool operator() (T first, T second) { (*local_counter)++; return first&lt;second; } Counting_Comparator(const Counting_Comparator&lt;T&gt; &amp;x) { was_allocated=x.was_allocated; local_counter=x.local_counter; } ~Counting_Comparator() { if (was_allocated) delete local_counter; } }; struct limits { int lower_limit,upper_limit,reccursion_depth; }; void parallel_merge_sort(limits argument) { int lower_limit=argument.lower_limit; int upper_limit=argument.upper_limit; if (upper_limit-lower_limit&lt;2) return; //An array of length less than 2 is already sorted. int reccursion_depth=argument.reccursion_depth; int middle_of_the_array=(upper_limit+lower_limit)/2; limits left_part={lower_limit,middle_of_the_array,reccursion_depth+1}, right_part={middle_of_the_array,upper_limit,reccursion_depth+1}; if (reccursion_depth&lt;log2(std::thread::hardware_concurrency())) { //Making more threads than there are CPU cores is counter-productive. try { std::thread left_thread(parallel_merge_sort,left_part),right_thread(parallel_merge_sort,right_part); protector_of_the_thread_counter.lock(); number_of_threads+=2; protector_of_the_thread_counter.unlock(); left_thread.join(); right_thread.join(); } catch(std::system_error error) { std::cerr &lt;&lt;"Can't create a new thread, error \"" &lt;&lt;error.what() &lt;&lt;"\"!" &lt;&lt;std::endl; delete[] original_array; delete[] auxiliary_array; exit(1); } } else { parallel_merge_sort(left_part); parallel_merge_sort(right_part); } int local_counter=0; Counting_Comparator&lt;int&gt; comparator_functor(&amp;local_counter); std::merge(original_array+lower_limit, original_array+middle_of_the_array, original_array+middle_of_the_array, original_array+upper_limit, auxiliary_array+lower_limit, comparator_functor); protector_of_the_global_counter.lock(); global_counter+=comparator_functor.get_count(); protector_of_the_global_counter.unlock(); std::copy(auxiliary_array+lower_limit, auxiliary_array+upper_limit, original_array+lower_limit); } int main(void) { using std::cout; using std::cin; using std::endl; cout &lt;&lt;"Enter how many numbers you will input." &lt;&lt;endl; int n; cin &gt;&gt;n; try { original_array=new int[n]; auxiliary_array=new int[n]; } catch (...) { std::cerr &lt;&lt;"Not enough memory!?" &lt;&lt;endl; return 1; } cout &lt;&lt;"Enter those numbers:" &lt;&lt;endl; for (int i=0; i&lt;n; i++) cin &gt;&gt;original_array[i]; limits entire_array={0,n,0}; number_of_threads=1; clock_t processor_time=clock(); try { std::thread root_of_the_reccursion(parallel_merge_sort,entire_array); root_of_the_reccursion.join(); } catch (std::system_error error) { std::cerr &lt;&lt;"Can't create a new thread, error \"" &lt;&lt;error.what() &lt;&lt;"\"!" &lt;&lt;endl; delete[] original_array; delete[] auxiliary_array; return 1; } processor_time=clock()-processor_time; cout &lt;&lt;"The sorted array is:" &lt;&lt;endl; for (int i=0; i&lt;n; i++) cout &lt;&lt;original_array[i] &lt;&lt;'\n'; delete[] original_array; delete[] auxiliary_array; cout &lt;&lt;"It took MergeSort " &lt;&lt;global_counter &lt;&lt;" comparisons to sort it." &lt;&lt;endl; cout &lt;&lt;"It used " &lt;&lt;number_of_threads &lt;&lt;" threads." &lt;&lt;endl; cout &lt;&lt;"It took " &lt;&lt;float(processor_time)/CLOCKS_PER_SEC*1000 &lt;&lt;" miliseconds." &lt;&lt;endl; cout &lt;&lt;"The expected number of comparisons, by the formula n*ln(n), would be: " &lt;&lt;n*log(n) &lt;&lt;endl; } </code></pre> <p>So, what do you think about it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T16:43:54.823", "Id": "466296", "Score": "1", "body": "Not enough time to write a full answer, but the formatting is pretty bad. You should put some spaces in there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T16:49:29.140", "Id": "466298", "Score": "0", "body": "Remember what Yoda said, `Either do or don't do, don't try`. Does the code work as expected or not?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T16:52:09.227", "Id": "466300", "Score": "0", "body": "@pacmaninbw, I think it works as expected, but I haven't tested it too much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T17:07:42.503", "Id": "466303", "Score": "0", "body": "@FlatAssembler Be sure when asking here 1st please." } ]
[ { "body": "<p>Parallelism, threads and global state don't mix well. Pass parameters to functions instead of using global state.</p>\n\n<p>C++ is not Java, you don't need to use <code>new</code> for everything.</p>\n\n<p>Mutexes are a bit overkill just to protect counters (both in terms of performance and amount of code one needs to write). Try using atomic variables.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T18:12:09.087", "Id": "237752", "ParentId": "237751", "Score": "2" } } ]
{ "AcceptedAnswerId": "237752", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T16:30:17.807", "Id": "237751", "Score": "2", "Tags": [ "c++", "multithreading", "mergesort" ], "Title": "Parallel MergeSort in C++" }
237751
<p>I wrote a function in Python to call 7zip to compress a folder. The code works and is able to perform the task, however I do not know if this is the most optimal way. Are there any ways to improve the code, any redundant steps?</p> <pre><code>def Compress_7z(Initial_path,Container_Name,File_List, compression_level = -1,DAC = False): """Compression level = -1 standard, 0-9 compression level DAC : Delete After Compression - Remove File after being compressed """ try: chdir(Initial_path) except: return('Path does not exist') # write a listfile with open('list.txt', 'w') as f: for item in File_List: f.write("%s\n" % item) cmd = ['7z', 'a', Container_Name,'@list.txt'] if compression_level != -1 and compression_level &lt;= 9: cmd.append('-mx{0}'.format(compression_level)) elif compression_level &gt; 9 or compression_level &lt; -1: return("Compression not standard: aborting compression") system = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE,shell=True) while system.poll() == None: # .poll() will return a value once it's complete. time.sleep(1) if DAC: for f in File_List: remove(f) # Clean up from compression remove('list.txt') return(system.communicate()) </code></pre>
[]
[ { "body": "<p>Simply reading the code already has a few things which stand out to me\n(in general this all goes towards the style described in\n<a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">this document</a>, which is\nstandard to follow for Python code):</p>\n\n<ul>\n<li><code>Compress_7z</code> should start lower-case and probably should also say\n<code>compress_7zip</code>. I'm agreeing that the literal \"7\" would be\nappropriate here, given the format name.</li>\n<li><code>DAC</code> is a bad variable name, as you've to read the docstring to even\nbegin to understand what this parameter is doing. A better name might\nbe, well, <code>delete_files_after</code> perhaps.</li>\n<li>The rest of the parameters should also all be lower-case.</li>\n<li>Try and apply consistent formatting, or use an IDE or\n<a href=\"https://black.readthedocs.io/en/stable/\" rel=\"nofollow noreferrer\">command-line tool</a> to do it\nfor you (right now there's no whitespace after some of the commas for\nexample, also some of the quotes are single and some are double for no\ngood reason).</li>\n<li>The docstring is not very standard, though at least it mentions the\nvalue range of the parameters, which is obviously good.</li>\n</ul>\n\n<p>Next up, actual functionality:</p>\n\n<p>Shelling out to the <code>7z</code> utility is of course an option, although there\nare also pure Python libraries for this as far as I can see. The reason\nI point this out is that for one the command-line utility might not be\ninstalled and e.g. <code>pip</code> or a similar tool for Python might make it\neasier to handle the dependency.</p>\n\n<p>Since you've already settled on it though, a few more points about the\ncurrent implementation:</p>\n\n<ul>\n<li><code>chdir</code> in a library function is almost certainly a bad idea. It's\ncompletely not expected that \"compress these files\" also means \"change\nmy current working directory\". Instead make sure that the function\nworks without by specifying file names reliably (that is, using\nabsolute path names, or by specifying the working directory <em>for the\ninvoked process only</em>).</li>\n<li>Using strings as error values is a big no. Use exceptions, or if you\nabsolutely do not want to do that, a properly structured return\nvalue. Right now you couldn't distinguish the return value of the\ntool from the strings <code>\"Path does not exist\"</code> and that's generally to\nbe avoided.</li>\n<li>If the compression level is a string the <code>list.txt</code> file will not be\ncleaned up. That's why you generally want to handle exceptions\nproperly, look up how\n<a href=\"https://docs.python.org/3/tutorial/errors.html\" rel=\"nofollow noreferrer\"><code>try</code>, <code>catch</code> and <code>finally</code> work</a>\nfor that.</li>\n<li>Finally it seems like the <code>subprocess.Popen</code> invocation is too much\nwork. If you don't have to communicate with the invoked process,\nsimply run it and wait for the result. <code>time.sleep</code> is an extremely\nwasteful way of accomplishing the same. Instead I think you might\njust be able to use <code>subprocess.run</code> with the <code>cwd</code> argument (see\nabove) and be done with it. You don't need <code>shell=True</code> either, since\nthe invocation doesn't use any shell features at all.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T16:56:10.443", "Id": "237786", "ParentId": "237753", "Score": "3" } } ]
{ "AcceptedAnswerId": "237786", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T18:33:36.507", "Id": "237753", "Score": "4", "Tags": [ "python" ], "Title": "Python function for 7zip compression" }
237753
<p>Not sure this is the right place, but I'll have a try.</p> <p>I'm trying to implement a mutex with capacity, which can be achieved easily with buffered channel like this:</p> <pre><code>var ch = make(chan struct{}, 1000) func Enter(ctx context.Context) error { select { case ch&lt;- struct{}{}: return nil case &lt;-ctx.Done(): return ctx.Err() } } func Exit() { select { case &lt;-ch: return nil default: } } </code></pre> <p>But in order to reduce lock contention, I tried this(<a href="https://github.com/zhiqiangxu/util/blob/master/wm/max.go" rel="nofollow noreferrer">https://github.com/zhiqiangxu/util/blob/master/wm/max.go</a>):</p> <pre><code>package wm import ( "context" "sync/atomic" ) // Max watermark model, a tmutex with capacity // The entire point of this module is to reduce lock contention under fast path type Max struct { count int64 // total number of participators entered int64 // total number of entered max int64 // max number of entered, immutable ch chan struct{} // channel for exit signal from entered } // NewMax is ctor for Max func NewMax(max int64) *Max { m := &amp;Max{max: max, ch: make(chan struct{}, max)} return m } // Enter returns nil if not canceled // Enter guarantees at most N callers will enter successfully at any moment, and will wait when overflow func (m *Max) Enter(ctx context.Context) error { count := m.incCount() // slow path, wait for exit signal before try contendFunc := func() error { for { select { case &lt;-m.ch: // someone exited, try enter again if m.tryAddEntered() { return nil } continue case &lt;-ctx.Done(): // ctx canceled, restore count before return m.decCount() return ctx.Err() } } } if count &gt; m.max { // too many participators, wait for someone to exit return contendFunc() } if !m.tryAddEntered() { // this means there is a sudden burst of participators that entered in very short instant in other goroutines // this should happen very rarely return contendFunc() } return nil } //go:nosplit func (m *Max) tryAddEntered() bool { if atomic.AddInt64(&amp;m.entered, 1) &lt;= m.max { return true } // recover before return m.decEntered() return false } //go:nosplit func (m *Max) decEntered() { atomic.AddInt64(&amp;m.entered, -1) } // TryEnter returns true if succeed func (m *Max) TryEnter() bool { count := m.incCount() if count &gt; m.max { m.decCount() return false } if !m.tryAddEntered() { m.decCount() return false } return true } // Exit should only be called if Enter returns nil func (m *Max) Exit() { m.decEntered() count := m.decCount() // two cases to consider: // 1. remaining count &lt; Max // can there be any waiters? // prove that if there are X(&lt;=count&lt;Max) waiters, there must be at least X signals in ch. // suppose there are X waiters, // then they must have tried to enter at a moment when there are at least Max participators or exactly Max entered // consider the last waiter, when its Max entered callers exit, the first X will see the X waiters(Max-i+X&gt;=Max), // so at least X signals will be dilivered. // // 2. ch is full // will some waiters miss the signal? // remaining count &gt;= max if count &gt;= m.max { // try to wake some waiter up by exit signal. // buffered channel ensures never miss any signal // the waiter may have been canceled by ctx, but it doesn't matter, // superfluous signals only matters for performance purpose select { case m.ch &lt;- struct{}{}: default: } } } //go:nosplit func (m *Max) incCount() int64 { return atomic.AddInt64(&amp;m.count, 1) } //go:nosplit func (m *Max) decCount() int64 { count := atomic.AddInt64(&amp;m.count, -1) if count &lt; 0 { panic("Max: count &lt; 0") } return count } </code></pre> <p>As you can see, this file contains more comments than actual code, because correctness is hard to verify, especially the case at Line 105, can someone review it? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T06:51:46.610", "Id": "466529", "Score": "1", "body": "implement mutex with capacity using channels is a good way... could you explain what this code does.. cause I think it can be made simpler." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T12:06:42.217", "Id": "468564", "Score": "1", "body": "Are we talking of [a semaphore](https://godoc.org/golang.org/x/sync/semaphore#ex-package)?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T19:08:38.713", "Id": "237754", "Score": "3", "Tags": [ "go", "lock-free" ], "Title": "implementing a mutex with capacity" }
237754
<pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; #include &lt;string&gt; using namespace std; void wrapUp() { cout &lt;&lt; "-------------------------------------------------" &lt;&lt; endl; system("CLS"); } int main() { srand(time(0)); string name; int player; int livesTracker = 5; int x = 1 + (rand() % 10); cout &lt;&lt; "Hello, what is your name?" &lt;&lt; endl; cin &gt;&gt; name; cout &lt;&lt; "Welcome to guess the number, " &lt;&lt; name &lt;&lt; "!" &lt;&lt; endl; wrapUp; cout &lt;&lt; '\n' &lt;&lt; "Number of Lives: " &lt;&lt; livesTracker &lt;&lt; endl; for (int round = 1; round &lt;= 3; round++) { if (livesTracker == 0) { system("CLS"); cout &lt;&lt; "Game Over! Actual Answer: " &lt;&lt; x &lt;&lt; endl; system("Color 4"); break; } cout &lt;&lt; "Guess the number that will come up on the screen from 1 to 10" &lt;&lt; endl; cin &gt;&gt; player; if (player == x) { cout &lt;&lt; "You won round " &lt;&lt; round &lt;&lt; "!" &lt;&lt; endl; x = (rand() &amp; 10); } else if(player &gt; x){ cout &lt;&lt; "Your guess was too high, round" &lt;&lt; round &lt;&lt; "!" &lt;&lt; endl; wrapUp; round--; livesTracker--; cout &lt;&lt; '\n' &lt;&lt; "Number of Lives: " &lt;&lt; livesTracker &lt;&lt; endl; } else { cout &lt;&lt; "Your guess was too low, round" &lt;&lt; round &lt;&lt; "!" &lt;&lt; endl; wrapUp; round--; livesTracker--; cout &lt;&lt; '\n' &lt;&lt; "Number of Lives: " &lt;&lt; livesTracker &lt;&lt; endl; } if (round == 3) { cout &lt;&lt; "For the hard level, you have to guess a number from 15!" &lt;&lt; endl; for (int roundh = 1; roundh &lt;= 2; roundh++) { int xh = 1 + (rand() % 15); cout &lt;&lt; "Guess the number that will come up on the screen from 1 to 15" &lt;&lt; endl; cin &gt;&gt; player; if (player == xh) { cout &lt;&lt; "You won round " &lt;&lt; roundh &lt;&lt; "!" &lt;&lt; endl; cout &lt;&lt; "-------------------------------------------------" &lt;&lt; endl; xh = 1 + (rand() % 15); } else if (player &gt; xh) { cout &lt;&lt; "Your guess was too high, round " &lt;&lt; round &lt;&lt; "!" &lt;&lt; endl; wrapUp; roundh--; cout &lt;&lt; '\n' &lt;&lt; "Number of Lives: " &lt;&lt; livesTracker &lt;&lt; endl; } else { cout &lt;&lt; "Your guess was too low, round " &lt;&lt; round &lt;&lt; "!" &lt;&lt; endl; wrapUp; roundh--; cout &lt;&lt; '\n' &lt;&lt; "Number of Lives: " &lt;&lt; livesTracker &lt;&lt; endl; } } } } system("pause"); } </code></pre> <p>This program first creates a random number before going into the loop. A <code>livesTracker</code> variable is then created to control the player's lives. The first loop runs until the player finishes the first round/ level. If the player gets the randomly generated number correct, a new random number will be assigned to x for the next round to start, until the player runs out of lives or wins the game, this will happen. </p> <p>Just wanted to explain the program because its probably too messy to read, appreciate any help!</p> <p>EDIT: I know its not good to clear the screen using <code>system("CLS")</code>, but couldn't find any other options, any help on that would be helpful as well!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T03:00:06.927", "Id": "466336", "Score": "2", "body": "If you think the code is too messy to read, then you should clean it up to make it readable before posting it for a review. This would make it easier for your code to be reviewed, and avoid comments about the messiness of the code. (However, since you now have an answer, you should not edit the code in the question.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T03:57:32.123", "Id": "466337", "Score": "0", "body": "Hey, this is was my first program that I created in MSX BASIC back in ... uh, let's just say that it was a new VG-8235 :)" } ]
[ { "body": "<p>I have some suggestions to improve your code:</p>\n\n<hr>\n\n<h2>Formatting</h2>\n\n<ul>\n<li>You should use empty lines consistently. E.g. you have some ifs/else ifs blocks where you put an empty line at the beginning but not everywhere. I suggest you to not use empty lines there at all.</li>\n<li>You should not use more than two empty lines to seperate things. It's harder to read.</li>\n<li>You should put empty lines between logically grouped things. E.g. your <code>#include</code> statements, the <code>using</code> statement and the <code>wrapUp</code> function are glued together.</li>\n<li>In general try to group things visually that belong together. In the <code>wrapUp</code> function the two empty lines are seperating the ending curly bracket from the function for no reason.</li>\n<li>You should not put a newline as first thing you print in a line, e.g. <code>cout &lt;&lt; '\\n' &lt;&lt; \"Number of Lives: \" &lt;&lt; livesTracker &lt;&lt; endl;</code>. And you should not mixup <code>'\\n'</code> and <code>endl</code>.</li>\n</ul>\n\n<hr>\n\n<h2>Naming</h2>\n\n<ul>\n<li>You should name variables more precisely. <code>player</code> should be named <code>playerGuess</code>. This will make it much clearer what the variable is for. You may ask why this is relevant because you know it already but be aware of other developers. Just by putting that <em>Guess</em> at the end will remove the amount of time someone has to put in finding out stuff. Some other variables could use better naming as well, like <code>roundh</code> or <code>livesTracker</code>.</li>\n<li>I think <code>wrapUp</code> does not describe well enough what it's doing. (That one is kinda personal taste.)</li>\n</ul>\n\n<hr>\n\n<h2>Functional</h2>\n\n<ul>\n<li>It's strange to put the game logic in a for loop and decrement the iterator to continue with the game. I know, I know, it works, but this is not the usual way to use a for loop. A while loop does fit here much better. When you connect the while loop to the amount of lifes left, you will have a much more readable code, e.g. <code>while (amountOfLifes &gt; 0) {// continue with the game}</code>.</li>\n<li>The game logic for the normal game and the <em>hard mode</em> is very similar. You can put it in a method and use parameters, e.g. to individualize the range for the random number to guess.</li>\n</ul>\n\n<hr>\n\n<p>Here is an <em>example</em> of how the program could look like when you apply my suggestions. It doesn't need to be exactly like that. Please note that I didn't double check everything and I changed some of the logic but I hope you get an overall idea about what is improvable:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;iostream&gt;\n#include &lt;cstdlib&gt;\n#include &lt;ctime&gt;\n#include &lt;string&gt;\n\nusing namespace std;\n\n\nvoid printSeperator() {\n cout &lt;&lt; \"-------------------------------------------------\" &lt;&lt; endl;\n}\n\n\nbool guess(int&amp; lifesCounter, int numberToGuess, int round, int upperRandomLimit) {\n cout &lt;&lt; \"Guess the number that will come up on the screen from 1 to \" &lt;&lt; upperRandomLimit &lt;&lt; \": \";\n int playerGuess;\n cin &gt;&gt; playerGuess;\n\n if (playerGuess == numberToGuess) {\n cout &lt;&lt; \"You won round \" &lt;&lt; round &lt;&lt; \"!\" &lt;&lt; endl;\n printSeperator();\n return true;\n }\n else if (playerGuess &gt; numberToGuess) {\n cout &lt;&lt; \"Your guess was too high, round \" &lt;&lt; round &lt;&lt; \"!\" &lt;&lt; endl;\n printSeperator();\n lifesCounter--;\n cout &lt;&lt; \"Number of Lives: \" &lt;&lt; lifesCounter &lt;&lt; endl;\n }\n else {\n cout &lt;&lt; \"Your guess was too low, round \" &lt;&lt; round &lt;&lt; \"!\" &lt;&lt; endl;\n printSeperator();\n lifesCounter--;\n cout &lt;&lt; \"Number of Lives: \" &lt;&lt; lifesCounter &lt;&lt; endl;\n }\n return false;\n}\n\n\nbool playRounds(int&amp; lifesCounter, int upperRandomLimit) {\n int numberToGuess;\n for (int round = 1; round &lt; 3; round++) {\n numberToGuess = 1 + (rand() % upperRandomLimit);\n while (!guess(lifesCounter, numberToGuess, round, upperRandomLimit)) {\n if (lifesCounter == 0) {\n cout &lt;&lt; \"Game Over! Actual Answer: \" &lt;&lt; numberToGuess &lt;&lt; endl;\n return false;\n }\n }\n }\n return true;\n}\n\n\nint main() {\n srand(time(0));\n string playerNamer;\n int lifesCounter = 5;\n\n cout &lt;&lt; \"Hello, what is your name? \";\n cin &gt;&gt; playerNamer;\n cout &lt;&lt; \"Welcome to guess the number, \" &lt;&lt; playerNamer &lt;&lt; \"!\" &lt;&lt; endl;\n printSeperator();\n cout &lt;&lt; \"Number of lifes you have: \" &lt;&lt; lifesCounter &lt;&lt; endl;\n\n if (!playRounds(lifesCounter, 10)) {\n return 0;\n }\n lifesCounter += 5;\n cout &lt;&lt; \"You got more lifes! Now you have: \" &lt;&lt; lifesCounter &lt;&lt; endl;\n cout &lt;&lt; \"For the hard level, you have to guess a number from 15!\" &lt;&lt; endl;\n playRounds(lifesCounter, 15);\n return 0;\n}\n\n</code></pre>\n\n<hr>\n\n<p>P.S.: It's very hard to win when you have just 5 lifes for all 4 guesses. ¯\\_(ツ)_/¯</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T06:00:04.287", "Id": "466339", "Score": "1", "body": "Ill look into this later, thanks for the help! Oh and btw I changed the 5 lives thing to 10 while playing around with my program :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T01:52:21.140", "Id": "237770", "ParentId": "237755", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T19:11:13.577", "Id": "237755", "Score": "2", "Tags": [ "c++", "random" ], "Title": "Random Number Generator game" }
237755
<p>I have to prepare program that summing the digits of two given by user numbers and then give back the random number which is </p> <ul> <li>natural number</li> <li>the digit sum of this number is bigger then the digit sum of given by user numbers</li> </ul> <p>It's look like everything is ok but i dont know if it is just luck in random number generator or it's working well. Thank you for review.</p> <pre><code>import java.util.Random; import java.util.Scanner; public class Ex1 { public static void main(String[] args) { Random rnd = new Random(); Scanner scn = new Scanner(System.in); int sum1 = 0; int sum2 = 0; int sum3 = 0; int sum4 = 0; System.out.println("1TH NUMBER : "); int a1 = scn.nextInt(); System.out.println("2ND NUMBER : "); int a2 = scn.nextInt(); System.out.println((0 &gt; a1 || 0 &gt; a2 ? "ERROR-NEGATIVE NUMBER" : "OK")); while (a1 &gt; 0) { sum1 += a1 % 10; a1 /= 10; } //System.out.println(sum1); while (a2 &gt; 0) { sum2 += a2 % 10; a2 /= 10; } //System.out.println(sum2); int temp = sum1 + sum2; //temporary-for storage /= while (temp &gt; 0) { sum3 += (temp) % 10; (temp) /= 10; } // System.out.println(sum3); while (true) { int a3 = rnd.nextInt(Integer.MAX_VALUE); sum4 += (a3) % 10; (a3) /= 10; // System.out.println(sum4); if (sum4 &gt; sum3) { System.out.println(a3 + " this is my number"); break; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T21:21:18.957", "Id": "466321", "Score": "1", "body": "Could you provide some pairs of examples? (input -> expected output)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T21:42:27.453", "Id": "466323", "Score": "1", "body": "Ex1 : `Input: a1 = 222` - so digit sum = 6; `a2 = 333` - so digit sum = 9; sum of digits from a1 and a2= 15 = 1 + 5 = 6 so i expect the number with higher digit sum like `Output 4545` because 4+5+4+5 = 18 \nEx2 Input - `a1 - 23234` (digit sum= 14) `a2 - 454545`(digit sum=27), sum of digits a1+a2 = 14+27 = 41 = 4 + 1 = 5 `Output: a3=61= 6+1 = 7 ` (higher digit sum)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T21:47:12.803", "Id": "466324", "Score": "1", "body": "@AdamK I suggest that you edit your answer and add the inputs and outputs, that you gave, in a table / formatted." } ]
[ { "body": "<p>I have some suggestion for you.</p>\n\n<h3>Code duplication</h3>\n\n<p>In your code, you have some code duplication that can be extracted in a method. By extracting the code, the code will become shorter, be less error-prone and easier to read.</p>\n\n<ol>\n<li>I suggest that you make a method to print a question and read the user input. </li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n //[...]\n int a1 = askQuestionAndReceiveAnswer(scn, \"1TH NUMBER : \");\n int a2 = askQuestionAndReceiveAnswer(scn, \"2ND NUMBER : \");\n //[...]\n}\n\n\nprivate static int askQuestionAndReceiveAnswer(Scanner scn, String s) {\n System.out.println(s);\n return scn.nextInt();\n}\n</code></pre>\n\n<ol start=\"2\">\n<li>Since the logic is the same to handle the sum, you can extract both of the <code>while</code> into a method. This extraction will remove lots of code!</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>\npublic static void main(String[] args) {\n //[...]\n int sum1 = getSum(a1);\n int sum2 = getSum(a2);\n\n int temp = sum1 + sum2; //temporary-for storage /=\n\n int sum3 = getSum(temp);\n //[...]\n}\n\nprivate static int getSum(int userInput) {\n int currentSum = 0;\n while (userInput &gt; 0) {\n currentSum += userInput % 10;\n userInput /= 10;\n }\n return currentSum;\n}\n</code></pre>\n\n<h3>Other observations</h3>\n\n<ol>\n<li>In my opinion, I would extract the last calculation in a method and return the result.</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n //[...]\n int number = findNumber(rnd, sum3);\n System.out.println(number + \" this is my number\");\n //[...]\n}\n\nprivate static int findNumber(Random rnd, int sum3) {\n int sum4 = 0;\n while (true) {\n int a3 = rnd.nextInt(Integer.MAX_VALUE);\n sum4 += (a3) % 10;\n (a3) /= 10;\n if (sum4 &gt; sum3) {\n return a3;\n }\n }\n}\n</code></pre>\n\n<h3>Refactored code</h3>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n Random rnd = new Random();\n Scanner scn = new Scanner(System.in);\n\n int a1 = askQuestionAndReceiveAnswer(scn, \"1TH NUMBER : \");\n int a2 = askQuestionAndReceiveAnswer(scn, \"2ND NUMBER : \");\n System.out.println((0 &gt; a1 || 0 &gt; a2 ? \"ERROR-NEGATIVE NUMBER\" : \"OK\"));\n\n int sum1 = getSum(a1);\n int sum2 = getSum(a2);\n int temp = sum1 + sum2; //temporary-for storage /=\n\n int sum3 = getSum(temp);\n\n int number = findNumber(rnd, sum3);\n System.out.println(number + \" this is my number\");\n}\n\nprivate static int findNumber(Random rnd, int sum3) {\n int sum4 = 0;\n while (true) {\n int a3 = rnd.nextInt(Integer.MAX_VALUE);\n sum4 += (a3) % 10;\n (a3) /= 10;\n if (sum4 &gt; sum3) {\n return a3;\n }\n }\n}\n\nprivate static int getSum(int userInput) {\n int currentSum = 0;\n while (userInput &gt; 0) {\n currentSum += userInput % 10;\n userInput /= 10;\n }\n return currentSum;\n}\n\nprivate static int askQuestionAndReceiveAnswer(Scanner scn, String s) {\n System.out.println(s);\n return scn.nextInt();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T21:45:49.663", "Id": "237761", "ParentId": "237758", "Score": "3" } }, { "body": "<p>Welcome to Code Review, you are not closing the <code>Scanner</code> resource and this is a resource leak: to avoid this you can use from java 8 the construct <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try-with-resource</a> like below:</p>\n\n<pre><code>try (Scanner scn = new Scanner(System.in)) {\n //here your code\n}\n</code></pre>\n\n<p>You can write your line:</p>\n\n<blockquote>\n<pre><code>System.out.println((0 &gt; a1 || 0 &gt; a2 ? \"ERROR-NEGATIVE NUMBER\" : \"OK\"));\n</code></pre>\n</blockquote>\n\n<p>using <code>Math.min</code> in the following way:</p>\n\n<pre><code>System.out.println(Math.min(a1, a2) &lt; 0 ? \"ERROR-NEGATIVE NUMBER\" : \"OK\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T10:11:47.877", "Id": "237776", "ParentId": "237758", "Score": "0" } } ]
{ "AcceptedAnswerId": "237761", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T21:10:41.097", "Id": "237758", "Score": "3", "Tags": [ "java", "mathematics" ], "Title": "Digit sum loops+random positive number generator" }
237758
<p>I have backend project in which there's own "parent-to-all exception" exists, something like this (also I have InvalidArgumentException derived from this exception):</p> <pre><code>class CaliException extends \Exception { private $caliCode; public function __construct(string $message = "", string $caliCode = self::UNDEFINED_CODE, int $code = 0, Throwable $previous = null) { parent::__construct($message, $code, $previous); $this-&gt;caliCode = $caliCode; } function getCaliCode(): string { return $this-&gt;caliCode; } } </code></pre> <p>It's clear from code above, that purpose of custom class is ability to keep string codes. Why do I need string codes? Because I have HTTP API which works in the following way:</p> <ol> <li>Get JSON request</li> <li>Do something</li> <li>Produce JSON output with 'state' field which contains either code of a thrown exception or the "200" response. These state codes are quite useful for client which can distinguish different problems and react to them accordingly.</li> </ol> <p>So there's a problem. System above produces code like this:</p> <pre><code>class UsernameFormatException extends InvalidArgumentException { public const USERNAME_FORMAT_UNDEFINED_CODE = "DM:USERCA:0001"; public function __construct(string $message = "", string $calistoCode = self::USERNAME_FORMAT_UNDEFINED_CODE, int $code = 0, \Throwable $previous = null) { parent::__construct($message, $calistoCode, $code, $previous); } } class PasswordFormatException extends InvalidArgumentException { public const PASSWORD_FORMAT_UNDEFINED_CODE = "DM:USERCA:0002"; public function __construct(string $message = "", string $calistoCode = self::PASSWORD_FORMAT_UNDEFINED_CODE, int $code = 0, \Throwable $previous = null) { parent::__construct($message, $calistoCode, $code, $previous); } } class InvalidLastActivityTimestampException extends InvalidArgumentException { public const INVALID_TIMESTAMP = "DM:USERCA:0003"; public function __construct(string $message = "", string $calistoCode = self::INVALID_TIMESTAMP, int $code = 0, \Throwable $previous = null) { parent::__construct($message, $calistoCode, $code, $previous); } } class InvalidCreationTimestampException extends InvalidArgumentException { public const INVALID_TIMESTAMP = "DM:USERCA:0004"; public function __construct(string $message = "", string $calistoCode = self::INVALID_TIMESTAMP, int $code = 0, \Throwable $previous = null) { parent::__construct($message, $calistoCode, $code, $previous); } } </code></pre> <p>As seen, <strong>for each invalid-argument-case I create new <code>CaliException</code>-derived exception</strong>. I consider it as not cool. Is it good? How can I improve the code?</p> <p>Bonus question: I read that I should throw <code>\InvalidArgumentException</code> when it's a programmer's mistake, so an exception must be not caught. But in my code there's no <code>\InvalidArgumentException</code> only my own version of this. Is it acceptable in the context of best practices and so on? And how to distinguish when it's a programmer's mistake and when it's mistake of user (invalid user input)? (After all, any invalid values passed to a function are invalid <strong>inputs</strong> relatively to this function)</p>
[]
[ { "body": "<p>With regard to if you need multiple exceptions or not:<br>\nI'd argue not in this particular situation, multiple exceptions are great for if you want to do different logic to handle them(so you plan to catch <code>PasswordFormatException</code> because that needs to be handled differently to your other validation errors).</p>\n\n<p>To solve this you can add multiple constants on the same class if you want to return the code for what's invalid at the point you throw it:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>class CaliException extends \\Exception {\n const INVALID_USERNAME = \"DM:USERCA:0001\";\n const INVALID_PASSWORD = \"DM:USERCA:0002\";\n const INVALID_LAST_ACTIVITY_TIME = \"DM:USERCA:0003\";\n const INVALID_CREATION_TIME = \"DM:USERCA:0004\";\n\n private $caliCode;\n\n // Note that caliCode is now required, forcing you to pass in a constant\n // to say what the error is\n public function __construct(string $caliCode, string $message = \"\",\n int $code = 0, Throwable $previous = null) {\n parent::__construct($message, $code, $previous);\n\n $this-&gt;caliCode = $caliCode;\n }\n\n function getCaliCode(): string {\n return $this-&gt;caliCode;\n }\n}\n\n// ....\n// And then when you use it you now say it's a username or password field that failed validation\n\nthrow new CaliException(CaliException::INVALID_USERNAME, 'Username must not contain special characters');\n</code></pre>\n\n<p>As for if this should extend InvalidArgumentException:<br>\nI'd argue not, this feels more like you should have a class for UserInputValidationError or similar and extend this for your purpose. Failing validation of user input is not a fundamental problem with the program which InvalidArgumentException would imply but instead a natural consequence of having to handle user inputs.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T14:00:05.890", "Id": "237837", "ParentId": "237759", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T21:13:00.047", "Id": "237759", "Score": "4", "Tags": [ "php", "exception" ], "Title": "Custom exception for each invalid input value" }
237759
<p>I am looking for assistance in optimizing a partition method I wrote for a class. It does its job correctly, but I only received half points on it, so I was wondering if there was a way to make it more efficient?</p> <pre><code>private int runPartition(int lowIndex, int highIndex) { //Sets up pivot index and values int pivotIndex = lowIndex; int pivotValue = localArray[pivotIndex]; //Inner counter value int counterOne = highIndex + 1; //Loops through array from top down for (int counterTwo = highIndex; counterTwo &gt;= lowIndex; counterTwo--) { //If element is bigger than pivot, move to end if (localArray[counterTwo] &gt; pivotValue) { //Decrements inner counter and swaps values counterOne--; swapValuesAtIndex(counterTwo, counterOne); } } //At end, swap pivot value with value BEFORE larger elements counterOne--; swapValuesAtIndex(counterOne, pivotIndex); //Sets new pivot index and returns pivotIndex = counterOne; return pivotIndex; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T14:57:10.987", "Id": "466449", "Score": "0", "body": "When you say \"partition method\", can you specify exactly what you mean to avoid any potential confusion?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-27T09:21:21.480", "Id": "466813", "Score": "0", "body": "Yes - this method partitions the array around the top index in the array. For example, for an array of {3, 9, 6}, the number 6 would be the partition index, and the other items would be sorted so that the numbers equal to or less than 6 would come before it, and the numbers greater than 6 would come after it. This method is used in a quick sort method." } ]
[ { "body": "<p>I'm wondering if it is the efficiency that resulted in you getting half points:</p>\n\n<ul>\n<li><code>runPartition</code> is rather an unclear name in itself;</li>\n<li><code>highIndex</code> seems to be inclusive, which is uncommon (the number of elements is now <code>highIndex - lowIndex + 1</code>);</li>\n<li><code>counterOne</code> and <code>counterTwo</code> are not good names for <em>indices</em> - even <code>i</code> and <code>j</code> would have been better;</li>\n<li>it is very likely that the <code>localArray</code> as a field name raises some questions; why is it a field in the first place? And why is it called <code>local</code> if it is not local to the method?</li>\n<li>it seems to me that you would set the <code>counterOne</code> to the index you want to swap and perform the decrease <em>afterwards</em> (possibly using <code>--</code> in the call to <code>swapValues</code>);</li>\n<li>the braces are at uncommon and uneven positions when it comes to Java / indentation.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T22:58:51.267", "Id": "237763", "ParentId": "237762", "Score": "5" } } ]
{ "AcceptedAnswerId": "237763", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T22:31:33.180", "Id": "237762", "Score": "2", "Tags": [ "java" ], "Title": "Optimizing a Partition Method" }
237762
<p>I created this calculation algorithm, unfortunately, it works a little hard for more combinations. How should it be improved for faster operation?</p> <pre><code> Private Sub BttRemize_Click(sender As Object, e As EventArgs) Handles BttRemize.Click If CBRealTime.Checked = True Then Dim myProcess As System.Diagnostics.Process = System.Diagnostics.Process.GetCurrentProcess() myProcess.PriorityClass = System.Diagnostics.ProcessPriorityClass.RealTime ElseIf CBHigh.Checked = True Then Dim myProcess As System.Diagnostics.Process = System.Diagnostics.Process.GetCurrentProcess() myProcess.PriorityClass = System.Diagnostics.ProcessPriorityClass.High ElseIf CBAboveNormal.Checked = True Then Dim myProcess As System.Diagnostics.Process = System.Diagnostics.Process.GetCurrentProcess() myProcess.PriorityClass = System.Diagnostics.ProcessPriorityClass.AboveNormal ElseIf CBBelowNormal.Checked = True Then Dim myProcess As System.Diagnostics.Process = System.Diagnostics.Process.GetCurrentProcess() myProcess.PriorityClass = System.Diagnostics.ProcessPriorityClass.BelowNormal ElseIf CBNormal.Checked = True Then Dim myProcess As System.Diagnostics.Process = System.Diagnostics.Process.GetCurrentProcess() myProcess.PriorityClass = System.Diagnostics.ProcessPriorityClass.Normal ElseIf CBIdle.Checked = True Then Dim myProcess As System.Diagnostics.Process = System.Diagnostics.Process.GetCurrentProcess() myProcess.PriorityClass = System.Diagnostics.ProcessPriorityClass.Idle End If TxtMReadOnly.Clear() For i As Integer = 1 To 10 Try If TxtListScanValue.Text = 1 Then TxtDrawR1.AppendText(Environment.NewLine &amp; lastDraw1) End If Next Catch ex As Exception End Try End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T01:03:36.837", "Id": "466332", "Score": "3", "body": "As the title states and the content shows, this is VB.Net code. Could you please change the tag to reflect that? VBA and VB.Net are different languages." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T05:23:16.427", "Id": "466338", "Score": "0", "body": "sorry for mistake,I changed now with Algorithm, i don't work change with vb, i don't have reputation point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T15:23:53.843", "Id": "466355", "Score": "1", "body": "Welcome to code review! In the question can you please tell us what you mean by `it works a little hard for more combinations` and explain what is being calculated a little better so that we can understand the question better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T16:06:53.740", "Id": "466356", "Score": "0", "body": "should improve this code, display results faster. Do you think something can be done, or did I make the most of it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T05:25:23.400", "Id": "466402", "Score": "0", "body": "Why did you remove a large portion of the code?" } ]
[ { "body": "<p>The question indeed deserves clarification. That being said...</p>\n\n<p>Do you realize that by having an empty <code>catch</code> you are silently swallowing exceptions that may occur, thus making your code hard to debug ? Either remove all those <code>catch</code> or add some code that actually handles the exception. One catch for the whole procedure should suffice anyway.</p>\n\n<p>As for this loop:</p>\n\n<pre><code>For i As Integer = 1 To 10\n Try\n Dim txtRemove As TextBox = CType(Me.Controls(\"txtDrawR\" &amp; i.ToString), TextBox)\n txtRemove.Clear()\n Catch ex As Exception\n End Try\nNext\n</code></pre>\n\n<p>It could be expressed like this (a simple loop on the form's child controls):</p>\n\n<pre><code> For Each ctl As Control In Me.Controls\n If TypeOf ctl Is TextBox Then\n ' optionally\n If ctl.Name.StartsWith(\"txtDrawR\") Then\n DirectCast(ctl, TextBox).Clear()\n End If\n End If\n Next\n</code></pre>\n\n<p>This is more flexible and will work regardless of how many <code>txtDrawR</code> textboxes there are in your form (even if there is none).</p>\n\n<p>The <code>case</code> statement can surely be simplified by a loop, list or something similar.</p>\n\n<p>Progress bar Value and Maximum should be integer values eg. <code>ProgressBar1.Value = 0</code> instead of: <code>ProgressBar1.Value = (\"0\")</code>. Likewise: <code>ProgressBar1.Maximum = Convert.ToInt32(TxtCheckL.Text)</code> instead of: <code>ProgressBar1.Maximum = TxtCheckL.Text</code>\n<em>provided that you have validated TxtCheckL contains digits only</em> or an exception will occur. Instead of a textbox you could use a <a href=\"https://docs.microsoft.com/en-us/dotnet/framework/winforms/controls/numericupdown-control-overview-windows-forms\" rel=\"nofollow noreferrer\">spinner</a> or a similar control that will directly return an integer value based on user selection and requires less validation.</p>\n\n<p>This is pretty bad:</p>\n\n<pre><code>Dim tmp(10000) As String\n</code></pre>\n\n<p>Rather than working with large arrays you can instead use a <code>StringBuilder</code>, or perhaps a <code>List (Of String)</code>. But it's not clear to me why you are even doing this, why you have 10000 (how was that value chosen ?) lines to put in <code>TxtMReadOnly</code>, and then split the string. It doesn't look good in terms of performance.</p>\n\n<p>Note that if you want to iterate lines in a multi-line textbox you can simply do:</p>\n\n<pre><code>For Each s As String In Me.TextBox1.Lines \n ' do something\n console.writeline(s)\nNext \n</code></pre>\n\n<p>No need to do splitting once more.</p>\n\n<p>There is a lot that can be improved, but if you could explain the general purpose we may be able to help further.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T17:09:26.557", "Id": "237788", "ParentId": "237766", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T00:15:07.343", "Id": "237766", "Score": "-2", "Tags": [ "performance", "algorithm", "vb.net" ], "Title": "Calculate draws faster in VB.Net" }
237766
<p>I made a HTML script to quickly make a Dnd5 sheet.</p> <p>This was a project done in two weeks, I don't know what to say else except I'm learning JS, CSS and HTML. I would love to learn how to make this better. </p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang = "en-US"&gt; &lt;body&gt; &lt;h1&gt; DND5 Quick Sheet &lt;/h1&gt; &lt;l&gt;&lt;font size = "2"&gt; this is for a quick C&amp;P sheet, enter the details in the former prompts and you'll have it on the page, reload the page to change items. Please message me on &lt;a href="https://discordapp.com/"&gt;Discord&lt;/a&gt; if you see or have ANY problems. (---) &lt;/font&gt;&lt;/l&gt; &lt;small&gt; &lt;script language = "JavaScript"&gt; try{ var b = []; // the dialogue var c = []; // prompts and inputs var d = "&lt;br&gt;/#:"; var e = confirm("Click ok if you wish to make a sheet, clicking elsewhere will cancel this.") if(e == true) { for (var x = 0; x &lt; 23; ++x) { //plus one switch (x) { case 0: b[x] = "Username: "; c[x] = "What username?"; break; case 1: b[x] = "Name: "+d; c[x] = "Name of your character?"; break; case 2: b[x] = "Race: "; c[x] = "Their race?"; break; case 3: b[x] = "Level: "; c[x] = "Level? 1 to 20."; break; case 4: b[x] = "Exp: "; c[x] = "Experience total?"; break; case 5: b[x] = "Class: "; c[x] = "Their class?"; break; case 6: b[x] = "Subclasses: "; c[x] = "If any, Subclass / Subclasses?"; break; case 7: b[x] = "Alignment: "; c[x] = "Their alignment?"; break; case 8: b[x] = "Background: "+d; c[x] = "background?"; break; case 9: b[x] = "Hit dice: "; c[x] = "Their hit dice?"; break; case 10: b[x] = "Armor: "; c[x] = "If any, what armor?"; break; case 11: b[x] = "SPEED: "; c[x] = "Their speed?"; break; case 12: b[x] = "HP: "; c[x] = "Their HP?"; break; case 13: b[x] = "AC: "+d; c[x] = "Their AC total."; break; case 14: b[x] = "Strength: "; c[x] = "Strength, 4d6dl."; break; case 15: b[x] = "Dexterity: "; c[x] = "Dexterity?"; break; case 16: b[x] = "Constitution: "; c[x] = "Constitution?"; break; case 17: b[x] = "Intelligence: "; c[x] = "Intelligence?"; break; case 18: b[x] = "Wisdom: "; c[x] = "Wisdom?"; break; case 19: b[x] = "Charisma: "+d; c[x] = "Charisma?"; break; case 20: b[x] = "Inventory: "; c[x] = "Items held?"; break; case 21: b[x] = "Weapons: "; c[x] = "Wepons held?"; break; case 22: b[x] = "proficiency: "; c[x] = "Your Proficiencys? List bonus prof. tool prof. skill prof. weapons prof. armor prof."; break; } c[x] = prompt(c[x]); if(c[x] == null) continue; if(c[x].length &gt; 1256) throw "Long String Error. [CE1]&lt;br&gt;"; document.write("/#:", b[x]+c[x], "&lt;br&gt;"); } } } catch (err) { document.write("Attempt again. &lt;em&gt;[[UNKOWN ERROR] CE0] &lt;/em&gt;&lt;br&gt;"+err); } &lt;/script&gt; &lt;/small&gt; &lt;ul style="list-style-type:square;"&gt; &lt;l&gt;&lt;b&gt;&lt;font size = "2"&gt;Cedits&lt;/font&gt;&lt;br&gt;&lt;/b&gt;&lt;/l&gt; &lt;l&gt;&lt;font size = "1"&gt;&gt;--- Programmed This HTML Page&lt;br&gt;&lt;/l&gt; &lt;l&gt;--- Inspired This&lt;/font&gt;&lt;br&gt;&lt;/l&gt; &lt;l&gt;&lt;b&gt;&lt;font size = "2"&gt;Resources&lt;/font&gt;&lt;/b&gt;&lt;br&gt;&lt;/l&gt; &lt;l&gt;&lt;a href "https://stackoverflow.com/"&gt;stackoverflow.com&lt;/a&gt; &lt;br&gt;&lt;/l&gt; &lt;l&gt;&lt;a href "https://www.dndbeyond.com/"&gt;dndbeyond.com&lt;/a&gt; &lt;br&gt;&lt;/l&gt; &lt;/ul&gt; &lt;p&gt;&lt;font size = "1"&gt; Apps Used --- anWriter free - Js Run - duckduckgo --- on android&lt;br&gt; [305[111]]&lt;br&gt; THANK YOU FOR YOUR USAGE OF THIS &lt;br&gt; &lt;br&gt; DMY 8-2-2020 -- TILL NOW AND FOREVER &lt;/font&gt; &lt;p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T03:43:30.140", "Id": "237772", "Score": "1", "Tags": [ "javascript", "html5" ], "Title": "DND print script in HTML5" }
237772
<p>I have a common List in mind which looks something like this:</p> <p><a href="https://i.stack.imgur.com/VsQcq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VsQcq.png" alt="enter image description here"></a> </p> <p>it has one remove button</p> <p>one input in which user can enter the name of element and on clicking insert the element will be added in the list.</p> <p>For this i have added HOC like this:</p> <pre><code>function ListHOC(Component, data, listName, placeholder) { return class extends React.Component { constructor() { super(); this.state = { data, element: "" }; } add = item =&gt; { const { data } = this.state; data.push(item); this.setState({ data }); }; remove = keyToRemove =&gt; { const { data } = this.state; const newData = data.filter(({ key }) =&gt; keyToRemove !== key); this.setState({ data: newData }); }; render() { const { data, element } = this.state; const updatedList = data.map(({ name, key }) =&gt; ( &lt;div style={{ display: "flex" }} key={key}&gt; &lt;div&gt;{name}&lt;/div&gt; &lt;button onClick={() =&gt; this.remove(key)}&gt;remove&lt;/button&gt; &lt;/div&gt; )); return ( &lt;&gt; &lt;div&gt;{listName}: &lt;/div&gt; &lt;Component data={updatedList} {...this.props} /&gt; &lt;input placeholder={placeholder} onChange={e =&gt; this.setState({ element: e.target.value })} /&gt; &lt;button onClick={() =&gt; this.add({ name: element, key: data.length + 1 })} &gt; insert &lt;/button&gt; &lt;/&gt; ); } }; } </code></pre> <p>one thing i am not sure about is weather to use the <code>input</code> and <code>button</code> and listname inside HOC or not </p> <p>link to codepen: <a href="https://codepen.io/saxenanihal95/pen/NWKVJOx?editors=1010" rel="nofollow noreferrer">https://codepen.io/saxenanihal95/pen/NWKVJOx?editors=1010</a></p>
[]
[ { "body": "<p>There's no reason to use a HOC for this, it can be done more simply and clearly with a component:</p>\n\n<pre><code>class List extends React.Component {\n state = { data: this.props.initialData, element: \"\" };\n\n add = item =&gt; {\n this.setState(prev =&gt; ({ data: prev.data.concat(item) }));\n };\n\n remove = keyToRemove =&gt; {\n this.setState(prev =&gt; ({\n data: prev.data.filter(({ key }) =&gt; keyToRemove !== key)\n }));\n };\n\n render() {\n const { data, element } = this.state;\n const { placeholder, listName } = this.props;\n\n return (\n &lt;&gt;\n &lt;div&gt;{listName}: &lt;/div&gt;\n {data.map(({ name, key }) =&gt; (\n &lt;div style={{ display: \"flex\" }} key={key}&gt;\n &lt;div&gt;{name}&lt;/div&gt;\n &lt;button onClick={() =&gt; this.remove(key)}&gt;remove&lt;/button&gt;\n &lt;/div&gt;\n ))}\n &lt;input\n placeholder={placeholder}\n onChange={e =&gt; this.setState({ element: e.target.value })}\n /&gt;\n &lt;button\n onClick={() =&gt; this.add({ name: element, key: data.length + 1 })}\n &gt;\n insert\n &lt;/button&gt;\n &lt;/&gt;\n );\n }\n}\n\nconst Users = () =&gt; (\n &lt;List\n initialData={[\n { name: \"a\", key: 1 },\n { name: \"b\", key: 2 }\n ]}\n listName=\"Users\"\n placeholder=\"insert user\"\n /&gt;\n);\nconst Comments = () =&gt; (\n &lt;List initialData={[]} listName=\"Comments\" placeholder=\"insert comment\" /&gt;\n);\nconst AnotherList = () =&gt; &lt;Users /&gt;;\n\nfunction App() {\n return (\n &lt;div&gt;\n &lt;Users /&gt;\n &lt;Comments /&gt;\n &lt;AnotherList /&gt;\n &lt;/div&gt;\n );\n}\n\nReactDOM.render(&lt;App /&gt;, document.getElementById(\"app\"));\n</code></pre>\n\n<p>HOCs are generally better for cross-cutting concerns, or behavior (not presentation) which you want to add to any component. for example logging:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const withLogging = Component =&gt; props =&gt; {\n console.log('Props:', props);\n return &lt;Component {...props} /&gt;;\n}\n\nconst List = ({ name, data }) =&gt; ...\nconst ListWithLogging = withLogging(List); // &lt;-- This will log all props\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:30:59.980", "Id": "471511", "Score": "0", "body": "I have came across this blog: https://css-tricks.com/what-are-higher-order-components-in-react/ which is using search as common component \n\nso i got confused as you said we use HOC for behaviour(not presentation)\n\nplease help to understand this" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T18:03:38.717", "Id": "471542", "Score": "1", "body": "CSS-Tricks has some valuable resources, but I wouldn't consider the examples in that article the best use of HOCs. Take a look at the official React docs on HOCs (linked at the bottom of that article): https://reactjs.org/docs/higher-order-components.html - notice that none of those examples include any JSX in the HOC's `render` method other than the WrappedComponent. The HOCs in those examples are only used for behavioral/data concerns, not presentation. That said, you COULD use HOCs for presentation, but there are other patterns that would do it more clearly (like render props or hooks)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T03:27:11.070", "Id": "237816", "ParentId": "237773", "Score": "2" } } ]
{ "AcceptedAnswerId": "237816", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T05:04:28.730", "Id": "237773", "Score": "0", "Tags": [ "javascript", "react.js" ], "Title": "Using common code inside a Higher Order Component" }
237773
<p>I'm trying to solve <a href="https://leetcode.com/problems/wildcard-matching/" rel="nofollow noreferrer">Wildcard Matching</a> on Leetcode. I found <a href="https://leetcode.com/problems/wildcard-matching/discuss/138878/Finite-state-machine-with-Python-and-dictionary.-13-lines-O(p%2Bs)-time" rel="nofollow noreferrer">a great solution using the Finite-state machine</a>. The author builds an FSM and searches with BFS.</p> <p>I rewrite the solution with the same idea (FSM) but use DFS:</p> <pre class="lang-py prettyprint-override"><code>class Solution: def isMatch(self, s: str, p: str) -&gt; bool: # build the fsm fsm = {} state = 0 for i in range(len(p)): if p[i] == "*": # connect to state itself fsm[state, p[i]] = state else: fsm[state, p[i]] = state + 1 state += 1 self.accept = state self.fsm = fsm return self.dfs(s, idx=0, state=0) def dfs(self, s: str, idx: int, state: int) -&gt; bool: """deep first search through the finite state machine""" if idx == len(s): # processing string finished if state == self.accept: return True else: return False for value in [s[idx], "*", "?"]: if (state, value) not in self.fsm: # invaild state continue next_state = self.fsm[state, value] if self.dfs(s, idx + 1, next_state): return True return False </code></pre> <p>Since we need to iterate the whole string <code>s</code>, I think the time complexity of DFS and BFS are the same. However, I had the Time Limit Exceeded on the testing case:</p> <pre><code>"babbbbaabababaabbababaababaabbaabababbaaababbababaaaaaabbabaaaabababbabbababbbaaaababbbabbbbbbbbbbaabbb" "b**bb**a**bba*b**a*bbb**aba***babbb*aa****aabb*bbb***a" </code></pre> <ol> <li>Are the time complexity of DFS and BFS the same?</li> <li>Is there something wrong with my code?</li> </ol>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T11:19:22.647", "Id": "237777", "Score": "1", "Tags": [ "python", "algorithm", "time-limit-exceeded", "interview-questions" ], "Title": "Wildcard Matching with DFS and FSM" }
237777
<p>I am following a <a href="https://www.toptal.com/flask/flask-production-recipes" rel="nofollow noreferrer">guide</a> that specifies how to manage different configurations (DB_URI, LOGGER_NAME, etc...) per development environments.</p> <p>I create a <code>config</code> module that is structured like this</p> <p><code>\my_project\config\__init__.py</code></p> <pre><code>import os import sys from . import settings # create settings object corresponding to specified env APP_ENV = os.environ.get('APP_ENV', 'Dev') _current_config = vars(setting).get(f'{APP_ENV}Config') # copy attributes to the module for convenience for atr in [f for f in dir(_current_config) if '__' not in f]: # environment can override anything val = os.environ.get(atr, getattr(_current_config, atr)) setattr(sys.modules[__name__], atr, val) </code></pre> <p><code>\my_project\config\settings.py</code></p> <pre><code>class BaseConfig: DEBUG = True LOGGER_NAME = 'my_app' class DevConfig(BaseConfig): # In actuality calling a function that fetches a secret SQLALCHEMY_DATABASE_URI = 'sqlite://user.db' class ProductionConfig(BaseConfig): DEBUG = False # In actuality calling a function that fetches a secret SQLALCHEMY_DATABASE_URI = 'sqlite://user.db' </code></pre> <p>calling the config </p> <p><code>application.py</code></p> <pre><code>import config config.SQLALCHEMY_DATABASE_URI </code></pre> <p>This approach is kind of a hit and miss for me. on one hand it allows me to easily specify several environments (dev, stage, prod, dev) without having a complex <code>if else</code> logic in my <code>settings.py</code>.</p> <p>On the other hand I dont like using <code>setattr</code> on <code>sys.modules[__name__]</code>, seems a bit wonky to me. what do you think ?</p>
[]
[ { "body": "<p>Incase you are using Docker for deployment. The <strong>required environment variable</strong> can be configured as <strong>Kuberenetes configuration</strong> and it reads based on the deployment configuration environment. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T17:43:36.537", "Id": "466364", "Score": "2", "body": "Welcome to CodeReview@SE. Not all questions should be answered here, see [How do I write a Good Answer?](https://codereview.stackexchange.com/help/how-to-answer)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T10:13:54.337", "Id": "466419", "Score": "1", "body": "thanks for the help, but my question is about python configuration. As I dont use docker at the moment" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T17:12:22.730", "Id": "237789", "ParentId": "237783", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T16:22:35.767", "Id": "237783", "Score": "3", "Tags": [ "python", "meta-programming", "configuration" ], "Title": "config files for different development environments (Production, Dev, Testing)" }
237783
<p>I have implemented a java class for minHeap but it is not working as fast as I want . I want some help to change it to work faster in insertion or deleting the minimum node.</p> <p>Here is my implementation:</p> <pre><code>public class MinHeap { private static final int d = 2; private int heapSize; private long[] heap; MinHeap(int capacity) { heapSize = 0; heap = new long[capacity + 1]; Arrays.fill(heap, -1); } boolean isEmpty() { return heapSize == 0; } boolean isFull() { return heapSize == heap.length; } private int parent(int i) { return (i - 1) / d; } private int kthChild(int i, int k) { return d * i + k; } void insert(long x) { if (isFull()) throw new NoSuchElementException("Overflow Exception"); heap[heapSize++] = x; bubbleUp(heapSize - 1); } long findMin() { if (isEmpty()) throw new NoSuchElementException("Underflow Exception"); return heap[0]; } void deleteMin() { delete(0); } void delete(int ind) { if (isEmpty()) throw new NoSuchElementException("Underflow Exception"); heap[ind] = heap[heapSize - 1]; heapSize--; bubbleDown(ind); } private void bubbleUp(int childInd) { long tmp = heap[childInd]; while (childInd &gt; 0 &amp;&amp; tmp &lt; heap[parent(childInd)]) { heap[childInd] = heap[parent(childInd)]; childInd = parent(childInd); } heap[childInd] = tmp; } private void bubbleDown(int ind) { int child; long tmp = heap[ind]; while (kthChild(ind, 1) &lt; heapSize) { child = minChild(ind); if (heap[child] &lt; tmp) heap[ind] = heap[child]; else break; ind = child; } heap[ind] = tmp; } private int minChild(int ind) { int bestChild = kthChild(ind, 1); int k = 2; int pos = kthChild(ind, k); while ((k &lt;= d) &amp;&amp; (pos &lt; heapSize)) { if (heap[pos] &lt; heap[bestChild]) bestChild = pos; pos = kthChild(ind, k++); } return bestChild; } } </code></pre> <p>Thanks in advance for your help!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T17:28:15.180", "Id": "466360", "Score": "0", "body": "@greybeard Thanks for your comment, sorry I made a mistake, I had to delete the method maxElementIndex, It was related to the code I wrote for a special program, it is not in the minHeap implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T17:28:57.167", "Id": "466361", "Score": "1", "body": "Welcome to CodeReview@SE. How did you establish `minHeap [deleteMin() and insert() are] not working as fast as I want`? When in doubt, use a microbenchmarking framework. To check improvement suggestions, usage context, sample data or a test data generator would be useful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T17:39:24.867", "Id": "466363", "Score": "0", "body": "(What about [java.util.PriorityQueue](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/PriorityQueue.html)/[java.util.concurrent.PriorityBlockingQueue](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/concurrent/PriorityBlockingQueue.html)?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T07:02:31.927", "Id": "466405", "Score": "0", "body": "@greybeard I do not know what is the main problem, I'm implementing this for a homework assignment and I get two of the test cases as \"time limit exceeded\", I asked my teacher what is the reason and he said I can get a faster implementation of my minHeap. I have also tried PriorityQueue but still does not work:(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T08:51:54.313", "Id": "466409", "Score": "1", "body": "Welcome to CodeReview, as suggested by greybeard it would be useful posting here test cases (input and output) indicating which ones ended with time limit exceeded." } ]
[ { "body": "<p>Without more information <em>what</em>, when asked for a reason for two \"time limit exceeded\" results, motivated your teacher to mention the possibility to \"get\" a faster <em>minHeap</em>, you deprive yourself of getting more useful answers. See <a href=\"https://codereview.meta.stackexchange.com/q/2436\">How to get the best value out of Code Review - Asking Questions</a><br>\nFirst and foremost, just <em>what</em> is the task timed?<br>\nI can't see anything seriously detrimental in your implementation:<br>\nI guess a bigger task than, say, handle a batch of <em>insertions</em> and <em>min extractions</em> gets timed, in need of an algorithmic improvement more likely than any tuning.</p>\n\n<hr>\n\n<p>That said, there are principles like <em>YAGNI</em>, <em>KISS</em> and <em>DRY</em>.<br>\nLet me start with the bright side of <em>YAGNI</em> - You <em>Are</em> Gonna Need It:</p>\n\n<ul>\n<li>Documentation. The type that does <em>not</em> get separated from the code:<br>\n<a href=\"https://www.oracle.com/technetwork/java/javase/documentation/index-137868.html#styleguide\" rel=\"nofollow noreferrer\">Documentation <em>in</em> the code</a></li>\n</ul>\n\n<p>Otherwise, the code presented looks a pretty decent beginner's stab at coding a heap.<br>\nCatch: </p>\n\n<ul>\n<li>There are omissions from the <em>delete</em>s:<br>\n• <em>not relevant when using an array of primitives as presented in the question</em>:<br>\n Failing to set the reference at the index deallocated to something innocent (as <code>null</code>) does not immediately impede garbage collection, as it gets copied to a lower index. Enter the next <em>delete</em>…\n\n<ul>\n<li>bug in <code>delete(int d)</code>:<br>\nIt replaces element <code>atD</code> with <code>formerLast</code> and restores the heap relations in <code>formerLast</code> and its descendants.<br>\nBut what about its ancestors?<br>\nNot to worry <em>if</em><br>\n1) it ends up at an index abode <code>d</code> <em>or</em><br>\na) it was a descendant of <code>atD</code>: none of those has higher priority<br>\nThere are many ways to handle the situation -<br>\nI'd prefer just dropping <code>delete(int d)</code> over just calling <code>bubbleUp()</code> or some elaborate handling trying to keep the number of comparisons low.</li>\n</ul></li>\n</ul>\n\n<p>Room for improvement:</p>\n\n<ul>\n<li>Part of <em>Don't Repeat Yourself</em> is using interfaces:<br>\nDefine an <code>interface</code> for an, um, <code>PriorityCollection&lt;E&gt; extends Collection&lt;E&gt;</code>.<br>\nOne advantage is that implementations don't get to reduce visibility of interface methods like <code>isEmpty()</code>.<br>\nAnother is <em>inheriting</em> documentation, too.<br>\n• have an <code>E extractTop()</code> return the top priority element it just removed from the Collection<br>\n• nowadays, Java <code>interface</code>s can include <em>unit test code</em>, too. </li>\n<li><em>Keep It Short&amp;Simple</em> meets <em>You Ain't Gonna Need It</em> in fixing arity at 2:<br>\n• simpler/shorter code<br>\n• fixes a naming issue in <code>d</code> (maximal <em>d</em>egree?)<br>\n• maximises information in relative position of keys<br>\n• doesn't show in the interface, anyway </li>\n</ul>\n\n<hr>\n\n<p>If and when competent (&rarr; framework) measurements suggest the performance being a problem,<br>\n• consider returning to an array of <em>primitives</em>.<br>\n• <em>If</em> the cost of comparing elements is high, change tactics in <em>bubbleDown</em>(sink?): find the path along which to sink/bubble down, and look for elements that should stay in place starting from the bottom: this may almost half the number of comparisons.<br>\n• an <code>E replaceTop(E replacement)</code> may save considerable work<br>\n  it may be useful to additionally have the similar <code>E addAndExtractTop(E addition)</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T00:30:13.420", "Id": "237865", "ParentId": "237787", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T17:05:02.493", "Id": "237787", "Score": "2", "Tags": [ "java", "performance", "homework", "heap" ], "Title": "Optimizing minHeap implementation" }
237787
<p>I have written this Rust code to implement the quick sort algorithm. Could you review it and tell me if it is idiomatic or not? Especially about my use of the slices?</p> <pre class="lang-rust prettyprint-override"><code>fn quick_sort&lt;T: Ord&gt;(array: &amp;mut [T]) { let n = array.len(); if n &gt; 0 { let mut i_pivot = 0; for i in 1..n { if &amp;array[i] &lt; &amp;array[n - 1] { array.swap(i, i_pivot); i_pivot += 1; } } array.swap(i_pivot, n - 1); quick_sort(&amp;mut array[0..i_pivot]); quick_sort(&amp;mut array[i_pivot + 1..n]); } } fn main() { // Fixed-size array (type signature is superfluous) let mut xs = [ 8, 13, 20, 13, 4, 21, 24, 13, 18, 23, 14, 6, 10, 2, 4, 6, 16, 6, 17, 9, 8, 20, 14, 19, 7, 9, 18, 0, 18, 1, 8, 10, ]; quick_sort(&amp;mut xs); println!("{:?}", xs); } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T17:53:01.903", "Id": "466365", "Score": "0", "body": "(Positive you want to sort arrays of len 1 recursively?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T18:58:38.163", "Id": "466367", "Score": "0", "body": "Oh, right, it would be better with `if n > 1` ! Thanks @greybeard" } ]
[ { "body": "<p>Code review:<br>\n1. Your code has a bug here <code>for i in 1..n</code>,<br>\nthe correct version starts from <strong>zero</strong>: <code>for i in 0..n</code>,<br>\nChange your main to the following code and then <code>cargo run</code>:</p>\n\n<pre><code>fn main() {\n let mut xs = vec![\n 8, 13, 20, 13, 4, 21, 24, 13, 18, 23, 14, 6, 10, 2, 4, 6, 16, 6, 17, 9, 8, 20, 14, 19, 7,\n 9, 18, 0, 18, 1, 8, 10,\n ];\n let mut v = xs.clone();\n v.sort();\n quick_sort(&amp;mut xs);\n assert_eq!(v, xs);\n}\n</code></pre>\n\n<p>You will see this error:</p>\n\n<pre><code>thread 'main' panicked at 'assertion failed: `(left == right)`\n left: `[0, 1, 2, 4, 4, 6, 6, 6, 7, 8, 8, 8, 9, 9, 10, 10, 13, 13, 13, 14, 14, 16, 17, 18, 18, 18, 19, 20, 20, 21, 23, 24]`,\n right: `[0, 1, 2, 4, 6, 6, 7, 6, 8, 4, 8, 9, 9, 10, 10, 8, 13, 13, 14, 14, 16, 17, 18, 18, 18, 19, 20, 20, 13, 23, 24, 21]`', src/main.rs:25:5\n</code></pre>\n\n<ol start=\"2\">\n<li><p>Rename <code>i_pivot</code> to <code>j</code>, since it is just an index and your pivot is <code>a[n - 1]</code>.</p></li>\n<li><p>Change <code>if n &gt; 0</code> to <code>if n &gt; 1</code> since the slice length should be at least <strong>two</strong>.</p></li>\n<li><p>You don't need <code>Ord</code> here, <a href=\"https://doc.rust-lang.org/std/cmp/trait.PartialOrd.html\" rel=\"nofollow noreferrer\"><code>PartialOrd</code></a> is enough (<a href=\"https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=7ad1c81d319d1c3c4d5a2715f3d75569\" rel=\"nofollow noreferrer\">try it here</a>):</p></li>\n</ol>\n\n<pre><code>fn quick_sort&lt;T: PartialOrd&gt;(a: &amp;mut [T]) {\n let n = a.len();\n if n &gt; 1 {\n let mut j = 0;\n for i in 0..n {\n if &amp;a[i] &lt; &amp;a[n - 1] {\n a.swap(i, j);\n j += 1;\n }\n }\n a.swap(j, n - 1); // pivot\n quick_sort(&amp;mut a[0..j]);\n quick_sort(&amp;mut a[j + 1..n]);\n }\n}\n\nfn main() {\n let mut xs = vec![\n 8, 13, 20, 13, 4, 21, 24, 13, 18, 23, 14, 6, 10, 2, 4, 6, 16, 6, 17, 9, 8, 20, 14, 19, 7,\n 9, 18, 0, 18, 1, 8, 10,\n ];\n let mut v = xs.clone();\n v.sort();\n quick_sort(&amp;mut xs);\n assert_eq!(v, xs);\n}\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-28T16:53:50.457", "Id": "238120", "ParentId": "237790", "Score": "1" } } ]
{ "AcceptedAnswerId": "238120", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T17:47:59.340", "Id": "237790", "Score": "2", "Tags": [ "rust", "quick-sort" ], "Title": "Quick sort algorithm in Rust" }
237790
<p>I've written some code that will take multiple stock tickers and calculate their returns over yearly, monthly, bi-weekly, and weekly holding periods. The results are written to an xlsx file.</p> <p>I'm seeking commentary on any general best-practices I've missed, or any possible simplifications. In particular, I feel like the to_excel function is over-complicated. Also, I'm unsure whether my application of functions is excessive or incorrect.</p> <p>Let me know if I can help, and thanks in advance!</p> <pre class="lang-py prettyprint-override"><code>import yfinance as yf import pandas as pd from openpyxl import load_workbook import time import datetime import os Tickers = ['MSFT','AMZN'] ReturnPeriods = ['Yearly','Monthly', 'BiWeekly', 'Weekly'] def ticker_hist (Ticker): """ returns pandas dataframe containing yahoo finance history for given ticker """ ticker = yf.Ticker(Ticker) df = ticker.history(period="max") df.insert(0, 'Ticker', Ticker) return df def derive_columns(df): """ derives columns needed for performance attribution """ df['DateTime'] = pd.to_datetime(df.index) df['day_of_week'] = df['DateTime'].dt.day_name() df['DivCumSum'] = df.Dividends.cumsum() return df def date_framing(df, window): """ Filters dataframe for date ranges of interest """ if window == 'Weekly': df = df[df.day_of_week == 'Thursday'] df = df.sort_values(by='Date', ascending=False) elif window == 'BiWeekly': df = df[df.day_of_week == 'Thursday'] df = df.sort_values(by='Date', ascending=False) df = df.loc[::2, :] # only get paid every other Thursday elif window == 'Monthly': df = df.groupby([df.index.year, df.index.month]).tail(1) df = df.sort_values(by='Date', ascending=False) elif window == 'Yearly': df = df.groupby([df.index.year]).tail(1) df = df.sort_values(by='Date', ascending=False) else: raise ValueError('Enter a valid return period.') df.insert(1, 'ReturnPeriod', window) return df def attribution_cols (df): """ Returns performance attribution calcs """ df['PrevClose'] = df['Close'].shift(-1) df['DeltaDividend'] = df['DivCumSum'] - df['DivCumSum'].shift(-1) df['DeltaPrice'] = df['Close'] - df['PrevClose'] df['Delta'] = df['DeltaPrice'] + df['DeltaDividend'] df['Return'] = df['Delta'] / df['PrevClose'] * 100 return df def to_excel(df): """ Writes results to spreadsheet """ master_file = "Investments" + time.strftime("%Y%m%d") + ".xlsx" if os.path.exists(master_file): book = load_workbook(master_file) writer = pd.ExcelWriter(master_file, engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) startrow = book.worksheets[0].max_row df.to_excel(writer, "Return", startrow=startrow, header=False) else: df.to_excel(master_file, sheet_name="Return") return def main(Ticker, ReturnPeriod): df = ticker_hist(Ticker) df = derive_columns(df) df = date_framing(df, ReturnPeriod) df = attribution_cols(df) df = df.drop(columns=['Open','Volume','High','Low','day_of_week','Dividends', 'Stock Splits', 'DateTime', 'DivCumSum']) to_excel(df) return for Ticker in Tickers: for ReturnPeriod in ReturnPeriods: main(Ticker, ReturnPeriod) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T18:13:07.973", "Id": "237792", "Score": "4", "Tags": [ "python", "python-3.x", "pandas", "finance" ], "Title": "Get Asset Returns for multiple Tickers and Holding Periods" }
237792
<p>Recently i added such generic list in github and i would like to get some feedback.</p> <p>Here is a link to the code in github:</p> <p><a href="https://github.com/MartinChekurov/Generic-Linked-List" rel="noreferrer">https://github.com/MartinChekurov/Generic-Linked-List</a></p> <p><strong>GenericList.c</strong></p> <pre><code>#include "GenericList.h" typedef struct GenListNode_t { void* data; struct GenListNode_t* pNext; }GenListNode; struct GenList_t { GenListNode* head; Compare cmp; unsigned int dataSize; unsigned int count; }; static GenListError genListCopyNodeData(void* data, unsigned int dataSize, void* buf, unsigned int bufSize) { unsigned int cSize = 0; if (!data || !buf) { return GEN_LIST_WRONG_PAR; } cSize = bufSize &lt; dataSize ? bufSize : dataSize; memcpy(buf, data, cSize); return GEN_LIST_NO_ERR; } static GenListNode* genLisNewNode(void* data, unsigned int dataSize) { GenListNode* node = NULL; if (!data) { return NULL; } node = malloc(sizeof(*node)); if (!node) { return NULL; } memset(node, 0, sizeof(*node)); node-&gt;data = malloc(dataSize); if (!node-&gt;data) { return NULL; } memcpy(node-&gt;data, data, dataSize); return node; } static GenListError genListDestroyNode(GenListNode* node) { if (!node) { return GEN_LIST_WRONG_PAR; } free(node-&gt;data); free(node); return GEN_LIST_NO_ERR; } GenList* genListNew(unsigned int dataSize, Compare cmp) { GenList* list = NULL; list = malloc(sizeof(*list)); if (!list) { return NULL; } memset(list, 0, sizeof(*list)); list-&gt;dataSize = dataSize; if (cmp) { list-&gt;cmp = cmp; } return list; } GenListError genListPushHead(GenList* list, void* data) { GenListNode* node = NULL; if (!list || !data) { return GEN_LIST_WRONG_PAR; } if (list-&gt;count == UINT_MAX) { return GEN_LIST_FULL; } node = genLisNewNode(data, list-&gt;dataSize); if (!node) { return GEN_LIST_NO_MEMORY; } node-&gt;pNext = list-&gt;head; list-&gt;head = node; list-&gt;count++; return GEN_LIST_NO_ERR; } GenListError genListPopHead(GenList* list, void* buf, unsigned int size) { GenListNode* node = NULL; GenListError status = GEN_LIST_NO_ERR; if (!list) { return GEN_LIST_WRONG_PAR; } if (list-&gt;head) { node = list-&gt;head; list-&gt;head = node-&gt;pNext; status = genListCopyNodeData(node-&gt;data, list-&gt;dataSize, buf, size); if (status != GEN_LIST_NO_ERR) { return status; } genListDestroyNode(node); if (list-&gt;count) list-&gt;count--; } return GEN_LIST_NO_ERR; } GenListError genListGetIndex(GenList* list, unsigned int index, void* buf, unsigned int size) { GenListNode* node = NULL; unsigned int count = 0; if (!list) { return GEN_LIST_WRONG_PAR; } node = list-&gt;head; while(node &amp;&amp; count &lt; list-&gt;count) { if (count == index) { return genListCopyNodeData(node-&gt;data, list-&gt;dataSize, buf, size); } node = node-&gt;pNext; count++; } return GEN_LIST_ERROR; } GenListError genListSearchNode(GenList* list, void* data, void* buf, unsigned int size) { GenListNode* node = NULL; GenListError status = GEN_LIST_NO_ERR; if (!list || !data || !buf) { return GEN_LIST_WRONG_PAR; } node = list-&gt;head; while(node) { if (list-&gt;cmp) { status = list-&gt;cmp(node-&gt;data, data); if (status == GEN_LIST_MATCH) { return genListCopyNodeData(node-&gt;data, list-&gt;dataSize, buf, size); } } node = node-&gt;pNext; } return GEN_LIST_ERROR; } GenListError genListDestroy(GenList* list) { GenListNode* node = NULL; GenListError status = GEN_LIST_NO_ERR; if (!list) { return GEN_LIST_WRONG_PAR; } while(list-&gt;head) { node = list-&gt;head; list-&gt;head = node-&gt;pNext; status = genListDestroyNode(node); if (status != GEN_LIST_NO_ERR) { return status; } } free(list); return GEN_LIST_NO_ERR; } GenListError genListGetSize(GenList* list, unsigned int *size) { if (!list || !size) { return GEN_LIST_WRONG_PAR; } *size = list-&gt;count; return GEN_LIST_NO_ERR; } </code></pre> <p><strong>GenericList.h</strong></p> <pre><code>/* * Author: Martin Chekurov */ #ifndef GEN_LIST_H_ #define GEN_LIST_H_ #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;limits.h&gt; typedef enum { GEN_LIST_NO_ERR, GEN_LIST_WRONG_PAR, GEN_LIST_NO_MEMORY, GEN_LIST_MATCH, GEN_LIST_NO_MATCH, GEN_LIST_FULL, GEN_LIST_ERROR }GenListError; typedef GenListError (*Compare)(void*, void*); typedef struct GenList_t GenList; GenList* genListNew (unsigned int dataSize, Compare cmp); GenListError genListDestroy (GenList* list); GenListError genListPushHead (GenList* list, void* data); GenListError genListPopHead (GenList* list, void* buf, unsigned int size); GenListError genListSearchNode(GenList* list, void* data, void* buf, unsigned int size); GenListError genListGetSize (GenList* list, unsigned int *size); GenListError genListGetIndex (GenList* list, unsigned int index, void* buf, unsigned int size); #endif </code></pre> <p><strong>Test.c</strong> </p> <pre><code>#include"GenericList.h" #include&lt;stdio.h&gt; #define MAX_NODES (5) GenListError compare(void* dataIn, void* dataOut) { return *(int*)dataIn == *(int*)dataOut ? GEN_LIST_MATCH : GEN_LIST_NO_MATCH; } int main(void) { GenListError status = GEN_LIST_NO_ERR; GenList* list = NULL; unsigned int buf[MAX_NODES] = {1, 2, 3, 4, 5}; unsigned int i = 0, size = 0, value = 0; printf("\nInitialize the list."); list = genListNew(sizeof(int), compare); if (!list) { printf("\ngenListNew failed."); return 1; } printf("\nPush %d nodes:", MAX_NODES); for (i = 0 ; i &lt; MAX_NODES ; i++) { printf("\nPush value: %d.", buf[i]); status = genListPushHead(list, &amp;buf[i]); if (status != GEN_LIST_NO_ERR) { printf("\ngenListPushHead() error: %d", (int)status); return 1; } } for (i = 0 ; i &lt; MAX_NODES ; i++) { printf("\nGet value on index %d.", i); status = genListGetIndex(list, i, &amp;value, sizeof(int)); if (status != GEN_LIST_NO_ERR) { printf("\ngenListGetIndex() error: %d", (int)status); return 1; } printf("\nGot value: %d.", value); } status = genListGetSize(list, &amp;size); if (status != GEN_LIST_NO_ERR) { printf("\ngenListGetSize() error: %d", (int)status); return 1; } printf("\nPushed %d nodes.", size); for (i = 0 ; i &lt; MAX_NODES ; i++) { printf("\nFind value: %d.", buf[i]); status = genListSearchNode(list, &amp;buf[i], &amp;value, sizeof(int)); if (status != GEN_LIST_NO_ERR) { printf("\ngenListSearchNode() error: %d", (int)status); return 1; } printf("\nFound value: %d.", value); } for (i = 0 ; i &lt; MAX_NODES ; i++) { printf("\nPop a value from the list."); status = genListPopHead(list, &amp;value, sizeof(int)); if (status != GEN_LIST_NO_ERR) { printf("\ngenListPopHead() error: %d", (int)status); return 1; } printf("\nPoped value: %d.", value); status = genListGetSize(list, &amp;size); if (status != GEN_LIST_NO_ERR) { printf("\ngenListGetSize() error: %d", (int)status); return 1; } printf("\nValues left: %d.", size); } printf("\nDestroy the list."); status = genListDestroy(list); if (status != GEN_LIST_NO_ERR) { printf("\ngenListDestroy() error: %d", (int)status); return 1; } printf("\nDone."); getchar(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T19:13:53.237", "Id": "466370", "Score": "1", "body": "For future reference, it is better to add the test case so that we can see how the code is used. I've already done this for the current question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T06:21:05.860", "Id": "466404", "Score": "0", "body": "**tldr**; \"function names should be lowercase, with words separated by underscores as necessary to improve readability\". From [GTK+ coding convention](https://stackoverflow.com/a/1722518/307454), point 3 recommends [snake_case](https://en.wikipedia.org/wiki/Snake_case) for function names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T16:59:46.880", "Id": "466467", "Score": "4", "body": "@lifebalance OP hasn't mentioned this has anything to do with GTK+." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T02:35:49.053", "Id": "466524", "Score": "0", "body": "@Pod my reference to GTK+ was merely as an example for accepted naming conventions." } ]
[ { "body": "<h2>GenericList.h and GenericList.c</h2>\n<p>Generally this is excellent code as long as it is a stack you want. It seems that what is created is really a generic stack implemented on a linked list rather than a generic linked list. If it was truly a generic linked list there would also be an append function and the delete node function would have to be smart enough to reset the next pointer of the previous node to the node being deleted next node.</p>\n<p>Good things are that <code>GenericList.h</code> has include guards, <code>malloc()</code> is used properly and the return value is tested, I don't see any memory leaks.</p>\n<p>A possible issue with <code>GenericList.h</code> is that all the includes that are required by <code>GenericList.c</code> are included in <code>GenericList.h</code> and those include files are not needed by <code>Test.c</code>.</p>\n<p><code>GenericList.c</code> is well designed and implemented, all the functions are well designed and implemented.</p>\n<h2>Test.c</h2>\n<p>I realize that this is just a test file, but the same care that was given to <code>GenericList.h</code> and <code>GenericList.c</code> should be given to the test code as well.</p>\n<p>The <code>main()</code> function is too complex (does too much) and should be broken up into multiple functions (each loop should probably be a function). As it stands it would be very difficult to expand the functionality of the test code if additional functionality was added to <code>GenericList.h</code> and <code>GenericList.c</code>.</p>\n<p>Rather than return <code>0</code> or <code>1</code> for the program status, it would be better to include <code>&lt;stdlib.h&gt;</code> in main and utilize the <code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code> symbolic constants.</p>\n<p>One other issue I see in <code>Test.c</code> is that it can use some blank lines for vertical spacing between the tests, this wouldn't be necessary if the tests were functions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T19:57:23.437", "Id": "237797", "ParentId": "237794", "Score": "8" } }, { "body": "<ul>\n<li>It reads like <code>list.cmp</code> is required to be initialized, otherwise <code>genListSearchNode</code> is not meaningful. In that case, I would suggest checking <code>cmp</code>'s value in function <code>genListNew</code>. If it is null, return a null ptr. Then in function <code>genListSearchNode</code>, we could have checked <code>list-&gt;cmp</code> as part of the parameter validations; exit early if <code>list-&gt;cmp</code> is <code>null</code>. </li>\n<li>you may consider to include a <code>copy function</code> for node's data. Currently, the code is doing a shallow copy via <code>memcpy</code>. </li>\n<li>In function <code>genListPopHead</code>, it sets <code>list-&gt;head = node-&gt;pNext</code> before <code>genListCopyNodeData</code> succeeds. If <code>genListCopyNodeData</code> fails then the list is mutated unintendedly. I would suggest swap the order so that make a copy first then change <code>list-&gt;head</code>. Also you would want to check <code>if(buf)</code> in this function. </li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T20:11:53.557", "Id": "237798", "ParentId": "237794", "Score": "5" } }, { "body": "<p>Your test code may cover all the main code, but it has a huge drawback. It won't fail if you make a programming mistake in the main code.</p>\n\n<p>Instead of printing the values from the list, you should rather <code>assert</code> that they are exactly what you expect.</p>\n\n<p>Instead of writing the boring <code>if (status != GEN_LIST_NO_ERR)</code> each time again, you should extract that code into a separate function.</p>\n\n<p>In the type <code>GenListError</code> you are mixing programming errors and runtime errors. I would rather fail fast on any programming mistake and <code>abort()</code> the program. This is the nicest variant of <em>undefined behavior</em> that you can give to the users of your code since it forces them to fix their mistakes early and well.</p>\n\n<p>If you include programming mistakes in the API of your generic list, it will bloat the caller's code since it has to check whether the call succeeded, failed expectedly (\"no match\") or was aborted by a programming error. If the caller checks only for success or failure, programming errors might silently be interpreted as either of these, which would have unpredictable consequences.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T20:48:22.107", "Id": "237799", "ParentId": "237794", "Score": "5" } }, { "body": "<p>High level comment: you have chosen your list to own its data (as you allocate/free the data behind list elements inside this code) but without compile-time checking of the type of the data being fed to it.</p>\n\n<p>Now this is actually fine if the user code is very careful with the data pointers and size inputs.\nBut that is an assumption that you might not <em>want</em> to make.\nFurthermore, constant allocation/deallocation is somewhat wasteful, and copying the underlying data around on every input/output operation isn't something I'd expect to be necessary most of the time.\nIn short, it looks like a generic Java list, minus type checking.</p>\n\n<p>C isn't the best language for this sort of thing, but there are better ways even in pure C.\nFirst, consider if your use-case could do with a list which doesn't actually contain anything other than the concept of things which are in a certain order. Instead of copying your data into the list elements, make a mapping between your data owned by some other object (typically an array) and the list elements. This is trivial if your list has a sane bound on the maximum number of elements, not so much otherwise. If your list isn't used to pass things around between different parts of the code (i.e. your list type doesn't show up in high level interfaces), then I would recommend going with this \"light\" variant. Incidentally, this is how lists are usually implemented in baremetal code because it means you can get rid of dynamic allocation.</p>\n\n<p>Second point, the use of void* as a pointer to something with non-zero size is obviously not very safe.\nIf your list doesn't cross library boundaries, you can write function-like preprocessor macros with type names as argument to generate the exact function variants you need for every data type which you'll use your list with.\nIt's ugly and no code analysis tool on earth with like it, but this way you can get type checking (and not have to ask for the size of the data when allocating).</p>\n\n<p>Finally, some small scale comments:</p>\n\n<ul>\n<li>At the very least add some text explaining how to use your code in the documentation block at the top of the header file. Better also put in there the things that the user has to pay attention to in order to not have the whole thing break horribly (i.e. your assumptions about your input).</li>\n<li>If you use malloc then memset then it is always preferable to go straight for calloc. Actually, better always use calloc unless there's a demonstrable performance issue with it.</li>\n<li>Use const whenever you can, except when it's meaningless such as the exterior type of a function parameter in a function declaration. Users will thank you. Yourself will thank you because const prevents you from writing nonsense.</li>\n<li>Don't declare variables until you can give them a meaningful value (and ideally almost always their <em>final</em> value, see the const thing above). All that</li>\n</ul>\n\n<pre><code>GenListNode* node = NULL;\n</code></pre>\n\n<p>is achieving is to placate the compiler, without actually protecting you against using node before it is set to a good value. In cases such as these it's actually better to leave it uninitialized as then the compiler will figure out cases such as:</p>\n\n<pre><code>int i;\nif(somebool) { i = 0; } else { i = 1; }\n</code></pre>\n\n<p>without complaining.</p>\n\n<ul>\n<li>In the same spirit, don't re-use allocated variables for different purposes. Allocate your for loop counters inside the for loop initialization statement (actually, minimize the scope of your variables in general).</li>\n<li>Don't omit braces after control flow statements. It's just too easy to make a mistake when refactoring code such as</li>\n</ul>\n\n<pre><code>if (list-&gt;count)\n list-&gt;count--;\n</code></pre>\n\n<ul>\n<li>The standard type to use when a value is semantically the size of an object in bytes is <code>size_t</code>. It is effectively an unsigned int in most cases.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T16:04:38.157", "Id": "237846", "ParentId": "237794", "Score": "6" } }, { "body": "<p><strong>Consistent Naming</strong></p>\n\n<p>Code naming is unnecessarily different</p>\n\n<p>Files are <code>GenericList.*</code><br>\nFunctions <code>genList*</code><br>\nTypes <code>GenList*</code><br>\nEnums <code>GEN_LIST_*</code></p>\n\n<p>Consider a common <code>GenList_</code>, <code>GENLIST_</code></p>\n\n<p><strong>Sizes best as <code>size_t</code></strong></p>\n\n<pre><code>// unsigned int dataSize;\nsize_t dataSize;\n\n// GenList *genListNew(unsigned int dataSize, Compare cmp);\nGenList *genListNew(size_t dataSize, Compare cmp);\n// and various other functions\n</code></pre>\n\n<p><strong>Save formatting time</strong></p>\n\n<p>Below code hints that automatic formatting is not used. Improve productivity and consistency. Use an auto formatter. Life is too short for manual formatting.</p>\n\n<pre><code>struct GenList_t {\n\n\nstatic GenListError genListCopyNodeData(void* data, unsigned int dataSize, void* buf, unsigned int bufSize)\n{\n</code></pre>\n\n<p><strong><a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRYer</a> code</strong></p>\n\n<pre><code>// GenList* list = NULL;\n// list = malloc(sizeof(*list));\nGenList* list = malloc(sizeof *list);\n</code></pre>\n\n<p><strong>How many enumerations?</strong></p>\n\n<p>Sometimes it is useful to know how many enumerations exist. Consider a last <code>xxx_N</code> one.</p>\n\n<pre><code>typedef enum {\n GEN_LIST_NO_ERR,\n GEN_LIST_WRONG_PAR,\n GEN_LIST_NO_MEMORY,\n GEN_LIST_MATCH,\n GEN_LIST_NO_MATCH,\n GEN_LIST_FULL,\n GEN_LIST_ERROR,\n GEN_LIST_N // Add this one\n} GenListError;\n\nif (error &lt; 0 || error &gt;= GEN_LIST_N) Whoa_Handle_Errant_error_Code();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T16:40:28.870", "Id": "237917", "ParentId": "237794", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T18:57:12.377", "Id": "237794", "Score": "9", "Tags": [ "c", "linked-list", "generics" ], "Title": "Generic linked list implemented in pure C" }
237794
<p>I am trying to learn to implement DSs in C++ and here is a simple implementation. Please review in terms of optimization, memory management, coding standards, etc</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;iostream&gt; class BstNode{ int data; BstNode* left; BstNode* right; public: BstNode(int data) { this-&gt;data = data; this-&gt;left = NULL; this-&gt;right = NULL; } ~BstNode(); void Insert(int data) { if(this-&gt;data &gt;= data) { if (this-&gt;left == NULL) this-&gt;left = new BstNode(data); else this-&gt;left-&gt;Insert(data); } else { if (this-&gt;right == NULL) this-&gt;right = new BstNode(data); else this-&gt;right-&gt;Insert(data); } } bool Search(int data) { if(this-&gt;data == data) return true; else if(this-&gt;data &gt;= data) { if(this-&gt;left == NULL) return false; else return this-&gt;left-&gt;Search(data); } else { if(this-&gt;right == NULL) return false; else return this-&gt;right-&gt;Search(data); } } }; int main() { BstNode* ptr_root = new BstNode(15); ptr_root-&gt;Insert(10); ptr_root-&gt;Insert(16); int num; std::cout&lt;&lt;"Enter the number: \n"; std::cin&gt;&gt; num; if (ptr_root-&gt;Search(num)) std::cout&lt;&lt;"Found\n"; else std::cout&lt;&lt;"Not Found\n"; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T22:04:45.030", "Id": "466380", "Score": "0", "body": "The code in search is broken for a number of reasons. This question is off-topic because it can't work in many situations. You might want to enable warning messages in your compile, the warning I got was `'BstNode::Search': not all control paths return a value`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T22:13:38.940", "Id": "466382", "Score": "0", "body": "@pacmaninbw I used onlineGDB and it compiled without any issues. Can you please tell what you're using so that I can try to reproduce the error?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T22:15:08.070", "Id": "466383", "Score": "0", "body": "I'm using Visual Studio 2019 installed locally on my computer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T22:52:10.100", "Id": "466386", "Score": "0", "body": "@pacmaninbw corrected the code." } ]
[ { "body": "<p>This program is using purely C++ I/O so the include for the old style C I/O is not necessary, you don't need the <code>#include &lt;stdio.h&gt;</code> and it would be better to remove it.</p>\n\n<p>The indentation of the code is inconsistent and confusing, both in the class and in the <code>main()</code> function.</p>\n\n<p>Generally in C++ it is unnecessary to use the <code>this</code> pointer, it is required in only two places in the code and wouldn't be necessary at all if the name of the input variable was changed.</p>\n\n<pre><code> BstNode(int data)\n {\n this-&gt;data = data;\n left = NULL;\n right = NULL;\n }\n\n\n bool Search(int data)\n {\n if(this-&gt;data == data)\n return true;\n else if(data &gt;= data)\n {\n if(left == nullptr)\n return false;\n else\n return left-&gt;Search(data);\n }\n else\n {\n if(right == nullptr)\n return false;\n else\n return right-&gt;Search(data);\n }\n\n }\n</code></pre>\n\n<p>In modern C++ one should use <code>nullptr</code> rather than NULL as shown above.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T23:23:11.120", "Id": "237807", "ParentId": "237800", "Score": "4" } }, { "body": "<h1>Overall organization</h1>\n\n<p>Right now, you've defined a <code>BstNode</code>, which you use directly in <code>main</code>. I'd at least consider defining a <code>Bst</code> class, and then (probably inside that) a <code>Node</code> class.</p>\n\n<pre><code>class Bst {\n class Node {\n // only code to deal with individual nodes goes here\n };\n\n Node *root;\npublic:\n\n bool insert(int value);\n\n bool find(int value);\n};\n</code></pre>\n\n<p>Then to create a Binary search tree, you'd just instantiate a <code>Bst</code> object, and use it:</p>\n\n<pre><code>int main() {\n\n Bst tree;\n\n // oops--this will lead to a completely imbalanced tree.\n for (int i=0; i&lt;10; i++)\n tree.insert(i);\n\n}\n</code></pre>\n\n<h1>in-class initialization</h1>\n\n<p>Since you (almost?) always create a node with its child pointers set to nullptrs, I'd just specify that directly in the class instead of in the ctor:</p>\n\n<pre><code>// ...\nclass Node {\n int value;\n Node *left = nullptr;\n Node *right = nullptr;\n\n Node(int value) : value(value) {}\n};\n</code></pre>\n\n<h1>Insertion and Search</h1>\n\n<p>I'd at least consider whether you really want to use recursion to do insertion and/or search. Since you only ever descend to one child of any given node, it's pretty easy to use iteration for these tasks.</p>\n\n<h1>Insert return type</h1>\n\n<p>I'd at least consider having <code>Insert</code> return a bool to indicate whether it actually inserted a value in the tree or not (e.g., return false if a value is already present).</p>\n\n<h1>Collection type</h1>\n\n<p>What you've currently implemented is roughly equivalent to a <code>std::set</code>. That is, it stores only keys. This can certainly be useful, but there are times its also useful to have data associated with the key (i.e., roughly equivalent to <code>std::map</code>).</p>\n\n<h1>Generic Code</h1>\n\n<p>Right now, you've written the code so the only thing can be stored in your BST is <code>int</code>s. I'd at least consider making it generic so other types can be stored.</p>\n\n<pre><code>template &lt;class T, class Cmp = std::less&lt;T&gt;&gt;\nclass Bst {\n // ...\n</code></pre>\n\n<p>This increases complexity a little, but increases functionality quite a lot.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T05:55:09.100", "Id": "237819", "ParentId": "237800", "Score": "5" } } ]
{ "AcceptedAnswerId": "237819", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T20:57:59.867", "Id": "237800", "Score": "3", "Tags": [ "c++", "object-oriented", "binary-search", "binary-tree" ], "Title": "Simple Binary Search Tree Class with Insert and Search Functions" }
237800
<p>I want to put the worksheets from several (2-5) excel workbooks (files) into one single workbook.</p> <p>The names of the workbooks are not standardized and so I opted for a dialog box to select the workbooks.</p> <p>Here is the code. It meets the basic requirement that all the worksheets (sheets actually) from the selected files are collected into a single file (the <code>ActiveWorkbook</code>).</p> <pre><code>Sub openDialogBoxAndSelectFiles() Dim wb1 As Workbook Set wb1 = ActiveWorkbook With Application.FileDialog(msoFileDialogFilePicker) .AllowMultiSelect = True .InitialFileName = ThisWorkbook.path &amp; "\" .Title = "Paddington Bear Selection Window" .ButtonName = "Omlette" .Filters.Clear .Filters.Add "All Files", "*.*" If .Show = True Then Dim file As Variant For Each file In .SelectedItems Dim wb2 As Workbook Set wb2 = Workbooks.Open(Filename:=file, ReadOnly:=True) Dim i As Long For i = 1 To wb2.Sheets.Count wb2.Sheets(i).Copy before:=wb1.Sheets(1) Next i wb2.Close Next End If End With End Sub </code></pre> <p>The code is pretty clean (I think) for the time being and pretty much fits the bill, but that's because it doesn't do the following:</p> <p>If the <code>ActiveWorkbook</code> which I've defined as <code>wb1</code> has blank sheets (and a wb has to have at least 1 sheet), once this process is done, I will have a few blank sheets left over.</p> <p>So if <code>file1.worksheets.count = 4</code>, and <code>file2.worksheets.count = 5</code>, I will have a minimum of 10 (1 + 4 + 5) worksheets in the final workbook.</p> <p><strong>Questions:</strong></p> <ol> <li>Insofar as aggregating the sheets of the files is concerned, is this a reasonable way of doing it?</li> <li>Is there a simple of ensuring there are no blank worksheets left over? Unless the input files have blank sheets that is.</li> </ol> <p>Kindly,</p>
[]
[ { "body": "<p>I think the way you are doing this is reasonable. Regarding pre-existing blank sheets..The rewritten code below removes blank worksheet(s) in the importing workbook, after the selected workbooks' worksheets have been inserted.</p>\n\n<pre><code>Sub openDialogBoxAndSelectFiles()\n\n Dim wb1 As Workbook\n Set wb1 = ActiveWorkbook\n\n 'Cache worksheet references\n Dim originalWorksheets As Collection\n Set originalWorksheets = New Collection\n For i = 1 To wb1.Sheets.Count\n originalWorksheets.Add wb1.Sheets(i)\n Next i\n\n With Application.FileDialog(msoFileDialogFilePicker)\n .AllowMultiSelect = True\n .InitialFileName = ThisWorkbook.Path &amp; \"\\\"\n .Title = \"Paddington Bear Selection Window\"\n .ButtonName = \"Omlette\"\n\n .Filters.Clear\n 'only interested in Exel workbooks\n .Filters.Add \"All Files\", \"*.xls*\"\n\n\n If .Show = True Then\n For Each file In .SelectedItems\n ImportWorksheets wb1, file\n Next file\n End If\n End With\n\n 'Delete non-imported blank worksheets\n If wb1.Sheets.Count &gt; originalWorksheets.Count Then\n DeleteBlankSheets originalWorksheets\n End If\n\nEnd Sub\n\nPrivate Sub ImportWorksheets(ByRef wb1 As Workbook, ByVal filename As Variant)\nOn Error GoTo ErrorExit\n Dim wb2 As Workbook\n Set wb2 = Workbooks.Open(filename:=filename, ReadOnly:=True)\n\nOn Error GoTo WorkbookOpenError\n Dim i As Long\n For i = 1 To wb2.Sheets.Count\n wb2.Sheets(i).Copy before:=wb1.Sheets(1)\n Next i\n\nWorkbookOpenError:\n wb2.Close\n\nErrorExit:\nEnd Sub\n\nPrivate Sub DeleteBlankSheets(ByRef originalWorksheets As Collection)\nOn Error GoTo ErrorExit\n\n Dim displayAlertsFlagCurrentValue As Boolean\n displayAlertsFlagCurrentValue = Application.DisplayAlerts\n\n 'Prevent Sheet deletion prompts\n Application.DisplayAlerts = False\n\n Dim wksht As Worksheet\n For Each wksht In originalWorksheets\n If IsBlank(wksht) Then\n wksht.Delete\n End If\n Next wksht\n\nErrorExit:\n Application.DisplayAlerts = displayAlertsFlagCurrentValue\nEnd Sub\n\nPrivate Function IsBlank(ByRef wksht As Worksheet) As Boolean\n IsBlank = WorksheetFunction.CountA(wksht.UsedRange) = 0 And wksht.Shapes.Count = 0\nEnd Function\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T02:38:27.903", "Id": "466393", "Score": "0", "body": "This would certainly solve the problem. I was considering something similar but it seemed kind of inelegant. I will keep this open for a bit longer, but it might just be the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-26T02:04:32.273", "Id": "466647", "Score": "0", "body": "In the end, the only thing I did differently is that I saved the original worksheet names as a collection, instead of the ws objects." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-26T04:02:09.830", "Id": "466656", "Score": "0", "body": "Perfectly good solution to use worksheet names in this context." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T23:04:42.937", "Id": "237805", "ParentId": "237803", "Score": "2" } } ]
{ "AcceptedAnswerId": "237805", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T21:30:32.927", "Id": "237803", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "aggregate sheets from many excel workbooks into one workbook" }
237803
<p>I am trying to implement DSs in C++ and this is BST insert and search functions. I tried in two different ways, please review and see if one is advantageous over other.<br> With pointer to pointer</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;iostream&gt; struct BstNode{ int data; BstNode* left; BstNode* right; }; BstNode* NewNode(int data) { BstNode* newNode = new BstNode(); newNode-&gt;data = data; newNode-&gt;left = NULL; newNode-&gt;right = NULL; return newNode; } void Insert(BstNode** root,int data) { if(*root == NULL) { *root= NewNode(data); } else if(data &lt;= (*root)-&gt;data) { (*root)-&gt;left = NewNode(data); } else { (*root)-&gt;right = NewNode(data); } } bool SearchBST(BstNode* root, int data) { if(root == NULL) { return false; } else if(root-&gt;data == data) { return true; } else if(data &lt;= root-&gt;data) { return SearchBST(root-&gt;left, data); } else { return SearchBST(root-&gt;right, data); } } int main() { BstNode* ptr_root = NULL; Insert(&amp;ptr_root,15); Insert(&amp;ptr_root,10); Insert(&amp;ptr_root,16); int num; std::cout&lt;&lt;"Enter the number: \n"; std::cin&gt;&gt; num; if (SearchBST(ptr_root,num)) std::cout&lt;&lt;"Found\n"; else std::cout&lt;&lt;"Not Found\n"; return 0; } </code></pre> <p>Without pointer to a pointer:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;iostream&gt; struct BstNode{ int data; BstNode* left; BstNode* right; }; BstNode* NewNode(int data) { BstNode* newNode = new BstNode(); newNode-&gt;data = data; newNode-&gt;left = NULL; newNode-&gt;right = NULL; return newNode; } BstNode* Insert(BstNode* root,int data) { if(root == NULL) { root= NewNode(data); } else if(data &lt;= root-&gt;data) { root-&gt;left = NewNode(data); } else { root-&gt;right = NewNode(data); } return root; } bool SearchBST(BstNode* root, int data) { if(root == NULL) { return false; } else if(root-&gt;data == data) { return true; } else if(data &lt;= root-&gt;data) { return SearchBST(root-&gt;left, data); } else { return SearchBST(root-&gt;right, data); } } int main() { BstNode* ptr_root = NULL; ptr_root=Insert(ptr_root,15); ptr_root=Insert(ptr_root,10); ptr_root=Insert(ptr_root,16); int num; std::cout&lt;&lt;"Enter the number: \n"; std::cin&gt;&gt; num; if (SearchBST(ptr_root,num)) std::cout&lt;&lt;"Found\n"; else std::cout&lt;&lt;"Not Found\n"; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T22:09:37.310", "Id": "466381", "Score": "1", "body": "Same problem as the other one, not all paths return a value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T23:13:15.627", "Id": "466387", "Score": "0", "body": "Corrected the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T23:24:34.120", "Id": "466388", "Score": "1", "body": "To all considering a VTC the code has been corrected." } ]
[ { "body": "<p>Neither of your implementations is \"advantageous\" over other because both of them are C-style, unidiomatic C++ code &mdash; they are really C code with a handful of C++ additions. Moreover, they share many errors. This review will (hopefully) help you convert your code to C++ style and fix these errors.</p>\n\n<h1>Formatting</h1>\n\n<p>The indentation of the first implementation is a nightmare. Fix it by consistently indenting everything by 4 spaces and make sure lines on the same indentation level align with each other. Also, comma tokens should generally be followed by a space.</p>\n\n<h1>General design</h1>\n\n<p>You code does not provide a suitable interface because \"BST Node\" is an implementation detail. Users do not want to work directly with nodes most of the time; they want to work with the trees. Therefore, you should provide a class to encapsulate the tree. The insert and search functions should be member functions of the tree, not free functions.</p>\n\n<h1>Memory management</h1>\n\n<p>You use <code>new</code> to allocate nodes, but never <code>delete</code> them. In other words, you are constantly leaking memory. This makes your code not reusable. You should use a smart pointer (e.g., <code>std::unique_ptr</code>) instead of raw pointers in order to solve this problem.</p>\n\n<h1>Miscellaneous</h1>\n\n<p><code>#include &lt;stdio.h&gt;</code> is redundant and should be removed.</p>\n\n<p>Instead of the type-unsafe <code>NULL</code>, use <code>nullptr</code>.</p>\n\n<hr>\n\n<p>Here's how I'd put the whole thing together (minimal version):</p>\n\n<pre><code>#include &lt;initializer_list&gt;\n#include &lt;iostream&gt;\n#include &lt;memory&gt;\n\nclass Binary_search_tree {\n struct Node {\n int value{};\n std::unique_ptr&lt;Node&gt; left{};\n std::unique_ptr&lt;Node&gt; right{};\n };\npublic:\n Binary_search_tree() = default;\n Binary_search_tree(std::initializer_list&lt;int&gt; init)\n {\n for (auto elem : init) {\n insert(elem);\n }\n }\n void insert(int value)\n {\n insert_at(root, value);\n }\n bool contains(int value) const\n {\n return contains_at(root, value);\n }\nprivate:\n void insert_at(std::unique_ptr&lt;Node&gt;&amp; node, int value)\n {\n if (!node) {\n node.reset(new Node{value});\n } else if (value &lt; node-&gt;value) {\n insert_at(node-&gt;left, value);\n } else {\n insert_at(node-&gt;right, value);\n }\n }\n bool contains_at(const std::unique_ptr&lt;Node&gt;&amp; node, int value) const\n {\n if (!node) {\n return false;\n } else if (value &lt; node-&gt;value) {\n return contains_at(node-&gt;left, value);\n } else if (node-&gt;value &lt; value) {\n return contains_at(node-&gt;right, value);\n } else {\n return true;\n }\n }\n std::unique_ptr&lt;Node&gt; root{};\n};\n\nint main()\n{\n Binary_search_tree tree{31, 41, 59, 26, 53, 59};\n\n int num;\n std::cout &lt;&lt; \"Enter the number: \\n\";\n std::cin &gt;&gt; num;\n\n if (tree.contains(num)) {\n std::cout &lt;&lt; \"Found\\n\";\n } else {\n std::cout &lt;&lt; \"Not Found\\n\";\n }\n\n return 0;\n}\n</code></pre>\n\n<p>(<a href=\"https://wandbox.org/permlink/7cUuoRLpC0gyWZGK\" rel=\"nofollow noreferrer\">live demo</a>)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T20:54:50.683", "Id": "466496", "Score": "0", "body": "Took all my fun away. Great review. The only difference I could have done was not using `std::unique_ptr` to make it a more interesting learning example. But in all honesty using `std::unique_ptr` is the better technique here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T01:28:45.410", "Id": "466521", "Score": "0", "body": "@MartinYork Thanks. I wanna keep it simple so that’s why :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T01:40:40.740", "Id": "237814", "ParentId": "237804", "Score": "5" } } ]
{ "AcceptedAnswerId": "237814", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T21:58:41.963", "Id": "237804", "Score": "2", "Tags": [ "c++", "comparative-review", "binary-search", "binary-tree" ], "Title": "Simple BST implementation using C++ Struct" }
237804
<p>I was bored and sketched out this idea in pseudocode( I will try to turn it into C++ later) for taking a set of numeric data and manipulating it. I ran through it manually and it seems to put the data in a range <code>[0, something]</code></p> <pre><code>count = data[count] = { d_0, d_1, … , d_(count -1) } sigma = $Σ_{a∈ℕ} data_a$ avg = sum / count newData[count] = {} for x in data append (x · avg)/count to newData </code></pre> <p>What I am curious about, is if this "doodle" has any potential uses, or if it can be extended somehow?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T03:27:03.220", "Id": "466394", "Score": "0", "body": "Also: I am very sorry that the MathJax will not render,my device dislikes markdown..." } ]
[ { "body": "<p>Your computer will get bored, too, dividing (<code>over</code>?) by <em>count</em> over and again. Use<br>\n<em>avg_count</em> = <em>sum</em> / <em>count</em> / <em>count</em> - or<br>\n<em>scale</em> = <em>something</em> / <em>sum</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T05:19:32.010", "Id": "466400", "Score": "0", "body": "So... useless, I think is what you are saying?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T05:25:10.333", "Id": "466401", "Score": "0", "body": "I guess I fail to see *algorithm*, and I'm not sure ***I*** like to see *pseudocode* here. From [What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic): `actual code from a project rather than pseudo-code`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T05:12:53.377", "Id": "237818", "ParentId": "237809", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T01:00:46.773", "Id": "237809", "Score": "0", "Tags": [ "algorithm" ], "Title": "Algorithm for shifting data" }
237809
<p>I am wondering if there is any way to meaningfully shorten the chain of conditionals used here to compare two versions. <code>struct VERSIONCODE</code> represents a version number of the form <code>major.minor.revision</code> and <code>CompareVersions</code> returns <code>EQUAL</code> if they're equal; <code>LHS_NEWER</code> if <code>vLHS</code> is newer, and <code>RHS_NEWER</code> if <code>vRHS</code> is newer. </p> <pre><code>typedef enum { EQUAL = 0, LHS_NEWER, RHS_NEWER } ECOMPARISON; // Specifically not named "VERSION" to avoid conflicting with common names from third-party libraries etc. typedef struct { int nMajor; int nMinor; int nRev; } VERSIONCODE; ECOMPARISON CompareVersions(VERSIONCODE vLHS, VERSIONCODE vRHS) { if (vLHS.nMajor &gt; vRHS.nMajor) { return LHS_NEWER; } else if (vLHS.nMajor &lt; vRHS.nMajor) { return RHS_NEWER; } else// if (vLHS.nMajor == vRHS.nMajor) { if (vLHS.nMinor &gt; vRHS.nMinor) { return LHS_NEWER; } else if (vLHS.nMinor &lt; vRHS.nMinor) { return RHS_NEWER; } else// if (vLHS.nMinor == vRHS.nMinor) { if (vLHS.nRev &gt; vRHS.nRev) { return LHS_NEWER; } else if (vLHS.nRev &lt; vRHS.nRev) { return RHS_NEWER; } else// if(vLHS.nRev == vRHS.nRev) { return EQUAL; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-26T22:01:08.560", "Id": "466764", "Score": "1", "body": "I think it would be good to explicitly define `LHS_NEWER=-1` and `RHS_NEWER=1`, because that's what functions like `qsort()` expect" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-27T00:21:14.060", "Id": "466773", "Score": "0", "body": "@MontyHarder Yup, thought of that after posting. :)" } ]
[ { "body": "<p>You can remove the \"else\". You use conditions that return, so the else isn't needed as there is no other code that can be run.</p>\n\n<p>That'll reduce nesting :</p>\n\n<pre><code>if (vLHS.nMajor &gt; vRHS.nMajor)\n{\n return LHS_NEWER;\n}\nelse if (vLHS.nMajor &lt; vRHS.nMajor)\n{\n return RHS_NEWER;\n}\n\nif (vLHS.nMinor &gt; vRHS.nMinor)\n{\n return LHS_NEWER;\n}\nelse if (vLHS.nMinor &lt; vRHS.nMinor)\n{\n return RHS_NEWER;\n}\n\nif (vLHS.nRev &gt; vRHS.nRev)\n{\n return LHS_NEWER;\n}\nelse if (vLHS.nRev &lt; vRHS.nRev)\n{\n return RHS_NEWER;\n}\n\nreturn EQUAL;\n</code></pre>\n\n<p>That's more readable isn't it ? \nNext, you could wrap the repeated code in a function, which would reduce those 3 conditions to 1 line each, and make it easier to read.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T14:27:35.143", "Id": "466445", "Score": "1", "body": "I would say that conditional expressions could be used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T16:30:53.173", "Id": "466461", "Score": "2", "body": "You could remove the remaining `else` as well to make the code even shorter and more uniform." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T17:16:02.477", "Id": "466469", "Score": "0", "body": "One of those conditionals can only be reduced to one line by putting them in a function if they return always. But since your conditions are `if return else if return else continue` this cannot ever be captured in a single line" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T08:16:16.073", "Id": "237820", "ParentId": "237812", "Score": "8" } }, { "body": "<blockquote>\n<pre><code>typedef enum\n{\n EQUAL = 0,\n LHS_NEWER,\n RHS_NEWER\n} ECOMPARISON;\n</code></pre>\n</blockquote>\n\n<p>A common convention for three-way comparisons is that of <code>strcmp()</code> - return any negative value if the first argument is less than the second, zero if equal, and positive if greater.</p>\n\n<p>If we take that approach, and if we can ensure that the version values are small enough to avoid integer overflow, we can simplify the comparison to just:</p>\n\n<pre><code>int CompareVersions(VERSIONCODE a, VERSIONCODE b)\n{\n int diff = a.nMajor - b.nMajor;\n if (diff) return diff;\n diff = a.nMinor - b.nMinor;\n if (diff) return diff;\n return a.nRev - b.nRev;\n}\n</code></pre>\n\n<p>If we can't ensure overflow won't happen, or if we absolutely must return fixed values, we'll need to convert those subtractions into calls to a custom comparison function - perhaps like this:</p>\n\n<pre><code>int compare_int(int a, int b)\n{\n /* standard idiom to return -1, 0 or +1 */\n return (a &gt; b) - (b &gt; a);\n}\n</code></pre>\n\n<hr>\n\n<p>The naming can be improved. Most C conventions use <code>ALL_UPPERCASE</code> only for macros, to call attention to their difference from C code. And most authorities discourage prefixes like the <code>n</code> and <code>v</code> used at the start of variable and member names - I encourage you to research \"<em>Hungarian notation</em>\" and understand the arguments.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T20:17:36.747", "Id": "466494", "Score": "0", "body": "Oops, you're right - fixed. Thanks for pointing that out." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T09:58:52.673", "Id": "237822", "ParentId": "237812", "Score": "21" } }, { "body": "<p>The <code>CompareVersions()</code> function in <a href=\"https://codereview.stackexchange.com/a/237822/213380\">this answer</a> uses subtraction for comparison.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/6103636/c-qsort-not-working-correctly\">This is considered to be bad practice</a> - it leads to bugs and potential security holes.</p>\n\n<p>(Yes, the post does say \"if we can ensure that the version values are small enough to avoid integer overflow\", but that pretty much requires the caller of this function to know the result ahead of time.)</p>\n\n<p>To actually answer the question, I would remove the unnecessary <code>else</code>s:</p>\n\n<pre><code>ECOMPARISON CompareVersions(VERSIONCODE vLHS, VERSIONCODE vRHS)\n{\n if (vLHS.nMajor &gt; vRHS.nMajor) return LHS_NEWER;\n if (vLHS.nMajor &lt; vRHS.nMajor) return RHS_NEWER;\n\n // vLHS.nMajor == vRHS.nMajor\n\n if (vLHS.nMinor &gt; vRHS.nMinor) return LHS_NEWER;\n if (vLHS.nMinor &lt; vRHS.nMinor) return RHS_NEWER;\n\n // vLHS.nMinor == vRHS.nMinor\n\n if (vLHS.nRev &gt; vRHS.nRev) return LHS_NEWER;\n if (vLHS.nRev &lt; vRHS.nRev) return RHS_NEWER;\n\n return EQUAL;\n}\n</code></pre>\n\n<p>This is much easier to read, and can be seen to be correct by inspection.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-26T21:49:28.920", "Id": "466762", "Score": "0", "body": "I like that you leave in the comments to tell the next programmer to look at this that, having passed the previous pair of comparisons, we know the more-significant version components are equal." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T17:35:20.707", "Id": "237850", "ParentId": "237812", "Score": "14" } }, { "body": "<p>Late to the party, yet another candidate simplification. </p>\n\n<p>Look for inequality starting with most important. The logic flows fairly directly. Also, at most 4 compares.</p>\n\n<pre><code>ECOMPARISON CompareVersions(VERSIONCODE vLHS, VERSIONCODE vRHS) {\n if (vLHS.nMajor != vRHS.nMajor) {\n return (vLHS.nMajor &gt; vRHS.nMajor) ? LHS_NEWER : RHS_NEWER;\n }\n if (vLHS.Minor != vRHS.nMinor) {\n return (vLHS.nMinor &gt; vRHS.nMinor) ? LHS_NEWER : RHS_NEWER;\n }\n if (vLHS.nRev != vRHS.nRev) {\n return (vLHS.nRev &gt; vRHS.nRev) ? LHS_NEWER : RHS_NEWER;\n }\n return EQUAL;\n}\n</code></pre>\n\n<p>Note that without subtraction, no risk of <code>int</code> overflow.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T21:18:19.803", "Id": "237857", "ParentId": "237812", "Score": "6" } }, { "body": "<pre><code>int ultimateLVersion = 1000000 * vLHS.nMajor + 1000 * vLHS.nMinor + 1 * vLHS.nRev;\nint ultimateRVersion = 1000000 * vRHS.nMajor + 1000 * vRHS.nMinor + 1 * vRHS.nRev;\n\nif (ultimateLVersion &gt; ultimateRVersion){\n return vLHS;\n} else if (ultimateRVersion &gt; ultimateLVersion){\n return vRHS;\n} else {\n return EQUAL;\n}\n</code></pre>\n\n<p>Increase the number of zeros if needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T14:45:14.693", "Id": "466581", "Score": "1", "body": "I'm not sure if I love this or if I hate this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T16:34:29.713", "Id": "466604", "Score": "4", "body": "I do like this approach a lot, and have used it myself. It is especially advantageous in cases where performance matters, because it has the potential to reduce a lot of unpredictable branches. But it does suffer from some risk of overflow. To help catch those problems, I'd want to add some some assertions (at least runtime checks, but preferably compile-time checks for overflow)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T16:54:36.050", "Id": "466609", "Score": "1", "body": "@CodyGrayIn addition to overflow concerns (which is usually manageable), should `.nMajor`, or other members have negative values, then pedantically we have more order issues as `.nMinor` could \"beat\" `.nMajor`. Here I'd go for unsigned math and unsigned members and asserts to mitigate that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-27T02:33:20.730", "Id": "466781", "Score": "1", "body": "Yup, version numbers should never be negative, @chux. I *wouldn't* necessary use unsigned types, as that can mask errors via the magic of implicit conversion. Using a signed type as a parameter allows you to actually catch the error with an assert." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T12:00:32.960", "Id": "237891", "ParentId": "237812", "Score": "3" } } ]
{ "AcceptedAnswerId": "237850", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T01:28:39.693", "Id": "237812", "Score": "17", "Tags": [ "c" ], "Title": "Compare version numbers" }
237812
<p>I'm trying to display the fetched data on a table. I structured the data based on the columns table in the UI and stored them in an array, then <code>*ngFor</code> on the table rows on the frontend. Good or bad practice? Or are there other ways to do this in a much simpler way?</p> <pre><code> getLicensesofDealer(id) { this._license.get_license_by_id(id).subscribe( (data: License[]) =&gt; { let counter = 1; // Structure data and store in an array data.forEach(l =&gt; { const license = { unique_key: l.licenseId, count: counter, key: l.licenseKey, date: l.dateCreated } this.license_data.push(license); counter++; }) // Structure data and store in an array } ) } </code></pre>
[]
[ { "body": "<p>just my personal opinion, so pick what you like and ignore the rest. :-)</p>\n\n<p>In general i think it is a good practice to use your \"own\" data structure in the frontend.\nif the backend changes their format, then you only have to change your mapping functions, and the rest could stay the same. If you use the backend format directly, then your code depends on that format. Means, if the backend changes a name, you would have to change that name all over your application...</p>\n\n<p>Some points in general:</p>\n\n<p><strong>subscribe/unsubscribe</strong><br>\nthe first thing i would like to mention is, that if you subscribe in a component, then this subscription will be still active, after your component is long dead. Or to make it more explicit, when you \"subscribe\", then call the method \"subscribe\" on the observable. And you provide a (fat arrow) function to it. This function is then stored in the observable. Now, each time the observable emits a value, the function is executed. Because this function now \"lives\" in the observable, it does not get cleaned up when your component is destroyed. This can create memory leaks and/or unwanted behavior.</p>\n\n<p>Therefor if your oberservable does not complete by itself (e.g. an http call, will only do one emit and then \"complete\") you should always clean up your subscriptions. This could be done by saving them all into a \"Subscription\" object.</p>\n\n<pre><code>private subscriptions: Subscription = new Subscription();\n// ...\nthis.subscriptions.add(\n this.myObservable.subscribe( (...)=&gt;{...})\n)\nthis.subscriptions.add(\n this.myOtherObservable.subscribe( (...)=&gt;{...})\n)\n\nngOnDestroy(){\n this.subscriptions.unsubscribe();\n}\n</code></pre>\n\n<p><strong>forEach vs. map</strong><br>\nforEach is used if you want to execute something for each element of an array. Map is used, if you want to change the format of each element. In your case you want to change the format, so i would prefer \"map\"</p>\n\n<pre><code>let counter = 1;\nthis.licence_data = data.map( el =&gt; {\n return {\n count: counter++,\n unique_key: el.licenceId,\n key: el.licenceKey,\n date: el.dateCreated\n };\n}\n</code></pre>\n\n<p><strong>Readability by extracting into methods</strong><br>\nI personaly like it, when i don´t have to read 5 lines (often much more) of code to understand what happens here. Its much easier if a method is called and the name of the method gives me a good clue what happens in it. As a result, sometimes i don´t even have to look into the method, because the name alone tells me that the problem i am hunting is not there. OR the name gives me some context which allows me to understand the content of the method more easily.<br>\nAnd last but not least, splitting code into multiple methods means to separate the code into chunks which communicate with each other over interfaces. And that makes changes much easier, because, as long as i do not change the interface (the method signature), as long can i do changes without having to fear to break something outside. That makes refactorings much easier.</p>\n\n<pre><code>this._licence.get_licence_by_id(id).subscribe(\n (data: Licence[] =&gt; this.licence_data = this.mapToUIFormat(data)\n);\n\nthis.mapToUIFormat(licences: Licence[]): MyUiFormat { // i would give that format an interface\n let counter = 1;\n return data.map( licence =&gt; {\n return {\n count: counter++,\n unique_key: licence.licenceId,\n key: licence.licenceKey,\n date: licence.dateCreated\n };\n }\n</code></pre>\n\n<p>}</p>\n\n<p>The advantage of this method is, that its a \"pure\" method. It only expects some input, and it returns an output that ONLY depends on the input. It also has no side effects, means it does not change anything else. That makes it easier to understand and very easy to test.</p>\n\n<p>If you want you could also extract the mapping of a single licence into the ui format in a extra method. It depends on the complexity of the code, but in some circumstances it really helps to structure the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T10:54:58.813", "Id": "466542", "Score": "0", "body": "JanRecker I owe you one, This will help me a lot. Everything you said is so easy to understand and I thank you for that, I hope I could buy you a beer someday. Thanks Man! I really appreciate it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T15:45:15.050", "Id": "237843", "ParentId": "237813", "Score": "2" } } ]
{ "AcceptedAnswerId": "237843", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T01:30:28.887", "Id": "237813", "Score": "2", "Tags": [ "javascript", "angular-2+" ], "Title": "Subscribing and manipulating data from API in Angular" }
237813
<p>I was writing a little coding kata, and wanted to have a hook which managed a list of names. The hook should allow adding a name to the list, and also make the list available to the component.</p> <p>I didn't want to bring in a state management library, or complicate the code with having to <code>useDispatch</code> or anything like that. I also didn't want to bring in a package that explicitly enables a <code>useSharedState</code> or <code>useGlobal</code> thing. Here's what I came up with.</p> <pre><code>import { useState } from 'react'; let list: string[] = []; // Force a single instance of a list, even if Hook is used in multiple places const useNameList = () =&gt; { const [, _setList] = useState&lt;string[]&gt;(list); const [lastSelectedItem, setLastSelectedItem] = useState&lt;string | null&gt;(null); return { add: (name: string) =&gt; { list = [...list, name]; // Components are delayed on detecting state updates if you don't explicitly update the hook state too... _setList(list); }, names: list } }; export default useNameList; </code></pre> <p>By setting the <code>list</code> up outside the hook, it forces there to be one instance. However, I still need to <code>setList</code> within a <code>useState</code>; without doing that, there was some buggy stuff happening across different components.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T01:17:36.660", "Id": "466520", "Score": "0", "body": "I'm a bit confused. What exactly do you think your current code is lacking? And is this code working as intended or not?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T10:00:12.570", "Id": "237823", "Score": "1", "Tags": [ "javascript", "react.js" ], "Title": "React Hooks - Single instance of state" }
237823
<p>I am experimenting with the best way to standardise my dynamic <code>import()</code> expressions when importing javascript modules.</p> <p><code>import()</code> returns a promise, so, to handle the asynchronous steps after the<code>import()</code> expression, I can use either:</p> <ul> <li><code>.then()</code> syntax; or</li> <li><code>async</code> / <code>await</code> syntax</li> </ul> <p>Whilst I am quite familiar with the older <code>XHR2</code> approach and somewhat familiar with ES2015 <code>.then()</code> syntax, I am less familiar with <code>async</code> / <code>await</code> syntax.</p> <p>I understand that I can only use <code>await</code> <em>inside</em> a function which has been declared or assigned with <code>async</code>.</p> <p>But I am trying to understand why <strong>Approach 1</strong> works.</p> <p><strong>Approach 1:</strong></p> <pre><code>(async () =&gt; { let myImportedModule = await import('/path/to/my-module.js'); myImportedModule.myFunction1(); myImportedModule.myFunction2(); })(); </code></pre> <p>But <strong>Approach 2</strong> does not.</p> <p><strong>Approach 2:</strong></p> <pre><code>(async () =&gt; { await import('/path/to/my-module.js'); myFunction1(); myFunction2(); })(); </code></pre> <hr> <p><strong>Additional Notes:</strong></p> <p>Clearly I have something wrong, but I thought <strong>Approach 2</strong> would be the <code>async</code> / <code>await</code> equivalent of <em>this</em> snippet (using <code>.then()</code> syntax):</p> <pre><code>import('/path/to/my-module.js') .then((myImportedModule) =&gt; { myImportedModule.myFunction1(); myImportedModule.myFunction2(); }); </code></pre> <p>but that it would enable me to access <code>myFunction1</code> and <code>myFunction2</code> directly, without needing to give a name to the resolved <code>Promise</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T17:18:42.467", "Id": "466470", "Score": "0", "body": "It's the opposite. Approach 1 is the equivalent of the `then` version. Otherwise the meaning would be completely different. To understand this, think about how names are resolved and how they can be shadowed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T19:34:00.337", "Id": "466491", "Score": "0", "body": "Thanks, @AluanHaddad. I'm just trying to find a way to avoid returning the functions as properties of a named object. Whatever syntax I try, that's what they keep coming back as. The only way I have succeeded in extracting the properties from the object is by deploying `for (let entry of Object.entries(moduleTest)) {window[entry[0]] = entry[1];}` - but then I end up with the functions at `global` scope and I definitely don't want that. I just want them as standalone functions at the scope of the `module` they have been `imported` into." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T21:20:12.807", "Id": "466498", "Score": "1", "body": "But that's not how modules work in general. Maybe you want a destructuring assignment (`const {f, g} = await import(...);`)? If you want them at module scope, that's highly problematic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T21:25:14.837", "Id": "466499", "Score": "1", "body": "You may also be interested in https://github.com/tc39/proposal-top-level-await, which you can start using now if you use TypeScript or Babel." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T23:37:21.937", "Id": "466512", "Score": "1", "body": "Thanks for all your help, @AluanHaddad. This is a key statement: _\"But that's not how modules work in general.\"_ I've reconciled myself to importing an object with properties, rather than individual variables whenever I use dynamic `import()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T00:45:26.353", "Id": "466517", "Score": "1", "body": "Glad to be of service. I think the ergonomics don't bother me as much since I usually just `export default expression`, a habit I got into because of loader-interop issues and then became enamored of. I fully understand why many prefer to export multiple bindings though." } ]
[ { "body": "<p><strong>Approach 2</strong> does not work because <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Description\" rel=\"noreferrer\">accoring to MDN</a>:</p>\n\n<pre><code>import '/modules/my-module.js';\n</code></pre>\n\n<p>Is how you <code>import</code> a module for <strong>Import a module for its side effects only</strong></p>\n\n<blockquote>\n <p>Import an entire module for side effects only, without importing anything. This runs the module's global code, but doesn't actually import any values.</p>\n</blockquote>\n\n<p>So, <code>await import('/path/to/my-module.js');</code> won't actually import your <code>myfunction1</code> and <code>myFunction2</code> for you to use them, however, if you put an IIFE in there, it will be called.</p>\n\n<p>If you don't want to use long names to call your function, you can destructure them :</p>\n\n<pre><code>(async () =&gt; {\n\n const { myFunction1, myFunction2 } = await import('/path/to/my-module.js');\n\n myFunction1();\n myFunction2();\n\n})();\n</code></pre>\n\n<p>Or, call them in <code>my-module.js</code> and just import it and they will get called.</p>\n\n<p>See the answers here for <a href=\"https://stackoverflow.com/questions/41127479/es6-import-for-side-effects-meaning\">es6 import for side effects meaning</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T23:35:05.643", "Id": "466510", "Score": "1", "body": "Well explained answer. Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T21:55:47.207", "Id": "237861", "ParentId": "237824", "Score": "9" } } ]
{ "AcceptedAnswerId": "237861", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T10:14:32.600", "Id": "237824", "Score": "8", "Tags": [ "javascript", "ecmascript-6", "async-await", "promise", "modules" ], "Title": "Using async / await with dynamic import() for ES6 modules" }
237824