body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>For practice purposes, I reimplemented a STL Vector container. This container has most/all of the capabilities of STL vector.In my previous <a href="https://codereview.stackexchange.com/questions/251492/linked-list-queue-implementation">post</a>, the reviewers made critical and concised observations which I researched about and considered them very important, thanks to them, I made a more robust class than the previous iteration.</p> <h1>Overview</h1> <p>Class Vector is a STL container ( first class container ) that supports various functionalities such as push_back(), pop_back(), front(), back(), at() and many more.</p> <h1>Purpose/Aim</h1> <ol> <li>As an exercise to get in-depth knowledge on the rule of 0/3/5</li> <li>I aim to understand more about move semantics</li> <li>To get my hands dirty with templates early on</li> </ol> <h1>Major Concerns</h1> <ol> <li>Comparisons between iterators <code>begin()</code> and <code>cbegin()</code> returns true, I cross-checked with the standard implementation and same case. Since am trying to mimic the standard, I had to implement it that way. Does it make sense to implement otherwise?</li> </ol> <p><strong>General advice, major/common pitfalls, general good practices and constructive critic are highly welcomed</strong></p> <pre><code>#ifndef VECTOR_H_ #define VECTOR_H_ #include &lt;cstddef&gt; #include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;initializer_list&gt; namespace MyIterator { template&lt; typename T &gt; class Iterator { protected: std::size_t index_; T* memory_ptr; public: Iterator( T* memory_block ) : index_( 0 ), memory_ptr( memory_block ) {} Iterator( T* memory_block, std::size_t end ) : index_( end ), memory_ptr( memory_block ) {} Iterator &amp;operator++() { ++index_; return *this; } Iterator &amp;operator--() { --index_; return *this; } bool operator==( const Iterator &amp;other_it ) const { return ( index_ == other_it.index_ ); } bool operator!=( const Iterator &amp;other_it ) const { return !( *this == other_it ); } T&amp; operator*() { return memory_ptr[ index_ ]; } }; template&lt; typename T &gt; class ConstIterator : public Iterator&lt;T&gt; { public: ConstIterator( T* memory_block ) : Iterator&lt;T&gt;( memory_block ){} ConstIterator( T* memory_block, std::size_t end ) : Iterator&lt;T&gt;( memory_block, end ){} const T&amp; operator*() const { return this-&gt;memory_ptr[ this-&gt;index_ ]; } }; } namespace MyVector { template&lt; typename T &gt; class Vector { friend void swap( Vector &amp;lhs, Vector &amp;rhs ) { using std::swap; swap( lhs.size_index, rhs.size_index ); swap( lhs.vector_capacity, rhs.vector_capacity ); swap( lhs.memory_block, rhs.memory_block ); } private: std::size_t size_index; std::size_t vector_capacity; T* memory_block; public: /* ctors */ Vector() : size_index( 0 ), vector_capacity( 1 ), memory_block ( new T[ vector_capacity ]{} ){} Vector( std::size_t sz ) : size_index( sz ), vector_capacity( sz ), memory_block( new T[ vector_capacity ]{} ) {} Vector( std::size_t sz, const T &amp;val ) : Vector( sz ) { for( std::size_t i = 0; i != vector_capacity; ++i ) { memory_block[ i ] = val; ++size_index; } } Vector( std::initializer_list&lt;T&gt; list ) : Vector( list.size() ) { std::size_t index = 0; for( const auto &amp;item : list ) memory_block[ index++ ] = item; } Vector( const Vector &amp;other_vec ) : size_index( other_vec.size_index), vector_capacity( other_vec.vector_capacity ), memory_block( new T[ other_vec.vector_capacity ] ) { std::copy( other_vec.memory_block, other_vec.memory_block + vector_capacity, memory_block ); } Vector &amp;operator=( Vector rhs ) { swap( *this, rhs ); return *this; } Vector( Vector &amp;&amp;other_vec ) { swap( *this, other_vec ); } /* modifiers */ void push_back( const T &amp;val ) { if( size_index &gt;= vector_capacity ) { // allocates twice the size of the current vector's capacity T * new_memory_block = new T[ vector_capacity * 2 ]; // copy each element to new vector's memory_block for( std::size_t i = 0; i != size_index; ++i ) new_memory_block[ i ] = memory_block[ i ]; delete [] memory_block; // delete old memory; very important! memory_block = new_memory_block; vector_capacity *= 2; } memory_block[ size_index++ ] = val; } void insert( int index, const T&amp; val ) { if( index &lt; 0 || index &gt; size_index ) throw std::out_of_range( &quot;Exception: index out of range&quot;); for( int temp_index = size_index; temp_index &gt;= index; --temp_index ) { /* Move elements one step back until we get to the desired location */ memory_block[ temp_index + 1 ] = memory_block[ temp_index ]; } memory_block[ index ] = val; size_index++; } void erase( int index ) { for( int temp_index = index; temp_index &lt; size_index; ++temp_index ) { /* Move elements one step back until we get to the desired location */ memory_block[ temp_index ] = memory_block[ temp_index + 1 ]; } --size_index; } void pop_back() { --size_index; }// ignored garbage value void clear() { delete [] memory_block; memory_block = nullptr; size_index = 0; } /* accessors */ MyIterator::Iterator&lt;T&gt; begin() { return MyIterator::Iterator&lt;T&gt;( memory_block ); } MyIterator::Iterator&lt;T&gt; end() { return MyIterator::Iterator&lt;T&gt;( memory_block, size_index ); } const MyIterator::ConstIterator&lt;T&gt; cbegin() const { return MyIterator::ConstIterator&lt;T&gt;( memory_block ); } const MyIterator::ConstIterator&lt;T&gt; cend() const { return MyIterator::ConstIterator&lt;T&gt;( memory_block, size_index ); } T&amp; front() const { return memory_block[ 0 ]; } T&amp; back() const { return memory_block[ size_index - 1 ]; } T&amp; front() { return memory_block[ 0 ]; } T&amp; back() { return memory_block[ size_index - 1 ]; } T&amp; at( const std::size_t i ) const { if( i &lt; 0 || i &gt;= size_index ) throw std::out_of_range( &quot;Exception: index out of range &quot; ); return memory_block[ i ]; } T&amp; at( const std::size_t i ) { if( i &lt; 0 || i &gt;= size_index ) throw std::out_of_range( &quot;Exception: index out of range &quot; ); return memory_block[ i ]; } T&amp; operator[]( const int i ) const { return memory_block[ i ]; } T&amp; operator[]( const int i ) { return memory_block[ i ]; } std::size_t capacity() const { return vector_capacity; } std::size_t size() const { return size_index; } bool empty() const { return ( size_index == 0 ); } /* dtor */ ~Vector() { delete [] memory_block; } }; } #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T00:41:14.673", "Id": "495473", "Score": "1", "body": "`if( 1 < 0` in `T& at` seems like a typo. Please fix." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T00:48:54.133", "Id": "495474", "Score": "0", "body": "@vnp, missed that. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T18:49:36.683", "Id": "495595", "Score": "2", "body": "Please have a read on the articles I wrote about creating a vector: https://lokiastari.com/series/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T21:22:32.520", "Id": "495616", "Score": "0", "body": "@Martin York. Thanks for the link, nice resources" } ]
[ { "body": "<ul>\n<li>First, your iterator:</li>\n</ul>\n<p>It doesn't have STL-required fields (<code>pointer</code>, <code>reference</code>, <code>iterator_category</code>, etc... checkout the <a href=\"https://en.cppreference.com/w/cpp/iterator/iterator\" rel=\"noreferrer\">reference</a>) and methods so it won't work for variety of STL based algorithms and some common operations aren't supported, like: <code>itr++</code> (different from <code>++itr</code>) or <code>itr2-itr1</code> as well as operators like <code>+=,-=,+,-</code> and <code>[]</code>.</p>\n<p>Furthermore, some algorithms like sorting require <code>&lt;</code> and/or <code>&lt;=</code> operators to function.</p>\n<p>Besides, you const version will not function properly. As it requires <code>T*</code> to instantiate instead of <code>const T*</code>. So implementing it as a derived class from regular iterator is a wrong approach.</p>\n<p>Also the <code>operator *</code> of the iterator is a const method.</p>\n<p>Note: I don't understand why people write members variables with suffix <code>_</code> like <code>index_</code>. What's the purpose of this suffix? If you wrote it with prefix <code>m_</code> like <code>m_index</code> then you'd at least be able to auto find them quickly in IDEs by typing <code>m_</code> and then searching through found options. Just don't use <code>_</code> solo for prefix as those are reserved for compiler MACROS.</p>\n<ul>\n<li>Second, your vector:</li>\n</ul>\n<p>There are people that propagate swap idiom. It was surely a wise choice prior to C++11 before move semantics were introduced but these days I don't find it good approach.\nWhile it is definitely possible to implement the vector via this approach your implementation definitely isn't one such and has several issues.</p>\n<ol>\n<li><p>Move constructor: your move constructor swaps between <code>*this</code> and <code>source</code>. So <code>Vector A = std::move(B);</code> will result in <code>A</code> having <code>B</code>'s data but <code>A</code>'s variables weren't initialized so content of <code>B</code> is pure garbage and will break the program in destructor.</p>\n</li>\n<li><p>Assignment: you should implement it properly with Copy-Assignment and Move-Assignment instead of hoping that constructors will do everything for you. In the Copy-Assignment you miss the opportunity to reuse to already allocated memory by the vector and instead allocate new one. This causes some issues, like user would definitely expect you to reuse the memory if newly copied data doesn't exceed capacity - notice that iterators get invalidated upon reallocation which would cause UB if user expected no reallocations.</p>\n</li>\n<li><p>Copy Constructor: you shouldn't copy the capacity and instead allocate the required amount.</p>\n</li>\n<li><p>Default Constructor: You should initialize it to completely empty instead of <code>1</code>-sized allocation.</p>\n</li>\n<li><p>Why does you <code>front()</code>, <code>back()</code>, <code>operator []</code> const versions return <code>T&amp;</code> instead of <code>const T&amp;</code>? This contradicts the idea of what const vector is meant to be.</p>\n</li>\n<li><p>There are reasons why <code>std::vector</code> doesn't support insert operation. It is a very slow one and shouldn't be used. So don't bother implementing it.</p>\n</li>\n<li><p>You didn't implement <code>reserve(...)</code>, <code>resize(...)</code>, <code>emplace_back(...)</code> methods as well as move version for <code>push_back(T&amp;&amp;)</code>.</p>\n</li>\n</ol>\n<p>These were easy to fix issues. But the bigger problem is that you assumed your <code>T</code> type is some trivial object like <code>int</code>. This is not the case in general. The type might be non-copyable, have costly default construction, or non-trivial destructor.</p>\n<p>Because of this you cannot just write <code>T * new_memory_block = new T[ vector_capacity * 2 ];</code> upon a reallocation you need to allocate the memory and in a for-loop appropriately move/copy/default - construct each element according to new size and not capacity. All the while avoid the unnecessary construction calls for trivial types else it will be inefficient. Also, the <code>pop_back()</code> must call destructor of the last element instead of just reducing <code>size_index</code> and similarly in <code>push_back()</code> it should call copy/move-constructor to the newly allocated element instead of copy assignment when reallocation is not used.</p>\n<p>Yeah, unfortunately because of these issues you cannot quite use <code>new[]/delete[]</code> in a vector implementation.</p>\n<p>This isn't a beginner's' task as to implement it properly and efficiently you need to utilize SFINAE which has a very troublesome syntax.</p>\n<p>Edit: forgot to mention. It is rather important. Move-Assignment and Move-Constructor must be marked <code>noexcept</code> as otherwise various <code>STL</code> based algorithm and containers will perform poorly while using your class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T19:49:51.103", "Id": "495598", "Score": "1", "body": "Much good, some not: 1. [An iterator doesn't need any member-typedefs.](https://en.cppreference.com/w/cpp/named_req/Iterator) Though `std::iterator_traits<Iterator>` must still have the required members. Also, `std::iterator` which you link to was deprecated in C++17 for being pretty useless. 2. Nearly all standard library code only ever uses `<` of all the relational operators. 3. Beginning with a single underscore and a lowercase character is fine. 4. Move-assignment is fine, clarify that? 5. [`std::vector`](https://en.cppreference.com/w/cpp/container/vector/insert) supports `.insert()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T19:58:56.880", "Id": "495600", "Score": "0", "body": "@Deduplicator, I was wondering why my move assignment was bad ever since!." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T20:01:17.310", "Id": "495601", "Score": "0", "body": "@Deduplicator (1) I don't know why these fields needed or not but lacking them causes compilation issues on some platforms. (2) `<` usually but once got issues cause didn't have `<=`. And both `==` and `!=` are needed for general use. (4) It isn't fine cause move-constructor is corrupted and it lacks `noexcept` as it is implemented via `copy-like` assignment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T20:48:00.920", "Id": "495604", "Score": "0", "body": "(1) The typedefs are needed for `std::iterator_traits` to pick them up, if that isn't specialized. Any other code using them is wrong. (2) With relational operators I follow common grouping and exclude (in-)equality. Library code using any relational operator but `<` and it not being contractual (which is rare and only where obviously needed and expected) is AFAICR wrong. (4) move-assignment works but should be custom coded. Admittedly, the ctor below assignment fooled me into thinking it was better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T20:54:25.357", "Id": "495607", "Score": "0", "body": "@Deduplicator he has no dedicated move-assignment. Only move-constructor which doesn't work as it corrupts input vector." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T21:06:21.407", "Id": "495614", "Score": "0", "body": "Yes, I already admitted my slight mistake. When move-ctor is fixed the op= he has is only slightly expensive for move-assignment (though probably fine after inlining and optimization). As he should separate out copy-ctor, that should be improved too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T21:06:46.697", "Id": "495615", "Score": "0", "body": "Agree with the sentiment: `Just don't use _ solo for prefix as those are reserved for compiler MACROS` but not exactly correct. I would just say: `The rules are complex and most people don't know all of them so simply best avoided`. https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T21:37:03.183", "Id": "495619", "Score": "2", "body": "`There are people that propagate swap idiom. It was surely a wise choice prior to C++11 before move semantics were introduced but these days I don't find it good approach`. Why? The easy easy to implement move semantics is via swap." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T21:41:27.237", "Id": "495620", "Score": "0", "body": "@MartinYork the preferable way is via `std::exchange` on all members." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T00:52:18.243", "Id": "495632", "Score": "1", "body": "@ALX23z Does not look like it is preferable to me: https://stackoverflow.com/a/20843994/14065 It looks like exchange in this scenario can be equivalent but can be slower. Do you have a reference that I can check out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T01:37:09.973", "Id": "495635", "Score": "0", "body": "@MartinYork the reference you showed was about \"how to implement swap\". Here it is about \"how to implement move-ctor\". With swap one needs default-ctor + 2 move-ctor + 2 move-assignment prior to O2+ optimizations that might or might not happen. With `std::exchange` it is `set-to-default`+ move-ctor (could be 2 but most likely one will be NRVOd out even in debug mode) which is the minimal possible number of operations. Note that if you have several layers of structures built on top of each other with move-via-swap the number of operations applied raises exponentially with each layer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T06:13:21.633", "Id": "495642", "Score": "0", "body": "@ALX23z Comments are not good for detailed explanations. Do you have a good reference. I am not sure I follow your argument as it is." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T02:38:29.120", "Id": "251635", "ParentId": "251625", "Score": "4" } }, { "body": "<h2>Overview</h2>\n<p>You have two namespaces.<br />\nAny particular reason?</p>\n<p>You tried to implement move semantics for the Vector. You missed the move assignment. But you forget to implement move semantics for the <code>T</code> type. So large types in your vector are expensive to use.</p>\n<p>You don't provide the strong exception guarantee. You should definitely try. If something throws your object can be left in a bad state.</p>\n<p>The standard for this:</p>\n<pre><code>// 1: Do anything the can throw on temporary objects.\n// 2: Use noexcept safe functions to swap temp with state.\n// 3: Cleanup.\n</code></pre>\n<p>A couple of <code>const</code> correctness issues.</p>\n<h2>Code Review:</h2>\n<p>Seems relatively generic. I might expect this to have already been used. I normally include the namespace as part of the guard macro.</p>\n<pre><code>#ifndef VECTOR_H_\n#define VECTOR_H_\n</code></pre>\n<hr />\n<p>I would expect <code>swap()</code> to be implemented as a member method but not required. The friend function swap then simply calls the member function.</p>\n<p>But you do want to mark it as <code>noexcept</code>. This is because you also want to mark the move constructor / move assignment as noexcept and the easy way to implement these is to call <code>swap</code>.</p>\n<pre><code> friend void swap( Vector &amp;lhs, Vector &amp;rhs )\n</code></pre>\n<hr />\n<p>Yes. But be careful with this declaration.</p>\n<pre><code> T* memory_block;\n</code></pre>\n<p>When you allocate you don't want to construct.</p>\n<hr />\n<p>The problem here:</p>\n<pre><code> Vector() : size_index( 0 ), vector_capacity( 1 ), memory_block ( new T[ vector_capacity ]{} ){}\n</code></pre>\n<p>You are constructing <code>T</code> here. This has a couple of issues. The type <code>T</code> may not have a default constructor. The type <code>T</code> may be very expensive to construct so you don't actually want to construct until you know you are going to use it. Think about when you resize the vector from 100 -&gt; 200 elements. You are now going to construct 100 elements but you may only use 1 of those 100 elements. Do you really want to pay the cost? When you reduce the size of the vector you currently cannot destroy the object but the user may want to force the release of the resources.</p>\n<p>So in general you want to allocate space but you don't want to construct the object. That is why we keep a capacity and a size as different values.</p>\n<hr />\n<p>On the same sort of vein:</p>\n<p>In this constructor you are constructing <code>sz</code> objects of type <code>T</code>:</p>\n<pre><code> Vector( std::size_t sz, const T &amp;val ) : Vector( sz )\n</code></pre>\n<p>Then the first thing you do is copy over all the elements in the container. So you are basically destroying the old value and re-creating the new values.</p>\n<pre><code> {\n for( std::size_t i = 0; i != vector_capacity; ++i ) {\n memory_block[ i ] = val;\n ++size_index;\n }\n }\n</code></pre>\n<p>This means you have effectively done the same work twice. Also you are copying elements that are not valid. Simply copy <code>size</code> not <code>capacity</code> elements.</p>\n<hr />\n<p>I saw you define iterators.<br />\nWhy can I not use the range-based <code>for</code> loop here?</p>\n<pre><code> for( std::size_t i = 0; i != vector_capacity; ++i ) {\n memory_block[ i ] = val;\n ++size_index;\n }\n</code></pre>\n<hr />\n<p>Yep. But declare the move constructor as <code>noexcept</code>.</p>\n<pre><code> Vector( Vector &amp;&amp;other_vec ) { swap( *this, other_vec ); }\n</code></pre>\n<p>What happened to the move assignment operator?</p>\n<p>The reason for marking the move operations as <code>noexcept</code> is that it allows certain optimizations when your object is placed into container.</p>\n<hr />\n<p>Good try. But you potentially leak.</p>\n<pre><code> void push_back( const T &amp;val )\n {\n\n // STUFF\n\n T * new_memory_block = new T[ vector_capacity * 2 ];\n\n // What happens if the copy constructor of T throws\n // an exception during this operation?\n //\n // In that case you have leaked `new_memory_block`\n // and all the resources held by the T objects in this\n // block. \n for( std::size_t i = 0; i != size_index; ++i )\n new_memory_block[ i ] = memory_block[ i ];\n\n // What happens if the destructor throws in a T?\n // probably an application quits but you don't know.\n //\n // If the delete throws and is escapes the destructor\n // and the excetion is caught higher in the call stack\n // then you have leaked `new_memory_block` and resouces\n // this object is in an invlalid state as the memory_block\n // is no longer valid.\n delete [] memory_block;\n\n // Sure this is safe. :-)\n memory_block = new_memory_block;\n vector_capacity *= 2;\n }\n memory_block[ size_index++ ] = val;\n }\n</code></pre>\n<p>A simpler way to implement this:</p>\n<pre><code> void push_back( const T &amp;val )\n {\n if( size_index &gt;= vector_capacity ) {\n Vector&lt;T&gt; temp(vector_capacity * 2);\n std::move(std::begin(*this), std::end(*this), std::begin(temp)); \n swap(*this, temp);\n }\n memory_block[ size_index++ ] = val;\n }\n</code></pre>\n<hr />\n<p>The push back is fine:</p>\n<pre><code> void push_back(T const&amp; val);\n</code></pre>\n<p>But <code>T</code> could be large. You should allow <code>T</code> to be moved into your vector or constructed in place.</p>\n<pre><code> void push_back(T&amp;&amp; val);\n template&lt;typename... Args)\n void emplace_back(Args&amp;&amp;... args);\n</code></pre>\n<hr />\n<p>In your <code>insert</code>, you copy elements when resizing.</p>\n<pre><code> void insert( int index, const T&amp; val )\n {\n // This is a copy operation not a move operation.\n // If T is large then this can be costly.\n memory_block[ temp_index + 1 ] = memory_block[ temp_index ];\n }\n }\n\n }\n</code></pre>\n<hr />\n<p>Interesting:</p>\n<pre><code> void clear()\n {\n delete [] memory_block;\n memory_block = nullptr;\n size_index = 0;\n }\n</code></pre>\n<hr />\n<p>For const versions of <code>front()</code> and back. I would expect them to return a const reference.</p>\n<pre><code> T&amp; front() const { return memory_block[ 0 ]; }\n T&amp; back() const { return memory_block[ size_index - 1 ]; }\n</code></pre>\n<hr />\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T19:20:31.803", "Id": "251673", "ParentId": "251625", "Score": "4" } } ]
{ "AcceptedAnswerId": "251673", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T23:22:34.400", "Id": "251625", "Score": "5", "Tags": [ "c++", "beginner", "reinventing-the-wheel", "stl" ], "Title": "Custom STL Vector container Implementation" }
251625
<p><a href="https://leetcode.com/problems/longest-common-prefix/submissions/" rel="nofollow noreferrer">Link here</a> I'm currently learning c++ coming from a python background, so I'll include a solution in python and in c++ for the problem statement below, I'm including both for convenience, if you don't know c++, feel free to review python and vice versa.</p> <blockquote> <p>Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string &quot;&quot;.</p> </blockquote> <p><strong>Example 1:</strong></p> <p>Input: <code>words = ['flower', 'flow', 'flight']</code></p> <p>Output: <code>'fl'</code></p> <p><strong>Example 2:</strong></p> <p>Input: <code>strs = ['dog', 'racecar', 'car']</code></p> <p>Output: <code>''</code></p> <p><code>longest_common_prefix.py</code></p> <pre><code>def get_longest(words): if not words: return '' common = words[0] for word in words: while not word.startswith(common): common = common[:-1] return common if __name__ == '__main__': print(f&quot;Longest prefix: \n{get_longest(['flower', 'flow', 'fly'])}&quot;) </code></pre> <p><strong>Leetcode stats:</strong></p> <ul> <li><p>Runtime: 32 ms, faster than 76.56% of Python3 online submissions for Longest Common Prefix.</p> </li> <li><p>Memory Usage: 14 MB, less than 100.00% of Python3 online submissions for Longest Common Prefix.</p> </li> </ul> <p><code>longest_common_prefix.h</code></p> <pre><code>#ifndef LEETCODE_LONGEST_COMMON_PREFIX_H #define LEETCODE_LONGEST_COMMON_PREFIX_H #include &lt;string_view&gt; #include &lt;vector&gt; std::string_view get_common_prefix(const std::vector&lt;std::string_view&gt;&amp; words); #endif //LEETCODE_LONGEST_COMMON_PREFIX_H </code></pre> <p><code>longest_common_prefix.cpp</code></p> <pre><code>#include &lt;iostream&gt; #include &lt;string_view&gt; #include &lt;vector&gt; std::string_view get_common_prefix(const std::vector&lt;std::string_view&gt; &amp;words) { if (words.empty()) return &quot;&quot;; std::string_view common = words[0]; for (auto word: words) { while (word.find(common, 0) != 0) { common = common.substr(0, common.size() - 1); } } return common; } int main() { std::vector&lt;std::string_view&gt; xxx{&quot;flow&quot;, &quot;flower&quot;, &quot;fly&quot;}; std::cout &lt;&lt; &quot;Longest prefix:\n&quot; &lt;&lt; get_common_prefix(xxx); } </code></pre> <p><strong>Leetcode stats:</strong></p> <ul> <li>Runtime: 0 ms, faster than 100.00% of C++ online submissions for Longest Common Prefix.</li> <li>Memory Usage: 9.9 MB, less than 7.29% of C++ online submissions for Longest Common Prefix.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T03:44:31.020", "Id": "495485", "Score": "0", "body": "[I posted a question on meta](https://codereview.meta.stackexchange.com/questions/10574/are-you-allowed-to-ask-for-reviews-of-the-same-program-written-in-two-languages) taking this into consideration( 2 languages ). You might want to see what others have to say" } ]
[ { "body": "<p>I'm only going to review the C++ code here, as all I could suggest for the Python code also applies to the C++, so is included in this review.</p>\n<p>Firstly, the interface is quite limiting - the inputs need to be converted to vector of string-view objects, which is inconvenient if I have a linked-list of strings, or an input stream yielding <code>QString</code>s. I recommend changing to accept a pair of iterators, or in sufficiently modern C++, a <strong><code>std::ranges::range</code></strong> object.</p>\n<p>This test is inefficient:</p>\n<pre><code>word.find(common, 0) != 0\n</code></pre>\n<p>If we don't find <code>common</code> at position 0, <code>find()</code> will continue searching the rest of the string (the Python code is better here). We need an implementation of <code>starts_with()</code> (which is in C++20's <code>std::string</code>) - or better, we could use <code>std::mismatch()</code> to directly find how much of the strings are common, eliminating the loop where we repeatedly remove a single character.</p>\n<p>Here's my attempt at that, also with a simple optimisation to return early when the common string becomes empty:</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iterator&gt;\n#include &lt;string_view&gt;\n#include &lt;vector&gt;\n\nnamespace\n{\n template&lt;typename String&gt;\n String common_prefix(const String&amp; a, const String&amp; b)\n {\n using std::begin;\n using std::end;\n auto end_iter = std::mismatch(begin(a), end(a), begin(b), end(b));\n if (end_iter.first == end(a)) { return a; }\n if (end_iter.second == end(b)) { return b; }\n return String(begin(a), end_iter.first - begin(a));\n }\n}\n\ntemplate&lt;typename Iter, typename IterEnd = Iter&gt;\nstd::string_view get_common_prefix(Iter first, IterEnd last)\n{\n if (first==last) { return &quot;&quot;; }\n std::string_view common = *first;\n for (auto it = first; it != last; ++it) {\n common = common_prefix(common, *it);\n if (common.empty()) { return common; }\n }\n return common;\n}\n\ntemplate&lt;typename Container&gt;\nstd::string_view get_common_prefix(const Container&amp; words)\n{\n using std::begin;\n using std::end;\n return get_common_prefix(begin(words), end(words));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T16:30:01.387", "Id": "495579", "Score": "2", "body": "Yes, `starts_with()` is [in C++20](https://en.cppreference.com/w/cpp/string/basic_string/starts_with). But I didn't dwell on that, because we can do better with our own `common_prefix()` function." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T16:23:19.883", "Id": "251664", "ParentId": "251628", "Score": "4" } } ]
{ "AcceptedAnswerId": "251664", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T00:52:43.197", "Id": "251628", "Score": "2", "Tags": [ "python", "c++", "programming-challenge" ], "Title": "Longest common prefix (Leetcode)" }
251628
<p>In the below code I've implemented a method to find the lowest common ancestor of a binary tree.</p> <p>This is an iterative approach using <a href="https://afteracademy.com/blog/lowest-common-ancestor-of-a-binary-tree" rel="nofollow noreferrer">this</a> pseudocode.</p> <p>Please suggest any improvements that can be made.</p> <pre><code>class Node: def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right def lowest_common_ancestor(root, node1, node2): parent = {root: None} stack = [root] while node1 not in parent or node2 not in parent: node = stack[-1] stack.pop() if node.left: parent[node.left] = node stack.append(node.left) if node.right: parent[node.right] = node stack.append(node.right) ancestors = set() while node1: ancestors.add(node1) node1 = parent[node1] while node2 not in ancestors: node2 = parent[node2] return node2.data def main(): ''' Construct the below binary tree: 30 / \ / \ / \ 11 29 / \ / \ 8 12 25 14 ''' root = Node(30) root.left = Node(11) root.right = Node(29) root.left.left = Node(8) root.left.right = Node(12) root.right.left = Node(25) root.right.right = Node(14) print(lowest_common_ancestor(root, root.left.left, root.left.right)) # 11 print(lowest_common_ancestor(root, root.left.left, root.left)) # 11 print(lowest_common_ancestor(root, root.left.left, root.right.right)) # 30 if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<h2>Unit tests</h2>\n<p>Turn these:</p>\n<pre><code>print(lowest_common_ancestor(root, root.left.left, root.left.right)) # 11\nprint(lowest_common_ancestor(root, root.left.left, root.left)) # 11\nprint(lowest_common_ancestor(root, root.left.left, root.right.right)) # 30\n</code></pre>\n<p>into assertions of the form <code>assert 11 == ...</code>, and you'll immediately have a unit test, which is generally of greater value.</p>\n<h2>Pop</h2>\n<pre><code>node = stack[-1]\nstack.pop()\n</code></pre>\n<p>should not be necessary; that's what <code>pop</code> already does:</p>\n<pre><code>node = stack.pop()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T02:01:27.510", "Id": "251632", "ParentId": "251629", "Score": "1" } }, { "body": "<p>You did <em>not</em> tag <a href=\"/questions/tagged/beginner\" class=\"post-tag\" title=\"show questions tagged &#39;beginner&#39;\" rel=\"tag\">beginner</a> - let me just mention there <em>are</em> <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">deviations</a> from the <a href=\"https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a>.<br />\nYou show a minimalistic <code>Node</code>: I added<br />\n<code>def __repr__(self):</code><br />\n<code> return '‹'+str(self.left)+'#'+str(self.data)+'#'+str(self.right)+'›'</code></p>\n<p>You chose to tackle &quot;LCA&quot; from nodes that do not allow to get the parent in constant time: interesting.<br />\nYou chose to solve a problem in a recursive data structure avoiding recursion: oh well.</p>\n<p>You start by building a supplementary data structure adding parent information until provably sufficient. I'm all for &quot;early out&quot; in programming.<br />\nYou can go further down that road by checking first if one node specified is a descendent of the other one.<br />\nYou implement <em>depth first traversal</em> (right-to-left, without so much as mentioning either).<br />\nThis may spend fruitless effort limited by the size of the tree, only.<br />\nIf you do <em>breadth first traversal</em>s from the root and both nodes concurrently, you will stay within a constant factor of the minimum node visits required.<br />\n<code>lowest_common_ancestor()</code> as presented returns the LCA's <code>data</code> instead of the node itself - don't do that, use a wrapper where necessary.</p>\n<hr />\n<p>Only revisiting the hyperlinked pseudo-code I appreciated how faithfully you transcribed it to Python. I wish you used more comments rather than less, though.<br />\n(The <em>Critical Ideas to Think</em> are quite good.)<br />\nI think I didn't like the iterative alternative for using O(n) <em>additional</em> space, <em>expected</em> as well as worst case.<br />\nI made <code>Node</code> an <code>Iterable</code> in hopes of seeing whether the approach carries to <em>k</em>-ary trees:<br />\n<code> def __iter__(self):</code><br />\n<code> return (self.left, self.right).__iter__()</code><br />\nI renamed <code>stack</code> <code>to_do</code> as that's what I see it used for. If I don't pop the <code>Node</code>s whose children I'm about to push, I have all ancestors in the stack. Worst case remains O(n) space, but expected case is linear in the depth of the tree. Trying to work out the details:</p>\n<pre><code># LCA avoiding recursion and O(n) additional space\ndef lowest_common_ancestor(root, node1, node2):\n &quot;&quot;&quot; return lowest common ancestor of node1 and node2\n in the tree at root, else None.\n A node is an ancestor of itself. &quot;&quot;&quot;\n# *if* ready to assume the other node under root, too\n# if root is node1 or root is node2\n# return root\n# if node1 is node2:\n# return node1\n if None in (root, node1, node2):\n return None\n\n # traverse the tree from root\n # depth first keeps all ancestors accessible with limited overhead\n # right-to-left is a non-consequential implementation artefact\n to_do = [root]\n # length of to_do including candidate LCA as last element\n candidate_len = 0\n\n while to_do:\n # the easy part: check if done, push nodes to process\n node = to_do[-1]\n if node is node1 or node is node2:\n if 0 &lt; candidate_len:\n return to_do[candidate_len-1]\n candidate_len = len(to_do)\n leaf = True\n for child in node:\n if child:\n leaf = False\n to_do.append(child)\n if not leaf:\n continue\n # the difficult part:\n # get rid of nodes processed\n # updating candidate_len\n while True:\n # either processed above\n # or a parent with all descendants processed\n node = to_do.pop()\n if not to_do:\n return None\n check = to_do[-1]\n if node not in check: # check is a sibling not yet processed\n break\n n = len(to_do)\n if n &lt;= candidate_len:\n # XXX &quot;knows&quot; exactly one sibling left\n candidate_len = n - 1\n # (the alternative being a (&quot;branching factor limited&quot;)\n # search from the end for node's parent\n return None\n</code></pre>\n<p>Contributing to my lack of enthusiasm in implementing a proper &quot;parent search&quot;: 1) <code>index(needle)</code> as a <em>common sequence operation</em>, but no <code>rindex()</code> (as with <code>bytearray</code> or <a href=\"https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/List.html#lastIndexOf(java.lang.Object)\" rel=\"nofollow noreferrer\">Java's <code>int List.lastIndexOf(needle)</code></a>) 2) such operation using some notion of equality rather than <em>parent</em>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T08:14:53.520", "Id": "495654", "Score": "0", "body": "I would have preferred `__str__(self)` over `repr` if that was effective in my IDE." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-22T21:16:36.653", "Id": "497563", "Score": "0", "body": "Didn't manage to code *concurrent traversals* or *minimum comparison search* without ugly code multiplication." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T08:14:19.170", "Id": "251695", "ParentId": "251629", "Score": "1" } } ]
{ "AcceptedAnswerId": "251632", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T00:56:45.140", "Id": "251629", "Score": "2", "Tags": [ "python", "algorithm", "tree", "binary-tree" ], "Title": "Lowest Common Ancestor in Binary Tree (Iterative)" }
251629
<p>Explanation: Although merge sort runs in Ω(nlgn) and insertion sort runs in Ω(n^2), the constant factors in insertion sort can make it faster in implementation for small problem sizes. This sorting implementation should still be stable.</p> <p>Recursive Merge sort subroutine method:</p> <pre><code>private static void recursiveMergeSort(double[] arr, int lowerBound, int upperBound) { if (lowerBound &lt; upperBound) { // Split the sub array into halves int mid = lowerBound + (upperBound - lowerBound) / 2; recursiveMergeSort(arr, lowerBound, mid); recursiveMergeSort(arr, mid + 1, upperBound); merge(arr, lowerBound, mid, upperBound); } } </code></pre> <p>Merge method: *note- I would like to replace the while loop with for and if-else statements.</p> <pre><code>private static void merge(double[] arr, int left, int mid, int right) { int i = 0, j = 0, k = left; //System.out.println(&quot;used merge&quot;); // Sizes of the temporary arrays to be copied int n1 = (mid - left) + 1; int n2 = (right - mid); // Create temporary arrays and copy data double[] leftTemp = Arrays.copyOfRange(arr, left, mid + 1); double[] rightTemp = Arrays.copyOfRange(arr, mid + 1, right + 1); // Merge the temp arrays back into arr[left...right] while (i &lt; n1 &amp;&amp; j &lt; n2) { if (leftTemp[i] &lt;= rightTemp[j]) { arr[k++] = leftTemp[i++]; } else { arr[k++] = rightTemp[j++]; } } // Copy remaining elements, if any while (i &lt; n1) { arr[k++] = leftTemp[i++]; } while (j &lt; n2) { arr[k++] = rightTemp[j++]; } } </code></pre> <p>Insertion sort subroutine method:</p> <pre><code>private static void insertionSort(double[] arr, int left, int right){ for (int i = left + 1; i &lt;= right; i++) { double key = arr[i]; int j = i - 1; while (j &gt;= left &amp;&amp; arr[j] &gt; key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } } </code></pre> <p>Hybrid merge/insertion sorting method:</p> <p>Optimized is a value that is best set between [25,100]</p> <pre><code>private static void insertionRecursiveMergeSort(double[] arr, int left, int right) { // If &lt;= OPTIMIZED use insertion sort subroutine if (right &lt;= left + OPTIMIZED - 1) { insertionSort(arr, left, right); } else { int mid = left + (right - left) / 2; insertionRecursiveMergeSort(arr, left, mid); insertionRecursiveMergeSort(arr, mid + 1, right); merge(arr, left, mid, right); } } </code></pre> <p>For test runs, I used array sizes 1M, 2M, 3M, and 5M with optimized set to 25, 50, 100, and 125.</p>
[]
[ { "body": "<p>Optimization notes.</p>\n<ul>\n<li><p>Allocate the temporary array once, and pass it down to the recursive invocations.</p>\n</li>\n<li><p><strike> Do not fall back to the insertion sort immediately. Postpone it until all the recursions complete, and insertion sort the entire array once.</p>\n<p>It feels scary to insertion sort the entire array. Wouldn't it degrade performance to <span class=\"math-container\">\\$O(n^2)\\$</span>? The answer is no. The array is already &quot;almost sorted&quot;: every element is at most <code>OPTIMIZED</code> away from its final destination. Therefore, an inner loop does at most <code>OPTIMIZED</code> iterations per element, and the overall complexity is <span class=\"math-container\">\\$O(n * \\texttt{OPTIMIZED})\\$</span>. This observation also hints that <code>OPTIMIZED</code> should be in a ballpark of <span class=\"math-container\">\\$\\log n\\$</span>.</strike></p>\n<p><strong>Edit</strong>: I don't know what I was thinking. The above is totally wrong (it is valid for quicksort, but not here), except the observation that <code>OPTIMIZED</code> should be in a ballpark of <span class=\"math-container\">\\$\\log n\\$</span>.</p>\n</li>\n<li><p>A little-known trick allows to cut the number of comparisons in the insertion sort in half. Instead of</p>\n<pre><code> while (j &gt;= left &amp;&amp; arr[j] &gt; key)\n</code></pre>\n<p>consider first comparing <code>key</code> to <code>arr[left]</code>:</p>\n<pre><code> if (key &lt; arr[left]) {\n // The key shall land at the left. No need to compare values anymore\n for (j = i; j &gt; 0; j--) {\n arr[j] = arr[j-1];\n }\n } else {\n // arr[left] is a natural sentinel. No need to compare indices anymore\n for (j = i; arr[j] &gt; key; j--) {\n arr[j] = arr[j-1];\n }\n }\n</code></pre>\n<p>Now if you opt for a postponed insertion sort, it could be optimized even more: find the min among first <code>OPTIMIZED</code> elements and swap it with <code>arr[0]</code>. Now there is no need to test for <code>key &lt; arr[left]</code> - it is guaranteed to fail. Go straight into the unguarded loop.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T16:43:19.127", "Id": "251666", "ParentId": "251634", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T02:32:55.760", "Id": "251634", "Score": "4", "Tags": [ "java", "sorting", "mergesort", "insertion-sort" ], "Title": "Hybrid Merge/Insertion sort algorithm" }
251634
<p>The <code>check_celebrity()</code> function below takes an <code>n*n</code> grid as its parameter and prints the celebrity if there is one.</p> <p>A celebrity is a person who is known by everybody but doesn't know anybody except himself.</p> <p>If <code>grid [ i ] [ j ]</code> equals 1, &quot;i&quot; knows &quot;j&quot;.<br /> If <code>grid [ i ] [ j ]</code> equals 0, &quot;i&quot; doesn't know &quot;j&quot;.</p> <p>However, I am not satisfied with this one because there are too many loops inside loops and if checks. Are there any ways I can improve it?</p> <pre class="lang-py prettyprint-override"><code>def check_celebrity(grid): known = 0 unknown = 0 for i in range(len(grid)): ## Reset these variable for every person i known = 0 unknown = 0 for j in range(len(grid)): if grid[i][j] == 0: unknown += 1 ## if he doesn't know anybody, ## check if every other &quot;j&quot; knows him if unknown == len(grid)-1: for j in range(len(grid)): if grid[j][i] == 1: known += 1 if known == len(grid): print(&quot;#{} is the one.&quot;.format(i)) break </code></pre> <pre class="lang-py prettyprint-override"><code>#These can be used as test cases ## 0 is a celebrity. grid = [ [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 1, 0], [1, 0, 1, 0] ] ## 2 is a celebrity grid = [ [0, 0, 1, 0, 0], [0, 1, 1, 0, 1], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [1, 0, 1, 1, 1] ] </code></pre>
[]
[ { "body": "<p>Welcome to Code Review, few suggestions:</p>\n<ul>\n<li>Instead of calling <code>.format()</code> you can use f-Strings: <code>print(f&quot;#{i} is the one.&quot;)</code></li>\n<li>Is better to return the result, instead of printing in the method and <code>break</code></li>\n<li>You can use <code>all()</code> to test the celebrity and make the code more compact.</li>\n</ul>\n<p>Applying the suggestions:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def check_celebrity(grid):\n for i in range(len(grid)):\n # Check if i is a candidate celebrity\n if grid[i][i] == 1 and grid[i].count(1) == 1:\n # Ensure that i is a celebrity\n if all(grid[j][i] == 1 for j in range(len(grid))):\n return i\n</code></pre>\n<p>Test:</p>\n<pre class=\"lang-py prettyprint-override\"><code>grid = [ [1, 0, 0, 0],\n [1, 0, 0, 0],\n [1, 0, 1, 0],\n [1, 0, 1, 0] ]\n\nprint(f&quot;#{check_celebrity(grid)} is the one.&quot;)\n# Outputs: #0 is a celebrity\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T06:42:37.150", "Id": "251642", "ParentId": "251638", "Score": "2" } }, { "body": "<h1>Benchmarks</h1>\n<p>Before we make changes, I'll measure the time taken by the <code>check_celebrity()</code>\nfunction executed <code>i</code> times on a <code>5x5</code> grid</p>\n<p>Note that I have made a small change, I am returning the celebrity ID rather than printing to cut the cost of <code>print()</code></p>\n<pre class=\"lang-py prettyprint-override\"><code># Number of iterations | Time taken (seconds)\n# ---------------------------------------------\n# 10 ^ 5 | 0.385\n# 10 ^ 6 | 3.428\n# 10 ^ 7 | 35.049\n</code></pre>\n<hr />\n<h1>Use <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">f-strings</a></h1>\n<p>Compared to using <code>.format()</code>, Python-3 has <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">f-strings</a> which provide a nicer way of formatting strings</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(f&quot;{i} is the one&quot;)\n</code></pre>\n<hr />\n<h1><a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't repeat yourself</a></h1>\n<pre class=\"lang-py prettyprint-override\"><code> known = 0\n unknown = 0\n\n for i in range(len(grid)):\n known = 0\n unknown = 0\n</code></pre>\n<p>You are going to initialize <code>known, unknown </code> with <code>0</code> in the loop anyway, why do it again outside the loop?</p>\n<pre class=\"lang-py prettyprint-override\"><code> for i in range(len(grid)):\n ## Reset these variable for every person i\n known = 0\n unknown = 0\n</code></pre>\n<hr />\n<h1>Use a tuple</h1>\n<p>Since you don't need to modify <code>grid</code>, shift to a tuple as <a href=\"https://stackoverflow.com/questions/3340539/why-is-tuple-faster-than-list-in-python\"> it will be faster</a></p>\n<hr />\n<h1>Optimize #1</h1>\n<pre class=\"lang-py prettyprint-override\"><code> for j in range(len(grid)):\n if grid[i][j] == 0:\n unknown += 1\n\n ## if he doesn't know anybody,\n ## check if every other &quot;j&quot; knows him\n if unknown == len(grid)-1\n</code></pre>\n<p>The second condition will only be true if the first one is also true because the value of <code>unknown</code> remains the same if the first condition evaluates to false. The question says that</p>\n<blockquote>\n<p>if grid [ i ][ j ] == 1 , i knows j</p>\n</blockquote>\n<p>If <code>i</code> knows <code>j</code> and <code>i != j</code>, we can be certain that <code>i</code> isn't our celebrity, so we can directly skip this loop and go to the next person - <code>break</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code> for j in range(len(grid)):\n if (grid[i][j] == 1) and (i != j):\n break\n\n unknown += 1\n</code></pre>\n<hr />\n<h1>Optimize #2</h1>\n<p>Out of the two conditions, we have already checked one. So now all we need to do is check the other one. if either of those conditions fails, we immediately exit the loop. If the whole inner loop has been iterated through without anything failing, then <code>j == len(grid-1)</code>, so at the end, we check for this, if it's true we return <code>i</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def check_celebrity(grid):\n r = range(len(grid))\n for i in r:\n is_celeb = True\n for j in r:\n if (grid[i][j] == 1) and (i != j):\n break\n if (grid[j][i] == 0) and (i != j):\n break\n\n if j == len(grid)-1: return i\n</code></pre>\n<p>Smashed into one statement</p>\n<pre class=\"lang-py prettyprint-override\"><code>def check_celebrity(grid):\n r = range(len(grid))\n for i in r:\n for j in r:\n if (i != j and (( not grid[j][i]) or (grid[i][j] == 1))):\n break\n\n if j == len(grid)-1: return i\n</code></pre>\n<hr />\n<h1>Test</h1>\n<p>I will use the 4 tests given on the <a href=\"http://programarcadegames.com/worksheets/show_file.php?file=worksheet_16.php\" rel=\"nofollow noreferrer\">website</a> <br>\nI designed a simple function to do this</p>\n<pre class=\"lang-py prettyprint-override\"><code>def test(grid, test_no,correct_answer):\n print(f&quot;Test number {test_no} \\nCorrect answer: {correct_answer}&quot;)\n print(f&quot;Returned answer: #{check_celebrity(grid)}\\n\\n&quot;)\n</code></pre>\n<p>Tests</p>\n<pre class=\"lang-py prettyprint-override\"><code>grid1 = [ [1, 1, 1, 0],\n [0, 1, 1, 0],\n [0, 0, 1, 0],\n [1, 0, 1, 1] ]\n\ntest(grid1, 1, &quot;#2&quot;)\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>grid2 = [ [1, 1, 1, 0, 1],\n [0, 1, 1, 0, 1],\n [0, 0, 1, 0, 0],\n [1, 0, 0, 1, 1],\n [1, 0, 0, 1, 1] ]\ntest(grid2, 2, &quot;#None&quot;)\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>grid3 = [ [1, 1, 1, 0, 1],\n [0, 1, 1, 0, 1],\n [0, 0, 1, 0, 0],\n [0, 0, 1, 0, 1],\n [1, 0, 1, 1, 1] ]\ntest(grid3, 3, &quot;#2&quot;)\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>grid4 = [ [1, 1, 1, 0, 1],\n [0, 1, 1, 0, 1],\n [1, 0, 1, 0, 0],\n [0, 0, 1, 0, 1],\n [1, 0, 1, 1, 1] ]\n\ntest(grid4, 4, &quot;#None&quot;)\n</code></pre>\n<p>Results</p>\n<pre><code>Test number 1\nCorrect answer: #2\nReturned answer: #2\n\n\nTest number 2\nCorrect answer: #None\nReturned answer: #None\n\n\nTest number 3\nCorrect answer: #2\nReturned answer: #2\n\n\nTest number 4\nCorrect answer: #None\nReturned answer: #None\n</code></pre>\n<ul>\n<li>Grids are copy-pasted from the original question, hence they are <code>[[]]</code> and not <code>(())</code>. I will switch to tuples for the <strong>new</strong> code</li>\n</ul>\n<hr />\n<h1>Comparison</h1>\n<h2>Old</h2>\n<pre class=\"lang-py prettyprint-override\"><code># Number of iterations | Time taken (s)\n# ---------------------------------------------\n# 10 ^ 5 | 0.385\n# 10 ^ 6 | 3.428\n# 10 ^ 7 | 35.049\n</code></pre>\n<h2>New</h2>\n<pre class=\"lang-py prettyprint-override\"><code># Number of iterations | Time taken (s)\n# ---------------------------------------------\n# 10 ^ 5 | 0.256\n# 10 ^ 6 | 1.815\n# 10 ^ 7 | 17.518\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>def check_celebrity(grid):\n r = range(len(grid))\n for i in r:\n for j in r:\n if (i != j and (( not grid[j][i]) or (grid[i][j] == 1))):\n break\n\n if j == len(grid)-1: return i\n\ngrid = ( (1, 1, 1, 0, 1),\n (0, 1, 1, 0, 1),\n (0, 0, 1, 0, 0),\n (0, 0, 1, 0, 1),\n (1, 0, 1, 1, 1) )\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T03:35:54.697", "Id": "495639", "Score": "0", "body": "Thanks a lot for the detailed improvements. This solution always works whenever there is just one \"1\" at the position where `\"i\" == \"j\"` regardless of the ones or zeros on that column. That is, the loop just checks if \" i \" knows anybody and not the other way around. For example if you change `grid2[3][2]` to 0, it will still work although it shouldn't because that means there is someone who doesn't know `\"i\"`. Therefore, I think there must be another if check for the column in the first loop. Please correct me if I am wrong or missing something. Thanks a lot in advance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T07:37:49.507", "Id": "495651", "Score": "0", "body": "@Bilgili I tested it with all cases on the website, it works just as expected." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T12:14:50.667", "Id": "495679", "Score": "1", "body": "Okay, I gave it a second try by copying and pasting your code under the **New** heading and the following grid from the website which is the 2nd test: `grid = [[1, 1, 1, 0, 1],[0, 1, 1, 0, 1],[0, 0, 1, 0, 0],[1, 0, 0, 1, 1],[1, 0, 0, 1, 1] ]`. There is no celebrity here but the function returns #2 as a celebrity. I can't see what I am missing. Could you please clarify this for me?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T15:44:29.550", "Id": "495705", "Score": "1", "body": "@Bilgili Please check my new answer, you are right. I made a horrible, stupid mistake, really sorry about that. I have updated the answer and the benchmarks, I hope everything is alright now :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T07:28:44.380", "Id": "251643", "ParentId": "251638", "Score": "3" } } ]
{ "AcceptedAnswerId": "251643", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T05:18:52.253", "Id": "251638", "Score": "4", "Tags": [ "python-3.x", "programming-challenge", "pygame" ], "Title": "Program Arcade Games: Ch 16 Worksheet 2D-Array Algorithm" }
251638
<p>I was given the following prompt in a coding interview:</p> <blockquote> <p>Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.</p> <p>For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]</p> </blockquote> <p>I solved this in two ways:</p> <ul> <li><code>fun</code> multiplies all elements together in the first iteration, and then loops again and divides by the number at that position</li> <li><code>fun2</code> does not use division, and instead iteratively builds up the sum in each index</li> </ul> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int fun(int* nums, int arr_size) { int sum; int i; for(i=0, sum=1; i&lt;arr_size; i++) sum*=nums[i]; for(i=0; i&lt;arr_size; i++) nums[i]=sum/nums[i]; return 0; } int fun2(int* nums, int arr_size) { int i,j; int sum=1; int new_arr[arr_size]; for(i=0; i&lt;arr_size; i++) { for(j=0; j&lt;arr_size; j++) { if(i!=j) sum*=nums[j]; //skip member same index in the loop } new_arr[i]=sum; sum=1; } memcpy(nums, new_arr, arr_size*sizeof(int)); return 0; } int main(void) { /*Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24] */ int nums[] = {1, 2, 2, 4, 6}; int size = sizeof(nums)/sizeof(nums[0]); int i; fun(nums, size); for (i = 0; i &lt; size; i++) printf(&quot;%d &quot;, nums[i]); //what if you can't use division? printf(&quot;\n&quot;); int nums2[] = {1, 2, 2, 4, 6}; fun2(nums2, size); for (i = 0; i &lt; size; i++) printf(&quot;%d &quot;, nums2[i]); return 0; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T13:12:56.940", "Id": "495545", "Score": "7", "body": "It feels like this might have a mathematical solution that gives better time complexity then O(N²) for `fun2` but I am not good enough at math to find it, so my only nit pick for `fun2` is that you don't need the `sum` var. Just use `new_arr[i]` directly. Also, I would suggest moving the description of what the code does from comment in `main` to actual text of you question above the code to make it easy for other users find it. It is easy to miss and people might ignore the question if they don't know what the code is suppose to produce." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T15:20:40.683", "Id": "495558", "Score": "4", "body": "Please make up your mind. Is it about **sum** or about **product**?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T15:21:29.853", "Id": "495559", "Score": "3", "body": "You're supposed to \"return a new array\" but your first solution doesn't even create one and the second solution doesn't return it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T15:22:32.503", "Id": "495560", "Score": "7", "body": "Your first code fails if there's a zero." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T16:00:26.910", "Id": "495572", "Score": "2", "body": "@superbrain both solutions return an array in the original array passed in, the problem with it is the original data is destroyed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T22:13:11.160", "Id": "495622", "Score": "2", "body": "@LevM.At a cost of additional array you can reduce the `fun2` complexity to O(N). Just sweep the input up and down to calculate a running product of the input array's prefixes and the input array's suffixes. Then multiply them to get `result[i] = prefixproduct[i-1] * suffixproduct[i+1]` (with a necessary special handling of two edge cases)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T22:41:19.110", "Id": "495624", "Score": "0", "body": "@pacmaninbw I'd say calling that \"*returning* a *new* array\" is a bit of a stretch." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T13:01:06.047", "Id": "495801", "Score": "1", "body": "@CiaPan there’s a way to do this without requiring an array beyond the returned one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T09:32:56.453", "Id": "495979", "Score": "1", "body": "@Edward You're right, one array suffices." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T06:41:44.973", "Id": "496054", "Score": "1", "body": "@Edward, CiaPan Thanks for the hint. I will implement new function and add it to this thread." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T04:18:44.883", "Id": "496153", "Score": "0", "body": "@CiaPan new code here: https://codereview.stackexchange.com/questions/251929/product-of-all-but-one-number-in-a-sequence-follow-up" } ]
[ { "body": "<p>As mentioned by a commenter on the question, neither version satisfies the requirement to <strong>return a new array</strong>. I'll leave that for you to fix yourself (demonstrating your understanding of memory allocation to your interviewer).</p>\n<p>The division version requires some modification to work when one or more inputs are zero. I suggest keeping track of the position of any zero that is found on the first pass - if a second zero is found, all the results will be zero, and if a single zero is found, then all the results except at that position will be zero.</p>\n<p>That looks a bit like this:</p>\n<pre><code>void fun(int *nums, int arr_size)\n{\n int product = 1;\n int zero_pos = -1;\n\n for (int i = 0; i &lt; arr_size; i++) {\n if (nums[i]) {\n product *= nums[i];\n } else if (zero_pos &lt; 0) {\n zero_pos = i;\n } else {\n product = 0;\n break;\n }\n }\n\n if (zero_pos &lt; 0) {\n for(int i = 0; i &lt; arr_size; i++) {\n nums[i] = product / nums[i];\n }\n } else {\n for (int i = 0; i &lt; arr_size; i++) {\n nums[i] = (i == zero_pos) ? product : 0;\n }\n }\n}\n</code></pre>\n<p>I haven't made any attempt to deal with the risk of signed integer overflow in this code; that's as much a risk as it is in your original.</p>\n<p>There are some problems in <code>fun2()</code>: failure to include <code>&lt;string.h&gt;</code> for the use of <code>memcpy()</code> is the most serious there.</p>\n<p>We should use an unsigned type (probably <code>size_t</code>) for the size parameter. That also means that we don't have mixed-signedness arithmetic where we multiply by <code>sizeof</code>. Although having said that, we don't need to multiply - we can simply use <code>sizeof new_arr</code> (the whole array) and the compiler will manage that for us.</p>\n<p>We can also reduce the scope of several of the variables:</p>\n<pre><code>#include &lt;string.h&gt;\nvoid fun2(int *nums, int arr_size)\n{\n int new_arr[arr_size];\n\n for (int i = 0; i &lt; arr_size; i++) {\n int product = 1;\n for (int j = 0; j &lt; arr_size; j++) {\n if (i != j) {\n product *= nums[j];\n }\n }\n new_arr[i]=product;\n }\n memcpy(nums, new_arr, sizeof new_arr);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T17:20:56.043", "Id": "251670", "ParentId": "251647", "Score": "6" } }, { "body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Use all required <code>#include</code>s</h2>\n<p>The code uses <code>memcpy</code>, so it should <code>#include &lt;string.h&gt;</code>. It might still compile on your machine, with your compiler, but it's not portable.</p>\n<h2>Think about potential errors</h2>\n<p>As one of the comments correctly notes, if one of the entries has the value of zero, this line will have a problem:</p>\n<pre><code>nums[i]=sum/nums[i];\n</code></pre>\n<p>Also, what happens if the passed <code>arr_size</code> is zero or negative? What should the function return if there is exactly one item in the array? What if the passed pointer is <code>NULL</code>?</p>\n<h2>Follow directions exactly</h2>\n<p>The problem says to &quot;return a new array&quot; but that is not really what this code is doing. This code is overwriting the input array. One of the problems with that is that it's not possible to call this with a <code>const</code> pointer as mentioned in the next suggestion. It also means that rather than returning a meaningless constant value in all cases, the function should probably return a pointer.</p>\n<h2>Use <code>const</code> where practical</h2>\n<p>As mentioned above, the code should return a new array rather than overwriting the passed one. I would suggest that the function should be something like this:</p>\n<pre><code>int* exclusive_product(const int* nums, size_t nums_size)\n</code></pre>\n<p>Note that first, we use <code>const</code> and second, we use <code>size_t</code> rather than <code>int</code> for the second argument to more clearly indicate the type of variable we are expecting.</p>\n<h2>Use better variable names</h2>\n<p>I would say that <code>nums</code>, <code>size</code> and <code>i</code> are good variable names, but that <code>fun</code> and <code>fun2</code> and definitely <code>sum</code> are not. The problem is that <code>fun</code> doesn't tell the reader anything about what the code is supposed to do and <code>sum</code> is actually misleading (it's a <em>product</em>, not a <em>sum</em>).</p>\n<h2>Think about an efficient way to solve this</h2>\n<p>The <span class=\"math-container\">\\$O(n^2)\\$</span> code you have in <code>fun2</code> is not a terrible way to solve the problem and has the advantage of being obviously correct. When I interview people, I typically like such answers because it's much easier to make slow <em>correct</em> code fast than it is to make fast <em>incorrect</em> code correct. However, in a good interview, I like to ask the candidate to make comments on his or her own code, including any limitations, assumptions or potential improvements that might be made. In this case, it helps if we think mathematically about the final values in the resulting array <span class=\"math-container\">\\$B\\$</span> from input array <span class=\"math-container\">\\$A\\$</span>. For example, we know that every value <span class=\"math-container\">\\$B_j\\$</span> can be expressed as the product <span class=\"math-container\">$$\\displaystyle B_j = \\prod_{i=0}^{j-1} A_i \\prod_{i=j+1}^{n-1} A_i$$</span> if <span class=\"math-container\">\\$n\\$</span> is the length of the array. This suggests a more efficient approach I'll leave for you to figure out.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T22:53:07.427", "Id": "495626", "Score": "0", "body": "You ask what happens when `arr_size` is zero. Pretty much *nothing* happens, right? Which is the right thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T22:57:22.183", "Id": "495627", "Score": "1", "body": "@superbrain: My point in including that question (and others) it is to get the person *writing* the program to think about and answer the question. If they can answer, with confidence, what it does in those corner cases, then they've thought about it, which is the kind of thing one would want to demonstrate in a job interview." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:25:07.587", "Id": "495723", "Score": "0", "body": "Another issue with division is that now you're working in floating point math." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:27:35.380", "Id": "495724", "Score": "1", "body": "@Acccumulation The original code did not use floating point division." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T04:18:11.180", "Id": "496152", "Score": "0", "body": "@Edward please take look at my new code here: https://codereview.stackexchange.com/questions/251929/product-of-all-but-one-number-in-a-sequence-follow-up" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T17:40:01.907", "Id": "251671", "ParentId": "251647", "Score": "13" } }, { "body": "<p><strong>Overflow</strong></p>\n<p>Certainly the product of many <code>int</code> can overflow ---&gt; leading to <em>udenfined bahavior</em> (UB).</p>\n<p>If an additional specification included &quot;the product does not overflow&quot;, we still have a problem with <code>fun()</code>. That approach may overflow the <em>intermediate</em> product <code>sum</code>.</p>\n<p>A work around is to use <code>long long</code> or <code>intmax_t</code> for <code>sum</code>.</p>\n<p>Code could use a compile time check</p>\n<pre><code>#if LLONG_MAX/INT_MAX &lt; INT_MAX\n #error &quot;int lacks a 2x wide type.&quot;\n#endif\n</code></pre>\n<p><strong>Zero</strong></p>\n<p>A simple improvement would handle <code>num[i] == 0</code> and certainly not divide by zero. If that occurs more than once, the resultant array is all zeros. With only 1 <code>num[i] == 0</code>, all other elements are zero, and the one <code>i</code> ellement is the product of the rest.</p>\n<p><strong>C2x</strong></p>\n<p><a href=\"https://en.wikipedia.org/wiki/C2x#Features\" rel=\"nofollow noreferrer\">C2X</a> promotes the idiom of coding with the array size first.</p>\n<pre><code>// int fun(int* nums, int arr_size)\nint fun(int arr_size, int* nums)\n</code></pre>\n<p><strong><code>int</code> vs. <code>size_t</code></strong></p>\n<p>Array sizes may exceed <code>INT_MAX</code>. Consider <code>size_t</code> for the size. Keep in mind that <code>size_t</code> is an <em>unsigned</em> type.</p>\n<p><strong><code>int* nums</code> or <code>int *nums</code></strong></p>\n<p>C standard uses style <code>int *nums</code>. Follow your group's style standard.</p>\n<p><strong>Return value</strong></p>\n<p>Perhaps use the return value for something useful. Perhaps: detect overflow.</p>\n<p><strong>Keep <code>for()</code> clean</strong></p>\n<p>Avoid over-packing <code>for()</code>. As with such coding style issue, follow group's standards.</p>\n<pre><code>// for(i=0, sum=1; i&lt;arr_size; i++)\nsum = 1;\nfor(i=0; i&lt;arr_size; i++)\n// of better, declare when needed\nint sum = 1;\nfor(int i=0; i&lt;arr_size; i++)\n</code></pre>\n<p><strong>Example</strong></p>\n<p><em>Unchecked code - will review later</em></p>\n<pre><code>// Return NULL out-of-memory or overflow.\nint fun(size_t arr_size, const int *nums) {\n int *parray = calloc(arr_size, sizeof *parray);\n if (parray == NULL) {\n return parray;\n }\n\n int *zero = NULL;\n intmax_t product = 1;\n bool overflow = false;\n \n for (size_t i = 0; i &lt; arr_size; i++) {\n if (nums[i]) {\n overflow |= mult_check(nums[i], &amp;product);\n } else {\n if (zero) {\n return parray; // We are done, 2 zeros found\n }\n zero = &amp;nums[i];\n }\n }\n\n for (size_t i = 0; i &lt; arr_size; i++) {\n int divisor = nums[i] ? nums[i] : 1; \n intmax_t q = product/divisor;\n if (q &lt; INT_MIN || q &gt; INT_MAX) {\n overflow = true;\n break;\n } \n }\n\n if (overflow) {\n free(parray);\n return NULL;\n }\n\n return parray;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T22:34:33.257", "Id": "251680", "ParentId": "251647", "Score": "3" } }, { "body": "<p>Thank you all for your helpful responses. I am posting a better solution here with taking into consideration the suggestions of [Edward], [CiaPan], [chux], [superb rain] and others suggestions.</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\n//without division, with O(n) time, but extra space complexity as suggested\n//return new array on the heap \nint *find_product_arr(const int *nums, int arr_size)\n{\n int *new_arr = (int *)malloc(sizeof(int)*arr_size);\n\n int mult_prefix=1; //product of prefix elements\n int mult_suffix=1; //product of suffix elements\n \n //left most element special handling\n new_arr[0]=1;\n \n //swipe up \n for(int i=1; i&lt;arr_size; i++) {\n mult_prefix *= nums[i-1];\n new_arr[i] = mult_prefix;\n }\n \n //swipe down\n for(int j=arr_size-2; j&gt;=0; j--) {\n mult_suffix *= nums[j+1];\n new_arr[j] *= mult_suffix;\n }\n \n return new_arr;\n}\n\n\nint main(void)\n{\n /*Given an array of integers, return a new array such that each element at index i of the \n new array is the product of all the numbers in the original array except the one at i.\n For example, if our input was [1, 2, 3, 4, 5], the expected output would be \n [120, 60, 40, 30, 24] */\n int nums[] = {1, 2, 2, 4, 6}; \n int size = sizeof(nums)/sizeof(nums[0]);\n \n int *products = find_product_arr(nums, size); //get a new array\n \n for (int i = 0; i &lt; size; i++) \n printf(&quot;%d &quot;, *(products+i) ); \n \n free(products); //release heap memory\n \n return 0;\n}\n</code></pre>\n<p>It would be helpful if you give further improvements too.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T15:52:53.377", "Id": "496100", "Score": "2", "body": "You can create a follow up question by posting the new code in a new question and creating a link to this question. If you need an example of how [this](https://codereview.stackexchange.com/questions/248817/common-unit-testing-code-follow-up?noredirect=1&lq=1) is one of my follow up questions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T10:10:35.690", "Id": "251893", "ParentId": "251647", "Score": "0" } } ]
{ "AcceptedAnswerId": "251671", "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T11:09:01.180", "Id": "251647", "Score": "11", "Tags": [ "c", "array", "interview-questions" ], "Title": "Product of all but one number in a sequence" }
251647
<p>Hello today after few weeks of learning I tried some form validation. I am wondering how I could improve my code and what things I missed.<br><br> Here is a <strong><a href="https://isaayy.github.io/Form-validation/" rel="nofollow noreferrer">preview</a></strong> hosted on github + <strong><a href="https://github.com/Isaayy/Form-validation" rel="nofollow noreferrer">repository</a></strong>.<br> And here is my code :</p> <p><strong>HTML</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;main.css&quot;&gt; &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Rubik:wght@300;400;500;600;700&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt; &lt;title&gt;Form validation&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form action=&quot;#&quot; class=&quot;form&quot;&gt; &lt;h2&gt;Contact with us&lt;/h2&gt; &lt;div class=&quot;wrapper&quot;&gt; &lt;div&gt; &lt;input type=&quot;text&quot; name=&quot;name&quot; class='input-name' id='input' placeholder=&quot;First name *&quot; required&gt; &lt;p id='input-name-p' class='p-hidden'&gt;&lt;/p&gt; &lt;/div&gt; &lt;div&gt; &lt;input type=&quot;text&quot; name=&quot;surname&quot; class='input-surname' id='input' placeholder=&quot;Surname&quot;&gt; &lt;p id='input-surname-p' class='p-hidden'&gt;&lt;/p&gt; &lt;/div&gt; &lt;div&gt; &lt;input type=&quot;text&quot; name=&quot;email&quot; class='input-email' id='input' placeholder=&quot;E-mail *&quot; required&gt; &lt;p id='input-email-p' class='p-hidden'&gt;&lt;/p&gt; &lt;/div&gt; &lt;div&gt; &lt;input type=&quot;text&quot; name=&quot;phone&quot; class='input-phone' id='input' placeholder=&quot;Phone number&quot;&gt; &lt;p id='input-phone-p' class='p-hidden'&gt;&lt;/p&gt; &lt;/div&gt; &lt;textarea name=&quot;message&quot; rows=&quot;8&quot; cols=&quot;80&quot; class='input-message' id='input' placeholder=&quot;Message *&quot; required&gt;&lt;/textarea&gt; &lt;button href=&quot;#&quot; class=&quot;btn&quot;&gt;Submit&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;script type=&quot;text/javascript&quot; src=&quot;script.js&quot;&gt; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>JS</strong></p> <pre><code>'use strict'; const submit = document.querySelector('.btn'); const name = document.querySelector('.input-name'); const surname = document.querySelector('.input-surname'); const email = document.querySelector('.input-email'); const phone = document.querySelector('.input-phone'); const items = document.querySelectorAll('#input'); const isValid = function(item) { for (let i = 0; i &lt; item.length; i++) { if (item[i].value){ // Check if contains value let error = document.getElementById(`${item[i].className}-p`); const letters = /^[A-Za-z]+$/; const numbers = /^\d+$/; let inputLength = item[i].value.length; switch (item[i].className){ case 'input-name': case 'input-surname': if(!letters.test(item[i].value)){ // Invalid input error.textContent = 'Invalid data'; error.classList.remove('p-hidden'); }else error.classList.add('p-hidden'); break; case 'input-email': if(!item[i].value.includes('.') || !item[i].value.includes('@') || !letters.test(item[i].value[inputLength-1]) ){ // check if includes (@ or .) and check if the last index is a letter error.textContent = 'Invalid data'; error.classList.remove('p-hidden'); }else error.classList.add('p-hidden'); break; case 'input-phone': if(!numbers.test(item[i].value) || inputLength&lt;5){ // Invalid input error.textContent = 'Invalid data'; error.classList.remove('p-hidden'); }else error.classList.add('p-hidden'); break; } } } } for (let i = 0; i &lt; items.length; i++) { items[i].addEventListener('click',function(){ // Check if the input is valid isValid(items); }); } </code></pre>
[]
[ { "body": "<p><strong>Duplicate IDs are invalid HTML</strong> You have multiple elements of <code>id='input'</code>, which is not permitted in HTML. If multiple elements need a particular attribute, use classes instead. IDs should be reserved for elements that are going to be <em>absolutely unique</em> on a page (or, you could also consider not using IDs at all, since they implicitly create global variables, which can lead to hard-to-understand bugs).</p>\n<p><strong>Input iteration</strong> You put the input collection into a variable named <code>items</code>, which is good: <code>const items = document.querySelectorAll('#input');</code> but then you pass the collection to a function whose parameter is named <code>item</code>, and you do:</p>\n<pre><code>for (let i = 0; i &lt; item.length; i++) {\n if (item[i].value) { // Check if contains value\n // a long block\n }\n</code></pre>\n<ul>\n<li><p>A reader of the code wouldn't expect an individual <code>item</code> to have a <code>length</code> and a numeric index. How about calling the parameter <code>items</code> instead - or, even better, <code>inputs</code>?</p>\n</li>\n<li><p>Rather than iterate over the indicies of each element, since you don't actually care about the indicies, but only about the underlying elements, it might be preferable to use <code>for..of</code> instead, so you never have to reference the indicies.</p>\n</li>\n<li><p>Nested indentation can be difficult to read. Instead of a long block inside an <code>if</code> statement, consider continuing the loop early instead:</p>\n</li>\n</ul>\n<pre><code>for (const input of inputs) {\n if (!input.value) {\n continue;\n }\n // put validation code here\n</code></pre>\n<p>Or put it into a function:</p>\n<pre><code>for (const input of inputs) {\n if (input.value) {\n validateInput(input);\n }\n</code></pre>\n<p><strong>Check validity on blur</strong>, not on click. Your current implementation will show errors only after the user has inputted something invalid, focused away, then clicked on the input box <em>again</em>. Better to inform them immediately, as soon as a box is de-focused.</p>\n<p><strong>Check validity even if input is empty</strong>, since errors may be displayed - if the input is empty, you'll want to clear the error. You could also consider clearing errors when an input is focused (so that errors are only displayed when an input currently isn't active).</p>\n<p><strong>Error text</strong> is always the same, so don't set it via the JS - put it into the HTML, and hide the error on pageload.</p>\n<p><strong>Use the case-insensitive flag</strong> in regular expressions instead of repeating both the capital and lowercase versions, eg: <code>/^[a-z]$/i</code></p>\n<p><strong>Wording</strong> <code>Contact with us</code> would be better as <code>Contact us</code></p>\n<p><strong>DRY input navigation</strong> There are a few sources of repetitiveness in the code:</p>\n<ul>\n<li>Separate class names for each input, requiring iteration through each class name in the <code>switch</code></li>\n<li>Separate error class names for each input</li>\n<li>Separate logic for each class name</li>\n</ul>\n<p>You can make this better by:</p>\n<ul>\n<li>Use an object indexed by the <code>name</code> attribute of each input, whose values are regular expressions to test the values against</li>\n<li>Navigate to the input's adjacent error element with <code>nextElementSibling</code> instead of having separate error classes</li>\n</ul>\n<p>For the email, you can use a <a href=\"https://stackoverflow.com/q/201323\">regular expression</a> so that the validation is of the same shape as for the other inputs.</p>\n<pre class=\"lang-js prettyprint-override\"><code>const validators = {\n name: /^[a-z]$/i,\n surname: /^[a-z]$/i,\n email: /^(?:[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+)*|&quot;(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*&quot;)@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/,\n phone: /^\\d{5,}$/,\n};\nfor (const input of document.querySelectorAll('#input')) {\n input.addEventListener('blur', () =&gt; {\n checkValidity(input);\n });\n}\nconst checkValidity = (input) =&gt; {\n const isBad = validators[input.name].test(input.value);\n input.nextElementSibling.classList.toggle('p-hidden', isBad);\n};\n</code></pre>\n<p>That's all you need.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>'use strict';\n\nconst validators = {\n name: /^[a-z]+$/i,\n surname: /^[a-z]+$/i,\n email: /^(?:[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/,\n phone: /^\\d{5,}$/,\n};\nfor (const input of document.querySelectorAll('.wrapper input')) {\n input.addEventListener('blur', () =&gt; {\n checkValidity(input);\n });\n}\nconst checkValidity = (input) =&gt; {\n const isBad = validators[input.name].test(input.value);\n input.nextElementSibling.classList.toggle('p-hidden', isBad);\n};</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.p-hidden {\n display: none;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;form action=\"#\" class=\"form\"&gt;\n &lt;h2&gt;Contact us&lt;/h2&gt;\n &lt;div class=\"wrapper\"&gt;\n &lt;div&gt;\n &lt;input name=\"name\" placeholder=\"First name *\" required&gt;\n &lt;p class='p-hidden'&gt;Invalid data&lt;/p&gt;\n &lt;/div&gt;\n\n &lt;div&gt;\n &lt;input name=\"surname\" placeholder=\"Surname\"&gt;\n &lt;p class='p-hidden'&gt;Invalid data&lt;/p&gt;\n &lt;/div&gt;\n\n &lt;div&gt;\n &lt;input name=\"email\" placeholder=\"E-mail *\" required&gt;\n &lt;p class='p-hidden'&gt;Invalid data&lt;/p&gt;\n &lt;/div&gt;\n\n &lt;div&gt;\n &lt;input name=\"phone\" placeholder=\"Phone number\"&gt;\n &lt;p class='p-hidden'&gt;Invalid data&lt;/p&gt;\n &lt;/div&gt;\n\n &lt;textarea name=\"message\" rows=\"8\" cols=\"80\" placeholder=\"Message *\" required&gt;&lt;/textarea&gt;\n &lt;button href=\"#\" class=\"btn\"&gt;Submit&lt;/button&gt;\n &lt;/div&gt;\n&lt;/form&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The email regex is probably more complicated than it needs to be, you could write a much more easy-to-read one with only a handful of characters that works just as well in 99% of situations, if you wanted.</p>\n<p>Another option would be to remove <strong>all</strong> the JavaScript, and use the <code>pattern</code> attribute and <code>type=&quot;email&quot;</code> in the HTML instead, letting the browser inform the user of invalid inputs:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;form action=\"#\" class=\"form\"&gt;\n &lt;h2&gt;Contact us&lt;/h2&gt;\n &lt;div class=\"wrapper\"&gt;\n &lt;div&gt;\n &lt;input name=\"name\" placeholder=\"First name *\" required pattern=\"[a-zA-z]+\"&gt;\n &lt;/div&gt;\n &lt;div&gt;\n &lt;input name=\"surname\" placeholder=\"Surname\" pattern=\"[a-zA-z]+\"&gt;\n &lt;/div&gt;\n &lt;div&gt;\n &lt;input name=\"email\" placeholder=\"E-mail *\" required type=\"email\"&gt;\n &lt;/div&gt;\n &lt;div&gt;\n &lt;input name=\"phone\" placeholder=\"Phone number\" pattern=\"\\d+{5,}\"&gt;\n &lt;/div&gt;\n\n &lt;textarea name=\"message\" rows=\"8\" cols=\"80\" placeholder=\"Message *\" required&gt;&lt;/textarea&gt;\n &lt;button href=\"#\" class=\"btn\"&gt;Submit&lt;/button&gt;\n &lt;/div&gt;\n&lt;/form&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Result:</p>\n<p><a href=\"https://i.stack.imgur.com/M5fPJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/M5fPJ.png\" alt=\"enter image description here\" /></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T11:34:28.963", "Id": "495914", "Score": "0", "body": "such useful feedback thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T11:44:26.370", "Id": "495915", "Score": "0", "body": "also thanks for your time I really appreciate it" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T18:53:05.650", "Id": "251672", "ParentId": "251650", "Score": "1" } } ]
{ "AcceptedAnswerId": "251672", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T12:32:54.237", "Id": "251650", "Score": "1", "Tags": [ "javascript", "html" ], "Title": "My Javascript form validation" }
251650
<p>I'm a newbie and originally I wanted to write some code to automate getting to the results page of a site that lists apartments for workers.</p> <p>Then I got some inspiration and wanted to automate getting the data from each entry as well.</p> <p>It works and it saves me a lot of time, but it does seem like I went to too much trouble for what it does?</p> <p>I was already advised that I should use more functions/define more functions, but I guess that'd just make seven functions? How would that be helpful in comparison to the 7 blocks of code I have?</p> <p>I am also convinced hat this is the hackiest thing I could have done and it does not seem like a good solution at all.</p> <pre><code>import openpyxl from openpyxl import Workbook from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.select import Select import requests from bs4 import BeautifulSoup import pandas as pd #prepare the excel workbook wb = openpyxl.Workbook() sheet = wb.active driver = webdriver.Firefox() #give the driver the site to load and ask the user for the german postal code and number of results webpage = r&quot;https://mein-monteurzimmer.de&quot; print('Prosim vnesi zeljeno mesto') searchterm = input() print('Prosim vnesi stevilo rezultatov.') number_of_results = int(input()) driver.get(webpage) #go through the steps required to get to the results page GDPR = driver.find_element_by_css_selector(&quot;span.primary&quot;) GDPR.click() sbox = driver.find_element_by_xpath(&quot;//input[@placeholder='Adresse, PLZ oder Ort eingeben']&quot;) sbox.send_keys(searchterm) driver.implicitly_wait(2) addressXpath = &quot;//div[contains(text(),'&quot;+searchterm+&quot;')]&quot; driver.find_element_by_xpath(addressXpath).click() submit = driver.find_element_by_xpath(&quot;/html/body/main/cpagearea/section/div[2]/div/section[1]/div/div[1]/section/form/button&quot;) submit.click() First_result = driver.find_element_by_xpath(&quot;/html/body/main/cresultcontainer/div/div[2]/div[2]/section[1]/div&quot;) First_result.click() #iterate through the results as many times as the user demanded i = 0 while (i &lt; number_of_results): Result_page = driver.current_url stran = requests.get(driver.current_url) soup = BeautifulSoup(stran.content, 'html.parser') #find and extract the relevant info for each listing ime = soup.find(&quot;dd&quot;, itemprop=&quot;name&quot;) if ime: print(ime.text) c1 = sheet.cell(row=i+1, column=1) c1.value = ime.text ulica = soup.find(&quot;dd&quot;, itemprop=&quot;streetAddress&quot;) if ulica: print(ulica.text) c1 = sheet.cell(row=i+1, column=2) c1.value = ulica.text postna_stevilka = soup.find(&quot;span&quot;, itemprop=&quot;postalCode&quot;) if postna_stevilka: print(postna_stevilka.text) c1 = sheet.cell(row=i+1, column=3) c1.value = postna_stevilka.text kraj = soup.find(&quot;span&quot;, itemprop=&quot;addressLocality&quot;) if kraj: print(kraj.text) c1 = sheet.cell(row=i+1, column=4) c1.value = kraj.text tel = soup.find(&quot;dd&quot;, itemprop=&quot;telephone&quot;) if tel: print(tel.text) c1 = sheet.cell(row=i+1, column=5) c1.value = tel.text spletna_stran = soup.find(&quot;dd&quot;, itemprop=&quot;url&quot;) if spletna_stran: print(spletna_stran.text) c1 = sheet.cell(row=i+1, column=6) c1.value = spletna_stran.text #this specific one doesn't work as they used the same class and name for #both mobile and landline. Need to figure this out. #However, if there is no landline, at least the mobile number is extracted. mobil = soup.find(&quot;dd&quot;, itemprop=&quot;telephone&quot;).parent.find_next_siblings() if mobil: print(mobil.text) c1 = sheet.cell(row=i+1, column=7) c1.value = mobil.text #click through to the next result next_entry = driver.find_element_by_xpath(&quot;/html/body/main/chousingdetail/div/div[2]/div[1]/nav/div/div[2]/a[2]/i&quot;) next_entry.click() i +=1 #once all the results have been worked through, save the workbook to this directory: wb.save(&quot;[Directory to save to]&quot;) </code></pre>
[]
[ { "body": "<h2>Localisation</h2>\n<p>This:</p>\n<pre><code>#give the driver the site to load and ask the user for the german postal code and number of results\n</code></pre>\n<p>and this:</p>\n<pre><code>print('Prosim vnesi stevilo rezultatov.')\n</code></pre>\n<p>are both great. The former uses English for code, which is generally advised; and the latter uses a localised language (Slovenian?) for user-facing content.</p>\n<p>These should be avoided:</p>\n<pre><code>ulica = soup.find\npostna_stevilka = soup.find\n</code></pre>\n<p>and use English instead (street, postcode). For better or worse, English is the de-facto language of international programming, and using it for your variable names will make your code more legible for collaborators and colleagues.</p>\n<h2>General approach</h2>\n<p>Always when thinking about scraping a website, look at the network or traffic tab of your browser's developer tools. In this case it shows:</p>\n<pre><code>https://mein-monteurzimmer.de/api/v2/search\n</code></pre>\n<p>That's an API that you can call into with Requests, which will be more simpler and more efficient than Selenium.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T07:08:15.000", "Id": "495646", "Score": "1", "body": "Thank you very much. I will keep in mind to look for API first next time. \n\nAnd the point about using English for variables makes a lot of sense going forward!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T07:25:35.507", "Id": "495648", "Score": "1", "body": "Oh, and good job on recognizing the language. :D" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T15:16:02.223", "Id": "251658", "ParentId": "251651", "Score": "1" } } ]
{ "AcceptedAnswerId": "251658", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T13:37:38.217", "Id": "251651", "Score": "2", "Tags": [ "python", "web-scraping", "automation" ], "Title": "Search for listings on a german website in a given postal code, return an excel spreadsheet with details from X listings" }
251651
<p><strong>Problem description:</strong></p> <blockquote> <p>Given a 32-bit signed integer, reverse digits of an integer.</p> <p><strong>Note</strong>: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: <span class="math-container">\$[−2^{31}, 2^{31} − 1]\$</span>. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.</p> </blockquote> <p><strong>My solution:</strong></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>var reverse = function(x) { temp = (x &lt; 0) ? -1 : 1; x = x * temp; let res = x % 10; while(x &gt; 9) { x = (x - x % 10) / 10; res = 10 * res + x % 10; }; res = ((res &lt; 2147483648) &amp;&amp; (res &gt;= -2147483648)) ? res : 0; return res * temp; }; console.log(reverse(-321)); console.log(reverse(1534236469));</code></pre> </div> </div> </p> <p><strong>Test:</strong></p> <pre><code>Input #1: -321 Expected #1: -123 Input #2: 1534236469 Expected #2: 0 </code></pre> <p><strong>Test summmary:</strong></p> <pre><code>Solution accepted Runtime: 88ms </code></pre> <p><strong>Question:</strong> Is there a way to make this function less complex, maybe also improving its runtime?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T13:19:04.310", "Id": "495684", "Score": "0", "body": "If you execute that code in an environment that could only store integers within the 32-bit signed integer range, then the code will fail detecting values outside the valid range.\nSo I am not sure your code solves the problem." } ]
[ { "body": "<p>A simple and clear approach would be to take an array of characters of the number, and reverse the array:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const reverse = function(inputNum) {\n const result = Math.sign(inputNum) * String(Math.abs(inputNum))\n .split('')\n .reverse()\n .join('');\n return result &lt; -2147483648 || result &gt; 2147483647 ? 0 : result;\n};\nconsole.log(reverse(-321));\nconsole.log(reverse(1534236469));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The runtime is a little bit higher (92ms, not sure how precisely reliable the measurements are on LeetCode, they seemed all over the place), but in the vast majority of real-world situations, to write strong and maintainable code, one should first optimize clarity and readability, and <em>then</em> if the whole app isn't running as fast as would be ideal, run a performance test to identify bottlenecks and work on <em>those particular bottlenecks</em>.</p>\n<p>Note the use of <code>Math.sign</code> to determine whether the number is positive or negative - it'll return -1 if the number is negative, and 1 if the number is positive, so it's probably a bit more appropriate for the situation.</p>\n<p>Another approach without creating an intermediate array would be</p>\n<pre><code>let res = '';\nfor (let i = inputStr.length - 1; i &gt;= 0; i--) res += inputStr[i];\n</code></pre>\n<p>With regards to your code:</p>\n<p><strong>Always declare your variables</strong> You're implicitly creating a global variable <code>temp</code>. Implicit creation of global variables will cause odd bugs when a function gets called when it's already in the process of running. Consider using a linter or strict mode or both to avoid these sorts of mistakes. (When declaring variables, prefer <code>const</code>, or use <code>let</code> when it needs to be reassigned.) On a similar note, your <code>reverse</code> function should be declared with <code>const</code> (not <code>var</code>).</p>\n<p><strong>Give variables meaningful names</strong> An argument named <code>x</code> and a variable named <code>temp</code> aren't very informative at a glance. How about calling them <code>inputNum</code> and <code>sign</code> instead?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T11:12:13.227", "Id": "495677", "Score": "0", "body": "By reversing the sense of the validity tests (from the way they were given in the question, which is correct) the `reverse` function in this answer gets them wrong. It should be `return (result < -2147483648 || result > 2147483647) ? 0 : result;`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T22:50:29.363", "Id": "495961", "Score": "0", "body": "Quick question (I'm not a JS dev): What is `Math.sign(inputNum) * String(Math.abs(inputNum))` for? Wouldn't the number itself already contain all the information?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T22:58:49.840", "Id": "495962", "Score": "0", "body": "@PNDA The `Math.sign(inputNum)` is being multiplied by `String(Math.abs(inputNum))\n .split('')\n .reverse()\n .join('')` - it's a much longer expression on the right, and for that logic to be implemented, the sign needs to be stripped out, which can be done with `Math.abs`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T08:48:50.670", "Id": "495977", "Score": "0", "body": "@CertainPerformance Oh, I see what I missed. Thanks!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T15:31:49.460", "Id": "251659", "ParentId": "251652", "Score": "6" } }, { "body": "<h3>Disclaimer: Not a Code Reviewer</h3>\n<p>Just a few brief comments:</p>\n<ul>\n<li><p>Looks pretty good!</p>\n</li>\n<li><p>You have the right approach.</p>\n</li>\n<li><p>We can just make it (very slightly) more readable if you will, or maybe add a new function to get the sign for instance.</p>\n</li>\n<li><p>We are allowed to alter LeetCode's variable names.</p>\n</li>\n<li><p>LeetCode's runtime/memory measurements are inaccurate (fluctuating; no isolation – differs from cloud region to region); we can safely ignore those data.</p>\n</li>\n<li><p>We are not supposed to use the built-in <code>.reverse()</code> of JavaScript for the reverse integer problem, not to mention that would be inefficient in JavaScript.</p>\n</li>\n<li><p>Here is a rough imprecise non-isolated benchmark, still efficiency is pretty visible:</p>\n</li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const reverseUsingMath = function(num) {\n sign = getSign(num);\n num *= sign;\n let res = num % 10;\n while (num &gt; 9) {\n num -= num % 10;\n num /= 10;\n res *= 10;\n res += num % 10;\n };\n\n res = (res &lt; 2147483648) &amp;&amp; (res &gt;= -2147483648) ? res : 0;\n return res * sign;\n};\n\nconst getSign = function(num) {\n return num &lt; 0 ? -1 : 1;\n}\n\nlet counter = 10000000;\nlet start = Date.now();\n\nfor (let i = counter; i &gt;= 0; i--) {\n reverseUsingMath(-2147483641);\n}\n\nlet end = Date.now() - start;\n\nconsole.log(end / 1000 + \" is the runtime of reverseUsingMath \" + counter + \" times benchmark test. \");\n\n\n\nconst reverseWithBuiltInReverse = function(inputNum) {\n const result = Math.sign(inputNum) * String(Math.abs(inputNum))\n .split('')\n .reverse()\n .join('');\n return result &lt;= -2147483648 || result &gt; 2147483648 ? 0 : result;\n};\n\n\nstart = Date.now();\n\nfor (let i = counter; i &gt;= 0; i--) {\n reverseWithBuiltInReverse(-2147483641);\n}\n\nend = Date.now() - start;\n\nconsole.log(end / 1000 + \" is the runtime of reverseWithBuiltInReverse \" + counter + \" times benchmark test. \");\n\n// Not an efficient solution because of the parseInt() function;\n// Yet easy to understand;\nconst reverseWithParseInt = function(num) {\n let reversed = 0;\n\n while (num) {\n reversed = parseInt(reversed * 10);\n reversed = parseInt(reversed + num % 10);\n num = parseInt(num / 10);\n };\n\n\n return (reversed &gt; 2147483647) || (reversed &lt; -2147483648) ? 0 : reversed;\n};\n\n\nstart = Date.now();\n\nfor (let i = counter; i &gt;= 0; i--) {\n reverseWithParseInt(-2147483641);\n}\n\nend = Date.now() - start;\n\nconsole.log(end / 1000 + \" is the runtime of reverseWithParseInt \" + counter + \" times benchmark test. \");\n\n\n\nfunction reverseUsingMathAndUseStrict(num) {\n \"use strict\";\n const max = 0x80000000;\n const sign = (num &amp; max) ? -1 : 1;\n num *= sign;\n var res = num % 10;\n if (num &lt; 1e9 || res &lt; 3) {\n while (num &gt; 9) {\n num = num / 10 | 0;\n res = res * 10 + (num % 10);\n }\n return res &lt; max ? res * sign : 0;\n }\n return 0;\n}\n\n\nstart = Date.now();\n\nfor (let i = counter; i &gt;= 0; i--) {\n reverseUsingMathAndUseStrict(-2147483641);\n}\n\nend = Date.now() - start;\n\nconsole.log(end / 1000 + \" is the runtime of reverseUsingMathAndUseStrict \" + counter + \" times benchmark test. \");</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<ul>\n<li>Here is a C solution:</li>\n</ul>\n<pre><code>// Since the relevant headers are already included on the LeetCode platform,\n// the headers can be removed;\n#include &lt;stdio.h&gt;\n#include &lt;limits.h&gt;\n\nint reverse(int num) {\n\n long long reversed = 0;\n\n while (num) {\n reversed *= 10;\n reversed += num % 10;\n num /= 10;\n }\n\n return reversed &lt; INT_MIN || reversed &gt; INT_MAX ? 0 : reversed;\n}\n\n\nint main() {\n puts(reverse(123456789) == 987654321 ? &quot;true&quot; : &quot;false&quot;);\n puts(reverse(-123456789) == -987654321 ? &quot;true&quot; : &quot;false&quot;);\n}\n</code></pre>\n<p>PS: Now a code reviewer has to review my code ( ˆ_ˆ )</p>\n<h2>Happy Coding! ( ˆ_ˆ )</h2>\n<hr />\n<h3>Reference</h3>\n<ul>\n<li><p><a href=\"https://codereview.stackexchange.com/a/251659/190910\">reverseWithBuiltInReverse() is from here by @CertainPerformance</a></p>\n</li>\n<li><p><a href=\"https://codereview.stackexchange.com/a/251763/190910\">reverseUsingMathAndUseStrict() is from here by @Blindman67</a></p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T23:07:51.737", "Id": "495629", "Score": "2", "body": "Use [jsbench](https://jsben.ch). It's usually more accurate at timing code execution." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T16:14:02.997", "Id": "251663", "ParentId": "251652", "Score": "5" } }, { "body": "<h1>Performance</h1>\n<h2>Numbers</h2>\n<p>You can get a little more out of JS numbers if you force them to be 32 Bit Signed Integers. (Note this will depend on the JS engine. Works for V8 (chrome))</p>\n<p>This is done by performing a bit wise operation on the number\nEg the double 2147483648 is converted to the uint32 -2147483648 by applying bit wise or zero <code>(2147483648 | 0) === -2147483648</code> is true.</p>\n<p>Integers are generally about 4-5% quicker than using Doubles.</p>\n<p>As applying a bit-wise operator to a positive double &lt; 2 ** 31 is the equivalent to Math.floor you can also gain some improvement by simplifying <code>x = (x - x % 10) / 10;</code> to <code>x = x / 10 | 0</code>. Saving a subtraction and a remainder per iteration.</p>\n<h2>Early exit</h2>\n<p>Approx 42% of reversed numbers will be out of range.</p>\n<p>Thus there is also an opportunity for performance gain with an exit early.</p>\n<p>We can check if the lowest digit is greater than 2 and number is greater than 1e9 and just return 0 if so thus not having to process a significant number of the 42% out of range values.</p>\n<h2>Use declared variables</h2>\n<p>You use the value <code>temp</code> that you have not declared. That means it will be in global scope. Every step out of the current scope a variable is the slower the access to the variable.</p>\n<p>If you declare <code>temp</code> in the functions scope and use strict mode you will gain a significant performance boost.</p>\n<h2>Needless test</h2>\n<p>You can remove the test for &lt; -2147483648 as the result will be positive until you revert the sign. Thus you can change the sign at the very last moment saving the need to check past the min int.</p>\n<h2>Rewrite is 3.5 times faster</h2>\n<p>The rewrite is 3.5 times quicker (for a random set of 32bit signed integers)</p>\n<p>Though the source is a little longer it is well worth the performance gain</p>\n<pre><code>function reverse(num) {\n &quot;use strict&quot;;\n const max = 0x80000000;\n const sign = (num &amp; max) ? -1 : 1; \n num *= sign;\n var res = num % 10;\n if (num &lt; 1e9 || res &lt; 3) {\n while (num &gt; 9) {\n num = num / 10 | 0;\n res = res * 10 + (num % 10);\n }\n return res &lt; max ? res * sign : 0;\n }\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T16:47:10.320", "Id": "495819", "Score": "1", "body": "@Emma Must be first line of function or first line of file / script tag As the OPs code is likely running in an embedded file or script tag its safest to put inside function.. Most add it as first line of file / script tag to save the need to add to each function. Not needed for modules as they are always in strict mode." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T16:21:48.743", "Id": "251763", "ParentId": "251652", "Score": "2" } } ]
{ "AcceptedAnswerId": "251659", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T14:04:50.173", "Id": "251652", "Score": "5", "Tags": [ "javascript" ], "Title": "'Reverse a number' function" }
251652
<p>I started university this semester. Can you review my code and share your thoughts with me</p> <pre><code># 5-November-2020 username = input(&quot;Please enter your username: &quot;) password = input(&quot;Please enter your password: &quot;) username_password = { 'Mert': &quot;mertt&quot; } if username in username_password: if username == &quot;Mert&quot; and password == username_password[username]: print(&quot;Welcome Sir&quot;) else: print(&quot;You're not authorized!&quot;) else: confirmation = input(&quot;Do you want to register? (Y/N): &quot;) if confirmation == &quot;Y&quot;: username = input(&quot;Enter your username: &quot;) password = input(&quot;Enter your password: &quot;) password_2 = input(&quot;Confirm your password: &quot;) if password == password_2: username_password[username] = password else: print(&quot;Your password is incorrect!&quot;) else: print(&quot;Good bye&quot;) print(username_password) </code></pre> <p>If you have any improvement suggestion please tell me.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T14:23:52.510", "Id": "495551", "Score": "4", "body": "Welcome to code review! Please [edit] your title so that it only states what your code does. Also, an explanation of your code in the question body can also help reviewers! I suggest you read [ask]" } ]
[ { "body": "<h1>Validate input</h1>\n<p>You should be certain that your program wouldn't fail for any kind of <strong>bad</strong> input, something the user <strong>shouldn't</strong> have entered that might cause the program to behave incorrectly</p>\n<p>Is this possible for your program? Yes, take this line</p>\n<pre class=\"lang-py prettyprint-override\"><code>username = input(&quot;Please enter your username: &quot;)\n</code></pre>\n<p>If the user enters <kbd>Ctrl+Z</kbd> here, it causes an error and the program stops.</p>\n<blockquote>\n<p>EOFError</p>\n</blockquote>\n<p>We can catch these exceptions using <a href=\"https://www.w3schools.com/python/python_try_except.asp#:%7E:text=The%20try%20block%20lets%20you,the%20try%2D%20and%20except%20blocks.\" rel=\"nofollow noreferrer\">try and except in Python</a></p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n username = input(&quot;Please enter your username: &quot;)\nexcept (Exception, KeyboardInterrupt): \n print(&quot;Please enter a valid username!&quot;)\n</code></pre>\n<p>The same applies to the input for <code>password</code></p>\n<p>One step further, I would also like to check the length of the details, i.e if the username or password is too short. Show a custom message if that is true</p>\n<hr />\n<h1>On an exception</h1>\n<p>Due to the changes we made previously, we can easily print an error message if we catch an exception rather than the termination of the program.<br> <strong>But what happens after?</strong></p>\n<p>You have two options, either to stop the program there because you cannot process bad input <strong>or</strong>, you can ask for input again. <br>\nIf you choose the second option, that will take a few more lines of code but is surely better because the user gets another chance rather than running the whole program again\nFor that, we need to wrap it in a <code>while</code> loop that will iterate till it gets valid input</p>\n<pre class=\"lang-py prettyprint-override\"><code>def username_input():\n while True:\n try:\n username = input(&quot;Please enter your username: &quot;)\n except Exception:\n print(&quot;Please a enter valid username! \\n\\n&quot;)\n continue \n return username\n\ndef password_input():\n while True:\n try:\n password = input(&quot;Please enter your password: &quot;)\n except Exception:\n print(&quot;Please enter a valid password! \\n\\n&quot;)\n continue\n return password\n</code></pre>\n<p>Here we are repeating ourselves, the functions are identical. With a little hack, we can clean up the code</p>\n<pre class=\"lang-py prettyprint-override\"><code>def ask_input(field):\n while True:\n try:\n word = input(f&quot;Please enter your {field}: &quot;)\n except (Exception, KeyboardInterrupt):\n print(f&quot;Please enter a valid {field}! \\n\\n&quot;)\n continue\n if not word: continue # if field is empty\n return word\n\ndef take_input():\n username = ask_input(&quot;username&quot;)\n password = ask_input(&quot;password&quot;)\n return username, password\n</code></pre>\n<hr />\n<h1>Split work into functions</h1>\n<p>In my last point, you must've noticed I moved something into a function</p>\n<p>We can really clean up our code if we follow the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">SRP</a> rule or the Single-responsibility principle</p>\n<blockquote>\n<p>The single-responsibility principle (SRP) is a computer-programming\nprinciple that states that every module, class, or function in a\ncomputer program should have responsibility over a single part of that\nprogram's functionality,</p>\n</blockquote>\n<p>If assig the task of taking input in this program, to let's say <code>take_input()</code>\nWe can re-use the same function if we would ever want to perform the same task again, without copy-pasting the same segment of code</p>\n<pre class=\"lang-py prettyprint-override\"><code>username, password = take_input()\nprocess_login( username, password ):\n</code></pre>\n<ul>\n<li><code>take_input()</code> will take care of the input related tasks, and when it has proper valid it returns a <code>username</code> and <code>password</code></li>\n<li><code>process_login()</code> decides whether the login will be authorized or not, based on the records</li>\n</ul>\n<hr />\n<h1>Check with key <code>username</code></h1>\n<pre class=\"lang-py prettyprint-override\"><code>if username in username_password:\n if username == &quot;Mert&quot; and password == username_password[username]:\n print(&quot;Welcome Sir&quot;)\n else:\n print(&quot;You're not authorized!&quot;)\n</code></pre>\n<p>This works right now, but only due to the fact that the size of records is <code>1</code>, any extra records added and your algorithm will fail, if the size was <code>50</code> you cannot write <code>50</code> if statements, you need to check with the username entered</p>\n<pre class=\"lang-py prettyprint-override\"><code>def process_login(username, password, records):\n try:\n if records[username] == password:\n print(&quot;Authorized&quot;)\n return True\n except KeyError:\n print(&quot;Not authroized&quot;)\n return False\n</code></pre>\n<p>Here, if the <code>username</code> isn't present in <code>records</code>, a <code>KeyError</code> is raised, which I will catch and print <code>Not authorized</code></p>\n<hr />\n<h1>Re-written</h1>\n<pre><code>def ask_input(field):\n while True:\n try:\n word = input(f&quot;Please enter your {field}: &quot;)\n except (Exception, KeyboardInterrupt):\n print(f&quot;Please enter a valid {field}! \\n\\n&quot;)\n continue\n if not word: continue\n\n return word\n\ndef take_input():\n username = ask_input(&quot;username&quot;)\n password = ask_input(&quot;password&quot;)\n return username,password\n\n\ndef process_login(username, password, records):\n try:\n if records[username] == password:\n print(&quot;Authorized&quot;)\n\n except KeyError:\n print(&quot;Not authroized&quot;)\n \n</code></pre>\n<p>I have left out the last part, which is the &quot;registration&quot;. Which I will explain next</p>\n<pre class=\"lang-py prettyprint-override\"><code>records = {\n &quot;__Testu&quot; : &quot;__Testp&quot;,\n &quot;__Testu2&quot; : &quot;__Testp2&quot;\n}\n\nusername, password = take_input()\nprocess_login(username, password, records)\n</code></pre>\n<h1>Write records into a file</h1>\n<p>As it is currently, you have pre-added a record to your dictionary, any record added after this is pointless since the next time you run the program, the dictionary will be initialized again with the same one record you added. <br>\nYou need some way to save the users records so that the next time he opens your program, his previous details are saved</p>\n<p>The best way to do this is the user the <a href=\"http://csv\" rel=\"nofollow noreferrer\">csv</a> module in Python, - <code>csv.DictReader</code> which will automate all reading/writing of the file for you. But is something you would have to write on your own.</p>\n<p>Cheers</p>\n<pre><code>&gt;&gt;&gt; Please enter your username: (empty input)\n&gt;&gt;&gt; Please enter your username: __Testu\n&gt;&gt;&gt; Please enter your password: (empty input)\n&gt;&gt;&gt; Please enter your password: __Testp\n\n&gt;&gt;&gt; Authorized\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T15:50:03.483", "Id": "495562", "Score": "0", "body": "I advise against the `except Exception:` approach written in your validation section. Ctrl+Z is a control character that exists for a reason. It's not meaningful to catch that and ask for another input." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T15:50:20.063", "Id": "495563", "Score": "0", "body": "In other words: yes, check for length and complexity, but do _not_ intercept control characters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T15:51:53.963", "Id": "495564", "Score": "0", "body": "@Reinderien Is it fine not to catch any exception here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T15:55:34.823", "Id": "495566", "Score": "0", "body": "@Reinderien The flag is only raised if the user deliberately presses `Cntrl + Z`, but the bare input of `^Z` doesn't raise the exception" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T15:58:08.603", "Id": "495570", "Score": "0", "body": "Ctrl+Z and ^Z are the same thing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T15:59:44.410", "Id": "495571", "Score": "0", "body": "@Reinderien I assume that's what you mean right? When you enter `Cntrl + Z`, a `^Z` is shown. I believe this is what you *don't* want to catch as an exception, correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T16:08:04.617", "Id": "495574", "Score": "0", "body": "@Reinderien I'm not sure what you mean, what is supposed to be done at `Cntrl + Z`? Without catching any exception the program fails, with EOFError" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T16:10:03.493", "Id": "495575", "Score": "0", "body": "@Reinderien I always compare with exisiting command line apps in windows, on a control command the system just asks for an input again" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T16:23:26.740", "Id": "495577", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/115874/discussion-between-reinderien-and-aryan-parekh)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T10:18:36.650", "Id": "495676", "Score": "0", "body": "I got it thanks, however, as Reinderien said it's better not to catch Ctrl+Z." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T15:44:19.430", "Id": "251661", "ParentId": "251653", "Score": "3" } } ]
{ "AcceptedAnswerId": "251661", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T14:17:08.783", "Id": "251653", "Score": "5", "Tags": [ "python", "beginner" ], "Title": "Username-Password Matching Program" }
251653
<p>I am trying to use bluepy to write and read serial data to/from an HC-08 Bluetooth module. The HC-08 is connected to a device that returns a fixed number of bytes whenever it receives a message over the HC-08.</p> <p>Below is my code so far. This seems to work—however, I kind of winged this code from examples and an a lot of trial and error. I am not entirely sure what I am doing. Therefore, any comments/feedback for potential improvements would be very welcome. The code is implemented as a <code>class myhc08</code> that has a <code>write</code> method. This method writes a string to the hc08 and then reads out a set number of bytes.</p> <pre><code>import struct import bluepy.btle as btle from matplotlib import pyplot class ReadDelegate(btle.DefaultDelegate): def __init__(self): self.data = b'' def reset(self): self.data = b'' def handleNotification(self, cHandle, data): self.data = self.data + data @property def data_length(self): return len(self.data) class myHC08: def __init__(self): self.mac = '34:14:B5:50:34:77' self.write_service_id = 4 self.write_service = None self.peripheral = btle.Peripheral(self.mac) self.delegate = ReadDelegate() self.peripheral.withDelegate(self.delegate) def connect(self): s = self.write_service_id services = self.peripheral.getServices() self.write_service = self.peripheral.getServiceByUUID(list(services)[s].uuid) def write(self, message, min_bytes, unpack_string=False): print('Writing:', message) self.delegate.reset() c = self.write_service.getCharacteristics()[0] c.write(bytes(message, &quot;utf-8&quot;)) print('Receiving %i bytes' % min_bytes) while self.peripheral.waitForNotifications(1): pass while self.delegate.data_length &lt; min_bytes: pass received = self.delegate.data if unpack_string: received = struct.unpack(unpack_string,received) return received def disconnect(self): self.peripheral.disconnect() bt = myHC08() bt.connect() r = bt.write('1*', 1250*2, '1250H') bt.disconnect() </code></pre> <p>In case this helps, my computer lists the following UUIDs for the HC-08 device:</p> <pre><code>00001800-0000-1000-8000-00805f9b34fb Generic Access 00001801-0000-1000-8000-00805f9b34fb Generic Attribute 0000180a-0000-1000-8000-00805f9b34fb Device Information 0000ffe0-0000-1000-8000-00805f9b34fb Unknown 0000fff0-0000-1000-8000-00805f9b34fb Unknown </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T14:30:33.160", "Id": "495554", "Score": "3", "body": "Welcome to Code Review!" } ]
[ { "body": "<h2>Concatenation</h2>\n<p>In computer science terms, depending on a lot of things, this:</p>\n<pre><code> self.data = self.data + data\n</code></pre>\n<p>can be worst-case O(n^2). This happens when the Python runtime needs to work reallocating everything in the existing buffer before it's able to add new data. One way around this is to use <code>BytesIO</code> instead.</p>\n<h2>Casting to a list</h2>\n<p>Based on the <a href=\"https://ianharvey.github.io/bluepy-doc/peripheral.html\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n<blockquote>\n<p>getServices() / Returns a list of Service objects</p>\n</blockquote>\n<p>Since it's already a list, there is no need to re-cast to a <code>list</code> here:</p>\n<pre><code> self.write_service = self.peripheral.getServiceByUUID(list(services)[s].uuid)\n</code></pre>\n<h2>Disconnection safety</h2>\n<p>Since <code>myHC08</code> has a <code>disconnect</code> method, it should be made into a context manager, and used in a <code>with</code> statement; or at the least:</p>\n<pre><code>bt.connect()\ntry:\n r = bt.write('1*', 1250*2, '1250H')\nfinally:\n bt.disconnect()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T19:35:02.730", "Id": "495596", "Score": "1", "body": "Thank you very much for this. I will implement these suggestions. Thanks for catching those." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T14:41:09.867", "Id": "251656", "ParentId": "251654", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T14:23:24.473", "Id": "251654", "Score": "6", "Tags": [ "python", "bluetooth" ], "Title": "Using bluepy to send and read serial data" }
251654
<p>Below is a simple typescript class used to generate a room code for an online lobby-based game (for example, <a href="https://jackbox.tv/" rel="nofollow noreferrer">https://jackbox.tv/</a> uses 4 digit codes to join rooms)</p> <p>The goal of the class is to quickly generate <em>unique</em> 4-letter codes for game lobbies, and release them after the lobby is closed. Typically, less than 100 lobby codes will be used at once so using up all 26^4 codes will likely never happen.</p> <p>Concerns:</p> <ul> <li>Is the method for generating codes efficient? Currently it just picks a random code and keeps incrementing until an unused code is found</li> <li>Is the method for encoding a number to an alphabet efficient? (converting a number to base 26)</li> </ul> <pre class="lang-js prettyprint-override"><code>const ALPHABET = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;; function randInt(min: number, max: number) { return Math.floor(Math.random() * (max - min)) + min; } export class RoomCodeManager { codeLength: number; usedCodes: Set&lt;string&gt;; // Generate 4-letter codes by default constructor(codeLength = 4) { this.codeLength = codeLength; this.usedCodes = new Set(); } generateCode() { const min = 0; const max = Math.pow(ALPHABET.length, this.codeLength); let code = randInt(min, max); // If every code is already in use, just return a random code if (this.usedCodes.size &gt;= max) { return this.encodeAlphabet(code); } // Keep incrementing by 1 until an unused code is found while (this.usedCodes.has(this.encodeAlphabet(code))) { code = (code + 1) % max; } this.usedCodes.add(this.encodeAlphabet(code)); return this.encodeAlphabet(code); } encodeAlphabet(num: number) { let str = &quot;&quot;; const len = ALPHABET.length; while (num &gt; 0) { let radix = num % len; str = ALPHABET[radix] + str; num = Math.floor(num / len); } return str.padStart(this.codeLength, ALPHABET[0]); } releaseCode(code: string) { this.usedCodes.delete(code); } } </code></pre>
[]
[ { "body": "<p>I believe this is over-engineered in some ways. If all you need is a random 4-character code, the following should suffice:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const generateCode = length =&gt; {\n return Array(length).fill('x').join('').replace(/x/g, () =&gt; {\n return String.fromCharCode(Math.floor(Math.random() * 26) + 65)\n })\n}\n\nconsole.log(generateCode(4))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>JS has a function <code>String.fromCharCode()</code> that turns decimals into the equivalent character. You can look up an ascii table and see that A-Z is 65-90. No need to hardcode a string of letters.</p>\n<pre><code>Math.floor(Math.random() * 26) + 65\n</code></pre>\n<p>This piece generates a random digit from 65-90. What it does is take <code>Math.random()</code> (0-1, 1 not included), multiplies it by 26 (gives you 0-26, 26 not included), then offsets by 65 (gives 65-91, 91 not included).</p>\n<p>You can keep calling the function until you find a unique random sequence. <code>string.replace()</code> can take a function that allows you to dynamically define a replacement. In our case, a random character form A-Z. The fill-join part is just a way to create a variable-length placeholder string, nothing special there.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T15:55:46.067", "Id": "495567", "Score": "0", "body": "`You can keep calling the function until you find a unique random sequence`\n\nThe purpose of the class was to encapsulate this process, the set keeps track of codes in use so that collisions don't occur" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T15:57:08.593", "Id": "495569", "Score": "0", "body": "But your process of generating random codes is much more concise and doesn't depend on hard-coded variables which I like, thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T16:07:34.330", "Id": "495573", "Score": "0", "body": "@thesilican Yup, you'd call this inside your class. Your class will track collisions. Just so happened that I copy-pasted the `generateCode` name to my example snippet and made it confusing. :D" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T15:43:45.270", "Id": "251660", "ParentId": "251657", "Score": "0" } }, { "body": "<p>One important consideration: should those who do not have the code for a room be able to guess it (or guess a random code) and enter a room they were never told the code for? If not, then 4 characters probably isn't quite enough:</p>\n<ul>\n<li>If guesses and codes were random, the chance of guessing a lobby is on the order of magnitude of 100/450_000. Chances are low, but they're not astronomically low. To make it better, increase the number of characters in a code.</li>\n<li>But long random character strings are difficult to remember. If you think that might be a problem for the UI, consider using random <em>words</em> instead - for example, have a dictionary of a large number of English words, and then to generate a code, put two or three of them together.</li>\n</ul>\n<blockquote>\n<p>Is the method for generating codes efficient? Currently it just picks a random code and keeps incrementing until an unused code is found</p>\n</blockquote>\n<p>If you really expect there to be less than 100 codes in use at a given time, then the chances of a collision are extremely low, so simply re-picking a random number in such rare cases sounds perfectly fine to me. If the app became more popular and collisions started happening on a regular basis, <em>then</em> it might be time to consider a different approach (such as hashing incremental numbers, or increasing the number of characters, or using a different algorithm entirely).</p>\n<blockquote>\n<p>Is the method for encoding a number to an alphabet efficient? (converting a number to base 26)</p>\n</blockquote>\n<p>When turning a number into a string, I'd prefer to use <code>toString</code> if possible. For example, if you're able to use numbers 0-9 in addition to letters, you could make <code>encodeAlphabet</code> much simpler and use:</p>\n<pre><code> encodeAlphabet(num) {\n return num.toString(36);\n }\n</code></pre>\n<p>(though, for such an approach to be user-friendly, you might also want to remove all characters that might get confused with each other, like <code>O</code> and <code>0</code>)</p>\n<p>Another approach to consider - rather than generating a number and then turning it into a string, how about generating random <em>characters</em> and putting those into a string instead? No need to work with modulo and radix:</p>\n<pre><code>generateCode() {\n let code;\n do {\n code = this.getRandomCode();\n } while (this.usedCodes.has(code));\n this.usedCodes.add(code);\n return code;\n}\ngetRandomCode() {\n return Array.from(\n { length: this.codeLength },\n () =&gt; String.fromCharCode(Math.floor(Math.random() * 26) + 65)\n ).join('');\n}\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\nfunction randInt(min, max) {\n return Math.floor(Math.random() * (max - min)) + min;\n}\n\nclass RoomCodeManager {\n // Generate 4-letter codes by default\n constructor(codeLength = 4) {\n this.codeLength = codeLength;\n this.usedCodes = new Set();\n }\n generateCode() {\n let code;\n do {\n code = this.getRandomCode();\n } while (this.usedCodes.has(code));\n this.usedCodes.add(code);\n return code;\n }\n getRandomCode() {\n return Array.from(\n { length: this.codeLength },\n () =&gt; String.fromCharCode(Math.floor(Math.random() * 26) + 65)\n ).join('');\n }\n releaseCode(code) {\n this.usedCodes.delete(code);\n }\n}\n\nconst roomCodeManager = new RoomCodeManager();\nconsole.log(roomCodeManager.generateCode());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Regarding</p>\n<pre><code>// If every code is already in use, just return a random code\nif (this.usedCodes.size &gt;= max) {\n return this.encodeAlphabet(code);\n}\n</code></pre>\n<p>Maybe, in such a case, increment <code>this.codeLength</code> instead of returning a duplicate? (Though, this'll probably never happen)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T16:05:52.507", "Id": "251662", "ParentId": "251657", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T15:05:14.533", "Id": "251657", "Score": "2", "Tags": [ "javascript", "random", "typescript" ], "Title": "Random game code id generator in typescript" }
251657
<p>I needed to write a Python generator that lazily generates, in lexicographical order, strings composed of a certain alphabet (e.g. lowercase English letters).</p> <p>My first thought was to make an infinite generator, but an infinite iterator would be pretty useless because it would just generate strings composed of only the character <code>a</code>. This is because the lexicographical ordering of strings is not a <a href="https://en.wikipedia.org/wiki/Well-order" rel="noreferrer">well-order</a>; it can be thought of as composed of an infinite sequence of infinitely nested sequences: (<code>a</code>, (<code>aa</code>, ...), (<code>ab</code>, ...), ...), (<code>b</code>, (<code>ba</code>, ...), (<code>bb</code>, ...), ...), ... The generator would never reach <code>ab</code> since it has an infinite amount of predecessors.</p> <p>Thus I went for limiting the maximum length of the strings. I.e., the full specification is a generator that lazily generates all strings in a given alphabet of up to a certain length in lexicographical order. E.g., for a maximum length of 3 with ASCII lowercase letters, it should generate, in this order: <code>&quot;&quot;</code>, <code>&quot;a&quot;</code>, <code>&quot;aa&quot;</code>, <code>&quot;aaa&quot;</code>, <code>&quot;aab&quot;</code>, ..., <code>&quot;aaz&quot;</code>, <code>&quot;ab&quot;</code>, &quot;<code>aba</code>&quot;, ..., <code>&quot;zzz&quot;</code>.</p> <p>The solution I came up with is elegant in the abstract; it uses the intrinsic recursive relationship of lexicographical ordering: if you take the set of all strings—including infinite strings—and remove the first character from each, you're still left with the set of all strings. But it's probably not very efficient in practice, as for each iteration it uses Python's string concatenation operation <code>+</code> <span class="math-container">\$m\$</span> times to build a string of length <span class="math-container">\$m\$</span> (<span class="math-container">\$m - 1\$</span> times in between characters plus the &quot;terminating&quot; empty string, as you'll see below), and strings are immutable so copies are made at every intermediate step, resulting in <span class="math-container">\$O(m^2)\$</span> time complexity at each iteration.</p> <p>Here is my solution:</p> <pre class="lang-py prettyprint-override"><code>import string def lexstrings(max_length: int, alphabet=string.ascii_lowercase): yield &quot;&quot; if max_length == 0: return for first in alphabet: for suffix in lexstrings(max_length - 1, alphabet=alphabet): yield first + suffix </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; g = lexstrings(max_length=3, alphabet=&quot;ab&quot;) &gt;&gt;&gt; list(g) ['', 'a', 'aa', 'aaa', 'aab', 'ab', 'aba', 'abb', 'b', 'ba', 'baa', 'bab', 'bb', 'bba', 'bbb'] </code></pre> <p>This implementation also &quot;supports&quot; the infinite version by supplying a negative maximum length:</p> <pre><code>&gt;&gt;&gt; g = lexstrings(-1) &gt;&gt;&gt; next(g) '' &gt;&gt;&gt; next(g) 'a' &gt;&gt;&gt; next(g) 'aa' &gt;&gt;&gt; next(g) 'aaa' ... </code></pre> <hr /> <p>Some benchmarking confirms a single iteration of this is quadratic in terms of the string size. Here is a plot of execution time for generating a string of maximum length (in a single iteration) vs the maximum length:</p> <p><a href="https://i.stack.imgur.com/U14z1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/U14z1.png" alt="Benchmarks show quadratic time complexity per iteration" /></a></p> <p>The code to generate this plot using <code>perfplot</code> follows. (I modified the order of generation so that the first iteration yields a max-length string.)</p> <pre class="lang-py prettyprint-override"><code>import string import perfplot import sys import numpy as np def lexstrings(max_length: int, alphabet=string.ascii_lowercase): if max_length == 0: return for first in alphabet: for suffix in lexstrings(max_length - 1, alphabet=alphabet): yield first + suffix yield &quot;&quot; n_range = np.linspace(1, sys.getrecursionlimit() - 500) benchmark = perfplot.bench( setup=lambda n: n, kernels=[ lambda n: next(lexstrings(n)), ], labels=[ &quot;lexstrings&quot;, ], n_range=n_range, xlabel=&quot;maximum string length&quot;, title=&quot;Single iteration (max-length string)&quot;, target_time_per_measurement=0.1, equality_check=None, ) benchmark.show(logx=False, logy=False) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T07:40:39.143", "Id": "495653", "Score": "1", "body": "Hey, why don't you plot graphs of alphabet size and max length against execution time, then you'll be able to see exactly what complexity these 2 variables contribute" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:43:24.590", "Id": "495727", "Score": "1", "body": "@Greedo Good idea, I've added a plot for time vs length of generated string. (The alphabet size only influences the number of iterations, not the time each takes to execute, so I skipped that.)" } ]
[ { "body": "<p>It's a great question, and the only improvements I can see are superficial ones:</p>\n<ul>\n<li>Your method has incomplete type hints. <code>alphabet</code> should be <code>Iterable[str]</code>, and it should return <code>-&gt; Iterable[str]</code> as well.</li>\n<li>PEP8 discourages multi-statement lines (your <code>return</code>).</li>\n</ul>\n<p>Otherwise, you should reconsider making this a recursive implementation. I see that you were careful to check <code>sys.getrecursionlimit()</code> in your test code, so you're already aware of the fact that this will break given sufficient depth. Python also does not have tail optimization so an iterative implementation will potentially yield performance improvements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T10:17:29.387", "Id": "495792", "Score": "1", "body": "I've thought of how to write this without recursion but honestly I wasn't able to come up with anything... Any hints?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T18:40:08.903", "Id": "251727", "ParentId": "251665", "Score": "3" } }, { "body": "<p>First... go read <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"nofollow noreferrer\">itertools</a>. It's in the standard library, you're reinventing some wheels here. Note that there's a long 'recipes' section at the bottom.</p>\n<p>In particular, the strings on a given alphabet of length <code>n</code> is just <code>itertools.combinations_with_replacement(alphabet, r)</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import itertools\n\ndef lexstrings(max_length: int, alphabet=string.ascii_lowercase):\n return itertools.chain(itertools.combinations_with_replacement(alphabet, r) \n for r in range(0, max_length+1))\n</code></pre>\n<p>or an abstract infinite one:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import itertools\n\ndef lexstrings(max_length: int, alphabet=string.ascii_lowercase):\n return itertools.chain(itertools.combinations_with_replacement(alphabet, r) \n for r in itertools.count())\n</code></pre>\n<p>In the future, you should also know about python 3.3 introducing <a href=\"https://docs.python.org/3/whatsnew/3.3.html#pep-380\" rel=\"nofollow noreferrer\">yield from</a>.</p>\n<p>Edit: Last, if it's not lexicographical order, rename it from <code>lexstrings</code>.\nEdit 2: Oh, looks like your original does preserve order. Keep my tips and ignore my (different order) rewrite.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T10:14:27.137", "Id": "495791", "Score": "1", "body": "1. I know itertools and yield from, if I had found a way (and a need) to use them I would have. 2. Your generators don't generate strings in lexicographical order as defined in the question." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T06:59:12.093", "Id": "251749", "ParentId": "251665", "Score": "-2" } }, { "body": "<p>On a possible non-recursive solution, as a possible improvement (per Reinderien's answer).</p>\n<p>The general idea here is that if we build a tree of these strings in the obvious way*, then the lexicographical ordering is nothing but a DFS on this tree.</p>\n<p>*Let the root be the empty string, then its neighbours are the one character long strings for each character of the alphabet, and so on. For example on the alphabet <code>ab</code> with <code>max_length = 2</code>, the tree would look like the following:</p>\n<pre><code>&lt;root&gt;\n|\n+- a\n| |\n| +- aa\n| |\n| `- ab\n|\n`- b\n |\n +- ba\n |\n `- bb\n</code></pre>\n<p>Then we can sort of build the tree while doing the DFS like so:</p>\n<pre><code>def lexstrings(max_length=3, alphabet=&quot;ab&quot;):\n reversed_alphabet = list(reversed(alphabet))\n nodes_to_visit = ['']\n\n while nodes_to_visit:\n current_node = nodes_to_visit.pop()\n \n if len(current_node) &gt; max_length:\n continue\n\n yield current_node\n nodes_to_visit.extend(current_node + tc for tc in reversed_alphabet)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T17:38:35.227", "Id": "495947", "Score": "0", "body": "Ah! So basically a DFS on a \"sorted\" trie?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T17:59:45.913", "Id": "495948", "Score": "1", "body": "How about starting with `nodes_to_visit = ['']`? Less code, and would support even negative `max_length` (at the moment you do yield `''` for that)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T18:57:56.900", "Id": "495952", "Score": "0", "body": "@superbrain Of course! Marvellous, thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T19:15:23.790", "Id": "495953", "Score": "0", "body": "@Anakhand I'm not sure, but I have added an example. I hope it makes my intentions clearer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T11:53:18.657", "Id": "251805", "ParentId": "251665", "Score": "4" } }, { "body": "<p>One approach to avoid string copying and improve the time complexity from <span class=\"math-container\">\\$\\Theta(m^2)\\$</span> to <span class=\"math-container\">\\$\\Theta(m)\\$</span> (<span class=\"math-container\">\\$m\\$</span> is the output string length) for each output string is to store characters of strings in a list and modify it in-place.</p>\n<pre><code>from typing import List, Iterable\n\ndef lex_string_gen_recursive(cur_depth: int, ch_list: List[str], alphabet: Iterable[str]) -&gt; Iterable[str]:\n yield &quot;&quot;.join(ch_list)\n if cur_depth &lt; len(ch_list):\n next_depth = cur_depth + 1\n for ch in alphabet:\n ch_list[cur_depth] = ch\n yield from lex_string_gen_recursive(next_depth, ch_list, alphabet)\n ch_list[cur_depth] = &quot;&quot;\n\ndef lex_string_gen(max_length: int, alphabet: Iterable[str]) -&gt; Iterable[str]:\n yield from lex_string_gen_recursive(0, [&quot;&quot;] * max_length, sorted(alphabet))\n</code></pre>\n<p>Test:</p>\n<pre><code>list(lex_string_gen(3, &quot;ab&quot;))\n</code></pre>\n<p>Output:</p>\n<pre><code>['',\n 'a',\n 'aa',\n 'aaa',\n 'aab',\n 'ab',\n 'aba',\n 'abb',\n 'b',\n 'ba',\n 'baa',\n 'bab',\n 'bb',\n 'bba',\n 'bbb']\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T13:21:36.857", "Id": "251810", "ParentId": "251665", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T16:28:41.540", "Id": "251665", "Score": "8", "Tags": [ "python", "recursion", "generator", "lazy" ], "Title": "Lazy generator of strings in lexicographical order" }
251665
<p>Original problem (not in English): <a href="https://pokval21.kattis.com/problems/pokval21.robotdammsugaren" rel="nofollow noreferrer">https://pokval21.kattis.com/problems/pokval21.robotdammsugaren</a></p> <p>How can my code be optimized?</p> <pre><code>import sys j = 0 instructions = [] room = [] for i in sys.stdin: inp = i.split() if(j == 0): r = int(inp[0]) c = int(inp[1]) k = int(inp[2]) if(j==1): instructions = list(inp[0]) if(j &gt;= 2): room.append(list(inp[0])) if(len(room) == r): break j += 1 def findStartPos(c, room): for y, sublist in enumerate(room): pos = [] if c in sublist: x = room[y].index(c) pos.append(x) pos.append(y) return pos return -1 botPos = findStartPos(&quot;O&quot;, room) # [x, y] x = botPos[0] y = botPos[1] i = 0 visited = [botPos] clean = 1 append = visited.append for i in instructions: if(i == &quot;&gt;&quot;): while room[y][x+1] != &quot;#&quot;: if([x+1, y] in visited): pass else: append([x+1, y]) botPos = [x+1, y] clean += 1 x += 1 botPos = [x, y] elif(i == &quot;&lt;&quot;): while room[y][x-1] != &quot;#&quot;: if([x-1, y] in visited): pass else: append([x-1, y]) botPos = [x-1, y] clean += 1 x -= 1 botPos = [x, y] elif(i== &quot;^&quot;): while room[y-1][x] != &quot;#&quot;: if([x, y-1] in visited): pass else: append([x, y-1]) botPos = [x, y-1] clean += 1 y -= 1 botPos = [x, y] elif(i == &quot;v&quot;): while room[y+1][x] != &quot;#&quot;: if([x, y+1] in visited): pass else: append([x, y+1]) botPos = [x, y+1] clean += 1 y += 1 botPos = [x, y] print(clean) </code></pre> <p>What I'm doing is taking an input where the first line is r c k. r is the max y value in the 2d array starting from 1, c is the max x value starting from 1 <code>arr[y][x]</code> and k is the amount of instructions. the second is a line of instructions eg. &lt;&gt;^v for left, right, up and down.</p> <p>In the function findStartPos I am iterating though the 2d array of strings I created from the rest of the input eg,</p> <p><code>[[#, #, #, #], [#, O, #, ., #], [#, . ., ., #], [#, #, ., ., #], [#, #, #, #]]</code> to find the starting cordinates of O.</p> <p>In the rest of the code I go though the instructions and moving the O around to count how many unique points it has been on. It can't be on a #. eg.</p> <pre><code>###### instuction: &lt; #....# #.#.O# ###### instuction: ^ #....# #.#O.# ###### instuction: &lt; #..O.# #.#..# ###### instuction: None #O...# #.#..# been on 5 unique &quot;squares&quot; </code></pre> <p>Samples:</p> <pre><code>5 5 4 v&gt;^v ##### #O#.# #...# ##..# ##### returns: 6 8 10 14 &lt;v&gt;^&lt;v&gt;v&lt;^^&gt;&lt;&gt; ########## #.#......# #....#...# ##......O# #........# #..#.....# #....#...# ########## returns: 33 </code></pre> <p>Hope the code is readable enough to be understood.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T17:21:50.667", "Id": "495584", "Score": "1", "body": "What should the first line of input imply? `r` `c` `k`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T17:23:58.253", "Id": "495585", "Score": "0", "body": "@AryanParekh r is the max y value in the 2d array starting from 1, c is the max x value starting from 1 and k is the amount of instructions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T17:27:44.703", "Id": "495586", "Score": "2", "body": "got it, you can [edit] your question to add this" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T17:29:24.043", "Id": "495587", "Score": "2", "body": "You should also add a sample set of inputs so we can test," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T17:34:03.070", "Id": "495588", "Score": "1", "body": "Samples and r,c,k implication added." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T17:35:29.263", "Id": "495589", "Score": "0", "body": "After you enter the sample input you added, the code still expects more input" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T17:38:16.470", "Id": "495590", "Score": "0", "body": "even after pressing enter? For me it works.This is use to exit the stdin `if(len(room) == r) break`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T17:39:18.380", "Id": "495591", "Score": "0", "body": "Yes, after pressing enter" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T17:40:46.193", "Id": "495592", "Score": "2", "body": "if this is from a programming challenge, please provide a link to the same." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T17:41:22.037", "Id": "495593", "Score": "0", "body": "For me it works.This is use to exit the stdin `if(len(room) == r) break` The sample can be copy and pasted into the console without going row for row." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T17:42:35.357", "Id": "495594", "Score": "0", "body": "@hjpotter92 [link](https://pokval21.kattis.com/problems/pokval21.robotdammsugaren) Here you go but it's in Swedish." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T21:04:56.470", "Id": "495612", "Score": "0", "body": "@isetnt If you find an answer useful, don't forget to give it an upvote :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T21:06:16.767", "Id": "495613", "Score": "1", "body": "@AryanParekh I can't don't have 15 rep yet" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T07:00:05.917", "Id": "495644", "Score": "0", "body": "Please include a description of the programming challenge. In English." } ]
[ { "body": "<p>A loop that does different things based on how many times the loop has executed is a code smell. It's harder to understand then breaking the loop into discrete steps.</p>\n<p>And put it in a function. Pass in the file, so you can use a file or <code>io.StringIO</code> instead of <code>sys.stdin</code> for testing.</p>\n<pre><code>def load_problem(file_input):\n r, c, k = map(int, file_input.readline().strip().split())\n\n instructions = file_input.readline().strip()\n\n room = [file_input.readline() for _ in range(r)]\n\n return room, instructions\n</code></pre>\n<p>Simplified <code>find_start()</code> a bit:</p>\n<pre><code>def find_start(room):\n for r,row in enumerate(room):\n c = row.find('O')\n if c &gt;= 0:\n return r,c\n</code></pre>\n<p>Code to solve the problem can go in another function.\nA <code>set()</code> is great for keeping track of places you've visited.\nThe duplication of code can be eliminated by using the instruction to select an x-step (dc) and y-step (dr) to be added to the current position.</p>\n<pre><code>STEP = {\n '&gt;':( 0, 1),\n 'v':( 1, 0),\n '&lt;':( 0,-1),\n '^':(-1, 0)\n}\n\ndef solve_problem(room, instructions):\n r, c = find_start(room)\n \n visited = set()\n visited.add((r, c))\n \n for instruction in instructions:\n dr, dc = STEP[instruction]\n \n while room[r + dr][c + dc] != '#':\n r += dr\n c += dc\n visited.add((r, c))\n\n return len(visited)\n</code></pre>\n<p>Drive the whole thing:</p>\n<pre><code>room, instructions = load_problem(sys.stdin)\nresult = solve_problem(room, instructions)\nprint(result)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T05:10:06.313", "Id": "495640", "Score": "0", "body": "`if \"O\" in row: return row.find(\"O\")`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T08:21:23.657", "Id": "495656", "Score": "1", "body": "@hjpotter92, that works toom but it searches `row` twice. My code searches once. Truthfully, the difference doesn't matter for this problem," } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T20:42:44.533", "Id": "251676", "ParentId": "251668", "Score": "3" } } ]
{ "AcceptedAnswerId": "251676", "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T17:13:01.763", "Id": "251668", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "programming-challenge" ], "Title": "Program to move in a 2d array given instructions, array and starting position" }
251668
<p>I am making a puzzling tool using Pygame. We have unlimited containers that we can choose their maximum capacity, and how much water is in them. We can also choose the size of each unit for convenience.</p> <p>Here is how it goes:</p> <p><a href="https://i.stack.imgur.com/NJKom.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NJKom.gif" alt="enter image description here" /></a></p> <p>Here is my code:</p> <pre><code>import pygame pygame.init() wn = pygame.display.set_mode((600, 600)) class TextBox(): def __init__(self, x, y, w, h, color_active=(0, 0, 200), color_inactive=(0, 0, 0), default='', pad=10, font=pygame.font.SysFont('Arial', 22)): self.pad = pad self.input_box = pygame.Rect(x+self.pad, y+self.pad, w, h) self.w = w self.h = h self.font = font self.color_inactive = color_inactive self.color_active = color_active self.color = self.color_inactive self.default = default self.text = default self.active = False def draw(self): if not self.text: self.text = '0' txt = self.font.render(self.text, True, self.color) width = max(self.w, txt.get_width()+self.pad) self.input_box.w = width wn.blit(txt, (self.input_box.x+5, self.input_box.y+3)) pygame.draw.rect(wn, self.color, self.input_box, 2) def check_status(self, pos): if self.input_box.collidepoint(pos): self.active = not self.active else: self.active = False self.color = self.color_active if self.active else self.color_inactive objs = [] class Obj(): def __init__(self, color, x, y, w, h, default): self.w = w self.h = h self.color = color self.rect = pygame.rect.Rect(x, y, w, h) self.dragging = False self.pad = 10 self.txt_box = TextBox(x, y, w-20, 30, pad=10, default='0') self.txt_box2 = TextBox(x, y-default, w-20, 30, pad=10, default='0') self.new = True self.straw = pygame.rect.Rect(x, y, self.pad, self.pad) self.line = False self.straw_start = None self.straw_end = None self.snap = False self.snap_y = 450 objs.append(self) def clicked(self, pos): return self.rect.collidepoint(pos) def clicked_straw(self, pos): return self.straw.collidepoint(pos) def trans(self, o): empty = int(o.txt_box.text) - int(o.txt_box2.text) full = int(self.txt_box2.text) total = full if empty &gt;= full else empty self.txt_box2.text = str(int(self.txt_box2.text) - total) o.txt_box2.text = str(int(o.txt_box2.text) + total) def offset_click(self, pos): self.dragging = True self.offset_x = self.rect.x - pos[0] self.offset_y = self.rect.y - pos[1] self.offset_x2 = self.txt_box.input_box.x - pos[0] self.offset_y2 = self.txt_box.input_box.y - pos[1] self.offset_x3 = self.txt_box2.input_box.x - pos[0] self.offset_y3 = self.txt_box2.input_box.y - pos[1] def offset_drag(self, pos): self.new = False self.rect.x = self.straw.x = self.offset_x + pos[0] self.rect.y = self.straw.y = self.offset_y + pos[1] self.txt_box.input_box.x = self.offset_x2 + pos[0] self.txt_box.input_box.y = self.offset_y2 + pos[1] self.txt_box2.input_box.x = self.offset_x3 + pos[0] self.txt_box2.input_box.y = self.offset_y3 + pos[1] def draw(self): pygame.draw.rect(wn, self.color, self.rect) amt1, amt2 = int(self.txt_box.text), int(self.txt_box2.text) bt_y = self.txt_box.input_box.bottom if amt1: w, h = self.rect.w, self.h * amt2 x, y = self.rect.x, bt_y-h + self.pad - self.h pygame.draw.rect(wn, (145, 255, 255), (x, y, w, h)) self.txt_box2.draw() else: self.txt_box2.text = '0' self.rect.h = self.h * (amt1 + 1) self.rect.y = bt_y - self.rect.h + self.pad self.txt_box.draw() pygame.draw.rect(wn, (0, 55, 255), self.straw) def draw_straw(self): if self.line: pygame.draw.line(wn, (0, 255, 255), self.straw_start, self.straw_end, 5) num = TextBox(400, 20, 100, 50, color_inactive=(255, 255, 255), color_active=(200, 200, 255), default='50', font=pygame.font.SysFont('Arial', 40)) obj = Obj((255, 255, 255), 30, 30, 70, 50, int(num.default)) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: for o in objs: o.txt_box.check_status(event.pos) o.txt_box2.check_status(event.pos) if o.clicked_straw(event.pos): o.line = True o.straw_start = event.pos o.straw_end = event.pos elif o.clicked(event.pos): o.offset_click(event.pos) num.check_status(event.pos) elif event.button == 3: for o in objs: if o.clicked(event.pos) and not o.new: o.snap = not o.snap if o.snap: o.offset_click(event.pos) o.offset_drag((event.pos[0], o.snap_y+event.pos[1]-o.rect.y-int(o.txt_box.text)*o.h-int(num.text))) o.dragging = False elif event.type == pygame.MOUSEBUTTONUP: if event.button == 1: for o in objs: if o.line: o2 = [o for o in objs if o.clicked_straw(event.pos)] if o2: o.trans(o2[0]) o.line = False o.dragging = False elif event.type == pygame.MOUSEMOTION: for o in objs: if o.line: o.straw_end = event.pos if o.dragging: if o.new: o.new = False obj = Obj((255, 255, 255), 30, 30, 70, int(num.text), int(num.default)) o.offset_drag(event.pos) elif event.type == pygame.KEYDOWN: if num.active: if event.key == pygame.K_BACKSPACE: num.text = '0' elif event.unicode.isdigit(): if num.text == '0': num.text = '' num.text += event.unicode for o in objs: o.h = int(num.text) o.rect.h = int(num.text) o.rect.y = o.txt_box.input_box.bottom-o.rect.h + o.pad o.straw.y = o.rect.y - o.h * int(o.txt_box.text) for o in objs: if o.txt_box.active: if event.key == pygame.K_BACKSPACE: o.txt_box.text = '0' o.rect.h = o.h elif event.unicode.isdigit(): if o.txt_box.text == '0': o.txt_box.text = '' o.txt_box.text += event.unicode o.rect.h = o.h * (int(o.txt_box.text) + 1) o.rect.y = o.txt_box.input_box.bottom - o.rect.h + o.pad o.straw.y = o.rect.y elif o.txt_box2.active: if event.key == pygame.K_BACKSPACE: o.txt_box2.text = '0' elif event.unicode.isdigit(): if int(o.txt_box2.text + event.unicode) &lt;= int(o.txt_box.text): if o.txt_box2.text == '0': o.txt_box2.text = '' o.txt_box2.text += event.unicode wn.fill((0, 100, 0)) num.draw() for o in objs: o.draw() for o in objs: o.draw_straw() pygame.display.flip() </code></pre> <p>As you can see, my code is in one heck of a mess. Believe this is the opposite of DRY.</p> <h3>Can someone show me how to merge the redundant lines of code?</h3> <p>Also, there might be a bug or too swimming in my code, I don't know. Big thanks to those who find one!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T05:17:16.913", "Id": "495641", "Score": "0", "body": "how do you remove a placed bucket/jug?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T12:16:13.840", "Id": "495680", "Score": "0", "body": "@hjpotter92 They are permanent buckets. Choose wisely." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T14:09:06.257", "Id": "495687", "Score": "0", "body": "Cool program +1" } ]
[ { "body": "<p>This seems like a really interesting program. There are definitely some steps you could take to make the program easier to maintain and expand. Here are my thoughts.</p>\n<ul>\n<li><p>I would avoid causing side effects in the constructor of <code>Obj</code>. Having the line <code>objs.append(self)</code> means that whenever you want to create an <code>Obj</code>, you always need to have the global list <code>objs</code> initialised appropriately.</p>\n</li>\n<li><p>You could abstract some common features out of <code>Obj</code> and <code>TextBox</code> as there is definitely some shared logic. Perhaps something like this:</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>class Clickable:\n def __init__(self, x, y, w, h, pad=0):\n self.x = x\n self.y = y\n self.w = w\n self.h = h\n self.pad = pad\n self.rect = pygame.Rect(x + pad, y + pad, w, h)\n \n def clicked(self, pos):\n return self.rect.collidepoint(pos)\n</code></pre>\n<p>Then, you can simplify <code>TextBox</code>, for example, by writing</p>\n<pre class=\"lang-py prettyprint-override\"><code>class TextBox(Clickable):\n def __init__(self, x, y, w, h, color_active=(0, 0, 200), color_inactive=(0, 0, 0), default='', pad=10, font=pygame.font.SysFont('Arial', 22)):\n super(x, y, w, h, pad)\n # Rest of code here\n\n def check_status(self, pos):\n if self.clicked(pos):\n ...\n</code></pre>\n<ul>\n<li>Your game loop seems quite tightly coupled to the implementation of the <code>Obj</code> class, and it manipulates quite a lot of the internal state of each <code>Obj</code>. Instead, perhaps it would make more sense to pass on each relevant event to an object, for example writing <code>o.mouse_moved(...)</code> and then letting the object itself decide how to react. As it stands, the main loop decides whether to change each object, which breaks the idea of &quot;encapsulation&quot;.</li>\n</ul>\n<p>As a rough guide of the direction you should try to go with the program:</p>\n<ul>\n<li><p>Decouple the main game loop and the internals of each <code>Obj</code>. Try to make it so the main loop knows as little as possible about the <code>Obj</code> itself, and instead, if a click or mouse move occurs, tell the object and let it decide what action is appropriate. This will make it easier if you want to add more classes like <code>Obj</code>, because you can implement general methods such as <code>draw()</code> and <code>clicked()</code> which the game loop can call.</p>\n</li>\n<li><p>Share logic through inheritance. Where two objects behave in a similar way or you feel that you're repeating yourself, try and figure out what is the same about the two classes, then abstract that out into a parent class as I demonstrated above.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T19:07:31.787", "Id": "495748", "Score": "0", "body": "Thanks! I'm still studying your post, but I've noticed the merging of the 2 for loops. \nThe 2 loops are intentional so that the straws will never be covered by any of the jugs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T19:45:54.947", "Id": "495753", "Score": "0", "body": "@user229550 Indeed, that is a mistake on my part, thanks. I've amended this now." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T18:21:01.983", "Id": "251725", "ParentId": "251674", "Score": "1" } } ]
{ "AcceptedAnswerId": "251725", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T20:00:11.123", "Id": "251674", "Score": "4", "Tags": [ "python", "pygame" ], "Title": "Water jug puzzle simulation using Pygame" }
251674
<p>I have multiple binary (structured) file, each of 2GB, which I am currently reading in pair, using memmap to cross-correlate the same. I want to minimise the time required by this IO process, in the code.</p> <p>I am implementing this as a Cython function, though the copying of memmap array to numpy array is quite fast (~3 sec) when same set of files are processed twice, it takes large amount of time if new files are to be read (~71 sec), possibly because of cache memory, this is the same with numpy fromfile as well.</p> <p>What is the efficient and fastest way of copying the memmap to numpy array?</p> <p>Any suggestions on the same are appreciated.</p> <p>Code used:</p> <pre><code>comf = np.memmap(file_name, dtype = dt, mode = 'c') comf1 = np.memmap(file_name1, dtype = dt, mode = 'c') cdef np.ndarray tempcomf = np.zeros((templen, 1024), dtype = np.int8) cdef np.ndarray tempcomf1 = np.zeros((templen1, 1024), dtype = np.int8) tempcomf = comf['data'] tempcomf1 = comf1['data'] </code></pre> <p><strong>EDIT:</strong></p> <p>Here is the function used:</p> <pre><code>cpdef tuple decrypt_file(file_name, file_name1): cdef long long int templen = 0 cdef long long int templen1= 0 cdef np.ndarray tempcomf = np.zeros((templen, 1024),dtype=np.int8) cdef np.ndarray tempcomf1 = np.zeros((templen1, 1024),dtype=np.int8) dt = np.dtype([('header', 'S8'), ('Source', 'S10'), ('header_rest', 'S10'), ('Packet', '&gt;u4'), ('data', '&gt;i1', 1024)]) comf = np.memmap(file_name, dtype = dt, mode = 'c') comf1 = np.memmap(file_name1, dtype = dt, mode = 'c') templen = comf['Packet'][-1]-comf['Packet'][0] templen1= comf1['Packet'][-1]-comf1['Packet'][0] t_1 = time.time() tempcomf = comf['data'] tempcomf1= comf1['data'] print('Time take for memarray copy...'+str(time.time()-t_1)) tempcomf = tempcomf.ravel() tempcomf1= tempcomf1.ravel() tempcomf_X = np.array(tempcomf[1::2], order = 'F') tempcomf_Y = np.array(tempcomf[0::2], order = 'F') tempcomf1_X= np.array(tempcomf1[1::2],order = 'F') tempcomf1_Y= np.array(tempcomf1[0::2],order = 'F') return tempcomf_X, tempcomf_Y, tempcomf1_X, tempcomf1_Y </code></pre> <p><strong>Input Data Structure:</strong> The binary file input has 32 bytes header and 1024 bytes data, the focus is on reading the latter memmap array to numpy array.</p> <p>This is the function where the files are read and the data is separated from the header. If same file set is given twice, memory copy takes ~2 sec, but when a different set of files are given the copying takes ~72 sec.</p> <p><strong>EDIT - MORE INFORMATION</strong></p> <p>After further investigation, I found that this problem indeed stems from caching of memory. As part of the test I cleared cache (echo 3 &gt; /proc/sys/vm/drop_caches), which results in longer time for the copy of memmap array to numpy array (to volatile memory).</p> <p>As part of confirmation of the issue, when I pre-cache the binary files into memory using <code>vmtouch</code> it takes ~3 sec for the copy (memmap to numpy array) to take place.</p> <p>Though the solution to the problem is not yet found, as even the pre-caching takes ~52 sec, when done by <code>vmtouch</code>, the reason for the problem is related to the caching of memory.</p> <p><strong><code>vmtouch</code> OUTPUT</strong>:</p> <pre><code>vmtouch -vt /data/ch01_SOURCE_Binary_20201011_110101.bin [OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO] 522720/522720 Files: 1 Directories: 0 Touched Pages: 522720 (1G) Elapsed: 52.403 seconds </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T20:19:48.057", "Id": "495602", "Score": "0", "body": "Read this article that may help you https://pythonspeed.com/articles/reduce-memory-array-copies/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T20:32:45.997", "Id": "495603", "Score": "1", "body": "I feel that this question is more suitable for https://stackoverflow.com/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T20:53:14.207", "Id": "495605", "Score": "2", "body": "@AryanParekh I disagree in this case: issues of performance are expressly permitted on CR. This question needs work, but for reasons of missing context, not due to its subject." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T20:55:13.277", "Id": "495608", "Score": "2", "body": "And I agree with @Reinderien that the question is missing context, there is no problem with asking performance related question on CR." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T20:56:49.980", "Id": "495609", "Score": "0", "body": "Yes I agree with you, as I said I feel it is \" more suitable \" for SO" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T20:58:27.743", "Id": "495610", "Score": "0", "body": "@AryanParekh It's not, though... it would actually be a quite poor question for SO. It doesn't have a minimum reproducible example. It's a great question for CR. It just needs more context." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T21:00:43.467", "Id": "495611", "Score": "0", "body": "Well that's the problem, it's missing a lot of review context" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T21:34:46.197", "Id": "495618", "Score": "1", "body": "I have added the complete code." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T20:10:33.140", "Id": "251675", "Score": "4", "Tags": [ "python", "numpy", "signal-processing", "cython" ], "Title": "Slow copying of memmap array to numpy array" }
251675
<p>I am creating a watchdog in python to monitor a folder and then create a backup with the new version when a file is modified. I extend the FileSystsemEventHandler class to add 7 extra variables. However not every variable is used on every event so I'm not sure where to initialize the variables and where to put the logic for initializing certain variables based on the event. My current program works however I am new to coding and want to make sure I am using proper coding convention.</p> <pre><code>import os import getpass import re import glob import sys import time import pathlib import logging import shutil import tkinter as tk from tkinter import filedialog from watchdog.observers import Observer from watchdog.events import LoggingEventHandler, FileSystemEventHandler SLEEP_TIME = 30 class OnMyWatch: def __init__(self, watch_src, watch_dest): self.observer = Observer() self.watch_src = watch_src self.watch_dest = watch_dest def run(self): event_handler = Handler(watch_src, watch_dest) self.observer.schedule(event_handler, watch_src, recursive = True) self.observer.start() try: while True: time.sleep(SLEEP_TIME) except: self.observer.stop() print(&quot;Observer Stopped&quot;) self.observer.join() class Handler(FileSystemEventHandler): def __init__(self, watch_src, watch_dest): self.watch_src = watch_src self.watch_dest = watch_dest self.src_dir = '' self.src_name = '' self.dest_dir = '' self.file_extension = '' # METHOD DONE def on_any_event(self, event): if event.event_type == 'moved': self.src_dir = os.path.join(self.watch_dest, os.path.relpath(event.src_path, self.watch_src)) self.dest_dir = os.path.join(self.watch_dest, os.path.relpath(event.dest_path, self.watch_src)) else: if event.is_directory: self.src_dir = event.src_path self.dest_dir = os.path.join(self.watch_dest, os.path.relpath(event.src_path, self.watch_src)) else: src_path, self.file_extension = os.path.splitext(event.src_path) self.src_name = os.path.basename(src_path) self.src_dir = os.path.dirname(src_path) self.dest_dir = os.path.join(self.watch_dest, os.path.relpath(src_path, self.watch_src)) def on_created(self, event): # CREATED EVENT def on_modified(self, event): # MODIFIED EVENT def on_moved(self, event): # MOVED EVENT def on_deleted(self, event): # DELETED EVENT if __name__ == &quot;__main__&quot;: root = tk.Tk() root.withdraw() watch_src = filedialog.askdirectory() watch_dest = filedialog.askdirectory() watch = OnMyWatch(watch_src, watch_dest) watch.run() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T07:06:08.973", "Id": "495645", "Score": "2", "body": "You've omitted too much code to give a review--the variables you initialize are never used. Include the code of \"on_created\", etc. That said, the short answer is that your event handler is called many times, once for each event, so you should not be storing the variable for each specific event, on the handler. In fact, \"on_any_event\" should probably be left as the default." } ]
[ { "body": "<h2>Wait loops</h2>\n<p>I don't think that this:</p>\n<pre><code> try:\n while True:\n time.sleep(SLEEP_TIME)\n except:\n self.observer.stop()\n print(&quot;Observer Stopped&quot;)\n</code></pre>\n<p>should be necessary. I would expect that if you simply <code>join</code>, it would do what you want - block until the observer is done.</p>\n<p>Even if you retained the above structure, you're not using your <code>try</code> correctly. That <code>except</code> should be a <code>finally</code>. In other words, you don't want to <code>stop</code> when something goes wrong; you want to stop whether something goes wrong or not.</p>\n<h2>Pathlib</h2>\n<p><code>on_any_event</code> contains a lot of <code>os.path</code> calls. You'll find that replacing these with <code>pathlib.Path</code> equivalents is better-structured. It's a more object-oriented and &quot;syntactically sugary&quot; way of manipulating paths.</p>\n<h2>Overall</h2>\n<p>I'm not convinced that writing these generic <code>watchdog</code> wrappers (Handler, OnMyWatch) is useful. It's subtracting from the utility of <code>watchdog</code>. What if you want code of your own to run once <code>Handler.on_any_event</code> changes some of its attributes? You could subclass <code>Handler</code> and override <code>on_any_event</code>, calling <code>super().on_any_event</code> to set those attributes, but that's a fairly poor data-passing pattern.</p>\n<p>You'd be better off writing a purpose-built <code>FileSystemEventHandler</code> that does not have those file-component attributes, does not look at <code>event.event_type</code>, and handles specifically the event you care about.</p>\n<p>In other words, this is abstraction that hurts rather than helps you, and introduces functions with side-effects that set attributes that don't make sense as attributes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T15:15:31.143", "Id": "251709", "ParentId": "251677", "Score": "3" } } ]
{ "AcceptedAnswerId": "251709", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T21:34:05.887", "Id": "251677", "Score": "4", "Tags": [ "python", "file-system" ], "Title": "Watchdog to monitor a folder" }
251677
<p>Hello I am making a code in C to find the value of the last sequence of palindromes of a specified size (<code>d</code>) and I need to optimize this code as it is for an exercise platform called URI Online Judge and is giving <code>Time Limit exceeded</code>.</p> <p><a href="https://www.urionlinejudge.com.br/judge/en/problems/view/1686" rel="nofollow noreferrer">https://www.urionlinejudge.com.br/judge/en/problems/view/1686</a></p> <blockquote> <p>Given a string s[1..N], we define a palindromic sequence of length p and displacement d (1 &lt;= p &lt;= d) as a sequence of k (k &gt;= 1) disjoint substrings of s (each of which is a palindrome of length p) distant d characters from each other.</p> <p>More formally, it can be written as the following sequence of disjoint substrings of s : A= (s[i..i+p-1], s[i+d..i+d+p-1], s[i+2d..i+2d+p-1], ...), where each element of A is a palindrome of length p. Recall that a string is called a palindrome if it reads the same forwards and backwards.</p> <p>The value of a palindromic sequence is the total number of characters from string s it uses (i.e., if the sequence has k palindromes of length p, its value is k*p). Given a fixed displacement value D, calculate the largest value of a palindromic sequence contained in a string S.</p> <p><strong>Input</strong><br /> Each test case is described using two lines. The first line contains two integers N and D (1 &lt;= N &lt;=10^5), 1 &lt;= D &lt;=10^5) representing respectively the length of the string S and the required displacement value. The next line contains the string S of length N consisting only of lowercase letters.</p> <p>The last test case is followed by a line containing two zeros.</p> <p><strong>Output</strong><br /> For each test case output a line with the maximum value of a palindromic sequence with displacement D in string S.</p> <p><strong>Samples</strong><br /> Input<br /> 5 1<br /> abbbc<br /> Output<br /> 5</p> </blockquote> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; char palavra[100000]; int palindrome(const int inicio, const int fim) { if (inicio &gt;= fim) { return 1; } if (palavra[inicio] != palavra[fim - 1]) { return 0; } return palindrome(inicio + 1, fim - 1); } int maior_sequencia(const int n, const int d) { int valor = 0, temp; int i, j; for (i = 1; i &lt;= d; i++) { temp = 0; for (j = 0; j &lt; n; j += d) { if (palindrome(j, j + i)) { temp++; } } if (temp * i &gt; valor) { valor = temp * i; } } return valor; } int main() { int n, d; while (1) { scanf(&quot;%d %d&quot;, &amp;n, &amp;d); if (n == 0 || d == 0) { return 0; } scanf(&quot;%s&quot;, palavra); printf(&quot;%d\n&quot;, maior_sequencia(n, d)); } return 0; } </code></pre> <p>edit: Now i have a functional code, but give <code>Time Limit exceeded</code> again :/</p> <p>edit 2: I added another version of the code, how could I optimize one of these two versions?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T23:00:07.343", "Id": "495628", "Score": "0", "body": "Welcome to Code Review! We only review functional code here - based on your final comment, the code is currently non-functional, and thus this question is off-topic. Please [edit](https://codereview.stackexchange.com/posts/251678/edit) your question to have functioning code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T08:29:02.417", "Id": "495658", "Score": "0", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too vague to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T08:29:49.997", "Id": "495659", "Score": "2", "body": "Actually, I'm struggling to understand what you mean by \"*find the value of the last sequence of palindromes*\". Could you be more specific about the purpose of the program? Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T09:35:54.073", "Id": "495664", "Score": "1", "body": "@Dannnno Actually this question just requires a little edit and some details. Otherwise, it is fully on-topic as `Time limit Exceeded` is just performance-related." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T14:04:57.593", "Id": "495686", "Score": "0", "body": "Welcome to Code Review. When posting online programming-challenges please include the actual text of the challenge as well as the link because links can break." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T14:18:33.960", "Id": "495688", "Score": "0", "body": "@TobySpeight is it clear enough yet?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T14:25:56.337", "Id": "495692", "Score": "2", "body": "The title doesn't seem to have changed, @pacmaninbw. Other than that, it looks ready for CR (I'm assuming that the writer of the challenge permits the re-use of it here; I don't have time to go and check)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T14:31:56.360", "Id": "495695", "Score": "1", "body": "Am I reading it wrong, or would the pathological case \"palindromes of length 1, directly after each other\" qualify?" } ]
[ { "body": "<h2>General Observations</h2>\n<p>It might be better to use an iterative solution rather than a recursive solution for this problem. Recursion can be expensive in terms of memory resources for the stack and it could also result in stack overflow. Calling a function is more expensive in terms of time than looping through a string as well. If the calling function created a reverse string it might be possible to use <code>strcmp()</code> or <code>strstr()</code> in the <code>palindrome()</code> function, either of those functions are very fast. It would also be faster to base the <code>palindrome()</code> function on strings rather than indexes.</p>\n<p>While the program description uses <code>n</code> and <code>d</code> it would better to use more descriptive names in the program to make it more readable, examples might be <code>length</code> and <code>displacement</code>.</p>\n<p>Since this question is performance based I won't recommend this, but memory for palavra be allocated in the <code>while (1) {</code> loop in <code>main()</code> since the length of the string is read in during each iteration.</p>\n<p>Since English variable and function names are generally considered a global programming standard it might be better to use English variable and function names. I can figure out <code>inicio</code> and <code>fim</code> as <code>start</code> and <code>end</code>, but I don't have a clue what <code>palavra</code> or <code>maior_sequencia</code> (for <code>maior_sequencia</code> I'm guessing that it means major sequence). This is especially true since the problem statement is in English.</p>\n<h2>Avoid Global Variables</h2>\n<p>It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C and C++ global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The <a href=\"https://stackoverflow.com/questions/484635/are-global-variables-bad\">answers in this stackoverflow question</a> provide a fuller explanation.</p>\n<p>The variable <code>palavra</code> should be declared in main and passed into functions as necessary.</p>\n<h2>Declare Variables as Necessary</h2>\n<p>The original version of C required all variables to be declared at the top of a logic block, but this is no longer the case. In almost all programming languages it is now considered better to declare and initialize variables as they are needed. In the C programming language they need to be initialized because no local variable have a default value assigned. Each variable should be declared and initialized on its own line to make the code easier to read, write and maintain. In the function <code>maior_sequencia</code> the variables i and j can be defined in their respective loops:</p>\n<pre><code>int maior_sequencia(const size_t length, const size_t displacement, char *palavra) {\n\n size_t valor = 0;\n size_t temp = 0;\n\n for (size_t i = 1; i &lt;= displacement; i++) {\n temp = 0;\n for (size_t j = 0; j &lt; length; j += displacement) {\n if (palindrome(j, j + i, palavra)) {\n temp++;\n }\n }\n if (temp * i &gt; valor) {\n valor = temp * i;\n }\n }\n\n return valor;\n}\n</code></pre>\n<h2>Use Unsigned Integer Based Variables for Indexes and Sizes</h2>\n<p>Rather than using integers that can go negative for indexes and sizes it is better to use types such as <code>size_t</code> which are based on unsigned integers. The type <code>size_t</code> is what is returned by the <code>sizeof(OBJECT)</code> function as an example.</p>\n<h2>Magic Numbers</h2>\n<p>There are Magic Numbers function (100000), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.</p>\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n<h2>Don't Ignore Library Function Return Values</h2>\n<p>The function <code>scanf()</code> returns an integer that <a href=\"https://stackoverflow.com/questions/10469643/what-does-the-scanf-function-return\">indicates the number of values read or end of file (EOF)</a>. This value can be used to control the while loop in <code>main()</code> rather than having the <code>while (1) loop</code> with a break.</p>\n<pre><code>#define MAX_LENGTH 10000\n\nint main() {\n size_t length = 0;\n size_t displacement = 0;\n\n while (scanf(&quot;%d %d&quot;, &amp;length, &amp;displacement) != EOF) {\n char palavra[MAX_LENGTH + 1];\n\n if (scanf(&quot;%s&quot;, palavra) == EOF)\n {\n break;\n }\n else\n {\n printf(&quot;%d\\n&quot;, maior_sequencia(length, displacement, palavra));\n }\n }\n\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T20:51:58.110", "Id": "495760", "Score": "0", "body": "Better than `!= EOF` would be `== 2` respectively `== 1`. 10000? Nope, 10 to the 5th == 100000." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T16:15:33.357", "Id": "251716", "ParentId": "251678", "Score": "3" } } ]
{ "AcceptedAnswerId": "251716", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T21:43:52.080", "Id": "251678", "Score": "3", "Tags": [ "performance", "c", "programming-challenge", "palindrome" ], "Title": "palindrome code in C times out in program challenge?" }
251678
<p>Hi I am trying to write a programme that outputs the probability that the two randomly selected numbers are coprime</p> <ul> <li>Two integers are coprime if the only positive integer that divides into both of them is 1. In other words, the greatest common divisor of two coprime numbers is 1.</li> <li>If two numbers x and y are selected randomly, the odds that they will be coprime with each other is 61% (6 divided by PI^2). But what if we put some restrictions on the two numbers? For example, if x is a randomly selected number that is divisible by 7 and y is a randomly selected number that is divisible by 13? In this case, the odds that they are coprime is 49%.</li> <li>I am given a divisor of the first number and a divisor of the second number. I must then output an integer from 0 to 100, which is the percentage probability that the two randomly selected numbers are coprime.</li> </ul> <p>here is what I have so far</p> <pre><code>import java.util.Scanner; public class Main { public static int myTestMethod(int a, int b) //method taking two numbers a and b { //Calculating gcd because if gcd is 1 then a and b are //coprimes. if (b == 0) return a; else return myTestMethod(b, a % b); } public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println(&quot;Enter a and b&quot;); int y; float p = 0; //taking inputs a and b two numbers. int a = sc.nextInt(); int b = sc.nextInt(); //Calculating gcd by calling method y = (myTestMethod(a, b)); System.out.print(&quot;gcd is:&quot;); System.out.println(y); p = (myTestMethod(a, b)); //if gcd is 1 the probability should be 1 if (y == 1) { System.out.println(&quot;probability is:&quot;); System.out.println(p); } //else print probability as p/100. else { System.out.println(&quot;The probability is :&quot;); System.out.println(p / 100); } } } </code></pre> <p>is this the correct way to go about it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T22:19:38.273", "Id": "495623", "Score": "2", "body": "Hello, you should format the code with a formatter and add the missing method `myTestMethod`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T22:52:51.833", "Id": "495625", "Score": "4", "body": "Did you test it? Does it print 0.49 for inputs 7 and 13?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T02:03:15.330", "Id": "495636", "Score": "0", "body": "(FYI, from a mathematical point of view, a \"randomly selected integer\" doesn't quite exist. You can make sense of the statement if you're being careful, and that ends up giving you the 6/π^2.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T16:13:54.843", "Id": "495706", "Score": "1", "body": "@vnp, I've tried and it gave me the result: `gcd is:1` and `probability is: 1.0` for an input `7` and `13`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T16:42:45.043", "Id": "495711", "Score": "1", "body": "Unfortunately, that makes it an off-topic here. We may only review the code that works as expected." } ]
[ { "body": "<p>This review is for the code only, not the optimization / correctness; I assume the code works as IS.</p>\n<h2>Avoid using <code>C-style</code> array declaration</h2>\n<p>In the main method, you declared a <code>C-style</code> array declaration with the <code>args</code> variable.</p>\n<p><strong>before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>String args[]\n</code></pre>\n<p><strong>after</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>String[] args\n</code></pre>\n<p>In my opinion, this style is less used and can cause confusion.</p>\n<h2>Always add curly braces to <code>loop</code> &amp; <code>if</code></h2>\n<p>In my opinion, it's a bad practice to have a block of code not surrounded by curly braces; I saw so many bugs in my career related to that, if you forget to add the braces when adding code, you break the logic / semantic of the code.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>if (b == 0)\n return a;\nelse\n return myTestMethod(b, a % b);\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>if (b == 0) {\n return a;\n} else {\n return myTestMethod(b, a % b);\n}\n</code></pre>\n<h2>Other things</h2>\n<h3>To save space in the main method, you can inline the variable <code>y</code> and <code>p</code></h3>\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nint y = (myTestMethod(a, b));\n//[...]\nfloat p = (myTestMethod(a, b));\n//[...]\n</code></pre>\n<h3>You can take less lines for the printing in the main method</h3>\nYou can make a printing method\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n if (y == 1) { //if gcd is 1 the probability should be 1\n printMultiLine(&quot;probability is:&quot;, p);\n } else { //else print probability as p/100.\n printMultiLine(&quot;The probability is :&quot;, p / 100);\n }\n}\n\nprivate static void printMultiLine(String message, float value) {\n System.out.println(message);\n System.out.println(value);\n}\n</code></pre>\n<p><strong>or</strong></p>\nYou can uses <code>java.io.PrintStream#printf</code>\n<p><code>java.io.PrintStream#printf</code> offer you to use <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Formatter.html\" rel=\"nofollow noreferrer\">patterns</a> to build the string without concatenating it manually. The only downside is you will be forced to add the break line character yourself; in java you can use the <code>%n</code> to break the line (portable between various platforms) or uses the traditional <code>\\n</code> / <code>\\r\\n</code>.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n //[...]\n if (y == 1) { //if gcd is 1 the probability should be 1\n System.out.printf(&quot;probability is:%n%f&quot;, p);\n } else { //else print probability as p/100.\n System.out.printf(&quot;The probability is:%n%f&quot;, p / 100);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T16:07:52.160", "Id": "251713", "ParentId": "251679", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T22:06:21.277", "Id": "251679", "Score": "1", "Tags": [ "java" ], "Title": "Java probability if 2 integers are coprime" }
251679
<p>I decided to write a simple tab bar for macOS using Swift.</p> <p><code>tabs.swift</code></p> <pre class="lang-swift prettyprint-override"><code>import SwiftUI import Foundation import Combine class ViewRouter: ObservableObject { @Published var currentView = &quot;home&quot; } struct Tabs: View { @ObservedObject var viewRouter = ViewRouter() var body: some View { GeometryReader { geometry in VStack { if self.viewRouter.currentView == &quot;home&quot; { Text(&quot;Home&quot;) } else if self.viewRouter.currentView == &quot;settings&quot; { Text(&quot;Settings&quot;) } Spacer() HStack { { () -&gt; Text in if self.viewRouter.currentView == &quot;home&quot; { return Text(&quot;Home&quot;).foregroundColor(Color.blue) } else { return Text(&quot;Home&quot;) } }() .onTapGesture { self.viewRouter.currentView = &quot;home&quot; } { () -&gt; Text in if self.viewRouter.currentView == &quot;settings&quot; { return Text(&quot;Settings&quot;).foregroundColor(Color.blue) } else { return Text(&quot;Settings&quot;) } }() .onTapGesture { self.viewRouter.currentView = &quot;settings&quot; } } }.edgesIgnoringSafeArea(.bottom).padding(20) } } } </code></pre> <p>In <code>ContentView.swift</code>, I just display this using <code>Tabs()</code> in the <code>ContentView</code> struct.</p> <p>In the <code>HStack</code>, I use two anonymous functions to give the text in the tab bar a blue color when that item is selected:</p> <pre class="lang-swift prettyprint-override"><code>{ () -&gt; Text in if self.viewRouter.currentView == &quot;home&quot; { return Text(&quot;Home&quot;).foregroundColor(Color.blue) } else { return Text(&quot;Home&quot;) } }() .onTapGesture { self.viewRouter.currentView = &quot;home&quot; } </code></pre> <p>I also do this for the second item in the tab bar.</p> <p>Is this the best (fastest and most concise) way to do this, or is there a better way?</p>
[]
[ { "body": "<p>There <em>is</em> a shorter and faster way, using <a href=\"https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html#ID71\" rel=\"nofollow noreferrer\">ternary operators</a>.</p>\n<p>You could use</p>\n<pre class=\"lang-swift prettyprint-override\"><code>Text(&quot;Home&quot;).foregroundColor(self.viewRouter.currentView == &quot;home&quot; ? Color.blue: Color.black)\n</code></pre>\n<p>instead of</p>\n<pre class=\"lang-swift prettyprint-override\"><code>{ () -&gt; Text in\n if self.viewRouter.currentView == &quot;home&quot; {\n return Text(&quot;Home&quot;).foregroundColor(Color.blue)\n } else {\n return Text(&quot;Home&quot;)\n }\n}()\n</code></pre>\n<p>However, with the advent of macOS Mojave 10.14 two years ago, users had an option to enable dark mode. So, unless you've explicitly disabled dark mode in your app, <code>Color.black</code> will blend in with the rest of your app bar. To prevent this, check for dark mode with <code>UserDefaults.standard.object(forKey: &quot;AppleInterfaceStyle&quot;)</code>. If the user is using light mode, <code>UserDefaults.standard.object(forKey: &quot;AppleInterfaceStyle&quot;)</code> will be <code>nil</code>, and if it's dark mode, it will be <code>&quot;Dark&quot;</code></p>\n<pre class=\"lang-swift prettyprint-override\"><code>Text(&quot;Home&quot;).foregroundColor(self.viewRouter.currentView == &quot;home&quot; ? Color.blue: UserDefaults.standard.object(forKey: &quot;AppleInterfaceStyle&quot;) == nil ? Color.black: Color.white)\n</code></pre>\n<hr />\n<p>As @BenLeggiero has suggested, this is a much shorter way to do the above:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>Text(&quot;Home&quot;).foregroundColor(viewRouter.currentView == &quot;home&quot; ? .blue : .primary)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-05T18:57:32.013", "Id": "498970", "Score": "1", "body": "You can check for dark mode with `@Environment(\\.colorScheme) var colorScheme`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-07T15:52:38.160", "Id": "499190", "Score": "1", "body": "Is there a reason to not use `Text(\"Home\").foregroundColor(viewRouter.currentView == \"home\" ? .blue : .primary)`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-07T16:58:52.357", "Id": "499208", "Score": "1", "body": "@BenLeggiero No, there's not. In fact, I'll update my answer right now to reflect that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T23:59:25.587", "Id": "251682", "ParentId": "251681", "Score": "2" } } ]
{ "AcceptedAnswerId": "251682", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-05T22:36:28.650", "Id": "251681", "Score": "2", "Tags": [ "swift", "closure", "swiftui" ], "Title": "Display a Text() with a foreground color based on a condition" }
251681
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251620/231235">A recursive_transform Template Function for BoostMultiArray</a> and <a href="https://codereview.stackexchange.com/q/251379/231235">An Add/Minus Operator For Boost.MultiArray in C++</a>. Besides the add / minus operator for Boost.MultiArray, I am trying to implement an element-wise increment operator and decrement operator as below. The <code>recursive_transform</code> template function is used here to handle the element-wise incresing and decresing work.</p> <pre><code>// Element Increment Operator // Define nonmember prefix increment operator template&lt;class T&gt; requires is_multi_array&lt;T&gt; auto operator++(T&amp; input) { input = recursive_transform(input, [](auto&amp; x) {return x + 1; }); return input; } // Define nonmember postfix increment operator template&lt;class T&gt; requires is_multi_array&lt;T&gt; auto operator++(T&amp; input, int i) { auto output = input; input = recursive_transform(input, [](auto&amp; x) {return x + 1; }); return output; } // Element Decrement Operator // Define nonmember prefix decrement operator template&lt;class T&gt; requires is_multi_array&lt;T&gt; auto operator--(T&amp; input) { input = recursive_transform(input, [](auto&amp; x) {return x - 1; }); return input; } // Define nonmember postfix decrement operator template&lt;class T&gt; requires is_multi_array&lt;T&gt; auto operator--(T&amp; input, int i) { auto output = input; input = recursive_transform(input, [](auto&amp; x) {return x - 1; }); return output; } </code></pre> <p>The used <code>recursive_transform</code> template function and the other concepts:</p> <pre><code>template&lt;typename T&gt; concept is_back_inserterable = requires(T x) { std::back_inserter(x); }; template&lt;typename T&gt; concept is_multi_array = requires(T x) { x.num_dimensions(); x.shape(); boost::multi_array(x); }; template&lt;typename T&gt; concept is_iterable = requires(T x) { *std::begin(x); std::end(x); }; template&lt;typename T&gt; concept is_elements_iterable = requires(T x) { std::begin(x)-&gt;begin(); std::end(x)-&gt;end(); }; template&lt;typename T&gt; concept is_summable = requires(T x) { x + x; }; template&lt;class T, class F&gt; auto recursive_transform(const T&amp; input, const F&amp; f) { return f(input); } template&lt;class T, std::size_t S, class F&gt; auto recursive_transform(const std::array&lt;T, S&gt;&amp; input, const F&amp; f) { using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f)); std::array&lt;TransformedValueType, S&gt; output; std::transform(input.cbegin(), input.cend(), output.begin(), [f](auto&amp; element) { return recursive_transform(element, f); } ); return output; } template&lt;template&lt;class...&gt; class Container, class Function, class... Ts&gt; requires (is_back_inserterable&lt;Container&lt;Ts...&gt;&gt;&amp;&amp; is_iterable&lt;Container&lt;Ts...&gt;&gt; &amp;&amp; !is_elements_iterable&lt;Container&lt;Ts...&gt;&gt;) // non-recursive version auto recursive_transform(const Container&lt;Ts...&gt;&amp; input, const Function&amp; f) { using TransformedValueType = decltype(f(*input.cbegin())); Container&lt;TransformedValueType&gt; output; std::transform(input.cbegin(), input.cend(), std::back_inserter(output), f); return output; } template&lt;template&lt;class...&gt; class Container, class Function, class... Ts&gt; requires (is_back_inserterable&lt;Container&lt;Ts...&gt;&gt; &amp;&amp; is_elements_iterable&lt;Container&lt;Ts...&gt;&gt;) auto recursive_transform(const Container&lt;Ts...&gt;&amp; input, const Function&amp; f) { using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f)); Container&lt;TransformedValueType&gt; output; std::transform(input.cbegin(), input.cend(), std::back_inserter(output), [&amp;](auto&amp; element) { return recursive_transform(element, f); } ); return output; } template&lt;class T, class F&gt; requires (is_multi_array&lt;T&gt;) auto recursive_transform(const T&amp; input, const F&amp; f) { boost::multi_array output(input); for (decltype(+input.shape()[0]) i = 0; i &lt; input.shape()[0]; i++) { output[i] = recursive_transform(input[i], f); } return output; } </code></pre> <p>The test of the nonmember postfix increment operator for Boost.MultiArray is as below.</p> <pre><code>// Create a 3D array that is 3 x 4 x 2 typedef boost::multi_array&lt;double, 3&gt; array_type; typedef array_type::index index; array_type A(boost::extents[3][4][2]); // Assign values to the elements int values = 1; for (index i = 0; i != 3; ++i) for (index j = 0; j != 4; ++j) for (index k = 0; k != 2; ++k) A[i][j][k] = values++; std::cout &lt;&lt; &quot;A:&quot; &lt;&lt; std::endl; for (index i = 0; i != 3; ++i) for (index j = 0; j != 4; ++j) for (index k = 0; k != 2; ++k) std::cout &lt;&lt; A[i][j][k] &lt;&lt; std::endl; auto B = A++; std::cout &lt;&lt; &quot;After executing auto B = A++&quot; &lt;&lt; std::endl; std::cout &lt;&lt; &quot;A:&quot; &lt;&lt; std::endl; for (index i = 0; i != 3; ++i) for (index j = 0; j != 4; ++j) for (index k = 0; k != 2; ++k) std::cout &lt;&lt; A[i][j][k] &lt;&lt; std::endl; std::cout &lt;&lt; &quot;B:&quot; &lt;&lt; std::endl; for (index i = 0; i != 3; ++i) for (index j = 0; j != 4; ++j) for (index k = 0; k != 2; ++k) std::cout &lt;&lt; B[i][j][k] &lt;&lt; std::endl; </code></pre> <p>The whole experimental code can be checked at <a href="https://gist.github.com/Jimmy-Hu/b76591fb1ad9317f9a0548fe4d70ff1f" rel="nofollow noreferrer">here</a>.</p> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/251620/231235">A recursive_transform Template Function for BoostMultiArray</a> and</p> <p><a href="https://codereview.stackexchange.com/q/251379/231235">An Add/Minus Operator For Boost.MultiArray in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>The previous question <a href="https://codereview.stackexchange.com/q/251620/231235">A recursive_transform Template Function for BoostMultiArray</a> focused on <code>recursive_transform</code> template function and <a href="https://codereview.stackexchange.com/q/251379/231235">An Add/Minus Operator For Boost.MultiArray in C++</a> just mentioned that the <code>+</code> and <code>-</code> operator for Boost.MultiArray. I am trying to propose the <code>++</code> and <code>--</code> operator overloading implementation here.</p> </li> <li><p>Why a new review is being asked for?</p> <p>I am not sure if this is a good idea to call another function (such as the usage of <code>recursive_transform</code> template function here) in <code>++</code> and <code>--</code> operator. If there is any possible improvement, please let me know.</p> </li> </ul>
[]
[ { "body": "<p>This is wrong:</p>\n<pre><code>auto operator++(T&amp; input)\n{\n input = recursive_transform(input, [](auto&amp; x) {return x + 1; });\n</code></pre>\n<p>So the outer call to <code>operator++</code> causes recursion, but the recursive call uses <code>+ 1</code> instead of <code>++</code>. There might be types where these operations are not equivalent, where only one of the two operations is supported, and/or where one of them has very different performance. Make sure you use <code>operator++</code> on all levels of the recursion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T14:24:03.853", "Id": "495690", "Score": "0", "body": "Thank you for the answer. About the part of using `operator++` on all levels of the recursion, this means in both prefix increment operator and postfix increment operator?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T15:19:22.700", "Id": "495704", "Score": "1", "body": "Yes, the prefix version should `return ++x`, the postfix version `return x++`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T01:55:57.697", "Id": "495771", "Score": "0", "body": "Thank you for the reply. In the recursion process, there is something like `boost::detail::multi_array::const_sub_array` which can't apply `++` successfully. Is there any way to deal with this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T08:21:32.113", "Id": "495778", "Score": "1", "body": "Well if it's `const` you cannot modify it, so `++` and `--` operators can't be used on them. There is nothing you can do about that." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T10:03:08.983", "Id": "251700", "ParentId": "251684", "Score": "1" } } ]
{ "AcceptedAnswerId": "251700", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T01:50:04.397", "Id": "251684", "Score": "1", "Tags": [ "c++", "recursion", "lambda", "boost", "c++20" ], "Title": "An Element-wise Increment and Decrement Operator For Boost.MultiArray in C++" }
251684
<p>This time, one of my labs state that I need to write a complete java program which will calculate the square root of a number via Newton's method. The reason behind using Newton's method, as opposed to <code>Math.sqrt(x)</code> is so that I get to practice the use of simple IO, conditional expressions, loops, and nested loops.</p> <p><strong>The complete set of instructions are as follows:</strong></p> <p>Assume you want to compute the square root of <strong>x</strong>.</p> <p>First: We always start with a guess/approximation that the square root of any value for <strong>x</strong> is <strong>y = 1.0</strong></p> <p>Next we compute the average of this <strong>y value</strong> plus the <strong>x value</strong> divided by the <strong>y value</strong>.</p> <p><strong>This equation → ( y + (x/y) ) / 2.</strong></p> <p>The result from solving this equation then becomes the new approximation of the square root (the new <strong>y</strong> value). This new <strong>y</strong> value will be closer to the actual value for the square root of <strong>x</strong> than the original <strong>y</strong> guess of 1.0</p> <p><strong>Repeat</strong> the step above using each new computed value for <strong>y</strong> as the new guess for the square root of x until the y value is <strong>close enough</strong>.</p> <p>For example: suppose we want to compute the square root of 2 then the computation would proceed as follows (all values as double): <strong>x = 2.0</strong> and <strong>y = 1.0</strong></p> <pre><code>Iteration Guess Quotient Average Number for y x/y ( y + (x/y) ) / 2 1 1.0 2.0/1.0 =&gt; 2.0 (1.0 + 2.0/1.0)/2.0 =&gt; 1.5 2 1.5 2.0/1.5 =&gt; 1.33333 (1.5 + 1.33333)/2.0 =&gt; 1.41666 3 1.41666 2.0/1.41666 =&gt; 1.41176 (1.41666 + 1.41176)/2.0 =&gt; 1.41421 4 1.41421 etc... </code></pre> <p>The solution is achieved when the <strong>square of the guess</strong> is “same” as the value of x (the definition of square root). Unfortunately, for most numbers the exact solution can never be reached this way so the process continues forever. In order to ensure that the computation process actually stops we must change the stop condition of the loop to be “<strong>close enough</strong>”. Close enough is the <strong>tolerance</strong> (a small number) which we accept as being a good approximation of the exact value.</p> <p><strong>Close enough</strong> occurs when the <strong>absolute</strong> difference between x and (y*y) is less than the tolerance (defined by the user).</p> <p>In order to see how your program is progressing print out the iteration number and the guess value. Use at <strong>least 8 digits</strong> after the decimal value and <strong>2 before</strong> the decimal. In the example run shown below only 5 digits after the decimal are used.</p> <p><strong>Example Run:</strong></p> <pre><code>Square Root approximation program Enter the value : 2.0 Enter the tolerance : 0.00001 Iteration Guess Guess Absolute value Number value Squared Difference 1 1.00000 1.00000 1.00000 2 1.50000 2.25000 0.25000 3 1.41666 2.00693 0.00693 4 1.41421 1.99999 0.00001 Approximated Square root of 2.0 = 1.41422 </code></pre> <p><strong>The resulting code that I wrote to solve this problem is as follows:</strong></p> <pre><code>import java.util.Scanner; /** * SRN: 507-147-9 */ public class Lab8_1 { public static void main(String[] args) { // new input Scanner input = new Scanner(System.in); // define vars int iteration = 1; double x, y, guessSquared = 1, quotient, average, tolerance, absValDiff = 1; y = 1.0; // program name System.out.println(&quot;Square Root approximation program&quot;); System.out.println(); // prompt variables System.out.print(&quot;Enter the value : &quot;); // prompt x value x = input.nextDouble(); // store input as &quot;x&quot; System.out.print(&quot;Enter the tolerance : &quot;); // prompt tolerance tolerance = input.nextDouble(); // store input as &quot;tolerance&quot; System.out.println(); // print formatted header System.out.println(&quot;Iteration Guess Guess Absolute value&quot;); System.out.println(&quot;Number value Squared Difference&quot;); System.out.println(); // print first calculation System.out.printf(&quot;%9d %11.8f %11.8f %11.8f \n&quot;, iteration, y, guessSquared, absValDiff); // increment the value of &quot;iteration&quot; by 1 iteration++; while (absValDiff &gt; tolerance) { // looped calculations quotient = x / y; average = (y + quotient) / 2; y = average; guessSquared = y * y; absValDiff = Math.abs(x - guessSquared); // print results per iteration System.out.printf(&quot;%9d %11.8f %11.8f %11.8f \n&quot;, iteration, y, guessSquared, absValDiff); // increment the value of &quot;iteration&quot; by 1 iteration++; } // print results System.out.println(); System.out.printf(&quot;Approximated Square root of &quot; + x + &quot; = %11.8f \n&quot;, y); } } </code></pre> <p>With this, I do have a question regarding the accuracy of my responses as opposed to the ones in the example. Even though mathematically, the correct floating point numbers are stored in my variables, when the results are printed to the console, the last digit of my floating point is always rounded up. From my perspective, this feels similar to the round-off errors one would get on a calculator, where the result of the calculations performed are only approximate representations of the actual numbers, since only fixed point rational numbers can be represented exactly within the machine.</p> <p>An example of this kind of error would be: 2/3 = 0.666666667</p> <p>Is there a way that I could capture a set length for my variables using the <code>printf</code> format without allowing the number to be round up when it is printed to the console?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T12:56:45.727", "Id": "495683", "Score": "0", "body": "Regarding the round up vs. round down question: surely `printf()` rounds to the closest number, up or down. And `2/3 = 0.666666667` is in fact a better approximation for the infinite digits series of `0.666666...` than `2/3 = 0.666666666`. So, it's not an error, but the best possibility, and I wouldn't change that behaviour." } ]
[ { "body": "<blockquote>\n<p>Is there a way that I could capture a set length for my variables\nusing the printf format without allowing the number to be round up\nwhen it is printed to the console?</p>\n</blockquote>\n<p>You can use a &quot;trick&quot;</p>\n<pre><code>String output = String.format(&quot;%12.9f&quot;, doubleValue);\nSystem.out.println(output.substring(0, output.length() - 1);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:00:59.557", "Id": "495718", "Score": "1", "body": "Note that this fails if the number ends .9999999995 -- because this rounds first (which would make that number 1.0000000000) and then removes the last digit. Using `DecimalFormat` with `RoundingMode.DOWN` avoids that caveat." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T12:46:58.930", "Id": "251705", "ParentId": "251685", "Score": "7" } }, { "body": "<p>Your program looks pretty good so far. Here are some things I noticed:</p>\n<ul>\n<li><p>There's a logical error for your first iteration when you calculate <code>absValDiff</code>. You always initialise <code>absValDiff</code> to 1 and don't recalculate it for the first iteration, so if you put in a value such as x = 5, it will say the difference between your first guess (y = 1) squared and x is only 1, when in fact it should be 4.</p>\n</li>\n<li><p>As a result of the above, this also means that asking for any tolerance greater than or equal to 1 doesn't work correctly, and the program ends immediately. Asking for a tolerance of 2 for example doesn't work correctly.</p>\n</li>\n<li><p>You might be able to write your comments to be more useful to other readers. Unless you've been told otherwise on your course, you can assume that the person reading your code understands what the language does, and is more interested in why your code is taking the steps that it does. For example:</p>\n<pre class=\"lang-java prettyprint-override\"><code>// define vars\nint iteration = 1;\ndouble x, y, guessSquared = 1, quotient, average, tolerance, absValDiff = 1;\n</code></pre>\n<p>It's clear that you're defining variables here, so you could try explaining what you're doing instead. Why not try telling the reader what the variables are for?</p>\n</li>\n<li><p>It's usually easier to declare your variables as you need them, rather than all at the top of the method. For a further reference, see the section on Declarations <a href=\"https://perso.ensta-paris.fr/%7Ediam/java/online/notes-java/principles_and_practices/style/style-practices.html#declarations\" rel=\"noreferrer\">here</a>. As mentioned in that source, while it was tradition in older programming languages to declare all your variables upfront, it's generally not considered best practice to do that now.</p>\n</li>\n</ul>\n<p>Changing all of this, your code might look something more like so:</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.Scanner;\n\n/**\n * SRN: 507-147-9\n */\npublic class Lab8_1 {\n\n public static void main(String[] args) {\n Scanner input = new Scanner(System.in);\n\n int iteration = 1; // Counts the current iteration number at each step.\n double y = 1.0; // Initial guess for the square root of the number x.\n double guessSquared = y * y; // The value y^2 which we want to be close to x.\n\n System.out.println(&quot;Square Root approximation program&quot;);\n System.out.println();\n\n System.out.print(&quot;Enter the value : &quot;);\n // The number we intend to approximate the square root of.\n double x = input.nextDouble(); \n System.out.print(&quot;Enter the tolerance : &quot;);\n // The tolerance so that we terminate if |y^2 - x| &lt; tolerance.\n double tolerance = input.nextDouble();\n System.out.println();\n \n // Compute the initial difference between x and the square of\n // the approximate square root.\n double absValDiff = Math.abs(x - guessSquared);\n\n // Print formatted header.\n System.out.println(&quot;Iteration Guess Guess Absolute value&quot;);\n System.out.println(&quot;Number value Squared Difference&quot;);\n System.out.println();\n\n // Print the results for the first iterate\n System.out.printf(&quot;%9d %11.8f %11.8f %11.8f \\n&quot;, iteration, y, guessSquared, absValDiff);\n iteration++;\n\n // Iterate using Newton's method until we obtain a value within tolerance of\n // the true square root.\n while (absValDiff &gt; tolerance) {\n // Calculate the new approximation for x using \n // Newton's method, where given the previous approximation y,\n // the next approximation is given by (y + (x / y)) / 2.\n double quotient = x / y;\n y = (y + quotient) / 2;\n guessSquared = y * y;\n // Compute the new difference between the square of our approximation and x.\n absValDiff = Math.abs(x - guessSquared);\n\n // Print results per iteration.\n System.out.printf(&quot;%9d %11.8f %11.8f %11.8f \\n&quot;, iteration, y, guessSquared, absValDiff);\n iteration++;\n }\n // Print results for the final iteration which was in tolerance.\n System.out.println();\n System.out.printf(&quot;Approximated Square root of &quot; + x + &quot; = %11.8f \\n&quot;, y);\n }\n}\n</code></pre>\n<p>In order to avoid the rounding (and instead <em>truncate</em> the number), you could use <a href=\"https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html\" rel=\"noreferrer\">DecimalFormat</a>, as explained <a href=\"https://stackoverflow.com/questions/10332546/truncate-a-float-and-a-double-in-java\">here</a> if you wanted an alternative approach to Gilbert Le Blanc's method. After importing <code>java.text.DecimalFormat</code> and <code>java.math.RoundingMode</code>, you can use it as follows:</p>\n<pre class=\"lang-java prettyprint-override\"><code>DecimalFormat df = new DecimalFormat(&quot;#.##&quot;);\ndf.setRoundingMode(RoundingMode.DOWN);\nSystem.out.println(df.format(0.66999f));\n</code></pre>\n<p>which would output <code>0.66</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T15:01:31.200", "Id": "251707", "ParentId": "251685", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T03:24:20.023", "Id": "251685", "Score": "8", "Tags": [ "java", "beginner", "mathematics" ], "Title": "Square roots via Newton's method in Java" }
251685
<p>There is a problem on <a href="https://exercism.io" rel="noreferrer">Exercism</a> Java track that requires writing a function to flatten an arbitrarily nested list to a flattened list without null values. For Example<br /> input: [1,[2,3,null,4],[null],5]<br /> output: [1,2,3,4,5]</p> <p>Here is the solution I wrote for it without using wildcards.</p> <pre><code>public List flatten(List&lt;Object&gt; two) { Function&lt;Object, List&gt; mapper = item -&gt; (item instanceof List) ? flatten((List) item) : Collections.singletonList(item); return (List) two.stream() .filter(x -&gt; x != null) .map(mapper) .flatMap(x -&gt; x.stream()) .collect(Collectors.toList()); } </code></pre> <p>Here is my solution with the wildcard generics. My IDE was happier with this solution.</p> <pre><code>public List&lt;Object&gt; flatten(List&lt;?&gt; two) { Function&lt;Object, List&lt;?&gt;&gt; mapper = item -&gt; (item instanceof List) ? flatten((List&lt;?&gt;) item) : Collections.singletonList(item); return two.stream() .filter(Objects::nonNull) .map(mapper) .flatMap(List::stream) .collect(Collectors.toList()); } </code></pre> <p>Is it ok to use the wildcard in this case? Which solution would you prefer? Any other comments about the code are also welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T11:54:38.773", "Id": "495678", "Score": "4", "body": "While Torben and Marc did some good effort in answering your question, I'd rather like to challenge the exercise itself: as often, this is somthing without any practical relevance that someone found mildly interesting. In reality, we've had generics for 16 years now, and you *do not mix collections* today. If you really have old legacy code that still does, refactor this code. Do not try to find \"elegant\" solutions for this kind of impractical crap." } ]
[ { "body": "<p><strong>The question</strong></p>\n<p>Your IDE complains about the first one because you're mixing raw types and parameterized types. By changing the raw types to <code>List&lt;Object&gt;</code> your IDE will be <em>a bit</em> happier. However, the second example, with the unknown type, is the correct one to use. It lets you call the method with any list type, such as <code>List&lt;List&lt;String&gt;&gt;</code>, not just <code>List&lt;Object&gt;</code>. Also you use the method reference operator <code>::</code> instead of lambdas (the operator was added for this exact purpose so it should be used here).</p>\n<p><strong>Plain old review</strong></p>\n<ul>\n<li>Method name should tell the caller it does recursive flattening.</li>\n<li>Did the exercise specify only lists to be flattened instead of all collections? If former, call it <code>flattenListsRecursively</code>.</li>\n<li>Parameter name <code>two</code> is confusing.</li>\n<li>Variable name <code>mapper</code> is a bit generic. Use <code>mapToList</code> or similar instead.</li>\n<li>There is no limit in the recursion.</li>\n</ul>\n<p>The last one may be a bit controversial, but my opinion is that if you intend to do a recursive algorithm for generic use you should provide the caller with tools to prevent it from running out of control instead of just relying on an eventual <code>StackOverflowError</code>.</p>\n<p><strong>Performance</strong></p>\n<p>The stream API requires you to do an awful lot of throwaway singleton list creation. A good old loop with recursion would be much more effective in this case. It may even be a bit more readable as the recursive call is not buried down into a fairly long one line lambda. Remember, streams are like a hammer. It's a handy tool sometimes but hardly the right tool every time.</p>\n<pre><code>public static List&lt;Object&gt; flattenListsRecursively(List&lt;?&gt; input) {\n final List&lt;Object&gt; result = new ArrayList&lt;&gt;();\n flattenListRecursively(input, result);\n return result;\n}\n\nprivate static void flattenListsRecursively(List&lt;?&gt; input, List&lt;Object&gt; result) {\n for (Object o: input) {\n if (o instanceof List) {\n flattenListRecursively((List&lt;?&gt;) o, result);\n } else if (o != null) {\n result.add(o);\n }\n }\n}\n</code></pre>\n<p>If you made the latter public, you could let the caller use the <code>result</code> list as a way to control the execution by, for example, passing a size limited list. But this doesn't solve the stack overflow problem I mentioned earlier as a list of lists that contains itself just goes into a runaway recursion without necessarily affecting the output size.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T13:05:13.253", "Id": "495919", "Score": "0", "body": "I am choosing this answer as I found this most helpful towards the problem I asked. Thanks for other comments and answers too everyone." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T07:22:50.733", "Id": "251692", "ParentId": "251687", "Score": "3" } }, { "body": "<p>@TorbenPutkonen already provided a great review, I just wanted to add something about usability.</p>\n<p>Depending on your use case, returning a <code>List&lt;Object&gt;</code> means that you need to do the casting later. For example:</p>\n<pre class=\"lang-java prettyprint-override\"><code>List&lt;Object&gt; result = flatten(myList);\nfor(Object o : result) {\n if(o instanceof String) {\n String myString = (String) o;\n // do something with the string\n }\n // etc...\n}\n</code></pre>\n<p>If you know the type of the elements you can pass it to the method:</p>\n<pre class=\"lang-java prettyprint-override\"><code>@SuppressWarnings(&quot;unchecked&quot;)\npublic &lt;T&gt; List&lt;T&gt; flatten(List&lt;?&gt; list, Class&lt;T&gt; itemType) {\n return list.stream()\n .filter(Objects::nonNull)\n .flatMap(i -&gt; i instanceof List ? flatten((List&lt;?&gt;)i, itemType).stream() : Stream.of((T)i))\n .collect(Collectors.toList());\n}\n</code></pre>\n<p>And then use it like:</p>\n<pre class=\"lang-java prettyprint-override\"><code>List&lt;String&gt; result = flatten(myList, String.class);\nfor(String s : result) {\n // do something with the string\n}\n</code></pre>\n<p>This is the version without streams:</p>\n<pre><code>@SuppressWarnings(&quot;unchecked&quot;)\npublic static &lt;T&gt; List&lt;T&gt; flatten(List&lt;?&gt; list, Class&lt;T&gt; itemType) {\n List&lt;T&gt; result = new ArrayList&lt;&gt;();\n for(Object o : list) {\n if(o instanceof List) {\n result.addAll(flatten((List&lt;?&gt;) o, itemType));\n }\n else if (o != null){\n result.add((T) o);\n }\n }\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T13:36:12.117", "Id": "495685", "Score": "0", "body": "You should have insist in your usage of `Stream.of(i)` in your answer before the code. The first answer mentionned the creation of lot intermediary list and propose immediately to switch to the old for insteand of this, which is using the Stream API more properly instead of throwing it altogether as if it wasn't good enough" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T15:06:30.750", "Id": "495701", "Score": "0", "body": "@Walfrat It's a better use but arguably the best time to use Stream here, that's why I haven't insisted. Honestly, I would be happier to read and debug the version without Stream." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T15:13:17.557", "Id": "495703", "Score": "0", "body": "I know that's why i said \"good enough\" and not the \"best\"." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T08:38:41.823", "Id": "251697", "ParentId": "251687", "Score": "5" } } ]
{ "AcceptedAnswerId": "251692", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T03:57:23.740", "Id": "251687", "Score": "5", "Tags": [ "java", "programming-challenge", "generics" ], "Title": "Java generics with wildcard vs non generic List to deal with non generic data" }
251687
<p>I'm trying to implement a Doubly Linked List data structure in C++. Please give me suggestions on how this code can be improved. Try to remain in C++11 because that's what I know atm.</p> <pre><code>#ifndef DOUBLY_LINKED_LIST_HPP #define DOUBLY_LINKED_LIST_HPP #include &lt;iostream&gt; template &lt;typename T&gt; class DoublyLinkedList { template &lt;typename T&gt; struct Node { T val; Node&lt;T&gt;* next; Node&lt;T&gt;* prev; }; public: DoublyLinkedList() : len(0), head(nullptr), tail(nullptr) { } DoublyLinkedList(const DoublyLinkedList&amp; rhs) : DoublyLinkedList() { Node&lt;T&gt;* currNode = rhs.head; while (currNode) { this-&gt;PushBack(currNode-&gt;val); currNode = currNode-&gt;next; } } DoublyLinkedList(DoublyLinkedList&amp;&amp; rhs) : head(rhs.head), tail(rhs.tail), len(rhs.len) { rhs.head = rhs.tail = nullptr; } DoublyLinkedList&amp; operator=(DoublyLinkedList rhs) { swap(*this, rhs); return *this; } ~DoublyLinkedList() { this-&gt;Clear(); } const T&amp; GetFront() const { return head-&gt;val; } const T&amp; GetBack() const { return tail-&gt;val; } size_t GetLength() const { return len; } void PushFront(const T&amp; val) { Node&lt;T&gt;* newNode = new Node&lt;T&gt;{ val, head, nullptr }; if (tail == nullptr) { tail = newNode; } else { head-&gt;prev = newNode; } head = newNode; ++len; } void PushBack(const T&amp; val) { Node&lt;T&gt;* newNode = new Node&lt;T&gt;{ val, nullptr, tail }; if (head == nullptr /*&amp;&amp; tail == nullptr*/) { head = newNode; } else { tail-&gt;next = newNode; } tail = newNode; ++len; } void InsertAt(size_t idx, const T&amp; val) { Node&lt;T&gt;* currNode = head; while (idx--) { currNode = currNode-&gt;next; } if (currNode == tail || currNode == nullptr) { this-&gt;PushBack(val); } else if (currNode == head) { this-&gt;PushFront(val); } else { Node&lt;T&gt;* newNode = new Node&lt;T&gt;{ val, currNode, currNode-&gt;prev }; currNode-&gt;prev-&gt;next = newNode; currNode-&gt;prev = newNode; } } T PopFront() { T val = std::move(head-&gt;val); Node&lt;T&gt;* newHead = head-&gt;next; delete head; if (newHead) { newHead-&gt;prev = nullptr; } else { tail = nullptr; } head = newHead; --len; return val; } T PopBack() { T val = std::move(tail-&gt;val); Node&lt;T&gt;* newTail = tail-&gt;prev; delete tail; if (newTail) { newTail-&gt;next = nullptr; } else { head = nullptr; } tail = newTail; --len; return val; } T RemoveAt(size_t idx) { Node&lt;T&gt;* currNode = head; while (idx--) { currNode = currNode-&gt;next; } if (currNode == tail || currNode == nullptr) { return this-&gt;PopBack(); } else if (currNode == head) { return this-&gt;PopFront(); } else { T val = std::move(currNode-&gt;val); currNode-&gt;prev-&gt;next = currNode-&gt;next; currNode-&gt;next-&gt;prev = currNode-&gt;prev; delete currNode; return val; } } void Clear() { Node&lt;T&gt;* currNode = head; while (currNode) { Node&lt;T&gt;* nextNode = currNode-&gt;next; delete currNode; currNode = nextNode; } this-&gt;head = this-&gt;tail = nullptr; this-&gt;len = 0; } friend std::ostream&amp; operator&lt;&lt; (std::ostream&amp; out, const DoublyLinkedList&lt;T&gt;&amp; list) { out &lt;&lt; &quot;DoublyLinkedList{&quot;; Node&lt;T&gt;* currNode = list.head; while (currNode) { std::cout &lt;&lt; currNode-&gt;val; if (currNode-&gt;next) std::cout &lt;&lt; &quot;, &quot;; currNode = currNode-&gt;next; } out &lt;&lt; &quot;}&quot;; return out; } friend void swap(DoublyLinkedList&lt;T&gt;&amp; lhs, DoublyLinkedList&lt;T&gt;&amp; rhs) { std::swap(lhs.head, rhs.head); std::swap(lhs.tail, rhs.tail); std::swap(lhs.len, rhs.len); return; } private: Node&lt;T&gt;* head; Node&lt;T&gt;* tail; size_t len; }; #endif <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T08:54:41.713", "Id": "495781", "Score": "0", "body": "Side note, why do you limit to C++11?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T03:49:24.290", "Id": "496051", "Score": "0", "body": "@Aryan Parekh \"Because that's what I know atm\"" } ]
[ { "body": "<ol>\n<li><p>The <code>InsertAt()</code> and <code>RemoveAt()</code> operations are quite expensive\nwhen implemented to accept a position. These operations are\nusually implemented using <a href=\"http://www.cplusplus.com/reference/iterator/\" rel=\"nofollow noreferrer\">iterators</a>, which are wrappers around\nthe internal node structure.</p>\n</li>\n<li><p>Making the stream output operator part of the class is rather inflexible. You should define a standalone non-friend function to help you dump your list. To do that non-friendliness, however, you need access to the internal node structure. But this problem fades away if you implement the iterators.</p>\n</li>\n<li><p>Generally, you might want to comply with the concept of the standard containers. Use the same method names (ie. <code>size()</code>, <code>push_back()</code>), etc.</p>\n</li>\n<li><p>Also, I'm not sure but maybe a standard <code>std::swap</code> is going to be enough and actually more efficient. Definitely, the return on the end of <code>void</code> function is useless.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T07:27:51.147", "Id": "251693", "ParentId": "251689", "Score": "2" } }, { "body": "<h1>Wrap your class in a namespace</h1>\n<p>Just like the STL has its containers in the <code>std::</code> namespace, it's a good practice to wrap your containers in your personal namespace too. That way you group related classes and functions together.</p>\n<hr />\n<h1><strike><code>Node&lt;T&gt;</code></strike> <code>Node</code></h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>template &lt;typename T&gt;\nclass DoublyLinkedList \n</code></pre>\n<pre class=\"lang-cpp prettyprint-override\"><code> template &lt;typename T&gt;\n struct Node {\n T val;\n Node&lt;T&gt;* next;\n Node&lt;T&gt;* prev;\n };\n</code></pre>\n<p>There is a problem here, you don't need to write out another template for <code>Node</code> since it uses the same type that <code>DoublyLinkedList</code> uses. Due to this, you had to write <code>Node &lt; T &gt;</code> everywhere, except if <code>Node</code> didn't have its template, you could do <code>Node</code> alone</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template &lt; typename T &gt;\nclass DoublyLinkedList\n{\n struct Node {\n T val;\n Node* next; // don't require Node &lt; T &gt;*\n Node* prev;\n };\n</code></pre>\n<p>This replaces every <code>Node &lt; T &gt; </code> with <code>Node</code> in your program</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> Node&lt;T&gt;* newNode = new Node&lt;T&gt;{ val, head, nullptr };\n Node* newNode = new Node{val, head, nullptr};\n</code></pre>\n<hr />\n<h1>Unnecessary <code>this-&gt;</code></h1>\n<pre class=\"lang-cpp prettyprint-override\"><code> ~DoublyLinkedList()\n {\n this-&gt;Clear();\n }\n</code></pre>\n<p><code>this-&gt;</code> is completely unnecessary here, you don't have to use it everywhere unless you have a good reason.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> ~DoublyLinkedList()\n {\n Clear();\n }\n</code></pre>\n<hr />\n<h1>Use an <a href=\"https://www.learncpp.com/cpp-tutorial/15-2-rvalue-references/\" rel=\"nofollow noreferrer\">rvalue reference</a></h1>\n<p>An lvalue reference in your program already avoids a copy, with an rvalue reference you can make it even more efficient because we know that it's a temporary object, hence we can use <code>std::move</code> and treat an rvalue reference differently</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> void PushFront(T const&amp; val) // this remains the same\n {\n Node* newNode = new Node{ val, head, nullptr };\n\n if (tail == nullptr) {\n tail = newNode;\n }\n else {\n head-&gt;prev = newNode;\n }\n\n head = newNode;\n ++len;\n }\n\n void PushFront(T&amp;&amp; val) // overload for an rvalue reference\n {\n Node* newNode = new Node{ std::move(val), head, nullptr };\n\n if (tail == nullptr) {\n tail = newNode;\n }\n else {\n head-&gt;prev = newNode;\n }\n\n head = newNode;\n ++len;\n }\n</code></pre>\n<hr />\n<h1>Constructor with <a href=\"https://en.cppreference.com/w/cpp/utility/initializer_list\" rel=\"nofollow noreferrer\"><code>std::initializer_list</code></a></h1>\n<p><sup>Defined in header <code>&lt;initializer_list&gt;</code></sup></p>\n<p>A constructor with this will make initializing your list much easier. Once you add a constructor that supports an initializer_list, you can create a list in the following manner</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>DoublyLinkedList &lt; int &gt; l { 1, 2, 3, 4, 5}; // \n\nDoublyLinkedList &lt; int &gt; l2;\n\nl2.PushBack(1);\nl2.PushBack(2);\nl2.PushBack(3);\nl2.PushBack(4);\nl2.PushBack(5); // \n</code></pre>\n<pre class=\"lang-cpp prettyprint-override\"><code>DoublyLinkedList( std::initializer_list &lt; T &gt; const&amp; init); // iterate and add elements\n</code></pre>\n<hr />\n<h1><code>PopBack()</code> on an empty list</h1>\n<p>Your pop functions don't handle this exception at all, the best thing to do is use <code>assert</code> to deal with this, if you look at the implementation of <code>pop_back()</code> in <code>std::list</code>, it does the same</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> void pop_back() noexcept {\n#if _CONTAINER_DEBUG_LEVEL &gt; 0\n _STL_VERIFY(_Mypair._Myval2._Mysize != 0, &quot;pop_back called on empty list&quot;);\n#endif \n\n _Unchecked_erase(_Mypair._Myval2._Myhead-&gt;_Prev);\n }\n</code></pre>\n<hr />\n<h1>Extending your class</h1>\n<p>A few things which you can add</p>\n<ul>\n<li><code>empty()</code> returns whether the list is empty</li>\n<li>overload of the equality operator <code>==</code> to check if two lists are equal</li>\n<li>merge two lists</li>\n</ul>\n<hr />\n<h1>Naming conventions</h1>\n<p>Consider matching the function names in the STL</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>PopBack() -&gt; pop_back()\nPushBack() -&gt; push_back()\nGetLength() -&gt; size()\n</code></pre>\n<p>I also suggest you take change <code>DoublyLinkedList</code> to something like <code>List</code> because the declaration gets really strange</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>DoublyLinkedList &lt; DoublyLinkedList &lt; int &gt; &gt; my_list;\n</code></pre>\n<p>I again recommend you wrap everything in your own namespace, that way you don't have to afraid of collisions</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T01:42:29.827", "Id": "495871", "Score": "0", "body": "As an aside: \"*[What's the difference between “STL” and “C++ Standard Library”?](//stackoverflow.com/questions/5205491/whats-the-difference-between-stl-and-c-standard-library)*\"" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T09:19:55.333", "Id": "251699", "ParentId": "251689", "Score": "5" } } ]
{ "AcceptedAnswerId": "251699", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T05:31:51.740", "Id": "251689", "Score": "6", "Tags": [ "c++", "c++11", "linked-list", "reinventing-the-wheel", "template" ], "Title": "Doubly Linked List Data Structure ADT in C++" }
251689
<p>I like to compute dummy variables based on the existing values in a dataframe and a dictionary with certain &quot;cut off&quot; points. I wonder whether I need to get rid of the for loop in the example below. And if so, how?</p> <p>The second answer in <a href="https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas">this</a> Stackoverflow post compellingly urges to avoid looping through dataframes. In my real dataset (about 20.000 rows and 50 columns/variables) the &quot;apply lambda&quot; for the rows indeed performs much better than a for loop (which after a few hours still wasn't finished). Yet, the for loop for the columns doesn't really give a problem with time and it is handy to automatically name the variables.</p> <p>Here is an example dataset</p> <pre><code>import pandas as pd # create df dict={'file':['a', 'b', 'c'],'t_0':[1.5, 2.5, 3.5], 't_1':[0.5, 1.5, 0]} df=pd.DataFrame(dict,index=['0', '1', '3']) print(df) # create dictionary with cut off points for dummy variable d = dict={'t_0_cut_off':1, 't_1_cut_off':2} print(d) </code></pre> <p>And here the for loop and apply lambda function which I use to compute the dummy variables.</p> <pre><code>for column in df.columns[-2:]: df[f'{column}_result']=df[f'{column}'].apply(lambda x: 1 if x&gt; d[f'{column}_cut_off'] else 0) df </code></pre> <p>The results look like this (and appear as I expect)</p> <pre><code> file t_0 t_1 t_0_result t_1_result 0 a 1.5 0.5 1 0 1 b 2.5 1.5 1 0 3 c 3.5 0.0 1 0 </code></pre>
[]
[ { "body": "<p><code>df.apply</code> is essentially a loop and can be slower than vectorized methods. Here is a proposal without using <code>apply</code>:</p>\n<p>First, we can rename the keys in the dictionary to match the column names in the dataframe:</p>\n<pre><code>d1 = {k.rsplit('_',2)[0]: v for k, v in d.items()}\n#{'t_0': 1, 't_1': 2}\n</code></pre>\n<p>Next step is make a subset of your dataframe, since you are interested in second and subsequent columns; for this, use <strong><a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html\" rel=\"nofollow noreferrer\"><code>df.iloc</code></a></strong>. Then, using <strong><a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html\" rel=\"nofollow noreferrer\"><code>df.assign</code></a></strong>, we can assign the values from the dictionary in the columns we are interested in and compare them with the original values using <strong><a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.gt.html\" rel=\"nofollow noreferrer\"><code>df.gt</code></a></strong>, then convert the boolean value to <code>int</code> using <strong><a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.astype.html\" rel=\"nofollow noreferrer\"><code>df.astype</code></a></strong> . Finally, we can <strong><a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html\" rel=\"nofollow noreferrer\"><code>df.join</code></a></strong> it back to the original dataframe and use <code>rsuffix</code> argument to rename the columns to add <code>&quot;_result&quot;</code></p>\n<pre><code>sub_df = df.iloc[:,1:] #subsets the dataframe leaving the first column out\nout = df.join(sub_df.gt(sub_df.assign(**d1)).astype(int) , rsuffix='_result')\n</code></pre>\n<hr />\n<p>Final code looks like:</p>\n<pre><code>d1 = {k.rsplit('_',2)[0]: v for k, v in d.items()}\nsub_df = df.iloc[:,1:]\nout = df.join(sub_df.gt(sub_df.assign(**d1)).astype(int) , rsuffix='_result')\nprint(out)\n\n file t_0 t_1 t_0_result t_1_result\n0 a 1.5 0.5 1 0\n1 b 2.5 1.5 1 0\n3 c 3.5 0.0 1 0\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T08:47:50.617", "Id": "495660", "Score": "0", "body": "\"df.apply is essentially a loop and can be slower than vectorized methods,\" great, this was indeed the sort of answer I was looking for. So the solution proposed by @anky is a \"vectorized methods\" approach? Later I will also compare the time it takes to run both codes on my actual data." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T08:53:37.197", "Id": "495661", "Score": "0", "body": "Indeed it is, please let me know how it goes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T08:55:54.847", "Id": "495662", "Score": "1", "body": "Alright, thanks for your solution then, Anky! You opened the door for me to the vectorized approach :) (I will report the run time later)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T07:20:30.260", "Id": "251691", "ParentId": "251690", "Score": "2" } }, { "body": "<p>The concept of <strong>broadcasting</strong> is very important for vectorized computation in both <a href=\"https://numpy.org/doc/stable/user/theory.broadcasting.html#array-broadcasting-in-numpy\" rel=\"nofollow noreferrer\">numpy</a> and <a href=\"https://pandas.pydata.org/pandas-docs/stable/user_guide/basics.html#matching-broadcasting-behavior\" rel=\"nofollow noreferrer\">pandas</a>, in which a lower-dimentional array can be viewed as a higher-dimentional one for computation.</p>\n<p>A direct improvement of your <code>apply</code> method is based on broadcasting of scalar values:</p>\n<pre><code>for column in df.columns[-2:]:\n df[f'{column}_result'] = (df[f'{column}'] &gt; d[f'{column}_cut_off']).astype(int)\n</code></pre>\n<p>Instead of comparing row by row in Python, all comparisons are performed at once.</p>\n<p>The solution can be further improved using broadcasting of 1D arrays:</p>\n<pre><code>col_names = [k.rstrip(&quot;_cut_off&quot;) for k in d.keys()]\ndf[list(d.keys())] = df[col_names].gt(list(d.values())).astype(int)\n</code></pre>\n<p>Side Remarks:</p>\n<ol>\n<li><code>dict</code> is a built-in class in Python and should not be used as user variable names.</li>\n<li>The SO post you refer to provides several links related to the performance topic, such as <a href=\"https://stackoverflow.com/questions/54028199/are-for-loops-in-pandas-really-bad-when-should-i-care/54028200#54028200\">this one</a>. You may want to read more of those.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T08:21:33.277", "Id": "251750", "ParentId": "251690", "Score": "2" } } ]
{ "AcceptedAnswerId": "251691", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T06:46:40.183", "Id": "251690", "Score": "3", "Tags": [ "python", "pandas", "lambda" ], "Title": "Create dummy variables in dataframe using for loop and apply lambda" }
251690
<p>I'm new to javascript and trying to figure out what improvements I can make to my code.</p> <p>In this code I retrieve values ​​from an iODBC database then I format and push in SQL database. I am making arrays to get all my values that I am processing, however I think the best way would be to do it in object. I don't know if this is useful or too heavy?</p> <pre><code>function refreshPrice(){ cron.schedule('* 20 * * *', () =&gt; { console.log(&quot;refresh prix CLIP&quot;); var articlesClip = null; var codeGPAO = [], priceGPAO = [], pmpGPAO = [], dateGPAO = []; // Set de la query + exec pour récuperer les infos dans la BDD CLIP var command = 'echo &quot;SELECT COARTI,PRIXART,PMP,DAT FROM ARTICLEM&quot; | iodbctest &quot;DSN=DSNServ&quot;'; var exec = require('child_process').exec; var child = exec(command, {maxBuffer: 10000 * 1024}, function (error, stdout, stderr) { var articlesClip = stdout.toString(&quot;utf8&quot;).split('\n'); for (var i = 0; i &lt; 8; i++){ articlesClip.shift(); } for (var i = 0; i &lt; 7; i++){ articlesClip.pop(); } console.log(articlesClip) for (var articleID in articlesClip) { articlesClip[articleID] = stdoutConvert(articlesClip[articleID]); var str = articlesClip[articleID]; var tab = pipSplit(str); codeGPAO.push(tab[0].trim()); priceGPAO.push(tab[1].trim()); pmpGPAO.push(tab[2].trim()); dateGPAO.push(dateFormatFR(tab[3])); } for (var i = 0; i &lt; codeGPAO.length; i++){ var query = &quot;UPDATE COMPOSANTS SET \ PRIX_CLIP=&quot; + mysql.escape(priceGPAO[i]) + &quot;, \ PRIX_PMP=&quot; + mysql.escape(pmpGPAO[i]) + &quot;, \ DATE=&quot; + mysql.escape(dateGPAO[i]) + &quot;&quot; query += &quot; WHERE GPAO=&quot; + mysql.escape(codeGPAO[i]) console.log(query); connection.query(query, function (error, results, fields) { if (error) throw error; }); } console.log(&quot;FINISH&quot;); }); },{ scheduled: true, timezone: &quot;Europe/Paris&quot; }); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T07:35:10.127", "Id": "495650", "Score": "3", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T19:03:24.150", "Id": "495747", "Score": "0", "body": "Please edit your question and explain the code thoroughly" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T12:35:22.857", "Id": "495998", "Score": "0", "body": "Hello, no idea to edit my title, any idea ?" } ]
[ { "body": "<p>When you have multiple standalone variables that hold strongly related data, often it's a good idea to coalesce those variables into a single variable that holds the entire collection, which permits more dynamic and <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> manipulation of the data. Here, your <code>codeGPAO</code>, <code>priceGPAO</code> and similar variables fall exactly into this category; you're right, putting each parsed line into an object instead of 4 standalone variables would make a lot more sense.</p>\n<p>For example, you could do:</p>\n<pre><code>const GPAOs = [];\nfor (var articleID in articlesClip) {\n // ...\n GPAOs.push({\n code: tab[0].trim(),\n price: tab[1].trim(),\n pmp: tab[2].trim(),\n date: dateFormatFR(tab[3]),\n });\n}\n</code></pre>\n<p>That data structure would make a lot more sense.</p>\n<blockquote>\n<p>I don't know if this is too heavy?</p>\n</blockquote>\n<p>Not at all. It'll have the same computational complexity and the same basic operations. Except in ultra-performance-critical code (which is exceedingly rare to run into in real-world JavaScript), the performance difference between using an object and standalone variables is completely insignificant. And since it'll make the code more comprehensible to readers, it's definitely worth it.</p>\n<p>That said, there's an even better option available to you - why store the results at all? I think it'd make more sense to send off the database query immediately once the string has been parsed - that way, there's no need for any of the <code>GPAO</code> variables at all. For example:</p>\n<pre><code>for (var articleID in articlesClip) {\n // ...\n updateDatabase({\n code: tab[0].trim(),\n price: tab[1].trim(),\n pmp: tab[2].trim(),\n date: dateFormatFR(tab[3]),\n });\n}\n</code></pre>\n<p>There are many other improvements that can be made to the code as well.</p>\n<p><strong>Use modern syntax</strong> Since this is running in Node, and you're using arrow functions already, there shouldn't be any compatibility problems with using modern syntax everywhere. Most importantly - use <code>const</code> (or <code>let</code> when you need to reassign), not <code>var</code>. <code>var</code> has unintuitive function-scoping rules and a few other odd behaviors, and <code>const</code> makes code more readable when it's clear at a glance when a variable won't be reassigned, so it's a good idea to use <code>const</code> wherever possible. Consider using the ESLint rules <a href=\"https://eslint.org/docs/rules/no-var\" rel=\"nofollow noreferrer\"><code>no-var</code></a> and <a href=\"https://eslint.org/docs/rules/prefer-const\" rel=\"nofollow noreferrer\"><code>prefer-const</code></a>.</p>\n<p><strong>Only declare variables right before you need to use them</strong> It's good for variables to exist in <a href=\"https://softwareengineering.stackexchange.com/a/388055\">as narrow a scope as possible</a>. This improves readability because it means that when reading an outer block, you don't need to read over and cognitively parse variable declarations that are only used inside an inner block. You can remove the <code>var articlesClip = null;</code> completely, and only declare it once the stdout has been parsed with <code>stdout.toString(&quot;utf8&quot;).split('\\n');</code>.</p>\n<p><strong>Don't ignore errors</strong> With your current implementation, if the <code>exec</code> call doesn't succeed, you will not know what the error was - you don't even check it - and then you proceed to try to parse the stdout anyway. Instead, check to see if there's an error <em>first</em> - if there is one, log it (somewhere that you can find it easily when reading server logs) and return. Otherwise, proceed with parsing.</p>\n<p><strong>Concisely taking a slice of an array</strong> Rather than looping 8 and 7 times, <code>.pop</code> and <code>.unshift</code>ing items from the array, consider using <code>.slice</code> instead, which allows you to grab a section of an array between two indicies. Change the <code>for</code> loops to:</p>\n<pre><code>.slice(8, articlesClip.length - 7)\n</code></pre>\n<p><strong>If you only care about the values of an array, avoid <code>for..in</code></strong> - <code>for..in</code> lets you iterate over the <em>indicies</em> of an array, but when you don't care about the indicies, only the values, better to iterate over the <em>values themselves</em>, which can be done with <code>for..of</code> or <code>forEach</code>. You can change</p>\n<pre><code>for (var articleID in articlesClip) {\n</code></pre>\n<p>to</p>\n<pre><code>for (const articleStr of articlesClip) {\n</code></pre>\n<p>Or - since you want to know when <em>all</em> queries are done, use <code>Array#map</code> instead, to map each <code>articleStr</code> to a database query Promise that you can pass into <code>Promise.all</code>.</p>\n<p><strong>Don't concatenate input when performing database queries</strong> It's not only inelegant, it also opens you up to SQL injection (either purposeful or accidental) when done wrong. Using <code>mysql.escape</code> is better than nothing, but it's still not a good idea. Use <a href=\"https://en.wikipedia.org/wiki/Prepared_statement\" rel=\"nofollow noreferrer\">prepared statements</a> instead.</p>\n<p>How to do this depends on your database and database driver. For example, with postgresql, syntax like the following can be used:</p>\n<pre><code>db.query(\n `\n SELECT username\n FROM account\n WHERE userid = $(userid);\n `,\n { userid }\n)\n</code></pre>\n<p>Look up the docs for your database to figure out how it can be used with prepared statements (also known as parameterized queries).</p>\n<p><strong>&quot;Finish&quot; finishes at the wrong place</strong> Your <code>finish</code> log is <em>outside</em> of the <code>connection.query</code> callback, so it'll be logged before any of the queries are done. If you want to wait for all asynchronous operations to finish, you should use <code>Promise.all</code>, which will require the database query to return a Promise instead of using a callback. (Promises are generally nicer to use than callbacks anyway - they require less nesting, and error handling is easier.)</p>\n<p>In all, I'd hope to be able to refactor the code to something like this:</p>\n<pre><code>const updateDatabaseQueryString = `\n UPDATE COMPOSANTS\n SET\n PRIX_CLIP=$(price),\n PRIX_PMP=$(pmp),\n DATE=$(date)\n WHERE GPAO=$(code);\n`;\nconst parseLine = (articleLine) =&gt; {\n const str = stdoutConvert(articleLine);\n const tab = pipSplit(str);\n // Use a promisified version of connection.query:\n return connection.query(updateDatabaseQueryString, {\n code: tab[0].trim(),\n price: tab[1].trim(),\n pmp: tab[2].trim(),\n date: dateFormatFR(tab[3]),\n });\n};\nconst refreshPrice = () =&gt; {\n const command = 'echo &quot;SELECT COARTI,PRIXART,PMP,DAT FROM ARTICLEM&quot; | iodbctest &quot;DSN=DSNServ&quot;';\n // Import the promisified version of .exec:\n const exec = util.promisify(require('child_process').exec);\n exec(command, { maxBuffer: 10000 * 1024 })\n .then((stdout) =&gt; {\n const stdoutLines = stdout.toString(&quot;utf8&quot;).split('\\n');\n const articlesClip = stdoutLines.slice(8, stdoutLines.length - 7);\n return Promise.all(articlesClip.map(parseLine));\n })\n .then(() =&gt; {\n console.log('All prices updated successfully');\n })\n .catch((error) =&gt; {\n console.log('Error updating prices:', error);\n });\n};\nfunction scheduleRefreshPrice() {\n cron.schedule('* 20 * * *', refreshPrice, {\n scheduled: true,\n timezone: &quot;Europe/Paris&quot;\n });\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T12:33:41.307", "Id": "495996", "Score": "0", "body": "I say a big thank you. Thank you for spending so much time answering my question.\nYou answered all the questions I asked myself. And your code is \"perfect\".\n\nSo that I can learn, I will not copy your code from A to Z but I will study it and spot my mistakes. You made me a lesson and I thank you again.\n\nJust a quick question, the exec child_process won't crash with all promises?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T14:07:08.610", "Id": "496007", "Score": "0", "body": "If your original code doesn't have a problem with sending out all requests at once, then this code, which is doing the same thing, shouldn't have an issue with it either." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T14:48:25.717", "Id": "496011", "Score": "0", "body": "Ok thank !\nMocha is the best way to test this code ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T14:50:34.330", "Id": "496012", "Score": "0", "body": "I barely have any experience with testing frameworks, but I don't see anything here that would interfere with that. Any of the well-used standard testing libraries should be able to test it (at least until the point of database insertion)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T08:14:12.843", "Id": "496059", "Score": "0", "body": "Nice ! because i run your code and nothing appears in my database. I have an empty array. So I would like to run a test to see where the problem is in order to correct it. @CertainPerformance" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T13:56:36.343", "Id": "496079", "Score": "0", "body": "Check your logs for errors. The code in the answer is probably *very close* to what you need, but I don't know your database, database driver, or syntax for parameterized queries, or if its queries can return Promises instead of using callbacks. Check your database driver's docs to see how it can be done." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T16:22:10.703", "Id": "251717", "ParentId": "251694", "Score": "5" } } ]
{ "AcceptedAnswerId": "251717", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T07:30:28.830", "Id": "251694", "Score": "0", "Tags": [ "javascript", "object-oriented" ], "Title": "Arrays to Object" }
251694
<p>I am working on a project in which I am using vue js 2 and electron , to manage the state I use vuex , I have at least 20 actions to call</p> <pre><code> methods: { ...mapActions('Store1', ['FETCH_AB',...]), ...mapActions('Store2', ['FETCH_DS',...]), ...mapActions('Store3', ['FETCH_SD']), ...mapActions('Store4', ['FETCH_XD']), ...mapActions('Store5', ['FETCH_SD']), ...mapActions('Store6', ['FETCH_AZ']) } </code></pre> <p>I use ...mapActions in my file vue and to call it :</p> <pre><code>async mounted(){ this.FETCH_AZ() this.FETCH_DS() .... } </code></pre> <p>I created an method mounted but i don't know if it's the best way to use vuex when you have enough actions to call and there are actions that need getter or data from actions i mean by example :</p> <pre><code>const actions = { async FETCH_AZ(){ const valueM8 = vm.$store.getters['Store1/GET_AB'] .... } } </code></pre> <p>i.e. an action can use the result of another action to do other operations</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T19:18:45.777", "Id": "524457", "Score": "0", "body": "This is more of a theoretical issue than a practical example to work on" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T08:27:23.147", "Id": "251696", "Score": "1", "Tags": [ "javascript", "asynchronous", "vue.js", "electron" ], "Title": "vuejs: best practices with vuex when you call multiple actions" }
251696
<p>I have a list of dictionary let's say : <code>l=[{'a':1,'b':2},{'a':5,'b':6},{'a':3,'b':2}]</code> and I want to have another list l2 and add 4 to the 'a' in the all dictionaries<br /> <code>l2=[{'a':5,'b':2},{'a':9,'b':6},{'a':7,'b':2}]</code> (the first list l shouldn't change) so I am doing it this way but i feel there is better, it is a bit hard coded I think :</p> <pre><code> l=[{'a':1,'b':2},{'a':5,'b':6},{'a':3,'b':2}] l2=[d.copy() for d in l] for v in l2: v['a']=v['a']+4 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T14:38:11.597", "Id": "495697", "Score": "2", "body": "Can you show more of your code? Currently this seems somewhat hypothetical." } ]
[ { "body": "<p>Should have spaces around <code>=</code>, and <code>+=</code> would shorten it a bit. And I'd be consistent with the variable name (not switch from <code>d</code> to <code>v</code>) and use better names for the lists (<code>l</code> looks too much like <code>1</code> and is just too short for something presumably living longer (unlike <code>d</code>, which I find ok in such small contexts)):</p>\n<pre><code>lst2 = [d.copy() for d in lst]\nfor d in lst2:\n d['a'] += 4\n</code></pre>\n<p>I'd say that's alright then. But here are two alternatives:</p>\n<pre><code>&gt;&gt;&gt; [d | {'a': d['a'] + 4} for d in lst]\n[{'a': 5, 'b': 2}, {'a': 9, 'b': 6}, {'a': 7, 'b': 2}]\n</code></pre>\n<pre><code>&gt;&gt;&gt; [{**d, 'a': d['a'] + 4} for d in lst]\n[{'a': 5, 'b': 2}, {'a': 9, 'b': 6}, {'a': 7, 'b': 2}]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T16:27:42.793", "Id": "496018", "Score": "0", "body": "thank you , this is what I was looking for ,i was feeling it can be done in one line of code, and yes for the variables I know it was just a quick example of what I wanted to do in my real code I am using more significant variable names" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T12:00:23.593", "Id": "251703", "ParentId": "251701", "Score": "6" } } ]
{ "AcceptedAnswerId": "251703", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T10:26:16.320", "Id": "251701", "Score": "4", "Tags": [ "python", "hash-map" ], "Title": "Increment value in a list of dictionaries" }
251701
<p>I have two optional strings, any of them can be None. I want to create their combination with a delimiter between them if they both exist.</p> <p>I expect to be able to come with a more concise and nicer solution.</p> <pre><code>val seq = (Some(&quot;abc&quot;), None) val none = (None, None) val both = (Some(&quot;abc&quot;), Some(&quot;x&quot;)) def concat(s: (Option[String], Option[String])): Option[String] = { s match { case (Some(a), Some(b)) =&gt; Some(a + &quot;, &quot; + b) case (a, None) =&gt; a case (None, b) =&gt; b } } concat(seq) concat(none) concat(both) </code></pre> <p>Can this be rewritten somehow in a more elegant way? The input can be changed from Tuple to Seq if desired.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T20:14:42.473", "Id": "496827", "Score": "0", "body": "If we change it from \"Tuple to Seq\", as you suggest, then it can be done with 2 lines of code: `val res = s.flatten.mkString(\", \")` followed by `Option.when(res.nonEmpty)(res)`" } ]
[ { "body": "<p>I came up with a solution which I like a bit more, based on sequence flattening, but still, I guess someone might be able to provide a better alternate answer.</p>\n<pre><code>val seq = Seq(Some(&quot;abc&quot;), None)\nval none = Seq(None, None)\nval both = Seq(Some(&quot;abc&quot;), Some(&quot;x&quot;))\n\ndef concat(s: Seq[Option[String]]): Option[String] = {\n val r = s.flatMap(_.toSeq)\n if (r.nonEmpty) Some(r.mkString(&quot;, &quot;))\n else None\n}\n\nconcat(seq)\nconcat(none)\nconcat(both)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T15:56:25.453", "Id": "251712", "ParentId": "251702", "Score": "0" } }, { "body": "<p>As you seem to have already noticed yourself, the fact that the input to the function is a pair of strings is somewhat awkward. It violates the <a href=\"https://wiki.c2.com/?ZeroOneInfinityRule\" rel=\"nofollow noreferrer\">Zero-One-Infinity Rule</a>.</p>\n<p>You <em>might</em> be worried about <a href=\"https://wiki.c2.com/?YouArentGonnaNeedIt\" rel=\"nofollow noreferrer\">YAGNI</a> or the <a href=\"https://wiki.c2.com/?RuleOfThree\" rel=\"nofollow noreferrer\">Rule Of Three</a>, but I would argue that it is okay to fudge those guidelines here a little bit, since</p>\n<ul>\n<li>the extension from two to many is obvious,</li>\n<li>simplifies the code, and</li>\n<li>is in service to another guideline.</li>\n</ul>\n<p>One main question you need to ask yourself, which I feel is not really answered in the specification you gave in your question nor in the code snippet you are asking to have reviewed, relates to this statement from your question [<strong>bold</strong> emphasis mine]:</p>\n<blockquote>\n<p>I want to create their combination with a delimiter between them <strong>if they both exist</strong>.</p>\n</blockquote>\n<p>What, <em>precisely</em> do you mean by &quot;if they both exist&quot;? If we are looking at ways that an <code>Option[String]</code> in Scala can exist or maybe not exist, I can think of many different scenarios:</p>\n<ul>\n<li>It can be <code>null</code>. (Unfortunately, since Scala is designed to tightly integrate with the underlying platform, and all of the &quot;interesting&quot; underlying platforms all have a concept of <code>null</code>, it is hard to get rid of this.)</li>\n<li>It can be <code>None</code>.</li>\n<li>It can be <code>Some(&quot;&quot;)</code>, i.e. the empty string.</li>\n<li>It can be <code>Some(&quot; &quot;)</code>, i.e. a string consisting purely of <a href=\"https://util.unicode.org/UnicodeJsps/character.jsp?a=0020\" rel=\"nofollow noreferrer\">U+0020 <em>Space</em></a> characters.</li>\n<li>It can be <code>Some(&quot;  &quot;)</code>, i.e. a string consisting purely of whitespace characters <em>other than</em> U+0020 <em>Space</em>. (There are at least 16 different whitespace characters that are not U+0020 which I have found in about 30s of research.)</li>\n<li>It can be <code>Some(&quot;​&quot;)</code>, i.e. a string consisting purely of <em>zero-width</em> characters. (Note, this is <em>not</em> an empty string! It contains a <a href=\"https://util.unicode.org/UnicodeJsps/character.jsp?a=200B\" rel=\"nofollow noreferrer\">U+200B <em>Zero-width space</em></a>. For added fun, this particular character is not considered Whitespace by the Unicode standard!)</li>\n</ul>\n<p>And these are just some of the things I can think of off the top of my head.</p>\n<p>For example, both your original code in the question and your revised code in the answer will return <code>Some(&quot;, &quot;)</code> when passed two empty strings, or <code>Some(&quot; , &quot;)</code> when passed two strings consisting of one space character.</p>\n<p>If you are willing to accept a very broad definition, then a very simple implementation could be something like this:</p>\n<pre class=\"lang-scala prettyprint-override\"><code>def concat(s: Option[String]*) = s.flatten.mkString(&quot;, &quot;)\n</code></pre>\n<p>However, this will <em>always</em> give you a <code>String</code>, it will not give you an <code>Option[String]</code>. For your <code>None, None</code> example, it will give you the empty string:</p>\n<pre class=\"lang-scala prettyprint-override\"><code>concat(None, None)\n//=&gt; &quot;&quot;\n</code></pre>\n<p>[<a href=\"https://scastie.scala-lang.org/JoergWMittag/1EScnd33SZ68MEXCCXjTQg\" rel=\"nofollow noreferrer\">Scastie link</a>]</p>\n<p>Any specification more complex than this very simple one, including the one from your question, will complicate the code, there is not much you can do about that. There is no getting around the fact that text processing <em>looks</em> deceptively simple (everybody knows what an &quot;empty string&quot; or a &quot;character&quot; is, right?) but is actually very complex.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://scastie.scala-lang.org/JoergWMittag/1EScnd33SZ68MEXCCXjTQg.js\"&gt;&lt;/script&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T10:19:08.947", "Id": "251800", "ParentId": "251702", "Score": "2" } }, { "body": "<p>Alternatively,</p>\n<p>You can redefine what concat does:</p>\n<p>Using <code>Seq</code>:</p>\n<pre><code>val seq: Seq[Option[String]] = Seq(None, Some(&quot;b&quot;))\n</code></pre>\n<p>We can use <code>foldLeft</code> to easily compute this (maybe a little bit overkill, but here goes):</p>\n<pre><code>// HelperFunc for appending commas if we have multiple values\ndef appendValues(total: Option[String], value: String, delimiter: String = &quot;, &quot;): String = {\n total match {\n case None =&gt; value\n case Some(result) =&gt; s&quot;$result$delimiter$value&quot;\n }\n}\n\n// HelperFunc for each op in the foldLeft\ndef op(total: Option[String], next: Option[String]): Option[String] ={\n next match {\n case Some(value) =&gt; Some(appendValues(total, value))\n case None =&gt; total\n }\n}\n\ndef concat(seq: Seq[Option[String]]): Option[String] = {\n seq.foldLeft(Option.empty[String])(op)\n}\n</code></pre>\n<p>So finally:</p>\n<pre><code>concat(seq)\n// Some(b)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T21:34:52.473", "Id": "251969", "ParentId": "251702", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T11:44:14.473", "Id": "251702", "Score": "3", "Tags": [ "strings", "scala", "optional" ], "Title": "Concatenating optional strings in Scala" }
251702
<p>Currently, I am working on this project where I need to achieve the following...</p> <p>Get column named <code>Category</code> from MySQL database. And whatever the output is, check the specific radio button on winforms.</p> <p>I'd like to see if I can improve it, or if there is a much easier way of achieving my goal:</p> <p>Personally - i think there is too many if, else if statements...</p> <p><strong>Radio Buttons:</strong></p> <p><a href="https://i.stack.imgur.com/TcyGK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TcyGK.png" alt="enter image description here" /></a></p> <p><strong>Code:</strong></p> <pre><code>void function() { try { using(var conn = new MySqlConnection(ConnectionString.ConnString)) { string query = &quot;select category from customer_complaints_actions where id = @id&quot;; conn.Open(); using(var cmd = new MySqlCommand(query, conn)) { cmd.Parameters.AddWithValue(&quot;@id&quot;, Convert.ToInt32(complaints_data.SelectedRows[0].Cells[0].Value.ToString())); using(MySqlDataReader read = cmd.ExecuteReader()) { while (read.Read()) { // Categories if ((read[&quot;category&quot;].ToString()) == &quot;Retained Pitt/Shell&quot;) { Pitt_Shell.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Mineral Stone&quot;) { mineral_stone.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Extraneous Vegetable Matter&quot;) { vegetable_matter.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Paper/Cardboard&quot;) { paper_cardboard.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Wood&quot;) { wood.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;String&quot;) { _string.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Hair&quot;) { hair.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Rubber&quot;) { rubber.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Metal&quot;) { metal.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Other Foreign Body&quot;) { other_foreign_body.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Taste&quot;) { taste.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Texture&quot;) { texture.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Smell / Odour&quot;) { smell.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Appearance&quot;) { appearance.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Off / Mould&quot;) { off_mould.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Crystallised / Bloomed&quot;) { bloomed.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Insect Damage / Infestation&quot;) { infestation.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Other Organoleptic&quot;) { other_organoleptic.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Light Weight Pack&quot;) { light_weight_pack.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Product Caught in Seals&quot;) { product_caught_in_seal.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Shepcote Damage&quot;) { shepcote_damage.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Courier Damage&quot;) { courier_damage.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Incorrect Packaging / Label&quot;) { incorrect_pack_label.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Other Packing / Packaging&quot;) { other_pack.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Short Shelf Life&quot;) { short_shelf_life.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Out of Date&quot;) { out_of_date.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Picking Error&quot;) { picking_error.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Order Input Error&quot;) { order_input_error.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Customer Order Error / Change&quot;) { customer_order_error.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Delivery Issues (Wrong Location etc.)&quot;) { delivery_issues.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Other Order / Delivery&quot;) { other_delivery.Checked = true; } else if ((read[&quot;category&quot;].ToString()) == &quot;Injury&quot;) { injury.Checked = true; } } read.Close(); conn.Close(); } } } } catch (Exception e) { MessageBox.Show(e.ToString(), &quot;Error&quot;, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T14:24:01.013", "Id": "495689", "Score": "0", "body": "The current question title applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T14:25:43.027", "Id": "495691", "Score": "1", "body": "Why don't you use [Dapper](https://dapper-tutorial.net/dapper)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T14:29:16.360", "Id": "495694", "Score": "3", "body": "Don't mix UI logic and DB queries. Abstract to something like MVVM. See https://softwareengineering.stackexchange.com/questions/277143/how-do-you-separate-view-from-logic-in-a-winform-application ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T14:34:16.960", "Id": "495696", "Score": "0", "body": "@BCdotWEB I have looked into using MVVM but it does not make sense for me. I don't even know how to apply it to my current project." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T20:52:30.623", "Id": "495761", "Score": "1", "body": "I suppose you have a form where the controls (radio buttons) are already laid out statically, but instead you could add them **dynamically** to the form as you are reading from the database. Do you already have a table that contains possible categories ? Then it should be easy to fix the problem and you'll have dynamic layout, hence freedom to add more categories in the future without having to redesign your form." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T21:51:12.237", "Id": "495765", "Score": "0", "body": "@Anonymous No I don't - but I suppose I can create one to add the flexibility?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T22:27:10.713", "Id": "495768", "Score": "0", "body": "Maybe that would be a good idea. If you stick to the static layout, then you could have some sort of [dictionary](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.8) of key-value pairs, associating your control names with tables values. Then you can get rid of those ifs. If that is still not clear I will try to provide an example, it's just that I am not equipped at the moment." } ]
[ { "body": "<p><strong>Notes :</strong></p>\n<ul>\n<li><p>Don't mix UI logic with Business logic, separate them using classes, and you can use one of the known design patters such as MVVM. (as @BCodotWEB noted).</p>\n</li>\n<li><p>When you use <code>using</code>, there is no need to close the connection or dispose the object such as calling <code>Dispose()</code> or <code>Close()</code> within the <code>using</code> block. As the <code>using</code> block will do that for you whenever it reaches the end of the block. So, in your code, <code>conn</code> and <code>cmd</code> will be disposed automatically.</p>\n</li>\n<li><p>When you compare strings, ensure that you specify the <code>StringComparison.OrdinalIgnoreCase</code> to avoid <code>Case Sensitively</code> comparison.</p>\n</li>\n<li><p>When you have multiple <code>if/else</code> statments on just one <code>value</code> (like yours), convert it to <code>switch</code> statement, for better readability and maintainability.</p>\n</li>\n<li><p>don't use <code>MySqlCommand</code> nor any <code>DbCommand</code> derived class directly, as it's barebone classes, meaning, it will require you to handle everything from the connection, commands, results, types conversations, modeling ..etc. Which is too much work.(Not to mention SQL Injection). Instead, use managed Object–relational Mapping (ORM) framework, such as <code>Dapper</code> and <code>Entity Framework</code> that are built around <code>ADO.NET</code> which saves time, and effort, and also has a better implementation and handling.</p>\n</li>\n</ul>\n<p>Coming back to your main concern :</p>\n<blockquote>\n<p>I'd like to see if I can improve it, or if there is a much easier way\nof achieving my goal:</p>\n<p>Personally - i think there is too many if, else if statements...</p>\n</blockquote>\n<p>it seems that your database has <code>category</code> table, which has predefined values, and the <code>customer_complaints_actions</code> table saves <code>category</code> values and not the foreign key of the <code>category</code> table. This would be a design issue. Even if the values are matching, there is no guarantee of keeping them intact. For instance, if for some reason someone decided to add just an <code>s</code> to the <code>Wood</code> category name to be plural, then it will invalidate all related records that uses <code>Wood</code> category, and you will need to update them with this change as well. But, if you used the <code>FK</code>, then any changes to the category name, it won't affect the results. Because it's linked with the <code>Key</code> and not the <code>Value</code>. If you change the <code>Key</code> then it will do a cascade update on all its <code>FK</code>s.</p>\n<p>To solve that, you'll need to first to fix the database structure design and follow database principles and best practices. Then, in your code, you will need to use ORM and also applying at least one of the known design patterns that would fit your application requirements.</p>\n<p>If you do this, then, you can make your application more dynamic and fixable for any business changes.</p>\n<p>For instance, instead of creating <code>RadioButton</code> for each <code>category</code> manually, you could make your <code>Form</code> dynamically on the form initiation, based on the <code>category</code> table values.</p>\n<p>So, first thing you need to get all <code>Category</code> table values when the <code>Form</code> is initiated, something like this (Using Entity Framework as an example) :</p>\n<pre><code>public FormCustomerComplaint() {\n \n InitiateCategories();\n}\n\nprivate void InitiateCategories()\n{\n // Looping over Category Table Rows \n // context represents the database in Entity Framework\n foreach(var category in context.Categories)\n {\n var radio = new RadioButton\n {\n Name = $&quot;CatId{category.Id}&quot;,\n Text = category.Name, \n };\n\n GroupBoxCategory.Controls.Add(radio);\n }\n}\n</code></pre>\n<p>Now, even if there is a new change on the <code>Category</code> table, it'll be affected automatically.</p>\n<p>Then, you can use the same concept to reterive the values for each record in the customer_complaints_actions table, something like this (again, using <code>Entity Framework</code> as an example) :</p>\n<pre><code>// Now to get the category from customer_complaints_actions\n// Assuming that `categoryId` is the FK for `Category` table. \n// context represents the database in Entity Framework\nvar result = context.CustomerComplaintsActions.FirstOrDefault(x=&gt; x.Id == id);\n\nif(result != null)\n{ \n \n var control = GroupBoxCategory.Controls.Find($&quot;CatId{result.CategoryId}&quot;, true).FirstOrDefault();\n \n if(control != null) \n {\n var radio = (RadioButton) control; \n radio.Checked = true; \n }\n}\n</code></pre>\n<p>These are just simple examples to show you how easy would be when you using the proper techniques to work with your application. I used them to encourage you to start using <code>ORM</code> (not focusing on the design patterns here). Just start with that, andif you found yourself good at using it, then you can start using a design pattern that would fit your application needs such as object-modeling and <code>MVVM</code> to make your code easy to manage.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T20:18:17.330", "Id": "495841", "Score": "0", "body": "Really appreciate your answer! - Will look into it when I am back at work and try to implement everything you suggested :D" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T06:38:25.277", "Id": "251748", "ParentId": "251706", "Score": "5" } }, { "body": "<p>You already got a good review from iSR5. So perhaps I am not going to comment a lot on the code. My take is on ergonomics. Like all (?) developers I am lazy but I like challenges, however I am willing to think outside the box and devise a better solution before tackling a new problem.</p>\n<p>After a more careful look I am thinking that you might want to reconsider form design. A combo box bound to a datatable may be a better option if the number of items becomes consequential, and would optimize form space. A combo box can also provide autocomplete facilities, and thus speed up encoding. Since you are using radio buttons, it means only one answer is possible per category, then a combo box is a valid alternative.</p>\n<p>As it is the form already looks pretty crowded, that means lots of back and forth mouse movements to get from one control to another, considering the width of the form. I even predict elbow pain under heavy use conditions.\nIf you have to add more options in the future, that could be problematic from a usability point of view. The form will become overwhelming and unengaging.</p>\n<p>Moreover, the items do not seem to be sorted. Unless the user is very accustomed to the form, he/she has to visually scan the form every time to locate the desired option.\nHint: a column layout could make a difference and consider sorting items (unless they are actually sorted in terms of frequency based on your business experience). Either way, the options should be arranged in a way that is intuitive and not random.</p>\n<p>Basically, you could have a more compact form with 5 combo boxes instead of the current 5 radio button zones you have now, and each combo box can be fed by a table. Thus you can have a form with a static layout but dynamic values, and its size will always remain contained.</p>\n<p>Another possible trick that I have used sometimes is to place a group of dynamic controls inside a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.flowlayoutpanel?view=netframework-4.8\" rel=\"nofollow noreferrer\">flowlayoutpanel</a> in a kind of column layout, such a panel can have a vertical scrollbar and even autosize.\nHere is an <a href=\"https://stackoverflow.com/a/42711902/6843158\">example</a> from Stackoverflow with picture. This could be an alternative as long as you don't have to too many items to scroll.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T22:13:31.593", "Id": "495852", "Score": "0", "body": "Hi - Thanks for your answer. I completely agree with re-thinking the design of the form. It's only a start at the moment.. but eventually I'll get a decent form created :D I will keep your comments in mind and think of it when I back at it again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T21:58:22.710", "Id": "251780", "ParentId": "251706", "Score": "4" } } ]
{ "AcceptedAnswerId": "251748", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T13:22:39.657", "Id": "251706", "Score": "3", "Tags": [ "c#", "winforms" ], "Title": "Getting data from database and present it on Winforms" }
251706
<p>This is my code. It loops a menu, from which you can select whether you want to add a subject, see all subjects or delete a subject. Is there anything style- or functionality-wise to add or correct?</p> <pre><code>def add_subject(subjects): # ask for subject to add add = input(&quot;\nWhat subject do you want to add? &quot;) # if subject not already in list, add subject subjects.append(add) if not add in subjects else print(&quot;\nSubject already in list.&quot;) def show_subjects(subjects): # show all subjects print(&quot;\nThese are your subjects: &quot;, subjects) def delete_subject(subjects): # ask for subject to delete delete = input(&quot;\nPlease enter subject to delete: &quot;) # if subject is in list, delete subject subjects.remove(delete) if delete in subjects else print(&quot;\nSubject not found.&quot;) def main(): # initialise list of sample subjects subjects = [&quot;Math&quot;,&quot;Science&quot;,&quot;English&quot;] # loop action cycle while 1: try: # ask user for selection selection = int(input(&quot;\nPlease enter option: \n(1) Add subject\n(2) Show all subjects\n(3) Delete a subject\n(4) Quit\n&quot;)) # call associated function if selection == 1: add_subject(subjects) elif selection == 2: show_subjects(subjects) elif selection == 3: delete_subject(subjects) elif selection == 4: break else: raise ValueError except ValueError: print(&quot;\nNot a viable option. Please pick 1, 2 or 3.&quot;) if __name__ == &quot;__main__&quot;: main() </code></pre>
[]
[ { "body": "<h1>Clear the screen</h1>\n<p>Here is the terminal after three iterations\n<a href=\"https://i.stack.imgur.com/U4Zz0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/U4Zz0.png\" alt=\"enter image description here\" /></a></p>\n<p>We can clean a lot of this up by simply doing</p>\n<pre><code>print(chr(27) + &quot;[2J&quot;)\n</code></pre>\n<p>after every iteration.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def clear_scr():\n print(chr(27) + &quot;[2J&quot;)\n</code></pre>\n<p>Note that on adding this, you should also do</p>\n<pre class=\"lang-py prettyprint-override\"><code>input(&quot;Press any key to continue...&quot;) \n</code></pre>\n<p>After the user selects an option, this way the user can wait and see what is on the screen peacefully without the program interrupting</p>\n<pre class=\"lang-py prettyprint-override\"><code>def wait():\n input(&quot;Press any key to continue...&quot;)\n print(chr(27) + &quot;[2J&quot;)\n</code></pre>\n<p>Or a better version that also prints a confirmation message</p>\n<pre class=\"lang-py prettyprint-override\"><code>def wait(message):\n input(f&quot;{message}. Press any key to continue...&quot;)\n print(chr(27) + &quot;[2J&quot;)\n\n\n\nwait(&quot;Subject Added!&quot;)\n\n&gt;&gt;&gt; Subject Added! Press any key to coninue... \n</code></pre>\n<hr />\n<h1>Unnecessary comments</h1>\n<pre class=\"lang-py prettyprint-override\"><code># ask user for selection\nselection = int(input(&quot;\\nPlease enter option: \\n(1) Add subject\\n(2) Show all subjects\\n(3) Delete a subject\\n(4) Quit\\n&quot;))\n</code></pre>\n<p>A comment here is totally not required, it only makes the code look convoluted for no reason. What I do suggest is the usage of <a href=\"http://python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def wait():\n &quot;&quot;&quot;\n Wait for the user to press any key then clear the screen\n &quot;&quot;&quot;\n ...\n</code></pre>\n<hr />\n<h1>Print the subjects in a better fashion</h1>\n<p>I added a few more subjects in your program. When I entered <code>Show all subjects</code>.</p>\n<pre><code>These are your subjects: ['Math', 'Science', 'French', 'Computer', 'Hindi', 'Social Science', 'Spanish', 'English']\n</code></pre>\n<p>This isn't nice at all, I suggest you print one on each line, with numbering, something like</p>\n<pre><code>Subjects\n\n1. Math\n2. Science\n3. French\n3. Computer\n...\n</code></pre>\n<pre><code>def show_subjects(subjects):\n &quot;&quot;&quot;\n print all the subjects line-by-line \n &quot;&quot;&quot;\n print(&quot;\\n\\nSubjects\\n&quot;)\n for i in range(len(subjects)):\n print(f&quot;{i+1}. {subjects[i]}&quot;)\n</code></pre>\n<hr />\n<h1>Don't use <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)#:%7E:text=In%20computer%20programming%2C%20the%20term,be%20replaced%20with%20named%20constants\" rel=\"nofollow noreferrer\">magic numbers</a></h1>\n<pre class=\"lang-py prettyprint-override\"><code> if selection == 1:\n add_subject(subjects)\n elif selection == 2:\n show_subjects(subjects)\n elif selection == 3:\n delete_subject(subjects)\n elif selection == 4:\n break\n else:\n raise ValueError\n</code></pre>\n<p><code>1</code>, <code>2</code>, <code>3</code>, and <code>4</code> are unnamed numeric constants here. They don't really really tell anything about what the branch does. What if it was instead</p>\n<pre class=\"lang-py prettyprint-override\"><code> if selection == Choices.add.value:\n add_subject(subjects)\n elif selection == Choices.show.value:\n show_subjects(subjects)\n elif selection == Choices.delete.value:\n delete_subject(subjects)\n elif selection == Choices.quit.value:\n break\n else:\n raise ValueError\n</code></pre>\n<p>Without reading anything inside the if block, I can tell exactly what its going to do. That is an example of clean code.</p>\n<p>You can achieve this by using an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">enum</a></p>\n<pre class=\"lang-py prettyprint-override\"><code>from enum import Enum\n\nclass Choices(Enum):\n add = 1\n show = 2\n delete = 3\n quit = 4\n\nprint(Choices.add.value) \n&gt;&gt; 1\n\nprint(Choices.quit.value)\n&gt;&gt; 4\n</code></pre>\n<hr />\n<h1>Colored text</h1>\n<p>This one is optional, but it adds a lot of meaning to your code :). <br>\nYou can use the <a href=\"https://pypi.org/project/colorama/\" rel=\"nofollow noreferrer\">coloroma</a> module to color your text to different colors in an easy way. For example, when you find that the user has entered bad input, you can do</p>\n<p><a href=\"https://i.stack.imgur.com/BYZR3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BYZR3.png\" alt=\"enter image description here\" /></a></p>\n<p>Isn't that great! The best part about it is that it is cross-platform</p>\n<pre class=\"lang-py prettyprint-override\"><code>from colorama import Fore, Back, Style\nprint(Fore.RED + 'some red text')\nprint(Back.GREEN + 'and with a green background')\nprint(Style.DIM + 'and in dim text')\nprint(Style.RESET_ALL)\nprint('back to normal now')\n</code></pre>\n<p>You have a lot of options, it can help you customize the output a lot. Read the <a href=\"https://pypi.org/project/colorama/\" rel=\"nofollow noreferrer\">documentation</a></p>\n<p>As suggested by @Reinderien, using the colorama library you can clear the screen too</p>\n<pre class=\"lang-py prettyprint-override\"><code>import colorama as cr\ncr.init()\n\nprint(cr.ansi.clear_screen()) # clears the screen\n</code></pre>\n<h1>Re-written</h1>\n<pre class=\"lang-py prettyprint-override\"><code>from colorama import Fore, Back, Style\nimport colorama as cr\nfrom enum import Enum\n\ncr.init()\n\n\nclass Choices(Enum):\n add = 1\n show = 2\n remove = 3\n quit = 4\n\n\ndef wait(message = None):\n if message is None:\n input(&quot;Press any key to continue...&quot;)\n else:\n print(Fore.GREEN)\n print(Style.BRIGHT)\n\n print(message, end = '')\n\n print(Style.RESET_ALL)\n input(&quot;Press any key to continue...&quot;)\n\n print(cr.ansi.clear_screen())\n\ndef add_subject(subjects):\n add = input(&quot;\\nWhat subject do you want to add? &quot;)\n if add not in subjects:\n subjects.append(add)\n wait(&quot;Subject Added!&quot;)\n else:\n print(&quot;Subject already present&quot;)\n wait()\n\n\ndef show_subjects(subjects):\n print(&quot;Subjects\\n&quot;)\n print(Fore.YELLOW)\n print(Style.BRIGHT)\n for i in range(len(subjects)):\n print(f&quot;{i+1}. {subjects[i]}&quot;)\n wait()\n\ndef delete_subject(subjects):\n delete = input(&quot;\\nPlease enter subject to delete: &quot;)\n if delete not in subjects:\n print(&quot;Subject not found&quot;)\n wait()\n else:\n subjects.remove(delete)\n wait(&quot;Subject removed!&quot;)\n\ndef main():\n subjects = [&quot;Math&quot;,&quot;Science&quot;,&quot;English&quot;]\n while True:\n try:\n selection = int(input(&quot;\\nPlease enter option: \\n(1) Add subject\\n(2) Show all subjects\\n(3) Delete a subject\\n(4) Quit\\n&quot;))\n if selection == Choices.add.value:\n add_subject(subjects)\n elif selection == Choices.show.value:\n show_subjects(subjects)\n elif selection == Choices.remove.value:\n delete_subject(subjects)\n elif selection == Choices.add.value:\n break\n else:\n raise ValueError\n\n except ValueError:\n print(Fore.RED)\n print(&quot;\\nNot a viable option. Please pick 1, 2 or 3.&quot;)\n print(Style.RESET_ALL)\n wait()\n\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/b0YPS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/b0YPS.png\" alt=\"g\" /></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:12:53.323", "Id": "495720", "Score": "0", "body": "I think `dataclass` over enum for `Choices` here would be cleaner" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:21:15.920", "Id": "495721", "Score": "0", "body": "@hjpotter92 I have to research more about data classes before recommending it, can you give an example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:28:54.273", "Id": "495725", "Score": "0", "body": "Adding coloured text and clearing the screen are fine, but tightly coupling to raw ANSI escape sequences is a bad idea. Consider using something like https://github.com/tartley/colorama instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:30:18.033", "Id": "495726", "Score": "0", "body": "@AryanParekh as an example: https://tio.run/##Rc29CoUwDAXgvU@RURfBn0kQBJ@k2EgLamoTkfv0vaVYzBByvuHE/8TS2ce4BTrAaNHrrpmRwR2egnyklJq/kDcsltyKPCpIo40ZwZ0CE7QZ2NJTpMticEfBYn2263ZSZEhPfEh39TY3qbSO8Q8 (and the docs: https://devdocs.io/python~3.8/library/dataclasses#dataclasses.dataclass)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:56:34.643", "Id": "495733", "Score": "0", "body": "@Reinderien yes I've recommended the colorama library, what's wrong?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:57:23.850", "Id": "495735", "Score": "0", "body": "You're not making enough use of it. `print(chr(27) + \"[2J\")` should be a call to `colorama` as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T18:07:29.170", "Id": "495739", "Score": "1", "body": "@Reinderien Added the `clear_screen` call from the colorama library, I didn't expect it to have it earlier" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T18:24:56.833", "Id": "495742", "Score": "0", "body": "Fine; though I'd edit your explicit escape sequences to show the same. Anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T18:48:53.787", "Id": "495746", "Score": "0", "body": "@hjpotter92 Thanks! Ill check it out" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T09:09:15.693", "Id": "495784", "Score": "0", "body": "Why not use `for i, subject in enumerate(subjects, 1)` rather than `for i in range(len(subjects))`? That is usually considered more pythonic and cleans up your print statement: `print(f\"{i}. {subject}\")`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T09:25:30.300", "Id": "495785", "Score": "0", "body": "@Energya Yes, I didn't think of that, do you mind if I add it to my answer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T11:29:41.720", "Id": "495796", "Score": "0", "body": "Of course, go ahead" } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T16:56:16.840", "Id": "251720", "ParentId": "251710", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T15:51:36.163", "Id": "251710", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Manage list of subjects (show, delete, add) in Python" }
251710
<p><code>Given a byte string S of length l, obtain the string D of length l-1 as D(i) = S(i) * S(i+1) (each element of D is the product of two consecutive elements of S).</code></p> <p>here is my code.</p> <pre><code>bits 32 global start extern exit import exit msvcrt.dll segment data use32 class=data s db 1, -3, 4, 7 ; declaring the string of bytes s l equ $ - s - 1 ; compute the length of the string l - 1 d times l dw 0 ; reserve l bytes for the destination string and initialize it segment code use32 class=code start: mov ecx, l mov esi, 0 jecxz end_prog repeat_this: mov al, [s + esi] ; in al - the element on the esi position mov dh, [s + esi + 1] ; in dh - the element after the esi position imul dh ; multiplying consecutive terms mov [d + esi], ax; put the result in d inc esi ; incrementing esi to go to the next position loop repeat_this end_prog: push dword 0 call [exit] </code></pre> <p>my question is did I make a mistake by declaring <code>d times l dw 0</code> since I know that a byte * byte = word? Is everything else okay or should I pay attention to some details that I'm missing?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T16:49:18.880", "Id": "495714", "Score": "1", "body": "You're asking whether `d` is supposed to be declared with `dw` element-size, but the quoted program-description doesn't clearly say, so as far as I can tell there's no way for us to know that. Was there originally a larger explanation or some additional context that contains such information?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T16:54:19.550", "Id": "495715", "Score": "0", "body": "no, I just wanted to know if that would be considered a mistake even if it doesn't say. also I didn't know if my program was entirely correct because of that fact. so I wanted to check and asked someone more experienced than me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:52:44.620", "Id": "495728", "Score": "0", "body": "If this is homework, please tag it as such." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:54:29.757", "Id": "495730", "Score": "0", "body": "fixed it @Reinderien, I'm sorry! :c" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:55:09.683", "Id": "495731", "Score": "1", "body": "It's OK :) For a relatively new user this is a quite-good question for CR." } ]
[ { "body": "<h1>Inconsistent addressing of <code>d</code></h1>\n<p><code>d</code> is an array of 2-byte elements (<code>d times l dw 0</code>) and <code>mov [d + esi], ax</code> indexes into it with <code>esi</code> as the offset. However, <code>esi</code> is increased by 1 every iteration, so the resulting access pattern is that the stores keep stepping half on top of the previous store, shown by such a diagram: (storing -3, -12 and 28 in sequence)</p>\n<pre><code>FD FF\n F4 FF\n 1C 00\n</code></pre>\n<p>This is possible to do, but probably unintentional.</p>\n<p>Normally my recommendation would be to increase the register by 2 in the loop, but <code>esi</code> is also used to index <code>s</code> so that won't work. You can change the store to double <code>esi</code> though, for example:</p>\n<pre><code>mov [d + esi*2], ax\n</code></pre>\n<p>Or,</p>\n<pre><code>mov [d + esi + esi], ax\n</code></pre>\n<p>If you change <code>d</code> to be an array of bytes then the store should be <code>mov [d + esi], al</code>, with the original address but storing only 1 byte. Storing overlapping words would put the right data in <code>d</code>, but it's strange and stores a stray byte just after the end of <code>d</code>.</p>\n<h1>Calling <code>exit</code></h1>\n<p><code>exit</code> performs C library termination procedures, but the C library runtime environment wasn't used or even initialized (this code is in <code>start</code>, not <code>main</code>), so it's not necessary. It makes more sense to call <code>ExitProcess</code> (kernel32.dll), or just return (that does not work on Linux, but this is a Windows program and there it does work).</p>\n<h1>The <code>loop</code> instruction</h1>\n<p><a href=\"https://stackoverflow.com/questions/46881279/how-exactly-does-the-x86-loop-instruction-work\"><code>loop</code> is not great</a>, it has some niche uses but typically it should be avoided. <code>jecxz</code> by contrast is OK, just unusual.</p>\n<h1>Minor things</h1>\n<p>The best way to zero <code>esi</code> isn't <code>mov esi, 0</code>, it's <a href=\"https://stackoverflow.com/q/33666617/555045\"><code>xor esi, esi</code></a>, unless the flags must not be affected.</p>\n<p>The two loads of the current and next element of S could be merged into a single <code>word</code> load, if you want. For example <code>mov ax, [s + esi]</code> followed by <code>imul ah</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:53:37.280", "Id": "495729", "Score": "0", "body": "thank you for the detailed comment for the program! we were taught to use loop and jecxz, but I'll try to look for better alternatives in the future!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:57:22.350", "Id": "495734", "Score": "0", "body": "because it forces the content of esi to be 0." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:59:30.380", "Id": "495736", "Score": "1", "body": "@Reinderien that's also a link to the reasons, but perhaps the double-formatting is not super clear" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:59:54.830", "Id": "495738", "Score": "1", "body": "@harold Oh! I missed that - thank you!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:43:19.230", "Id": "251722", "ParentId": "251714", "Score": "6" } } ]
{ "AcceptedAnswerId": "251722", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T16:10:14.133", "Id": "251714", "Score": "6", "Tags": [ "homework", "assembly", "x86" ], "Title": "Given a byte string S of length l, obtain the string D of length l-1 as D(i) = S(i) * S(i+1)" }
251714
<p>Let's assume you are writing a REST Api with a common structure like Controller &gt; Service &gt; Repository &gt; Database. In the database there's a table with a column with a unique constraint:</p> <pre><code> // Examples with typeorm/typescript // user.entity.ts @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Unique() @Column() email: string; // Other properties } </code></pre> <p>In the <code>updateUser</code> method you have to check if the user exists and if the user <code>email</code> is not used by another one.</p> <p>Which one of the following approaches would it be better?</p> <p>A) Interrogate the database to check if the user with the given <code>id</code> exists and do it again to make sure there's not another user with the same email:</p> <pre><code> // users.service.ts @Entity() export class UsersService { async updateUser(user: UserDTO): Promise&lt;UserDTO&gt; { const userById = await this.repository.findOne(user.id); if (!userById) { throw new Error('User does not exist'); } const userWithSameEmail = await this.repository.findOne({ where: { id: Not(user.id), email: user.email } }); if (userWithSameEmail) { throw new Error('Email already in use'); } // Handle errors with some interceptor // Rest of the method } } </code></pre> <p>B) Database calls could lead to performance issues. The orm will anyway throw an error in case of invalid input:</p> <pre><code> @Entity() export class UsersService { async updateUser(user: UserDTO): Promise&lt;UserDTO&gt; { try { const updatedUserEntity = await this.repository.update(user); // Rest of the method } catch (e) { // Handle error } } } </code></pre> <p><strong>Quick bonus question</strong></p> <p>Should the service layer be aware about entities and handle operations like receive the <code>updatedUserEntity</code> from the repository, map it to the DTO and return it to the level above?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T07:06:08.560", "Id": "495777", "Score": "1", "body": "What language is this written in? Tag it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T08:40:04.610", "Id": "495780", "Score": "0", "body": "Typescript, the orm library used it's typeorm" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T13:57:05.910", "Id": "496080", "Score": "1", "body": "Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. Please take a look at the [help/on-topic]." } ]
[ { "body": "<p>With approach A) you may run in a concurrency problem.<br />\nFor example process A and process B want to write a new entry. Both load the data from the database and check if their new entry would be valid. Both decide &quot;YES, valid&quot;.<br />\nNow process A writes the new entry, and then process B tries to write. But A already changed the database, therefor the validation in B was executed on obsolete data.</p>\n<p>Be aware that node will execute things concurrently, because as soon as a &quot;process&quot; (task) has some waiting time, another process (task) will be executed until that one is finished or also waiting for something.</p>\n<p>With version B) this problem gets (for most db´s) fixed. On the other side, now your business logic is scattered over multiple systems, which makes maintenance harder.</p>\n<p>--&gt; As always, there is no YES or NO but a &quot;depends on your context&quot; :-)</p>\n<p>About the bonus question:\nIf your application uses the same entities as the DB, then your whole application (from top to bottom) has a dependency to your database schema.<br />\nAs a result, a change in your DB then has to be followed by a lot of changes in your application. If you do the mapping in the service layer (thats where i would expect the business logic), then all changes run at least until there.</p>\n<p>Therefor i would &quot;map&quot; the data in the data access layer into the entities i use in my application. Yep, in many cases the entites will look similar, but it decouples my application from my database. And my business logic will not know anything about the format that is used when data gets stored.</p>\n<p>By the way, some people use their entities over the whole application, some create new entities for each layer and the data get maped a lot. Both approaches have their reason, personaly i work with a entity set for the whole application.</p>\n<p>Just a few thoughts. Pick those that make sense to you and skip the rest. :-)</p>\n<p>warm regards</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T13:55:39.193", "Id": "251901", "ParentId": "251723", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T17:58:40.857", "Id": "251723", "Score": "2", "Tags": [ "validation", "error-handling", "typescript", "repository" ], "Title": "Handle database validation (exists, unique constraint, etc)" }
251723
<p>I have this code in my MVC Controller:</p> <pre><code>[HttpGet] [OutputCache(VaryByParam = &quot;*&quot;, Duration = 3600, Location = System.Web.UI.OutputCacheLocation.ServerAndClient)] public async Task&lt;string&gt; GetAPI(string callback, string libraries) { var location_selector_script = System.IO.File.ReadAllText(Server.MapPath(&quot;~/Scripts/nav/locselector.js&quot;)); var res = await Utilities.API.GetAsync(&quot;https://maps.googleapis.com/maps/api/js?key=&quot; + ConfigurationsHelper.GoogleMapsAPIKey + &quot;&amp;callback=&quot; + callback + &quot;&amp;libraries=&quot; + libraries); return res + location_selector_script; } </code></pre> <p>and call it like this:</p> <pre><code>&lt;script async defer src=&quot;/Navigation/GetAPI?callback=initMap&amp;libraries=places&quot;&gt;&lt;/script&gt; </code></pre> <p>Is this a good idea to initialize Google APIs in backend?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T19:13:00.593", "Id": "495749", "Score": "0", "body": "That looks like it hides your API key from the front-end? Even if it's not foolproof, it sounds like a great idea in general." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T19:25:28.553", "Id": "495752", "Score": "0", "body": "@CertainPerformance Yes that's why I was going for this approach. But just a minute ago I found that it doesn't hides the API key because when I moved the marker on the map, the frontend sends some requests with my API key to the Google API through browser. I saw them in the console. But I want know if I use this approach will it effect the SSL source that is required by the Google API endpoint?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T22:22:49.303", "Id": "495767", "Score": "0", "body": "I this may be more of a question for stack overflow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T09:29:30.287", "Id": "495786", "Score": "0", "body": "@AishwaryaShiva Well, if you need to hide the request traffic, you may need to register a `HttpClientHandler` with a different `WebProxy` to the `HttpClient` then use it. This would make the request uses a different proxy than the pre-configured one, which hides the traffic from the current connection for basic tracing tools such as browsers and `Fiddler` or similar tools." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T16:45:48.203", "Id": "495942", "Score": "0", "body": "@iSR5 Can you give me an example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T11:43:09.130", "Id": "495989", "Score": "0", "body": "@AishwaryaShiva sure, check this out : https://www.codegrepper.com/code-examples/csharp/add+proxy+to+httpclient+c%23" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T18:31:16.153", "Id": "251726", "Score": "0", "Tags": [ "c#", "javascript", "api", "asp.net", "google-maps" ], "Title": "Initializing Google APIs serverside in MVC controller" }
251726
<p>The following code is in-memory repository that stores key/value pairs. It will be used on our server to keep information about active clients. Clients send keepalive messages to indicate that them are active. Important point: the information of inactive (expired) clients should be removed from repository ASAP. A client sends keepalive message every 30 seconds and I expect 1000 clients connected.</p> <p>The methods usage:</p> <ul> <li>put - adds new client (registration)</li> <li>touch - updates client &quot;last seen time&quot; (keepalive)</li> <li>remove - removes client (client leaves)</li> <li>get - looks for client with given client's ID</li> </ul> <p>I would like to get feedback on:</p> <ul> <li>Coding style</li> <li>Possible performance problem</li> <li>Suggestions for improvement.</li> </ul> <p>Thanks in advance.</p> <pre><code>import java.util.AbstractMap.SimpleEntry; import java.util.HashMap; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ExpiringKeyValueRepository&lt;K, V&gt; { final public static long MAX_LIVE_TIME = Long.MAX_VALUE; private Node&lt;K, V&gt; first = null; private Node&lt;K, V&gt; last = null; private long timeToLive; private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); private Lock writeLock = rwLock.writeLock(); private Lock readLock = rwLock.readLock(); private Condition checkCondition = writeLock.newCondition(); private HashMap&lt;K, Node&lt;K, V&gt;&gt; map = new HashMap&lt;&gt;(); private Cleaner&lt;K, V&gt; cleaner = new Cleaner&lt;&gt;(this); private Thread cleanerThread = null; /** * Constructs an empty repository with the given live time period of stored elements * * @param timeToLive the live time in milliseconds * * @throws IllegalArgumentException if given live time is zero or negative */ public ExpiringKeyValueRepository(long timeToLive) throws IllegalArgumentException { if (timeToLive &lt;= 0) throw new IllegalArgumentException(); this.timeToLive = timeToLive; } /** * Starts the repository. * Call of this method on already running * repository has no effect */ synchronized public void start() { if (cleaner.isRunning()) return; cleanerThread = new Thread(cleaner); cleaner.stopped = false; cleanerThread.start(); } /** * Stops the repository. The method also removes * all stored entries. Call of this method on already * stopped repository has no effect */ synchronized public void stop() { if (!cleaner.isRunning()) return; try { cleaner.stop(); cleanerThread.join(); } catch (InterruptedException e){}; reset (); } /** * Adds the given key/value mapping to this repository * if the repository doesn't contain mapping for the given key * * @param key the key * @param value the value * * @return true if this repository did not already * contain mapping for the specified key * * @throws NullPointerException if either key or value is null * @throws IllegalStateException if repository is not running */ public boolean put(K key, V value) throws NullPointerException, IllegalStateException { if (!cleaner.isRunning()) throw new IllegalStateException(); Objects.requireNonNull(key); Objects.requireNonNull(value); writeLock.lock(); try { Node&lt;K, V&gt; node = map.get(key); if (node == null) { linkLast(key, value); map.put(key, last); return true; } return false; } finally { rwLock.writeLock().unlock(); } } /** * Updates expiration time of entry mapped to the given key * * @param key the key * * @return true if mapping for given key found * * @throws IllegalStateException if repository is not running */ public boolean touch(K key) throws IllegalStateException { if (!cleaner.isRunning()) throw new IllegalStateException(); Objects.requireNonNull(key); writeLock.lock(); try { Node&lt;K, V&gt; node = map.get(key); if (node == null) return false; node.updateExpirationTime(timeToLive); moveToEnd(node); checkCondition.notify(); return true; } finally { rwLock.writeLock().unlock(); } } /** * Returns the value with which the given key is associated. * If this repository contains no mapping for the key or entry * is expired then the method returns null. * * @param key the key * * @return the value with which the given key is associated, returns null * if no mapping for the key or entry is expired * * @throws IllegalStateException if repository is not running */ public V get(K key) throws IllegalStateException { if (!cleaner.isRunning()) throw new IllegalStateException(); readLock.lock(); try { Node&lt;K, V&gt; node = map.get(key); return node == null || node.isExpired() ? null : node.getValue(); } finally { readLock.unlock(); } } /** * Removes the association for the given key * * @param key the key whose mapping is to be removed * * @return the previous value associated with key, * or null if there was no mapping for key * * @throws IllegalStateException if repository is not running */ public V remove(K key) throws IllegalStateException { if (!cleaner.isRunning()) throw new IllegalStateException(); rwLock.writeLock().lock(); try { V value = removeNoLock(key); checkCondition.notify(); return value; } finally { rwLock.writeLock().unlock(); } } private void reset () { first = last = null; map.clear(); } private V removeNoLock(K key) { if (!cleaner.isRunning()) throw new IllegalStateException(); final Node&lt;K, V&gt; node = map.remove(key); if (node == null) return null; unlink(node); return node.getValue(); } private void linkLast(K key, V value) { final Node&lt;K, V&gt; node = new Node&lt;K, V&gt;(key, value, timeToLive); linkLast(node); } private void linkLast(Node&lt;K, V&gt; node) { if (!cleaner.isRunning()) throw new IllegalStateException(); node.setLinks(last, null); last = node; if (last.prev == null) first = node; else last.prev.next = node; } private Node&lt;K, V&gt; unlink(Node&lt;K, V&gt; node) { if (!cleaner.isRunning()) throw new IllegalStateException(); if (first == null) return null; final Node&lt;K, V&gt; prev = node.prev; final Node&lt;K, V&gt; next = node.next; if (prev == null) { first = next; } else { prev.next = next; node.prev = null; // Help GC } if (next == null) { last = prev; } else { next.prev = prev; node.next = null; // Help GC } return node; } private void moveToEnd(Node&lt;K, V&gt; node) { if (first == null) return; // should not be here if (first == last) return; unlink(node); linkLast(node); } private static class Node&lt;K, V&gt; extends SimpleEntry&lt;K, V&gt; { private static final long serialVersionUID = 1L; private Node&lt;K, V&gt; prev = null; private Node&lt;K, V&gt; next = null; private long expirationTime; private Node(K key, V value, long liveTime) { super(key, value); updateExpirationTime(liveTime); } private Node(Node&lt;K, V&gt; prev, Node&lt;K, V&gt; next, K key, V value, long liveTime) { this(key, value, liveTime); setLinks(prev, next); } private void setLinks(Node&lt;K, V&gt; prev, Node&lt;K, V&gt; next) { this.prev = prev; this.next = next; } private long timeTillExpiraton() { return expirationTime - System.currentTimeMillis(); } private boolean isExpired() { return expirationTime - System.currentTimeMillis() &lt;= 0; } public void updateExpirationTime(long liveTime) { expirationTime = System.currentTimeMillis() + liveTime; } } private static class Cleaner&lt;K, V&gt; implements Runnable { private ExpiringKeyValueRepository&lt;K, V&gt; rep; private boolean stopped = true; private Lock writeLock; private Condition checkCondition; private Cleaner(ExpiringKeyValueRepository&lt;K, V&gt; repository) { this.rep = repository; this.writeLock = repository.writeLock; this.checkCondition = repository.checkCondition; } @Override public void run() { writeLock.lock(); try { while (!stopped) { while (rep.first != null &amp;&amp; rep.first.isExpired()) { rep.removeNoLock(rep.first.getKey()); }; long timeToWait = rep.first == null ? MAX_LIVE_TIME : rep.first.timeTillExpiraton(); try { checkCondition.await(timeToWait, TimeUnit.MILLISECONDS); } catch (InterruptedException e) {} ; } } finally { writeLock.unlock(); } } private void stop() { writeLock.lock(); try { if (!stopped) stopped = true; } finally { writeLock.unlock(); } } private boolean isRunning () { return !stopped; } } } </code></pre>
[]
[ { "body": "<p>Nice implementation, the code is well commented and easy to understand. My suggestions:</p>\n<h2>Design</h2>\n<p><code>Node</code> keeps two pointers for the previous and the next. The repository also keeps two pointers for the first and last node. I think that is because <code>HashMap</code> is not ordered. Have you considered using <code>LinkedHashMap</code>? It keeps the insertion order so the oldest nodes are always on top and you don't need to do all the linking/unlinking.</p>\n<p>To update the keepalive of one node in a <code>LinkedHashMap</code> you can remove, update and re-add the node.</p>\n<h2>Exception handling</h2>\n<ul>\n<li><p>Exception messages are missing in all exceptions. The JavaDoc helps but it's important to provide a message in the exception. It's odd that invoking <code>.get(key)</code> throws and <code>IllegalStateException</code> without a message.</p>\n</li>\n<li><p>Each method checks if the repository is started, otherwise throws an exception. To simplify that consider to start the repository directly in the constructor.</p>\n</li>\n</ul>\n<h2>Stopping the repository issue</h2>\n<pre><code>public class ExpiringKeyValueRepository&lt;K, V&gt; {\n //...\n synchronized public void stop() {\n //...\n try {\n cleaner.stop(); \n cleanerThread.join();\n } catch (InterruptedException e){};\n //...\n }\n private static class Cleaner&lt;K, V&gt; implements Runnable {\n //...\n @Override\n public void run() {\n //...\n while (!stopped) {\n //...\n long timeToWait = rep.first == null ? MAX_LIVE_TIME : rep.first.timeTillExpiraton();\n try {\n checkCondition.await(timeToWait, TimeUnit.MILLISECONDS);\n } catch (InterruptedException e) {} ;\n }\n //...\n }\n private void stop() {\n writeLock.lock();\n try {\n if (!stopped) \n stopped = true;\n } finally {\n writeLock.unlock();\n }\n }\n }\n}\n</code></pre>\n<p>Consider this scenario:</p>\n<ol>\n<li>Start the repository: the thread <code>cleaner</code> is launched.</li>\n<li>Add and remove all keys.</li>\n<li>There are no keys left so the <code>cleaner</code> decides to go to sleep forever.</li>\n<li>Stop the repository: the main thread sets <code>stopped=true</code> and waits for cleaner to stop (<code>.join</code>) but it will never happen because it's sleeping.</li>\n</ol>\n<p>Also the method <code>Cleaner#stop</code> is a little bit overkill. It is a private method that is invoked only by the parent class within an already synchronized method. I think it can be safely changed to:</p>\n<pre><code>private void stop(){\n stopped=true;\n}\n</code></pre>\n<h2>Alternative</h2>\n<p>The Google library <a href=\"https://mvnrepository.com/artifact/com.google.guava/guava\" rel=\"nofollow noreferrer\">Guava</a> provides <a href=\"https://guava.dev/releases/22.0/api/docs/com/google/common/cache/Cache.html\" rel=\"nofollow noreferrer\">Cache</a> that should fit your use case. See a simple usage:</p>\n<pre><code>Cache&lt;Integer, String&gt; cache = CacheBuilder.newBuilder()\n .expireAfterAccess(1000,TimeUnit.MILLISECONDS)\n .build();\n// Add entry\ncache.put(1, &quot;user1&quot;);\n// Get the value\nassertEquals(&quot;user1&quot;,cache.getIfPresent(1));\n// Refresh the entry (update keep alive)\ncache.getIfPresent(1);\n// Remove a key\ncache.invalidate(1);\nassertNull(cache.getIfPresent(1));\n// Clear all keys\ncache.cleanUp();\n</code></pre>\n<p>It is also thread-safe and can be used by multiple concurrent threads.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T10:28:20.997", "Id": "495795", "Score": "1", "body": "@Markc Thanks for so deep and detailed review.\n1. About usage of LinkedHashMap. I checked this option. The reason to not use it is that remove/add on timestamp update may cause map rehashing which is time consumed operation with map locking.\n2. Cleaner stopping issue. You are right, this is a bug. I will fix it by insertion of checkCondition.notify() in Cleaner#stop, so cleaner will wakeup, check flag and exit.\n3. As for other things you mentioned - you are right, I will fix it. Guava usage looks reasanable and I will check it too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T15:50:14.160", "Id": "498297", "Score": "0", "body": "@bw_dev I am glad I could help ;) If you are satisfied with this answer consider to accept it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T08:58:50.227", "Id": "251753", "ParentId": "251728", "Score": "3" } } ]
{ "AcceptedAnswerId": "251753", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T19:05:29.077", "Id": "251728", "Score": "6", "Tags": [ "java", "repository" ], "Title": "Expiring key/value repository. Java" }
251728
<p>I have an init predicate which asserts some facts. I would like to clean these up after execution.</p> <p>I'm running queries of the form <code>init, do_stuff, cleanup.</code>. I would rather not have a separate cleanup call if i can avoid it (because I forget to call it).</p> <p>I found this as a solution:</p> <pre><code>init:- assert(foo); not(retract(foo)). </code></pre> <p>Are there cases I would not want to do this or reasons why I shouldn't?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T21:02:26.587", "Id": "495763", "Score": "1", "body": "Just warning you prolog is not very active on this site. Only four questions on it were asked since January..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T16:51:20.440", "Id": "495821", "Score": "0", "body": "Wonder whether we can add it to the iftt bot that posts to Twitter. I will accept comments years from now as well :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T02:11:10.123", "Id": "495873", "Score": "2", "body": "Why not use `setup_call_cleanup` and create a meta predicate? `run_query(Init_fact, Goal) :- setup_call_cleanup(assert(Init_fact), Goal, retract(Init_fact)).`" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T20:19:29.457", "Id": "251732", "Score": "1", "Tags": [ "prolog" ], "Title": "Prolog destructor?" }
251732
<p>Have you ever written a python script, then got to a part where you have to get input from the user? I would assume your code went something like this:</p> <pre><code>user_input = int(input(&quot;Enter number: &quot;)) </code></pre> <p>Then you realized that if the player enters <code>&quot;keyboard spam&quot;</code>, then your program crashes. So you need to set up a while-loop exception type thing, like this:</p> <pre><code>while True: try: user_input = int(input(&quot;Enter number: &quot;)) break except: print(&quot;you screwed up, only number allowed&quot;) </code></pre> <p><em>Then</em>, you realize that your inputs must be in between 5 and 23 for the features of your program, so you just code <em>that</em> in too... All in all, this is taking a while and is a pain in the neck!!! What you need is a function that already does all of this for you!</p> <p>Enter my function:</p> <pre><code> def get_input(prompt, # string conditions *conditions, check_alpha=False, must_be_lowercase=False, must_be_uppercase=False, conditions_on_input=False, all_conditions_must_be_true=True, # now int conditions must_be_an_int=False, highest_range=100000, lowest_range=-100000, must_be_odd=False, must_be_even=False): if must_be_uppercase and must_be_lowercase: raise ValueError(&quot;The word cannot be both uppercase and lowercase!!!&quot;) if must_be_even and must_be_odd: raise ValueError(&quot;The word cannot be both even and odd!!!&quot;) while True: word_valid = True try: user_input = input(prompt) if must_be_an_int: # if the value must be an int try: number = int(user_input) if not lowest_range &lt; number &lt; highest_range: print(f&quot;Values must be between {lowest_range} and {highest_range}!&quot;) word_valid = False continue else: # the number is between the specified range if must_be_even: if not number % 2 == 0: print(&quot;Number must be even!&quot;) word_valid = False continue elif must_be_odd: if number % 2 == 0: print(&quot;Number must be odd!&quot;) word_valid = False continue except Exception: print(&quot;The word must be an integer!&quot;, user_input) word_valid = False continue if word_valid: return user_input else: # if the value must be a string if check_alpha: # here we have a boolean. If it is true, we check to make sure only letter are in the # user input if not user_input.isalpha(): print(&quot;Only alphabetic characters allowed!&quot;) word_valid = False continue if conditions_on_input: if all_conditions_must_be_true: for condition in conditions: if condition not in user_input: print(f&quot;You have not satisfied the condition that there must be '{condition}!'&quot;) word_valid = False continue else: condition_found = False for condition in conditions: if condition in user_input: condition_found = True break if not condition_found: print(f&quot;You must satisfy one of the following conditions: &quot;, end=&quot;\n&quot;) for condition in conditions: print(&quot;'&quot;, condition, &quot;'&quot;, sep=&quot;&quot;) print() word_valid = False continue if must_be_lowercase: for i in user_input: if not i.islower(): print(&quot;Letters must be lowercase! Try again!&quot;) word_valid = False continue elif must_be_uppercase: for i in user_input: if not i.isupper(): print(&quot;Letters must be uppercase! Try again!&quot;) word_valid = False continue if word_valid: return user_input except Exception: print(&quot;No funny business!! Try again!&quot;) </code></pre> <p>Although my function may be a bit chunky, it gets the job done. Note: All of the below features you use as parameters, not modifications to the function itself...</p> <h1>Features:</h1> <ul> <li><p>first you put in the prompt, nothing special here</p> </li> <li><p>next you put in letters (or numbers) you want in the program, each of those as a positional argument. These get classified as conditions. These only apply if the boolean <code>must_be_an_int</code> is <code>False</code>.</p> </li> <li><p>next, if you want to use the conditions, you must set the bool <code>conditions_on_input</code> to <code>True</code>, whose default value is <code>False</code>.</p> </li> <li><p>There are two ways to use the conditions. There is a) all of the conditions must be met, or b) only one of the conditions must be met. The way to toggle this is by use of the keyword <code>all_conditions_must_be_true</code>. It's default value is <code>True</code>.</p> </li> <li><p>Using the keyword <code>check_alpha</code> you can check whether or not the value must only be in the alphabet.</p> </li> <li><p>Setting the keyword <code>must_be_lowercase</code> to <code>True</code> makes it so that your must phrase must be completely lowercase, same with <code>must_be_uppercase</code>. <strong>NOTE</strong>: If you set both <code>must_be_uppercase</code> and <code>must_be_lowercase</code> to <code>True</code>, the program will raise an error.</p> </li> <li><p>Those are all of the string conditions. The next keyword is <code>must_be_an_int</code>. If it is <code>True</code>, it will NOT check any of the string conditions, it will only check the following integer conditions. If it is <code>False</code>, (its default value), it will only check the string and not the ints.</p> </li> <li><p><code>highest_range</code> and <code>lowest_range</code>, respectively are the highest and lowest ranges that your number can be. They are by default, one hundred thousand and negative one hundred thousand.</p> </li> <li><p><code>must_be_odd</code> and <code>must_be_even</code>. They are self-explanatory. Once again, if both are <code>True</code>, the program will raise an error.</p> </li> </ul> <p>I am thinking of ways to improve this and make this better, thanks for any feedback!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T02:00:49.773", "Id": "495872", "Score": "0", "body": "I haven't used Python in a few years, does it provide a type system where all those boolean arguments can be encapsulated into an \"options\" type argument that is declared beforehand and just passed in? In my experience multiple boolean arguments one after the other will get messed up at some point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T12:07:37.340", "Id": "495916", "Score": "0", "body": "@Casey You need to use keyword arguments for most of the variables..." } ]
[ { "body": "<p>As a toy to experiment with Python, fine. Please, please don't use this in real life. It's both impossible and counter-productive to try and predict every user input validation scenario, and you're better off writing and using only what you need.</p>\n<p>Anyway, specific Python concerns:</p>\n<p><code>condition not in user_input</code> suggests that <code>condition</code> should really just be called <code>substring</code> or <code>needle</code>.</p>\n<p>In this loop:</p>\n<pre><code> for i in user_input:\n if not i.isupper():\n print(&quot;Letters must be uppercase! Try again!&quot;)\n word_valid = False\n continue\n</code></pre>\n<p>Your <code>continue</code> should probably be a <code>break</code>; otherwise you're going to output that error message for every single lowercase letter.</p>\n<p>If you want to attempt something that is both simpler and more powerful, accept an iterable of tuples, each a predicate callback and an error message. On every iteration, call every callback, and if it fails, output its error message. If none of the callbacks fails, accept and return the input. Delete all of your range-checking, case-checking and alphanumeric checking logic.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T23:23:20.030", "Id": "495769", "Score": "5", "body": "Adding to Reinderien's answer: It could be in a library that includes predefined predicates for numbers, Yes/No, etc." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T21:10:52.747", "Id": "251734", "ParentId": "251733", "Score": "10" } }, { "body": "<p>Be specific when catching exceptions, and include only the essential, relevant code inside a try-except!</p>\n<p>For example:</p>\n<pre class=\"lang-py prettyprint-override\"><code> if must_be_an_int: # if the value must be an int\n try:\n number = int(user_input)\n if not lowest_range &lt; number &lt; highest_range:\n print(f&quot;Values must be between {lowest_range} and {highest_range}!&quot;)\n word_valid = False\n continue\n else: # the number is between the specified range\n if must_be_even:\n if not number % 2 == 0:\n print(&quot;Number must be even!&quot;)\n word_valid = False\n continue\n elif must_be_odd:\n if number % 2 == 0:\n print(&quot;Number must be odd!&quot;)\n word_valid = False\n continue\n except Exception:\n print(&quot;The word must be an integer!&quot;, user_input)\n word_valid = False\n continue\n if word_valid:\n return user_input\n</code></pre>\n<p>The purpose of the try-except is to check that the input is an int! As it stands, the code catches a bunch of random exceptions, and then treats them all as if they meant that the input isn't an int.</p>\n<pre class=\"lang-py prettyprint-override\"><code> if must_be_an_int: # if the value must be an int\n try:\n number = int(user_input)\n except ValueError:\n print(&quot;The word must be an integer!&quot;, user_input)\n word_valid = False\n continue\n if not lowest_range &lt; number &lt; highest_range:\n print(f&quot;Values must be between {lowest_range} and {highest_range}!&quot;)\n word_valid = False\n continue\n else: # the number is between the specified range\n if must_be_even:\n if not number % 2 == 0:\n print(&quot;Number must be even!&quot;)\n word_valid = False\n continue\n elif must_be_odd:\n if number % 2 == 0:\n print(&quot;Number must be odd!&quot;)\n word_valid = False\n continue\n if word_valid:\n return user_input\n</code></pre>\n<hr />\n<p>That code snippet above can be further improved, by removing the superfluous <code>word_valid</code> variable.</p>\n<pre class=\"lang-py prettyprint-override\"><code> if must_be_an_int: # if the value must be an int\n try:\n number = int(user_input)\n except ValueError:\n print(&quot;The word must be an integer!&quot;, user_input)\n continue\n if not lowest_range &lt; number &lt; highest_range:\n print(f&quot;Values must be between {lowest_range} and {highest_range}!&quot;)\n continue\n else: # the number is between the specified range\n if must_be_even:\n if not number % 2 == 0:\n print(&quot;Number must be even!&quot;)\n continue\n elif must_be_odd:\n if number % 2 == 0:\n print(&quot;Number must be odd!&quot;)\n continue\n return user_input\n</code></pre>\n<hr />\n<p>The if statement</p>\n<pre class=\"lang-py prettyprint-override\"><code>if not number % 2 == 0:\n</code></pre>\n<p>can be simplified to</p>\n<pre class=\"lang-py prettyprint-override\"><code>if number % 2 != 0:\n</code></pre>\n<p>which also makes it less ambiguous.</p>\n<hr />\n<pre class=\"lang-py prettyprint-override\"><code> if must_be_lowercase:\n for i in user_input:\n if not i.islower():\n print(&quot;Letters must be lowercase! Try again!&quot;)\n</code></pre>\n<p>It's best to keep names like <code>i</code> or <code>j</code> to refer to indices.</p>\n<p>Also, you can use <code>str.islower()</code> on the entire string at once, which means the loop is superfluous.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T01:51:09.627", "Id": "251792", "ParentId": "251733", "Score": "6" } }, { "body": "<h2>Suggestion: use an appropriate library</h2>\n<p>There is an amazing amount of Python libraries with tons of usefull functionality. Also for input processing. You can search <a href=\"https://pypi.org/\" rel=\"nofollow noreferrer\">PyPi</a> for libraries. I found <a href=\"https://pypi.org/project/PyInputPlus/\" rel=\"nofollow noreferrer\">PyInputPlus</a> actively maintained and pretty suitable for your requirements. The function <a href=\"https://pyinputplus.readthedocs.io/en/latest/index.html?highlight=inputint#pyinputplus.inputInt\" rel=\"nofollow noreferrer\">inputInt</a> covers almost all of it.</p>\n<p>Your code could (almost!) be reduced to:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>import pyinputplus as pyip\nuser_input = pyip.inputInt(prompt='Enter a number between 5 and 23: ', min=5, max=23)\n</code></pre>\n<p>Checking even and odd values might be done with regexes, which is also supported by <code>inputInt</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T20:50:43.143", "Id": "251831", "ParentId": "251733", "Score": "3" } } ]
{ "AcceptedAnswerId": "251792", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T20:28:38.733", "Id": "251733", "Score": "9", "Tags": [ "python", "python-3.x" ], "Title": "\"superior\" input function" }
251733
<p>Today's assignment states that I need to write a complete java program which will calculate the relative orthodromic distance between two sets of geographic coordinates declared by the user.</p> <p>When the user enters latitudes, it should be in degrees with negative numbers representing South latitudes. Similarly, the longitudes should be degrees with negative numbers representing West longitudes. The GCC program below will provide me with the correct positive and negative values. My program <em>must</em> print out the computed distance as an <strong>integer value rounded up</strong>. I am also required to use the &quot;add half and cast&quot; approach.</p> <p>When dealing with distances on a globe of the earth, I am able to compute this distance by solving the following formulas:</p> <p><em>RADIUS</em> = the radius of the earth = 6391.2 km, <strong>declare as a constant</strong></p> <p><em>lat1</em> = the latitude of the first place, <strong>user input</strong></p> <p><em>long1</em> = the longitude of the first place, <strong>user input</strong></p> <p><em>lat2</em> = the latitude of the second place, <strong>user input</strong></p> <p><em>long2</em> = the longitude of the second place, <strong>user input</strong></p> <p><em>lat1_rad</em> = <em>lat1</em> converted to radians</p> <p><em>long1_rad</em> = <em>long1</em> converted to radians</p> <p><em>lat2_rad</em> = <em>lat2</em> converted to radians</p> <p><em>long2_rad</em> = <em>long2</em> converted to radians</p> <p><em>x1</em> = sin(<em>lat1_rad</em>)</p> <p><em>z1</em> = cos(<em>lat1_rad</em>)</p> <p><em>x2</em> = sin(<em>lat2_rad</em>)</p> <p><em>z2</em> = cos(<em>lat2_rad</em>)</p> <p>The website listed below is called the Great Circle Mapper. It allows me to find the latitude and longitude for any airport in the world. I will be able to use these locations to find the distances and the shortest path between two points.</p> <p><a href="http://www.gcmap.com/" rel="nofollow noreferrer">http://www.gcmap.com/</a></p> <p>I am required to use the site to verify that my program is computing the correct results. I should also note that it is not a requirement for my distances to be <strong>identical</strong> to those given by GC Mapper; however, they should be reasonably close.</p> <p>Some example locations include:</p> <ol> <li>YQU - Grande Prairie airport</li> <li>YEG - Edmonton International airport</li> <li>LHR - London Heathrow Airport</li> <li>JFK - John F Kennedy International airport, New York</li> </ol> <p><em>Note: My professor used an Earth radius which is about 20 Km larger than the accepted mean Earth radius (since Earth is not perfectly spherical). This modification in radius gives results which are closer to those computed by GC Mapper (which uses a different algorithm for its computations).</em></p> <p><strong>Example run:</strong></p> <pre><code>Great Circle Distance Program Start Location Enter latitude :55.179722 Enter Longitude :-118.884999 End Location Enter latitude :51.4775 Enter Longitude :-0.461388 Computed Distance : 6890 Km </code></pre> <p><strong>The resulting code that I wrote to solve this problem is as follows:</strong></p> <pre><code>import java.util.Scanner; /** * SRN: 507-147-9 */ public class GCC_Program { public static void main(String[] args) { // new input Scanner input = new Scanner(System.in); // define vars final double radius = 6391.2; double lat1, long1, lat2, long2, lat1_rad, long1_rad, lat2_rad, long2_rad, x1, z1, x2, z2, x3, a; int distance; // Program name System.out.println(&quot;Great Circle Distance Program&quot;); // prompt coordinates System.out.println(); System.out.println(&quot;Start Location&quot;); System.out.print(&quot;Enter latitude : &quot;); //prompt lat1 lat1 = input.nextDouble(); // store input as &quot;lat1&quot; System.out.print(&quot;Enter longitude : &quot;); //prompt long1 long1 = input.nextDouble(); // store input as &quot;long1&quot; System.out.println(); System.out.println(&quot;End Location&quot;); System.out.print(&quot;Enter latitude : &quot;); //prompt lat2 lat2 = input.nextDouble(); // store input as &quot;lat2&quot; System.out.print(&quot;Enter longitude : &quot;); //prompt long2 long2 = input.nextDouble(); // store input as &quot;long2&quot; System.out.println(); // define formulas lat1_rad = Math.toRadians(lat1); long1_rad = Math.toRadians(long1); lat2_rad = Math.toRadians(lat2); long2_rad = Math.toRadians(long2); x1 = Math.sin(lat1_rad); z1 = Math.cos(lat1_rad); x2 = Math.sin(lat2_rad); z2 = Math.cos(lat2_rad); x3 = Math.cos(long2_rad - long1_rad); a = (x1 * x2) + (z1 * z2 * x3); distance = (int) ((radius * Math.acos(a)) + 0.5); // print results System.out.println(&quot;Computed Distance : &quot; + distance + &quot; Km&quot;); } } </code></pre> <p>With this, I do have a question regarding whether or not there's a way I can increase the accuracy of <strong>my</strong> computed distance in relation to the <strong>real-life</strong> computed distance, while simultaneously retaining the simplicity of the program? In other words, would I be able to implement a more accurate solution which doesn't stray too far from simple IO (input/output), arithmetic operators, Math methods, and conditional/iterative statements?</p> <p><em>EDIT: I am unable to find any documentation concerning the GCC algorithm, and therefore I'm at a crossroads of whether my code is accurate enough to hand in...</em></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T10:31:21.097", "Id": "497009", "Score": "1", "body": "Your code looks totally fine. If you need a more accurate solution, you need to user bigger datatypes and functions which make use of those datatypes. Maybe there are some scientific library available (I'm pretty sure there are some available.)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T21:27:39.180", "Id": "251735", "Score": "1", "Tags": [ "java", "beginner", "mathematics", "geospatial" ], "Title": "Great-circle distance in Java" }
251735
<p>I created <a href="https://www.edaplayground.com/x/Vfme" rel="nofollow noreferrer">this project on EDA Playground</a> that builds a variable-width 3-way multiplexer out of 2 variable-width 2-way multiplexers. It will be part of homework that I assign, so I want to follow all best practices. I followed the <a href="https://github.com/lowRISC/style-guides/blob/master/VerilogCodingStyle.md" rel="nofollow noreferrer">lowRISC Verilog Coding Style Guide</a>.</p> <p><strong>Design Modules</strong></p> <pre><code>module mux2 #( parameter Width = 4 ) ( input control, input [Width-1:0] a, input [Width-1:0] b, output [Width-1:0] y ); assign y = control ? b : a; endmodule module mux3 #( parameter Width = 4 ) ( input [1:0] control, input [Width-1:0] a, input [Width-1:0] b, input [Width-1:0] c, output [Width-1:0] y ); wire [Width-1:0] mux_a_out; mux2 #( .Width (Width) ) mux_a ( .control (control[0]), .a (a), .b (b), .y (mux_a_out) ); mux2 #( .Width (Width) ) mux_b ( .control (control[1]), .a (mux_a_out), .b (c), .y (y) ); endmodule </code></pre> <p><strong>Test Module</strong></p> <pre><code>module test; reg[1:0] control; reg[7:0] a; reg[7:0] b; reg[7:0] c; reg[7:0] y; mux3 #( .Width(8) ) mux3( .control (control), .a (a), .b (b), .c (c), .y (y) ); initial begin a = &quot;A&quot;; b = &quot;B&quot;; c = &quot;C&quot;; for (int i = 0; i &lt; 3; i++) begin control = i; #1 $display(&quot;When Control = %d, Y = %c&quot;, control, y); end end endmodule </code></pre>
[]
[ { "body": "<p>I don't see any problems with the code functionally, and the layout follows good practices for the most part. That style guide seems mostly reasonable, and it is a good idea to use a set of guidelines.</p>\n<p>In my many years of Verilog coding, I have most frequently seen parameters use all capital letters (this departs from the guide you posted):</p>\n<p>Use <code>WIDTH</code> instead of <code>Width</code>.</p>\n<p>The guide recommends 2-space indents in some places and 4 in others; I recommend <strong>4-space</strong> indent everywhere because I think it is much easier to read.</p>\n<p>I don't think your <code>for</code> loop follows the guide. I would lay it out like this:</p>\n<pre><code>for (int i = 0; i &lt; 3; i++) begin\n control = i;\n #1\n $display(&quot;When Control = %d, Y = %c&quot;, control, y);\nend\n</code></pre>\n<p>I would also add a space between <code>reg</code> and <code>[</code>:</p>\n<pre><code> reg [1:0] control;\n reg [7:0] a;\n reg [7:0] b;\n reg [7:0] c;\n reg [7:0] y;\n</code></pre>\n<p>I usually find it helpful for debugging to also display the time (copied from my Answer to your previous Verilog Question):</p>\n<pre><code>$display($time, &quot; When Control = %d, Y = %c&quot;, control, y);\n</code></pre>\n<p>The <code>for</code> loop exercises 3 of the 4 possible values of <code>Control</code>. It is a good practice to simulate all possibilities (<code>Control</code> = 3). Perhaps make it an extra-credit question to explain what happens and why.</p>\n<hr />\n<p>I assume one of the goals of this assignment is to demonstrate module hierarchy using an extremely simple design. Otherwise, your design modules normally would be replaced with a single <code>assign</code> statement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T23:46:43.740", "Id": "496038", "Score": "0", "body": "Thank you! Your feedback is helpful, and your assumption is correct." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T14:18:36.627", "Id": "251815", "ParentId": "251739", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T23:07:16.947", "Id": "251739", "Score": "2", "Tags": [ "verilog" ], "Title": "3-way multiplexer built on 2-way multiplexers in Verilog" }
251739
<p>I'm trying to refactor the working code below which intends to handle bill cancellation, but doesn't seem &quot;linear&quot; enough.</p> <pre><code>open FSharpPlus open FSharpPlus.Data type BillCancellationReason = | A | B type OrderBillingCommand = | A | B type OrderBillingEvent = | A | B type CommandError = | A | B type BillCancellationRequest = { BillSequence: int32 Reason: BillCancellationReason Comment: string } type BillCancellationsRequestPart = { OrderId: int32 BillSequence: int32 Reason: BillCancellationReason Comment: string } type BillCancellationsRequest = BillCancellationsRequestPart list module Validation = // Validation&lt;'Failure list, 'Success&gt; list -&gt; Validation&lt;'Failure list, 'Success list&gt; let cumulativeFoldList (validations: Validation&lt;'Failure list, 'Success&gt; list): Validation&lt;'Failure list, 'Success list&gt; = traverse id validations // BillCancellationsRequestPart -&gt; Validation&lt;CommandError list, (int32 * OrderBillingCommand)&gt; let toCommand (requestPart: BillCancellationsRequestPart) = Unchecked.defaultof&lt;Validation&lt;CommandError list, (int32 * OrderBillingCommand)&gt;&gt; // (int32 * OrderBillingCommand) list -&gt; Async&lt;Result&lt;OrderBillingEvent list, CommandError list&gt;&gt; let processValidCommands (commands: (int32 * OrderBillingCommand) list) = Unchecked.defaultof&lt;Async&lt;Result&lt;OrderBillingEvent list, CommandError list&gt;&gt;&gt; // BillCancellationsRequest -&gt; Async&lt;Result&lt;OrderBillingEvent list,CommandError list&gt;&gt; let cancelBills (request: BillCancellationsRequest) = async { match request |&gt; List.map toCommand |&gt; Validation.cumulativeFoldList with | Success commands -&gt; return! processValidCommands commands | Failure failure -&gt; return Error failure } </code></pre> <p>In particular this last bit:</p> <pre><code>// BillCancellationsRequest -&gt; Async&lt;Result&lt;OrderBillingEvent list,CommandError list&gt;&gt; let cancelBills (request: BillCancellationsRequest) = async { match request |&gt; List.map toCommand |&gt; Validation.cumulativeFoldList with | Success commands -&gt; return! processValidCommands commands | Failure failure -&gt; return Error failure } </code></pre> <p>I tried to come up with a new module but I found myself rolling a lot more code:</p> <pre><code> module Result = // ('T -&gt; 'U) -&gt; ('V -&gt; 'W) -&gt; Result&lt;'T, 'V&gt; -&gt; Result&lt;'U, 'W&gt; let bimap okMapping errorMapping result = result |&gt; Result.map okMapping |&gt; Result.mapError errorMapping // Result&lt;Async&lt;'T&gt;, 'U&gt; -&gt; Async&lt;Result&lt;'T, 'U&gt;&gt; let awaitOnOk result = async { match result with | Ok ok -&gt; let! awaitedOk = ok return Ok awaitedOk | Error error -&gt; return Error error } // BillCancellationsRequest -&gt; Async&lt;Result&lt;OrderBillingEvent list,CommandError list&gt;&gt; let cancelBills (request: BillCancellationsRequest) = request |&gt; List.map toCommand |&gt; Validation.cumulativeFoldList |&gt; Validation.toResult |&gt; Result.map processValidCommands |&gt; Result.awaitOnOk |&gt; Async.map Result.flatten </code></pre> <p>I'm wondering if there is like a better and more concise approach to achieve that?</p> <p>Note: <code>Unchecked.defaultof&lt;...&gt;</code> has been used just for the sake of making the code above to compile.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T20:18:27.600", "Id": "495842", "Score": "2", "body": "@BCdotWEB don't you think that \"nested\" is making the question specific enough? Not criticizing what you're saying, I just found my question pretty clear and well-scoped." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T20:28:58.257", "Id": "495844", "Score": "3", "body": "Your question is clear and well-scoped, but your title should **only state the task accomplished by your code**." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T22:29:07.887", "Id": "495854", "Score": "1", "body": "@AryanParekh \"ahhhh\" alright sorry, didn't get that right, so in my case saying something like \"F#: handling bills cancellation\" is okay?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T22:45:43.800", "Id": "495859", "Score": "1", "body": "Yes, whatever you think best titles your code :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T01:39:19.370", "Id": "495870", "Score": "1", "body": "@AryanParekh alrighty, hope this is good enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T08:44:45.730", "Id": "495902", "Score": "1", "body": "I think it would be better if your script compiles. I mean, there are some business types and functions missing. You can create dummy ones." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T14:38:35.833", "Id": "495932", "Score": "0", "body": "@Gus sure will add those tonite." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T00:51:47.537", "Id": "496147", "Score": "0", "body": "@Gus I added the relevant type info" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T17:02:52.697", "Id": "496194", "Score": "0", "body": "Still missing `AddressFormatError`, `BillCancellationReason`, `CommandError`, `OrderAcl` and `Handlers`." } ]
[ { "body": "<p>To be honest, your original implementation of <code>cancelBills</code> looks pretty good - it's very focused and is fairly easy to understand what it's doing even without much context.</p>\n<p>If you really want to write the function as a single chain of functions then your alternative version is most of the way there. I'd consider replacing the last three functions in the chain with a single <code>Result.asyncBind</code> function to simplify it somewhat, i.e.</p>\n<pre><code>module Result =\n let asyncBind (asyncBinder: 'T -&gt; Async&lt;Result&lt;'U, 'TError&gt;&gt;) (result: Result&lt;'T, 'TError&gt;) =\n match result with\n | Result.Ok value -&gt; asyncBinder value\n | Result.Error error -&gt; async { return Result.Error error }\n</code></pre>\n<p>This is effectively just an <code>async</code> equivalent of the built-in <code>Result.bind</code>, so shouldn't add much overhead when reading the code and should be fairly re-usable if you're piping <code>Result</code> and <code>Async</code> around a lot. That being said, if you're not going to be re-using <code>Result.asyncBind</code> (or your equivalent function chain) then just stick with your original implementation of <code>cancelBills</code>!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T17:08:44.973", "Id": "499612", "Score": "0", "body": "thanks Rob for your input!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T15:51:03.053", "Id": "253347", "ParentId": "251740", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T23:27:02.723", "Id": "251740", "Score": "4", "Tags": [ "f#" ], "Title": "Handling bill cancellation" }
251740
<p><strong>So I have two PHP files that execute SQL code in them. It's a simple registration script and an account recover script.</strong></p> <p>I want to know is my code safe from SQL exploits &amp; other exploits? Here's how my code works.</p> <ol> <li><p>how my registration system works</p> <p>a person goes to my url with specified data such as the following example.</p> <blockquote> <p><code>http://localhost/registeruser.php?identity=438746285267827419&amp;idnumber=2201</code></p> </blockquote> </li> <li><p>how my recovery account system works</p> <p>user goes to this url with this specified data passed through.</p> <blockquote> <p><code>http://localhost/accountrecovery.php?secretcode=GU3DZ99S4D73D9G7H</code></p> </blockquote> </li> </ol> <p>Below is the code for my following files</p> <ul> <li>registeruser.php</li> <li>accountrecovery.php</li> </ul> <h2>registeruser.php</h2> <pre><code>&lt;?php setcookie('timerValueHolder', 0); ?&gt; &lt;?php if (!isset($_SESSION)) session_start(); $timeCurrently = round(microtime(true)); $UserRegTime = (isset($_SESSION[&quot;timeLastAccessed&quot;])) ? $_SESSION[&quot;timeLastAccessed&quot;] : '0'; if (($timeCurrently - $UserRegTime) &gt; 3) { $_SESSION['timeLastAccessed'] = $timeCurrently; } else { header('refresh: 1'); die(&quot;cannot continue because you must wait &quot; . (3 - ($timeCurrently - $UserRegTime)) . &quot; seconds.&quot;); } $title = &quot;User registration&quot;; require_once (&quot;header.php&quot;); $passedInfo = $_GET['identity']; $passedInfoTwo = $_GET['idnumber']; if (strlen(trim($passedInfoTwo)) &lt; 1) { echo &quot;Invalid identification number of your account.&quot;; setcookie('timerValueHolder', 0); } if (strlen(trim($passedInfo)) &lt; 1) { echo &quot;Invalid identification number of your account.&quot;; setcookie('timerValueHolder', 0); } if ($_COOKIE['timerValueHolder'] &gt;= 0) { if (strlen(trim($passedInfo)) &gt; 0) { if (!isset($_COOKIE['timerValueHolder'])) { setcookie('timerValueHolder', 0); } if (isset($_COOKIE['timerValueHolder']) &amp;&amp; $_COOKIE['timerValueHolder'] &lt; 4) { $servername = &quot;localhost&quot;; $username = &quot;admin&quot;; $password = &quot;abc123&quot;; $dbname = &quot;databaseholder&quot;; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn-&gt;connect_error) { die(&quot;Failed to Complete Connection: &quot; . $conn-&gt;connect_error); } $usersIPAddress = $_SERVER['REMOTE_ADDR']; $checkAction = mysqli_real_escape_string($conn, &quot;select * from userconfiguration where membersID='$passedInfo' and MemberName&lt;&gt;''&quot;); if ($checkAction &gt; 0) { $checkActionRows = mysqli_num_rows($checkAction); if ($checkActionRows &gt; 0) { echo &quot;please wait as web page refreshes until you see a successful message.&quot;; } } else { $secondaryCheck = mysqli_real_escape_string($conn, &quot;select * from userconfiguration where ipaddress='$usersIPAddress' and membersID='$passedInfo'&quot;); if ($secondaryCheck &gt; 0) { $rowCheckTwo = mysqli_num_rows($secondaryCheck); if ($rowCheckTwo &gt; 0) { echo &quot;please wait as web page refreshes until you see a successful message.&quot;; } } else { $sql = &quot;INSERT INTO userconfiguration (ipaddress, membersID, TheirName) VALUES ('$usersIPAddress', '$passedInfo', '$passedInfoTwo')&quot;; if ($conn-&gt;query($sql) === true and $secondaryCheck &gt; 0 and $rowCheckTwo &gt; 0) { echo &quot;please wait as web page refreshes until you see a successful message.&quot;; } else { echo &quot;please wait as web page refreshes until you see a successful message.&quot;; } } } $conn-&gt;close(); $current_val = $_COOKIE['timerValueHolder']; $current_val++; setcookie('timerValueHolder', $current_val); echo $_COOKIE['timerValueHolder']; header('refresh: 4'); } else { echo &quot;success. go on to our application and finalize the registry by typing #finalizeregister &quot;; echo $_GET['identity']; setcookie('timerValueHolder', 0); } } } ?&gt; </code></pre> <h2>accountrecovery.php</h2> <pre><code>&lt;?php setcookie('timerValueHolder', 0); ?&gt; &lt;?php if (!isset($_SESSION)) session_start(); $timeCurrently = round(microtime(true)); $UserRegTime = (isset($_SESSION[&quot;timeLastAccessed&quot;])) ? $_SESSION[&quot;timeLastAccessed&quot;] : '0'; if (($timeCurrently - $UserRegTime) &gt; 3) { $_SESSION['timeLastAccessed'] = $timeCurrently; } else { header('refresh: 1'); die(&quot;cannot continue because you must wait &quot; . (3 - ($timeCurrently - $UserRegTime)) . &quot; seconds.&quot;); } $title = &quot;user recovery&quot;; require_once ('header.php'); $servername = &quot;localhost&quot;; $username = &quot;admin&quot;; $password = &quot;abc123&quot;; $dbname = &quot;databaseholder&quot;; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn-&gt;connect_error) { die(&quot;Failed to Complete Connectio: &quot; . $conn-&gt;connect_error); } $passedData = $_GET['secretcode']; $dataPassedTwo = mysqli_real_escape_string($conn, $passedData); $actionCheck = mysqli_query($conn, &quot;select * from userconfiguration where recoveryCode='$dataPassedTwo'&quot;); $rowCheckAction = mysqli_num_rows($actionCheck); $rowCount = mysqli_fetch_row($actionCheck); if ($rowCheckAction &gt; 0 and strlen(trim($passedData)) &gt; 0) { echo &quot;account recover details are &quot;; echo &quot; your password: &quot;, $rowCount[4]; echo &quot; your security pin: &quot;, $rowCount[5]; echo &quot;to recover your account in the future you must do the following task.&quot;; echo &quot;in our application type #finalizeregister to obtain a new recovery code.&quot;; $update = mysqli_query($conn, &quot;UPDATE userconfiguration SET recoveryCode = '' WHERE recoveryCode = '$dataPassedTwo'&quot;); if (!$update) { echo &quot;An issue has occured in the update task.&quot;; } } else { echo &quot;failed to recover account. try typing #finalizeregister in our application for a new code to generate.&quot;; } $conn-&gt;close(); ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T08:37:44.870", "Id": "495779", "Score": "3", "body": "I see lots of \"interesting\" code here. Tell me why you are doing this: `session_start();\nif (!isset($_SESSION)) session_start();`. Have you heard of \"prepared statements\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T09:01:21.287", "Id": "495783", "Score": "2", "body": "Welcome to Code Review, please [edit] your question so that it only states the **task accomplished by the code**, anything else belongs to the body of the question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T11:49:55.540", "Id": "495798", "Score": "1", "body": "@mickmackusa\n\nwow... i didn't notice the part you pointed out before expressing the usefulness of prepared statements ty brother i will fix that. but mick, can't you say if i use escape strings & if I use 'utf8mb4' format for mysql database it might as well be as safe as prepared statements?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T11:59:27.510", "Id": "495799", "Score": "2", "body": "@AryanParekh thank you for the advice i formatted my post as best as I could in regards to your response." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T12:36:40.223", "Id": "495800", "Score": "1", "body": "https://security.stackexchange.com/q/116670/208614" } ]
[ { "body": "<p>No, your code is not safe. Far from it. It's purely broken. Let's get into details.</p>\n<h1>Registration</h1>\n<p>I will go through the full code line by line and point each problem with it.</p>\n<ol>\n<li>Why is your script divided into two parts? What is the purpose of\n<pre><code>&lt;?php\nsetcookie('timerValueHolder', 0);\n?&gt;\n</code></pre>\nIf this is part of your PHP logic then why escape into HTML context and then back into PHP? You really should name your cookies better. Each name should clearly describe the purpose.</li>\n<li>Why is your <code>session_start()</code> conditional? This is an indicator that you are losing control of your source code and it might be a spaghetti code. A session should be started only once per each execution of the script.</li>\n<li>Why <code>round(microtime(true))</code>? Why not simply <code>time()</code>?</li>\n<li>Use null-coalesce operator instead of ternary operator.\n<pre><code>$UserRegTime = isset($_SESSION[&quot;timeLastAccessed&quot;]) ? $_SESSION[&quot;timeLastAccessed&quot;] : '0';\n// change to\n$UserRegTime = $_SESSION[&quot;timeLastAccessed&quot;] ?? 0;\n</code></pre>\n</li>\n<li>Using <code>die()</code> in a web application is not recommended. Try to redesign your code to avoid dying at all.</li>\n<li>What is <code>require_once &quot;header.php&quot;;</code>? Why are you including some random file in the middle of executing something else?</li>\n<li>You never check for the existence of your GET values. How about using <code>filter_input()</code> instead?</li>\n<li>Again, the names of your variables don't describe the contents properly. What is <code>$passedInfo</code> and <code>$passedInfoTwo</code>?</li>\n<li><code>strlen(trim($passedInfoTwo)) &lt; 1</code> means &quot;if non-zero byte long string&quot;. You can just do <code>if (!trim($passedInfoTwo))</code></li>\n<li>Why do repeat <code>setcookie('timerValueHolder', 0);</code> several times? You already sent that cookie.</li>\n<li>Why is <code>echo &quot;Invalid identification number of your account.&quot;;</code> repeated twice? Should it be two different messages? Are they meant to be validation messages? Why does the script continue execution despite having no values?</li>\n<li><code>if (isset($_COOKIE['timerValueHolder'])</code> inside of <code>if ($_COOKIE['timerValueHolder'] &gt;= 0)</code> ???</li>\n</ol>\n<p>At this point I lost interest in trying to figure out what you are doing with user input. Cookies, GET, Sesssion. What does it all mean? What are you trying to achieve?</p>\n<h1>MySQLi</h1>\n<ol>\n<li>Why are you using mysqli? Why do you have variables for mysqli arguments? Why are these values hardcoded?</li>\n<li>You should enable error reporting for mysqli. Add this line before <code>new mysqli</code>:\n<pre><code>mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\n</code></pre>\n</li>\n<li>NEVER check for mysqli connection errors manually and <strong>NEVER</strong> display them to the user! Remove the whole <code>if</code> statement after <code>new mysqli</code>.</li>\n<li>Set the correct charset. The correct one for MySQL should be <code>utf8mb4</code> unless you are using something else. If you use anything else then why?</li>\n<li><code>mysqli_real_escape_string</code> does not do what you think it does. I don't even know what you think it does. The next few lines of code make no sense at all. Just remove it all.</li>\n<li>Your code is wide open to SQL injection! You must use prepared statements. Always bind values as parameters.</li>\n</ol>\n<p>Assuming you wanted to perform some kind of existance check in your database the code should look something like this.</p>\n<pre><code>mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\n$mysqli = new mysqli('localhost', 'username from ENV', 'pass from ENV', 'databaseholder');\n$mysqli-&gt;set_charset('utf8mb4');\n\n$stmt = $mysqli-&gt;prepare('SELECT COUNT(*) FROM userconfiguration WHERE membersID=? AND (MemberName&lt;&gt;&quot;&quot; OR ipaddress=?)');\n$stmt-&gt;bind_param('ss', $passedInfo, $usersIPAddress);\n$stmt-&gt;execute();\n$result = $stmt-&gt;get_result();\n$exists = (bool) $result-&gt;fetch_row[0];\n\nif($exists) {\n // error message to the user\n}\n</code></pre>\n<p>Same for the insert. Remove that <code>if</code> statement. Use a prepared statement.</p>\n<pre><code>$stmt = $mysqli-&gt;prepare('INSERT INTO userconfiguration (ipaddress, membersID, TheirName) VALUES(?,?,?)');\n$stmt-&gt;bind_param('sss', $usersIPAddress, $passedInfo, $passedInfoTwo);\n$stmt-&gt;execute();\n</code></pre>\n<h1>Security</h1>\n<p>Your obvious problem is the glaring SQL injection. For this reason alone that code should be scraped and written again. Preferably using PDO this time. You must always bind data using SQL parameters.</p>\n<p>I have no idea what you are doing with cookies. I would not trust the user with the cookies and I see no reason to use them in your code at all.</p>\n<p>You are inserting data taken from GET. GET as the name suggests should be used to get the data from PHP not add it. To add data use POST method. This prevents crawlers, previews and other stuff like this from accidentally executing your code. <strong>GET operations should be idempotent</strong> and should not cause side effects.</p>\n<p>Your <code>recoveryCode</code> is actually a password that is called something else. You should never ever store passwords on your server. Such things should be hashed and salted. PHP has a function for this called <code>password_hash()</code>. <strong>Secret code</strong> is not secret if your server knows it.</p>\n<p>Your code is also vulnerable to XSS although it's difficult to assess to what degree. Do some research about printing data in documents like HTML. You must properly format the data so that it can never be interpreted as HTML code.</p>\n<p>There are also other problems, but I have not enough information to talk about them here. What is <code>identity</code> in your URL? What is <code>idnumber</code>? Are these sequential numbers? If not how much entropy do they have? Can I guess it? Your <code>secretcode</code> certainly does not look like it has enough entropy. How is it created?</p>\n<p>HTTP? Surely, this is only for development on localhost, right? If you ever expose this to the internet you must use HTTPS.</p>\n<h1>Conclusion</h1>\n<p>This code has plenty of flaws. In fact, it has so many problems that I deem it unfixable. Delete all of it and before you start writing it again spend a number of days reading about web security. There are plenty of good resources online. <a href=\"https://paragonie.com/\" rel=\"noreferrer\">https://paragonie.com/</a> has some good articles on their blog. <a href=\"https://stackoverflow.com/\">https://stackoverflow.com/</a> and <a href=\"https://security.stackexchange.com/\">https://security.stackexchange.com/</a> also have plenty of good information.</p>\n<p>When you start writing this again, use a proper IDE with syntax highlighting and syntax checking. Format the code properly. Read about PHP PSR standards. If you are unsure about something do some reading instead of copying code or trying to guess how it works.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T02:13:30.003", "Id": "495874", "Score": "0", "body": "honeestly as harash as you were (LOL) i am happy that u were XD my brother your response was above & beyond helpful. i cant express how f****** appreciative i am of you for taking the initative and putting my code and me in it's place. this is just what i needed. tysm brotha <3, so as we speak I am implementing every single detail u pointed out which needed fixed. ur an angel man im going to le4ave this question open if all else fails but for-reals the time, effort, & patience that went into ur post, i am learning alot and i do not feel confused thanks to u. bless u my man. @Dharman" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T09:35:13.673", "Id": "495904", "Score": "1", "body": "@ZERO I would like to add that you should not be accessing any additional resources until all required user input is validated. This mean that you check the quality of `$_GET['secretcode'];` BEFORE you bother to make any trips to the database. For this reason, you shouldn't even bother connecting to the database before you determine that it is necessary to do so. Also, while in the context of this question point #9 is true, it is not always true. https://3v4l.org/tQm31" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T10:33:22.933", "Id": "495909", "Score": "0", "body": "@mickmackusa thank you for staying on top still responding to my post. what you've stated i've documented in my sticky-notes & am reading it over it again & again to engrain these fundamentals in my skull obviously dont want to overlook somthing and miss even the slightest detail leaving my code insecure. I surely am starting to grasp what u guys are teaching me. appreciate it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T10:36:28.247", "Id": "495910", "Score": "0", "body": "stackexchange, thank-you for all the help it's nice having people actually provide details that actually improve my programming skills. just for awareness of my post, i'm going to leave it open a little bit longer but as of now rewriting my code with all the help responses is going in my favor." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T11:03:18.580", "Id": "495912", "Score": "0", "body": "@ZERO I personally invited Dharman to offer a review on this question because I absolutely knew that he would be able to offer a comprehensive review. I have done this several times before (like this guy who I met through Joomla connections: https://codereview.stackexchange.com/a/244209/141885). I always like to see people receive great reviews -- I am not always the best person for the job." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T14:46:38.290", "Id": "251760", "ParentId": "251744", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T03:22:35.367", "Id": "251744", "Score": "2", "Tags": [ "php", "mysql" ], "Title": "Is execution of sql in my php code safe?" }
251744
<p>Can you please give your feedback to my double linked list implementation below? It comes with some very basic functions as well as separate code to test the implementation. The tests are only 'success' tests. I used valgrind to catch and fix any kind of memory-related issues that I came across and valgrind did not report any issues with the implementation. If it matters, I am running this under macOS; I do not know if valgrind on Linux systems would produce errors or warnings with the code.</p> <p>Apologies in advance if the naming convention is a bit verbose or not like any C naming convention; I am still very new to C and my knowledge on naming conventions is limited.</p> <p>DoubleLinkedList.h</p> <pre><code>#ifndef DOUBLELINKEDLIST_H #define DOUBLELINKEDLIST_H // error codes static const int ENOMEMORY = -1; // Could not allocate memory static const int ENULLIST = -2; // The list is null; memory could not have been allocated to it static const int EEMPTYNODE = -3; // The node is null typedef struct DoubleLinkedList_Node { void* data; struct DoubleLinkedList_Node* next; struct DoubleLinkedList_Node* previous; } DoubleLinkedList_Node; typedef struct DoubleLinkedList { DoubleLinkedList_Node* head; DoubleLinkedList_Node* tail; } DoubleLinkedList; unsigned int DoubleLinkedList_Count(DoubleLinkedList *list); DoubleLinkedList *DoubleLinkedList_Initialize(void); int DoubleLinkedList_Destroy(DoubleLinkedList *list); int DoubleLinkedList_Add(DoubleLinkedList *list, void *data_to_add); DoubleLinkedList_Node *DoubleLinkedList_GetNode(DoubleLinkedList *list, void *data_to_search); int DoubleLinkedList_GetNodes(DoubleLinkedList *list, void *data_to_search, DoubleLinkedList *return_list); int DoubleLinkedList_Foreach(DoubleLinkedList *list, void (DoubleLinkedList_Node *callback)); int DoubleLinkedList_ForeachReverse(DoubleLinkedList *list, void (DoubleLinkedList_Node *callback)); int DoubleLinkedList_Clear(DoubleLinkedList *list); int DoubleLinkedList_Remove(DoubleLinkedList *list, DoubleLinkedList_Node *node_to_remove); int DoubleLinkedList_Find(DoubleLinkedList *list, void *data_to_find, DoubleLinkedList *return_list); #endif //DOUBLELINKEDLIST_H </code></pre> <p>DoubleLinkedList.c</p> <pre><code>#include &lt;stdlib.h&gt; #include &quot;DoubleLinkedList.h&quot; unsigned int DoubleLinkedList_Count(DoubleLinkedList *list) { if (!list) return ENULLIST; unsigned int count = 0; DoubleLinkedList_Node *current_node = list-&gt;head-&gt;next; while (current_node != list-&gt;tail) { count++; current_node = current_node-&gt;next; } return count; } DoubleLinkedList* DoubleLinkedList_Initialize(void) { DoubleLinkedList* return_value = calloc(1, sizeof(DoubleLinkedList)); if (return_value) { return_value-&gt;head = calloc(1, sizeof(DoubleLinkedList_Node)); return_value-&gt;tail = calloc(1, sizeof(DoubleLinkedList_Node)); if (return_value-&gt;head &amp;&amp; return_value-&gt;tail) { return_value-&gt;head-&gt;next = return_value-&gt;tail;// connect the head to the tail return_value-&gt;tail-&gt;previous = return_value-&gt;head;// connect the tail to the head return_value-&gt;tail-&gt;data = NULL; return_value-&gt;tail-&gt;next = NULL; return_value-&gt;head-&gt;previous = NULL; return return_value; } } return NULL; } int DoubleLinkedList_Destroy(DoubleLinkedList* list) { if (!list) return ENULLIST; while (list-&gt;head) { DoubleLinkedList_Node* node_to_free = list-&gt;head; list-&gt;head = list-&gt;head-&gt;next; free(node_to_free); node_to_free = NULL; } free(list-&gt;head); list-&gt;head = NULL; free(list); list = NULL; return 0; } int DoubleLinkedList_Add(DoubleLinkedList *list, void *data_to_add) { DoubleLinkedList_Node* new_node = calloc(1, sizeof(DoubleLinkedList_Node)); if (!new_node) return ENOMEMORY; list-&gt;tail-&gt;data = data_to_add; new_node-&gt;data = NULL; new_node-&gt;next = NULL; new_node-&gt;previous = list-&gt;tail; // make the new node the tail list-&gt;tail-&gt;next = new_node; //current tail is now the second to the last node list-&gt;tail = new_node; return 0; } DoubleLinkedList_Node* DoubleLinkedList_GetNode(DoubleLinkedList* list, void* data_to_search) { // from head, iterate through the list to find the data DoubleLinkedList_Node* return_value = list-&gt;head; while (return_value) { if (return_value-&gt;data == data_to_search &amp;&amp; return_value != list-&gt;head &amp;&amp; return_value != list-&gt;tail) { return return_value; } // move to the next node return_value = return_value-&gt;next; } // at this point, we went through the entire list but couldn't find the value; return NULL return NULL; } int DoubleLinkedList_Foreach(DoubleLinkedList* list, void (*callback)(DoubleLinkedList_Node *)) { if (!list) return ENULLIST; DoubleLinkedList_Node* currentNode = list-&gt;head; while (currentNode != list-&gt;tail) { // don't include the head and the tail in the evaluation if (currentNode != list-&gt;head &amp;&amp; currentNode != list-&gt;tail) { callback(currentNode); } currentNode = currentNode-&gt;next; } return 0; } int DoubleLinkedList_ForeachReverse(DoubleLinkedList *list, void(*callback) (DoubleLinkedList_Node *)) { if (!list) return ENULLIST; DoubleLinkedList_Node *currentNode = list-&gt;tail; while (currentNode != list-&gt;head) { // don't include the head and the tail in the evaluation if (currentNode != list-&gt;head &amp;&amp; currentNode != list-&gt;tail) { callback(currentNode); } currentNode = currentNode-&gt;previous; } return 0; } int DoubleLinkedList_Clear(DoubleLinkedList *list) { if (!list) return ENULLIST; DoubleLinkedList_Node *currentNode = list-&gt;head-&gt;next; while (currentNode != list-&gt;tail) { currentNode = currentNode-&gt;next; free(currentNode-&gt;previous); currentNode-&gt;previous = NULL; } // reconnect the head to the tail and the tail to the head list-&gt;head-&gt;next = list-&gt;tail; // connect the head to the tail list-&gt;tail-&gt;previous = list-&gt;head; // connect the tail to the head list-&gt;tail-&gt;data = NULL; list-&gt;tail-&gt;next = NULL; list-&gt;head-&gt;previous = NULL; return 0; } int DoubleLinkedList_Remove(DoubleLinkedList *list, DoubleLinkedList_Node *node_to_remove) { if (!list) return ENULLIST; if (!node_to_remove) return EEMPTYNODE; DoubleLinkedList_Node *current_node = list-&gt;head-&gt;next; while (current_node != list-&gt;tail) { if (current_node-&gt;data == node_to_remove-&gt;data) { // connect the currentNode's previous to its next and vice-versa current_node-&gt;previous-&gt;next = current_node-&gt;next; current_node-&gt;next-&gt;previous = current_node-&gt;previous; free(current_node); current_node = NULL; return 0; } current_node = current_node-&gt;next; } // at this point, the record has not found. return 0; } int DoubleLinkedList_GetNodes(DoubleLinkedList *list, void *data_to_search, DoubleLinkedList *return_list) { if (!list) return ENULLIST; if (!return_list) return ENULLIST; DoubleLinkedList_Node *current_node = list-&gt;head-&gt;next; while (current_node != list-&gt;tail) { if (current_node-&gt;data == data_to_search) { int addResult = DoubleLinkedList_Add(return_list, current_node-&gt;data); if (addResult != 0) return addResult; } current_node = current_node-&gt;next; } return 0; } int DoubleLinkedList_Find(DoubleLinkedList *list, void *data_to_find, DoubleLinkedList *return_list) { if (!list) return ENULLIST; if (!return_list) return ENULLIST; DoubleLinkedList_Node *current_node = list-&gt;head-&gt;next; while (current_node != list-&gt;tail) { if (current_node-&gt;data == data_to_find) { int addResult = DoubleLinkedList_Add(return_list, current_node-&gt;data); if (addResult != 0) return addResult; } current_node = current_node-&gt;next; } return 0; } </code></pre> <p>For testing:</p> <p>DoubleLinkedListTests.h</p> <pre><code>#ifndef DOUBLELINKEDLISTTESTS_H #define DOUBLELINKEDLISTTESTS_H // runner void DoubleLinkedList_Tests_RunAllTests(void); // success tests void DoubleLinkedList_SuccessTests_Count(void); void DoubleLinkedList_SuccessTests_InitializeAndDestroy(void); void DoubleLinkedList_SuccessTests_Add(void); void DoubleLinkedList_SuccessTests_GetNode(void); void DoubleLinkedList_SuccessTests_GetNodes(void); void DoubleLinkedList_SuccessTests_Foreach(void); void DoubleLinkedList_SuccessTests_ForeachReverse(void); void DoubleLinkedList_SuccessTests_Clear(void); void DoubleLinkedList_SuccessTests_Remove(void); void DoubleLinkedList_SuccessTests_Find(void); #endif //DOUBLELINKEDLISTTESTS_H </code></pre> <p>DoubleLinkedListTests.c</p> <pre><code>#include &quot;DoubleLinkedList.h&quot; #include &lt;assert.h&gt; #include &lt;stddef.h&gt; static char *testData = &quot;test data&quot;; void DoubleLinkedListTests_Foreach_Callback(DoubleLinkedList_Node *node) { assert(node-&gt;data == testData); } void DoubleLinkedList_SuccessTests_Count(void) { DoubleLinkedList *list = DoubleLinkedList_Initialize(); for (int i = 0; i &lt; 10; i++) { DoubleLinkedList_Add(list, &amp;i); } assert(DoubleLinkedList_Count(list) == 10); DoubleLinkedList_Destroy(list); } void DoubleLinkedList_SuccessTests_InitializeAndDestroy(void) { DoubleLinkedList *list = DoubleLinkedList_Initialize(); assert(list); assert(list-&gt;head-&gt;next == list-&gt;tail); assert(list-&gt;tail-&gt;previous == list-&gt;head); DoubleLinkedList_Destroy(list); } void DoubleLinkedList_SuccessTests_Add(void) { DoubleLinkedList *list = DoubleLinkedList_Initialize(); int isSuccess = DoubleLinkedList_Add(list, testData); assert(isSuccess == 0); assert(list-&gt;head-&gt;next-&gt;data == testData); DoubleLinkedList_Destroy(list); } void DoubleLinkedList_SuccessTests_GetNode(void) { DoubleLinkedList *list = DoubleLinkedList_Initialize(); DoubleLinkedList_Add(list, testData); DoubleLinkedList_Node *test = DoubleLinkedList_GetNode(list, testData); assert(test != NULL); assert(test-&gt;data == testData); DoubleLinkedList_Destroy(list); } void DoubleLinkedList_SuccessTests_GetNodes(void) { DoubleLinkedList *list = DoubleLinkedList_Initialize(); DoubleLinkedList *container = DoubleLinkedList_Initialize(); DoubleLinkedList_Add(list, testData); DoubleLinkedList_Add(list, testData); DoubleLinkedList_Add(list, &quot;invalid data&quot;); DoubleLinkedList_Add(list, &quot;even more invalid data&quot;); int isSuccess = DoubleLinkedList_GetNodes(list, testData, container); assert(isSuccess == 0); assert(container-&gt;head-&gt;next-&gt;data == testData); assert(container-&gt;head-&gt;next-&gt;next-&gt;data == testData); DoubleLinkedList_Destroy(list); DoubleLinkedList_Destroy(container); } void DoubleLinkedList_SuccessTests_Foreach(void) { DoubleLinkedList *list = DoubleLinkedList_Initialize(); DoubleLinkedList_Add(list, testData); int isSuccess = DoubleLinkedList_Foreach(list, DoubleLinkedListTests_Foreach_Callback); assert(isSuccess == 0); DoubleLinkedList_Destroy(list); } void DoubleLinkedList_SuccessTests_ForeachReverse(void) { DoubleLinkedList *list = DoubleLinkedList_Initialize(); DoubleLinkedList_Add(list, testData); int isSuccess = DoubleLinkedList_ForeachReverse(list, DoubleLinkedListTests_Foreach_Callback); assert(isSuccess == 0); DoubleLinkedList_Destroy(list); } void DoubleLinkedList_SuccessTests_Clear(void) { DoubleLinkedList *list = DoubleLinkedList_Initialize(); DoubleLinkedList_Add(list, testData); DoubleLinkedList_Clear(list); assert(list-&gt;head-&gt;next == list-&gt;tail); assert(list-&gt;tail-&gt;previous == list-&gt;head); DoubleLinkedList_Destroy(list); } void DoubleLinkedList_SuccessTests_Remove(void) { DoubleLinkedList *list = DoubleLinkedList_Initialize(); DoubleLinkedList_Add(list, testData); DoubleLinkedList_Remove(list, list-&gt;head-&gt;next); assert(list-&gt;head-&gt;next == list-&gt;tail); assert(list-&gt;tail-&gt;previous == list-&gt;head); DoubleLinkedList_Destroy(list); } void DoubleLinkedList_SuccessTests_Find(void) { char test2 = '2'; char *test3 = &quot;testData&quot;; int test4 = 0; double test5 = -123.456; DoubleLinkedList *list = DoubleLinkedList_Initialize(); DoubleLinkedList *container = DoubleLinkedList_Initialize(); DoubleLinkedList_Add(list, testData); DoubleLinkedList_Add(list, &amp;test2); DoubleLinkedList_Add(list, test3); DoubleLinkedList_Add(list, &amp;test4); DoubleLinkedList_Add(list, &amp;test5); DoubleLinkedList_Find(list, testData, container); assert(container-&gt;head-&gt;next-&gt;data == list-&gt;head-&gt;next-&gt;data); DoubleLinkedList_Find(list, &amp;test2, container); assert(container-&gt;head-&gt;next-&gt;next-&gt;data == list-&gt;head-&gt;next-&gt;next-&gt;data); DoubleLinkedList_Find(list, test3, container); assert(container-&gt;head-&gt;next-&gt;next-&gt;next-&gt;data == list-&gt;head-&gt;next-&gt;next-&gt;next-&gt;data); DoubleLinkedList_Find(list, &amp;test4, container); assert(container-&gt;head-&gt;next-&gt;next-&gt;next-&gt;next-&gt;data == list-&gt;head-&gt;next-&gt;next-&gt;next-&gt;next-&gt;data); DoubleLinkedList_Find(list, &amp;test5, container); assert(container-&gt;tail-&gt;previous-&gt;data == list-&gt;tail-&gt;previous-&gt;data); DoubleLinkedList_Destroy(list); DoubleLinkedList_Destroy(container); } void DoubleLinkedList_Tests_RunAllTests() { DoubleLinkedList_SuccessTests_Count(); DoubleLinkedList_SuccessTests_InitializeAndDestroy(); DoubleLinkedList_SuccessTests_Add(); DoubleLinkedList_SuccessTests_GetNode(); DoubleLinkedList_SuccessTests_GetNodes(); DoubleLinkedList_SuccessTests_Foreach(); DoubleLinkedList_SuccessTests_ForeachReverse(); DoubleLinkedList_SuccessTests_Clear(); DoubleLinkedList_SuccessTests_Remove(); DoubleLinkedList_SuccessTests_Find(); } </code></pre> <p>main.c</p> <pre><code>#include &quot;DoubleLinkedListTests.h&quot; int main(void) { DoubleLinkedList_Tests_RunAllTests(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T15:01:24.090", "Id": "495808", "Score": "0", "body": "I would also keep track of the count, so that calling size() is a constant op instead of having to go through the whole list" } ]
[ { "body": "<p>Overall this looks pretty good, and valgrind should catch most common errors in a linked list.</p>\n<ul>\n<li>Test running out of memory.</li>\n<li>Get someone to review your API in person. It's good, just a little weird.</li>\n<li>Write documentation for your API. Why is there no <code>next</code> method, is the programmer expected to use pointers? What do the error codes mean, and what can each API method return? What is and isn't safe during iteration? Can you delete during <code>Foreach</code>? Add nodes? For things like <code>find</code>, explicitly mention that the user is responsible for freeing the space, and how to.</li>\n<li>Right now this is &quot;Generic&quot; in the sense that it stores a <code>void*</code>, which is not the common usage of that term. When I hear 'generic' I expect 'takes one or more template types'. In C the usual method I've seen is to use lots of macros. The end effect is that either you have typed pointers, or you avoid the overhead of pointers by putting the object into the node struct. Code with lots of macros is ugly, so it's up to you if you want to do that.</li>\n<li>Efficiency. C users like low overhead, especially in a library like this.\n<ul>\n<li>It's more common to offer <code>find</code> as an increment search (give the <code>find</code> the last found node, and it finds the next one) instead of returning a list. Or you could define some kind of iterator and return that.</li>\n<li>Have you encountered the <a href=\"https://en.wikipedia.org/wiki/XOR_linked_list\" rel=\"nofollow noreferrer\">xor trick</a> for doubly linked lists? It's fine (arguably good) not to use it, but it's good to know it exists.</li>\n<li>Why is an empty list two nodes, instead of one or zero? Something like a hash table may make one linked list per entry, so it may be worth optimizing.</li>\n</ul>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T06:33:26.143", "Id": "251747", "ParentId": "251746", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T05:35:30.160", "Id": "251746", "Score": "4", "Tags": [ "c", "linked-list" ], "Title": "Generic double linked list implementation with tests in C" }
251746
<p><code>S</code> is a given character string, then I have to find all the digits characters of <code>S</code>. Did I make it unnecessarily complicated?</p> <pre><code>bits 32 global start extern exit import exit msvcrt.dll segment data use32 class=data s db '+', 'r', '0', '8', '8', '1', 'i', '5' len equ $ - s digits db '012345789' d times len db 0 segment code use32 class=code start: mov ecx, len mov esi,0 mov ebx,0 jecxz end_prog repeat_this: push ecx mov al, [s + esi] mov ecx, 10 mov edi, digits find: scasb jz found loop find jmp next found: mov edi, ebx inc ebx mov [d + edi], al next: inc esi pop ecx loop repeat_this end_prog: push dword 0 call [exit] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T09:00:08.270", "Id": "495782", "Score": "0", "body": "Don't forget that your title should only state the **task accomplished by the code** and nothing else. I also recommend you to add more information about your code in the body to help reviewers" } ]
[ { "body": "<blockquote>\n<p>Did I make it unnecessarily complicated?</p>\n</blockquote>\n<ul>\n<li><p>You can replace</p>\n<pre><code>find:\n scasb\n jz found\n loop find\n jmp next\n</code></pre>\n<p>by the simpler</p>\n<pre><code> repne scasb\n jne next\n</code></pre>\n<p>The use of the <code>SCASB</code> instruction here depends on the direction flag DF being in the clear state (<code>CLD</code>). It is a safe assumption that this will be the case. Nonethesless prudent programmers will at least at program start include one <code>CLD</code> instruction.<br />\nIf ever you find that you need to reverse the direction for the string primitives by the use of <code>STD</code>, you should always issue a restoring <code>CLD</code> as soon as possible (once the string operation has finished). Why is this? Well, just as you can expect the direction flag to be clear, any library functions that your program invokes expect the same thing. During normal program execution <code>DF=0</code> is almost true 100% of the time. <a href=\"https://stackoverflow.com/questions/48490225/the-probability-of-selected-eflags-bits\">See</a>.</p>\n</li>\n<li><p>No need to use the extra register <code>EDI</code> in:</p>\n<pre><code>mov edi, ebx\ninc ebx\nmov [d + edi], al\n</code></pre>\n<p>Just write:</p>\n<pre><code>mov [d + ebx], al\ninc ebx\n</code></pre>\n</li>\n<li><p>The digits have well-known ASCII codes. Finding a digit is just a matter of comparing <code>AL</code> with the range 48 to 57. I find scanning that <em>digits</em> string a bit overkill, although at times that could be a good way. When the character codes aren't contiguous.</p>\n<pre><code> mov ecx, len\n jecxz end_prog\n xor esi, esi\n xor ebx, ebx\nrepeat_this:\n mov al, [s + esi]\n cmp al, '0'\n jb next\n cmp al, '9'\n ja next\n mov [d + ebx], al\n inc ebx\nnext: \n inc esi\n loop repeat_this\n</code></pre>\n<p>Clearing a register is best done using <code>XOR &lt;reg&gt;,&lt;reg&gt;</code>.</p>\n</li>\n</ul>\n<hr />\n<p>This shorter version uses the string primitives and avoids using the slow <code>LOOP</code> instruction:</p>\n<pre><code> mov ecx, len\n mov esi, s\n mov edi, d\n jmp next\n repeat_this:\n lodsb\n cmp al, '0'\n jb next\n cmp al, '9'\n ja next\n stosb\n next:\n sub ecx, 1 \n jnb repeat_this\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T20:09:16.017", "Id": "495840", "Score": "1", "body": "Good review! It might be worth commenting on the Direction Flag and what are and are not safe assumptions about its state." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T19:30:23.087", "Id": "497230", "Score": "1", "body": "You can also range-check more efficiently with `lea edx, [eax-'0']` / `cmp dl, 9` / `ja next`. Of course if you care about performance on modern CPUs you'd use `movzx eax, [esi]` / `inc esi` to load, instead of letting lodsb merge into the old EAX value. ([Why doesn't GCC use partial registers?](https://stackoverflow.com/q/41573502)). \n `lodsb` and `stosb` aren't fast in general." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T19:31:47.383", "Id": "251772", "ParentId": "251751", "Score": "5" } } ]
{ "AcceptedAnswerId": "251772", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T08:58:02.320", "Id": "251751", "Score": "5", "Tags": [ "homework", "assembly", "x86" ], "Title": "Find all the digits in a string" }
251751
<p>Very difficult to explain in a sentence sorry so here is example.</p> <p>I have this array:</p> <pre><code>$setParams = [ 'repeat_delay' =&gt; [23, 1], 'repeat_type' =&gt; ['Hour', 'Day'], ]; </code></pre> <p>that I want to turn into this</p> <pre><code>$wanted = [ [ 'repeat_delay' =&gt; 23, 'repeat_type' =&gt; 'Hour' ], [ 'repeat_delay' =&gt; 1, 'repeat_type' =&gt; 'Day' ] ]; </code></pre> <p>I have it working but wanting to know if there is a cleaner way, or even another way.</p> <pre><code>$newArray = []; $setKeys = array_keys($setParams); $setValues = array_values($setParams); $isSetValueArray = array_filter($setValues, static function ($setValue) { return is_array($setValue); }); if (!empty($isSetValueArray)) { foreach ($setKeys as $keyCount =&gt; $key) { foreach ($setValues as $valueCount =&gt; $value) { if (is_array($value)) { foreach ($value as $k =&gt; $v) { if ($keyCount === $valueCount) { $newArray[$k][$key] = $v; } } } } } } </code></pre> <p>Some more information to help others. I am sorry I didn't provide sooner as I know context is everything.</p> <p>Here is a link to my snippet with more info and complete example.</p> <p><a href="https://gitlab.mrwilde.solutions/-/snippets/18" rel="nofollow noreferrer">https://gitlab.mrwilde.solutions/-/snippets/18</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T09:40:10.517", "Id": "495788", "Score": "0", "body": "Please add more information about your code in the body, its very difficult to understand \" I have this\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T10:13:08.140", "Id": "495790", "Score": "0", "body": "Is that better? Is there a specific question you have I may be able to fill in the blanks better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T14:49:37.710", "Id": "495805", "Score": "1", "body": "What is the purpose of this code? We need to know more about the code before we can provide a good review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T11:44:58.703", "Id": "495990", "Score": "0", "body": "This is called \"array transposing\" and there will be plenty of answers on Stack Overflow to demonstrate the available techniques. Hello Mr. Wilde, see you at the next PHP Meetup. It looks like you are also doing some filtering. Perhaps your sample data is not representing the fringe cases that your code can accommodate. Will your input data always be a complete \"matrix\", or might it have gaps in values?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T12:18:14.187", "Id": "495995", "Score": "0", "body": "For instance: [Transposing multidimensional arrays in PHP](https://stackoverflow.com/q/797251/2943403) and [PHP - how to flip the rows and columns of a 2D array](https://stackoverflow.com/q/2221476/2943403) and [Transpose a PHP multidimensional array with predefined keys](https://stackoverflow.com/q/61610114/2943403)," } ]
[ { "body": "<p>Assuming you have the same number of items for each key, here are two alternative approaches:</p>\n<p>Foreach:</p>\n<pre><code>&lt;?php\n$setParams = [\n 'repeat_delay' =&gt; [23, 1],\n 'repeat_type' =&gt; ['Hour', 'Day'],\n];\n\n$i = 0;\nforeach($setParams['repeat_delay'] as $k =&gt; $v) {\n $result[$i]['repeat_delay'] = $v;\n $result[$i]['repeat_type'] = $setParams['repeat_type'][$k];\n $i++;\n}\n</code></pre>\n<p>Array map:</p>\n<pre><code>$result = array_map(null, ...array_values($setParams));\n$keys = array_keys($setParams);\n$result = array_map(function($v) use ($keys) { return array_combine($keys, $v);}, $result);\n</code></pre>\n<p>Both result in $result holding the following:</p>\n<pre><code>array (\n 0 =&gt; \n array (\n 'repeat_delay' =&gt; 23,\n 'repeat_type' =&gt; 'Hour',\n ),\n 1 =&gt; \n array (\n 'repeat_delay' =&gt; 1,\n 'repeat_type' =&gt; 'Day',\n ),\n)\n</code></pre>\n<p>You could rewrite the last array_map with the array_combine to:</p>\n<pre><code>$result = array_map(fn($v) =&gt; array_combine($keys, $v), $result);\n</code></pre>\n<p>Using a short arrow function for brevity.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T13:35:33.577", "Id": "251812", "ParentId": "251754", "Score": "1" } } ]
{ "AcceptedAnswerId": "251812", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T09:37:33.160", "Id": "251754", "Score": "0", "Tags": [ "php" ], "Title": "PHP array with array value into multiple arrays with same key" }
251754
<p>The program below defines macros START and END that expand to the left and right curly bracket symbols plus some example tracing code. Is this a portable use of a macro and are there any obvious major problems with this? It compiles fine under gcc --pedantic</p> <pre><code>#include &lt;stdio.h&gt; #define TRACE #ifdef TRACE #define START {TRACE_START #define END TRACE_END} #define TRACE_START printf(&quot;ENTERING %s\n&quot;, __func__); #define TRACE_END printf(&quot;LEAVING %s\n&quot;, __func__); #else #define START { #define END } #endif int func() START printf (&quot;Hello World %s\n&quot;); END int main() START func(); END </code></pre> <p>which produces the output</p> <pre><code>ENTERING main ENTERING func Hello World LEAVING func LEAVING main </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T15:03:00.133", "Id": "495809", "Score": "1", "body": "Welcome to the Code Review site. While this code seems to work there doesn't seem to be a lot of code to review. Other than validating the macro there doesn't seem to be any point to this code. This question is too hypothetical." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T15:04:58.373", "Id": "495810", "Score": "2", "body": "It is a very bad idea to hide the open brace and close brace within the macros." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T15:41:20.870", "Id": "495814", "Score": "0", "body": "Pseudocode is off-topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T18:23:18.607", "Id": "495830", "Score": "0", "body": "It is actually a C language program if you care to look at it. It is a valid construct that makes possible runtime configurable program execution tracing and profiling." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T10:35:18.000", "Id": "251755", "Score": "2", "Tags": [ "c", "macros" ], "Title": "Is this use of macros to trace program flow portable and free of major pitfalls?" }
251755
<p>I have created custom video player based on HTML5 video API and JS. Please review the JS.</p> <p>P.S. I couldn't add the video, if you want to check how it works, please add some example video.</p> <p>Thanks.</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() { 'use strict'; const player = document.querySelector('.player'); const video = player.querySelector('.viewer'); const toggleButton = document.querySelector('.toggle'); const progressBar = document.querySelector('.progress'); const progressBarFilled = document.querySelector('.progress__filled'); function togglePlay(e) { if(video.paused) { video.play(); toggleButton.textContent = '❚❚'; } else { video.pause(); toggleButton.textContent = '▶'; } } function updateVideoProgress(e) { video.currentTime = video.duration * e.offsetX / progressBar.clientWidth; } function makeFullScreen() { if(video.requestFullscreen) { video.requestFullscreen(); } else if(video.webkitRequestFullscreen) { video.webkitRequestFullscreen(); } else if(video.msRequestFullScreen) { video.msRequestFullScreen(); } } player.addEventListener('click', e =&gt; { if(e.target.closest('.toggle') || e.target.closest('.viewer')) { togglePlay(); } else if(e.target.closest('.progress')) { updateVideoProgress(e); } else if(e.target.closest('.fullscreen')) { makeFullScreen(); } else { const skipButton = e.target.closest('[data-skip]'); if(skipButton) { video.currentTime += Number(skipButton.dataset.skip); } } }, false); player.addEventListener('input', e =&gt; { const rangeSlider = e.target.closest('.player__slider'); if(!rangeSlider) return; video[rangeSlider.name] = rangeSlider.value; }, false); video.addEventListener('timeupdate', () =&gt; { progressBarFilled.style.flexBasis = `${video.currentTime * 1.0 / video.duration * 100}%`; }, false); progressBar.addEventListener('mouseup', e =&gt; { updateVideoProgress(e); }, false); })();</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>html { box-sizing: border-box; } *, *:before, *:after { box-sizing: inherit; } body { margin: 0; padding: 0; display: flex; background: #7A419B; min-height: 100vh; background: linear-gradient(135deg, #7c1599 0%, #921099 48%, #7e4ae8 100%); background-size: cover; align-items: center; justify-content: center; } .player { max-width: 750px; border: 5px solid rgba(0, 0, 0, 0.2); box-shadow: 0 0 20px rgba(0, 0, 0, 0.2); position: relative; font-size: 0; overflow: hidden; } /* This css is only applied when fullscreen is active. */ .player:fullscreen { max-width: none; width: 100%; } .player:-webkit-full-screen { max-width: none; width: 100%; } .player__video { width: 100%; } .player__button { background: none; border: 0; line-height: 1; color: white; text-align: center; outline: 0; padding: 0; cursor: pointer; max-width: 50px; } .player__button:focus { border-color: #ffc600; } .player__slider { width: 10px; height: 30px; } .player__controls { display: flex; position: absolute; bottom: 0; width: 100%; transform: translateY(100%) translateY(-5px); transition: all .3s; flex-wrap: wrap; background: rgba(0, 0, 0, 0.1); } .player:hover .player__controls { transform: translateY(0); } .player:hover .progress { height: 15px; } .player__controls&gt;* { flex: 1; } .progress { flex: 10; position: relative; display: flex; flex-basis: 100%; height: 5px; transition: height 0.3s; background: rgba(0, 0, 0, 0.5); cursor: ew-resize; } .progress__filled { width: 50%; background: #ffc600; flex: 0; flex-basis: 0%; } /* unholy css to style input type="range" */ input[type=range] { -webkit-appearance: none; background: transparent; width: 100%; margin: 0 5px; } input[type=range]:focus { outline: none; } input[type=range]::-webkit-slider-runnable-track { width: 100%; height: 8.4px; cursor: pointer; box-shadow: 1px 1px 1px rgba(0, 0, 0, 0), 0 0 1px rgba(13, 13, 13, 0); background: rgba(255, 255, 255, 0.8); border-radius: 1.3px; border: 0.2px solid rgba(1, 1, 1, 0); } input[type=range]::-webkit-slider-thumb { height: 15px; width: 15px; border-radius: 50px; background: #ffc600; cursor: pointer; -webkit-appearance: none; margin-top: -3.5px; box-shadow: 0 0 2px rgba(0, 0, 0, 0.2); } input[type=range]:focus::-webkit-slider-runnable-track { background: #bada55; } input[type=range]::-moz-range-track { width: 100%; height: 8.4px; cursor: pointer; box-shadow: 1px 1px 1px rgba(0, 0, 0, 0), 0 0 1px rgba(13, 13, 13, 0); background: #ffffff; border-radius: 1.3px; border: 0.2px solid rgba(1, 1, 1, 0); } input[type=range]::-moz-range-thumb { box-shadow: 0 0 0 rgba(0, 0, 0, 0), 0 0 0 rgba(13, 13, 13, 0); height: 15px; width: 15px; border-radius: 50px; background: #ffc600; cursor: pointer; } .fullscreen { background: url(https://i.postimg.cc/dVt8fZSX/fullscreen.png) no-repeat; background-position: 20% 45%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;HTML Video Player&lt;/title&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="player"&gt; &lt;video class="player__video viewer" src="652333414.mp4"&gt;&lt;/video&gt; &lt;div class="player__controls"&gt; &lt;div class="progress"&gt; &lt;div class="progress__filled"&gt;&lt;/div&gt; &lt;/div&gt; &lt;button class="player__button toggle" title="Toggle Play"&gt;►&lt;/button&gt; &lt;input type="range" name="volume" class="player__slider" min="0" max="1" step="0.05" value="1"&gt; &lt;input type="range" name="playbackRate" class="player__slider" min="0.5" max="2" step="0.1" value="1"&gt; &lt;button data-skip="-10" class="player__button"&gt;« 10s&lt;/button&gt; &lt;button data-skip="25" class="player__button"&gt;25s »&lt;/button&gt; &lt;button class="player__button fullscreen"&gt;&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="scripts.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-11-07T11:18:49.467", "Id": "251756", "Score": "2", "Tags": [ "javascript", "html5" ], "Title": "HTML5 custom video player in JS" }
251756
<p>I've a table with the following data</p> <p><a href="https://i.stack.imgur.com/wKug1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wKug1.png" alt="enter image description here" /></a></p> <p>and I need to find the number of minutes between two jobs (Say A and C).</p> <p>The following query works but wondering, if there is a simpler way to achieve the same.</p> <pre><code> DECLARE @StartTime datetime Declare @EndTime datetime set @StartTime = (SELECT start_time from table where jobname = 'A' ) set @EndTime = (SELECT end_time from table where jobname = 'C' ) select datediff(minute,@StartTime, @EndTime) numberOfMinutes </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T15:40:18.573", "Id": "495813", "Score": "0", "body": "Please follow the guidelines @ https://codereview.stackexchange.com/help/how-to-ask for titling your question." } ]
[ { "body": "<p>You can use Sql Server's <a href=\"https://www.sqlservertutorial.net/sql-server-window-functions/\" rel=\"nofollow noreferrer\"><em>window functions</em></a> <code>LEAD</code> and <code>LAG</code> to get access to two rows in one SELECT statement.</p>\n<p>Here's just one way to get the results you're after:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>DECLARE @jobs TABLE\n(\n Job char(1) primary key,\n Start_time datetime,\n End_time datetime\n);\n\nINSERT @jobs VALUES\n('A', '2020/01/10 8:00', '2020/01/10 8:15'),\n('B', '2020/01/10 8:15', '2020/01/10 8:17'),\n('C', '2020/01/10 8:17', '2020/01/10 8:19'),\n('D', '2020/01/10 8:19', '2020/01/10 8:53');\n\nSELECT Job,\n Start_time,\n [Other job],\n [Other job's end time],\n DATEDIFF(mi, Start_time, [Other job's end time]) [Diff (min)]\nFROM\n(\n SELECT\n Job, \n Start_time,\n LEAD(Job, 2) OVER (ORDER BY Start_time) [Other job],\n LEAD(End_time, 2) OVER (ORDER BY Start_time) [Other job's end time]\n FROM @jobs\n) AS data\nWHERE [Other job] IS NOT NULL\n</code></pre>\n<p>Which shows:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Job Start_time Other job Other job's end time Diff (min)\n---- ----------------------- --------- ----------------------- -----------\nA 2020-01-10 08:00:00.000 C 2020-01-10 08:19:00.000 19\nB 2020-01-10 08:15:00.000 D 2020-01-10 08:53:00.000 38\n</code></pre>\n<p>You can output the difference between two specific jobs by filtering appropriately:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT Job,\n Start_time,\n [Other job],\n [Other job's end time],\n DATEDIFF(mi, Start_time, [Other job's end time]) [Diff (min)]\nFROM\n(\n SELECT\n Job, \n Start_time,\n LEAD(Job) OVER (ORDER BY Start_time) [Other job],\n LEAD(End_time) OVER (ORDER BY Start_time) [Other job's end time]\n FROM @jobs\n WHERE Job IN ('A', 'C')\n) AS data\nWHERE Job = 'A'\n</code></pre>\n<p>Which shows:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Job Start_time Other job Other job's end time Diff (min)\n---- ----------------------- --------- ----------------------- -----------\nA 2020-01-10 08:00:00.000 C 2020-01-10 08:19:00.000 19\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T21:08:28.450", "Id": "251834", "ParentId": "251757", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T11:35:40.903", "Id": "251757", "Score": "1", "Tags": [ "sql", "sql-server" ], "Title": "Retrieve data from two different rows in a single SQL query?" }
251757
<p>So I have a file(story.dat) with a randomly generated story like: &quot;Sleeping in his car was never the plan but sometimes things don't work out as planned. This...&quot;</p> <p>It will print out each word and the corresponding word to it like so:</p> <pre><code>0.&quot;It: was, 1.&quot;Pepsi-Cola.&quot;: He, 2.&quot;This: is, 3./: 50., 4.50: /, 5.50.: I, 6.A: long, 7.All: that, 8.He: didn't,knew,had, 9.I: think,had, 10.I'd: love, 11.I'm: certain, 12.It: was, 13.Or: at, 14.She: knew, 15.Sleeping: in, ... </code></pre> <p>And then it prints the story like so:</p> <blockquote> <p>have a cup of everything. The inside was ten, and a little strange, but he was either exhausted of days ago. It was supposed to hear from you today and fondling over it. He knew what made the last option is to make a year ago. It was supposed to make this case, was in months. The third is the sun. He knew...</p> </blockquote> <p>Here's the code:</p> <pre><code>// #include files namespace Randomiser { std::mt19937 generator{ static_cast&lt;std::mt19937::result_type&gt;(std::time(nullptr)) }; } int getRandomNumber(int min, int max) { std::uniform_int_distribution&lt;int&gt; rand{ min, max }; return rand(Randomiser::generator); } void markovIt(const std::map&lt;std::string, std::vector&lt;std::string&gt;&gt;&amp; m) { std::string temp{}; std::vector&lt;std::string&gt; possibilities{}; std::string next{}; int i{ 0 }; int randomNumber{ getRandomNumber(0, m.size()) }; for (const auto&amp; n : m) { if (i == randomNumber) { temp = n.first; } ++i; } auto found{ m.find(temp) }; i = 0; while(found != m.end()) { if (i == 255) break; possibilities = found-&gt;second; next = possibilities.at(getRandomNumber(0, possibilities.size() - 1)); std::cout &lt;&lt; temp &lt;&lt; &quot; &quot;; temp = next; found = m.find(temp); ++i; } } int main() { std::ifstream wordStream{ &quot;story.dat&quot; }; std::string fWord; std::string sWord; std::vector&lt;std::string&gt; temp; std::map&lt;std::string, std::vector&lt;std::string&gt;&gt; gram{}; int i{ 0 }; while(wordStream) { wordStream &gt;&gt; fWord; if (i != 0) gram[sWord].push_back(fWord); wordStream &gt;&gt; sWord; gram[fWord].push_back(sWord); if (i == 0) i++; } i = 0; for (const auto&amp; n : gram) { std::cout &lt;&lt; i &lt;&lt; &quot;.&quot; &lt;&lt; n.first &lt;&lt; &quot;: &quot;; for (const auto&amp; key : n.second) std::cout &lt;&lt; key &lt;&lt; &quot;,&quot;; std::cout &lt;&lt; '\n'; ++i; } markovIt(gram); std::cout &lt;&lt; '\n'; return 0; } </code></pre> <p>The implementation feels awful and I believe it could be optimised alot further. I'm just not sure where to take it.</p>
[]
[ { "body": "<h1>Use <code>std::random_device</code> instead of <code>time()</code></h1>\n<p>Stay within C++, and use a real random device to seed the generator, like so:</p>\n<pre><code>std::random_device rd;\nstd::mt19937 generator{rd()};\n</code></pre>\n<h1>Consider turning <code>Randomiser</code> into an anonymous namespace</h1>\n<p>Does this namespace need a name? If only <code>getRandomNumber()</code> uses <code>Randomiser::generator</code>, and it's in the same source file, you can make it an anonynous namespace instead, just omit &quot;<code>Randomiser</code>&quot;.</p>\n<h1>Be consistent with types</h1>\n<p>Avoid mixing types like <code>int</code> and <code>size_t</code>. It might seem to work fine, but it is easy for errors to happen this way. Before changing types, consider that sometimes you don't really need to specify a type explicitly, and can instead use <code>template&lt;&gt;</code> or <code>auto</code>. For example:</p>\n<pre><code>template&lt;typename T&gt;\nauto getRandomNumber(T min, T max)\n{\n std::uniform_int_distribution&lt;T&gt; rand{ min, max };\n return rand(Randomiser::generator);\n}\n</code></pre>\n<p>However, you will now get some compiler errors, because you were actually calling <code>getRandomNumber()</code> with <code>min</code> and <code>max</code> having different types, like in:</p>\n<pre><code>int randomNumber{ getRandomNumber(0, m.size()) };\n</code></pre>\n<p>This is actually a good thing, the compiler is telling you something fishy is going on. In fact, <code>m.size()</code> returns a <code>size_t</code>, which can be bigger than what an <code>int</code> can hold on most 64-bit platforms, as well as being unsigned instead of signed. Considering that <code>min</code> is always 0 in your code, I would instead write:</p>\n<pre><code>template&lt;typename T&gt;\nauto getRandomNumber(T max) {\n std::uniform_int_distribution&lt;T&gt; rand{ 0, max };\n return rand(Randomiser::generator);\n}\n\n...\n\nauto randomNumber = getRandomNumber(m.size());\n</code></pre>\n<p>Note that you probably meant <code>getRandomNumber(m.size() - 1)</code> here. This brings me to:</p>\n<h1>Consider writing a <code>getRandomElement()</code> function</h1>\n<p>You actually use the random numbers to pick random elements out of containers. So write a function to do exactly that:</p>\n<pre><code>template&lt;typename T&gt;\nstatic auto &amp;getRandomElement(const T &amp;container)\n{\n std::uniform_int_distribution&lt;size_t&gt; rand{ 0, container.size() - 1 };\n return *std::next(std::begin(container), rand(Randomiser::generator));\n}\n</code></pre>\n<h1>Simplifying <code>markovIt()</code></h1>\n<p>Now that we have the above, we can simplify <code>markovIt()</code> greatly. It can be rewritten as:</p>\n<pre><code>void markovIt(const std::map&lt;std::string, std::vector&lt;std::string&gt;&gt;&amp; m)\n{\n // Get the initial word\n auto word = getRandomElement(m).first;\n\n for (int i = 0; i &lt; 255; ++i)\n {\n std::cout &lt;&lt; word &lt;&lt; &quot; &quot;;\n\n // Find the entry in m that matches word\n auto entry = m.find(word);\n if (entry == m.end())\n break;\n\n // Select a random word from the list of possibilities\n word = getRandomElement(entry-&gt;second);\n }\n}\n</code></pre>\n<h1>Move special cases out of loops if possible</h1>\n<p>While loading <code>story.dat</code>, you use the variable <code>i</code> do determine if you need to push back the first word. You can move that special case outside of the loop. The compiler will probably do this for you even if you don't, but it also cleans up the code if you do so in this case:</p>\n<pre><code>wordStream &gt;&gt; fword;\nwordStream &gt;&gt; sWord;\ngram[fWord].push_back[sWord];\n\nwhile(wordStream)\n{\n wordStream &gt;&gt; fWord;\n gram[sWord].push_back(fWord);\n wordStream &gt;&gt; sWord;\n gram[fWord].push_back(sWord);\n}\n</code></pre>\n<p>However, why read two words in each loop iteration? You can rewrite this to:</p>\n<pre><code>wordStream &gt;&gt; fWord;\n\nwhile(wordStream)\n{\n wordStream &gt;&gt; sWord;\n gram[fWord].push_back(sWord);\n fWord = sWord;\n}\n</code></pre>\n<h1>Move more functionality into functions</h1>\n<p>You are doing too much inside <code>main()</code>. Move more functionality into functions, and keep <code>main()</code> as high-level as possible. For example:</p>\n<pre><code>static auto load_gram(const std::string &amp;filename)\n{\n std::map&lt;std::string, std::vector&lt;std::string&gt;&gt; gram{};\n std::ifstream wordStream{ filename };\n\n // load the data into gram here\n ...\n\n return gram;\n}\n\nint main(int argc, char *argv[])\n{\n auto gram = load_gram(&quot;story.dat&quot;);\n markovIt(gram);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T07:53:58.770", "Id": "495974", "Score": "0", "body": "Thanks alot! I had already implemented some of these changes before, after getting some sleep and looking at it with a fresh mind. I didn't know about std::size_t and int differences so thanks for mentioning it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T22:36:41.993", "Id": "251838", "ParentId": "251758", "Score": "2" } } ]
{ "AcceptedAnswerId": "251838", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T12:59:16.163", "Id": "251758", "Score": "4", "Tags": [ "c++", "hash-map", "markov-chain" ], "Title": "Basic Markov Chain Algorithm" }
251758
<p>I have the following postgresql query that was created for use in a production database to return a daily recap of counts. This query runs and returns correct results in the &quot;staging&quot;/test version of the database, but when run on the production db, no results are returned. I suspect it's the method I used to accomplish this that is ultimately causing my problems (writing to temp table, dropping on commit and selecting * from said temp table).</p> <p>So my question- if there's another, better way to achieve what I'm trying to do here.. which is ultimately just to be able to declare &quot;queryDate&quot; as a variable and use it within the query.</p> <p>A few points of interest-</p> <ul> <li>We need to be able to change the queryDate &quot;variable&quot; easily, as it's referenced many times throughout the script. Which is why it's declared.</li> <li>queryDate is declared as timestamp, even though we're inputting dates because that columns data type is timestamp, even though the requirement is to be able to enter a date to be used in the query. From what I've seen as well as experienced during testing, a date is a valid input for timestamp type.</li> <li>I created a table &quot;temp_output&quot; because without it I get &quot;query has no destination for result data&quot;. I'm trying to emulate a temporary table in mssql/tsql. Is there a better way to do this?</li> <li>I suspect the &quot;ON COMMIT DROP AS&quot; portion to be causing issue here- any words on that?</li> </ul> <p>Any insights are appreciated.</p> <p>Here's a simplified version of what I'm doing, or looking for a better way to accomplish:</p> <pre><code>DO $$ DECLARE --*** MODIFY DATE TO BE USED VVV HERE *** YYYY-MM-DD format queryDate timestamp := '2020-10-4'; BEGIN CREATE TEMP TABLE temp_output ON COMMIT DROP AS select distinct on (queryDate) date(queryDate) as &quot;Date&quot;, ( select count(account.id) where date(account.created) = queryDate ) as &quot;Total Registrations&quot; from account order by queryDate; END $$; SELECT * FROM temp_output; </code></pre> <p>Here's the table you would need to test the minimal reproducable example above:</p> <pre><code>Table: Account ACCOUNT.ID (PK, Integer) ACCOUNT.CREATED (Timestamp w/ time zone) 1234 2020-10-04 17:52:40.340573-04 3245 2020-10-04 17:53:40.340573-04 2345 2020-10-04 19:52:40.340573-04 5533 2020-10-05 17:52:40.340573-04 2288 2020-10-10 17:52:40.340573-04 </code></pre> <p>Expected output for example:</p> <pre><code>Date: Total Registrations: 10-4-2020 3 </code></pre> <p>Here's the query:</p> <pre><code>-- Daily Recap Report : 10/30/2020 -- Single column report; totals for given day. DO $$ DECLARE --*** MODIFY DATE TO BE USED VVV HERE *** YYYY-MM-DD format queryDate timestamp := '2020-10-4'; BEGIN CREATE TEMP TABLE temp_output ON COMMIT DROP AS select distinct on (queryDate) date(queryDate) as &quot;Date&quot;, ( select count(account.id) where date(account.created) = queryDate ) as &quot;Total Registrations&quot;, ( select count(orders.id) from account inner join orders on account.id = orders.buyer_account_id where date(orders.placed) = queryDate and date(account.created) = queryDate ) as &quot;Total New User Orders&quot;, ( select count(orders.id) from orders where date(orders.placed) = queryDate ) as &quot;Total Orders&quot;, ( select sum(order_item.quantity) from order_item join orders on orders.id = order_item.order_id and date(orders.placed) = queryDate ) as &quot;Total Items Sold&quot;, ( select count (distinct orders.store_id) from orders where date(orders.placed) = queryDate ) as &quot;Cooks with Sales&quot;, ( select cast(sum(promo_code.value) as money) from orders join promo_code on promo_code.id = orders.promo_code_id where date(promo_code.redeemed) = queryDate and date(orders.placed) = queryDate ) as &quot;Promo Code Used&quot;, ( select cast(sum(transaction.sub_total) as money) from orders left join transaction on transaction.order_id = orders.id where date(orders.placed) = queryDate ) as &quot;Income Total&quot;, ( select count (orders.id) from account inner join orders on account.id = orders.buyer_account_id where date(orders.placed) = queryDate and account.zip_code like '01%' ) as &quot;Álvaro Obregón&quot;, ( select count (orders.id) from account inner join orders on account.id = orders.buyer_account_id where date(orders.placed) = queryDate and account.zip_code like '02%' ) as &quot;Azcapotzalcoelse&quot;, ( select count (orders.id) from account inner join orders on account.id = orders.buyer_account_id where date(orders.placed) = queryDate and account.zip_code like '03%' ) as &quot;Benito Juárez&quot;, ( select count (orders.id) from account inner join orders on account.id = orders.buyer_account_id where date(orders.placed) = queryDate and account.zip_code like '04%' ) as &quot;Coyoacán&quot;, ( select count (orders.id) from account inner join orders on account.id = orders.buyer_account_id where date(orders.placed) = queryDate and account.zip_code like '05%' ) as &quot;Cuajimalpa&quot;, ( select count (orders.id) from account inner join orders on account.id = orders.buyer_account_id where date(orders.placed) = queryDate and account.zip_code like '06%' ) as &quot;Cuauhtémoc&quot;, ( select count (orders.id) from account inner join orders on account.id = orders.buyer_account_id where date(orders.placed) = queryDate and account.zip_code like '07%' ) as &quot;Gustavo A. Madero&quot;, ( select count (orders.id) from account inner join orders on account.id = orders.buyer_account_id where date(orders.placed) = queryDate and account.zip_code like '08%' ) as &quot;Iztacalco&quot;, ( select count (orders.id) from account inner join orders on account.id = orders.buyer_account_id where date(orders.placed) = queryDate and account.zip_code like '09%' ) as &quot;Iztapalapa&quot;, ( select count (orders.id) from account inner join orders on account.id = orders.buyer_account_id where date(orders.placed) = queryDate and account.zip_code like '10%' ) as &quot;Magdalena Contreras&quot;, ( select count (orders.id) from account inner join orders on account.id = orders.buyer_account_id where date(orders.placed) = queryDate and account.zip_code like '11%' ) as &quot;Miguel Hidalgo&quot;, ( select count (orders.id) from account inner join orders on account.id = orders.buyer_account_id where date(orders.placed) = queryDate and account.zip_code like '12%' ) as &quot;Tlahuac&quot;, ( select count (orders.id) from account inner join orders on account.id = orders.buyer_account_id where date(orders.placed) = queryDate and account.zip_code like '13%' ) as &quot;Tlalpan&quot;, ( select count (orders.id) from account inner join orders on account.id = orders.buyer_account_id where date(orders.placed) = queryDate and account.zip_code like '14%' ) as &quot;Venustiano Carranza&quot;, ( select count (orders.id) from account inner join orders on account.id = orders.buyer_account_id where date(orders.placed) = queryDate and account.zip_code like '15%' ) as &quot;Xochimilco&quot; from account left join store on account.id = store.account_id left join menu on store.id = menu.store_id left join menu_item on menu.id = menu_item.menu_id left join orders on (orders.store_id = store.id) join store_address on store.id = store_address.store_id join address on store_address.address_id = address.id group by account.id order by queryDate; END $$; SELECT * FROM temp_output; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T16:45:55.090", "Id": "495818", "Score": "3", "body": "Two things. First, Code Review isn't designed to tell you why your code is not working as it should. We tell you how to make your code do what it is trying to do in a better fashion. Second, you might get a better answer to this specific question at [DBA.SE](https://dba.stackexchange.com/help)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T18:30:22.693", "Id": "495832", "Score": "0", "body": "@mdfst13 yeah I understand that. I probably should have worded differently. I'd really like to know if there's a better way to do what I'm doing here- as I presume it's the method I used that's causing my problems (writing to a temp table and dropping on commit, then selecting from that temp table)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T21:27:14.223", "Id": "495848", "Score": "1", "body": "According to [this documentation](https://www.postgresql.org/docs/9.3/sql-createtable.html) a temporary table will be deleted at the end of the stored procedure automatically, so what is the purpose of the `on commit drop` in your stored procedure? It seems to be deleting the temporary table before the final select statement. I believe you will get more help from the DBA site than you will get from this site." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T16:02:55.060", "Id": "251762", "Score": "1", "Tags": [ "sql", "postgresql" ], "Title": "Postgresql - query returns different results on 2 copies of same database" }
251762
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251684/231235">An Element-wise Increment and Decrement Operator For Boost.MultiArray in C++</a> and <a href="https://codereview.stackexchange.com/q/251620/231235">A recursive_transform Template Function for BoostMultiArray</a>. I am trying to implement a <code>ones</code> function which can construct a new Boost.MultiArray object with the given dimension and assign each value to <code>1</code>. This <code>ones</code> function is also based on <code>recursive_transform</code> template function. The value assignment task is handled by <code>[](auto&amp; x) { return 1; }</code> lambda function which is passed into <code>recursive_transform</code>.</p> <p>The main implementation of <code>ones</code> function is as below.</p> <pre><code>template&lt;class T, std::size_t NumDims&gt; auto ones(boost::detail::multi_array::extent_gen&lt;NumDims&gt; size) { boost::multi_array&lt;T, NumDims&gt; output(size); return recursive_transform(output, [](auto&amp; x) { return 1; }); } </code></pre> <p>Just for convenience, the used <code>recursive_transform</code> template function can also be checked here.</p> <pre><code>template&lt;typename T&gt; concept is_back_inserterable = requires(T x) { std::back_inserter(x); }; template&lt;typename T&gt; concept is_multi_array = requires(T x) { x.num_dimensions(); x.shape(); boost::multi_array(x); }; template&lt;typename T&gt; concept is_iterable = requires(T x) { *std::begin(x); std::end(x); }; template&lt;typename T&gt; concept is_elements_iterable = requires(T x) { std::begin(x)-&gt;begin(); std::end(x)-&gt;end(); }; template&lt;typename T&gt; concept is_element_visitable = requires(T x) { std::visit([](auto) {}, *x.begin()); }; template&lt;typename T&gt; concept is_summable = requires(T x) { x + x; }; template&lt;class T, class F&gt; auto recursive_transform(const T&amp; input, const F&amp; f) { return f(input); } template&lt;class T, std::size_t S, class F&gt; auto recursive_transform(const std::array&lt;T, S&gt;&amp; input, const F&amp; f) { using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f)); std::array&lt;TransformedValueType, S&gt; output; std::transform(input.cbegin(), input.cend(), output.begin(), [f](auto&amp; element) { return recursive_transform(element, f); } ); return output; } template&lt;template&lt;class...&gt; class Container, class Function, class... Ts&gt; requires (is_back_inserterable&lt;Container&lt;Ts...&gt;&gt;&amp;&amp; is_iterable&lt;Container&lt;Ts...&gt;&gt; &amp;&amp; !is_elements_iterable&lt;Container&lt;Ts...&gt;&gt;) // non-recursive version auto recursive_transform(const Container&lt;Ts...&gt;&amp; input, const Function&amp; f) { using TransformedValueType = decltype(f(*input.cbegin())); Container&lt;TransformedValueType&gt; output; std::transform(input.cbegin(), input.cend(), std::back_inserter(output), f); return output; } template&lt;template&lt;class...&gt; class Container, class Function, class... Ts&gt; requires (is_back_inserterable&lt;Container&lt;Ts...&gt;&gt; &amp;&amp; is_elements_iterable&lt;Container&lt;Ts...&gt;&gt;) auto recursive_transform(const Container&lt;Ts...&gt;&amp; input, const Function&amp; f) { using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f)); Container&lt;TransformedValueType&gt; output; std::transform(input.cbegin(), input.cend(), std::back_inserter(output), [&amp;](auto&amp; element) { return recursive_transform(element, f); } ); return output; } template&lt;class T, class F&gt; requires (is_multi_array&lt;T&gt;) auto recursive_transform(const T&amp; input, const F&amp; f) { boost::multi_array output(input); for (decltype(+input.shape()[0]) i = 0; i &lt; input.shape()[0]; i++) { output[i] = recursive_transform(input[i], f); } return output; } </code></pre> <p>The test of this <code>ones</code> function:</p> <pre><code>auto A = ones&lt;double, 3&gt;(boost::extents[3][4][2]); typedef decltype(A)::index index; std::cout &lt;&lt; &quot;A:&quot; &lt;&lt; std::endl; for (index i = 0; i != 3; ++i) for (index j = 0; j != 4; ++j) for (index k = 0; k != 2; ++k) std::cout &lt;&lt; A[i][j][k] &lt;&lt; std::endl; </code></pre> <p>The whole experimental code can be checked at <a href="https://gist.github.com/Jimmy-Hu/74cf5e27f6edc42ecae58eef236aed1b" rel="nofollow noreferrer">here</a>.</p> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/251684/231235">An Element-wise Increment and Decrement Operator For Boost.MultiArray in C++</a> and</p> <p><a href="https://codereview.stackexchange.com/q/251620/231235">A recursive_transform Template Function for BoostMultiArray</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>The template function <code>ones</code> has been created in this question.</p> </li> <li><p>Why a new review is being asked for?</p> <p>Please check the implementation of <code>ones</code> function above. If there is any possible improvement, please let me know.</p> </li> </ul>
[]
[ { "body": "<h1>Make it more generic</h1>\n<p>What if I want twos or threes? What if <code>T</code> is a <code>std::string</code>?</p>\n<h1>Consider avoiding recursion in this case</h1>\n<p>Since you only pass in the size of the outer <code>multi_array</code> to <code>ones()</code>, it doesn't make sense to call <code>recursive_transform()</code>. You can access all the elements of the <code>multi_array</code> directly, and initialize them with <a href=\"https://en.cppreference.com/w/cpp/algorithm/fill_n\" rel=\"nofollow noreferrer\"><code>std::fill_n()</code></a>:</p>\n<pre><code>template&lt;class T, std::size_t NumDims&gt;\nauto filled_multi_array(boost::detail::multi_array::extent_gen&lt;NumDims&gt; size, const T &amp;value)\n{\n boost::multi_array&lt;T, NumDims&gt; output(size);\n std::fill_n(output.data(), output.num_elements(), value);\n return output;\n}\n</code></pre>\n<p>As a bonus, since you now pass a value to the function, it can deduce the type of it, so you no longer have to specify any template parameters:</p>\n<pre><code>auto A = filled_multi_array(boost::extents[3][4][2], 1.0);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T20:53:07.770", "Id": "251832", "ParentId": "251764", "Score": "1" } } ]
{ "AcceptedAnswerId": "251832", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T16:32:11.310", "Id": "251764", "Score": "2", "Tags": [ "c++", "recursion", "lambda", "boost", "c++20" ], "Title": "A ones Function for Boost.MultiArray in C++" }
251764
<p>I made a word searching app that allows the user to inout words into a text box, and parts of the word grid will be highlighted to show the location of the words. The letters of the grid can be edited while you are using it by clicking on the cell, and pressing the key you want to replace the current letter with.</p> <p>Here is how it goes:</p> <p><a href="https://i.stack.imgur.com/FlWmv.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/FlWmv.gif" alt="enter image description here" /></a></p> <p>I made this recursive function to find each word:</p> <pre><code> def adj(self, c, idx, lstlst, wrd): x, y = self.cells.index(c) % self.cols, self.cells.index(c) // self.cols x1, x2 = max(0, x - 1), min(x + 2, self.cols + 2) y1, y2 = max(0, y - 1), min(y + 2, self.rows + 2) adjs = [cell for row in self.grid[y1:y2] for cell in row[x1:x2] if cell != c] taillst = lstlst[-1] for cell in adjs: if len(wrd) &gt; idx: if cell.text == wrd[idx] and cell not in taillst: lstlst.append(taillst[:] + [cell]) self.adj(cell, idx+1, lstlst, wrd) </code></pre> <p>This is how I called it:</p> <pre><code> elif event.type == pygame.KEYDOWN: grid.type(event) word.type(event) for cell in grid.cells: cell.color = (0, 0, 0) for cell in grid.cells: lstlst = [[cell]] grid.adj(cell, 1, lstlst, word.text) for lst in lstlst: if ''.join([c.text for c in lst]) == word.text: for c in lst: c.color = (255, 0, 0) </code></pre> <p>I know, it's a mess, but I am trying. Despite that, can you show me <strong>how can I improve the efficiency of my word-searching algorithim?</strong></p> <p>Here is my entire code:</p> <pre><code>import pygame pygame.font.init() wn = pygame.display.set_mode((600, 600)) letters = \ ''' KJDJCIOSDZ PGRIWOTAID VETVALCGLS OFZESGZASW SOYRBKOADL FUWTQOXNGE CILIWMEPAV NEZCJRVZNL GXZAOQMFIG EUPLIESCGP HORIZONTAL ''' class Cell(): def __init__(self, x, y, s, text='', color=(0, 0, 0), cell=True): self.input_box = pygame.Rect(x, y, s, s) self.x = x self.y = y self.s = s self.w = s self.color_inactive = color self.color_active = pygame.Color('purple') self.color = self.color_inactive self.text = text self.active = False self.pad = 10 self.cell = cell self.font = pygame.font.Font(None, s) def check_status(self, pos): if self.input_box.collidepoint(pos): self.active = not self.active else: self.active = False self.color = self.color_active if self.active else self.color_inactive def type(self, event): if self.active: if self.cell: if event.unicode and event.unicode.lower() in 'abcdefghijklmnopqrstuvwxyz ': self.text = event.unicode else: if event.key == pygame.K_BACKSPACE: self.text = '' if len(self.text) &lt; 2 else self.text[:-1] elif event.unicode and event.unicode.lower() in 'abcdefghijklmnopqrstuvwxyz ': self.text += event.unicode def draw(self): txt = self.font.render(self.text, True, self.color) if not self.cell: width = max(self.w, txt.get_width()) self.input_box.w = width + self.pad * 2 x = self.x + self.pad else: x = self.x+(self.s-txt.get_width())//2 y = self.y+(self.s-txt.get_height())*5//7 wn.blit(txt, (x, y)) pygame.draw.rect(wn, self.color, self.input_box, 2) class Grid(): def __init__(self, x, y, size, letters, color=(0, 0, 0)): rows = len(letters) cols = len(letters[0]) self.grid = [[Cell(i*size+x, j*size+y, size, letter) for i, letter in enumerate(row)] for j, row in enumerate(letters)] self.cells = [cell for row in self.grid for cell in row] self.rows = rows self.cols = cols def check_status(self, pos): for cell in self.cells: cell.check_status(pos) def type(self, event): for cell in self.cells: cell.type(event) def adj(self, c, idx, lstlst, wrd): x, y = self.cells.index(c) % self.cols, self.cells.index(c) // self.cols x1, x2 = max(0, x - 1), min(x + 2, self.cols + 2) y1, y2 = max(0, y - 1), min(y + 2, self.rows + 2) adjs = [cell for row in self.grid[y1:y2] for cell in row[x1:x2] if cell != c] taillst = lstlst[-1] for cell in adjs: if len(wrd) &gt; idx: if cell.text == wrd[idx] and cell not in taillst: lstlst.append(taillst[:] + [cell]) self.adj(cell, idx+1, lstlst, wrd) def draw(self): for cell in self.cells: cell.draw() grid = Grid(50, 70, 32, list(filter(None, letters.split('\n')))) word = Cell(50, 20, 32, cell=False) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.MOUSEBUTTONDOWN: grid.check_status(event.pos) word.check_status(event.pos) elif event.type == pygame.KEYDOWN: grid.type(event) word.type(event) for cell in grid.cells: cell.color = (0, 0, 0) for cell in grid.cells: lstlst = [[cell]] grid.adj(cell, 1, lstlst, word.text) for lst in lstlst: if ''.join([c.text for c in lst]) == word.text: for c in lst: c.color = (255, 0, 0) wn.fill((255, 255, 255)) grid.draw() word.draw() pygame.display.flip() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T16:35:45.223", "Id": "251765", "Score": "4", "Tags": [ "python", "performance", "recursion", "pygame" ], "Title": "Word finder using pygame" }
251765
<p><strong>[EDIT]</strong></p> <p>The question has been edited. Please make sure to read the summary at the end of the post. If you'd like me to make a new post with a cleaner explanation and better examples, tell me to do so in the comments.</p> <p><strong>[/EDIT]</strong></p> <p><strong>[ORIGINAL]</strong></p> <p>Recently, I've started learning and exploring more about template metaprogramming. I thought I had a new idea this morning when I thought of implementing a multidimensional vector declarator using templates, but turns out it has already been invented after just one google search :[</p> <p>Here's a very simple implementation I've written:</p> <pre class="lang-cpp prettyprint-override"><code>// Multidimensional Vector Declarator template &lt;typename T, size_t D = 1&gt; struct matrix : std::vector &lt;matrix &lt;T, D - 1&gt;&gt; { static_assert(D &gt; 0, &quot;matrix dimensions must be positive&quot;); template &lt;typename...Args&gt; matrix (const size_t&amp; size = 0, const Args&amp;... args) : std::vector &lt;matrix &lt;T, D - 1&gt;&gt; (size, matrix &lt;T, D - 1&gt; (args...)) { } }; template &lt;typename T&gt; struct matrix &lt;T, 1&gt; : public std::vector &lt;T&gt; { matrix (const size_t&amp; size = 0, const T&amp; value = 0) : std::vector &lt;T&gt; (size, value) { } }; // Usage // Declare a 1-D vector matrix &lt;int&gt; m; // equivalent to std::vector &lt;int&gt; m (0, 0) matrix &lt;int, 1&gt; m; // equivalent to std::vector &lt;int&gt; m (0, 0) matrix &lt;int, 1&gt; m (10); // equivalent to std::vector &lt;int&gt; m (10, 0) matrix &lt;int, 1&gt; m (10, 42); // equivalent to std::vector &lt;int&gt; m (10, 42) // Declare a 2-D vector matrix &lt;int, 2&gt; m; // equivalent to std::vector &lt;std::vector &lt;int&gt;&gt; m (0, std::vector &lt;int&gt; (0, 0)) matrix &lt;int, 2&gt; m (10); // equivalent to std::vector &lt;std::vector &lt;int&gt;&gt; m (10, std::vector &lt;int&gt; (0, 0)) matrix &lt;int, 2&gt; m (10, 5); // equivalent to std::vector &lt;std::vector &lt;int&gt;&gt; m (10, std::vector &lt;int&gt; (5, 0)) matrix &lt;int, 2&gt; m (10, 5, 42); // equivalent to std::vector &lt;std::vector &lt;int&gt;&gt; m (10, std::vector &lt;int&gt; (5, 42)) // ...so on // alternate implementation // i find that i'm more limited this way // i could essentially add multiple constructors and make it more sophisticated // to be able to achieve what i want, but I'd like to do so in a simple // manner. suggestions on the same are welcome. template &lt;typename T, size_t D = 1&gt; struct matrix : std::vector &lt;matrix &lt;T, D - 1&gt;&gt; { static_assert(D &gt; 0, &quot;matrix dimensions must be positive&quot;); template &lt;typename...Args&gt; matrix (const Args&amp;... args) : std::vector &lt;matrix &lt;T, D - 1&gt;&gt; (args...) { } }; template &lt;typename T&gt; struct matrix &lt;T, 1&gt; : public std::vector &lt;T&gt; { template &lt;typename...Args&gt; matrix (const Args&amp;... args) : std::vector &lt;T&gt; (args...) { } }; </code></pre> <p>I would like to know if this achieves what I think it achieves (because it looks way too simple and I'm afraid of loss of freedom in how I'm able to use this sort of a multidimensional vector). I would also like to be able to use this as freely as I'm able to use the equivalent forms of std::vector. From some light testing, everything works well and good, and I'm happy, but as I'm no language expert, I can't be sure.</p> <p>What are other ways I could achieve the same properties as I seek to achieve, perhaps ones without using deriving from classes, or without classes altogether? Is it possible to implement what I have purely through <code>template &lt;typename T&gt; using ... = ...;</code>?</p> <p><strong>[/ORIGINAL]</strong></p> <p><strong>[EDIT]</strong></p> <p>After being asked by a fellow SE.CR-er, here's an example which you can compile and test.</p> <pre class="lang-cpp prettyprint-override"><code>// Forgive me for not writing all includes like I should // PCH for fast compile time #include &quot;bits/stdc++.h&quot; // Just some debugging code // Important stuff a couple of lines below this namespace debugging::inline utility { template &lt;typename T, typename = void&gt; struct is_istream_streamble : std::false_type { }; template &lt;typename T&gt; struct is_istream_streamble &lt;T, std::void_t &lt;decltype(std::cin &gt;&gt; std::declval &lt;T&amp;&gt; ())&gt;&gt; : std::true_type { }; template &lt;typename T&gt; constexpr bool is_istream_streamble_v = is_istream_streamble &lt;T&gt;::value; template &lt;typename T, typename = void&gt; struct is_ostream_streamble : std::false_type { }; template &lt;typename T&gt; struct is_ostream_streamble &lt;T, std::void_t &lt;decltype(std::cerr &lt;&lt; std::declval &lt;T&gt; ())&gt;&gt; : std::true_type { }; template &lt;typename T&gt; constexpr bool is_ostream_streamble_v = is_ostream_streamble &lt;T&gt;::value; template &lt;typename T, typename = void&gt; struct has_begin_iterator : std::false_type { }; template &lt;typename T&gt; struct has_begin_iterator &lt;T, std::void_t &lt;decltype(std::declval &lt;T&gt; ().begin())&gt;&gt; : std::true_type { }; template &lt;typename T&gt; constexpr bool has_begin_iterator_v = has_begin_iterator &lt;T&gt;::value; template &lt;typename T, typename = void&gt; struct has_end_iterator : std::false_type { }; template &lt;typename T&gt; struct has_end_iterator &lt;T, std::void_t &lt;decltype(std::declval &lt;T&gt; ().end())&gt;&gt; : std::true_type { }; template &lt;typename T&gt; constexpr bool has_end_iterator_v = has_end_iterator &lt;T&gt;::value; template &lt;typename T&gt; constexpr bool has_begin_end_iterator_v = has_begin_iterator_v &lt;T&gt; &amp;&amp; has_end_iterator_v &lt;T&gt;; } namespace debugging { class view { private: std::ostream&amp; stream; public: view (std::ostream&amp; stream = std::cerr) : stream (stream) { } #ifdef LOST_IN_SPACE template &lt;typename T&gt; std::enable_if_t &lt;is_ostream_streamble_v &lt;T&gt;, view&amp;&gt; operator () (const T&amp; object) { return stream &lt;&lt; object, *this; } template &lt;typename T&gt; std::enable_if_t &lt;!is_ostream_streamble_v &lt;T&gt; &amp;&amp; has_begin_end_iterator_v &lt;T&gt;, view&amp;&gt; operator () (const T&amp; object) { (*this)(&quot;{&quot;); for (const auto&amp; element : object) (*this)(element, ' '); return (*this)(object.begin() == object.end() ? &quot;}&quot; : &quot;\b}&quot;); } template &lt;typename A, typename B&gt; view&amp; operator () (const std::pair &lt;A, B&gt;&amp; pair) { return (*this)(&quot;(&quot;, pair.first, &quot;, &quot;, pair.second, &quot;)&quot;); } template &lt;size_t N, typename...T&gt; std::enable_if_t &lt;(sizeof...(T) &lt;= N), view&amp;&gt; operator () (const std::tuple &lt;T...&gt;&amp;) { return *this; } template &lt;size_t N, typename...T&gt; std::enable_if_t &lt;(sizeof...(T) &gt; N), view&amp;&gt; operator () (const std::tuple &lt;T...&gt;&amp; tuple) { return (*this)(std::get &lt;N&gt; (tuple), ' '), operator () &lt;N + 1, T...&gt; (tuple); } template &lt;typename...T&gt; view&amp; operator () (const std::tuple &lt;T...&gt;&amp; tuple) { (*this)(&quot;&lt;&quot;); operator () &lt;0, T...&gt; (tuple); return (*this)(sizeof...(T) &gt; 0 ? &quot;\b&gt;&quot; : &quot;&gt;&quot;); } view&amp; operator () () { return *this; } template &lt;typename A, typename...B&gt; view&amp; operator () (const A&amp; object, const B&amp;...objects) { return (*this)(object)(objects...); } #else template &lt;typename...T&gt; view&amp; operator () (const T&amp;...) { return *this; } #endif }; } using view = debugging::view; view debug (std::cerr); #define print(x) &quot; [&quot;, #x, &quot;: &quot;, x, &quot;]\n\n&quot; // Multidimensional Vector Declarator template &lt;typename T, size_t D = 1&gt; struct matrix : std::vector &lt;matrix &lt;T, D - 1&gt;&gt; { static_assert(D &gt; 0, &quot;matrix dimensions must be positive&quot;); template &lt;typename...Args&gt; matrix (const size_t&amp; size = 0, const Args&amp;... args) : std::vector &lt;matrix &lt;T, D - 1&gt;&gt; (size, matrix &lt;T, D - 1&gt; (args...)) { } }; template &lt;typename T&gt; struct matrix &lt;T, 1&gt; : public std::vector &lt;T&gt; { matrix (const size_t&amp; size = 0, const T&amp; value = 0) : std::vector &lt;T&gt; (size, value) { } }; int main () { // Usage // Declare a 1-D vector matrix &lt;int&gt; m1; // equivalent to std::vector &lt;int&gt; m1 (0, 0) matrix &lt;int, 1&gt; m2; // equivalent to std::vector &lt;int&gt; m2 (0, 0) matrix &lt;int, 1&gt; m3 (10); // equivalent to std::vector &lt;int&gt; m3 (10, 0) matrix &lt;int, 1&gt; m4 (10, 42); // equivalent to std::vector &lt;int&gt; m4 (10, 42) // Declare a 2-D vector matrix &lt;int, 2&gt; m5; // equivalent to std::vector &lt;std::vector &lt;int&gt;&gt; m5 (0, std::vector &lt;int&gt; (0, 0)) matrix &lt;int, 2&gt; m6 (10); // equivalent to std::vector &lt;std::vector &lt;int&gt;&gt; m6 (10, std::vector &lt;int&gt; (0, 0)) matrix &lt;int, 2&gt; m7 (10, 5); // equivalent to std::vector &lt;std::vector &lt;int&gt;&gt; m7 (10, std::vector &lt;int&gt; (5, 0)) matrix &lt;int, 2&gt; m8 (10, 5, 42); // equivalent to std::vector &lt;std::vector &lt;int&gt;&gt; m8 (10, std::vector &lt;int&gt; (5, 42)) debug(print(m1), print(m2), print(m3), print(m4), print(m5), print(m6), print(m7), print(m8)); // Normally use like you'd use a vector &lt;type&gt; // Dimensions int a, b, c; std::cin &gt;&gt; a &gt;&gt; b &gt;&gt; c; // 2 3 2 // Dynamic sized vector matrix &lt;int, 3&gt; m (a, b, c); // Reading input // 8 4 2 7 1 3 6 11 12 5 9 10 for (int i = 0; i &lt; a; ++i) for (int j = 0; j &lt; b; ++j) for (auto&amp; k : m [i].at(j)) std::cin &gt;&gt; k; debug(print(m)); // Sorting std::sort(begin(m), end(m)); debug(print(m)); std::sort(begin(m [1]), end(m.at(1))); debug(print(m)); // Other std::algorithms std::transform(begin(m.at(1)[2]), end(m[1].at(2)), begin(m [1][2]), [] (auto i) -&gt; int { return i + 1; }); m [0][2][1] = 42; debug(print(m)); // Clear m.clear(); debug(print(m.size())); return 0; } </code></pre> <p>Everything works like you'd expect it to. My matrix type is trying to abstract away the number of dimensions one would use to type <code>std::vector &lt;std::vector &lt;.....&gt;&gt;</code>. I have no problem regarding how efficient the code produced would be. I expect it to be equivalently efficient to the multiple dimension &quot;normal&quot; std::vector declaration. Please correct me if I'm wrong.</p> <p>To respecify what I intend to do, here's a short bulletted summary:</p> <ul> <li>Implement an interface which abstracts away the number of dimensions from using a multiple dimension <code>std::vector</code>. Doing things this way reduces the verbosity in declaring a 3D vector, let's say, and using it this way instead:</li> </ul> <pre class="lang-cpp prettyprint-override"><code>// long version std::vector &lt;std::vector &lt;std::vector &lt;int&gt;&gt;&gt; v (a, std::vector &lt;std::vector &lt;int&gt;&gt; (b, std::vector &lt;int&gt; (c, d))); // slighly shorter template &lt;typename T&gt; using vec = std::vector &lt;T&gt;; vec &lt;vec &lt;vec &lt;int&gt;&gt;&gt; v (a, vec &lt;vec &lt;int&gt;&gt; (b, vec &lt;int&gt; (c, d))); // better? matrix &lt;int, 3&gt; v (a, b, c, d); </code></pre> <ul> <li>Implement as short as possible code (without the need to write multiple overloaded constructors, if possible) to construct the matrix type as freely as you'd be able construct equivalent std::vector implementation with initializer lists, etc...</li> </ul> <pre class="lang-cpp prettyprint-override"><code>// to use initialiser lists, what you can (need to) do is: matrix &lt;int, 1&gt; m (std::initializer_list &lt;int&gt; {1, 2, 3}); // remember, with the above long example code, this is not possible. // look at the code before the EDIT using variadic templates to use this // presently, you can't do this: matrix &lt;int, 1&gt; m {1, 2, 3}; // but this is what I'd like to achieve in as simple a way as possible. // // if not possible to do so in a simple straight-forward way without overloading // many constructor versions, alright, end of discussion. i've figured as much too, as of now // // also, not just keeping the implementation limited to initializer lists, i would // like it to be extensible too all constructor types and parameters of a std::vector // // in the near future, i also plan to make the implementation more generic. // instead of limiting to std::vector, as in my current implementation, i would // also accept other containers and only abstract the dimension part away. // probable usage: matrix &lt;std::vector, int, 3&gt; m; // 3 dimensional std::vector of int matrix &lt;std::array, int 2&gt; m; // 2 dimensional std::array of int </code></pre> <ul> <li><p>In my code above, I use class derivation. Is there an idea to do so without it? Is there a way to only use <code>using ... = ...</code> and be able to abstract away dimensions?</p> </li> <li><p>I do realise the fact that this question seems irrelevant to SE Code Review (because it is about best practices and writing efficient code), as also stated by fellow SE.CR-ers. It would be great, and I would be very thankful, if you could suggest me the right SE platform for this question. Stack Overflow?</p> </li> </ul> <p><strong>[/EDIT]</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T17:36:39.903", "Id": "495823", "Score": "0", "body": "Also, with the above code, I've noticed I can't freely use initializer lists without explicitly writing `std::initializer_list`, or using any similar implementation to it that adapts to c++ initializer lists, in the constructor. How could I get that sort of freedom back without bloating up my code size? I know it definitely doesn't work with the above version. However, on a similar version where I template specialize `matrix <T, 1>` with a variadic template constructor, I always need to use the `std::initializer_list` to get initializer lists to work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T22:32:38.850", "Id": "496140", "Score": "0", "body": "Have you actually tested it and does it work as expected." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T22:37:21.920", "Id": "496141", "Score": "0", "body": "@pacmaninbw Yes, it does work as expected, except that it is limited in the way I can construct it. Writing all sorts of constructor overloads (which I did try) that in turn pass on the values to the constructors of std::vector makes everything work smoothly. Maybe not so smoothly as I'd expect though (I need to explicitly type std::initializer_list in front of a brace-enclosed initialiser to make it work, among other things which I may have left uncovered). All other things like accessing with [], resizing, sorting and clearing, work cleanly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T22:43:59.987", "Id": "496142", "Score": "0", "body": "Please post the complete code it's missing the necessary headers. It would be best to post any unit test code you have as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T22:47:34.143", "Id": "496143", "Score": "0", "body": "@pacmaninbw Sure, doing so now. Unfortunately, I'll have to rewrite unit testing code as I have very messy debugging code lying around which will burn eyes. I'll get to it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T00:31:48.067", "Id": "496145", "Score": "0", "body": "I like `#ifdef LOSTINSPACE`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T00:33:00.673", "Id": "496146", "Score": "0", "body": "@AryanParekh You might want to delete your vote to close." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T03:08:50.030", "Id": "496149", "Score": "0", "body": "@pacmanibw, Sure," } ]
[ { "body": "<p>It has the same issues as almost all other recursion based solutions. It is inefficient AF.</p>\n<p>Imagine you have a 4 dimensional matrix. Then to access an element you need to need to access memory 4 times in full random access. Currently, memory access is one of the main sources of slowdown of the system. On an average PC, access to RAM memory takes over a hundred cycles.</p>\n<p>Memory is transferred in cachelines (64 bytes currently) so accessing data in the same cacheline is efficient. Also, if compiler is able to figure out beforehand which cacheline is needed to be loaded then it can sequence its load beforehand while doing other things.</p>\n<p>But in your case neither optimization is even remotely possible to do in all 4 times as compiler has no clue what data is contained in those vertexes.</p>\n<p>Standard practice it to flatten the matrix. Store a single <code>std::vector</code> of data and two arrays <code>std::array&lt;size_t,N&gt;</code> of dimensions and step sizes (normally step sizes are determined by dimensions but they are better be pre-calculated). And to figure out where exactly element corresponding to <code>(x,y,z,w)</code> simply compute <code>x*step[0]+y*step[1]+z*step[2]+w*step[3]</code> and access this element of the vector (normally either <code>step[0]</code> or <code>step[3]</code> is <code>1</code> depending on your choice of format).</p>\n<p>In addition it reduces significantly the amount of calls to memory allocations and deallocations as those are slow AF and cause memory fragmentation issues if used too many times.</p>\n<p>This way you need just a single memory load to access an element and if you use it contiguously with properly implemented iterators then the compiler will be able to optimize it to decent performance. To improve it further it'll require to utilize SIMD instructions and/or multithreading.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T15:04:25.157", "Id": "496087", "Score": "0", "body": "What does this answer have anything to do with my question? Please consider deleting it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T15:26:44.753", "Id": "496094", "Score": "0", "body": "@LostArrow the problem is that the idea is impractical and there are far better solutions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T15:44:38.783", "Id": "496098", "Score": "0", "body": "my question nowhere mentions that I'm looking for an efficient solution. The way I'd manually define `std::vector <std::vector <...>>`, I'd like to abstract the dimensions part off, and implement it with a generic interface which takes a type and dimension instead to do exactly what the nested vector declaration looks like and would do. As far as efficiency goes, if I wanted it, it'd have been mentioned in the question. Doing things the way I've given in the example will be equally as efficient as using the nested vectors. I'm not asking to efficient-ise _that_ or the access with [][][][]..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T15:55:51.283", "Id": "496101", "Score": "0", "body": "@LostArrow I think you got to a wrong site. Code review is about reviewing written code - what's good or bad about it and some advices to improve it. If you want to learn how to write C++ code there are other sites for it like FreeCodeAcademy.com or something. Or just buy/download a C++ guide book." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T15:57:36.053", "Id": "496102", "Score": "0", "body": "@LostArrow One of main points of C++ is to implement efficient and safe code. If you abstract away dimension you ensure that it can be neither efficient nor type safe. At best you'll get runtime safety checks. You'll need to store dimensions in a dynamic array an accepts a range for input. Not suitable for basic classes. Also in general multidimensional matrices aren't practical as within a few dimensions you overload the whole memory RAM way too fast." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T14:50:24.160", "Id": "251906", "ParentId": "251767", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T17:31:42.080", "Id": "251767", "Score": "4", "Tags": [ "c++", "c++17", "template", "template-meta-programming", "c++20" ], "Title": "Template Metaprogramming - Multidimensional Vector Declaration" }
251767
<p>can this script be made simpler? I'm just learning about javascript, so I don't really know which syntax to use.</p> <p>My HTML I have several id consisting of &quot;doc1, doc2, doc3, ..&quot; and there is another id &quot;icon-cek1, icon-ceck2, icon-cek3&quot;. &quot;icon-cek&quot; is used to display the place of a checkmark icon when the upload is successful / according to the extension that has been specified and if the file fails / doesn't match the extension will display a crossmark.</p> <pre><code>&lt;label&gt; DOcument 1&lt;/label&gt; &lt;input type=&quot;file&quot;id=&quot;doc1&quot;/&gt; &lt;label&gt; Choose&lt;/label&gt; &lt;div id=&quot;icon-cek1&quot;&gt;&lt;/div&gt; &lt;label&gt; DOcument 2&lt;/label&gt; &lt;input type=&quot;file&quot;id=&quot;doc2&quot; /&gt; &lt;label&gt; Choose&lt;/label&gt; &lt;div id=&quot;icon-cek2&quot;&gt;&lt;/div&gt; &lt;label&gt; DOcument 3&lt;/label&gt; &lt;input type=&quot;file&quot;id=&quot;doc3&quot;/&gt; &lt;label&gt; Choose&lt;/label&gt; &lt;div id=&quot;icon-cek3&quot;&gt;&lt;/div&gt; $.fn.checkFileType = function (options) { var defaults = { allowedExtensions: [], success: function () {}, error: function () {}, }; options = $.extend(defaults, options); return this.each(function () { $(this).on(&quot;change&quot;, function () { var value = $(this).val(), file = value.toLowerCase(), extension = file.substring(file.lastIndexOf(&quot;.&quot;) + 1); if ($.inArray(extension, options.allowedExtensions) == -1) { options.error(); $(this).focus(); } else { options.success(); } }); }); }; $(&quot;#doc1&quot;).checkFileType({ allowedExtensions: [&quot;pdf&quot;], success: function () { document.getElementById(&quot;icon-cek1&quot;).className = &quot;checkmark&quot;; }, error: function () { document.getElementById('doc1').value=''; document.getElementById(&quot;icon-cek1&quot;).className = &quot;crossmark&quot;; }, }); $(&quot;#doc2&quot;).checkFileType({ allowedExtensions: [&quot;pdf&quot;], success: function () { document.getElementById(&quot;icon-cek2&quot;).className = &quot;checkmark&quot;; }, error: function () { document.getElementById(&quot;doc2&quot;).value = &quot;&quot;; document.getElementById(&quot;icon-cek2&quot;).className = &quot;crossmark&quot;; }, }); $(&quot;#doc3&quot;).checkFileType({ allowedExtensions: [&quot;pdf&quot;], success: function () { document.getElementById(&quot;icon-cek3&quot;).className = &quot;checkmark&quot;; }, error: function () { alert(&quot;Just PDF&quot;); document.getElementById(&quot;doc3&quot;).value = &quot;&quot;; document.getElementById(&quot;icon-cek3&quot;).className = &quot;crossmark&quot;; }, }); </code></pre> <p>or is there a simpler code to handle the case I have?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T18:05:38.273", "Id": "495825", "Score": "0", "body": "Snippet [link](https://jsfiddle.net/akagami45/cgvtahky/12/)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T18:07:00.883", "Id": "495826", "Score": "4", "body": "Please [edit] your question title so that it only states the task accomplished by your code. Since you are new around here, also read [ask]" } ]
[ { "body": "<p>Because the <code>&lt;div&gt;</code> associated with each <code>input</code> not its adjacent sibling, but its <em>next</em> sibling, you can dynamically navigate from the element being validated to its associated icon with <code>.nextElementSibling</code> calls. But your <code>checkFileType</code> isn't set up to call the success callback with a calling context of the element it's attached to, so fix that first. Change the success and error calls to:</p>\n<pre><code>options.success.call(this);\n</code></pre>\n<pre><code>options.error.call(this);\n</code></pre>\n<p>and then the rest of your code simplifies to the following:</p>\n<pre><code>$('input[type=&quot;file&quot;]').checkFileType({\n allowedExtensions: [&quot;pdf&quot;],\n success() {\n $(this).next().next().attr('class', 'checkmark');\n },\n error() {\n $(this).val('');\n $(this).next().next().attr('class', 'crossmark');\n },\n});\n</code></pre>\n<p>If you're going to use jQuery, go ahead and use it instead of the native DOM methods like <code>getElementById</code> if you want, native DOM methods are a bit more verbose than jQuery's <code>$</code>.</p>\n<p>Using the above method, you'll also be able to remove the IDs entirely from your HTML. (Numeric indexed IDs are quite a code smell anyway.)</p>\n<p>This is a pretty simple problem though, it seems pretty odd to need to use a big library like jQuery for something this trivial. (If you're just learning JavaScript, consider focusing on learning just built-in JavaScript rather than a particular library like jQuery, which is somewhat obsolete for most things it's used for nowadays - built-in methods work just fine and are usually easier to understand in my experience)</p>\n<p>Just as one example, rather than</p>\n<pre><code>if ($.inArray(extension, options.allowedExtensions) == -1) {\n</code></pre>\n<p>you can use</p>\n<pre><code>if (!options.allowedExtensions.includes(extension)) {\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T22:08:29.223", "Id": "251837", "ParentId": "251769", "Score": "3" } } ]
{ "AcceptedAnswerId": "251837", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T17:51:37.953", "Id": "251769", "Score": "3", "Tags": [ "javascript", "jquery", "html5" ], "Title": "my code is messy and wasteful of lines, how do I make my code simple" }
251769
<p>I was thinking of the following problem: List all sequences <span class="math-container">\$ a_1, a_2, a_3, a_4, a_5, a_6, a_7 \$</span> of positive integers where <span class="math-container">\$ 1 \le a_1 &lt; a_2 &lt; \ldots &lt; a_7 \le 39 \$</span>. For any sequence with this property, my code computes the next sequence in lexicographic order. Starting with the initial sequence <span class="math-container">\$ [1,2,3,4,5,6,7] \$</span>, calling <code>next_row(a)</code> repeatedly produces all such sequences.</p> <p>Is there more elegant way to code the function that returns the next row than this?</p> <pre><code>def next_row(a): if a[-1]&lt;39: a[-1]+=1 return a elif a[-2]&lt;38: a[-2]+=1 a[-1]=a[-2]+1 return a elif a[-3]&lt;38: a[-3]+=1 a[-2]=a[-3]+1 a[-1]=a[-2]+1 return a elif a[-4]&lt;37: a[-4]+=1 a[-3]=a[-4]+1 a[-2]=a[-3]+1 a[-1]=a[-2]+1 return a elif a[-5]&lt;36: a[-5]+=1 a[-4]=a[-5]+1 a[-3]=a[-4]+1 a[-2]=a[-3]+1 a[-1]=a[-2]+1 return a elif a[-6]&lt;35: a[-6]+=1 a[-5]=a[-6]+1 a[-4]=a[-5]+1 a[-3]=a[-4]+1 a[-2]=a[-3]+1 a[-1]=a[-2]+1 return a elif a[-7]&lt;34: a[-7]+=1 a[-6]=a[-7]+1 a[-5]=a[-6]+1 a[-4]=a[-5]+1 a[-3]=a[-4]+1 a[-2]=a[-3]+1 a[-1]=a[-2]+1 return a </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T20:30:21.900", "Id": "495845", "Score": "1", "body": "I'm a little confused, what exactly does this code do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T05:17:02.173", "Id": "495891", "Score": "0", "body": "You didn't mention in the question, but do the integers have to be consecutive? The implementation seems to imply that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T09:44:02.627", "Id": "495905", "Score": "0", "body": "I am trying to make a program that gives me random lotto rows and check if the rows for lotto covering design, if 7 numbers are chosen from 39 numbers and you win if you get 4 or more common numbers. Therefore I tried to list all possible rows." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T03:30:55.253", "Id": "496050", "Score": "0", "body": "@user232941: I have taken the liberty to edit the task description a bit, trying to make it more clear. Please check if that still matches your intentions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T05:08:35.077", "Id": "496053", "Score": "0", "body": "I'm still trying to understand what your code does, please also provide sample input/outputs :)" } ]
[ { "body": "<p>There is a lot of repetition in your code, which makes it unnecessarily long, difficult to read, difficult to maintain, and error-prone. And in fact you have an apparent copy-paste error, can you spot it?</p>\n<pre><code>if a[-1]&lt;39:\n ...\nelif a[-2]&lt;38:\n ...\nelif a[-3]&lt;38:\n ...\nelif a[-4]&lt;37:\n ...\n</code></pre>\n<p>The outer if/elif chain is to find the rightmost position in the list which can be increased, and that can be done with a loop:</p>\n<pre><code>for i in range(len(a)):\n if a[-1-i] &lt; 39 - i:\n ...\n</code></pre>\n<p>The inner repeated assignments can be replaced by a loop as well. Then your function would look like this:</p>\n<pre><code>def next_row(a):\n for i in range(len(a)):\n if a[-1-i] &lt; 39 - i:\n a[-1-i] += 1\n for j in range(0, i):\n a[-1-j] = a[-1-i] + i - j\n return a\n</code></pre>\n<p>Here <code>i</code> and <code>j</code> are positions from the end of the array as in your code, other choices are possible.</p>\n<p>The new function is shorter, more general (it works with lists of arbitrary lists, not only lists of length 7), and can easily be generalized to arbitrary upper bounds (just replace the constant 39 by a function parameter).</p>\n<p>If the intention is to enumerate all 7-element subsets of the first 39 integers then you can also use existing functions from the <a href=\"https://docs.python.org/3.8/library/itertools.html#\" rel=\"nofollow noreferrer\"><code>itertools</code></a> module, in this case <a href=\"https://docs.python.org/3.8/library/itertools.html#itertools.combinations\" rel=\"nofollow noreferrer\"><code>itertools.combinations()</code></a>:</p>\n<pre><code>import itertools\n\nrows = itertools.combinations(range(1, 40), 7)\n</code></pre>\n<p>This creates an iterator which you can access one-by-one:</p>\n<pre><code>next_row = next(rows)\nprint(next_row) \n# (1, 2, 3, 4, 5, 6, 7)\n\nnext_row = next(rows)\nprint(next_row)\n# (1, 2, 3, 4, 5, 6, 8)\n\n...\n</code></pre>\n<p>or enumerate:</p>\n<pre><code>for row in rows:\n print(row)\n</code></pre>\n<p>As a general remark, I suggest to check your code against the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8 coding style</a>, for example at <a href=\"http://pep8online.com/\" rel=\"nofollow noreferrer\">PEP8 online</a>. It will report mainly missing whitespace around operators, and wrong indentation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T17:03:16.773", "Id": "251866", "ParentId": "251771", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T19:27:27.083", "Id": "251771", "Score": "2", "Tags": [ "python", "python-3.x", "combinatorics" ], "Title": "How to find the next sequence of integers?" }
251771
<p>I just completed a snake game using object-oriented programming. The focus is on the class implementation.</p> <h1>OVERVIEW</h1> <p>Snake game works by moving the snake in order to eat fruits whilst escaping obstacles such as walls and itself.</p> <h1>Aim</h1> <ol> <li>To conform to SOLID design pattern.</li> </ol> <h1>food.h</h1> <pre><code>#ifndef SNAKEXENXIA_FOOD_H_ #define SNAKEXENXIA_FOOD_H_ class Food { public: Food() : food_char( 'O' ), x_location( 0 ), y_location( 0 ), food_size( 3 ) {} Food( const char food_chr ) : food_char( food_chr ), x_location( 0 ), y_location( 0 ), food_size( 3 ) {} Food( const char food_chr, const unsigned x_loc, const unsigned y_loc, const unsigned sz ) : food_char( food_chr ), x_location( x_loc ), y_location( y_loc ), food_size( sz ) {} char get_food_char() const { return food_char; } Food&amp; set_food_char( const char val ) { food_char = val; return *this; } unsigned get_x_location() const { return x_location; } Food&amp; set_x_location( const unsigned val ) { x_location = val; return *this; } unsigned get_y_location() const { return y_location; } Food&amp; set_y_location( const unsigned val ) { y_location = val; return *this; } unsigned get_food_size() const { return food_size; } Food&amp; set_food_size( const unsigned val ) { food_size = val; return *this; } private: char food_char; unsigned x_location; unsigned y_location; unsigned food_size; }; #endif // SNAKEXENXIA_FOOD_H_ </code></pre> <h1>snakebody.h</h1> <pre><code>#ifndef SNAKEXENXIA_SNAKEBODY_H #define SNAKEXENXIA_SNAKEBODY_H #include &lt;iostream&gt; enum class COORD { /* This specifies where the snake individual body is relative to North, South, East, West */ N = 1, S = 2, E = 3, W = 4, }; class SnakeBody { public: SnakeBody() = default; SnakeBody( const char body_chr, const COORD &amp;coord, unsigned number ) : snake_co_ordinate( coord ), x_location( 0 ), y_location( 0 ), snake_body_char( body_chr ), body_number( number ){} SnakeBody( const unsigned x_loc, const unsigned y_loc, const char body_chr, const COORD &amp;coord,\ const unsigned number ) : snake_co_ordinate( coord ), x_location( x_loc ), y_location( y_loc ), snake_body_char( body_chr ), body_number( number ){} unsigned get_x_location() const { return x_location; } SnakeBody&amp; set_x_location( const unsigned val ) { x_location = val; return *this; } unsigned get_y_location() const { return y_location; } SnakeBody&amp; set_y_location( const unsigned val ) { y_location = val; return *this; } char get_snake_body_char() const { return snake_body_char; } SnakeBody&amp; set_snake_body_char( const char val ) { snake_body_char = val; return *this; } unsigned get_number() const { return body_number; } bool operator==( const SnakeBody &amp;sb ) const; COORD snake_co_ordinate; private: unsigned x_location; unsigned y_location; char snake_body_char; unsigned body_number; // unique number to diffrentiate each snakebody }; #endif // SNAKEXENXIA_SNAKEBODY_H </code></pre> <h1>snakebody.cpp</h1> <pre><code>#include &quot;snakebody.h&quot; bool SnakeBody::operator==( const SnakeBody &amp;sb ) const { if( x_location != sb.x_location ) return false; if( y_location != sb.y_location ) return false; if( snake_body_char != sb.snake_body_char ) return false; if( snake_co_ordinate != sb.snake_co_ordinate ) return false; if( body_number != sb.body_number ) return false; return true; } </code></pre> <h1>snake.h</h1> <pre><code>#ifndef SNAKEXENXIA_SNAKE_H #define SNAKEXENXIA_SNAKE_H #include &quot;snake.h&quot; #include &lt;vector&gt; #include &quot;snakebody.h&quot; class Snake { public: Snake( const char body_chr ) : snake_char( body_chr ), can_move_north( true ), can_move_south( true ), can_move_west( true ), can_move_east( false ) { body.push_back( SnakeBody( 20, 20, 'H', COORD::W, 1 ) ); body.push_back( SnakeBody( 20, 21, snake_char, COORD::W, 2 ) ); } char get_snake_char() const { return snake_char; } Snake&amp; set_snake_char( const char val ) { snake_char = val; return *this; } void eat() { grow(); } void move_north(); void move_south(); void move_west(); void move_east(); const std::vector&lt;SnakeBody&gt;&amp; get_snake() const { return body; } unsigned get_snake_head_x() const { return body.front().get_x_location(); } unsigned get_snake_head_y() const { return body.front().get_y_location(); } private: std::vector&lt;SnakeBody&gt; body; char snake_char; bool can_move_north; bool can_move_south; bool can_move_east; bool can_move_west; /* This holds the current location of the snake Before moving N, S, E, W */ unsigned move_x; unsigned move_y; void grow(); void move_snake( const COORD &amp;coord ); void set_snake_valid_moves( const COORD &amp;coord ); }; #endif // SNAKEXENXIA_SNAKE_H </code></pre> <h1>snake.cpp</h1> <pre><code>#include &quot;snake.h&quot; void Snake::grow() { unsigned tail_x = body.back().get_x_location(); unsigned tail_y = body.back().get_y_location(); unsigned number = body.back().get_number(); if( body.back().snake_co_ordinate == COORD::N ) { SnakeBody sb( ++tail_x, tail_y, snake_char, COORD::N, ++number ); body.push_back(sb); } else if( body.back().snake_co_ordinate == COORD::S ) { SnakeBody sb( --tail_x, tail_y, snake_char, COORD::S, ++number); body.push_back(sb); } else if( body.back().snake_co_ordinate == COORD::E ) { SnakeBody sb( tail_x, ++tail_y, snake_char, COORD::E, ++number ); body.push_back(sb); } else if( body.back().snake_co_ordinate == COORD::W ) { SnakeBody sb( tail_x, --tail_y, snake_char, COORD::W, ++number ); body.push_back(sb); } else return; } void Snake::move_north() { if( can_move_north ) move_snake( COORD::N ); return; } void Snake::move_south() { if( can_move_south ) move_snake( COORD::S ); return; } void Snake::move_east() { if( can_move_east ) move_snake( COORD::E ); return; } void Snake::move_west() { if( can_move_west ) move_snake( COORD::W ); return; } void Snake::move_snake( const COORD &amp;coord ) { move_x = body.front().get_x_location(); move_y = body.front().get_y_location(); unsigned temp_x = 0; unsigned temp_y = 0; switch( coord ) { case COORD::N: body.front().set_x_location( move_x - 1 ); break; case COORD::S: body.front().set_x_location( move_x + 1 ); break; case COORD::E: body.front().set_y_location( move_y + 1 ); break; case COORD::W: body.front().set_y_location( move_y - 1 ); break; default: break; } for( auto &amp;item : body ) { item.snake_co_ordinate = coord; if( item == body.front() ) continue; /* get x and y location of snakebody before it moves */ temp_x = item.get_x_location(); temp_y = item.get_y_location(); item.set_x_location( move_x ); item.set_y_location( move_y ); /* store the x and y for next snakebody move */ move_x = temp_x; move_y = temp_y; } set_snake_valid_moves( coord ); } void Snake::set_snake_valid_moves( const COORD &amp;coord ) { switch( coord ) { case COORD::N: can_move_east = true; can_move_south = false; can_move_west = true; can_move_north = true; break; case COORD::S: can_move_east = true; can_move_north = false; can_move_west = true; can_move_south = true; break; case COORD::E: can_move_west = false; can_move_north = true; can_move_south = true; can_move_east = true; break; case COORD::W: can_move_east = false; can_move_north = true; can_move_south = true; can_move_west = true; break; default: break; } } </code></pre> <p>I also included <code>main</code>. ncurses.h is required to run main</p> <h1>main.cpp</h1> <pre><code>#include &quot;food.h&quot; #include &quot;snake.h&quot; #include &lt;iostream&gt; #include &lt;random&gt; #include &lt;vector&gt; #include &lt;ncurses.h&gt; constexpr int HEIGHT = 30; constexpr int WIDTH = 80; std::default_random_engine engine ( static_cast&lt;unsigned int&gt; (time( nullptr )) ); std::uniform_int_distribution&lt;unsigned int&gt; random_WIDTH( 1, HEIGHT ); std::uniform_int_distribution&lt;unsigned int&gt; random_HEIGHT( 1, WIDTH ); void set_food( WINDOW *win, Food &amp;food, unsigned HEIGHT, unsigned WIDTH ); void display_snake( WINDOW *win, const std::vector&lt;SnakeBody&gt;&amp; snake ); void display_food( WINDOW *win, const Food &amp;food ); bool game_over( unsigned HEIGHT, unsigned WIDTH, const std::vector&lt;SnakeBody&gt;&amp; snake ); int main() { srand( static_cast&lt;unsigned int&gt; (time( nullptr )) ); initscr(); cbreak(); noecho(); curs_set( 0 ); int start_y = ( LINES - HEIGHT ) / 2; int start_x = ( COLS - WIDTH ) / 2; refresh(); WINDOW *win = newwin( HEIGHT, WIDTH, start_y, start_x ); keypad( win, true ); box( win, 0, 0 ); wrefresh( win ); /* Initialize the game */ Food game_food('*', 4, 5, 4 ); Snake game_snake( 'O' ); std::vector&lt;SnakeBody&gt; snake_vector = game_snake.get_snake(); set_food( win, game_food, HEIGHT, WIDTH ); display_food( win, game_food ); display_snake( win, snake_vector ); unsigned head_x, head_y; bool game_is_over = false; while( !game_is_over ) { int c = wgetch( win ); switch( c ) { case KEY_UP: game_snake.move_north(); break; case KEY_DOWN: game_snake.move_south(); break; case KEY_LEFT: game_snake.move_west(); break; case KEY_RIGHT: game_snake.move_east(); break; default: break; } snake_vector = game_snake.get_snake(); game_is_over = game_over( HEIGHT, WIDTH, snake_vector ); /* clear and reinitialize the screen */ wclear( win ); display_food( win, game_food ); box( win, 0, 0 ); display_snake( win, snake_vector ); wrefresh( win ); head_x = game_snake.get_snake_head_x(); head_y = game_snake.get_snake_head_y(); if( head_x == game_food.get_x_location() &amp;&amp; head_y == game_food.get_y_location() ) { game_snake.eat(); mvwaddch( win, game_food.get_y_location(), game_food.get_x_location(), ' ' ); set_food( win, game_food, HEIGHT, WIDTH ); wrefresh( win ); } } endwin(); } void set_food( WINDOW *win, Food &amp;food, unsigned height, unsigned width ) { unsigned x = random_WIDTH( engine ); unsigned y = random_HEIGHT( engine ); while( x &gt; height - 2 || y &gt; width - 2 ) { x = random_WIDTH( engine ); y = random_HEIGHT( engine ); } food.set_x_location( x ).set_y_location( y ); } void display_snake( WINDOW *win, const std::vector&lt;SnakeBody&gt;&amp; snake ) { for( const auto &amp;item : snake ) { mvwaddch( win, item.get_x_location(), item.get_y_location(), item.get_snake_body_char() ); } } void display_food( WINDOW *win, const Food &amp;food ) { mvwaddch( win, food.get_x_location(), food.get_y_location(), food.get_food_char() ); } bool game_over( unsigned height, unsigned width, const std::vector&lt;SnakeBody&gt;&amp; snake ) { unsigned snake_head_x = snake.front().get_x_location(); unsigned snake_head_y = snake.front().get_y_location(); if( snake_head_x &gt; height - 2 || snake_head_x &lt;= 0 ) return true; if( snake_head_y &gt; width - 2 || snake_head_y &lt;= 0 ) return true; for( const auto &amp;item : snake ) { if( item == snake.front() ) continue; if( item.get_x_location() == snake_head_x &amp;&amp; item.get_y_location() == snake_head_y ) return true; } return false; } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h1>Avoid setters and getters</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code> unsigned get_x_location() const { return x_location; }\n Food&amp; set_x_location( const unsigned val );\n unsigned get_y_location() const { return y_location; }\n Food&amp; set_y_location( const unsigned val );\n</code></pre>\n<p>For such a simple variable like <code>x_location</code>, having a setter/getter pair just means writing more lines for no good reason, why not make <code>x_location</code> public in the first place? <br>Now there is no point in the variable being <code>private</code>. If you keep following this pattern, you'll be forced to create a new getter/setter pair for every new variable that should be <code>public</code></p>\n<p>Your new <code>Food</code> class would be</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>struct Food\n{\n char food_char;\n unsigned x_location;\n unsigned y_location;\n\n // ctors..\n};\n</code></pre>\n<p>This applies to all of your other classes</p>\n<hr />\n<h1>Representing a position</h1>\n<p>You have a lot of these pairs</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>unsigned x_location;\nunsigned y_location;\n</code></pre>\n<p>I highly recommend you use <a href=\"https://en.cppreference.com/w/cpp/utility/pair\" rel=\"nofollow noreferrer\">std::pair</a> for this and just keep <code>position</code>. Even something like</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>struct Position\n{\n int x, y;\n\n Position(const int x, const int y)\n : x(x), y(y)\n {}\n};\n</code></pre>\n<p>will be much better.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>Position position;\n</code></pre>\n<hr />\n<h1>Unnecessary <code>return;</code></h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>void Snake::move_north()\n{\n if( can_move_north )\n move_snake( COORD::N );\n return;\n}\n\nvoid Snake::move_south()\n{\n if( can_move_south )\n move_snake( COORD::S );\n return;\n}\n\nvoid Snake::move_east()\n{\n if( can_move_east )\n move_snake( COORD::E );\n return;\n}\n\nvoid Snake::move_west()\n{\n if( can_move_west )\n move_snake( COORD::W );\n return;\n}\n</code></pre>\n<p>What purpose do these <code>return;</code> statements serve here? <strong>Nothing</strong>, they are quite unnecessary here.</p>\n<hr />\n<h1><code>set_snake_valid_moves()</code></h1>\n<p>Let's have a look at this function</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void Snake::set_snake_valid_moves( const COORD &amp;coord )\n{\n switch( coord )\n {\n case COORD::N:\n can_move_east = true;\n can_move_south = false;\n can_move_west = true;\n can_move_north = true;\n break;\n case COORD::S:\n can_move_east = true;\n can_move_north = false;\n can_move_west = true;\n can_move_south = true;\n break;\n case COORD::E:\n can_move_west = false;\n can_move_north = true;\n can_move_south = true;\n can_move_east = true;\n break;\n case COORD::W:\n can_move_east = false;\n can_move_north = true;\n can_move_south = true;\n can_move_west = true;\n break;\n default:\n break;\n }\n}\n</code></pre>\n<p>I have a problem here. Out of the 4 directions, there will always be only one direction that the snake cannot move to. So instead of having 4 directions = <code>can_move_west, can_move_east</code>..., why not just have <strong>one</strong> <code>cannot_move</code> direction?</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void Snake::set_snake_valid_moves( const COORD &amp;coord )\n{\n switch( coord )\n {\n case COORD::N:\n cannot_move == COORD::S;\n break;\n case COORD::S:\n cannot_move = COORD::N;\n break;\n case COORD::E:\n cannot_move = COORD::W;\n break;\n case COORD::W:\n cannot_move = COORD::E;\n break;\n\n default:\n break;\n }\n}\n</code></pre>\n<p>Or,</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>if (coord == COORD::S) cannot_move = COORD::N;\nelse if (coord == COORD::E) cannot_move = COORD::W;\nelse if (coord == COORD::W) cannot_move = COORD::E;\nelse if (coord == COORD::N) cannot_move = COORD::S;\n</code></pre>\n<p>That way, when you have to check if a certain <code>direction</code> is valid i.e doesn't break this rule, you can simply do</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>if ( direction != cannot_move) //...\n</code></pre>\n<p>as simple as that</p>\n<hr />\n<h1>When should you pass by <code>&amp;</code></h1>\n<p>I see a lot of</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>const COORD &amp;coord\n</code></pre>\n<p>When you pass by reference, you are implicitly passing a pointer to the object. In this case, <code>COORD</code> has an underlying type of <code>int</code>.</p>\n<p>The size of <code>int</code> differs a lot, mostly it is 4-bytes. You can check for yourself by doing\n<code>std::cout &lt;&lt; sizeof(int);</code>. For me, it's 4.</p>\n<p>As I said, passing by reference implicitly passes a pointer. The size of a pointer is <strong>8 bytes</strong>. which is double the size of <code>int</code>.\nIt's doing you no good. As a rule of thumb, you don't need to pas the primitive types i.e <code>int, char, float</code> as a reference. However, if you have something bigger like a <code>std::vector</code>, passing by value will be much more expensive.</p>\n<hr />\n<h1>Moving the snake</h1>\n<p>After I read your method, I understand that you are updating the whole body of the snake by assigning the position of <code>snake[n]</code> to <code>snake[n+1</code>. While this is okay, I propose another method. <br>\nWhat you can do here is pop back the last part of the snake, or its <code>tail</code> and add that to the front.</p>\n<p><a href=\"https://i.stack.imgur.com/HxlfW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HxlfW.png\" alt=\"enter image description here\" /></a></p>\n<p>Procedure</p>\n<ul>\n<li>Pop the last element</li>\n<li>Create a new body part</li>\n<li>Set its new position to be <code>positon_of_head + offset</code> where offset is the change ( the distance to be moved ). Basically, the future position of the head</li>\n<li>Repeat</li>\n</ul>\n<p>For this, you need to just a container like <a href=\"https://en.cppreference.com/w/cpp/container/deque\" rel=\"nofollow noreferrer\">std::deque</a> which allowest fast insertion/deletion at both ends\n<br> <code>std::vector</code> doesn't work here since it has a very slow insertion at front</p>\n<hr />\n<h1>Smaller suggestions</h1>\n<ul>\n<li><code>void eat() { grow; }</code>?? Why create this bridge, just make <code>grow()</code> public</li>\n<li>Keep your <code>main()</code> clean, create another file / class to handle the GUI</li>\n</ul>\n<h1>final thoughts</h1>\n<p>I like the design of your program, here are some things that I <strong>don't like</strong></p>\n<ul>\n<li>Overcomplication of many classes. Keep it simple, there only a few attributes <code>Food</code> can have, but at first glance, it looks huge</li>\n<li>Noise in <code>main.cpp</code>. I don't like the GUI handling in main, I highly suggest that you create a class of its own, which would handle all of that</li>\n<li></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T22:35:04.413", "Id": "495855", "Score": "3", "body": "Great. Thanks for the really optimized snake movement algorithm. smashed an O(n) operation to O(1)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T22:38:38.360", "Id": "495856", "Score": "3", "body": "I had a thought about the grow(). I came to this conclusion, the user should not have a say about whether the snake grows or not, all the user can do is simply make the snake eat. Though the snakes grows whenever it eats :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T22:40:36.403", "Id": "495857", "Score": "1", "body": "If I may ask, calling snakebody constructor every single time a movement is made, won't that be quite expensive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T22:44:00.020", "Id": "495858", "Score": "1", "body": "@theProgrammer You've actually over complicated the snake body class a lot, it should just be containing a position and it's character. With that, no." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T01:34:36.247", "Id": "495869", "Score": "1", "body": "If you have more than one value to return from a function then passing basic variables by reference does make sense. If speed is a concern then passing basic variables by reference may also make sense so that the copy doesn't happen." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T03:53:41.300", "Id": "495879", "Score": "0", "body": "@pacmanibw Yes that's true, but in this case that wasn't the intent" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T04:46:05.173", "Id": "495885", "Score": "0", "body": "@Aryan Parekh. Great review, but I was hoping to get a review on the class design, if it follows SOLID design pattern, that's my major concern." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T06:44:36.870", "Id": "495895", "Score": "1", "body": "@theProgrammer I have edited my answer and put in my thoughts" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T22:03:31.820", "Id": "251781", "ParentId": "251773", "Score": "9" } } ]
{ "AcceptedAnswerId": "251781", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T19:38:10.640", "Id": "251773", "Score": "9", "Tags": [ "c++", "object-oriented", "design-patterns", "snake-game" ], "Title": "Snake Game Object Oriented Approach" }
251773
<p>I've been learning PHP and I've created a phone book webpage as an exercise. I am satisfied with the way it works -- it seems to handle all possible input cases correctly, and the interface feels nice and solid. I would appreciate feedback on the code style, as well as suggestions for what would be a better or more idiomatic way to organize it.</p> <p><a href="https://i.stack.imgur.com/mGseU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mGseU.png" alt="enter image description here" /></a></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Phone Book&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;//fonts.googleapis.com/css?family=Ubuntu+Mono:300,400,600,700&amp;amp;lang=en&quot; /&gt; &lt;style&gt; body { font-family: Ubuntu Mono; background-color: #F2F1F0; } .form-control { border-radius: 0; border: 1px solid #AEA79F; } .btn-default { background-color: #EEEDEB; } .form-control:focus { border: 1px solid #E95420 !important; box-shadow: none !important; } .btn:focus, .btn:active { outline: none !important; box-shadow: none; } .header { text-shadow: 0px 1px #666; box-shadow: 0 0px 0 #F6BBA6 inset; color: #F6F6F5; background-color: #E95420; font-size: 28px; font-weight: bold; padding: 1px; padding-left: 20px; border: 1px solid #555; margin-top: 12px; } .c2 { background-color: #FFF; border: 1px solid #666; border-top: none; padding: 18px; } .msg { border: 1px solid #AEA79F; border-style: dashed; padding: 8px; margin-bottom: 18px; } .table td, th { border: 1px solid #AEA79F !important; border-style: dotted !important; } .spc { padding: 18px; } .inv { display: none; } input[type=&quot;radio&quot;] { margin: 5px; margin-top: 4px; vertical-align: middle; } input:invalid { border: 1px solid red; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;header&quot;&gt;Phone Book&lt;/div&gt; &lt;div class=&quot;c2&quot;&gt; &lt;form action=&quot;PhoneForm.php&quot; method=&quot;post&quot;&gt; &lt;div class=&quot;col-xs-5&quot; style=&quot;padding: 1px&quot;&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; name=&quot;name&quot; id=&quot;name&quot; placeholder=&quot;Name&quot; maxlength=&quot;36&quot;&gt; &lt;/div&gt; &lt;div class=&quot;col-xs-5&quot; style=&quot;padding: 1px;&quot;&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; name=&quot;phone&quot; id=&quot;phone&quot; placeholder=&quot;Phone Number&quot; maxlength=&quot;17&quot;&gt; &lt;div class=&quot;phonetypes&quot; class=&quot;inv&quot;&gt; &lt;input type=&quot;radio&quot; name=&quot;phonetype&quot; value=&quot;other&quot; CHECKED&gt;Other&lt;input type=&quot;radio&quot; name=&quot;phonetype&quot; value=&quot;home&quot;&gt;Home &lt;input type=&quot;radio&quot; name=&quot;phonetype&quot; value=&quot;work&quot;&gt;Work &lt;input type=&quot;radio&quot; name=&quot;phonetype&quot; value=&quot;cell&quot;&gt;Cell &lt;input type=&quot;radio&quot; name=&quot;phonetype&quot; value=&quot;fax&quot;&gt;Fax &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-xs-1&quot; style=&quot;padding: 1px&quot;&gt; &lt;select class=&quot;form-control&quot; id=&quot;actions&quot; name=&quot;actions&quot;&gt; &lt;option value=&quot;add&quot;&gt;Add&lt;/option&gt; &lt;option value=&quot;find&quot; selected&gt;Find&lt;/option&gt; &lt;option value=&quot;delete&quot;&gt;Delete&lt;/option&gt; &lt;option value=&quot;update&quot;&gt;Update&lt;/option&gt; &lt;option value=&quot;viewall&quot;&gt;View All&lt;/option&gt;; &lt;/select&gt; &lt;/div&gt; &lt;div class=&quot;col-xs-1&quot; style=&quot;padding: 1px&quot;&gt; &lt;input type=&quot;submit&quot; class=&quot;btn btn-default form-control&quot; name=&quot;btn&quot; value=&quot;Go&quot;&gt; &lt;/div&gt; &lt;BR&gt; &lt;div class=&quot;spc&quot;&gt;&lt;/div&gt; &lt;/form&gt; &lt;script&gt; var actions = document.getElementById('actions'); var phonetypes = document.querySelector('.phonetypes'); var phone = document.getElementById('phone'); var name = document.getElementById('name'); //var pattern_phone = phone.getAttribute(&quot;pattern&quot;); //var pattern_name = name.getAttribute(&quot;pattern&quot;); phonetypes.classList.add('inv'); actions.addEventListener('change', function() { if (actions.value == 'update') { name.placeholder = &quot;Old Name&quot;; phone.placeholder = &quot;New Name&quot;; // phone.setAttribute(&quot;pattern&quot;, pattern_name); } else { name.placeholder = &quot;Name&quot;; phone.placeholder = &quot;Phone Number&quot;; //phone.setAttribute(&quot;pattern&quot;, pattern_phone); } if (actions.value == 'add') { phonetypes.classList.remove('inv'); } else { phonetypes.classList.add('inv'); } }); &lt;/script&gt; &lt;?php $host = &quot;localhost&quot;; $user = &quot;user&quot;; $pass = &quot;pass&quot;; $db = &quot;db&quot;; $mysqli = new mysqli($host, $user, $pass, $db); if (mysqli_connect_errno()) { die(&quot;Unable to connect.&quot;); } $show_all = &quot;select Name, PhoneNumber, PhoneType, person.PersonID from person,phone where person.PersonID = phone.personID&quot;; $listquery = $show_all; msg_info(&quot;Displaying all entries.&quot;); $name = trim($_POST[&quot;name&quot;]); $phone = trim($_POST[&quot;phone&quot;]); $phonetype = trim($_POST[&quot;phonetype&quot;]); $action = trim($_POST['actions']); if ($btn = $_POST['btn']) { switch ($action) { case ('viewall'): $listquery = $show_all; msg_info(&quot;Displaying all entries.&quot;); break; /* --------------------------------------------------------------- */ case ('add'): if (! ($name or $phone)) { msg_warn(&quot;Enter a name and/or number to add.&quot;); break; } if (! ($name)) { msg_warn(&quot;Enter a name to be associated with this number.&quot;); break; } // is person already there? $query = &quot;select PersonID from person where Name like ('&quot; . $name . &quot;')&quot;; if ($id = $mysqli-&gt;query($query)-&gt;fetch_object()-&gt;PersonID) { // if person is there and we have an input phone number, assign // the number to him. if ($phone) { // check to see if he already has this number if ($result = $mysqli-&gt;query( &quot;select * from phone where PhoneNumber like '&quot; . $phone . &quot;' and PersonID = &quot; . $id . &quot;&quot;)-&gt;fetch_object()) { msg_warn( &quot;Person '&quot; . $name . &quot;' already has number '&quot; . $phone . &quot;'.&quot;); break; } // add new phone $q1 = &quot;insert into phone (PersonID, PhoneNumber, PhoneType) values (&quot; . $id . &quot;, '&quot; . $phone . &quot;', '&quot; . $phonetype . &quot;')&quot;; // get rid of dummy phone if there is one $q2 = &quot;delete from phone where PersonID = &quot; . $id . &quot; and PhoneNumber = 'none'&quot;; // queries okay? if ($mysqli-&gt;query($q1) &amp;&amp; $mysqli-&gt;query($q2)) { msg_success( &quot;Added &quot; . $phonetype . &quot; number '&quot; . $phone . &quot;' for person '&quot; . $name . &quot;'.&quot;); } else { msg_error( &quot;Error adding number '&quot; . $phone . &quot;' for person '&quot; . $name . &quot;': &quot; . $mysqli-&gt;error); } break; } // otherwise, do nothing else { msg_warn(&quot;'&quot; . $name . &quot;' is already in the phone book.&quot;); break; } } // if the person is not there, add him // and create dummy phone if none specified $newphone = $phone ? $phone : &quot;none&quot;; $q1 = &quot;insert into person (Name) values ('&quot; . $name . &quot;')&quot;; $q2 = &quot;set @id = (select PersonID from person where Name like ('&quot; . $name . &quot;'))&quot;; $q3 = &quot;insert into phone (PersonID, PhoneNumber, PhoneType) values (@id, '&quot; . $newphone . &quot;', '&quot; . $phonetype . &quot;')&quot;; // queries okay? if (! ($mysqli-&gt;query($q1) and $mysqli-&gt;query($q2) and $mysqli-&gt;query($q3))) { msg_error( &quot;Error adding '&quot; . $name . &quot;' to the phone book: &quot; . $mysqli-&gt;error); break; } // good; we are done msg_success( &quot;Added '&quot; . $name . &quot;' to the phone book&quot; . ($newphone == 'none' ? &quot;.&quot; : &quot; with &quot; . $phonetype . &quot; number &quot; . $newphone . &quot;.&quot;)); break; /* --------------------------------------------------------------- */ case ('find'): // does exactly one of the fields have input? if (! ($name xor $phone)) { msg_warn(&quot;Enter either a name or a number to find.&quot;); break; } // pick query based on which field has input if ($name) { $info = $name; // includes wild cards $q1 = &quot;select Name, PhoneNumber, PhoneType from phone, person where phone.PersonID = person.PersonID and Name like '%&quot; . $name . &quot;%'&quot;; } if ($phone) { $info = $phone; $q1 = &quot;select Name, PhoneNumber, PhoneType from phone, person where phone.PersonID = person.PersonID and PhoneNumber like '&quot; . $phone . &quot;'&quot;; } // query okay? if (! ($result = $mysqli-&gt;query($q1))) { $msg = &quot;Error searching for '&quot; . $info . &quot;': &quot; . $mysqli-&gt;error; $msg_color = $col_error; break; } // good; we are done if (($nr = $result-&gt;num_rows) &gt; 0) { msg_info( &quot;Displaying &quot; . $nr . &quot; result&quot; . ($nr &gt; 1 ? &quot;s&quot; : &quot;&quot;) . &quot; for '&quot; . $info . &quot;'.&quot;); } else { msg_info(&quot;No results for '&quot; . $info . &quot;'.&quot;); } $listquery = $q1; break; /* --------------------------------------------------------------- */ case ('delete'): if (! ($name || $phone)) { msg_warn(&quot;Enter a name and/or a number to delete.&quot;); break; } if ($phone &amp;&amp; $name) { // if both a phone and a person are entered, delete the phone // for that person only $q1 = &quot;set @id = (select PersonID from person where Name like ('&quot; . $name . &quot;'))&quot;; $q2 = &quot;delete from phone where PhoneNumber like '&quot; . $phone . &quot;' and PersonID = @id&quot;; if (! ($mysqli-&gt;query($q1) &amp;&amp; $mysqli-&gt;query($q2))) { msg_error( &quot;Error deleting number '&quot; . $phone . &quot; for person '&quot; . $name . &quot;': &quot; . $mysqli-&gt;error); break; } if ($mysqli-&gt;affected_rows &gt; 0) { msg_success( &quot;Removed number '&quot; . $phone . &quot;' for person '&quot; . $name . &quot;'.&quot;); } else { msg_warn( &quot;No name '&quot; . $name . &quot;' associated with number '&quot; . $phone . &quot;'.&quot;); } break; } else { if ($name) { $info = $name; $q1 = &quot;delete from person where Name like '&quot; . $name . &quot;'&quot;; } // if just a phone is entered, delete all instances of it if ($phone) { $info = $phone; // unfortunately we have to make sure everyone affected by // the phone delete has at least a dummy phone number // otherwise they won't show up. // working around a poor design choice $q1 = &quot;select phone.PersonID from phone, person where phone.PersonID = person.PersonID and PhoneNumber like '&quot; . $phone . &quot;'&quot;; if ($result = $mysqli-&gt;query($q1)) { while ($person_with_this_number = $result-&gt;fetch_array()) { $id = $person_with_this_number[0]; $cnt = $mysqli-&gt;query( &quot;select count(*) as c from phone where PersonID = &quot; . $id)-&gt;fetch_object()-&gt;c; // is this someone's only number? if ($cnt == '1') { // if so, then replace it with a dummy if (! ($mysqli-&gt;query( &quot;insert into phone values (&quot; . $id . &quot;, 'none', 'none')&quot;))) { msg_error($mysqli-&gt;error); break; } } } } $q1 = &quot;delete from phone where PhoneNumber like '&quot; . $phone . &quot;'&quot;; } if (! ($mysqli-&gt;query($q1))) { msg_error( &quot;Error deleting &quot; . ($info == $name ? &quot;person&quot; : &quot;phone&quot;) . &quot; '&quot; . $info . &quot;': &quot; . $mysqli-&gt;error); break; } } if ($mysqli-&gt;affected_rows &gt; 0) { msg_success(&quot;Removed '&quot; . $info . &quot;' from the phone book.&quot;); } else { msg_warn(&quot;'&quot; . $info . &quot;' is not in the phone book.&quot;); } break; /* --------------------------------------------------------------- */ case ('update'): // there is some javascript that changes the form placeholders // if 'update' is selected $oldname = $name; $newname = $phone; // is a name entered in both fields? if (! ($oldname &amp;&amp; $newname)) { msg_warn(&quot;Enter a name and a new name to replace it with.&quot;); break; } // is the person in the phone book? $q1 = &quot;select * from person where name like '&quot; . $oldname . &quot;'&quot;; if (! ($mysqli-&gt;query($q1)-&gt;num_rows &gt; 0)) { msg_warn(&quot;'&quot; . $oldname . &quot;' is not in the phone book.&quot;); break; } // is the new name different from the old one? if ($oldname == $newname) { msg_info( &quot;New name is the same as old name; no information was changed.&quot;); break; } // if ($mysqli-&gt;query( &quot;update person set Name = '&quot; . $newname . &quot;' where name = '&quot; . $oldname . &quot;'&quot;)) { msg_success( &quot;Changed name '&quot; . $oldname . &quot;' to '&quot; . $newname . &quot;'.&quot;); } else { msg_error(&quot;Error updating name: &quot; . $mysqli-&gt;error); } break; } } display($listquery); /* --------------------------------------------------------------- */ function msg_error ($msg) { $GLOBALS['msg'] = $msg; $GLOBALS['msg_color'] = &quot;#ffe3db&quot;; } function msg_success ($msg) { $GLOBALS['msg'] = $msg; $GLOBALS['msg_color'] = &quot;#deffdb&quot;; } function msg_info ($msg) { $GLOBALS['msg'] = $msg; $GLOBALS['msg_color'] = &quot;#f7fffe&quot;; } function msg_warn ($msg) { $GLOBALS['msg'] = $msg; $GLOBALS['msg_color'] = &quot;#fff9d4&quot;; } function display ($query) { echo '&lt;div class=&quot;msg&quot; style=&quot;background-color: ' . $GLOBALS['msg_color'] . ';&quot;&gt; ' . $GLOBALS['msg'] . ' &lt;/div&gt;'; if ($result = $GLOBALS['mysqli']-&gt;query($query)) { if ($result-&gt;num_rows &gt; 0) { echo '&lt;table class=&quot;table table-bordered table-striped&quot;&gt; &lt;tr&gt; &lt;th&gt; Name &lt;/th&gt; &lt;th&gt; Number &lt;/th&gt; &lt;th&gt; Type &lt;/th&gt;'; $last = &quot;&quot;; $name = &quot;&quot;; $phone = &quot;&quot;; $type = &quot;&quot;; while ($row = $result-&gt;fetch_array(MYSQLI_ASSOC)) { echo '&lt;tr&gt;'; if ($row[&quot;Name&quot;] != $last) { $last = $row[&quot;Name&quot;]; $name = $last; } else { $name = &quot;&quot;; } if ($row[&quot;PhoneNumber&quot;] != &quot;none&quot;) { $phone = $row[&quot;PhoneNumber&quot;]; $type = $row[&quot;PhoneType&quot;]; } else { $phone = &quot;(No number)&quot;; $type = &quot;&quot;; } echo &quot;&lt;td&gt; $name &lt;/td&gt; &lt;td&gt; $phone &lt;/td&gt; &lt;td&gt; $type &lt;/td&gt; &lt;/tr&gt;&quot;; } echo &quot;&lt;/table&gt;&quot;; } $result-&gt;close(); } else { echo &quot;Error in query: &quot; . $GLOBALS['mysqli']-&gt;error; } } /* --------------------------------------------------------------- */ ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>Your project looks nice, and the design of your web page is good. There were a few points I spotted with the code that are well worth taking note of.</p>\n<h2>Security</h2>\n<p>While security may sound less important if you're the only one using the project, the issues below are both critical for any public-facing website, and affect the correctness of the program as pointed out by ComFreek and the other answers. Your site should be able to cope with any user input, even that deliberately designed to cause problems, in order to be fully correct.</p>\n<p>It's useful to stick to best practices for any project so you remember to do things the safe way.</p>\n<ul>\n<li><p>Your code appears to be vulnerable to <a href=\"https://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow noreferrer\">SQL injection</a>. Whenever you want to perform a database query with user input, you cannot trust that the data the user gives is safe to put straight into a query. You should consider using <em>prepared statements</em> and the <a href=\"https://www.php.net/manual/en/pdo.prepared-statements.php\" rel=\"nofollow noreferrer\">PDO</a> extension of PHP. If you don't do this, a malicious user could choose a name like <code>');drop table person;#</code>. This would evaluate your query as</p>\n<pre class=\"lang-sql prettyprint-override\"><code>select PersonID from person where Name like ('');drop table person;#')\n ----------------------\n</code></pre>\n<p>so the attacker has now deleted your entire <code>person</code> database. The dashes show you where I substituted the name into the query, as PHP would.</p>\n</li>\n<li><p>Your code also seems vulnerable to <a href=\"https://owasp.org/www-project-top-ten/2017/A7_2017-Cross-Site_Scripting_(XSS)\" rel=\"nofollow noreferrer\">cross-site scripting</a> (XSS). Suppose a user entered a name along the lines of</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;script&gt; alert(&quot;Hello, world&quot;); &lt;/script&gt;\n</code></pre>\n<p>Your web page then embeds this into the HTML, so your browser will run the script. This can be exploited in all sorts of ways, and you'll find many examples on the web where this type of attack has been successful. One option is to ensure any user input you display has been sanitised with <a href=\"https://www.php.net/htmlspecialchars\" rel=\"nofollow noreferrer\"><code>htmlspecialchars</code></a>. You could, for example, escape the data before inputting it into the database. It's very easy to forget this, so a more robust option is to use a <em>templating engine</em> such as <a href=\"https://twig.symfony.com/\" rel=\"nofollow noreferrer\">Twig</a>. This will automatically escape any variables you display unless you specifically ask not to do this.</p>\n</li>\n<li><p>Storing your database connection credentials in the code is often discouraged for production-level code. See, for example this <a href=\"https://security.stackexchange.com/questions/13353/is-it-safe-to-store-the-database-password-in-a-php-file\">Security Stack Exchange</a> post on the topic. Instead, store the credentials in a configuration file, or as an environment variable.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T10:15:15.673", "Id": "495906", "Score": "1", "body": "I disagree with the sentiment that the security-related suggestions aren't important if OP is the only one using the app. SQL injections and XSS are not mere vulnerabilities -- **they make the code incorrect**. For example, entering any text value with quotes or HTML syntax will lead to query or UI errors. Apart from that major point, you also want to never get into the habit of coding like this lest you repeat the errors again and again in production systems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T10:27:19.100", "Id": "495908", "Score": "0", "body": "@ComFreek That is a very good point regarding the correctness, thanks. I've reconsidered my statement on that because as you rightly point out, even if you didn't care about security (which you certainly should) the code will still fail on real data that could genuinely be put into the site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T14:37:12.443", "Id": "495931", "Score": "1", "body": "Good suggestion to use Twig. If you later develop in Python and Flask for example you will notice the similarities with the Jinja templating engine." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T20:13:08.003", "Id": "251775", "ParentId": "251774", "Score": "10" } }, { "body": "<h2>Security</h2>\n<p>Security is super important. In 2020 it is not acceptable to write code that is blatantly vulnerable to SQL injection. Start taking good habits today.</p>\n<p>Even if you are lazy and you are the only one using this application you should still fix the SQL injection vulnerabilities because your code will choke on single quotes - and single quotes in family names are not uncommon (eg O'hara). This code is broken anyway.</p>\n<p>Don't show full error messages to users. In this case this would only help hackers by giving them insight into your database structure, and help them take over your site.</p>\n<p>I am also wondering how your form will behave if Javascript is not enabled on the browser ? It may degrade or not work properly. At the very least it should not cause security issues or lead to erratic behavior impacting the data.</p>\n<h2>CSS</h2>\n<p>I see that you are using Bootstrap but we are at version 4 right ? Consider bringing your code up to date while you are in the early stages of design. Then you have some more CSS, I suppose it is a mix of additional styles and Bootstrap overrides. I suggest that you move all your CSS to a separate .css file so as to declutter your file (= less scrolling, less distraction). It should come last if it contains Bootstrap overrides. Then you'll have more than 70 lines of code out of your sight.</p>\n<p>You also have some inline CSS like:</p>\n<pre><code>&lt;div class=&quot;col-xs-5&quot; style=&quot;padding: 1px&quot;&gt;\n</code></pre>\n<p>repeated several times, then it would make sense to redefine styles col-xs-5 and col-xs-1 instead. This will avoid lots of search &amp; replace if you want to tweak the layout in the future. The idea is to avoid repetition.</p>\n<p>Same remark about your Javascript: it can go to an external file, and you reduce your overall code by another 30 lines.</p>\n<p>An added benefit is that your browser can keep the external files in cache.</p>\n<h2>DB connection</h2>\n<p>For the database connection you might keep it in an include file, especially if the code is going to be reused in other pages.</p>\n<h2>Performing deletes</h2>\n<p>I can't test your code locally but I think some of the logic is flawed, for example the delete:</p>\n<pre><code> $q1 = &quot;set @id = (select PersonID from person where Name like ('&quot; .\n $name . &quot;'))&quot;;\n $q2 = &quot;delete from phone where PhoneNumber like '&quot; . $phone .\n &quot;' and PersonID = @id&quot;;\n</code></pre>\n<p>First you fetch the ID of the person based on the name, then you proceed to delete a phone number belonging to that person. But what happens if you have two persons with the same name ? In this case the query would fail because it returns more than one row. In other cases you might destroy data because of the criteria returning more records than intended.</p>\n<p>Normally, you would keep a database ID for each phone number in a hidden field in your form, and this is what you send in your POST request. The delete should then be performed on the basis of that ID. The two-step process is redundant and unsafe.</p>\n<p>Same remark for deleting a person, provide an ID that is unique as a criterion.</p>\n<p>You don't even need a LIKE if you are not using % for pattern matching, just use =.</p>\n<h2>Orphaned users</h2>\n<p>To get round this problem:</p>\n<pre><code> // unfortunately we have to make sure everyone affected by\n // the phone delete has at least a dummy phone number\n // otherwise they won't show up.\n // working around a poor design choice\n\n $q1 = &quot;select phone.PersonID from phone, person where phone.PersonID = person.PersonID and PhoneNumber like '&quot; .\n $phone . &quot;'&quot;;\n</code></pre>\n<p>It seems to me that you just need an OUTER JOIN or <code>phone.PersonID =* person.PersonID</code>. Feeding your database with garbage data is indeed not a good thing.</p>\n<h2>Use transactions</h2>\n<p>You should use <a href=\"https://www.mysqltutorial.org/mysql-transaction.aspx/\" rel=\"noreferrer\">transactions</a> if you perform multiple, related operations in one batch. If one statement fails in the middle for any reason, you will end up with inconsistent data or orphaned records.</p>\n<h2>Reserved keywords</h2>\n<p>Look at this query again:</p>\n<pre><code> $q1 = &quot;set @id = (select PersonID from person where Name like ('&quot; .\n $name . &quot;'))&quot;;\n</code></pre>\n<p>Name is a <a href=\"https://dev.mysql.com/doc/refman/8.0/en/keywords.html\" rel=\"noreferrer\">reserved keyword</a> in Mysql, it should be avoided for naming objects. It's still possible to enclose them within brackets or backticks but not recommended.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T04:24:29.860", "Id": "495884", "Score": "0", "body": "`Start taking good habits today.` I wish everyone would :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T23:08:36.553", "Id": "251783", "ParentId": "251774", "Score": "10" } }, { "body": "<p>I've noticed that you are using Bootstrap 3.3.6, which isn't maintained anymore.</p>\n<p>The latest 3.x version is 3.4.1, and you should consider using it.</p>\n<hr>\n<p>However, you're doing something wrong:<br />\n<strong>You are misusing the framework</strong></p>\n<p>Below is a copy part of the HTML, with all the CSS:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n font-family: Ubuntu Mono;\n background-color: #F2F1F0;\n}\n\n.form-control {\n border-radius: 0;\n border: 1px solid #AEA79F;\n}\n\n.btn-default {\n background-color: #EEEDEB;\n}\n\n.form-control:focus {\n border: 1px solid #E95420 !important;\n box-shadow: none !important;\n}\n\n.btn:focus, .btn:active {\n outline: none !important;\n box-shadow: none;\n}\n\n.header {\n text-shadow: 0px 1px #666;\n box-shadow: 0 0px 0 #F6BBA6 inset;\n color: #F6F6F5;\n background-color: #E95420;\n font-size: 28px;\n font-weight: bold;\n padding: 1px;\n padding-left: 20px;\n border: 1px solid #555;\n margin-top: 12px;\n}\n\n.c2 {\n background-color: #FFF;\n border: 1px solid #666;\n border-top: none;\n padding: 18px;\n}\n\n.msg {\n border: 1px solid #AEA79F;\n border-style: dashed;\n padding: 8px;\n margin-bottom: 18px;\n}\n\n.table td, th {\n border: 1px solid #AEA79F !important;\n border-style: dotted !important;\n}\n\n.spc {\n padding: 18px;\n}\n\n.inv {\n display: none;\n}\n\ninput[type=\"radio\"] {\n margin: 5px;\n margin-top: 4px;\n vertical-align: middle;\n}\n\ninput:invalid {\n border: 1px solid red;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\"&gt;\n\n&lt;link rel=\"stylesheet\" href=\"//fonts.googleapis.com/css?family=Ubuntu+Mono:300,400,600,700&amp;amp;lang=en\" /&gt;\n\n&lt;div class=\"container\"&gt;\n\n &lt;div class=\"header\"&gt;Phone Book&lt;/div&gt;\n\n &lt;div class=\"c2\"&gt;\n\n &lt;form action=\"PhoneForm.php\" method=\"post\"&gt;\n\n &lt;div class=\"col-xs-5\" style=\"padding: 1px\"&gt;\n &lt;input type=\"text\" class=\"form-control\" name=\"name\" id=\"name\"\n placeholder=\"Name\" maxlength=\"36\"&gt;\n\n &lt;/div&gt;\n &lt;div class=\"col-xs-5\" style=\"padding: 1px;\"&gt;\n\n &lt;input type=\"text\" class=\"form-control\" name=\"phone\" id=\"phone\"\n placeholder=\"Phone Number\" maxlength=\"17\"&gt;\n\n &lt;div class=\"phonetypes\" class=\"inv\"&gt;\n &lt;input type=\"radio\" name=\"phonetype\" value=\"other\" CHECKED&gt;Other&lt;input\n type=\"radio\" name=\"phonetype\" value=\"home\"&gt;Home &lt;input\n type=\"radio\" name=\"phonetype\" value=\"work\"&gt;Work &lt;input\n type=\"radio\" name=\"phonetype\" value=\"cell\"&gt;Cell &lt;input\n type=\"radio\" name=\"phonetype\" value=\"fax\"&gt;Fax\n &lt;/div&gt;\n\n &lt;/div&gt;\n &lt;div class=\"col-xs-1\" style=\"padding: 1px\"&gt;\n &lt;select class=\"form-control\" id=\"actions\" name=\"actions\"&gt;\n &lt;option value=\"add\"&gt;Add&lt;/option&gt;\n &lt;option value=\"find\" selected&gt;Find&lt;/option&gt;\n &lt;option value=\"delete\"&gt;Delete&lt;/option&gt;\n &lt;option value=\"update\"&gt;Update&lt;/option&gt;\n &lt;option value=\"viewall\"&gt;View All&lt;/option&gt;;\n &lt;/select&gt;\n &lt;/div&gt;\n\n &lt;div class=\"col-xs-1\" style=\"padding: 1px\"&gt;\n &lt;input type=\"submit\" class=\"btn btn-default form-control\"\n name=\"btn\" value=\"Go\"&gt;\n &lt;/div&gt;\n &lt;br/&gt;\n \n &lt;div class=\"spc\"&gt;&lt;/div&gt;\n\n &lt;/form&gt;\n \n &lt;div class=\"msg\" style=\"background-color: #ffe3db;\"&gt;\n An error has happened\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr>\n<h2>Problem 1: Where's the <code>.row</code>?</h2>\n<p>You have a <code>&lt;div class=&quot;container&quot;&gt;</code> but you aren't using any <code>&lt;div class=&quot;row&quot;&gt;</code>.</p>\n<h2>Problem 2: inline CSS.</h2>\n<p>I understand: you want to remove all the spacing between the form elements.</p>\n<p>Consider leaving it as-is.</p>\n<h2>Problem 3: more missuse</h2>\n<p>You are using a responsive framework, but your form isn't responsive at all.</p>\n<p>Consider using the other form sizing classes.</p>\n<p>For example, at the size of a tablet, you might want to make it have 2 rows of inputs instead of just 1.</p>\n<h2>Problem 4: you don't use already existing components</h2>\n<p>You create a <code>&lt;div class=&quot;msg&quot;&gt;...&lt;/div&gt;</code> for the error messages.</p>\n<p>Instead, you can use an <a href=\"https://getbootstrap.com/docs/3.4/components/#alerts\" rel=\"noreferrer\">alert</a> which already exists in the plataform:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\"&gt;\n\n&lt;link rel=\"stylesheet\" href=\"//fonts.googleapis.com/css?family=Ubuntu+Mono:300,400,600,700&amp;amp;lang=en\" /&gt;\n\n&lt;div class=\"alert alert-danger\" role=\"alert\"&gt;\n &lt;strong&gt;Error:&lt;/strong&gt; Something bad happened\n&lt;/div&gt;\n\n&lt;div class=\"alert alert-warning alert-dismissible\" role=\"alert\"&gt;\n &lt;button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"&gt;&lt;span aria-hidden=\"true\"&gt;&amp;times;&lt;/span&gt;&lt;/button&gt;\n &lt;strong&gt;Warning:&lt;/strong&gt; Something less bad happened\n&lt;/div&gt;\n\n&lt;small&gt;If you use bootstrap.js, you can do this too, and the close button works&lt;small&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>You can then personalize to your liking, and place where you want.</p>\n<hr>\n<h2>Conclusion</h2>\n<p>This should clean up your HTML and CSS quite a lot:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n font-family: \"Ubuntu Mono\";\n background-color: #F2F1F0;\n}\n\n.form-control {\n border-radius: 0;\n border: 1px solid #AEA79F;\n}\n\n.btn-default {\n background-color: #EEEDEB;\n}\n\n.form-control:focus {\n border: 1px solid #E95420 !important;\n box-shadow: none !important;\n}\n\n.btn:focus, .btn:active {\n outline: none !important;\n box-shadow: none;\n}\n\n.header {\n text-shadow: 0px 1px #666;\n box-shadow: 0 0px 0 #F6BBA6 inset;\n color: #F6F6F5;\n background-color: #E95420;\n font-size: 28px;\n font-weight: bold;\n padding: 1px;\n padding-left: 20px;\n border: 1px solid #555;\n margin-top: 12px;\n}\n\n.c2 {\n background-color: #FFF;\n border: 1px solid #666;\n border-top: none;\n padding: 18px;\n}\n\n.table td, th {\n border: 1px solid #AEA79F !important;\n border-style: dotted !important;\n}\n\n.spc {\n padding: 18px;\n}\n\ninput[type=\"radio\"] {\n margin: 5px;\n margin-top: 4px;\n vertical-align: middle;\n}\n\ninput:invalid {\n border: 1px solid red;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\"&gt;\n\n&lt;link rel=\"stylesheet\" href=\"//fonts.googleapis.com/css?family=Ubuntu+Mono:300,400,600,700&amp;amp;lang=en\" /&gt;\n\n&lt;div class=\"container\"&gt;\n\n &lt;div class=\"header\"&gt;Phone Book&lt;/div&gt;\n\n &lt;form action=\"PhoneForm.php\" method=\"post\" class=\"c2\"&gt;\n &lt;div class=\"row\"&gt;\n &lt;div class=\"col-xs-6 col-sm-4 col-md-5\"&gt;\n &lt;input type=\"text\" class=\"form-control\" name=\"name\" id=\"name\" placeholder=\"Name\" maxlength=\"36\"&gt;\n\n &lt;/div&gt;\n \n &lt;div class=\"col-xs-6 col-sm-3 col-md-3\"&gt;\n\n &lt;input type=\"text\" class=\"form-control\" name=\"phone\" id=\"phone\" placeholder=\"Phone Number\" maxlength=\"17\"&gt;\n\n &lt;div class=\"phonetypes\"&gt;\n &lt;input type=\"radio\" name=\"phonetype\" value=\"other\" checked&gt;Other\n &lt;input type=\"radio\" name=\"phonetype\" value=\"home\"&gt;Home\n &lt;input type=\"radio\" name=\"phonetype\" value=\"work\"&gt;Work\n &lt;input type=\"radio\" name=\"phonetype\" value=\"cell\"&gt;Cell\n &lt;input type=\"radio\" name=\"phonetype\" value=\"fax\"&gt;Fax\n &lt;/div&gt;\n &lt;/div&gt;\n \n &lt;div class=\"col-xs-6 col-sm-3 col-md-2\"&gt;\n &lt;select class=\"form-control\" id=\"actions\" name=\"actions\"&gt;\n &lt;option value=\"add\"&gt;Add&lt;/option&gt;\n &lt;option value=\"find\" selected&gt;Find&lt;/option&gt;\n &lt;option value=\"delete\"&gt;Delete&lt;/option&gt;\n &lt;option value=\"update\"&gt;Update&lt;/option&gt;\n &lt;option value=\"viewall\"&gt;View All&lt;/option&gt;;\n &lt;/select&gt;\n &lt;/div&gt;\n \n &lt;div class=\"col-xs-6 col-sm-2 col-md-2\"&gt;\n &lt;input type=\"submit\" class=\"btn btn-default form-control\" name=\"btn\" value=\"Go\"&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n \n &lt;div class=\"spc\"&gt;&lt;/div&gt;\n \n &lt;div class=\"alert alert-danger\" role=\"alert\"&gt;\n &lt;strong&gt;Error:&lt;/strong&gt; Something bad happened\n &lt;/div&gt;\n &lt;/form&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>I've re-used the form as a <code>.row</code>, which is fine, but should be avoided.<br />\nI've done it just to avoid another level or indentation.</p>\n<p>This is all just an example of how the code may look like, not a 200% final implementation.</p>\n<p>Despite all the negativity, it shows that you've tried to learn about Bootstrap (you use the correct classes for the table, instead of re-implementing what already exists).</p>\n<hr>\n<hr>\n<h2>Other issues</h2>\n<p>Adding to other answers, you still have some issues.</p>\n<h2>Problem 1: global variables</h2>\n<p>While not exactly wrong to do, there are better ways to do things.</p>\n<p>In this case, no global variables.</p>\n<p>If you want to store all messages before showing them, try making a class like this:</p>\n<pre><code>&lt;?php\n\nclass Alert {\n private static $messages = array();\n \n public static function error($message, $can_dismiss = false)\n {\n self::add('danger', $message, $can_dismiss);\n }\n \n public static function warning($message, $can_dismiss = false)\n {\n self::add('warning', $message, $can_dismiss);\n }\n public static function info($message, $can_dismiss = false)\n {\n self::add('info', $message, $can_dismiss);\n }\n public static function success($message, $can_dismiss = false)\n {\n self::add('success', $message, $can_dismiss);\n }\n \n public static function add($class, $message, $can_dismiss)\n {\n self::$messages[] = array(\n 'dismiss' =&gt; !!$can_dismiss,\n 'class' =&gt; $class,\n 'message' =&gt; $message\n );\n }\n \n public static function render()\n {\n foreach(self::$messages as $message)\n {\n echo '&lt;div class=&quot;alert alert-', $message['class'], ($message['dismiss'] ? ' alert-dismissible' : ''),'&quot; role=&quot;alert&quot;&gt;',\n ($message['dismiss'] ? '&lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;alert&quot; aria-label=&quot;Close&quot;&gt;&lt;span aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/span&gt;&lt;/button&gt;' : ''),\n $message['message'],\n '&lt;/div&gt;';\n }\n }\n}\n</code></pre>\n<p>To use it, you can just do <code>Alert::error()</code> or you can do <code>Alert::add(&lt;type&gt;, &lt;message&gt;)</code>.</p>\n<p>You can call <code>Alert::render()</code> even if you don't have any messages to show.</p>\n<p>Remember: this is <strong>an example</strong> of how you can do. It works, but isn't a 100% final version.</p>\n<h2>Problem 2: <code>function display ($query)</code> does too much</h2>\n<p>Currently, the display function has to do all the query fetching, error handling, presentation and query cleaning up.</p>\n<p>You should just do one thing with it: pass to it the array with all the things to display.</p>\n<p>Do everything else outside that function.</p>\n<hr>\n<p>There are other issues with the code, but, those are sorta minor (&quot;wrong&quot; operators, weird queries, ...) and can be for some other time (maybe a version 2?).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T16:10:27.147", "Id": "251821", "ParentId": "251774", "Score": "7" } } ]
{ "AcceptedAnswerId": "251783", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T19:43:15.933", "Id": "251774", "Score": "7", "Tags": [ "javascript", "php", "html", "sql" ], "Title": "Reorganizing unorthodox PHP phone book project" }
251774
<p>I created a dice rolling game where the outcome shows the highest sum of rolls per player. As you can see from the if/elif statements, it's not very eloquent. I do not want someone to rewrite those statements into something more efficient. I would like to know if there is a better way of writing it and what that suggestion would be?</p> <pre><code>import random total_rolls = [] total_rolls_for = 0 player_one = [] player_two = [] player_three = [] player_four = [] max_total = [] max_total_for = [] while len(player_one) &lt; 5: player_one.append(random.randint(1,12)) if len(player_one) == 5: print(&quot;Player one rolled:&quot;, player_one) while len(player_two) &lt; 5: player_two.append(random.randint(1,12)) if len(player_two) == 5: print(&quot;Player two rolled:&quot;, player_two) while len(player_three) &lt; 5: player_three.append(random.randint(1,12)) if len(player_three) == 5: print(&quot;Player three rolled:&quot;, player_three) while len(player_four) &lt; 5: player_four.append(random.randint(1,12)) if len(player_four) == 5: print(&quot;Player four rolled:&quot;, player_four) print(&quot;The sum of p1 is:&quot;, sum(player_one)) print(&quot;The sum of p2 is:&quot;, sum(player_two)) print(&quot;The sum of p3 is:&quot;, sum(player_three)) print(&quot;The sum of p4 is:&quot;, sum(player_four)) if sum(player_one) &gt; sum(player_two) and sum(player_one) &gt; sum(player_three) and sum(player_one) &gt; sum(player_four): print(&quot;aPlayer one has a higher score with:&quot;,sum(player_one)) elif sum(player_two) &gt; sum(player_one) and sum(player_two) &gt; sum(player_three) and sum(player_two) &gt; sum(player_four): print(&quot;aPlayer two has a higher score with:&quot;,sum(player_two)) elif sum(player_three) &gt; sum(player_one) and sum(player_three) &gt; sum(player_two) and sum(player_three) &gt; sum(player_four): print(&quot;aPlayer three has a higher score with:&quot;,sum(player_three)) elif sum(player_four) &gt; sum(player_one) and sum(player_four) &gt; sum(player_two) and sum(player_four) &gt; sum(player_three): print(&quot;aPlayer four has a higher score with:&quot;,sum(player_four)) elif sum(player_one) == sum(player_two) and sum(player_one) &gt; sum(player_three) and sum(player_one) &gt; sum(player_four): print(&quot;Player one and two has a higher score with:&quot;,sum(player_one)) elif sum(player_two) == sum(player_one) and sum(player_two) &gt; sum(player_three) and sum(player_two) &gt; sum(player_four): print(&quot;Player two and player one has a higher score with:&quot;,sum(player_two)) elif sum(player_three) == sum(player_one) and sum(player_three) &gt; sum(player_two) and sum(player_three) &gt; sum(player_four): print(&quot;Player three and player one has a higher score with:&quot;,sum(player_three)) elif sum(player_four) == sum(player_one) and sum(player_four) &gt; sum(player_two) and sum(player_four) &gt; sum(player_three): print(&quot;Player four and player one has a higher score with:&quot;,sum(player_four)) elif sum(player_two) == sum(player_three) and sum(player_two) &gt; sum(player_one) and sum(player_two) &gt; sum(player_four): print(&quot;Player two and three has a higher score with:&quot;,sum(player_two)) elif sum(player_two) == sum(player_four) and sum(player_two) &gt; sum(player_three) and sum(player_two) &gt; sum(player_one): print(&quot;Player two and player four has a higher score with:&quot;,sum(player_two)) elif sum(player_three) == sum(player_four) and sum(player_three) &gt; sum(player_two) and sum(player_three) &gt; sum(player_one): print(&quot;Player three and player four has a higher score with:&quot;,sum(player_three)) elif sum(player_four) == sum(player_one) == sum(player_two) and sum(player_four) &gt; sum(player_three): print(&quot;Player four and player one and player two has a higher score with:&quot;,sum(player_four)) elif sum(player_three) == sum(player_one) == sum(player_two) and sum(player_one) &gt; sum(player_four): print(&quot;Player three and player one and player two has a higher score with:&quot;,sum(player_one)) elif sum(player_four) == sum(player_three) == sum(player_two) and sum(player_four) &gt; sum(player_one): print(&quot;Player four and player three and player two has a higher score with:&quot;,sum(player_four)) elif sum(player_one) == sum(player_three) == sum(player_four) and sum(player_four) &gt; sum(player_two): print(&quot;Player one and player three and player four has a higher score with:&quot;,sum(player_four)) elif sum(player_one) == sum(player_four) == sum(player_three) == sum(player_two): print(&quot;all players have the same value:&quot;, sum(player_one)) </code></pre>
[]
[ { "body": "<p>To cut down on the long chain of <code>if</code>/<code>elif</code> statements, you could try something like this:</p>\n<pre><code>sum_p1 = sum(player_one)\nsum_p2 = sum(player_two)\nsum_p3 = sum(player_three)\nsum_p4 = sum(player_four)\nhighest_score = max(sum_p1, sum_p2, sum_p3, sum_p4)\nhighest_scoring_players = []\nif sum_p1 == highest_score:\n highest_scoring_players.append('Player 1')\nif sum_p2 == highest_score:\n highest_scoring_players.append('Player 2')\nif sum_p3 == highest_score:\n highest_scoring_players.append('Player 3')\nif sum_p4 == highest_score:\n highest_scoring_players.append('Player 4')\nprint(' and '.join(highest_scoring_players) + ' has a higher score with:', highest_score)\n</code></pre>\n<p>Note that we can't use <code>elif</code> because it could be the case that both Player 1 and 2 have the highest score.</p>\n<p>There's still a dissatisfying amount of repetition in the above example, so I'd suggest rewriting your code to have a list of players rather than four individual player variables. I've given an example of rewriting your program with this new approach.</p>\n<pre><code>import random\n\nNUM_PLAYERS = 4\n# Instead of storing each player's list of rolls, we can just store the score\n# in a list\nplayer_scores = []\n# Create four players (range loops through integers 1 &lt;= i &lt; 5)\nfor i in range(1, NUM_PLAYERS + 1):\n # Generate the 5 dice rolls for player i\n rolls = []\n while len(rolls) &lt; 5:\n rolls.append(random.randint(1, 12))\n print(f&quot;Player {i} rolled:&quot;, rolls)\n # Add the score of player i to the list. Player 1's score is\n # stored as player_scores[0] for example.\n player_scores.append(sum(rolls))\n\n# Compute the highest score, then check which players achieved the maximum\n# score.\nhighest_score = max(player_scores)\nhighest_scoring_players = []\n# We use the enumerate function so index goes from 1 to 4, with player_score\n# being the corresponding score for player i.\nfor (index, player_score) in enumerate(player_scores, 1):\n if player_score == highest_score:\n highest_scoring_players.append(f'Player {i}')\n# highest_scoring_players stores a list ['Player 1', 'Player 2'] for example\n# of the winning players. We can then use join() to turn this into the string\n# 'Player 1 and Player 2'.\nprint(' and '.join(highest_scoring_players) + ' has a higher score with:', highest_score)\n</code></pre>\n<p>I've commented to explain each individual step, and if there are any functions you're unfamiliar with, the Python documentation should be able to add further clarity. This approach has the advantage that we can easily add more players if we want by adjusting <code>NUM_PLAYERS</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T21:08:52.473", "Id": "251779", "ParentId": "251776", "Score": "5" } }, { "body": "<p>Welcome to code review. Great review question. I hope I can give you some suggestions to improve your Python coding style. One of the most important things you can do is to apply the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY-principle</a>, where DRY = <strong>D</strong>on't <strong>R</strong>epeat <strong>Y</strong>ourself. Let me explain how to do this for your code.</p>\n<h2>First: use functions</h2>\n<p>Split up your code in simple tasks and create a function for each task. Separate the input functions (asks user for input), processing functions and output functions. For your game, I created the following four functions:</p>\n<pre><code>- throw_dice() # more of the helper function for play_game\n- play_game() # all game-playing logic is here\n- winning_players() # logic for determining who won\n- print_game_results() # outputs the results of a game\n</code></pre>\n<p>Based on the name of the functions, it should be pretty clear what each function does and how those functions work together to play the game.</p>\n<p>One way of creating code/applications is by first splitting up your application into smaller functions (even before actually writing the code for your functions). This helps in creating the larger structure of your application instead of losing yourself into the implementation issues of smaller functions.</p>\n<h2>Use comments/docstrings</h2>\n<p>One you have identified which functions you need, try to specify them. As an example, I included <a href=\"https://google.github.io/styleguide/pyguide.html\" rel=\"nofollow noreferrer\">Google-style Python docstrings</a>. Give a short description, a list of input arguments and the output of the function.</p>\n<h2>Don't use magic values</h2>\n<p>Try not to use &quot;magic numbers&quot; in your code. Define constants (often in Python declared at the top of a module and with capitalised names) or function arguments and use them in your code. This makes it easy to override of adjust those values. Examples in the code below are <code>DICE_12</code> and <code>NUM_PLAYERS</code>.</p>\n<h2>Use default values</h2>\n<p>The dice values or number of player can be default values (in a function call, use the <code>=</code> sign to declare them: <code>def func(arg=12)</code>. <code>arg</code> now has a default value of <code>12</code>. You can call this function without arguments (in that case, <code>arg</code> has the value <code>12</code>, but you can also do: <code>func(13)</code> in which case, <code>arg</code> has value <code>13</code>.</p>\n<h2>Use the power of Python</h2>\n<p>Python has some very powerfull concepts. In my code, I use some of them to make the code much shorter. Specifically:</p>\n<ul>\n<li><a href=\"https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow noreferrer\">List comprehensions</a>: are a great way to create lists on the fly. You can look at them as for-loops on steroids. For example the code <code>[str(n) for n in range(10)]</code> creates a list of strings with the value 0 through 10. I use this in the <code>winning_players()</code> function.</li>\n<li><a href=\"https://docs.python.org/3/tutorial/datastructures.html#dictionaries\" rel=\"nofollow noreferrer\">Dict comprehensions</a>: are similar to dict comprehensions, but for dictionaries. I use this in the <code>play_game()</code> function.</li>\n<li><a href=\"https://docs.python.org/3/library/random.html#functions-for-sequences\" rel=\"nofollow noreferrer\">random.choices</a>: you use randint to get an integer number, but <code>choice</code> picks a number from a sequence and <code>choices</code> can pick a number from a sequence multiple times. This is exactly what you want to do when throwing dice.</li>\n</ul>\n<p>Putting all of these ingredients together, gives a much, much reduced codelength. Below is the full code with comments.</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>import random\n\n\n# Constant defining the possible dice outcomes.\nDICE_6 = list(range(1, 7)) # 6-sided dice; values 1-6\nDICE_12 = list(range(1, 13)) # 12-sided dice; values 1-12\n\n# Game parameters\nNUM_PLAYERS = 4 # number of players in the game\nNUM_THROWS = 5 # number of throws per player\n\n\ndef throw_dice(dice_sides, num_throws=1):\n \"\"\" Return a list of dice throw results.\n\n Args:\n dice_sides (list): List with the possible dice throw outcomes.\n num_throws (int) : The number of thows to make with the dice.\n\n Returns:\n list: A list of dice_sides items.\n \"\"\"\n return random.choices(dice_sides, k=num_throws)\n\n\ndef play_game(num_players=NUM_PLAYERS, num_throws=NUM_THROWS, dice_sides=DICE_12):\n \"\"\" Play a game where each player throws num_throws times with a dice.\n\n Args:\n num_players (int): The number of players.\n num_throws (int) : The number of thows each player makes with the dice.\n dice_sides (list): List with the possible dice throw outcomes.\n\n Returns:\n dict: Dict with player number as key and the list of throws as values.\n \"\"\"\n return {p: throw_dice(dice_sides, num_throws) for p in range(1, num_players + 1)}\n\n\ndef winning_players(game):\n \"\"\" Returns a list with the player(s) who have the maximum sum of dice throws.\n\n Args:\n game (dict): Dict with player number as key and the list of throws as values.\n\n Returns:\n list: A list with the player(s) with the highest sum of dice throws.\n \"\"\"\n max_dice_sum = max(map(sum, game.values()))\n return [player for player, throws in game.items() if sum(throws) == max_dice_sum]\n\n\ndef print_game_results(game):\n \"\"\" Prints the results of a game throwing dice.\n\n Args:\n game (dict): Dict with player number as key and the list of throws as values.\n \"\"\"\n for player, throws in game.items():\n print(f'Player {player} rolled {throws}. The sum of dice is: {sum(throws)}')\n\n players_won = winning_players(game)\n max_points = sum(game[players_won[0]])\n print(f'There is/are {len(players_won)} winning players.')\n for player in players_won:\n print(f\"Player(s) {' and '.join(map(str, players_won))} won with {max_points} points.\")\n\n\ndef main():\n game = play_game()\n print_game_results(game)\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n<p><a href=\"https://tio.run/##rVVhb9MwEP3eX3HqPjQRXSEbDKkoH6ZtAqQB1RhCaJosb3UbsySuYndlqvrby53tNG4XNBCr1KaJ753fvXfnzB5MpsrD9VoWM1UZqHg5VkWn09mDE1Vqw0sDYzGRpSynYDIBM6W1vMkFjOWtADU3t6oQetA5/Xhyxo4ghVxqE2GaqYiSPryNY8DPHhztazkWYwt7B/c8nwsNyf6RAyYHj5DJIUH3IDloRyYHRPI9L5ATr/BiRKU7n799YqPz4x9nF18x42u7dTkvbkQFagKznD9gFMjS1jJFlEVcfrj48p0Ab2AHYbJKLTTM8M6BURrUwz1nRCmiH0YUdZ@AzEHSJB52KFu324ULYeZVCdyWSGmteDYQKqHnuUEFbfRxNdUOR58mNUQEjYdwThkW0mQtbriEjSd1moYVRLI0MQzhEsFhlbRmFBT8TjTZKann5SoIqBGdIRxvVeSpSiMKvzsWb6@VE8B11@A2Uxitt5S7SxuWsReZFGdkUkRr3rw0sHhL8MbIfsAm9f0VuDHCROgFJYZFJioBgt9m3t/a8UAzI1FNpwoPNdn2KqDoVN4V2S/@sy0hOfJH7xr0TN3S7jOGos@n@OvyeCKeJNdwJ1DMcmw3qJvBV4Wrblxbm2E5Gz49RjFMFI4eTezmZAiVfgFJvPLtspAlHVP1WkQGPxpCXU9ho4oNj3CrRaYg4/fCPi74L1nMC9D43ZrY9lG13URFkOz/LddfzFwb//pRJqeZwJg27qETWCNzumNgSrdRwWcR3vVtQQPHJ4rjOHTuyldlrbF/@3UN6JMF2jMgikFOiERUm5mmW3te14NeYf/bSWf@ONw1b0QR2hbnI6gwP8Q2O72g/jicz@tOKOHTGjQsbJnRpDdy2y4dbgWVynN8wS0dfjWwx0DondRDWAY6rnqxq9K3OluoEv1rHYCN0TNlJUytIbR0FaCvXl1fu9Ca5KU9GaV@yfGyzEUZBeHxqt5sc6z14h09SIcA8kiG7mjTuMueVb03@IkcXQsa1DPckHbEIq1ty6acFbjroFu/NAqOKbzo1vY0eI8EJba0G2bAfmWspBVGzdpljPIx1h16HSn5ev0b\" rel=\"nofollow noreferrer\" title=\"Python 3 – Try It Online\">Try it online!</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T15:29:43.223", "Id": "495936", "Score": "1", "body": "`range(1,6)` does not include 6." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T15:37:26.397", "Id": "495938", "Score": "0", "body": "@Marc: you are completely right. Corrected it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T14:46:43.123", "Id": "251817", "ParentId": "251776", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T20:36:29.647", "Id": "251776", "Score": "7", "Tags": [ "python" ], "Title": "Dice rolling game with Python" }
251776
<p>I have the following program that I wrote as an exercise for learning C. It simulates the scheduling of processes according to round-robin, first-come-first-served, shortest-job-first, and priority-scheduling policies. It reads a list of processes from a file, which are represented with the format <code>[id] [cpu burst length] [io burst length] [number of repetitions] [priority]</code>.</p> <p>Here is an example input file:</p> <pre><code>1 10 3 5 5 2 29 1 5 10 3 3 4 5 15 4 7 2 5 20 5 12 5 5 25 </code></pre> <p>I tried to make it as clean and easy to read as possible. I would appreciate feedback on my style and organization.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #define NUM_JOBTYPES 4 #define RR_QUANTUM_LENGTH 10 enum states { RTR, CPU, IO, DONE }; enum algs { FCFS, PS, SJF, RR }; typedef struct job { int id; int priority; int start_time; int end_time; int wait_time; int state; int burst_countdown; int cpu_burst_length; int io_burst_length; int quant_countdown; int reps; } job_t; typedef struct node { int priority; job_t *job; struct node *next; } node_t; node_t *rtr_queue; job_t **jobs; job_t *active = NULL; int num_jobs = 0; int finished_jobs = 0; int time = 1; int cpu_busy_time = 0; int cpu_idle_time = 0; const char *alg_names[] = {&quot;fcfs&quot;, &quot;ps&quot;, &quot;sjf&quot;, &quot;rr&quot;}; int alg_id = -1; int iscomment(const char *line); void load_jobs(FILE *f); job_t *set_next_job(); void run(); void print_status_line(); void print_report(); void push(node_t **head, job_t *j); job_t *pop(node_t **); int getpri(job_t *j); /*-------------------------------------------------------------*/ int main(int argc, char *argv[]) { if (argc != 3) { puts(&quot;usage: cpu_sim &lt;process filename&gt; &lt;algorithm&gt;&quot;); return 0; } for (int i = 0; i &lt; NUM_JOBTYPES; i++) { if (!strcmp(argv[2], alg_names[i])) { alg_id = i; } } FILE *f = fopen(argv[1], &quot;r&quot;); load_jobs(f); fclose(f); if (alg_id != -1) { run(); } else { printf(&quot;\&quot;%s\&quot; is not a valid algorithm.\n&quot;, alg_names[alg_id]); return 0; } } /*-------------------------------------------------------------*/ void run() { puts(&quot;┌───────────────────────────────┐&quot;); puts(&quot;│ Time : CPU : IO │&quot;); puts(&quot;├───────────────────────────────┤&quot;); for (;;) { if (active) { --active-&gt;burst_countdown; --active-&gt;quant_countdown; // if CPU burst is done, switch to IO // and start running a new job. if (active-&gt;burst_countdown == 0) { active-&gt;state = IO; active-&gt;burst_countdown = active-&gt;io_burst_length; active = set_next_job(); } // else if the current job's quantum is expired, put it // at the end of the RTR queue and start the next one. else if (active-&gt;quant_countdown == 0) { active-&gt;state = RTR; push(&amp;rtr_queue, active); active = set_next_job(); } ++cpu_busy_time; } // if no job is using the CPU, try to pop a new one from the queue. // increment the idle time if there is nothing ready to run. else { if (!(active = set_next_job())) { ++cpu_idle_time; } } // now look at the jobs that are not using the CPU. for (int i = 0; i &lt; num_jobs; i++) { job_t *j = jobs[i]; if (j-&gt;state == IO) { // if IO burst is done, put back into RTR queue. if (j-&gt;burst_countdown-- == 0) { if (j-&gt;reps == 0) { j-&gt;state = DONE; j-&gt;end_time = time; finished_jobs++; } else { j-&gt;state = RTR; push(&amp;rtr_queue, j); } } } if (j-&gt;state == RTR) { ++j-&gt;wait_time; } } if(finished_jobs&lt;num_jobs) print_status_line(); else break; ++time; } print_report(); for (int i = 0; i &lt; num_jobs; i++) { free(jobs[i]); } if (rtr_queue) { free(rtr_queue); } } /*-------------------------------------------------------------*/ job_t *set_next_job() { job_t *j = NULL; if ((j = pop(&amp;rtr_queue))) { j-&gt;state = CPU; if (!j-&gt;start_time) { j-&gt;start_time = time; } if (j-&gt;burst_countdown &lt;= 0) { j-&gt;burst_countdown = j-&gt;cpu_burst_length; j-&gt;reps--; } j-&gt;quant_countdown = (alg_id == RR ? RR_QUANTUM_LENGTH : -1); } return j; } /*-------------------------------------------------------------*/ void push(node_t **head, job_t *j) { node_t *new = malloc(sizeof(node_t)); new-&gt;job = j; new-&gt;next = NULL; new-&gt;priority = getpri(j); if (*head == NULL) { *head = new; return; } if (new-&gt;priority &lt; (*head)-&gt;priority) { new-&gt;next = *head; *head = new; return; } node_t *cur = *head; while (cur-&gt;next &amp;&amp; new-&gt;priority &gt; cur-&gt;next-&gt;priority) { cur = cur-&gt;next; } new-&gt;next = cur-&gt;next; cur-&gt;next = new; } /*-------------------------------------------------------------*/ job_t *pop(node_t **head) { node_t *cur = *head; if (!cur) { return NULL; } job_t *j = cur-&gt;job; *head = (*head)-&gt;next; free(cur); return j; } /*-------------------------------------------------------------*/ int getpri(job_t *j) { int p = -1; if (alg_id == PS) { p = j-&gt;priority; } if (alg_id == SJF) { p = j-&gt;cpu_burst_length * j-&gt;reps; } if (alg_id == RR) { p = time; } return p; } /*-------------------------------------------------------------*/ void print_status_line() { char *iostring = malloc(16 * sizeof(char)); int c = 0; for (int i = 0; i &lt; num_jobs; i++) { if (jobs[i]-&gt;state == IO) { c += sprintf(&amp;iostring[c], &quot;%d &quot;, jobs[i]-&gt;id); } } if (!c) { strcpy(iostring, &quot;xx&quot;); } if (active) printf(&quot;│ %4d %9d %9s │\n&quot;, time, active-&gt;id, iostring); else printf(&quot;│ %4d %9s %9s │\n&quot;, time, &quot;xx&quot;, iostring); free(iostring); } /*-------------------------------------------------------------*/ void print_report() { puts(&quot;└───────────────────────────────┘\n&quot;); int turn_time = 0; for (int i = 0; i &lt; num_jobs; i++) { printf(&quot; Process ID: %5d\n&quot;, jobs[i]-&gt;id); printf(&quot; Start Time: %5d\n&quot;, jobs[i]-&gt;start_time); printf(&quot; End Time: %5d\n&quot;, jobs[i]-&gt;end_time); printf(&quot; Wait Time: %5d\n&quot;, jobs[i]-&gt;wait_time); turn_time += jobs[i]-&gt;end_time; puts(&quot;─────────────────────────────────&quot;); } printf(&quot; Average Turnaround Time: %d\n&quot;, turn_time / num_jobs); printf(&quot; CPU Busy Time: %d\n&quot;, cpu_busy_time); printf(&quot; CPU Idle Time: %d\n\n&quot;, cpu_idle_time); } /*-------------------------------------------------------------*/ void load_jobs(FILE *f) { int bufsize = 128; char line[bufsize]; while (fgets(line, bufsize, f)) { if (!iscomment(line)) { job_t *j = calloc(1, sizeof(job_t)); sscanf(line, &quot;%d %d %d %d %d&quot;, &amp;j-&gt;id, &amp;j-&gt;cpu_burst_length, &amp;j-&gt;io_burst_length, &amp;j-&gt;reps, &amp;j-&gt;priority); push(&amp;rtr_queue, j); ++num_jobs; } } jobs = malloc(num_jobs * sizeof(job_t)); node_t *cur = *&amp;rtr_queue; int i = 0; while (cur) { jobs[i++] = cur-&gt;job; cur = cur-&gt;next; } } /*-------------------------------------------------------------*/ int iscomment(const char *line) { return (line[0] == '/' &amp;&amp; line[1] == '/'); } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h1>Keep names and enum values in sync</h1>\n<p><code>enum algs</code> and <code>alg_names[]</code> are declared quite a bit apart from each other. That makes it hard to spot if they are in sync. It is best to declare the <code>enum</code> and the array with the names right next to each other, and use <a href=\"https://en.cppreference.com/w/cpp/language/aggregate_initialization#Designated_initializers\" rel=\"noreferrer\">designated initializers</a> to ensure the compiler will enforce the correct order, like so:</p>\n<pre><code>enum algs {\n FCFS, PS, SJF, RR\n};\n\nstatic const char *const alg_names[] = {\n [FCFS] = &quot;fcfs&quot;,\n [PS] = &quot;ps&quot;,\n [SJF] = &quot;sjf&quot;,\n [RR] = &quot;rr&quot;,\n};\n</code></pre>\n<p>If you have very long lists then you might also consider using macros so you can avoid repetion, see <a href=\"https://stackoverflow.com/questions/5530248/creating-a-string-list-and-an-enum-list-from-a-c-macro\">this question</a> for some examples.</p>\n<h1>Use <code>static</code> where appropriate</h1>\n<p>Use the <code>static</code> keyword for global variables and functions that are only accessed from within the same source file.</p>\n<h1>Use more <code>const</code></h1>\n<p>Make everything that should not change <code>const</code>. This helps the compiler find accidental errors where you do overwrite a <code>const</code> variable, and allows it to generate more optimal code.</p>\n<p>For example, the array <code>alg_names[]</code> as shown above can be made <code>const</code> as well (in your code, only the strings pointed to were marked <code>const</code>, the pointers themselves could still be changed). Another example is <code>getpri()</code>: since it doesn't change the job, you should write:</p>\n<pre><code>int getpri(const job_t *j);\n</code></pre>\n<h1>Avoid forward declarations</h1>\n<p>You have a number of forward declarations right before the definition of <code>main()</code>. These are unnecessary; if you change the order in which the functions are defined, you don't need the forward declarations anymore. That removes some repetition from the code, and reduces the potential for mistakes.</p>\n<h1>Consider moving all global variables into a single <code>struct</code></h1>\n<p>There are a lot of variables, and some of them even have names that conflict with standard library functions, such as <code>time</code>. Consider creating a <code>struct state</code> that holds all the variables related to the state of the simulation:</p>\n<pre><code>struct state {\n node_t *rtr_queue;\n job_t **jobs;\n job_t *active;\n ...\n};\n</code></pre>\n<p>Then you can declare and initialize the state as follows:</p>\n<pre><code>struct state state = {\n .active = NULL;\n .num_jobs = 0;\n ...\n};\n</code></pre>\n<p>The variable <code>state</code> could be the single global variable left, but you can also consider declaring this variable inside <code>main()</code> instead, and pass a pointer to it to the functions that need to access the state. This is even better, as it will allow you to simulate multiple systems at the same time in a single program.</p>\n<h1>Missing error checking</h1>\n<p>Always check the return value of functions that can fail. For example, <code>fopen()</code> can return NULL if the input file does not exist or doesn't have read permissions. If you don't check it, then the program will likely crash due to a segmentation fault. This will be very annoying for the user, who will correctly conclude there is a bug in your program. Instead, check it and print a helpful error message instead:</p>\n<pre><code>FILE *f = fopen(argv[1], &quot;r&quot;);\nif (!f) {\n fprintf(stderr, &quot;Could not open %s: %s\\n&quot;, arv[1], strerror(errno));\n return 1;\n}\n</code></pre>\n<p>There are some helper functions that make this easier, for example the standard function <a href=\"https://en.cppreference.com/w/c/io/perror\" rel=\"noreferrer\"><code>perror()</code></a> can be used to print an error message, or if you target Linux or *BSD only you could use the even more convenient <a href=\"https://man7.org/linux/man-pages/man3/err.3.html\" rel=\"noreferrer\"><code>err()</code></a>.</p>\n<p>Also check in <code>load_jobs()</code> that you have read the whole file. To distinguish <code>fgets()</code> from returning <code>NULL</code> because of the end-of-file has been reached or a real error occured, use <a href=\"https://en.cppreference.com/w/c/io/feof\" rel=\"noreferrer\"><code>feof()</code></a>.</p>\n<p>Memory allocations can also fail, so check the return value of <code>malloc()</code> and <code>calloc()</code> as well.</p>\n<h1>Add conditions to the outer <code>for</code>-loop in <code>run()</code></h1>\n<p>I would move the condition that you check at the end of the <code>for</code>-loop into the <code>for</code>-statement itself, so it is clear right at the top what is being looped over. So:</p>\n<pre><code>for (time = 0; finished_jobs &lt; num_jobs; ++time) {\n</code></pre>\n<p>Now just by looking at that line I can deduce that each iteration will be a time step, and we continue doing steps until all jobs are finished.</p>\n<h1>Don't free <code>jobs</code> and <code>rtr_queue</code> in <code>run()</code></h1>\n<p>These resources were not allocated by <code>run()</code>, so it shouldn't be <code>run()</code>'s job to clean them up. They were allocated by <code>load_jobs()</code>, I would put the resource cleanup in a new function called <code>free_jobs()</code>, and call that function from <code>main()</code>.</p>\n<h1>Avoid repeating type names when allocating memory</h1>\n<p>Instead of:</p>\n<pre><code>node_t *new = malloc(sizeof(node_t));\n</code></pre>\n<p>I recommend you write this instead:</p>\n<pre><code>node_t *new = malloc(sizeof(*new));\n</code></pre>\n<p>If you ever change the type of <code>new</code>, you only have to change it in one place. Of course now you have that problem when you change the name of the variable, but then it is more likely to generate a compiler error if you forget to change the right hand side.</p>\n<h1>Avoid unnecessary allocations</h1>\n<p>You don't need to use <code>malloc()</code> to allocate memory for <code>iostring</code> in <code>print_status_line()</code>, you can just write:</p>\n<pre><code>char iostring[16];\n</code></pre>\n<h1>Guard against buffer overflows</h1>\n<p>Is <code>iostring</code> actually large enough? What if <code>num_jobs</code> is very large, so that the string will be longer than 15 characters? Use <code>snprintf()</code> to guard against buffer overflows:</p>\n<pre><code>c += snprintf(&amp;iostring[c], sizeof(iostring) - c, &quot;%d &quot;, jobs[i]-&gt;id);\n</code></pre>\n<p>However, be aware that <code>snprintf()</code> can return a value greater than the number of bytes written if it reached the end of the buffer early. It can potentially also return <code>-1</code>. It would be easier to change the format of the report so that you don't need to write to a temporary string. For example:</p>\n<pre><code>void print_status_line() {\n if (active)\n printf(&quot;│ %4d %9d&quot;, time, active-&gt;id);\n else\n printf(&quot;│ %4d %9s&quot;, time, &quot;xx&quot;);\n\n int c = 0;\n\n for (int i = 0; i &lt; num_jobs; i++) {\n if (jobs[i]-&gt;state == IO) {\n c += printf(&quot; %d&quot;, jobs[i]-&gt;id);\n }\n } \n\n if (!c)\n c += printf(&quot; xx&quot;);\n\n printf(&quot;%*s|\\n&quot;, c &lt; 14 ? 14 - c : 0, &quot;&quot;);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T23:36:26.010", "Id": "495860", "Score": "2", "body": "You mentioned testing the value returned from `fopen()` you didn't mention testing the value returned by `calloc()` or `malloc()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T08:23:23.827", "Id": "495901", "Score": "0", "body": "@pacmaninbw Thanks for reminding me :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T10:25:28.993", "Id": "495907", "Score": "0", "body": "Also: Use `void` within the parentheses for functions taking no arguments." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T23:04:39.647", "Id": "251782", "ParentId": "251777", "Score": "17" } }, { "body": "<h2>Overall Impression</h2>\n<p>At first glance everything looks great, the indentation is good, the use of enums over Magic numbers is good, the only obvious thing is the comments between functions that look like <code>/*-------------------------------------------------------------*/</code>, they are not useful.</p>\n<p>First looks can be deceiving.</p>\n<h2>Avoid Global Variables</h2>\n<p>It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C and C++ global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The <a href=\"https://stackoverflow.com/questions/484635/are-global-variables-bad\">answers in this stackoverflow question</a> provide a fuller explanation.</p>\n<p>Functions such as <code>load_jobs()</code> can return values values such as the pointer to the head of the <code>rtr_queue</code>;</p>\n<h2>Use Descriptive Variable Names</h2>\n<p>Variable names using only one letter, such as <code>f</code> or <code>.j</code> don't really help anyone who has to maintain the code to understand the code. In 6 months time, even you might have problems understanding <code>f</code> means file pointer and <code>j</code> mean job or even what <code>cur</code> means.</p>\n<pre><code>void load_jobs(FILE* f) {\n\n int bufsize = 128\n char line[bufsize];\n\n while (fgets(line, bufsize, f)) {\n\n if (!iscomment(line)) {\n\n job_t* j = calloc(1, sizeof(job_t));\n\n sscanf(line, &quot;%d %d %d %d %d&quot;,\n &amp;j-&gt;id,\n &amp;j-&gt;cpu_burst_length,\n &amp;j-&gt;io_burst_length,\n &amp;j-&gt;reps,\n &amp;j-&gt;priority);\n\n push(&amp;rtr_queue, j);\n ++num_jobs;\n }\n }\n\n jobs = malloc(num_jobs * sizeof(job_t));\n\n node_t* cur = *&amp;rtr_queue;\n\n int i = 0;\n while (cur) {\n jobs[i++] = cur-&gt;job;\n cur = cur-&gt;next;\n }\n}\n</code></pre>\n<p>It is also very inconsistent with other variable names you are using. It is important to be consistent throughout the program for variable names</p>\n<h2>Test for Possible Memory Allocation Errors</h2>\n<p>In modern high level languages such as C++, memory allocation errors throw an exception that the programmer can catch. This is not the case in the C programming language. While it rare in modern computers because there is so much memory, memory allocation can fail, especially if the code is working in a limited memory application such as embedded control systems. In the C programming language when memory allocation fails, the functions <code>malloc()</code>, <code>calloc()</code> and <code>realloc()</code> return <code>NULL</code>. Referencing any memory address through a <code>NULL</code> pointer results in <strong>undefined behavior</strong> (UB).</p>\n<p>Possible undefined behavior in this case can be a memory page error (in Unix this would be call Segmentation Violation), corrupted data in the program and in very old computers it could even cause the computer to reboot (corruption of the stack pointer).</p>\n<p>To prevent this <strong>unknown behavior</strong> a best practice is to always follow the memory allocation statement with a test that the pointer that was returned is not NULL.</p>\n<p>Examples of the problem can be found in the <code>load_job()</code> function above.</p>\n<p><em>Example of Current Code with Test:</em></p>\n<pre><code> job_t* j = calloc(1, sizeof(job_t));\n if (!j)\n {\n fprintf(stderr, &quot;The call to calloc(1, %u) in load_jobs() failed\\n&quot;, sizeof(*j));\n exit(EXIT_FAILURE);\n }\n\n jobs = malloc(num_jobs * sizeof(*jobs));\n if (!jobs)\n {\n fprintf(stderr, &quot;The call to malloc(%d, %u) in load_jobs() failed\\n&quot;, num_jobs, sizeof(*jobs));\n exit(EXIT_FAILURE);\n }\n</code></pre>\n<p>The second example (<code>malloc()</code>) could also be re-written using <code>calloc()</code>.</p>\n<h2>Convention When Using Memory Allocation in C</h2>\n<p>When using malloc(), calloc() or realloc() in C a common convetion is to sizeof(*PTR) rather sizeof(PTR_TYPE), this make the code easier to maintain and less error prone, since less editing is required if the type of the pointer changes.</p>\n<pre><code> job_t* j = calloc(1, sizeof(job_t)); \n</code></pre>\n<p>Would be better as</p>\n<pre><code> job_t* j = calloc(1, sizeof(*j)); \n</code></pre>\n<h2>Avoid Using C++ Keywords as Variable Names</h2>\n<p>Someone may build this program using a C++ compiler because C++ is backward compatible with C (mostly) or it may be more convient to convert this program to C++ to use the STL and / or Object Oriented classes. The use of C++ keywords such as <code>new</code> can cause problems in these cases. The variable name <code>new</code> also isn't quite as descriptive as <code>newNode</code> or <code>new_node</code>.</p>\n<pre><code>void push(node_t** head, job_t* j) {\n\n node_t* new = malloc(sizeof(node_t));\n new-&gt;job = j;\n new-&gt;next = NULL;\n new-&gt;priority = getpri(j);\n\n ...\n}\n</code></pre>\n<p>This is another location where testing of the result of <code>malloc()</code> should be added.</p>\n<h2>Lack of Sufficient Error Checking in Main</h2>\n<p>Malloc is not the only library function used that can fail, the function <code>fopen()</code> will also return a <code>NULL</code> pointer if it fails, and <code>fopen()</code> can fail for a variety of reasons, the file may not be there, the file may not have the proper permissions for the program to open are just 2 possible causes for <code>fopen()</code> to fail. There needs to be a test to see that <code>f</code> has a value here as well.</p>\n<p>There is another distinct problem in <code>main()</code>, the array <code>alg_names</code> is being index by -1 in the error case, this causes undefined behavior and will probably not print what is requested. The test for <code>alg_id</code> being negative is too late, it should be performed before the code even attempts to open the input file.</p>\n<pre><code>int main(int argc, char* argv[]) {\n\n if (argc != 3) {\n puts(&quot;usage: cpu_sim &lt;process filename&gt; &lt;algorithm&gt;&quot;);\n return EXIT_FAILURE;\n }\n\n for (int i = 0; i &lt; NUM_JOBTYPES; i++) {\n if (!strcmp(argv[2], alg_names[i])) {\n alg_id = i;\n }\n }\n\n if (alg_id &lt; 0)\n {\n fprintf(stderr, &quot;Invalid argument %s please try one of the following:&quot;, argv[2]);\n for (int i = 0; i &lt; NUM_JOBTYPES; i++)\n {\n fprintf(stderr, &quot;%s\\n&quot;, alg_names[i]);\n }\n return EXIT_FAILURE;\n\n }\n\n FILE* f = fopen(argv[1], &quot;r&quot;);\n if (!f)\n {\n fprintf(stderr, &quot;Can't open file %s for input.\\n&quot;, argv[1]);\n return EXIT_FAILURE;\n }\n load_jobs(f);\n fclose(f);\n\n run();\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T23:31:55.333", "Id": "251787", "ParentId": "251777", "Score": "7" } }, { "body": "<h2>Array length</h2>\n<p>Explicitly declaring <code>NUM_JOBTYPES 4</code> and also having <code>alg_names</code> be automatically sized is risky. There are two options, either of which would bring you more consistency:</p>\n<ul>\n<li>Simply declare <code>alg_names[NUM_JOBTYPES]</code></li>\n<li>Define <code>NUM_JOBTYPES</code> to be equal to the size of <code>alg_names</code> via <code>sizeof</code></li>\n</ul>\n<p>Otherwise, a sleep-deprived future you (for example) could adjust one without adjusting the other, and the compiler would have a more difficult time catching the inconsistency.</p>\n<h2>Pre-decrement</h2>\n<pre><code> --active-&gt;burst_countdown;\n</code></pre>\n<p>creeps me out. Based on the <a href=\"https://en.cppreference.com/w/c/language/operator_precedence\" rel=\"noreferrer\">C order of operations</a> this does do what you want, but it's a misleading way to write decrement in this case. <code>active-&gt;burst_countdown--</code> accomplishes the same thing but it's more clear that it's the countdown that's being decremented, not the <code>active</code> pointer.</p>\n<h2>Assignment expressions</h2>\n<p>You're not doing yourself any favours here:</p>\n<pre><code> if (!(active = set_next_job())) {\n</code></pre>\n<p>Just split this up into two statements.</p>\n<h2>Early-return</h2>\n<p>I find <code>p</code> to be unneeded here:</p>\n<pre><code>int p = -1;\n\nif (alg_id == PS) {\n p = j-&gt;priority;\n}\n\nif (alg_id == SJF) {\n p = j-&gt;cpu_burst_length * j-&gt;reps;\n}\n\nif (alg_id == RR) {\n p = time;\n}\n\nreturn p;\n</code></pre>\n<p>This could be rephrased as a <code>switch</code> where every <code>case</code> returns.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T01:00:22.103", "Id": "251790", "ParentId": "251777", "Score": "8" } } ]
{ "AcceptedAnswerId": "251782", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T20:54:51.973", "Id": "251777", "Score": "18", "Tags": [ "c" ], "Title": "CPU scheduling simulator in C" }
251777
<p>I wrote a Java Spring Boot application with MongoDB that on every application start loads customer, account type and transaction details from CSV files to MongoDB. It has one end point that returns transactions for a given <code>customerId</code> and <code>accountType</code> (for example customer id 1,3,5 etc. or account type &quot;ALL&quot;). The main target is to return demanded data (and sorted ascending by transaction amount) as fast as possible (read time matters most). I also wrote 3 tests to test this end point.</p> <p>My service:</p> <pre><code>package com.colliers.mongodb.service; import com.colliers.mongodb.exception.TransactionNotFoundException; import com.colliers.mongodb.model.DTO.TransactionDTO; import com.colliers.mongodb.model.Transaction; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @Service public class TransactionService { private MongoTemplate mongoTemplate; @Autowired public TransactionService(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; } public List&lt;TransactionDTO&gt; getTransactions(String accountType, String customerId) throws TransactionNotFoundException { final List&lt;String&gt; accounts = Arrays.asList(accountType.split(&quot;,&quot;)); final List&lt;String&gt; customers = Arrays.asList(customerId.split(&quot;,&quot;)); Query query = new Query(); query.with(Sort.by(Sort.Direction.ASC, &quot;transactionAmount&quot;)); if(accountType.equals(&quot;&quot;) || accountType.equals(&quot;ALL&quot;)); else { query.addCriteria(Criteria.where(&quot;accountType.accountType&quot;).in(accounts)); } if(customerId.equals(&quot;&quot;) || customerId.equals(&quot;ALL&quot;)); else { query.addCriteria(Criteria.where(&quot;customer.id&quot;).in(customers)); } List&lt;Transaction&gt; transactions = this.mongoTemplate.find(query, Transaction.class, &quot;transactions&quot;); if(transactions.isEmpty()) { throw new TransactionNotFoundException(&quot;No Transactions found.&quot;); } List&lt;TransactionDTO&gt; result = new ArrayList&lt;&gt;(); for(var t : transactions) { TransactionDTO transactionDTO = TransactionDTO.builder() .transactionDate(t.getTransactionDate()) .transactionId(t.getId()) .transactionAmount(t.getTransactionAmount()) .accountTypeName(t.getAccountType().getName()) .firstName(t.getCustomer().getFirstName()) .lastName(t.getCustomer().getLastName()) .build(); result.add(transactionDTO); } return result; } } </code></pre> <p>My Controller:</p> <pre><code>package com.colliers.mongodb.controller; import com.colliers.mongodb.model.DTO.TransactionDTO; import com.colliers.mongodb.service.TransactionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController class Controller { private TransactionService service; @Autowired Controller(TransactionService service) { this.service = service; } @GetMapping(&quot;/transactions&quot;) ResponseEntity&lt;List&lt;TransactionDTO&gt;&gt; getTransactionsByAccountTypeAndCustomerId( @RequestParam(value = &quot;account_type&quot;) String accountType, @RequestParam(value = &quot;customer_id&quot;) String customerId) { String regex = &quot;^(^$)|(ALL)|(([1-9][0-9]*)((,[1-9][0-9]*)*))$&quot;; if(!accountType.matches(regex) || !customerId.matches(regex)) { return new ResponseEntity&lt;&gt;(HttpStatus.BAD_REQUEST); } return new ResponseEntity&lt;&gt;(this.service.getTransactions(accountType, customerId), HttpStatus.OK); } } </code></pre> <p>My AppInit - database seeder:</p> <pre><code>package com.colliers.mongodb.configuration; import com.colliers.mongodb.model.AccountType; import com.colliers.mongodb.model.Customer; import com.colliers.mongodb.model.Transaction; import com.colliers.mongodb.repository.AccountTypeRepository; import com.colliers.mongodb.repository.CustomerRepository; import com.colliers.mongodb.repository.TransactionRepository; import com.opencsv.CSVReader; import com.opencsv.bean.CsvToBean; import com.opencsv.bean.CsvToBeanBuilder; import com.opencsv.bean.HeaderColumnNameTranslateMappingStrategy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Component; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Component class AppInit implements CommandLineRunner { private CustomerRepository customerRepository; private TransactionRepository transactionRepository; private AccountTypeRepository accountTypeRepository; private MongoTemplate mongoTemplate; @Autowired public AppInit(CustomerRepository customerRepository, TransactionRepository transactionRepository, AccountTypeRepository accountTypeRepository, MongoTemplate mongoTemplate) { this.customerRepository = customerRepository; this.transactionRepository = transactionRepository; this.accountTypeRepository = accountTypeRepository; this.mongoTemplate = mongoTemplate; } @Override public void run(String... args) throws Exception { mongoTemplate.dropCollection(&quot;customers&quot;); mongoTemplate.dropCollection(&quot;transactions&quot;); mongoTemplate.dropCollection(&quot;accountypes&quot;); mongoTemplate.createCollection(&quot;customers&quot;); mongoTemplate.createCollection(&quot;transactions&quot;); mongoTemplate.createCollection(&quot;accountypes&quot;); File customersCSV = new File(&quot;src/main/resources/static/customers.csv&quot;); File transactionsCSV = new File(&quot;src/main/resources/static/transactions.csv&quot;); File accountypesCSV = new File(&quot;src/main/resources/static/accountypes.csv&quot;); Map&lt;String, Customer&gt; customers = parseCustomers(customersCSV); customerRepository.saveAll(customers.values()); Map&lt;String, AccountType&gt; accountTypes = parseAccountTypes(accountypesCSV); accountTypeRepository.saveAll(accountTypes.values()); List&lt;Transaction&gt; transactions = parseTransactions(transactionsCSV); for(var t : transactions) { t.setAccountType(accountTypes.get(t.getAccountTypeNumber())); t.setCustomer(customers.get(t.getCustomerId())); } transactionRepository.saveAll(transactions); } private List&lt;Transaction&gt; parseTransactions(File file) throws Exception { HeaderColumnNameTranslateMappingStrategy&lt;Transaction&gt; strategy = new HeaderColumnNameTranslateMappingStrategy&lt;&gt;(); strategy.setType(Transaction.class); Map&lt;String, String&gt; columnMapping = new HashMap&lt;&gt;(); columnMapping.put(&quot;transaction_id&quot;, &quot;id&quot;); columnMapping.put(&quot;transaction_amount&quot;, &quot;transactionAmount&quot;); columnMapping.put(&quot;account_type&quot;, &quot;accountTypeNumber&quot;); columnMapping.put(&quot;customer_id&quot;, &quot;customerId&quot;); columnMapping.put(&quot;transaction_date&quot;, &quot;transactionDate&quot;); strategy.setColumnMapping(columnMapping); CSVReader reader = new CSVReader(new FileReader(file.getPath())); CsvToBean&lt;Transaction&gt; csvToBean = new CsvToBeanBuilder&lt;Transaction&gt;(reader) .withMappingStrategy(strategy) .build(); return csvToBean.parse(); } private Map&lt;String, Customer&gt; parseCustomers(File file) throws IOException { HeaderColumnNameTranslateMappingStrategy&lt;Customer&gt; strategy = new HeaderColumnNameTranslateMappingStrategy&lt;&gt;(); strategy.setType(Customer.class); Map&lt;String, String&gt; columnMapping = new HashMap&lt;&gt;(); columnMapping.put(&quot;id&quot;, &quot;id&quot;); columnMapping.put(&quot;first_name&quot;, &quot;firstName&quot;); columnMapping.put(&quot;last_name&quot;, &quot;lastName&quot;); columnMapping.put(&quot;last_login_balance&quot;, &quot;lastLoginBalance&quot;); strategy.setColumnMapping(columnMapping); CSVReader reader = new CSVReader(new FileReader(file.getPath())); CsvToBean&lt;Customer&gt; csvToBean = new CsvToBeanBuilder&lt;Customer&gt;(reader) .withMappingStrategy(strategy) .build(); return csvToBean.parse().stream().collect(Collectors.toMap(Customer::getId, c -&gt; c)); } private Map&lt;String, AccountType&gt; parseAccountTypes(File file) throws IOException { HeaderColumnNameTranslateMappingStrategy&lt;AccountType&gt; strategy = new HeaderColumnNameTranslateMappingStrategy&lt;&gt;(); strategy.setType(AccountType.class); Map&lt;String, String&gt; columnMapping = new HashMap&lt;&gt;(); columnMapping.put(&quot;account_type&quot;, &quot;accountType&quot;); columnMapping.put(&quot;name&quot;, &quot;name&quot;); strategy.setColumnMapping(columnMapping); CSVReader reader = new CSVReader(new FileReader(file.getPath())); CsvToBean&lt;AccountType&gt; csvToBean = new CsvToBeanBuilder&lt;AccountType&gt;(reader) .withMappingStrategy(strategy) .build(); return csvToBean.parse().stream().collect(Collectors.toMap(AccountType::getAccountType, a -&gt; a)); } } </code></pre> <p>My ControllerTest:</p> <pre><code>package com.colliers.mongodb.controller; import com.colliers.mongodb.model.AccountType; import com.colliers.mongodb.model.Customer; import com.colliers.mongodb.model.DTO.TransactionDTO; import com.colliers.mongodb.model.Transaction; import com.colliers.mongodb.service.TransactionService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Query; import org.springframework.http.ResponseEntity; import java.util.Arrays; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class ControllerTest { @Mock private MongoTemplate mongoTemplate; private Controller controller; @BeforeEach void setup() { TransactionService service = new TransactionService(mongoTemplate); controller = new Controller(service); } @Test void test() {} @Test void getTransactionsByAccountTypeAndCustomerIdWithWIthOneAccountTypeAndOneCustomerIdTest() { Transaction t1 = Transaction.builder() .id(700) .transactionAmount(600.11) .accountType(new AccountType(&quot;1&quot;, &quot;1&quot;, &quot;checking account&quot;)) .customer(new Customer(&quot;1&quot;, &quot;Elliot&quot;, &quot;Alderson&quot;, 199)) .transactionDate(&quot;2017-03-06 13:23:11&quot;) .build(); when(this.mongoTemplate.find(ArgumentMatchers.any(Query.class), ArgumentMatchers.eq(Transaction.class), ArgumentMatchers.anyString())).thenReturn(Arrays.asList(t1)); ResponseEntity&lt;List&lt;TransactionDTO&gt;&gt; result = controller.getTransactionsByAccountTypeAndCustomerId(&quot;1&quot;, &quot;1&quot;); assertThat(result.getBody().get(0).getAccountTypeName()).isEqualTo(&quot;checking account&quot;); assertThat(result.getBody().get(0).getFirstName()).isEqualTo(&quot;Elliot&quot;); } @Test void getTransactionsByAccountTypeAndCustomerIdWithOneCustomerIdAndEmptyAccountTypeTest() { Transaction t1 = Transaction.builder() .id(700) .transactionAmount(600.11) .accountType(new AccountType(&quot;1&quot;, &quot;1&quot;, &quot;checking account&quot;)) .customer(new Customer(&quot;1&quot;, &quot;Elliot&quot;, &quot;Alderson&quot;, 199)) .transactionDate(&quot;2017-03-06 13:23:11&quot;) .build(); Transaction t2 = Transaction.builder() .id(723) .transactionAmount(524.32) .accountType(new AccountType(&quot;2&quot;, &quot;2&quot;, &quot;saving account&quot;)) .customer(new Customer(&quot;1&quot;, &quot;Elliot&quot;, &quot;Alderson&quot;, 199)) .transactionDate(&quot;2013-08-04 23:57:38&quot;) .build(); when(mongoTemplate.find(ArgumentMatchers.any(Query.class), ArgumentMatchers.eq(Transaction.class), ArgumentMatchers.anyString())).thenReturn(Arrays.asList(t1, t2)); ResponseEntity&lt;List&lt;TransactionDTO&gt;&gt; result = controller.getTransactionsByAccountTypeAndCustomerId(&quot;&quot;, &quot;1&quot;); assertThat(result.getBody().get(0).getAccountTypeName()).isEqualTo(&quot;checking account&quot;); assertThat(result.getBody().get(0).getFirstName()).isEqualTo(&quot;Elliot&quot;); assertThat(result.getBody().get(1).getAccountTypeName()).isEqualTo(&quot;saving account&quot;); assertThat(result.getBody().get(1).getFirstName()).isEqualTo(&quot;Elliot&quot;); } @Test void getTransactionsByAccountTypeAndCustomerIdWithEmptyAccountTypeAndALLCustomerIdTest() { Transaction t1 = Transaction.builder() .id(700) .transactionAmount(600.11) .accountType(new AccountType(&quot;1&quot;, &quot;1&quot;, &quot;checking account&quot;)) .customer(new Customer(&quot;1&quot;, &quot;Elliot&quot;, &quot;Alderson&quot;, 199)) .transactionDate(&quot;2017-03-06 13:23:11&quot;) .build(); Transaction t2 = Transaction.builder() .id(723) .transactionAmount(524.32) .accountType(new AccountType(&quot;2&quot;, &quot;2&quot;, &quot;saving account&quot;)) .customer(new Customer(&quot;1&quot;, &quot;Elliot&quot;, &quot;Alderson&quot;, 199)) .transactionDate(&quot;2013-08-04 23:57:38&quot;) .build(); Transaction t3 = Transaction.builder() .id(200) .transactionAmount(500) .accountType(new AccountType(&quot;1&quot;, &quot;1&quot;, &quot;checking account&quot;)) .customer(new Customer(&quot;2&quot;, &quot;Tyrell&quot;, &quot;Wellick&quot;, 10000)) .transactionDate(&quot;2020-10-07 23:59:59&quot;) .build(); Transaction t4 = Transaction.builder() .id(540) .transactionAmount(1000) .accountType(new AccountType(&quot;2&quot;, &quot;2&quot;, &quot;saving account&quot;)) .customer(new Customer(&quot;2&quot;, &quot;Tyrell&quot;, &quot;Wellick&quot;, 10000)) .transactionDate(&quot;2018-02-01 12:05:18&quot;) .build(); when(mongoTemplate.find(ArgumentMatchers.any(Query.class), ArgumentMatchers.eq(Transaction.class), ArgumentMatchers.anyString())).thenReturn(Arrays.asList(t1, t2, t3, t4)); ResponseEntity&lt;List&lt;TransactionDTO&gt;&gt; result = controller.getTransactionsByAccountTypeAndCustomerId(&quot;&quot;, &quot;ALL&quot;); assertThat(result.getBody().get(0).getAccountTypeName()).isEqualTo(&quot;checking account&quot;); assertThat(result.getBody().get(0).getFirstName()).isEqualTo(&quot;Elliot&quot;); assertThat(result.getBody().get(1).getAccountTypeName()).isEqualTo(&quot;saving account&quot;); assertThat(result.getBody().get(1).getFirstName()).isEqualTo(&quot;Elliot&quot;); assertThat(result.getBody().get(2).getAccountTypeName()).isEqualTo(&quot;checking account&quot;); assertThat(result.getBody().get(2).getFirstName()).isEqualTo(&quot;Tyrell&quot;); assertThat(result.getBody().get(3).getAccountTypeName()).isEqualTo(&quot;saving account&quot;); assertThat(result.getBody().get(3).getFirstName()).isEqualTo(&quot;Tyrell&quot;); } } </code></pre> <p>This application is all that I am currently capable of (I want also to note, that I'm not a professional software dev - still learning and want to become one in the future). In order to keep improving I need feedback concerning topics like &quot;clean code&quot;, don't do that - do that, use different library etc. I'm not interested in discussing app security (topic on different time). Below link to GitHub repo.</p> <p><a href="https://github.com/dstarostka/mongodb" rel="nofollow noreferrer">https://github.com/dstarostka/mongodb</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T22:11:31.600", "Id": "495851", "Score": "1", "body": "For anyone in the Close Queue the question has been updated and no longer violates the context rule." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T04:16:22.410", "Id": "495882", "Score": "0", "body": "@pacmaninbw Thanks a lot for that, it saves a lot of time!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T20:58:38.987", "Id": "251778", "Score": "3", "Tags": [ "java", "beginner", "spring", "mongodb", "junit" ], "Title": "Migrate customer and transaction data from CSV to MongoDB" }
251778
<p>IBM's Maximo Asset Management platform has a WORKORDER table (265 columns).</p> <p><strong>Details:</strong></p> <p>The WORKORDER table contains two different kinds of rows:</p> <ul> <li>WO records (istask = 0)</li> <li>Task records (istask = 1).</li> </ul> <p>The table has columns that store the <em>actual</em> costs (populated for both non-task WOs and for tasks):</p> <ul> <li>actlabcost (actual labor cost)</li> <li>actmatcost (actual material cost)</li> <li>actservcost (actual services cost)</li> <li>acttoolcost (actual tool costs)</li> </ul> <hr /> <p><strong>View:</strong></p> <p>I've written a query/view that selects <strong>non-task</strong> WOs.</p> <p>For those non-task workorders, the view rolls up the costs from the related tasks and summarizes them in these columns:</p> <ul> <li>actlabcost_incltask</li> <li>actmatcost_incltask</li> <li>actservcost_incltask</li> <li>acttoolcost_incltask</li> <li>acttotalcost_incltask</li> </ul> <p>I plan to use the view for multiple reports. So I've included all 265 columns in the view via <code>select *</code> (although, Oracle will convert the <code>select *</code> to actual column names when the view is created).</p> <pre><code>--WO_INCL_TASK_ACT_VW (non-task WOs, includes task actuals) select t.task_actlabcost, t.task_actmatcost, t.task_actservcost, t.task_acttoolcost, t.task_acttotalcost, nt.actlabcost + t.task_actlabcost as actlabcost_incltask, nt.actmatcost + t.task_actmatcost as actmatcost_incltask, nt.actservcost + t.task_actservcost as actservcost_incltask, nt.acttoolcost + t.task_acttoolcost as acttoolcost_incltask, t.task_acttotalcost + nt.actlabcost + nt.actmatcost + nt.actservcost + nt.acttoolcost as acttotalcost_incltask, nt.* from workorder nt --non-task WOs left join ( select parent, sum(actlabcost) as task_actlabcost, sum(actmatcost) as task_actmatcost, sum(actservcost) as task_actservcost, sum(acttoolcost) as task_acttoolcost, sum(actlabcost) + sum(actmatcost) + sum(actservcost) + sum(acttoolcost) as task_acttotalcost from workorder group by parent, istask having istask = 1 ) t --tasks on nt.wonum = t.parent where nt.istask = 0 </code></pre> <p><strong>Question:</strong></p> <p>The view works just fine. However, it's fairly lengthy for what it does.</p> <p>Can it be improved?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T00:41:35.510", "Id": "495861", "Score": "0", "body": "Are these columns - `sum(actlabcost) + sum(actmatcost) + sum(actservcost) + sum(acttoolcost) as task_acttotalcost ` - nullable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T00:59:15.863", "Id": "495862", "Score": "0", "body": "@Reinderien I did a search on the table for null values. I couldn't find any. So I think the application must be preventing nulls and storing zeros instead. https://i.stack.imgur.com/e9As1.png. If those columns were nullable, would it compromise my query?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T01:04:02.703", "Id": "495863", "Score": "0", "body": "@Reinderien I looked at the application too. It seems to default to zero, not null. https://i.stack.imgur.com/iPiwW.png" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T01:04:25.123", "Id": "495864", "Score": "1", "body": "_would it compromise my query?_ No, but it would affect my suggestion." } ]
[ { "body": "<p>I know you say that</p>\n<blockquote>\n<p>I plan to use the view for multiple reports. So I've included all 265 columns in the view via select *</p>\n</blockquote>\n<p>but given the truly absurd column count in that table, I would consider a select-splat to be a very last resort. Are you able to narrow this at all?</p>\n<p>Generally your query seems sane. Since you say that the following columns are non-nullable,</p>\n<pre><code>sum(actlabcost) + sum(actmatcost) + sum(actservcost) + sum(acttoolcost)\n</code></pre>\n<p>should be equivalent to</p>\n<pre><code>sum(actlabcost + actmatcost + actservcost + acttoolcost)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T01:24:57.230", "Id": "495866", "Score": "0", "body": "Right. Regarding the second option: summing a null instead of a zero would result in a null, which is not what I want." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T13:41:43.540", "Id": "495925", "Score": "0", "body": "Right; but you told me that there aren't any so it shouldn't matter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T21:51:58.667", "Id": "497248", "Score": "0", "body": "If a workorder doesn't have any tasks that are joined to it, then I think `nt.actlabcost+t.task_actlabcost` would result in `null`, even if `nt.actlabcost` wasn't null. This would not be the desired result (`1 + null = null`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T22:12:35.153", "Id": "497253", "Score": "0", "body": "`task_acttotalcost` is based on columns all from the same table, `workorder`, right? So they'll be all-null or all-non-null. No problem in using normal addition there. The trouble comes when you add `task_acttotalcost` to find `acttotalcost_incltask`, which has the null problem in your original post and needs a `coalesce` to zero." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T22:30:36.190", "Id": "497255", "Score": "0", "body": "I think I understand your point, but my concern is when there aren't any tasks associated with (aka joined to) the non-task workorders. So, `nt.actlabcost+t.task_actlabcost` could end up being `1243.00 + null = null`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-19T22:35:59.577", "Id": "497256", "Score": "0", "body": "Let's continue this chat in https://chat.stackexchange.com/rooms/116444/nullables-in-sql" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T01:13:01.527", "Id": "251791", "ParentId": "251785", "Score": "3" } }, { "body": "<p>This is the query I ended up going with. I believe it handles nulls correctly.</p>\n<p>Note: The cost columns in the WORKORDER table are not nullable (<code>actlabcost</code>, <code>actmatcost</code>, <code>actservcost</code>, <code>acttoolcost</code>).</p>\n<p>So that helps.</p>\n<hr />\n<pre><code>select \n nt.wonum,\n nt.parent,\n nt.hierarchypath,\n nt.classstructureid,\n nt.division,\n nt.worktype,\n nt.status, \n nt.glaccount, \n nt.fircode, \n actstart,\n actfinish,\n nt.siteid,\n nvl(nt.actlabcost,0) + nvl(t.t_actlabcost,0) as actlabcost,\n nvl(nt.actmatcost,0) + nvl(t.t_actmatcost,0) as actmatcost,\n nvl(nt.actservcost,0) + nvl(t.t_actservcost,0) as actservcost,\n nvl(nt.acttoolcost,0) + nvl(t.t_acttoolcost,0) as acttoolcost,\n nvl(t.t_acttotalcost,0) + nvl(nt.actlabcost,0) + nvl(nt.actmatcost,0) + nvl(nt.actservcost,0) + nvl(nt.acttoolcost,0) as acttotalcost,\n coalesce(nt.parent, nt.wonum) as parent_group --only works when WO hierarchy is 1 or 2 levels (not more)\nfrom \n workorder nt --non-task WOs\nleft join\n (\n select \n parent, \n sum(actlabcost) as t_actlabcost,\n sum(actmatcost) as t_actmatcost,\n sum(actservcost) as t_actservcost,\n sum(acttoolcost) as t_acttoolcost,\n sum(actlabcost + actmatcost + actservcost + acttoolcost) as t_acttotalcost\n from \n workorder \n where\n istask = 1\n and woclass in ('WORKORDER', 'ACTIVITY')\n and siteid = 'SERVICES'\n group by\n parent\n ) t --tasks\n on nt.wonum = t.parent\nwhere\n nt.istask = 0\n and woclass in ('WORKORDER', 'ACTIVITY')\n and siteid = 'SERVICES'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-23T17:32:23.337", "Id": "503289", "Score": "2", "body": "It's time to get out of the habit of using `NVL()` and use `COALESCE()` instead. `NVL()` can implicitly convert to a character, isn't in the SQL standard, and doesn't perform short-circuiting. `COALESCE()` fixes all these problems." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-23T07:28:00.627", "Id": "255125", "ParentId": "251785", "Score": "0" } }, { "body": "<p>It looks like you are trying to get the cost of a work order including its children, if it has any, by joining from workorder <code>nt</code> to your in-line view <code>t</code> where <code>nt.wonum = t.parent</code>.</p>\n<p>Are you aware that there is a <code>wogroup</code> column on <code>workorder</code> whose value is the same as <code>wonum</code> for non-task work orders and the same as <code>parent</code> on task work orders? So, you could remove the subquery from your query and just group your workorder records by <code>wogroup</code>.</p>\n<p>For example, to get the actual labor cost for this work order and its children, instead of doing this:</p>\n<pre><code>select \n...\n nt.actlabcost + t.task_actlabcost as actlabcost_incltask, \n...\n nt.*\nfrom \n workorder nt --non-task WOs\nleft join\n...\n ) t --tasks\n on nt.wonum = t.parent\nwhere\n nt.istask = 0\n</code></pre>\n<p>you could do this:</p>\n<pre><code>select \n sum(actlabcost) as acttotalcost, \n wogroup\nfrom workorder\nwhere woclass in ('WORKORDER', 'ACTIVITY')\n and siteid = 'SERVICES'\ngroup by wogroup\n</code></pre>\n<p>On a separate point, in your in-line view, is there a good reason for <code>having istask = 1</code> instead of <code>where istask = 1</code>. In my experience, the <code>having</code> clause is used for conditions that use aggregate functions, and your &quot;flat&quot; <code>istask = 1</code> seems out of place there.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-20T06:27:22.180", "Id": "528774", "Score": "1", "body": "Hi. Welcome to Code Review! This is an alternative code. Please note that we emphasize the review portion of our name. And this doesn't provide an explicit observation about the existing code. Implicitly you seem to be suggesting that the existing code is more complicated than it needs to be. Please say that explicitly and quote the code that you are simplifying. As is, it's hard to see how this relates to the original code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-20T12:20:07.107", "Id": "528795", "Score": "0", "body": "Good call. I should have used WOGROUP. Much simpler and faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T23:05:00.633", "Id": "528921", "Score": "0", "body": "Related post: [Group by x, get other fields too](https://dba.stackexchange.com/questions/299932/group-by-x-get-other-fields-too-comparing-options-and-performance)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-20T06:18:28.300", "Id": "268173", "ParentId": "251785", "Score": "1" } } ]
{ "AcceptedAnswerId": "251791", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T23:19:53.877", "Id": "251785", "Score": "3", "Tags": [ "sql", "oracle" ], "Title": "Select non-task workorders, but include the costs of the tasks" }
251785
<p>I am not an expert in shell scripting,</p> <p>I need help optimizing the shell script I wrote, This shell script I wrote is run by users on the client side who connect to our vpn server from the setting passed in the config.tar.</p> <p>I check if pip or or tar or other packaches are installed if not isntalled than install it, I am doing it in separate if condition, what I want to achieve is I put the packages to check in a listand then iterate if not installed than install it for all apt, pip or pip3 packages.</p> <pre><code>#!/usr/bin/env bash set - command=`which pip` if [ &quot;$command&quot; = &quot;&quot; ] then echo &quot;The pip program not exist on this system.&quot; sudo apt-get install python-pip -y sudo apt install python3-pip -y else echo &quot;Pip is intalled.&quot; fi sudo apt install speedtest-cli pip install -U pip pip3 install mysql-connector-python pip3 install pymysql pip3 install sqlalchemy TAR=`which tar` if [ &quot;$TAR&quot; = &quot;&quot; ] then echo &quot;Tar is not installed, installing now.&quot; sudo apt-get install tar -y else echo &quot;Tar is installed.&quot; fi # lets install requests pip install requests cd $HOME echo &quot;Iniating download...&quot; curl -sL &quot;http://my.domain.com/config&quot; -o &quot;config.tar&quot; tar xvf config.tar sudo chmod 604 ucc.py if [ -e ucc.py ] then echo &quot;ucc.py installed.&quot; else echo &quot;ucc.py failed to download.&quot; fi if [ -e ucc.service ] then echo &quot;ucc.service installed.&quot; else echo &quot;ucc.service failed to download.&quot; fi sudo mv ucc.service &quot;/lib/systemd/system/&quot; if [ -e client.conf ] then sudo mv client.conf /etc/openvpn/ echo &quot;client.conf downloaded.&quot; else echo &quot;client.conf failed to download.&quot; fi sudo mv -f client.conf /etc/openvpn/ cd /etc/openvpn/ if [ -e client.conf ] then echo &quot;client.conf installed.&quot; else echo &quot;client.conf failed to download.&quot; fi sudo systemctl restart openvpn@client sudo systemctl status openvpn@client </code></pre> <p>any help will be greatly appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T05:13:41.837", "Id": "495890", "Score": "1", "body": "For the apt-get install, why not just run the install command? Nothing bad should happen from attempting to install a package that already exists" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T09:15:16.030", "Id": "495903", "Score": "0", "body": "thats because on client side end user is non-technical person" } ]
[ { "body": "<ol>\n<li>Use for loops for expandability and readability.</li>\n<li>If you want to test for individual utilities, try using <code>command -v pip</code> instead of which and comparing against that.</li>\n<li>Look up and understand the functional difference between single bracket comparisons and double bracket. [ ] vs [[ ]]</li>\n<li>`` syntax is very out of date, use $()</li>\n<li>If you have to call /usr/bin/env for the location of bash, but broadly assume apt is the package manager on the system, it's much safer to use /bin/bash.</li>\n<li>Python requests is also stored as an apt package, I moved it into the first for loop statement.</li>\n</ol>\n<pre><code>#!/bin/bash\n\nfor PACKAGE in python-pip python-pip3 speedtest-cli tar python-requests; do\n if [[ ! $(dpkg -l ${PACKAGE}) ]] ; then\n echo &quot;${PACKAGE} is not installed, installing now.&quot;\n sudo apt-get install ${PACKAGE} -y\n else\n echo &quot;${PACKAGE} is installed.&quot;\n fi\ndone\n\npip3 install -U pip\n\nfor PACKAGE in mysql-connector-python pymysql sqlalchemy ; do\n pip3 install -U ${PACKAGE}\n\n if [[ $? -ne 0 ]] ; then echo &quot;${PACKAGE} failed to installed&quot; ; fi\ndone\n\ncd $HOME\necho &quot;Iniating download...&quot;\ncurl -sL &quot;http://my.domain.com/config&quot; -o &quot;config.tar&quot;\n\ntar xvf config.tar\n\nsudo chmod 604 ucc.py\n## I don't know why you need to use sudo to chmod an item inside your own home dir, but ill leave this here.\n## Also, you can tar a package with certian perms and then unpack it to obey those specific permissions.\n\nfor ITEM in ucc.py ucc.service client.conf; do\n if [[ -e ${ITEM} ]] ; then\n echo &quot;${ITEM} is installed.&quot;\n else\n echo &quot;${ITEM} failed to download&quot;\n fi\ndone\n\nsudo mv ucc.service /lib/systemd/system/\nsudo mv client.conf /etc/openvpn/\nsudo mv -f client.conf /etc/openvpn/\n\nsudo systemctl restart openvpn@client\nsudo systemctl status openvpn@client\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T23:41:45.357", "Id": "495964", "Score": "0", "body": "do you mean if i set the file permission and tar it on extraction those permission attributes will be preserved?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T00:20:45.867", "Id": "495966", "Score": "0", "body": "@ChangZhao https://askubuntu.com/questions/463325/what-does-tars-p-preserve-permissions-flag-actually-preserve" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T16:36:52.003", "Id": "251824", "ParentId": "251789", "Score": "1" } } ]
{ "AcceptedAnswerId": "251824", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T00:07:28.660", "Id": "251789", "Score": "5", "Tags": [ "performance", "bash", "shell" ], "Title": "How to put apt and python packages in a list and check if installed or not then install" }
251789
<h1>What is an FEN?</h1> <p>Link to the Wikipedia page: <a href="https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation" rel="noreferrer"><strong>Forsyth–Edwards Notation</strong></a></p> <p>An FEN is a very simple way of representing a chess position in a single line string. It contains the following data</p> <ul> <li>Which piece is placed where, and which squares remain empty</li> <li>Who is going to play the next move, white or black</li> <li><a href="https://en.wikipedia.org/wiki/Castling#:%7E:text=Castling%20may%20only%20be%20done,attacked%20by%20an%20enemy%20piece." rel="noreferrer">Castling rights</a></li> <li><a href="https://en.wikipedia.org/wiki/En_passant" rel="noreferrer">en-passant</a></li> <li>Halfmove clock ( not required )</li> <li>Fullmove number ( not required )</li> </ul> <p><sup> Anyone unfamiliar with these terms, you won't need to know <strong>what</strong> they are</sup></p> <p>At the current stage, I don't need to worry about the last two points.</p> <p>This is what the fen looks like at the very starting position of the chess game</p> <pre><code>rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 </code></pre> <p>Captial letters are white pieces, lowercase letters are black. <br></p> <h1>How to parse it</h1> <p>Apologies for the lenghty question, but it will be very helpful to the reviewer if he/she understands the FEN completely</p> <p>The main goal here is to decode this into a character array. The size will be equal to the number of square in a chess board(64).</p> <p>Assume we are parsing to this array</p> <pre><code>char board[64]; </code></pre> <p>We can assume this board to be <a href="https://i.stack.imgur.com/ZKC7E.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/ZKC7E.jpg" alt="chess" /></a> The numbers on the squares are just the indexes. A chess FEN starts the square <code>A8</code> and ends in the square <code>H8</code>, this is perfect because those are the start and end indexes of our array</p> <p>So if this is the FEN</p> <pre><code>rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 </code></pre> <p>the first few letters go <code>rnbq.../</code>. So the parsing should go as follows</p> <p><a href="https://i.stack.imgur.com/hVdYu.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/hVdYu.jpg" alt="parse" /></a></p> <p>A <code>/</code> indicates going to the next row. Each time you see a numeric value, for example <code>8</code> here. <br>You skip those number of squares ( which means you leave those squares as empty )So if you see a <code>5</code> at index <code>20</code>. Then <code>20, 21, 22, 23, 24</code> are left as empty squares and now we're at the 25th square.</p> <h1>Special attributes</h1> <p>After the parsing of the board is over, the fen has a <code>' '</code> or an empty space indicating we're moving to the next attribute</p> <p>So in our case</p> <pre><code>rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 ^ Here is our first space Leaves us with w KQkq - 0 1 </code></pre> <p>Each space says that now the fen will describe something else, the rest are split as follows <a href="https://i.stack.imgur.com/OGWRy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OGWRy.png" alt="enter image description here" /></a><br> last two numeric values are not required as mentioned earlier</p> <h2>turn</h2> <p>It will either be <code>w</code> or <code>b</code>,</p> <ul> <li><code>w</code> - White will play next</li> <li><code>b</code> - Black will play next</li> </ul> <h2>castling</h2> <p>Each color has two types of castling rights, king and queen castle</p> <ul> <li><code>k</code> Black's king side castle is possible</li> <li><code>q</code> Black's queen side castle is possible</li> <li><code>K</code> White's king side castle is possible</li> <li><code>Q</code> White's queen side castle is possible</li> </ul> <p>If any type of castle is <strong>not possible</strong>, then that letter will not be present here</p> <h2>en-passant</h2> <ul> <li><code>-</code> means no en-passant in this position</li> <li>anything other than <code>-</code> will be the en-passant square</li> </ul> <h2>examples</h2> <pre><code> b kK - </code></pre> <ul> <li>Black to play</li> <li>only king side castles are possible for both colors</li> <li>no en-passant</li> </ul> <pre><code> w KQq e4 </code></pre> <ul> <li>White to play</li> <li>White can castle king and queen side, black can castle only queen side</li> <li>en-passant is possible on square <code>e4</code></li> </ul> <p>I hope this explanation helps</p> <h1>My implementation</h1> <p>I'll parse the fen into this class</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;string&gt; #include &lt;cctype&gt; #define NB_SQ 64 // number of squares #define NB_CASTLE 2 // number of castle types #define NB_COLOR 2 // number of colors enum Castle { king_side, queen_side }; enum Color { white, black }; class Chess { private: Color turn; std::string en_passant; char board[NB_SQ]; bool castle_rights[NB_COLOR][NB_CASTLE]; public: Chess(); void parse_fen(const std::string&amp;); }; </code></pre> <pre class="lang-cpp prettyprint-override"><code>Chess::Chess() { for (int i = 0; i &lt; NB_SQ; i++) board[i] = '.'; // set all squares to be empty '.' for (int i = 0; i &lt; NB_COLOR; i++) for (int j = 0; j &lt; NB_CASTLE; j++) castle_rights[i][j] = false; // all castle_rights are false by default } void Chess::parse_fen (const std::string&amp; fen) { const size_t size = fen.size(); size_t iter = 0; int index = 0; // parse the board first for (; (iter &lt; size) and (fen[iter] != ' '); iter++) { if (fen[iter] == '/') continue; if (isdigit(fen[iter])) index += (fen[iter] - '0'); // converts char digit to int. `5` to 5 else { board[index] = fen[iter]; ++index; } } turn = fen[iter + 1] == 'w' ? Color::white : Color::black; for (iter += 3; (iter &lt; size )and (fen[iter] != ' '); iter++) { if (fen[iter] == 'k') castle_rights[Color::black][Castle::king_side] = true; else if (fen[iter] == 'K') castle_rights[Color::white][Castle::king_side] = true; else if (fen[iter] == 'q') castle_rights[Color::black][Castle::queen_side] = true; else if (fen[iter] == 'Q') castle_rights[Color::white][Castle::queen_side] = true; } en_passant = fen.substr(iter + 1, 3); } </code></pre> <ul> <li><p>Speed isn't a concern <strong>at all</strong> here. Anything that is slower, but better structured and more compact is definitely better since this function is performed at most 2-3 times and takes a few milliseconds anyway.</p> </li> <li><p>Looking to avoid the extra noise in the function.</p> </li> </ul> <h2>test</h2> <p>Can test whether this works by printing out the board array</p> <pre class="lang-cpp prettyprint-override"><code>void print_board() { for (int i = 0; i &lt; NB_SQ; i++) { if (i % 8 == 0) std::cout &lt;&lt; '\n'; std::cout &lt;&lt; board[i] &lt;&lt; ' '; } } </code></pre> <p>Output after parsing the default fen</p> <pre class="lang-cpp prettyprint-override"><code>a.parse_fen(&quot;rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1&quot;); </code></pre> <pre><code> r n b q k b n r p p p p p p p p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P P P P P P P P R N B Q K B N R </code></pre>
[]
[ { "body": "<ul>\n<li><p><strong>Handle malformed FEN</strong></p>\n<p>The code happily accepts <code>/9/</code>. It doesn't check that the rank spells out exactly 8 files. It doesn't check that the input spells out exactly 8 ranks. In both cases, hello buffer overflow.</p>\n<p>It also doesn't check that the piece letter makes sense (may be good for the fairy chess. but still ...).</p>\n</li>\n<li><p><strike><code>fen.substr(iter + 1, 3);</code> looks strange, as it has no effect. Along the same line, I don't see en passant handling.</strike></p>\n</li>\n<li><p>The code assumes that there is exacly one space between board and turn, and between turn and castling rights. I am not sure that FEN standard mandates it. If it does not, allow multiple spaces; if it does, prepare to handle a malformed one.</p>\n</li>\n<li><p><strong>More functions please</strong>, aka <strong>no naked loops</strong></p>\n<p>Every time you feel compelled to annotate a loop with a comment like</p>\n<pre><code> // parse the board first\n</code></pre>\n<p>consider to factor the loop out into a function with the proper name. Something along the lines of</p>\n<pre><code> void Chess::parse_fen (const std::string&amp; fen)\n {\n std::string::iterator it = fen.begin();\n it = parse_board(it);\n it = parse_turn(it);\n it = parse_castle_rights(it);\n ....\n }\n</code></pre>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T07:16:09.277", "Id": "495897", "Score": "1", "body": "Great! The last line captures the `en_passant`, I've tested it and it works, I made a last-second change and accidentally replaced the `en_passant = `, sorry about that. Can I edit the question and add it now? It wasn't intentional" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T07:36:25.030", "Id": "495900", "Score": "2", "body": "I thought so. Please do. While you do it, also remove the semicolon from `void Chess::parse_fen (const std::string& fen);`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T07:13:21.203", "Id": "251796", "ParentId": "251795", "Score": "7" } }, { "body": "<ul>\n<li><p>Use constant variables, not macros. (Perhaps <code>NB_COLOR</code> and <code>NB_CASTLE</code> could be added to the <code>enum</code>s).</p>\n</li>\n<li><p>Use <code>enum class</code> instead of a plain <code>enum</code>.</p>\n</li>\n<li><p><code>en_passant</code> could be translated to the relevant index in the board. Perhaps use <code>std::optional</code>, or a named constant (e.g. <code>-1</code>) for the &quot;no en-passant available&quot; case.</p>\n</li>\n<li><p>Use <code>std::array</code> instead of a plain array for utility reasons. e.g. in the constructor we could do <code>board.fill('.')</code>. It also makes copying much easier.</p>\n</li>\n<li><p>Don't forget to initialize <code>turn</code> in the constructor.</p>\n</li>\n<li><p>In addition to vnp's comments about parsing:</p>\n<p>Currently the parser skips over indices in the board (e.g. with <code>/8/</code>). If the board wasn't previously empty, these squares will still contain the pieces from before!! We must explicitly set these squares to be empty.</p>\n<p>It might be better to make <code>parse_fen</code> an alternate form of constructor instead.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T10:51:28.117", "Id": "251802", "ParentId": "251795", "Score": "3" } } ]
{ "AcceptedAnswerId": "251796", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T06:17:12.833", "Id": "251795", "Score": "11", "Tags": [ "c++", "parsing", "chess" ], "Title": "Parsing a Chess FEN" }
251795
<p>Need help to refactor this code to look like its done by a pro. Or just put some advice or links to useful stuff.</p> <p>The idea is to clone a div with two empty tables for two separate arrays of data. div is cloned depending on the longest array length between the two. Then append row of data to them, if rows reach max number the loop continues on another cloned table. loop continues even if the one row is finished appending</p> <pre><code>&lt;div id=&quot;d-page-0&quot;&gt; &lt;table id=&quot;e-tbl-0&quot;&gt; //content1 //7 row max &lt;/table&gt; &lt;table id=&quot;w-tbl-0&quot;&gt; //content2 //21 row max &lt;/table&gt; &lt;/div&gt; </code></pre> <p>Javascript part</p> <pre><code>let d1 = @json($data1); //get data let d2 = @json($data2); //get data let ar1 = []; let ar2 = []; let s = 0; for (let i = 7; i &lt; d1.length; i+=7) { ar1.push(d1.slice(i, i+7)); //slice data 1 } for (let i = 21; i &lt; d2.length; i+=21) { ar2.push(d2.slice(i, i+21)); //slice data 2 } ar1.length &gt; ar2.length ? s = ar1.length : s = ar2.length; //take longest array length for (let v = 0; v &lt; s-1; v++) { //clone div using longest array length $(&quot;#d-page-0&quot;).clone().prop(&quot;id&quot;, &quot;d-page-&quot;+(v+1)).insertAfter(&quot;#d-page-&quot;+v); //clone div, edit id $(&quot;#d-page-&quot;+(v+1)).find(&quot;#e-tbl-0&quot;, &quot;table&quot;).prop(&quot;id&quot;, &quot;e-tbl-&quot;+(v+1)); //edit 1st tbl id $(&quot;#d-page-&quot;+(v+1)).find(&quot;#w-tbl-0&quot;, &quot;table&quot;).prop(&quot;id&quot;, &quot;w-tbl-&quot;+(v+1)); //edit 2nd tbl id } //append 1st data to 1st table for (let x = 0; x &lt; ar1.length; x++) { let k = ar1[x]; for (let y = 0; y &lt; k.length; y++) { $('#e-tbl-'+x).append( `&lt;tr&gt; &lt;td&gt; ar1[x][y].content &lt;/td&gt; &lt;/tr&gt;` ); } } //append 2nd data to 2nd table for (let x = 0; x &lt; ar2.length; x++) { let k = ar2[x]; for (let y = 0; y &lt; k.length; y++) { $('#w-tbl-'+x).append( `&lt;tr&gt; &lt;td&gt; ar1[x][y].content &lt;/td&gt; &lt;/tr&gt;` ); } } </code></pre> <p>working sample <a href="https://jsfiddle.net/eeneg/pgk3dhac/57/" rel="nofollow noreferrer">https://jsfiddle.net/eeneg/pgk3dhac/57/</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T15:54:14.560", "Id": "514338", "Score": "1", "body": "I [changed the title](https://codereview.stackexchange.com/revisions/251797/2) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate." } ]
[ { "body": "<p>I've refactored your code below to add some of the repetitive items into functions and tried to improve your variable names a little.</p>\n<p>The new variable names and function names should clearly indicate their intended purpose/data.</p>\n<p>A rule of thumb worth remembering is the concept of <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY (Do not Repeat Yourself)</a>.\n<div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const createArraywithJsonData = function(count, data) {\n let array = [];\n \n for (let i = count; i &lt; data.length; i += count) {\n array.push(data.slice(i, i + count));\n }\n \n return array;\n}\n\nconst editTableId = function(selector, counter) {\n $(`#d-page-${(counter+1)}`).find(`#${selector}-0`, \"table\").prop(\"id\", `${selector}-${(counter+1)}`);\n}\n\nconst appendDataToTable = function(array, property, selector) {\n for (let x = 0; x &lt; array.length; x++) {\n let k = array[x];\n\n for (let y = 0; y &lt; k.length; y++) {\n $(`#${selector}-${x}`).append(`&lt;tr&gt;&lt;td&gt;${array[x][y][property]}&lt;/td&gt;&lt;/tr&gt;`);\n }\n }\n}\n\nlet d1 = [\n {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }, {\n a: \"1\"\n }\n];\nlet d2 = [\n {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }, {\n b: \"2\"\n }\n];\n\nlet ar1 = createArraywithJsonData(7, d1);\nlet ar2 = createArraywithJsonData(21, d2);\nlet longestArrayLength = ar1.length &gt; ar2.length ? ar1.length : ar2.length;\n\n\nfor (let v = 0; v &lt; longestArrayLength - 1; v++) { //clone div using longest array length\n $(\"#d-page-0\").clone().prop(\"id\", `d-page-${(v + 1)}`).insertAfter(`#d-page-${v}`); //clone div, edit id\n editTableId('e-tbl', v);\n editTableId('w-tbl', v);\n}\n\nappendDataToTable(ar1, 'a', 'e-tbl');\nappendDataToTable(ar2, 'b', 'w-tbl');</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;!DOCTYPE html&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"\" xml:lang=\"\"&gt;\n &lt;head&gt;\n &lt;title&gt;&lt;/title&gt;\n &lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/&gt;\n &lt;/head&gt;\n\n &lt;body bgcolor=\"#A0A0A0\" vlink=\"blue\" link=\"blue\"&gt;\n &lt;div id=\"d-page-0\"&gt;\n &lt;table id=\"e-tbl-0\"&gt;\n &lt;tr&gt;&lt;th&gt;tbl1&lt;/th&gt;&lt;/tr&gt;\n &lt;/table&gt;\n\n &lt;table id=\"w-tbl-0\"&gt;\n &lt;tr&gt;&lt;th&gt;tbl2&lt;/th&gt;&lt;/tr&gt;\n &lt;/table&gt;\n &lt;/div&gt;\n &lt;/body&gt;\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T15:31:54.483", "Id": "260570", "ParentId": "251797", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T07:40:52.757", "Id": "251797", "Score": "2", "Tags": [ "javascript", "beginner", "jquery", "html" ], "Title": "clone of HTML tables of data" }
251797
<p>I wrote brainfuck interpreter in order to prepare myself for a C job. I try to write the code as clear and as defensively as I can. Can somebody take a look at the code and give me some hints for improvement?</p> <pre><code>// tape.h #pragma once #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;assert.h&gt; typedef struct Tape { long pointer; long capacity; unsigned short *data; } Tape; void initializeTape(Tape *tape); void growTape(Tape *tape); void incrementPointer(Tape *tape); void decrementPointer(Tape *tape); void incrementValue(Tape *tape); void decrementValue(Tape *tape); void read(Tape *tape); void get(Tape *tape); void freeTape(Tape *tape); long interpret(Tape *tape, const char *source_code, long source_code_size, long position); </code></pre> <p>The implementation of <code>tape.h</code></p> <pre><code>// tape.c #include &quot;tape.h&quot; void initializeTape(Tape *tape) { tape-&gt;pointer = 0; tape-&gt;capacity = 8; tape-&gt;data = (unsigned short *) calloc( tape-&gt;capacity, sizeof(unsigned short)); if (tape-&gt;data == NULL) { fprintf(stderr, &quot;Out of memory error.\n&quot;); exit(1); } } void growTape(Tape *tape) { tape-&gt;capacity *= 2; tape-&gt;data = (unsigned short *) realloc(tape-&gt;data, tape-&gt;capacity); if (tape-&gt;data == NULL) { fprintf(stderr, &quot;Out of memory error.\n&quot;); exit(1); } } void incrementPointer(Tape *tape) { if (tape-&gt;pointer &gt;= tape-&gt;capacity) { growTape(tape); } tape-&gt;pointer++; } void decrementPointer(Tape *tape) { if (tape-&gt;pointer == 0) { fprintf(stderr, &quot;Syntax error. Negative pointer detected.&quot;); exit(1); } tape-&gt;pointer--; } void incrementValue(Tape *tape) { tape-&gt;data[tape-&gt;pointer]++; } void decrementValue(Tape *tape) { tape-&gt;data[tape-&gt;pointer]--; } void read(Tape *tape) { putchar(tape-&gt;data[tape-&gt;pointer]); } void get(Tape *tape) { tape-&gt;data[tape-&gt;pointer] = (char) getchar(); } void freeTape(Tape *tape) { free(tape-&gt;data); tape-&gt;pointer = 0; tape-&gt;capacity = 0; } long interpret(Tape *tape, const char *source_code, long source_code_size, long position) { char c = source_code[position]; switch (c) { case '&gt;': incrementPointer(tape); break; case '&lt;': decrementPointer(tape); break; case '+': incrementValue(tape); break; case '-': decrementValue(tape); break; case '.': read(tape); break; case ',': get(tape); break; case '[': if (tape-&gt;data[tape-&gt;pointer] == (char) 0) { int stack = 1; long j = position + 1; for (; j &lt; source_code_size &amp;&amp; stack &gt; 0 &amp;&amp; tape-&gt;pointer &lt; source_code_size; j++) { char _c = source_code[j]; if (_c == '[') { ++stack; } else if (_c == ']') { --stack; } } if (stack != 0) { fprintf(stderr, &quot;Syntax error. Missing closing ].\n&quot;); exit(1); } else { position = j + 1; } } break; case ']': if (tape-&gt;data[tape-&gt;pointer] != (char) 0) { int stack = 1; long j = position - 1; for (; j &gt;= 0 &amp;&amp; stack &gt; 0 &amp;&amp; tape-&gt;pointer &gt;= 0; j--) { char _c = source_code[j]; if (_c == '[') { --stack; } else if (_c == ']') { ++stack; } } if (stack != 0) { fprintf(stderr, &quot;Syntax error. Missing opening [.\n&quot;); exit(1); } else { position = j + 1; } } break; default: break; } return ++position; } </code></pre> <p>And the <code>main</code> file:</p> <pre><code>// main.c #include &quot;tape.h&quot; int main(int argc, char **argv) { FILE *file; if (argc &lt; 2) { file = fopen(&quot;helloworld.bf&quot;, &quot;r&quot;); } else { file = fopen(argv[1], &quot;r&quot;); } if (file == NULL) { fprintf(stderr, &quot;Can not open file %s\n&quot;, argv[1]); return 1; } if (fseek(file, 0L, SEEK_END) != 0) { fprintf(stderr, &quot;Fail to fseek file %s\n&quot;, argv[1]); return 1; } long filesize = ftell(file); if (filesize &lt; 0) { fprintf(stderr, &quot;Fail to read file's size\n&quot;); return 1; } rewind(file); char source_code[filesize]; size_t result = fread(source_code, 1, filesize, file); if (fclose(file) != 0) { fprintf(stderr, &quot;Can not close file %s\n&quot;, argv[1]); return 1; } if (result != filesize) { fprintf(stderr, &quot;Can not read file. Corrupt\n&quot;); } Tape tape; initializeTape(&amp;tape); long i = 0; while(i &lt; filesize) { i = interpret(&amp;tape, source_code, filesize, i); } freeTape(&amp;tape); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T23:58:16.660", "Id": "495965", "Score": "5", "body": "Minor detail: don’t throw away the original pointer when calling realloc(), because if it fails, you might still want to access (or free) the original data. You normally see something like `void *newptr = realloc(...); if ( newptr ) data = newptr; else handle_nomemory();`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T15:50:21.663", "Id": "496013", "Score": "5", "body": "With a little dyslexia, the title of this question suggests that one implemented a C interpreter in brainflak... which would be quite astonishing, and certainly imply enough knowledge of C for a job!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-12T15:36:44.447", "Id": "496369", "Score": "1", "body": "A syntax error is a specific kind of error; a negative tape pointer isn't one." } ]
[ { "body": "<h1>Only include the header files that you need</h1>\n<p>Looking at <code>tape.h</code>, it only contains declarations and no definitions. As such, the header files only serve to bloat up the source code and increase compilation time. You should move them to <code>tape.c</code>.</p>\n<h1>Use <code>static</code> methods if possible</h1>\n<p>If I look at <code>main.c</code>, the only functions that are utilized are <code>initializeTape</code>, <code>interpret</code> and <code>freeTape</code>. These are the only functions that form the interface. You could move the other functions into <code>tape.c</code> and declare them <code>static</code>. Remember, header files should only contain the necessary functions.</p>\n<h1>Use fixed width integers from &lt;stdint.h&gt;</h1>\n<p>I'm not a fan of using data types such as <code>long</code>, <code>unsigned short</code>, <code>long long</code> since the standard makes no guarantees about the actual size of these types; only the minimum size. Prefer using fixed types such as <code>int64_t</code>, <code>uint16_t</code>, <code>intptr_t</code>, etc.</p>\n<h1><code>initializeTape</code> and <code>growTape</code> should not exit</h1>\n<p>Imagine being a user trying to use your code in one of their projects. If you fail to allocate, the program will exit and will not give the user control on how to deal with the error.</p>\n<p>Consider returning a value based on whether memory was successfully allocated, such as 0 or -1, or even <code>true</code> or <code>false</code> if you have access to C99. That way, the user can check and decide what to do in case of failure.</p>\n<pre><code>if(!initializeTape(&amp;tape))\n{\n // Do some error handling here\n}\n</code></pre>\n<h1>You don't have to cast to <code>unsigned short *</code> after allocating</h1>\n<p>Not a problem, but I should mention that it is not necessary to cast to the desired type after allocating as <code>void*</code> is implicitly convertible to other pointer types.</p>\n<h1>Check <code>tape == NULL</code> in <code>freeTape</code></h1>\n<p>This could lead to potential segfaults if you're not careful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T14:34:57.223", "Id": "495930", "Score": "7", "body": "_tape.h only contains declarations and no definitions._ - Yeah - that's the point. It should stay like this; that's the standard thing to do, and mashing those into the `.c` file will not buy you much compilation efficiency, assuming that we're not living in the 1970s." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T09:42:47.507", "Id": "495981", "Score": "3", "body": "The standard does make some guarantees about the range of values that can be represented by the built-in types. Fixed-width types such as `int64_t` are usually a poor choice, especially compared to `int_fast64_t`, for example." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T11:38:52.397", "Id": "251804", "ParentId": "251798", "Score": "12" } }, { "body": "<h2>Overall Observations</h2>\n<p>An interpreter should be able to read from standard in as well as from a file, this would break the entire tape model. The user could also redirect an input file to standard in.</p>\n<p>If you are going to program in C then you need to get comfortable with pointers.</p>\n<p>In the case of file input I would use an algorithm that reads a line at a time, that way the file doesn't need to be read twice and the memory used to store the file doesn't need to be allocated. Reading a line at a time will also work for console input. If you are use C in an embedded environment allocating the space to store the memory could seriously affect the amount of memory available for processing. For this reason you also need to be careful when using <code>malloc()</code>, <code>calloc()</code>, or <code>realloc()</code> in an embedded environment. Some embedded C compilers do not support memory allocation and some companies will have coding standards that do not include memory allocation for embedded applications.</p>\n<h2>Only Include Headers Needed to Make the Code Compile</h2>\n<p>The header file <code>tape.h</code> includes <code>assert.h</code> and <code>assert()</code> is not used in the program. Since the C pre-processor implementation of include is generally to create a temporary source file and actually copy the included header files this increases the size of the temporary source files without need and increases compile time.</p>\n<p>Hiding <code>#include</code> statements within other include files can sometimes lead to problems, include files that are necessary to make the header compile and <code>tape.h</code> doesn't need any header files to compile. An example of when it would be necessary to include a header file in <code>tape.h</code> is if there were functions that returned type <code>bool</code> and then the header file should contain the statement <code>#include &lt;stdbool.h&gt;</code>.</p>\n<p>Make it clear what each C source file needs to compile by including the headers in the C source file.</p>\n<p>As a side note, it is better not to use <code>assert</code> since if the code is optimized all asserts will be optimized out of the code.</p>\n<h2>Performance (speed)</h2>\n<p>In the main loop of the program and in the function <code>interpret()</code> execution time might be improved if you used character pointers rather than integer indexing. In addition to possibly improving the performance this could also decrease the amount of code in the function <code>interpret()</code> by reducing the number of temporary variables. Note the following code has not been tested and may not work.</p>\n<p>In <code>main()</code>:</p>\n<pre><code> char* current_source_code_ptr = source_code;\n char* end_file_ptr = &amp;source_code[filesize - 1];\n while (current_source_code_ptr &lt; end_file_ptr) {\n current_source_code_ptr = interpret(current_source_code_ptr, end_file_ptr, source_code, &amp;tape);\n }\n\nchar* interpret(char* current_source_code_ptr, const char* end_file_ptr, const char *source_code, Tape* tape) {\n switch (*current_source_code_ptr) {\n case '&gt;':\n incrementPointer(tape);\n break;\n case '&lt;':\n decrementPointer(tape);\n break;\n case '+':\n incrementValue(tape);\n break;\n case '-':\n decrementValue(tape);\n break;\n case '.':\n read(tape);\n break;\n case ',':\n get(tape);\n break;\n case '[':\n if (tape-&gt;data[tape-&gt;pointer] == (char)0) {\n int stack = 1;\n for (; current_source_code_ptr &lt; end_file_ptr &amp;&amp; stack &gt; 0 &amp;&amp; tape-&gt;pointer &lt; (end_file_ptr - source_code); current_source_code_ptr++) {\n if (*current_source_code_ptr == '[') {\n ++stack;\n }\n else if (*current_source_code_ptr == ']') {\n --stack;\n }\n }\n if (stack != 0) {\n fprintf(stderr, &quot;Syntax error. Missing closing ].\\n&quot;);\n exit(EXIT_FAILURE);\n }\n else {\n current_source_code_ptr++;\n }\n }\n break;\n case ']':\n if (tape-&gt;data[tape-&gt;pointer] != (char)0) {\n int stack = 1;\n for (; current_source_code_ptr &gt;= source_code &amp;&amp; stack &gt; 0 &amp;&amp; tape-&gt;pointer &gt;= 0; current_source_code_ptr--) {\n if (*current_source_code_ptr == '[') {\n --stack;\n }\n else if (*current_source_code_ptr == ']') {\n ++stack;\n }\n }\n if (stack != 0) {\n fprintf(stderr, &quot;Syntax error. Missing opening [.\\n&quot;);\n exit(EXIT_FAILURE);\n }\n else {\n current_source_code_ptr++;\n }\n }\n break;\n default:\n break;\n }\n return ++current_source_code_ptr;\n}\n</code></pre>\n<h2>Complexity</h2>\n<p>The switch/case statement in the function <code>interpret()</code> is too long, each case should be implemented by a function, so the code for <code>case '[':</code> and <code>case ']':</code> should be moved into separate functions.</p>\n<h2>Use System Defined Constants</h2>\n<p>The header file <code>stdlib.h</code> includes system specific definitions for the macros <a href=\"https://en.cppreference.com/w/c/program/EXIT_status\" rel=\"noreferrer\">EXIT_SUCCESS and EXIT_FAILURE</a>. This would make the code more readable and possibly more portable.</p>\n<p>// main.c</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &quot;tape.h&quot;\n\nint main(int argc, char** argv) {\n FILE* file;\n if (argc &lt; 2) {\n file = fopen(&quot;helloworld.bf&quot;, &quot;r&quot;);\n }\n else {\n file = fopen(argv[1], &quot;r&quot;);\n }\n if (file == NULL) {\n fprintf(stderr, &quot;Can not open file %s\\n&quot;, argv[1]);\n return EXIT_FAILURE;\n }\n\n if (fseek(file, 0L, SEEK_END) != 0) {\n fprintf(stderr, &quot;Fail to fseek file %s\\n&quot;, argv[1]);\n return EXIT_FAILURE;\n }\n long filesize = ftell(file);\n if (filesize &lt; 0) {\n fprintf(stderr, &quot;Fail to read file's size\\n&quot;);\n return EXIT_FAILURE;\n }\n rewind(file);\n\n char source_code[filesize];\n size_t result = fread(source_code, 1, filesize, file);\n\n if (fclose(file) != 0) {\n fprintf(stderr, &quot;Can not close file %s\\n&quot;, argv[1]);\n return EXIT_FAILURE;\n }\n\n if (result != filesize) {\n fprintf(stderr, &quot;Can not read file. Corrupt\\n&quot;);\n }\n\n Tape tape;\n initializeTape(&amp;tape);\n long i = 0;\n\n while (i &lt; filesize) {\n i = interpret(&amp;tape, source_code, filesize, i);\n }\n freeTape(&amp;tape);\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T09:39:45.227", "Id": "495980", "Score": "4", "body": "\"_a line at a time, ... doesn't need to be allocated_\" - does Brainfuck have a strict line length limit, then?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T12:59:56.507", "Id": "496003", "Score": "4", "body": "I would be careful in assuming pointer arithmetic is more efficient than pointer + integer offset. Often CPUs have native instructions handling pointer + offset from register. And if the compiler can inline everything, it probably won't make any difference at all. In this case, it doesn't matter much, except checking whether the end of the tape is reached in `incrementPointer()` and `decrementPointer()` is IMO slightly nicer to write using offsets than using pointers." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T16:40:45.810", "Id": "251825", "ParentId": "251798", "Score": "18" } }, { "body": "<p>You could use <code>perror()</code> to give more useful information from library-call failures. For example, consider</p>\n<blockquote>\n<pre><code>if (file == NULL) {\n fprintf(stderr, &quot;Can not open file %s\\n&quot;, argv[1]);\n return EXIT_FAILURE;\n}\n</code></pre>\n</blockquote>\n<p>We could get better error message (e.g. &quot;file not found&quot;, &quot;permission denied&quot;, etc) like this:</p>\n<pre><code>if (!file) {\n perror(argv[1]);\n return EXIT_FAILURE;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T12:53:11.583", "Id": "496001", "Score": "2", "body": "But `perror()` unfortunately doesn't show what the filename was. You can write `fprintf(stderr, \"Could not open %s: %s\\n\", argv[1], strerror(errno))`, or if you're on Linux or BSD there's the very convenient [`err()`](https://man7.org/linux/man-pages/man3/err.3.html), sadly not standard C." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T13:16:30.933", "Id": "496004", "Score": "4", "body": "Yes @G.Sliepen, though in my example, it does show the filename (at the expense of not showing which operation failed). I do usually end up using `fprintf()` with `strerror()` as you show (or, in GNU environments `fprintf()` with `%m`)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T09:49:22.020", "Id": "251853", "ParentId": "251798", "Score": "8" } }, { "body": "<p>In general your code looks reasonable, there is only one thing that you need to keep for your self for future devs. In general, your function initializeTape and the rest of the file tape.c</p>\n<pre><code>void initializeTape(Tape *tape) {\n tape-&gt;pointer = 0;\n tape-&gt;capacity = 8;\n tape-&gt;data = (unsigned short *) calloc( tape-&gt;capacity, sizeof(unsigned short));\n if (tape-&gt;data == NULL) {\n fprintf(stderr, &quot;Out of memory error.\\n&quot;);\n exit(1);\n }\n}\n</code></pre>\n<p>should check that the pointer tape is not null</p>\n<pre><code>void initializeTape(Tape *tape) {\n if (tape) {\n tape-&gt;pointer = 0;\n tape-&gt;capacity = 8;\n tape-&gt;data = (unsigned short *) calloc( tape-&gt;capacity, sizeof(unsigned short));\n if (tape-&gt;data == NULL) {\n fprintf(stderr, &quot;Out of memory error.\\n&quot;);\n exit(1);\n }\n } // else exit(-1) or whatever you choose\n}\n</code></pre>\n<p>This will remove potentially issues (invalid pointer) if you extend your code.</p>\n<p>Hope it helps</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T23:58:25.300", "Id": "496040", "Score": "2", "body": "It's normal for functions that take a pointer arg to require it to be non-NULL without checking for it, e.g. `fprintf` itself will just crash if you pass a NULL pointer for either of its first 2 args. There's nothing useful you can do in this function other than exit as a debug check. But dereferencing a NULL pointer will fairly reliably crash on most implementations, so just do that, and let people use a debugger to find where they're passing a NULL pointer from, if it ever happens." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T15:29:31.190", "Id": "251861", "ParentId": "251798", "Score": "2" } } ]
{ "AcceptedAnswerId": "251825", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T10:00:46.387", "Id": "251798", "Score": "25", "Tags": [ "c", "brainfuck" ], "Title": "A brainfuck interpreter in C" }
251798
<p><a href="https://github.com/dmitrynogin/instrumentation" rel="nofollow noreferrer">GitHub</a></p> <p>Here is a <code>Castle.Core</code> based service interface decorator providing automatic logging through the ambient logging context. Logging context should be constructed higher in the call stack:</p> <pre><code>using var log = new Log(log.Debug, log.Info, log.Warning, log.Error); </code></pre> <p>and used through the static API after:</p> <pre><code>Log.Info(&quot;Hello World&quot;); </code></pre> <p>One could define custom attributes to associate with all the log entries deeper in the call stack:</p> <pre><code>using var log = new Log(log.Debug, log.Info, log.Warning, log.Error); using var tag1 = new Tags((&quot;UserId&quot;, userId), (&quot;Reason&quot;, reason)); … using var tag2 = new Tags((&quot;TenantId&quot;, tenantId)); … Log.Info(&quot;Hello World&quot;); Log.Info(&quot;Hello Mr. Postman&quot;); </code></pre> <p>Library types look like this:</p> <pre><code>public class Log : IDisposable { static AsyncLocal&lt;Log&gt; Context { get; } = new AsyncLocal&lt;Log&gt;(); public Log( Action&lt;string, Dictionary&lt;string, object&gt;&gt; onDebug, Action&lt;string, Dictionary&lt;string, object&gt;&gt; onInfo, Action&lt;string, Dictionary&lt;string, object&gt;&gt; onWarning, Action&lt;string, Exception, Dictionary&lt;string, object&gt;&gt; onError) { Parent = Context.Value; Context.Value = this; OnDebug = onDebug; OnInfo = onInfo; OnWarning = onWarning; OnError = onError; } public virtual void Dispose() { Context.Value = Parent; } Log Parent { get; } Action&lt;string, Dictionary&lt;string, object&gt;&gt; OnDebug { get; } Action&lt;string, Dictionary&lt;string, object&gt;&gt; OnInfo { get; } Action&lt;string, Dictionary&lt;string, object&gt;&gt; OnWarning { get; } Action&lt;string, Exception, Dictionary&lt;string, object&gt;&gt; OnError { get; } public static void Debug(string text, params (string Name, object Value)[] tags) { using (new Tags(tags)) Context.Value?.OnDebug(text, Tags.ToDictionary()); } public static void Info(string text, params (string Name, object Value)[] tags) { using (new Tags(tags)) Context.Value?.OnInfo(text, Tags.ToDictionary()); } public static void Warning(string text, params (string Name, object Value)[] tags) { using (new Tags(tags)) Context.Value?.OnWarning(text, Tags.ToDictionary()); } public static void Error(string text, Exception ex, params (string Name, object Value)[] tags) { using (new Tags(tags)) Context.Value?.OnError(text, ex, Tags.ToDictionary()); } } </code></pre> <p>Where:</p> <pre><code>public class Tags : IDisposable { static AsyncLocal&lt;Tags&gt; Context { get; } = new AsyncLocal&lt;Tags&gt;(); public Tags(params string[] tags) : this() =&gt; List = tags; public Tags(params (string Name, object Value)[] tags) : this() =&gt; Dictionary = tags; Tags() { Parent = Context.Value; Context.Value = this; } public virtual void Dispose() { Context.Value = Parent; } Tags Parent { get; } IEnumerable&lt;string&gt; List { get; } = new string[0]; IEnumerable&lt;(string Name, object Value)&gt; Dictionary { get; } = new (string, object)[0]; public static Dictionary&lt;string, object&gt; ToDictionary() { return Context.Value == null ? new Dictionary&lt;string, object&gt;() : Merge(Context.Value) .ToDictionary(kvp =&gt; kvp.Item1, kvp =&gt; kvp.Item2); IEnumerable&lt;(string, object)&gt; Merge(Tags tags) =&gt; tags.Parent == null ? tags.Dictionary : Merge(tags.Parent) .Concat(tags.Dictionary) .Distinct(); } public static string[] ToArray() { return Context.Value == null ? new string[0] : Merge(Context.Value); string[] Merge(Tags tags) =&gt; tags.Parent == null ? tags.List.ToArray() : Merge(tags.Parent).Concat(tags.List).Distinct() .ToArray(); } } </code></pre> <p>We also have an <code>AsLoggable()</code> extension method, which allows to generate a logging proxy for something like this:</p> <pre><code>public interface IFoo { void Bar(); … } </code></pre> <p>Let’s setup and test:</p> <pre><code>[Test] public void Log_Success() { var sb = new StringBuilder(); using var log = new Log(sb.Debug, sb.Info, sb.Warning, sb.Error); var foo = new Mock&lt;IFoo&gt;(); foo .Setup(f =&gt; f.Bar()) .Verifiable(); var obj = foo.Object.AsLoggable(); obj.Bar(); foo .Verify(f =&gt; f.Bar(), Times.Once); Assert.IsTrue(Regex.IsMatch( sb.ToString(), @&quot;Debug: Instrumentation.IFoo.Bar started. Method=Instrumentation.IFoo.Bar&quot; + NewLine + @&quot;Debug: Instrumentation.IFoo.Bar succeeded. Method=Instrumentation.IFoo.Bar, Taken=\d+&quot;)); } </code></pre> <p>Where test logging helpers are:</p> <pre><code>static class Logging { public static void Debug(this StringBuilder sb, string e, Dictionary&lt;string, object&gt; p) =&gt; sb.AppendLine(&quot;Debug: &quot; + e + &quot;. &quot; + string.Join(&quot;, &quot;, from kvp in p select $&quot;{kvp.Key}={kvp.Value}&quot;)); public static void Info(this StringBuilder sb, string e, Dictionary&lt;string, object&gt; p) =&gt; sb.AppendLine(&quot;Info: &quot; + e + &quot;. &quot; + string.Join(&quot;, &quot;, from kvp in p select $&quot;{kvp.Key}={kvp.Value}&quot;)); public static void Warning(this StringBuilder sb, string e, Dictionary&lt;string, object&gt; p) =&gt; sb.AppendLine(&quot;Warning: &quot; + e + &quot;. &quot; + string.Join(&quot;, &quot;, from kvp in p select $&quot;{kvp.Key}={kvp.Value}&quot;)); public static void Error(this StringBuilder sb, string e, Exception ex, Dictionary&lt;string, object&gt; p) =&gt; sb.AppendLine(&quot;Error: &quot; + e + &quot;. &quot; + ex.Message + &quot; &quot; + string.Join(&quot;, &quot;, from kvp in p select $&quot;{kvp.Key}={kvp.Value}&quot;)); } </code></pre> <p><code>AsLoggable()</code> uses <code>Castle.Core</code>:</p> <pre><code>public static T AsLoggable&lt;T&gt;(this T obj) where T: class { var proxyGenerator = new ProxyGenerator(); return proxyGenerator .CreateInterfaceProxyWithTarget(obj, new Logger()); } </code></pre> <p>Where:</p> <pre><code>class Logger : AsyncInterceptorBase { protected override async Task InterceptAsync(IInvocation invocation, Func&lt;IInvocation, Task&gt; proceed) { var sw = Stopwatch.StartNew(); var method = $&quot;{invocation.Method.DeclaringType.FullName}.{invocation.Method.Name}&quot;; using (new Tags((&quot;Method&quot;, method))) try { Log.Debug($&quot;{method} started&quot;); try { await proceed(invocation).ConfigureAwait(false); } finally { sw.Stop(); } using (new Tags((&quot;Taken&quot;, sw.ElapsedMilliseconds))) { var e = $&quot;{method} succeeded&quot;; Log.Debug(e); Stat.Increment(e); Stat.Gauge(e, sw); } } catch (Exception ex) { using (new Tags((&quot;Taken&quot;, sw.ElapsedMilliseconds))) { var e = $&quot;{method} failed&quot;; Log.Error(e, ex); Stat.Increment(e); Stat.Gauge(e, sw); throw; } } } protected override async Task&lt;TResult&gt; InterceptAsync&lt;TResult&gt;(IInvocation invocation, Func&lt;IInvocation, Task&lt;TResult&gt;&gt; proceed) { TResult result = default; var sw = Stopwatch.StartNew(); var method = $&quot;{invocation.Method.DeclaringType.FullName}.{invocation.Method.Name}&quot;; using (new Tags((&quot;Method&quot;, method))) try { Log.Debug($&quot;{method} started&quot;); try { result = await proceed(invocation).ConfigureAwait(false); } finally { sw.Stop(); } using (new Tags((&quot;Taken&quot;, sw.ElapsedMilliseconds))) { var e = $&quot;{method} succeeded&quot;; Log.Debug(e); Stat.Increment(e); Stat.Gauge(e, sw); return result; } } catch (Exception ex) { using (new Tags((&quot;Taken&quot;, sw.ElapsedMilliseconds))) { var e = $&quot;{method} failed&quot;; Log.Error(e, ex); Stat.Increment(e); Stat.Gauge(e, sw); throw; } } } } </code></pre> <p>Now we can implement our service interfaces and register them in IoC as loggable.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T10:03:31.707", "Id": "251799", "Score": "3", "Tags": [ "c#", "proxy" ], "Title": "Automatic service logging" }
251799
<p>In the code, I am checking <code>altPhoneExist</code> and <code>altEmailExist</code> conditions multiple times. How can I avoid this and improve the performance and readability of the code?</p> <p><em><strong>Code Description:</strong></em></p> <p>A contact is created and added to a list if one of the conditions is true. And a different set operation executed for each one.</p> <pre><code>boolean altPhoneExist = contact.getAlternativePhoneNumber() != null; boolean altEmailExist = contact.getAlternativeEmail() != null; if (altPhoneExist || altEmailExist) { if (altPhoneExist) { contact.setPhoneNumber(contact.getAlternativePhoneNumber()); } if (altEmailExist) { contact.setEmail(contact.getAlternativeEmail()); } rqType.getContactInfoList().add(CraneFactory.createContactPerson(contact)); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T13:08:42.647", "Id": "495920", "Score": "3", "body": "Make your question more clear please. Read [this](https://codereview.stackexchange.com/help/how-to-ask) first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T13:31:03.757", "Id": "495923", "Score": "2", "body": "Welcome to the Code Review site, this site is quite different from Stack Overflow. The goal of this site is to help you improve your coding abilities and we generally don't answer how to questions. To provide a good review we need to see more of the code, not less. We need at least complete functions and preferably complete classes or programs. As pointed out by @ZoranJankov please read the help center on how to ask a good question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T16:35:34.687", "Id": "495940", "Score": "2", "body": "This question lacks a lot of details. Moreover, it's too hypothetical" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T18:11:33.227", "Id": "495951", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T19:44:47.680", "Id": "495955", "Score": "0", "body": "The code given in the question is working and I want to improve its readability and performance by removing unnecessary conditional checks. It is a very simple question. Two people understood it and answered. I do not think it has missing points." } ]
[ { "body": "<p>In my opinion, there are not other good ways that I see to avoid this kind of logic; you can attenuate the <a href=\"https://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow noreferrer\">arrow code</a> by inverting the first condition and returning early.</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (!altPhoneExist &amp;&amp; !altEmailExist) {\n return;\n}\n\n// Here we know it's either one of them\n\n\nif (altPhoneExist) {\n contact.setPhoneNumber(contact.getAlternativePhoneNumber());\n}\n\nif (altEmailExist) {\n contact.setEmail(contact.getAlternativeEmail());\n}\n\nrqType.getContactInfoList().add(CraneFactory.createContactPerson(contact));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T12:50:28.270", "Id": "251809", "ParentId": "251803", "Score": "4" } }, { "body": "<p>An alternative is to use a flag without creating the temporary variables <code>altPhoneExist</code> and <code>altPhoneExist</code>:</p>\n<pre><code>boolean updated = false;\nif(contact.getAlternativePhoneNumber() != null) {\n contact.setPhoneNumber(contact.getAlternativePhoneNumber());\n updated = true;\n}\nif(contact.getAlternativeEmail() != null) {\n contact.setEmail(contact.getAlternativeEmail());\n updated = true;\n}\nif (updated) {\n rqType.getContactInfoList().add(CraneFactory.createContactPerson(contact));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T13:24:03.170", "Id": "251811", "ParentId": "251803", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T11:16:45.497", "Id": "251803", "Score": "2", "Tags": [ "java" ], "Title": "How to Avoid Conditional Check Duplication" }
251803
<h3>Conway's Game of Life</h3> <p>Conway's Game of Life is a mathematical game invented by English Mathematician John Horton Conway. The game is based on the theory of cellular automatons. It is a so-called zero-player game because once the &quot;player&quot; set the initial state of the automaton, the game is just about to watch the deterministic outcome of the game.</p> <p>The rules are as follows:</p> <ol> <li>Living cells with 2 or 3 neighbors stay alive.</li> <li>Living cells with less than two or more than 3 neighbors die.</li> <li>Dead cells with exactly 3 neighbors are &quot;re-born&quot;</li> </ol> <p>For more information, please see the great article on <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="nofollow noreferrer">wikipedia</a>.</p> <h3>My implementation</h3> <p>I've used pure JavaScript and a bit of JQuery to implement the Game of Life.</p> <h3>The code</h3> <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>let WIDTH = 800; let HEIGHT = 500; const RES = 10; const DEAD_CELL = 0; const LIVING_CELL = 1; const BORDER = 2; let grid; let isRunning = false; let interval; let generation = 0; window.addEventListener('load', function() { if(window.innerWidth &lt; 840) { WIDTH = window.innerWidth - 100; WIDTH = WIDTH - WIDTH % 100; HEIGHT = window.innerHeight - 40; HEIGHT = HEIGHT - HEIGHT % 100; } document.getElementById('canvas').height = HEIGHT; document.getElementById('canvas').width = WIDTH; generation = 0; updateGeneration(); initialDraw(); }); window.addEventListener('resize', function() { if(window.innerWidth &lt; 840) { WIDTH = window.innerWidth - 100; WIDTH = WIDTH - WIDTH % 100; HEIGHT = window.innerHeight - 40; HEIGHT = HEIGHT - HEIGHT % 100; } else { HEIGHT = 500; WIDTH = 800; } document.getElementById('canvas').height = HEIGHT; document.getElementById('canvas').width = WIDTH; generation = 0; updateGeneration(); initialDraw(); if(isRunning) { clearInterval(interval); isRunning = false; document.getElementById('startStop').textContent = 'Start'; switchButtons(); } }); /** * Allows the user to draw own pattern on the canvas */ document.getElementById('canvas').addEventListener('click', function(e) { // Which box did user click on? const row = Math.floor(e.offsetX / RES); const col = Math.floor(e.offsetY / RES); // Don't allow changes while simulation is running if (isRunning) { return; } // Case user clicked on a dead cell if (grid[row][col] === DEAD_CELL) { // Generation needs to be resetted generation = 0; updateGeneration(); grid[row][col] = LIVING_CELL; drawCell('#2B823A', 'LightGray', 1, row * RES, col * RES, RES, RES); } else if (grid[row][col] === LIVING_CELL) { // Generation needs to be resetted generation = 0; updateGeneration(); grid[row][col] = DEAD_CELL; drawCell('white', 'LightGray', 1, row * RES, col * RES, RES, RES); } }); /** * Starts / Stops the simulation and enables / disables the other buttons */ document.getElementById('startStop').addEventListener('click', function() { // Case user wants to start simulation if (!isRunning) { interval = setInterval(function() { const cols = WIDTH / RES; const rows = HEIGHT / RES; draw(cols, rows); // Count generation and show user updateGeneration(); generation++; }, (1 / document.getElementById('speed').value) * 1000); isRunning = true; document.getElementById('startStop').textContent = 'Stop'; switchButtons(); } else { clearInterval(interval); isRunning = false; document.getElementById('startStop').textContent = 'Start'; switchButtons(); } }); /** * Deletes pattern from canvas */ document.getElementById('clear').addEventListener('click', function() { if (!isRunning) { // Generation needs to be resetted generation = 0; updateGeneration(); createGrid(WIDTH / RES, HEIGHT / RES); draw(WIDTH / RES, HEIGHT / RES); } }); /** * Changes the speed of the simulation: The higher the value, * the faster the simulation */ document.getElementById('speed').addEventListener('change', function() { if (isRunning) { clearInterval(interval); interval = setInterval(function() { const cols = WIDTH / RES; const rows = HEIGHT / RES; draw(cols, rows); // Count generation and show user updateGeneration(); generation++; }, (1 / document.getElementById('speed').value) * 1000); } }); /** * Random pattern on the canvas */ document.getElementById('random').addEventListener('click', function() { // Case user wants to start simulation if (!isRunning) { // Generation needs to be resetted generation = 0; updateGeneration(); const cols = WIDTH / RES; const rows = HEIGHT / RES; grid = createArray(cols, rows); createRandom(cols, rows); draw(cols, rows); } }); /** * Creates a Lightweight spaceship * https://www.conwaylife.com/wiki/Lightweight_spaceship */ document.getElementById('lwss').addEventListener('click', function() { // Case user wants to start simulation if (!isRunning) { // Generation needs to be resetted generation = 0; updateGeneration(); const cols = WIDTH / RES; const rows = HEIGHT / RES; createGrid(cols, rows); const x = Math.floor(cols / 2); const y = Math.floor(rows / 2); createLwss(x, y); draw(cols, rows); } }); /** * Creates a r-pentomino * https://www.conwaylife.com/wiki/R-pentomino */ document.getElementById('r-pentomino').addEventListener('click', function() { // Case user wants to start simulation if (!isRunning) { // Generation needs to be resetted generation = 0; updateGeneration(); const cols = WIDTH / RES; const rows = HEIGHT / RES; createGrid(cols, rows); const x = Math.floor(cols / 2); const y = Math.floor(rows / 2); createRPentomino(x, y); draw(cols, rows); } }); /** * Create an acorn * https://www.conwaylife.com/wiki/Acorn */ document.getElementById('acorn').addEventListener('click', function() { // Case user wants to start simulation if (!isRunning) { // Generation needs to be resetted generation = 0; updateGeneration(); const cols = WIDTH / RES; const rows = HEIGHT / RES; createGrid(cols, rows); const x = Math.floor(cols / 2); const y = Math.floor(rows / 2); createAcorn(x, y); draw(cols, rows); } }); /** * Creates a gosper glider gun * https://www.conwaylife.com/wiki/Gosper_glider_gun */ document.getElementById('gosper').addEventListener('click', function() { // Case user wants to start simulation if (!isRunning) { // Generation needs to be resetted generation = 0; updateGeneration(); const cols = WIDTH / RES; const rows = HEIGHT / RES; createGrid(cols, rows); const x = Math.floor(cols / 2); const y = Math.floor(rows / 2); createGosperGliderGun(x, y); draw(cols, rows); } }); /** * Draws the initial state of the canvas */ function initialDraw() { const cols = WIDTH / RES; const rows = HEIGHT / RES; grid = createArray(cols, rows); // Field edge is getting filled up with "2" for (let i = 0; i &lt; cols; i++) { for (let j = 0; j &lt; rows; j++) { grid[i][j] = BORDER; } } // Field gets filled up with "0" = dead cells for (let i = 1; i &lt; cols - 1; i++) { for (let j = 1; j &lt; rows - 1; j++) { grid[i][j] = DEAD_CELL; } } draw(cols, rows); } /** * Draws the canvas * * @param {int} cols Number of columns * @param {int} rows Number of rows */ function draw(cols, rows) { // Draw for (let i = 0; i &lt; cols; i++) { for (let j = 0; j &lt; rows; j++) { const x = i * RES; const y = j * RES; if (grid[i][j] === DEAD_CELL) { // Dead cells are white drawCell('white', 'LightGray', 1, x, y, RES, RES); } else if (grid[i][j] === LIVING_CELL) { // Living cells are #2B823A (green) drawCell('#2B823A', 'LightGray', 1, x, y, RES, RES); } else { // Border cells are #00410B (red) drawCell('#00410B', 'LightGray', 1, x, y, RES, RES); } } } // Updates grid with values of next generation applyRules(cols, rows); } /** * Draws one cell of the canvas * * @param {string} fillStyle Color of the cell * @param {string} strokeStyle Color of the border of the cell * @param {int} lineWidth linewidth of the border * @param {int} x x-coordinate of upper-left corner * @param {int} y y-coordinate * @param {int} width width of cell * @param {int} height height of cell */ function drawCell(fillStyle, strokeStyle, lineWidth, x, y, width, height) { const ctx = document.getElementById('canvas').getContext('2d'); ctx.fillStyle = fillStyle; ctx.strokeStyle = strokeStyle; ctx.lineWidth = lineWidth; ctx.beginPath(); // Draw border of color strokeStyle ctx.rect(x, y, width, height); // Fill cell with color fillStyle ctx.fill(); ctx.stroke(); } /** * Updates the grid with the next generation: * Living cells with 2 or 3 neighbors stay alive. * Living cells with less than two or more than 3 neighbors die. * Dead cells with exactly 3 neighbors are "re-born" * * @param {int} cols Number of columns * @param {int} rows Number of rows */ function applyRules(cols, rows) { // Temporary array to save new values (next generation) const newArray = createArray(cols, rows); for (let i = 1; i &lt; cols - 1; i++) { for (let j = 1; j &lt; rows - 1; j++) { // how many living cells does the current cell (grid[i][j]) have const neighbors = countNeighbors(i, j); if (grid[i][j] == LIVING_CELL) { // Living cells with less than two or more than 3 neighbors die if ((neighbors &lt; 2) || (neighbors &gt; 3)) { newArray[i][j] = DEAD_CELL; } // Living cells with 2 or 3 neighbors stay alive if ((neighbors == 2) || (neighbors == 3)) { newArray[i][j] = LIVING_CELL; } } else if (grid[i][j] == DEAD_CELL) { // Dead cells with exactly 3 neighbors are "re-born" if (neighbors == 3) { newArray[i][j] = LIVING_CELL; } else { newArray[i][j] = DEAD_CELL; } } } } // Save temporary variables in grid so that grid now represents // the next generation for (let i = 1; i &lt; cols - 1; i++) { for (let j = 1; j &lt; rows - 1; j++) { grid[i][j] = newArray[i][j]; } } } /** * Counts the neighbors of cell in grid at * position (x,y) * * @param {int} x x-coordinate of cell * @param {int} y y-coordinate of cell * * @return {int} neighbors Number of neighbors */ function countNeighbors(x, y) { let neighbors = 0; /* 001 0X1 101 -&gt; X has four neighbors */ for (let i = x - 1; i &lt;= x + 1; i++) { for (let j = y - 1; j &lt;= y + 1; j++) { if (grid[i][j] == LIVING_CELL) { neighbors = neighbors + 1; } } } // Cell is not neighbor of itself if (grid[x][y] == LIVING_CELL) { neighbors = neighbors - 1; } return neighbors; } /** * Creates an empty 2d-array * * @param {int} cols Number of columns * @param {int} rows Number of rows * * @return {Obj} array newly created array */ function createArray(cols, rows) { const array = new Array(cols); for (let i = 0; i &lt; cols; i++) { array[i] = new Array(rows); } return array; } /** * Creates a grid with initial state * * @param {int} cols Number of columns * @param {int} rows Number of rows */ function createGrid(cols, rows) { grid = createArray(cols, rows); // Field edge is getting filled up with "2" for (let i = 0; i &lt; cols; i++) { for (let j = 0; j &lt; rows; j++) { grid[i][j] = BORDER; } } // Field gets filled up with "0" = dead cells for (let i = 1; i &lt; cols - 1; i++) { for (let j = 1; j &lt; rows - 1; j++) { grid[i][j] = DEAD_CELL; } } } /** * Updates the generation-counter */ function updateGeneration() { $(document).ready(function() { $('#generation').text(generation); }); } /** * Filling grid with random numbers (0 or 1) * * @param {int} cols Number of columns * @param {int} rows Number of rows */ function createRandom(cols, rows) { for (let i = 1; i &lt; cols - 1; i++) { for (let j = 1; j &lt; rows - 1; j++) { grid[i][j] = (Math.random() * 2 | 0); } } } /** * Enables buttons when user stops simulation, * disables buttons when user starts simulation */ function switchButtons() { document.getElementById('clear').disabled = isRunning; document.getElementById('random').disabled = isRunning; document.getElementById('lwss').disabled = isRunning; document.getElementById('r-pentomino').disabled = isRunning; document.getElementById('acorn').disabled = isRunning; document.getElementById('gosper').disabled = isRunning; } /** * Helper function to create a * lightweight spaceship * * @param {int} x x-coordinate of cell in the middle of grid * @param {int} y y-coordinate of cell in the middle of grid */ function createLwss(x, y) { const arr = [[0, 1], [-1, 1], [1, 1], [-2, 1], [-2, 0], [2, 0], [-2, -1], [-1, -2], [2, -2]]; createPattern(arr, x, y); } /** * Helper function to create a * r-pentomino * * @param {int} x x-coordinate of cell in the middle of grid * @param {int} y y-coordinate of cell in the middle of grid */ function createRPentomino(x, y) { const arr = [[0, 0], [0, -1], [0, 1], [-1, 0], [1, -1]]; createPattern(arr, x, y); } /** * Helper function to create a * acorn * * @param {int} x x-coordinate of cell in the middle of grid * @param {int} y y-coordinate of cell in the middle of grid */ function createAcorn(x, y) { const arr = [[1, 0], [2, 0], [3, 0], [-2, 0], [-3, 0], [0, -1], [-2, -2]]; createPattern(arr, x, y); } /** * Helper function to create a * gosper glider gun * * @param {int} x x-coordinate of cell in the middle of grid * @param {int} y y-coordinate of cell in the middle of grid */ function createGosperGliderGun(x, y) { const arr = [[-13, 0], [-12, 0], [-3, 0], [1, 0], [3, 0], [4, 0], [9, 0], [11, 0], [-3, 1], [3, 1], [11, 1], [-2, 2], [2, 2], [-1, 3], [0, 3], [-13, -1], [-12, -1], [-3, -1], [3, -1], [7, -1], [8, -1], [-2, -2], [2, -2], [7, -2], [8, -2], [-1, -3], [0, -3], [7, -3], [8, -3], [21, -2], [22, -2], [9, -4], [11, -4], [21, -3], [22, -3], [11, -5]]; createPattern(arr, x, y); } /** * Helper function to write pattern saved in * arr to grid * * @param {Obj} arr array of coordinates of cells to fill with 1 * @param {int} x x-coordinate of cell in the middle of grid * @param {int} y y-coordinate of cell in the middle of grid */ function createPattern(arr, x, y) { for (let i = 0; i &lt; arr.length; i++) { grid[x + arr[i][0]][y + arr[i][1]] = 1; } }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>/* ========================================================================= Main style ========================================================================= */ /* color palette */ :root { --active: #00410b; --light: #2b823a; --lighter: #82c38d; } html, body { padding: 0; font-family: "Open Sans", sans-serif; } /* Content in middle of page */ .inner { width: 840px; margin: 0 auto; padding: 0; position: relative; } /* main content not as wide as inner-div */ .content { padding-left: 20px; padding-right: 20px; padding-bottom: 100px; } /* ========================================================================= footer ========================================================================= */ .footer { text-align: center; width: 840px; } hr { color: var(--active); } /* ========================================================================= number input ========================================================================= */ label { display: block; } input[type="number"] { width: 18%; padding: 10px 10px; display: block; border: 1px solid black; border-radius: 5px; box-sizing: border-box; margin-bottom: 10px; margin-right: 12px; } .tooltip { display: inline-block; position: relative; margin-bottom: 10px; } .tooltip:hover::before { content: attr(tooltip-title); position: absolute; width: 250px; background: var(--active); color: white; padding: 10px; border-radius: 5px; box-sizing: border-box; bottom: 20px; left: 20px; opacity: 0.9; } /* ========================================================================= Other ========================================================================= */ canvas { border: 1px solid LightGray; border-radius: 5px; box-sizing: border-box; } button { width: 18%; padding: 10px 10px; display: inline; border: 1px solid black; border-radius: 5px; box-sizing: border-box; margin-bottom: 10px; margin-right: 12px; } h1, h2, h3, h4, h5, h6 { color: var(--active); font-family: "Baloo 2", sans-serif; } a.link { display: inline-block; margin: 0; color: var(--light); text-decoration: none; } a.link::after { display: block; content: ""; width: 0; border-bottom: 2px solid var(--light); transition: width 200ms; } a.link:hover::after { width: 100%; } /* ========================================================================= responsive ========================================================================= */ @media (max-width: 840px) { .inner { min-height: 100%; width: 100%; margin: 0 auto; padding: 0; position: relative; } .footer { text-align: center; width: 100%; } .pattern { width: 100%; padding: 10px 10px; display: inline; border: 1px solid black; border-radius: 5px; box-sizing: border-box; float: left; margin-bottom: 10px; } button { width: 50%; } canvas { height: calc(((100% - 100px) / 100) * 100); width: calc(((100% - 40px) / 100) * 100); } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div class="inner"&gt; &lt;div class="content"&gt; &lt;h1&gt;Conway's Game Of Life&lt;/h1&gt; &lt;canvas id="canvas" width="800" height="500"&gt;&lt;/canvas&gt; &lt;h3&gt;Information&lt;/h3&gt; &lt;p&gt;Generation: &lt;span id="generation"&gt;&lt;/span&gt;&lt;/p&gt; &lt;h3&gt;Control&lt;/h3&gt; &lt;button id="startStop"&gt;Start&lt;/button&gt; &lt;button id="clear"&gt;Clear&lt;/button&gt; &lt;label&gt; &lt;span class="tooltip" tooltip-title="The higher the number, the faster the simulation" style="border-bottom: 1px dotted black"&gt;Speed:&lt;/span&gt; &lt;input id="speed" type="number" min=1 max=20 value="5" onkeydown="return false;"&gt; &lt;/label&gt; &lt;h3&gt;Pattern&lt;/h3&gt; &lt;button id="random"&gt;Random&lt;/button&gt; &lt;button id="lwss"&gt;LWSS&lt;/button&gt; &lt;button id="r-pentomino"&gt;R-pentomino&lt;/button&gt; &lt;button id="acorn"&gt;Acorn&lt;/button&gt; &lt;button id="gosper"&gt;Gosper glider gun&lt;/button&gt; &lt;h3&gt;What is this?&lt;/h3&gt; &lt;p&gt;Conway's Game of Life is a mathematical game invented by English Mathematician John Horton Conway. The game is based on the theory of cellular automatons. It is a so-called zero-player game because once the "player" set the initial state of the automaton, the game is just about to watch the deterministic outcome of the game.&lt;/p&gt; &lt;p&gt;The rules are as follows:&lt;/p&gt; &lt;ol&gt; &lt;li&gt;Living cells with 2 or 3 neighbors stay alive.&lt;/li&gt; &lt;li&gt;Living cells with less than two or more than 3 neighbors die.&lt;/li&gt; &lt;li&gt;Dead cells with exactly 3 neighbors are "re-born"&lt;/li&gt; &lt;/ol&gt; &lt;p&gt;In this implementation, the living cells are green and the dead cells are white.&lt;/p&gt; &lt;p&gt;If you want to learn more about the Game of Life, reading the following articles will help:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;a class="link" href="https://en.wikipedia.org/wiki/Conway's_Game_of_Life"&gt;Conway's Game of Life&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="link" href="https://en.wikipedia.org/wiki/Cellular_automaton"&gt;Cellular automaton&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="link" href="https://en.wikipedia.org/wiki/John_Horton_Conway"&gt;John Conway&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;footer&gt; &lt;hr&gt; &lt;div class="footer"&gt; footer-text &lt;/div&gt; &lt;/footer&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <h3>Question</h3> <p>All suggestions are welcome.</p>
[]
[ { "body": "<p>I really like the <code>DEAD_CELL</code> and <code>LIVING_CELL</code> variables, they're a great approach to distinguishing cells without using just numbers. Here are some suggestions for the JavaScript:</p>\n<p><strong>Use modules for large scripts</strong> While writing everything in a single <code>.js</code> file can work fine in smaller scripts, when it gets to be more than a couple hundred lines long, it can start to get more difficult to manage than is ideal. For example, let's say you realize that cells aren't growing and dying as is intended. Currently, to debug it, unless you've memorized the function name, you'd probably scroll through the (long) code until you found a section that looks related, then examine it to see if it's really what you were looking for. That's not a very scalable approach.</p>\n<p>It would be better if you could do something like go into a <code>grid</code> folder, inside which you can see different files containing functions related to the grid, and then you could browse it and go to the <em>one file</em> that's causing the issue, <code>applyRules.js</code>, and fix it up. Modules make large scripts a whole lot easier to write, maintain, and debug. Other benefits include explicit dependencies and very narrow scope (narrow scope helps <a href=\"https://softwareengineering.stackexchange.com/a/388055\">a whole lot</a>).</p>\n<p>Use something like Webpack to coalesce all the separate <code>.js</code> files into a single one to serve on your HTML. Using a build process like this will also help you in other ways:</p>\n<ul>\n<li>Easy, automatic transpilation: you'll be able to write in as modern syntax as you want, and <em>automatically</em> transpile your code down to ES5 for production (allowing older browsers to understand your code, while keeping your source code modern and concise)</li>\n<li>Easy, automatic minification - <a href=\"https://en.wikipedia.org/wiki/Minification_(programming)\" rel=\"nofollow noreferrer\">A bit similar to above</a>, reduces network payloads</li>\n</ul>\n<p><strong>Declare variables close to where they'll be used</strong> The thought process of someone reading the following might get somewhat disjointed - you make a <code>row</code> and <code>col</code> variable, and then return and don't use them if a condition is met.</p>\n<pre><code>document.getElementById('canvas').addEventListener('click', function(e) {\n // Which box did user click on?\n const row = Math.floor(e.offsetX / RES);\n const col = Math.floor(e.offsetY / RES);\n\n // Don't allow changes while simulation is running\n if (isRunning) {\n return;\n }\n\n // Case user clicked on a dead cell\n if (grid[row][col] === DEAD_CELL) {\n</code></pre>\n<p>Consider returning as soon as possible instead, and only declaring the variables when you're going to use them in code below. Also consider renaming <code>row</code> and <code>col</code> to <code>clickedRow</code> and <code>clickedCol</code> for precision. This makes the code more self-documenting, and will mean that you can remove some of the comments:</p>\n<pre><code>document.getElementById('canvas').addEventListener('click', function(e) {\n // Don't allow changes while simulation is running\n if (isRunning) {\n return;\n }\n\n const clickedRow = Math.floor(e.offsetX / RES);\n const clickedCol = Math.floor(e.offsetY / RES);\n\n if (grid[clickedRow][clickedCol] === DEAD_CELL) {\n</code></pre>\n<p><strong>IDs</strong> You have a number of elements with IDs on the page. Unfortunately, such IDs <a href=\"https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables\">become global variables</a>. This has the potential to cause bugs due to variable name collisions. For example, you have <code>speed</code> and <code>random</code> IDs. What if, elsewhere, you tried to use a variable named <code>speed</code> or <code>random</code>, and/or accidentally refer to the standalone variables without doing <code>querySelector</code> or <code>getElementById</code> first? Then there could be problems that would have to be fixed (and could well be quite confusing).</p>\n<p>While you could reduce the chance of collisions by changing the IDs to be less likely to be referred to accidentally (and by using a linter to warn you against the use of undefined variables), I’d personally prefer to avoid IDs entirely - either use classes instead to select elements:</p>\n<pre><code>&lt;button class=&quot;clear&quot;&gt;Clear&lt;/button&gt;\n</code></pre>\n<pre><code>const clearButton = document.querySelector('.clear');\n</code></pre>\n<p>Or use a framework like React so that the elements are created at the same time as their handlers - that way, no elements have to be selected from the DOM at all. Just an idea - it makes the management of more complicated interfaces a bit easier.</p>\n<p><strong><code>generation</code></strong> The meaning of this variable wasn’t entirely clear to me until I saw how it was being used. Consider naming it something more precise like <code>generationCount</code>, or <code>generationCountSinceLastChange</code>.</p>\n<p><strong><code>updateGeneration</code></strong>: Throughout the code, you're frequently incrementing or setting to 0 the <code>generation</code> variable, and then calling <code>updateGeneration</code>, which does:</p>\n<pre><code>function updateGeneration() {\n $(document).ready(function() {\n $('#generation').text(generation);\n });\n}\n</code></pre>\n<p>Consider passing <code>updateGeneration</code> the new generation count instead:</p>\n<pre><code>function updateGeneration(newCount) {\n generationCountSinceLastChange = newCount;\n document.querySelector('#generation').textContent = newCount;\n}\n</code></pre>\n<p>This lets you do <code>updateGeneration(generationCountSinceLastChange + 1)</code> or <code>updateGeneration(0)</code>.</p>\n<p>(This is the only place you're using jQuery. Feel free to remove it entirely - it isn't accomplishing anything useful. The document is already going to be loaded by the time this runs.)</p>\n<p><strong>Waiting for the window to load</strong> Rather than wrapping the entry point in a <code>load</code> listener, you may consider either giving the <code>&lt;script&gt;</code> tag the <code>defer</code> attribute or putting it at the bottom of the <code>&lt;body&gt;</code> - I think it's a bit easier to direct it from the HTML, rather than from the JS.</p>\n<p><strong>initialDraw</strong> Best to name functions based on <em>what they do</em>, rather than when they're called. This function looks to draws the border, so maybe call it <code>drawBorder</code>.</p>\n<p><strong>Avoid sloppy comparison</strong> with <code>==</code> and <code>!=</code>, they have <a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\">strange coercion rules</a>. Better to always use <code>===</code> and <code>!==</code>. Consider using ESLint and the rule <a href=\"https://eslint.org/docs/rules/eqeqeq\" rel=\"nofollow noreferrer\"><code>eqeqeq</code></a>.</p>\n<h3>DRYing</h3>\n<p>There are many places in the current code that are pretty repetitive.</p>\n<p><strong>On canvas click</strong>, rather than <code>if</code> <code>else</code>s, you can use the conditional operator and call <code>updateGeneration</code> at once:</p>\n<pre><code>updateGeneration(0);\nconst setAlive = grid[row][col] === DEAD_CELL;\ngrid[row][col] = setAlive ? LIVING_CELL : DEAD_CELL;\ndrawCell(setAlive ? 'white' : '2B823A', 'LightGray', 1, row * RES, col * RES, RES, RES);\n</code></pre>\n<p><strong>createGrid</strong> Rather than calculating and passing <code>createGrid</code> the global constants every single time it's called:</p>\n<pre><code>const cols = WIDTH / RES;\nconst rows = HEIGHT / RES;\ncreateGrid(cols, rows);\n</code></pre>\n<p>Consider having <code>createGrid</code> itself calculate the grid dimensions needed:</p>\n<pre><code>function createGrid() {\n const cols = WIDTH / RES;\n const rows = HEIGHT / RES;\n</code></pre>\n<p>You can do the same sort of thing for the <code>draw</code> function. (If the arguments to a function are always the same, that's an indication that it's something that should be handled <em>inside</em> the function, not something that gets passed to the function.)</p>\n<p><strong>applyRules</strong> can be refactored to avoid redundant checks. For example, given <code>if ((neighbors &lt; 2) || (neighbors &gt; 3)) {</code>, rather than testing against 2 and 3 for the other branch, you can use <code>else</code>. Or, even better, use the conditional operator.</p>\n<pre><code>for (let i = 1; i &lt; cols - 1; i++) {\n for (let j = 1; j &lt; rows - 1; j++) {\n const neighborCount = countNeighbors(i, j);\n if (grid[i][j] === LIVING_CELL) {\n // Living cells with less than two or more than 3 neighbors die\n newArray[i][j] = (neighborCount &lt; 2 || neighborCount &gt; 3) ? DEAD_CELL : LIVING_CELL;\n } else {\n // Dead cells with exactly 3 neighbors are &quot;re-born&quot;\n newArray[i][j] = neighborCount === 3 ? LIVING_CELL : DEAD_CELL;\n }\n }\n}\n</code></pre>\n<p><strong>Concise shape insertion</strong> When you have lots of shapes that can be inserted, having separate functions for each of them gets a bit repetitive. Consider making an object indexed by shape name instead, eg:</p>\n<pre><code>const patterns = {\n lwss: [[0, 1], [-1, 1], [1, 1], [-2, 1], [-2, 0],\n [2, 0], [-2, -1], [-1, -2], [2, -2]]\n // ...\n};\n</code></pre>\n<p>Then, rather than <code>createLwss</code> and all the other separate functions, you can do:</p>\n<pre><code>createPattern(patterns.lwss, x, y);\n</code></pre>\n<p><strong>Avoid <code>new Array</code></strong>, since it creates sparse arrays (which are only guaranteed to have a <code>length</code> property, but may or may not have own-properties from 0 up to the length) - if you forget to assign to every index of the array, iteration over it can be very weird. Consider using <code>Array.from</code> instead, or using <code>.fill</code> after calling <code>new Array</code>.</p>\n<pre><code>function createArray(cols: number, rows: number) {\n return Array.from(\n { length: cols },\n () =&gt; new Array(rows).fill(null)\n );\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T11:48:44.083", "Id": "495991", "Score": "0", "body": "Thank you for your answer. In your last snippet, the line `() =>` does give me the error \"Argument type function(): this is not assignable to parameter type (v: unknown, k: number)\". Do you know what the problem is here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T14:39:57.287", "Id": "496009", "Score": "1", "body": "Forgot to type the arguments - they're numbers, so use `:number` and it should work." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T21:00:39.597", "Id": "251833", "ParentId": "251814", "Score": "5" } } ]
{ "AcceptedAnswerId": "251833", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T13:57:06.323", "Id": "251814", "Score": "5", "Tags": [ "javascript", "html", "css" ], "Title": "Conway's Game of Life - Javascript" }
251814
<p>I'm playing around with the concept of functional programming.</p> <p>I have flattened the nested if statements and made by code more verbose.</p> <p>The refactored code looks overly complicated.</p> <p>What could be a simpler approach?</p> <h2>Nested Ifs</h2> <pre class="lang-cs prettyprint-override"><code>public static int Main(string[] args) { int computer = 1; string brand = &quot;PC&quot;; if (computer &lt; 2) { if (brand != &quot;Apple&quot;) { // perform complex calculation 1 Console.WriteLine(&quot;you don't own a Mac&quot;); return 0; } else { // perform complex calculation 2 Console.WriteLine(&quot;you own less than 2 Macs&quot;); return 1; } } else { // perform complex calculation 3 Console.WriteLine(&quot;you own two or pcs&quot;); return 2; } } </code></pre> <h2>Flattened Main</h2> <pre class="lang-cs prettyprint-override"><code>public static int Main(string[] args) { int computer = 1; string brand = &quot;PC&quot;; return CalculatedResult = DetermineComputer(computer, brand); } </code></pre> <h2>Extension Methods</h2> <pre class="lang-cs prettyprint-override"><code>public static class extensions { public static int ComplexCalc1(this bool val) { Console.WriteLine(&quot;you don't own a Mac&quot;); return 0; } public static int ComplexCalc2(this bool val) { Console.WriteLine(&quot;you own less than 2 Macs&quot;); return 1; } public static int ComplexCalc3(this bool val) { Console.WriteLine(&quot;you own greater than two pcs&quot;); return 2; } public static int ComplexCalc4(this bool val) { Console.WriteLine(&quot;Condition not accounted for&quot;); return -1; } public static bool IsLessThanTwo(int computer) =&gt; computer &lt; 2; public static bool IsApple(string brand) =&gt; brand == &quot;Apple&quot;; public static (Func&lt;bool, int&gt; func, bool result) IsLessThanTwoAndNotApple(this int computer, string brand) =&gt; (ComplexCalc1, IsLessThanTwo(computer) &amp;&amp; (IsApple(brand) == false)); public static (Func&lt;bool, int&gt; func, bool result) IsLessThanTwoAndIsApple(this int computer, string brand) =&gt; (ComplexCalc2, IsLessThanTwo(computer) &amp;&amp; IsApple(brand)); public static (Func&lt;bool, int&gt; func, bool result) Unaccountedfor(this int computer, string brand) =&gt; (ComplexCalc4, true); public static (Func&lt;bool, int&gt; func, bool result) IsGreaterThanTwoAndIsNotApple(this int computer, string brand) =&gt; (ComplexCalc3, (IsLessThanTwo(computer) == false) &amp;&amp; (IsApple(brand) == false)); } </code></pre> <h2>Calculation</h2> <pre class="lang-cs prettyprint-override"><code>public static int DetermineComputer(int computer, string brand) { var methodlist = new List&lt;(Func&lt;bool, int&gt;, bool)&gt; { computer.IsLessThanTwoAndNotApple(brand), computer.IsLessThanTwoAndIsApple(brand), computer.IsGreaterThanTwoAndIsNotApple(brand), computer.Unaccountedfor(brand) }; var tupleResult = methodlist.Where(x =&gt; x.Item2 == true).Select(x =&gt; new { functor = x.Item1, result = x.Item2 }).First(); return tupleResult.functor(tupleResult.result); } </code></pre> <h2>Unit Tests</h2> <pre class="lang-cs prettyprint-override"><code>[DataRow(3, &quot;Apple&quot;, -1)] [DataRow(2, &quot;Apple&quot;, -1)] [DataRow(1, &quot;Apple&quot;, 1)] [DataRow(0, &quot;Apple&quot;, 1)] [DataRow(3, &quot;PC&quot;, 2)] [DataRow(2, &quot;PC&quot;, 2)] [DataRow(1, &quot;PC&quot;, 0)] [DataRow(0, &quot;PC&quot;, 0)] [DataTestMethod] public void NestedIfs_Demo(int first, string second, int expected) { int computer = first; string brand = second; var CalculatedResult = DetermineComputer(computer, brand); Assert.AreEqual(expected, CalculatedResult); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T18:10:28.897", "Id": "495950", "Score": "2", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T10:42:39.587", "Id": "496065", "Score": "0", "body": "(@PeterCsala: The formatting of the code presented is one aspect to review: please don't change it (beyond fixing \"markdown mistakes\"). While I think the (small) rest of your suggested edit useful, it seems to lack substance. The \"edit pitch\" gives `Because community members review edit` as a reason, which won't apply once you surpassed 2k rep.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T10:57:37.437", "Id": "496066", "Score": "0", "body": "@greybeard It was approved by the OP. But if you think adding and removing white spaces aren't appropriate then I'm sorry." } ]
[ { "body": "<p>I'm assuming that <code>computer</code> and <code>brand</code> are meant to be function parameters, otherwise any kind of branching would be unnecessary.\nHere's something that pretty much does what you want, assuming you just want messages that describe in clear english the quantity and brand of computers, and not necessarily have the exact messages used in your examples:</p>\n<pre><code>public static void Message(int quantity, string brand)\n{\n Console.WriteLine(&quot;You own &quot; + quantity + &quot; &quot; + brand + (quantity !== 1 ? 's' : '');\n}\n</code></pre>\n<p>The actual brand and quantities are variables that are inserted into the general message. If you want the message to be longer and use more variables, then you would probably want to create substrings to later be combined, for the sake of readability:</p>\n<pre><code>public static void Message(int quantity, string brand)\n{\n string brandPlural = brand + (quantity !== 1 ? 's' : '');\n\n Console.WriteLine(&quot;You own &quot; + quantity + &quot; &quot; + brandPlural;\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T19:20:24.543", "Id": "251828", "ParentId": "251818", "Score": "2" } }, { "body": "<p>The functional way to solve this problem is actually with pattern matching. My solution to do exactly as you showed would look something like this:</p>\n<pre><code> public static int ComputerType(int computer, string brand)\n {\n var (result, message) = (computer, brand) switch\n {\n (var n, var b) when n &lt; 2 &amp;&amp; b != &quot;Apple&quot; =&gt; (0, &quot;you don't own a Mac&quot;),\n (var n, _) when n &lt; 2 =&gt; (1, &quot;you own less than 2 Macs&quot;),\n _ =&gt; (2, &quot;you own two (or more) pcs or Macs&quot;)\n };\n Console.WriteLine(message);\n return result;\n }\n</code></pre>\n<p>But there are additional problems with your solution. You shouldn't need to hardcode any values, for instance.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T05:17:43.610", "Id": "251848", "ParentId": "251818", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T14:46:53.480", "Id": "251818", "Score": "1", "Tags": [ "c#" ], "Title": "How do I remove nested if else conditions?" }
251818
<p>So I have tried to implement a doubly-linked list in C++. My implementation includes some basic methods (although I know there could be many more), an iterator class and an overwritten <code>&lt;&lt;</code> operator. I know the code is quite big, but I would really appreciate any comments on functionality, style or anything else you think could be better.</p> <p><strong>Note:</strong> I know many people say using smart pointers is always a good idea, but I used raw pointers here, for training purposes and because I think using them in situations like this is not really wrong. Feel free to state your opinion on this, too.</p> <p><em>Cdoubly_linked_list.h</em>:</p> <pre><code>#ifndef CDOUBLY_LINKED_LIST #define CDOUBLY_LINKED_LIST #include &lt;cstdint&gt; namespace list { template&lt;class T&gt; class Cdoubly_linked_list { struct Node { Node(T _value, Node* _prev, Node* _next) : value{ _value }, prev{ _prev }, next{ _next }{}; T value; Node* prev; Node* next; }; public: Cdoubly_linked_list() : head{ nullptr }, tail{ nullptr }{}; // standard constructor ~Cdoubly_linked_list() { clear(); }; // destructor to call clear() Cdoubly_linked_list(const Cdoubly_linked_list&amp; other) : head{ nullptr }, tail{ nullptr } // copy constructor { Node* tmp = other.head; while (tmp != nullptr) { push_back(tmp-&gt;value); tmp = tmp-&gt;next; } } Cdoubly_linked_list&amp; operator=(const Cdoubly_linked_list&amp; other) // copy assignment operator { if (*this != other) { Node* tmp = other.head; while (tmp != nullptr) { push_back(tmp-&gt;value); tmp = tmp-&gt;next; } } return *this; } Cdoubly_linked_list(Cdoubly_linked_list&amp;&amp; other) = default; // move constructor Cdoubly_linked_list&amp; operator=(Cdoubly_linked_list&amp;&amp; other) = default; // move assignment operator bool is_empty() // return true if list is empty { if (head == nullptr) return true; return false; } void clear() // clears list and free's all memory { Node* tmp = head; while (tmp != nullptr) { head = tmp; tmp = tmp-&gt;next; delete head; } head = tail = nullptr; } bool remove(T val) // delete first matching element by value and return true if succesfull { if (val == head-&gt;value) { pop_front(); return true; } Node* tmp = head-&gt;next; while (tmp != tail) { if (tmp-&gt;value == val) { tmp-&gt;prev-&gt;next = tmp-&gt;next; tmp-&gt;next-&gt;prev = tmp-&gt;prev; delete tmp; return true; } tmp = tmp-&gt;next; } if (val == tail-&gt;value) { pop_back(); return true; } return false; } void pop_front() // pop first element { if (head != nullptr) { Node* tmp = head; head = head-&gt;next; delete tmp; if (head == nullptr) tail = nullptr; } } void pop_back() // pop last element { if (tail == head) pop_front(); tail = tail-&gt;prev; delete tail-&gt;next; tail-&gt;next = nullptr; } void push_front(T val) // insert element at front { if (head != nullptr) { head-&gt;prev = new Node(val, nullptr, head); head = head-&gt;prev; } else { head = new Node(val, nullptr, nullptr); tail = head; } } void push_back(T val) // insert element at back { if (head != nullptr) { tail-&gt;next = new Node(val, tail, nullptr); tail = tail-&gt;next; } else { head = new Node(val, nullptr, nullptr); tail = head; } } class it : private std::iterator&lt;std::bidirectional_iterator_tag, T&gt; // bidirectional iterator { public: it(Node* _ptr = nullptr) : ptr{ _ptr } {}; // standard constructor it(const it&amp; other) = default; // copy constructor it(it&amp;&amp; other) = default; // move constructor it&amp; operator=(const it&amp; other) = default; // copy assignment operator it&amp; operator=(it&amp;&amp; other) = default; // move assignment operator T&amp; operator*() const // dereference operator { return ptr-&gt;value; } it&amp; operator++() // pre-increment operator { ptr = ptr-&gt;next; return *this; } it operator++(int) // post-increment operator { it copy(ptr); ptr = ptr-&gt;next; return copy; } it&amp; operator--() // pre-decrement operator { ptr = ptr-&gt;prev; return *this; } it operator--(int) // post-decrement operator { it copy(ptr); ptr = ptr-&gt;prev; return copy; } bool operator==(const it&amp; other) // equality operator { return other.ptr == ptr; } bool operator!=(const it&amp; other) // inequality operator { return other.ptr != ptr; } private: Node* ptr; }; it begin() const // get begin iterator { return it(head); } it end() const // get end iterator { return it(tail); } friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, Cdoubly_linked_list&amp; list) // overload &lt;&lt; operator { Node* tmp = list.head; while (tmp != nullptr) { os &lt;&lt; tmp-&gt;value &lt;&lt; std::endl; tmp = tmp-&gt;next; } return os; } private: Node* head; Node* tail; }; } #endif </code></pre>
[]
[ { "body": "<h1>Overload the operator <code>!=</code> before it's use</h1>\n<p>You seem to use operator!= which was not overloaded, a simple implementation might be</p>\n<pre><code>bool operator==(const Cdoubly_linked_list&amp; other) \n{\n return head == other.head;\n}\n\n</code></pre>\n<p>Then you can simply implement operator!= like this</p>\n<pre><code>bool operator!=(const Cdoubly_linked_list&amp; other) \n{\n return !(*this == other );\n}\n</code></pre>\n<hr />\n<h1>Unnecessary call to <code>clear()</code></h1>\n<p>This is just unnecessary, define the cleanup operations in the destructor\nand thus avoid the function call overhead</p>\n<hr />\n<h1>Why squeeze this into one line?</h1>\n<p><code>if (val == head-&gt;value) { pop_front(); return true; }</code></p>\n<p>This can be written more clearly and less eye hurting like this</p>\n<pre><code>if (val == head-&gt;value) \n pop_front(); \n return true; \n}\n\n</code></pre>\n<p><strong>The same case here.</strong></p>\n<p><code>if (val == tail-&gt;value) { pop_back(); return true; }</code></p>\n<h1>No need for `if` statement</h1>\n<p>I see you are testing if head == nullptr in this method.</p>\n<pre><code>bool is_empty() // return true if list is empty\n{\n if (head == nullptr) return true;\n return false;\n}\n\n</code></pre>\n<p>This can simply be written as:</p>\n<pre><code>bool is_empty() // return true if list is empty\n{\n return head == nullptr;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T16:45:32.143", "Id": "495941", "Score": "0", "body": "Thank you for the answer, but I have a question: Wouldn't it be against the DRY principle to write the clean up operations again in the destructor? I want the ```clear()``` method to exist as public." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T17:10:42.290", "Id": "495944", "Score": "0", "body": "I would suggest making it `is_empty() const` as you aren't modifying member variables. Maybe the `[[nodiscard]]` keyword too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T17:13:24.027", "Id": "495945", "Score": "0", "body": "Follow your own advice. Get rid of the `if` statement in `operator==`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T17:19:21.587", "Id": "495946", "Score": "0", "body": "@Reinderien, my bad." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T18:02:50.447", "Id": "495949", "Score": "0", "body": "No problem - you can edit your answer and all will be well :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T16:14:18.453", "Id": "251822", "ParentId": "251819", "Score": "2" } }, { "body": "<h2>Overview</h2>\n<p>Good.</p>\n<p>Can't use default move operators as you do memory (resource) management within the class so you need to define your own.</p>\n<p>You should allow the user to pass objects so they can be copied or moved into the list.</p>\n<p>A couple of minor bugs (that should have been caught by your unit tests).</p>\n<h2>Code Review</h2>\n<p>First issue is that you forgot to call clear() first. here.</p>\n<pre><code> Cdoubly_linked_list&amp; operator=(const Cdoubly_linked_list&amp; other) // copy assignment operator\n {\n if (*this != other)\n {\n // should call clear() here.\n\n Node* tmp = other.head;\n while (tmp != nullptr)\n {\n push_back(tmp-&gt;value);\n tmp = tmp-&gt;next;\n }\n }\n return *this;\n }\n</code></pre>\n<p>If you fix that the implementation works. <strong>BUT</strong> it does not fulfill the strong exception guarantee. i.e. if something goes wrong and the assignment fails your object is left in an inconsistent state. I would use the copy and swap idiom. This is where you copy the object into a temporary then swap with the current state.</p>\n<pre><code>Cdoubly_linked_list&amp; operator=(Cdoubly_linked_list const&amp; other)\n{\n Cdoubly_linked_list tmp(other); // Use copy constructor\n // to make the copy.\n\n // Now that you have made a copy and it worked.\n // simply swap the tmp value with *this\n swap(tmp);\n\n return *this;\n // The destructor of tmp will not handle the cleanup\n // of the old object.\n}\nvoid swap(Cdoubly_linked_list&amp; other) noexcept\n{\n using std::swap;\n swap(head, other.head);\n swap(tail, other.tail);\n}\n</code></pre>\n<hr />\n<p>Because you have dynamic allocation in the class the default implementation does not work. You need to write your own versions of these operations.</p>\n<pre><code> Cdoubly_linked_list(Cdoubly_linked_list&amp;&amp; other) = default; // move constructor\n Cdoubly_linked_list&amp; operator=(Cdoubly_linked_list&amp;&amp; other) = default; // move assignment operator\n</code></pre>\n<p>But they are relatively simply to write:</p>\n<pre><code>Cdoubly_linked_list(Cdoubly_linked_list&amp;&amp; other) noexcept\n : head(nullptr)\n , tail(nullptr)\n{\n swap(other);\n}\nCdoubly_linked_list&amp; operator=(Cdoubly_linked_list&amp;&amp; other) noexcept\n{\n swap(other);\n return *this;\n}\n</code></pre>\n<p>Simply swap with the object that is being moved.</p>\n<hr />\n<p>This can be simplified:</p>\n<pre><code> bool is_empty() // return true if list is empty\n {\n if (head == nullptr) return true;\n return false;\n\n // rewrite as:\n\n return head == nullptr;\n }\n</code></pre>\n<hr />\n<p>You don't check if <code>head</code> is <code>nullptr</code>!! So <code>head-&gt;value</code> may be UB.</p>\n<pre><code> if (val == head-&gt;value) { pop_front(); return true; }\n</code></pre>\n<hr />\n<p>What happens if there is only one value in the list?</p>\n<pre><code> Node* tmp = head-&gt;next;\n while (tmp != tail)\n</code></pre>\n<p>tmp is already <code>nullptr</code> and will never be equal to <code>tail</code>.</p>\n<hr />\n<pre><code> void pop_front() // pop first element\n {\n if (head != nullptr)\n {\n Node* tmp = head;\n head = head-&gt;next;\n delete tmp;\n</code></pre>\n<p>This seems like a bug!</p>\n<pre><code> if (head == nullptr) tail = nullptr;\n</code></pre>\n<p>I think you mean: <code>if head == tail</code>.</p>\n<pre><code> }\n }\n</code></pre>\n<hr />\n<p>Pass values by const reference to prevent an unnecessaery copy here:</p>\n<pre><code> void push_front(T val) // insert element at front\n</code></pre>\n<p>You may also want to allow the user to pass by r-value ref.</p>\n<pre><code> void push_front(T const&amp; val)\n void push_front(T&amp;&amp; val)\n void push_back(T const&amp; val)\n void push_back(T&amp;&amp; val)\n</code></pre>\n<p>For advanced usage allow construction in place:</p>\n<pre><code> template&lt;typename... Args&gt;\n void emplace_front(Args&amp;&amp;... args);\n template&lt;typename... Args&gt;\n void emplace_back(Args&amp;&amp;... args);\n</code></pre>\n<hr />\n<p>Sure this looks good:</p>\n<pre><code> void push_front(T val) // insert element at front\n</code></pre>\n<p>But I think you can simplify to:</p>\n<pre><code> void push_front(T const&amp; val)\n {\n head = new Node(val, nullptr, head);\n if (tail == nullptr) {\n tail = head;\n }\n }\n</code></pre>\n<hr />\n<p>Same simplification</p>\n<pre><code> void push_back(T const&amp; val) // insert element at back\n {\n tail = new Node(val, tail, nullptr);\n if (head == nullptr) {\n head = tail;\n }\n }\n</code></pre>\n<hr />\n<p>end() should be one past the end of the container.</p>\n<pre><code> it end() const // get end iterator\n {\n return it(tail);\n }\n</code></pre>\n<p>If you do this the standard algorithms are going to miss the last element in the list.</p>\n<p>I would do:</p>\n<pre><code> it end() const {return it{nullptr};}\n</code></pre>\n<hr />\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T21:44:10.853", "Id": "495958", "Score": "1", "body": "Thanks for the answer. Shouldn't the default move constructor and move assignment operator work, because I dont actually have to deal with memory allocation like with the copy operations but can just copy the head and tail values?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T21:59:13.893", "Id": "495959", "Score": "1", "body": "@TomGebel. Move Assignment operator needs to de-allocate its current memory or make sure that the memory will be de-allocated." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T18:32:55.493", "Id": "251827", "ParentId": "251819", "Score": "6" } } ]
{ "AcceptedAnswerId": "251827", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T15:12:19.363", "Id": "251819", "Score": "7", "Tags": [ "c++", "linked-list" ], "Title": "Implementation of Doubly-linked list in C++" }
251819
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251132/231235">A recursive_transform for std::vector with various return type</a>, <a href="https://codereview.stackexchange.com/q/251060/231235">A recursive_transform Function For Various Type Nested Iterable With std::variant Implementation in C++</a> and <a href="https://codereview.stackexchange.com/q/251171/231235">A recursive_transform for std::array with various return type</a>. The execution policy parameter is available since C++17. I am trying to add this into the <code>recursive_transform</code> template function. The experimental version code is as below.</p> <pre><code>// With execution policy template&lt;class ExPo, class T, class F&gt; auto recursive_transform(ExPo execution_policy, const T&amp; input, const F&amp; f) { return f(input); } template&lt;class ExPo, class T, std::size_t S, class F&gt; requires std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt; auto recursive_transform(ExPo execution_policy, const std::array&lt;T, S&gt;&amp; input, const F&amp; f) { using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f)); std::array&lt;TransformedValueType, S&gt; output; std::transform(execution_policy, input.cbegin(), input.cend(), output.begin(), [execution_policy, f](auto&amp; element) { return recursive_transform(execution_policy, element, f); } ); return output; } template&lt;class ExPo, template&lt;class...&gt; class Container, class Function, class... Ts&gt; requires (std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt; &amp;&amp; is_iterable&lt;Container&lt;Ts...&gt;&gt; &amp;&amp; !is_elements_iterable&lt;Container&lt;Ts...&gt;&gt;) // non-recursive version auto recursive_transform(ExPo execution_policy, const Container&lt;Ts...&gt;&amp; input, const Function&amp; f) { using TransformedValueType = decltype(f(*input.cbegin())); Container&lt;TransformedValueType&gt; output(input.size()); std::transform(execution_policy, input.cbegin(), input.cend(), output.begin(), f); return output; } template&lt;class ExPo, template&lt;class...&gt; class Container, class Function, class... Ts&gt; requires (std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt; &amp;&amp; is_elements_iterable&lt;Container&lt;Ts...&gt;&gt;) auto recursive_transform(ExPo execution_policy, const Container&lt;Ts...&gt;&amp; input, const Function&amp; f) { using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f)); Container&lt;TransformedValueType&gt; output(input.size()); std::transform(execution_policy, input.cbegin(), input.cend(), output.begin(), [&amp;](auto&amp; element) { return recursive_transform(execution_policy, element, f); } ); return output; } </code></pre> <p>I found that <code>std::back_inserter(output)</code> cannot be used in here due to the error happened <code>Parallel algorithms require forward iterators or stronger.</code> Instead of using <code>std::back_inserter()</code> to fill the containers, the <code>.size()</code> function is used for constructing container. If there is any better way to handle the output container size, please let me know.</p> <p>The test of this version of <code>recursive_transform</code> template function:</p> <pre><code>// std::vector&lt;int&gt; -&gt; std::vector&lt;std::string&gt; std::vector&lt;int&gt; test_vector = { 1, 2, 3 }; auto recursive_transform_result = recursive_transform( std::execution::par, test_vector, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result.at(0) &lt;&lt; std::endl; // recursive_transform_result.at(0) is a std::string // std::vector&lt;std::vector&lt;int&gt;&gt; -&gt; std::vector&lt;std::vector&lt;std::string&gt;&gt; std::vector&lt;decltype(test_vector)&gt; test_vector2 = { test_vector, test_vector, test_vector }; auto recursive_transform_result2 = recursive_transform( std::execution::par, test_vector2, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result2.at(0).at(0) &lt;&lt; std::endl; // recursive_transform_result.at(0).at(0) is also a std::string // std::deque&lt;int&gt; -&gt; std::deque&lt;std::string&gt; std::deque&lt;int&gt; test_deque; test_deque.push_back(1); test_deque.push_back(1); test_deque.push_back(1); auto recursive_transform_result3 = recursive_transform( std::execution::par, test_deque, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result3.at(0) &lt;&lt; std::endl; // std::deque&lt;std::deque&lt;int&gt;&gt; -&gt; std::deque&lt;std::deque&lt;std::string&gt;&gt; std::deque&lt;decltype(test_deque)&gt; test_deque2; test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); auto recursive_transform_result4 = recursive_transform( std::execution::par, test_deque2, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result4.at(0).at(0) &lt;&lt; std::endl; // std::array&lt;int, 10&gt; -&gt; std::array&lt;std::string, 10&gt; std::array&lt;int, 10&gt; test_array; for (int i = 0; i &lt; 10; i++) { test_array[i] = 1; } auto recursive_transform_result5 = recursive_transform( std::execution::par, test_array, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result5.at(0) &lt;&lt; std::endl; // std::array&lt;std::array&lt;int, 10&gt;, 10&gt; -&gt; std::array&lt;std::array&lt;std::string, 10&gt;, 10&gt; std::array&lt;std::array&lt;int, 10&gt;, 10&gt; test_array2; for (int i = 0; i &lt; 10; i++) { test_array2[i] = test_array; } auto recursive_transform_result6 = recursive_transform( std::execution::par, test_array2, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result6.at(0).at(0) &lt;&lt; std::endl; // std::list&lt;int&gt; -&gt; std::list&lt;std::string&gt; std::list&lt;int&gt; test_list = { 1, 2, 3, 4 }; auto recursive_transform_result7 = recursive_transform( std::execution::par, test_list, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result7.front() &lt;&lt; std::endl; // std::list&lt;std::list&lt;int&gt;&gt; -&gt; std::list&lt;std::list&lt;std::string&gt;&gt; std::list&lt;std::list&lt;int&gt;&gt; test_list2 = { test_list, test_list, test_list, test_list }; auto recursive_transform_result8 = recursive_transform( std::execution::par, test_list2, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result8.front().front() &lt;&lt; std::endl; </code></pre> <p><a href="https://godbolt.org/z/85W3hs" rel="nofollow noreferrer">Here's the Godbolt link</a>.</p> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/251132/231235">A recursive_transform for std::vector with various return type</a>,</p> <p><a href="https://codereview.stackexchange.com/q/251060/231235">A recursive_transform Function For Various Type Nested Iterable With std::variant Implementation in C++</a> and</p> <p><a href="https://codereview.stackexchange.com/q/251171/231235">A recursive_transform for std::array with various return type</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>The execution policy parameter is considered here in this version of <code>recursive_transform</code> template function.</p> </li> <li><p>Why a new review is being asked for?</p> <p>In my opinion, I am not sure if it is a good idea to add the execution policy parameter in the above way. Especially the usage of <code>std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt;</code> in constraint expression.</p> </li> </ul>
[]
[ { "body": "<h1>Make sure every template overload requires <code>is_execution_policy&lt;ExPo&gt;</code></h1>\n<p>The overload for a single element does not place restrictions on the type of <code>execution_policy</code>. This means that if you pass something that is no an execution policy, it will always pick the first overload, which is most likely not what you want, and it may or may not give an error while compiling. Consider:</p>\n<pre><code>std::vector&lt;char&gt; test_vector = {1, 2, 3};\n\nauto sum_sizeofs = recursive_transform(\n 42,\n test_vector, [](auto &amp;x){return std::to_string(sizeof x);});\n</code></pre>\n<p>The expected result is a <code>std::vector&lt;string&gt;</code> containing <code>{&quot;1&quot;, &quot;1&quot;, &quot;1&quot;}</code>, but the above will compile without errors and return a <code>std::string</code> containing <code>&quot;24&quot;</code> (when compiled with GCC on a 64-bits architecture).</p>\n<h1>Container size vs. <code>std::back_inserter()</code></h1>\n<p>Indeed there is no way to use <code>std::back_inserter()</code>, since the transforms of elements can happen in parallel and <code>std::back_inserter()</code> is not thread safe. This means that you have to give the output container the right size before calling <code>std::transform()</code>. If this would not work, for example if <code>TransformedValueType</code> is a type that you could not assign to after it was constructed, then you have a problem. The only solution I see is to create a tread-safe back inserter, using <a href=\"https://en.cppreference.com/w/cpp/algorithm/for_each\" rel=\"nofollow noreferrer\"><code>std::for_each()</code></a> instead of <code>std::transform()</code>, like so:</p>\n<pre><code>template&lt;class ExPo, template&lt;class...&gt; class Container, class Function, class... Ts&gt;\nrequires (std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt; &amp;&amp; is_elements_iterable&lt;Container&lt;Ts...&gt;&gt;)\nauto recursive_transform(ExPo execution_policy, const Container&lt;Ts...&gt;&amp; input, const Function&amp; f)\n{\n using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f));\n Container&lt;TransformedValueType&gt; output;\n output.reserve(input.size());\n std::mutex mutex;\n\n std::for_each(execution_policy, input.cbegin(), input.cend(),\n [&amp;](auto&amp; element)\n {\n auto result = recursive_transform(execution_policy, element, f);\n std::lock_guard lock(mutex);\n output.emplace_back(std::move(result));\n }\n );\n\n return output;\n}\n</code></pre>\n<p>However, that still requires the type to be at least move constructible, and this version might actually be slower than your version, depending on the overhead of the mutex.</p>\n<h1>What about <code>std::vector&lt;std::string&gt;</code>?</h1>\n<p>What if I want to convert a vector of strings to a vector of <code>int</code>s?</p>\n<pre><code>std::vector&lt;std::string&gt; test_vector = {&quot;1&quot;, &quot;2&quot;, &quot;3&quot;};\n\nauto result = recursive_transform(\n std::execution::par,\n test_vector,\n [](const std::string &amp;x){return std::stoi(x);});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-20T10:54:47.017", "Id": "253697", "ParentId": "251823", "Score": "1" } } ]
{ "AcceptedAnswerId": "253697", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T16:29:13.703", "Id": "251823", "Score": "2", "Tags": [ "c++", "performance", "recursion", "lambda", "c++20" ], "Title": "A recursive_transform Template Function with Execution Policy" }
251823
<p>I am making a number uncovering app. The program takes in an equation that has numbers hidden as letters, like:</p> <pre><code>abc + d = efg - hi </code></pre> <p>and it will return all the strings like</p> <pre><code>290 + 6 = 347 - 51 290 + 7 = 348 - 51 250 + 6 = 347 - 91 250 + 7 = 348 - 91 290 + 4 = 365 - 71 270 + 4 = 365 - 91 290 + 4 = 375 - 81 280 + 4 = 375 - 91 290 + 7 = 358 - 61 260 + 7 = 358 - 91 290 + 5 = 376 - 81 280 + 5 = 376 - 91 490 + 6 = 527 - 31 ... </code></pre> <p>But there can will be duplicated strings. For example, when I input</p> <pre><code>a + b = c </code></pre> <p>the program returns</p> <pre><code>... 1 + 2 = 3 1 + 2 = 3 1 + 2 = 3 1 + 2 = 3 1 + 2 = 3 1 + 2 = 3 1 + 2 = 3 1 + 2 = 3 1 + 2 = 3 1 + 2 = 3 1 + 2 = 3 1 + 2 = 3 1 + 2 = 3 1 + 2 = 3 1 + 2 = 3 1 + 3 = 4 1 + 3 = 4 1 + 3 = 4 1 + 3 = 4 1 + 3 = 4 1 + 3 = 4 1 + 3 = 4 1 + 3 = 4 1 + 3 = 4 1 + 3 = 4 1 + 3 = 4 1 + 3 = 4 1 + 3 = 4 ... </code></pre> <p><strong>I know that I can put all the strings into set and then iterate through the set again to print out the strings, but I want to know if that is necessary.</strong></p> <p>Perhaps in my program there is an unnecessary loop or such that is causing the duplicated strings, which in turns makes its performance slower? If so, I would like to know the proper way of doing it.</p> <p>Here is my code:</p> <pre><code>from itertools import permutations from re import findall ope = '+-*/( ).=' var = 'abcdefghijklmnopqrstuvwxyz' num = '1234567890' while True: while True: whole = input(&quot;&gt;&gt;&gt; &quot;) # User inputs equation here if any(c not in ope + var + num for c in whole): # Makes sure that all the characters are valid print(f'You may only use: {ope}{var}{num}') continue chars = list({char for char in whole if char in var}) # Extract all the mystery numbers if len(chars) &gt; 10: # There are only 10 different digits, so the user may only input 10 different mystery numbers print('Enter at most 9 different letters.') continue while len(chars) &lt; 10: # If there are less that 10 different mystery numbers chars.append(None) # add None until the length of the list is 10 # From here to the break is to check if the syntax works, so a bit processing time is used on the first permutation of chars exp = whole for i, v in enumerate(chars): if v: exp = exp.replace(v, str(i)) if all(int(e[0]) for e in findall('\d+', exp)): try: eval(exp.replace('=', '==')) except SyntaxError: print('Invalid Syntax') continue break # If not continue was hit, that means that the equation is valid for p in permutations(chars): exp = whole for i, v in enumerate(p): if v: exp = exp.replace(v, str(i)) if all(int(e[0]) for e in findall('[\d\w]+', exp)): # If all the individual numbers don't begin with 0 if eval(exp.replace('=', '==')): # If the equation is correct print(exp) # Print the equation </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T17:03:25.330", "Id": "496021", "Score": "0", "body": "Is the problem your own idea, or is it from a challenge website?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T17:07:24.533", "Id": "496022", "Score": "0", "body": "@Reinderien My own problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T02:37:33.770", "Id": "496044", "Score": "0", "body": "Long story short, if you want to keep this as a brute-force solution, you should really drop `permutations` and vectorize the thing, potentially with a Numpy `meshgrid` input as I've shown." } ]
[ { "body": "<h2>Functions</h2>\n<p>Split your code into individual smaller functions, doing singular tasks. A few examples would be validating the expression, extracting variables and so on.</p>\n<h2><code>if __name__</code> block</h2>\n<p>For scripts, it is a good practice to put your executable feature inside the <code>if __name__ == &quot;__main__&quot;</code> clause.</p>\n<h2>Comments</h2>\n<p>The comments like in:</p>\n<pre><code>while len(chars) &lt; 10: # If there are less that 10 different mystery numbers\n</code></pre>\n<p>are pointless. The condition already explains what you write in 10 words. A more important comment here could've been what the <em>mystery numbers</em> are?</p>\n<p>This applies to almost all of the comments you have added in your program. Once you split to functions, add docstrings to those functions explaining <strong>what</strong> and maybe <strong>why</strong> the function does. The code should be self-explanatory on the <em>how</em>.</p>\n<h2>Execution logic</h2>\n<p>From what I understand of the program, you are:</p>\n<ol>\n<li>asking user for expression</li>\n<li>validating if there are any invalid characters</li>\n<li>extracting variables (and creating a forced list of 10 elements)</li>\n<li>Not sure about the <code>findall('\\d+', exp)</code> validation, and later the same thing is being achieved by a different regex pattern</li>\n<li>check if the expression is mathematically consistent</li>\n<li>permute all elements from variables list (created above)</li>\n<li>iterate on all permutations and replace into the expression</li>\n<li>evaluate expression and print if successful</li>\n</ol>\n<p>A lot of the code seems duplicated, for eg. the <code>exp.replace</code> calls, the <code>findall</code> validation etc. You have to work with 2 nested loops just because there are no helper functions to assist you.</p>\n<p>For the permutations themselves, you can obviously permute over a forced set of length 10, or you can just permute over the integers <code>range(10)</code> selecting as many elements as there are variables. Since you anyway need those integers (using enumerate), I'd go for this.</p>\n<p>As a side note, instead of printing all valid results in the main loop, use a generator and yield valid results.</p>\n<hr />\n<h2>Example rewrite</h2>\n<pre><code>from typing import Tuple, Set\nfrom itertools import count, permutations\n\nOPERATORS = '+-*/( ).='\nVARIABLES = 'abcdefghijklmnopqrstuvwxyz'\nNUMERALS = '1234567890'\nVALID_CHARACTERS = OPERATORS + VARIABLES + NUMERALS\n\n\ndef is_expression_valid(expression: str) -&gt; bool:\n return all(c in VALID_CHARACTERS for c in expression)\n\n\ndef is_expression_consistent(expression: str, variables: Set[str]) -&gt; bool:\n for index, value in zip(count(1), variables):\n expression = expression.replace(value, str(index))\n try:\n eval(expression.replace(&quot;=&quot;, &quot;==&quot;))\n except SyntaxError:\n return False\n return True\n\n\ndef extract_variables(expression: str) -&gt; Set[str]:\n variables = {char for char in expression if char in VARIABLES}\n if len(variables) &gt; 10:\n raise ValueError()\n return variables\n\n\ndef get_expression() -&gt; Tuple[str, Set[str]]:\n while True:\n expression = input(&quot;&gt;&gt;&gt; &quot;)\n if not is_expression_valid(expression):\n print(f&quot;Invalid characters in the expression. Use only from: {VALID_CHARACTERS}&quot;)\n continue\n try:\n variables = extract_variables(expression)\n except ValueError:\n print(&quot;Expected at most 9 variable/letters!&quot;)\n continue\n if not is_expression_consistent(expression, variables):\n print(&quot;Invalid syntax!&quot;)\n continue\n break\n return expression, variables\n\n\ndef substitute_expression_format(expression: str) -&gt; str:\n return &quot;&quot;.join(r&quot;{}&quot; if c in VARIABLES else c for c in expression)\n\n\ndef valid_results(expression: str, variables: Set[str]) -&gt; str:\n formatted_expression = substitute_expression_format(expression)\n for permute in permutations(range(10), len(variables)):\n variation = formatted_expression.format(*permute)\n if eval(variation.replace(&quot;=&quot;, &quot;==&quot;)):\n yield variation\n\n\ndef main():\n expression, variables = get_expression()\n for result in valid_results(expression, variables):\n print(result)\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n<p>Notice in <code>is_expression_consistent</code>, I've use <code>zip</code> with <code>itertools.count</code>, so that the dependency on regex is removed.</p>\n<p>Now, the above fails for invalid token check, when the first substitution is <span class=\"math-container\">\\$ 0 \\$</span>; which can be resolved by having a <code>try-except</code> in the generator:</p>\n<pre><code>def valid_results(expression: str, variables: Set[str]) -&gt; str:\n formatted_expression = substitute_expression_format(expression)\n for permute in permutations(range(10), len(variables)):\n variation = formatted_expression.format(*permute)\n try:\n if eval(variation.replace(&quot;=&quot;, &quot;==&quot;)):\n yield variation\n except SyntaxError:\n continue\n</code></pre>\n<p>You can check the <a href=\"https://tio.run/##jVXbTttAEH33V0z9gg0hkNIbkRIppamKREsVAi@osjbJJFlw1u7uGBIQ357urh1fUnPZF8h4Z@bMmTOz8YrmkThar6cyWgCtYi5mwBdxJAmGSRxiAy6QHPuVE0qKolBtLoyjRFADYpSLhBjxSCjHOf/dH/SG54ML6MDO3v7ugQd@s7PjXPUGp72vZ31rZ6PxBKezOb@5DRciiv9KRcnd/XL1sOP8uvypI5zZe633Rx8@fvr85fjQBDg7/Rac/OgNeifDvo1f5NqDIv4ebEI4jqPTAFcBLmOJSmmIwR0L@cQrDG1QJH3Y78JIF9d2QB@JlEgBLAy9MXAB/@WeRhLslyKOX5ttrEnhilDQdsoG3DHJ2ShE1TYkX2vbny0cJg0XE1yay2GCJuMDjz3LvNfySzH81MOcIpHmqPjRlBiHbIyeDdUwGDwb3PetK8lVKYa@5NX4uh23AW6n42ZOuBxjTHCxEsSWfSkjWcTIWPzOQoVlWocywYwsXJJkYwryMmobs2EnDZ3f1dU9judMpt0w/1QaAnyaW3N1PNkQ@kuIwivIgy60DkvIGVcIV4YnW5Pnl/HnblkRM6RSyz0L2Q7PtW3zBn0G/37OQ7QcPNMxLuKEPLfb7YLr51c0ZBHRK1ouicCcWHItk6l7KuxFy4ZmG6UynNAcy@qAS11yJMIVmGlvw@O26J9KaMzR0iYuEsyNFQFtd@qlTvslIqycCubrCnL7yxh1GRNgBItIERznqQ5CJFPgu9fA1vJZO631Q1aCs6FX2SF4pwek3vllQCOJ7LYss9ogmeRUMlLEKSEsw9dzsGBUO0L6b2W1uW7zJuLCk@7jk2snpTImgHpmte2FPWdrDrQxCUm9fbnlQFKwuotBRf1vrMzP92P6/NjVWH6JPMnEDL3WoV6S1VkvNdEaKU1ch6eZ5d3NkvjPa11TaHdmHrJuZVZdzFlxDCcFju1BqN2rFfmkzVgw3cssfK1udIHbaypnMO2hIfC5ntaPQCr/9LZRhaYgCARbYBBApwNuEBhYQeCmLilGZ73Wr79@pCdmKUxnsA9z/g8\" rel=\"nofollow noreferrer\">code on tio.run</a>.</p>\n<hr />\n<h2>EDIT</h2>\n<p>For fixing the issue mentioned in comments (about repeated letters):</p>\n<pre><code>def substitute_expression_format(expression: str) -&gt; str:\n return &quot;&quot;.join(f&quot;{{{c}}}&quot; if c in VARIABLES else c for c in expression)\n\n\ndef valid_results(expression: str, variables: Set[str]) -&gt; str:\n formatted_expression = substitute_expression_format(expression)\n for permute in permutations(range(10), len(variables)):\n variation = formatted_expression.format(**dict(zip(variables, permute)))\n try:\n if eval(variation.replace(&quot;=&quot;, &quot;==&quot;)):\n yield variation\n except SyntaxError:\n continue\n</code></pre>\n<p>Updated example <a href=\"https://tio.run/##jVXbbtpAEH33V0z9EjshJDS9BQkkmlI1UtpUhOQlqqzFDLCJWbu74wSC@Ha6uwbbUOeyL@DxzsyZM3PGyZwmsThZrUYyngLNEy7GwKdJLAn6aRJhDa6QHPuWE0qK40htLoRxKqgGCcppSox4LJTjXP7u9jr9y94VtGDv4HD/yAO/3tpzbjq9887Xi661s0E4xNF4wu/uo6mIk79SUfrwOJs/7Tm/rn/qCBf2XuP9yYePnz5/OT02AS7OvwVnPzq9zlm/a@MXuQ6giH8AmxCO4@g0wFWAs0SiUhpi8MAiPvQKQxMUSR8O2zDQxTUd0EcipVIAiyIvBC7gv9yjWIJ9U8TxK7OFmhSuCAXtpqzBA5OcDSJUTUPyrbb92cFh0nAxxJm5HKVoMj7xxLPMew2/FMPPPMwpEmmOioe6xCRiIXo2VM1g8Gxw37euJOelGPqSV@HrttwauK2Wu3bCWYgJwdVcEJt1pYxlEWPN4ncWKSzT2pcprsnCGUkWUpCXUdmYDTtZ6Pyurm4RTpjMumH@bDUE@Ci35tOxtCH0mwiFV5AHbWgcl5AzrhBuDE@2Js8v48/d1kWMkUot9yxkK55b2@YN@jX8xwmP0HLwTMe4SFLy3Ha7Da6fX9GQRUyvzHJpCMxJJNdjMnLPhb1o2dBso1SGE5pgeTrgWpcci2gORu1NWOwO/bKExhw92sRFirlxa4B2O/VSp/0SEXacCuarCnK7swR1GUNgBNNYEZzmqY4iJFPgu9fAVvJZqdZqkZXgbOhVVgTvtECqnV8GNJDI7stjVhlkPXIqHSjilBKW4WsdTBlVSkj/bq02163fxVzo4VgsFuFyuXStXLa0AqiFq20vLDtbeKCNaUTq7RsuR5Mh1q0MtiTwxvL8fElm3yC7H8ufI08yMUavcaw35bbgS520RsoSV@Gpr/Pu7w95SJ7Zv3mczdcPfd9/XgeaWbtP80xV63TbxZw5x2hYwNsVSeXO3RqtrEdTpvu8Dl85U7ru3RWWE5u11vD6XKur5ZFJI7tthkVTEASCTTEIoNUCNwgMrCBwM5cMo7NaTRiDQxhoSBr6Pw\" rel=\"nofollow noreferrer\">on tio.run</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T13:38:01.053", "Id": "496005", "Score": "0", "body": "The `findall('\\d+', exp)` if statement is to make sure none of the integers begin with `0`, because abc cannot be equal to `089`, as `089` is the equivalent of just `89`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T14:06:07.150", "Id": "496006", "Score": "0", "body": "You code returns an error when we use the same letter more than once. For example: `haa - b = def`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T16:28:01.797", "Id": "496019", "Score": "0", "body": "@user229550 updated for the same in my post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T20:44:17.140", "Id": "496028", "Score": "0", "body": "Great, thanks! -" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T02:33:44.847", "Id": "496043", "Score": "0", "body": "Naive `eval` is quite dangerous. You're going to want to eliminate all of the built-ins, as I've shown in my solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T02:40:00.827", "Id": "496045", "Score": "0", "body": "@Reinderien But doesn't the conditions filter out the danger? Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T02:48:24.587", "Id": "496047", "Score": "0", "body": "I wouldn't trust it. Disabling built-ins is an easy step, and it's worth the (very minimal) cost if it means reducing attack surface area." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T16:06:46.673", "Id": "496104", "Score": "0", "body": "Also this throws for some inputs including `abc - cab = ab`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T17:01:28.743", "Id": "496111", "Score": "0", "body": "@Reinderien The whole point of the OP's problem was that for letters `x` and `y`, they should never have the same values. So, in your example \\$ abc - cab = ab \\$, the valid answers require either \\$ a = b = c \\$ or \\$ a = b \\$." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T17:11:26.163", "Id": "496113", "Score": "0", "body": "Fine - so output an error message to that effect, instead of `IndexError: Replacement index 3 out of range for positional args tuple`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T17:20:53.057", "Id": "496114", "Score": "0", "body": "@Reinderien I think you're using the code from pre-edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T17:24:12.580", "Id": "496115", "Score": "0", "body": "I'm sorry; my mistake. I propose that you keep your edit-message but simply replace the old code. Anyway, with the new code, it silently fails, which is only marginally better - a message saying that there were no valid solutions would be helpful." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T10:28:05.293", "Id": "251856", "ParentId": "251830", "Score": "4" } }, { "body": "<p>It's an interesting question, but given the broad range of expression operators permitted I believe it's infeasible to arrive at an exact solution.</p>\n<p>Your approach is definitely broken in at least one category of cases, and I think an integer-math general solution is either difficult or maybe impossible.</p>\n<p>Take for instance</p>\n<pre><code>&gt;&gt;&gt; 35 / (7/3)\n14.999999999999998\n&gt;&gt;&gt; 35 / (7/3) == 15\nFalse\n&gt;&gt;&gt; \n</code></pre>\n<p>You're expecting that floating-point comparison is going to do what you want, but there are many circumstances where it won't.</p>\n<p>A quick, approximate fix is to</p>\n<ul>\n<li>avoid doing direct comparison</li>\n<li>evaluate the left and right sides separately</li>\n<li>set some small epsilon value like <code>1e-12</code> under which any errors are considered equal.</li>\n</ul>\n<p>A more careful brute-force approach is to vectorize your parameter space and use Numpy. Given that every added variable introduces another factor of 10 this will need to be limited, and might require segmentation (which I have not done) - but it stands a very good chance of running faster than your original.</p>\n<p>I'm also going to propose that you be more careful with <code>eval</code>, and don't parse anything yourself. Tell the Python AST to run parsing, and do selective node replacement e.g. from <code>ab</code> to <code>10*a + 1*b</code>. The following code does this, and offers a more secure and performant solution.</p>\n<pre><code>import ast\nimport numpy as np\nfrom typing import Callable, Mapping, Tuple, Sequence, List\n\n\nArgs = Mapping[str, int]\nCallback = Callable[[Args], float]\nNO_BUILTINS = {'__builtins__': {}}\nMAX_VARS = 5\n\n\nclass ExprSyntaxError(SyntaxError):\n pass\n\n\nclass DigitTransformer(ast.NodeTransformer):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.names = set()\n\n def visit_Name(self, node: ast.Name) -&gt; ast.AST:\n self.names.update(node.id)\n\n digits = len(node.id)\n if digits == 1:\n return node\n\n digit_expr = '+'.join(\n f'{10**(digits - i)}*{letter}'\n for i, letter in enumerate(node.id, 1)\n )\n return ast.parse(digit_expr, mode='eval').body\n\n\ndef make_cb(side: ast.AST) -&gt; Callback:\n code = compile(\n ast.Expression(side),\n filename='&lt;stdin&gt;',\n mode='eval',\n dont_inherit=True,\n )\n\n def execute(args: Args) -&gt; float:\n return eval(code, NO_BUILTINS, args)\n return execute\n\n\ndef parse(expr: str) -&gt; Tuple[\n List[str],\n Callback,\n Callback,\n]:\n tree = ast.parse(expr, mode='eval')\n trans = DigitTransformer()\n compare = trans.visit(tree).body\n if not (\n isinstance(compare, ast.Compare) and\n isinstance(compare.ops[0], ast.Eq)\n ):\n raise ExprSyntaxError('Only == is supported')\n\n lhs, (rhs,) = compare.left, compare.comparators\n return sorted(trans.names), make_cb(lhs), make_cb(rhs)\n\n\ndef solve(letters: Sequence[str], lhs_fun: Callback, rhs_fun: Callback) -&gt; np.array:\n n = len(letters)\n\n ten_by_n = np.repeat(\n np.arange(10)[np.newaxis, ...],\n n, axis=0\n )\n grid = np.array(\n np.meshgrid(*ten_by_n)\n ).T.reshape(-1, n)\n params = dict(zip(letters, grid.T))\n\n error = np.abs(lhs_fun(params) - rhs_fun(params))\n return grid[error &lt; 1e-12, :]\n\n\ndef capture() -&gt; Tuple[\n List[str],\n Callback,\n Callback,\n]:\n while True:\n try:\n letters, lhs, rhs = parse(\n input('Expression: ')\n )\n if len(letters) &lt;= MAX_VARS:\n return letters, lhs, rhs\n print(f'{len(letters)} variables exceeds the maximum of {MAX_VARS}.')\n except SyntaxError:\n pass\n\n\ndef main():\n while True:\n letters, lhs, rhs = capture()\n sorted_letters = sorted(letters)\n solutions = solve(sorted_letters, lhs, rhs)\n\n print(f'{len(solutions)} solutions', end='')\n if len(solutions):\n print(':')\n print(', '.join(sorted_letters))\n print(solutions)\n else:\n print()\n print()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Example output:</p>\n<pre><code>Expression: abc - cab == ab\n2 solutions:\na, b, c\n[[0 0 0]\n [9 9 8]]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T20:43:42.730", "Id": "496027", "Score": "1", "body": "Thank you very much!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T12:53:14.310", "Id": "496071", "Score": "0", "body": "Just so you know, every letter must have a different value, and numbers such as `abc` cannot be `056`, because `056` will be counted as only 2 digits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T16:08:36.317", "Id": "496105", "Score": "0", "body": "@Chocolate Do you mean that _every letter must have a different value_, and/or _every letter must appear at most once in the input_? Your problem description does not mention either constraint." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T16:56:04.490", "Id": "496109", "Score": "0", "body": "The comment in my code `# There are only 10 different digits, so the user may only input 10 different mystery numbers`; every letter must have a different value, so the user can input a maximum of 10 different letters. But reusing the same letter wouldn't count as another different letter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T16:58:57.173", "Id": "496110", "Score": "0", "body": "This part of the code `if all(int(e[0]) for e in findall('\\d+', exp)):` ensures that no integer begins with 0." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T17:43:31.573", "Id": "496117", "Score": "0", "body": "I see; so letters needn't be unique, but values must be. Thanks for the clarification." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T17:08:39.617", "Id": "251867", "ParentId": "251830", "Score": "1" } } ]
{ "AcceptedAnswerId": "251856", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T20:38:51.770", "Id": "251830", "Score": "4", "Tags": [ "python", "performance" ], "Title": "Number uncovering with given equations" }
251830
<p>I have a registration system, but I really don't know if it is safe, because I don't understand security very well and I'm afraid of compromising my clients' data, I believe that the methods I created are good for security, but I still have doubts if it is safe</p> <p>I created several variables using encapsulation, and then used them, is that right? Or should I create them within the methods</p> <p>Is regular expression enough to protect against JavaScript attacks?</p> <p>Is there a vulnerability in my code or an error?</p> <p>Can we consider that I have created efficient methods for the security of my clients?</p> <pre><code>&lt;?php /** * Signup */ class SignUp { private $email; private $password; private $name; private $sql; private $result; private $conn; private $remote_addr; private $http_user_agent; private $http_client_ip; private $http_x_forwarded_for; private $check_name; private $line; public function __construct($host, $dbname, $user, $pass) { try { $this-&gt;conn = new PDO(&quot;mysql:host=$host;dbname=$dbname&quot;, $user, $pass); $this-&gt;conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $this-&gt;conn; }catch(PDOException $e) { throw new Exception($e-&gt;getMessage()); } } public function setEmail($e) { $this-&gt;email = $e; } public function getEmail() { return $this-&gt;email; } public function setName($n) { $this-&gt;name = $n; } public function getName() { return $this-&gt;name; } public function setPassword($password, $confirm) { if ($password === $confirm) { $this-&gt;password = password_hash($password, PASSWORD_BCRYPT); } else { // Handle input error here echo &quot;Password does not match!&quot;; } } public function getPasswordHash() { return $this-&gt;password; } // public function CheckHashes() { // echo $this-&gt;password; // } public function CheckName(){ $this-&gt;check_name = $this-&gt;conn-&gt;prepare(&quot;SELECT name FROM users WHERE name = :name&quot;); $this-&gt;check_name-&gt;execute(array( &quot;:name&quot; =&gt; $this-&gt;getName() )); $this-&gt;line = $this-&gt;check_name-&gt;rowCount(); if($this-&gt;line != 0){ $_SESSION['msg'] = '&lt;p style=&quot;color:red;&quot;&gt;Name already exists!&lt;/p&gt;'; header(&quot;Location: signup.php&quot;); exit(); } } public function CheckEmail(){ $checkmail = $this-&gt;conn-&gt;prepare(&quot;SELECT email FROM users WHERE email = :email&quot;); $checkmail-&gt;execute(array( &quot;:email&quot; =&gt; $this-&gt;getEmail() )); $theline = $checkmail-&gt;rowCount(); if($theline != 0){ $_SESSION['msg'] = '&lt;p style=&quot;color:red;&quot;&gt;Email already exists!&lt;/p&gt;'; header(&quot;Location: signup.php&quot;); exit(); } } public function CheckFields(){ if(empty($this-&gt;password) || empty($this-&gt;name) || empty($this-&gt;email)){ $_SESSION['msg'] = '&lt;p style=&quot;color:red;&quot;&gt;Please, fill out all the fields!&lt;/p&gt;'; header(&quot;Location: signup.php&quot;); exit(); } } public function ValidateNameLength(){ if(strlen($this-&gt;getName()) &lt; 10){ $_SESSION['msg'] = '&lt;p style=&quot;color:red;&quot;&gt;Can only use 10 or more characters as name!&lt;/p&gt;'; header(&quot;Location: signup.php&quot;); exit(); } if(strlen($this-&gt;getName()) &gt; 25){ $_SESSION['msg'] = '&lt;p style=&quot;color:red;&quot;&gt;Can only use a maximum of 25 characters as name!&lt;/p&gt;'; header(&quot;Location: signup.php&quot;); exit(); } } public function ValidateEmail(){ if(!filter_var($this-&gt;getEmail(), FILTER_VALIDATE_EMAIL)){ $_SESSION['msg'] = '&lt;p style=&quot;color:red;&quot;&gt;Incorrect email!&lt;/p&gt;'; header(&quot;Location: signup.php&quot;); exit(); } } public function Insert() { if (preg_match(&quot;/^[A-Za-z0-9\s]*$/&quot;, $this-&gt;getName()) ) { $this-&gt;sql = &quot;INSERT INTO users (name, email, pass, ip_address, http_client_ip, http_x_forwarded_for, http_user_agent) VALUES(:name, :email, :pass, :ip_address, :http_client_ip, :http_x_forwarded_for, :http_user_agent)&quot;; $this-&gt;result = $this-&gt;conn-&gt;prepare($this-&gt;sql); $this-&gt;remote_addr = $_SERVER['REMOTE_ADDR']; $this-&gt;http_client_ip = $_SERVER['HTTP_CLIENT_IP']; $this-&gt;http_x_forwarded_for = $_SERVER['HTTP_X_FORWARDED_FOR']; $this-&gt;http_user_agent = $_SERVER['HTTP_USER_AGENT']; $this-&gt;result-&gt;execute(array( &quot;:name&quot; =&gt; $this-&gt;getName(), &quot;:email&quot; =&gt; $this-&gt;getEmail(), &quot;:pass&quot; =&gt; $this-&gt;getPasswordHash(), &quot;:ip_address&quot; =&gt; $this-&gt;remote_addr, &quot;:http_client_ip&quot; =&gt; $this-&gt;http_client_ip, &quot;:http_x_forwarded_for&quot; =&gt; $this-&gt;http_x_forwarded_for, &quot;:http_user_agent&quot; =&gt; $this-&gt;http_user_agent )); if($this-&gt;result == true){ $_SESSION['msg'] = '&lt;p style=&quot;color:green;&quot;&gt;Registered successfully!&lt;/p&gt;'; header(&quot;Location: signin.php&quot;); exit(); } } else { $_SESSION['msg'] = '&lt;p style=&quot;color:green;&quot;&gt;You can only use letters and numbers as name!&lt;/p&gt;'; header(&quot;Location: signup.php&quot;); exit(); } } } $obj = new SignUp('localhost', 'dbname', 'user', 'password'); $obj-&gt;setEmail('email@gmail.com'); $obj-&gt;setName('Anne'); $obj-&gt;setPassword('password', 'password'); $obj-&gt;CheckName(); $obj-&gt;CheckEmail(); $obj-&gt;CheckFields(); $obj-&gt;ValidateNameLength(); $obj-&gt;ValidateEmail(); $obj-&gt;Insert(); // $obj-&gt;getEmail(); // echo $obj-&gt;CheckHashes(); // echo &quot;\n&quot;; </code></pre>
[]
[ { "body": "<h2>Security</h2>\n<p>Your main worry is security. I don't see any obvious security problems in your code. To judge whether your code is really safe, I would need to see the whole system, and you have only given us a part of it. This piece seems secure, and that's all I can say.</p>\n<h2>Coding style</h2>\n<p>Your code has some real style problems. It looks to me that you're new to OOP. I'll deal with the problems from the big ones to minor ones.</p>\n<p><strong>Code repetition</strong></p>\n<p>There's quite a lot of code repetition. Two obvious case are:</p>\n<p><strong>1:</strong> Where you set an error message, jump to <code>signup.php</code>, and <code>exit()</code>. There could be a method like this:</p>\n<pre><code>private function returnWithError($errorMessage)\n{\n $_SESSION['error'] = $errorMessage;\n header('Location: ' . $this-&gt;signUpPage);\n exit();\n} \n</code></pre>\n<p>I would leave out the HTML tag in the error message. The HTML should be added by the code that outputs the error to the user. That makes more sense because it is the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">responsibility</a> of the output code to format the error. I will come back to this further on.</p>\n<p><strong>2:</strong> The methods <code>CheckName()</code> and <code>CheckEmail()</code> are very similar. They could both use a method that would look something like this:</p>\n<pre><code>private function existingColumnValue($columnName, $value)\n{ \n $statement = $this-&gt;database-&gt;prepare(&quot;SELECT userId FROM users WHERE $columnName = :value&quot;); \n $statement-&gt;execute([':value' =&gt; $value]);\n return $statement-&gt;rowCount() &gt; 0;\n}\n</code></pre>\n<p>This method simply checks whether a value exists in a column. It can be reused for all columns in the users table. Instead of redirecting, and exiting, it returns a boolean. Now you can rewrite <code>CheckName()</code> and <code>CheckEmail()</code> as:</p>\n<pre><code>public function existingName($name)\n{ \n return existingColumnValue('name', $name); \n}\n\npublic function existingEmail($email)\n{ \n return existingColumnValue('email', $email); \n}\n</code></pre>\n<p><strong>Responsibility</strong></p>\n<p>Now let's dive a bit deeper into what this class is meant to do. The main focus is: Accepting new users into the database, or not. That is its <em>responsibility</em>, no more no less. So setting up a database connection, redirecting, or formatting output, shouldn't be part of this class. The code at the bottom of your page should ideally look something like this:</p>\n<pre><code>$database = new PDO(.....);\n$users = new Users($database);\nif ($users-&gt;isValidNewUser($name, $email, $password)) {\n $userId = $users-&gt;addUser($name, $email, $password);\n}\nelse {\n $_SESSION['error'] = $users-&gt;getLastError();\n header('Location: signup.php');\n}\n</code></pre>\n<p>I've named the class after the database table it interacts with. The database handle is now created outside this class. Exactly how is up to you. I use two methods of the class: <code>isValidNewUser()</code> and <code>addUser()</code>. This also points to future extensions, of this class, with methods like <code>getUser()</code> and <code>removeUser()</code>. So all the <code>Users</code> class does now is interacting with the database. Of course you're wondering what <code>isValidNewUser()</code> and <code>addUser()</code> might look like:</p>\n<pre><code>private function setError($errorMessage)\n{\n $this-&gt;errorMessage = $errorMessage;\n return FALSE;\n}\n\npublic function getLastError()\n{\n return $this-&gt;errorMessage;\n}\n\npublic function isValidNewUser($name, $email, $password)\n{\n if (empty($name)) return setError('Please supply a name');\n if (empty($email)) return setError('Please supply an email address');\n if (empty($password)) return setError('Please supply a password');\n if (!this-&gt;isValidName($name)) return setError('Invalid name. The name should be between 10 and 25 characters. You can only use letters and numbers.');\n if ($this-&gt;existingName($name)) return setError('This name is already taken, please choose another');\n if ($this-&gt;existingEmail($email)) return setError('This email address is already registered');\n return TRUE;\n}\n\npublic function addUser($name, $email, $password)\n{\n $statement = $this-&gt;database-&gt;prepare(&quot;INSERT INTO users (name, email, pass, ip_address, http_client_ip, http_x_forwarded_for, http_user_agent) \n VALUES(:name, :email, :password_hash, :ip_address, :http_client_ip, :http_x_forwarded_for, :http_user_agent)&quot;); \n $statement-&gt;execute([':name' =&gt; $name,\n ':email' =&gt; $email,\n ':password_hash' =&gt; password_hash($password, PASSWORD_BCRYPT),\n ':ip_address' =&gt; $_SERVER['REMOTE_ADDR'],\n ':http_client_ip' =&gt; $_SERVER['HTTP_CLIENT_IP'],\n ':http_x_forwarded_for' =&gt; $_SERVER['HTTP_X_FORWARDED_FOR'],\n ':http_user_agent' =&gt; $_SERVER['HTTP_USER_AGENT']]);\n return $this-&gt;database-&gt;lastInsertID();\n}\n</code></pre>\n<p>By using two methods you can now skip the validation if you want to. This could be useful if you want to import users from somewhere else and you know that list is error free. But even if you use the validation, it will not redirect, it only sets an error message. I haven't written out the <code>isValidName()</code> method, because this code example is already quite long.</p>\n<p><strong>Minor other issues</strong></p>\n<ul>\n<li>You return <code>$this-&gt;conn</code> from <code>__construct()</code>. A constructor always returns the class it constructs, so a return of something else will not work.</li>\n<li>You abbreviate the name parameter to <code>$n</code> and the email parameter to <code>$e</code>. Why? Would <code>$name</code> and <code>$email</code> not be better?</li>\n<li>You use <code>$this-&gt;password</code> to store the password hash. It's not uncommon to do this, but it is confusing. What's in <code>$this-&gt;password</code>? Is it the password or a hash? Why not call it <code>$this-&gt;passwordHash</code>?</li>\n<li>You're using a lot of class level variables where they are not needed, for instance <code>$this-&gt;check_name</code> in <code>CheckName()</code>. Moreso, in <code>CheckEmail()</code> you don't do that.</li>\n<li>I think using <code>Check</code> in a method name is not very descriptive of what the method does.</li>\n<li>A short array syntax exists which replaces <code>array()</code> with <code>[]</code>. I prefer it, but <code>array()</code> does exactly the same.</li>\n</ul>\n<h2>Ideas for the future</h2>\n<p>There's one problem I haven't addressed: By separating the validation of the user data from the insert routine, we run the risk that this will not work properly. It is very unlikely, but suppose two different people, with the same name, sign up at exactly the same time. Both could have their name checked against the database, it is not found, and then both are inserted. These very unlikely events tend to occur, once in a blue moon, on very busy sites. These type of errors are very hard to debug.</p>\n<p>There are several ways to solve this problem. A classic way is to <a href=\"https://riptutorial.com/php/example/4186/database-transactions-with-pdo\" rel=\"nofollow noreferrer\">use transations</a>. Another method is to use <a href=\"https://www.tutorialspoint.com/how-to-form-a-mysql-conditional-insert\" rel=\"nofollow noreferrer\">a conditional insert query</a>: &quot;If this name doesn't exist, then insert this data.&quot;.</p>\n<p>Either way, I thought you should be aware of this minor problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T00:03:03.447", "Id": "496041", "Score": "1", "body": "Thank you very much, excellent explanation" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T11:30:54.367", "Id": "251859", "ParentId": "251835", "Score": "5" } } ]
{ "AcceptedAnswerId": "251859", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T21:13:57.857", "Id": "251835", "Score": "6", "Tags": [ "php" ], "Title": "Website user registration script in PHP" }
251835
<p>This is the initial skeleton for a short game written in Fennel for a Jam event. It runs sensibly, but I want to know if I'm missing something that could make the code more elegant as it's a bit confusing and smelly at the moment.</p> <p>Edit: since it seems people found this interesting, updated with the actual final release code. Feedback for future learning is still valuable.</p> <pre><code>(global cheat false) (global SCREEN_WIDTH 400) (global SCREEN_HEIGHT 240) (global START_LEVEL 1) (global GRID_SIZE 20) (global GRID_WIDTH (/ SCREEN_WIDTH GRID_SIZE)) (global GRID_HEIGHT (- (/ SCREEN_HEIGHT GRID_SIZE) 1)) (global ANIMATION_SPEED 0.5) (global BEAT_FREQ (/ 60 113)) (global MOVE_TIME BEAT_FREQ) (global PLAYER_MOVE_TIME 0.1) (global BASE_SEQUENCE [ 3 3 2 0 1 1 4 0 ]) (global DIRECTIONS [ {:dx -1 :dy 0} {:dx 0 :dy 1} {:dx 1 :dy 0} {:dx 0 :dy -1} ]) (global LEVELS [ {:tx 10 :ty 0 :seq [3 0 3 0 1 0 1 0] } {:tx 10 :ty 9 :seq [1 1 4 0 3 3 2 0] } {:tx 0 :ty 5 :seq [0 3 3 2 4 2 4 1 1 0] } {:tx 19 :ty 5 :seq [1 4 4 0 2 2 3 0] } ] ) (global GRID_BOTTOM (- SCREEN_HEIGHT GRID_SIZE)) (global BEATS_ON_RIBBON 8) (global RIBBON_TIME_FACTOR (/ SCREEN_WIDTH (* BEAT_FREQ BEATS_ON_RIBBON))) (global SYNC_TOLERANCE 0.1) (global FAIL_HEIGHT 50) (global FAIL_WIDTH 200) (global FAIL_EFFECT_TIME 0.5) (global font (love.graphics.newFont &quot;futurabook.ttf&quot; 35)) (global music (love.audio.newSource &quot;etiq2pr.mp3&quot; &quot;stream&quot;)) (require &quot;math&quot;) (require &quot;os&quot;) (macro update [x ...] `(set ,x (-&gt; ,x ,...))) (macro unless [x ...] `(when (not ,x) ,...)) (fn lightColor [] (love.graphics.setColor 0.69 0.68 0.65 1)) (fn darkColor [] (love.graphics.setColor 0.19 0.18 0.16 1)) (fn addListWrap [v d max] (let [r (+ v d)] (if (&lt;= r max) r 1))) (fn initNpcItem [x y sprite] {:x x :y y :dx 0 :dy 0 :idx 0 :idy 0 :moveTime 0 :moveSpeed 0 :frame (math.random 8) :frameTime 0 :maxFrame (if (= sprite 1) 8 10)}) (fn reInit [] ; Initialize player and basics. (global state { :items [ { :x 10 :y 9 :dx 0 :dy 0 :idx 0 :idy 0 :idir 0 :moveTime 0 :moveSpeed 0 :frame 1 :frameTime 0 } ] :beatTime 0 :masterTime 0 :seq (. (. LEVELS START_LEVEL) :seq) :seqStep 1 :pendingControl 0 :leadIn 4 :failed false :aniTime 0 :sillyAngle 0 :failEffect 0 :level START_LEVEL :message (love.graphics.newText font &quot;Ready?&quot;)}) (when (&gt; START_LEVEL 1) (let [p (. state.items 1) lastLevel (- START_LEVEL 1)] (set p.x (. (. LEVELS lastLevel) :tx)) (set p.y (. (. LEVELS lastLevel) :ty)))) ; Choose sprites at random or follow selected direction. (if (love.keyboard.isDown &quot;left&quot;) (do (set state.npcsprite 1) (set state.pcsprite 2)) (love.keyboard.isDown &quot;right&quot;) (do (set state.npcsprite 2) (set state.pcsprite 1)) (love.keyboard.isDown &quot;up&quot;) (do (set state.npcsprite 1) (set state.pcsprite 1)) (love.keyboard.isDown &quot;down&quot;) (do (set state.npcsprite 2) (set state.pcsprite 2)) (do (set state.npcsprite (math.random 2)) (set state.pcsprite (if (= state.npcsprite 2) 1 2)))) ;Load NPCs (for [ny 1 9 3] (for [nx 3 16 6] (table.insert state.items (initNpcItem nx ny state.npcsprite)))) ;Start music (music:seek 0) (music:setPitch 1) (love.audio.play music)) (fn curlevel [] (. LEVELS state.level)) ;; First time setup of everything. (fn love.load [arg] ;Set up mode and RNG (love.window.setMode SCREEN_WIDTH SCREEN_HEIGHT {:vsync 1}) (love.window.setTitle &quot;Crossing the Floor&quot;) (love.graphics.setBackgroundColor 0.69 0.68 0.65 1) (math.randomseed (os.time)) ;Load sprites (global frames [ [] [] ]) (for [x 1 8] (table.insert (. frames 1) (love.graphics.newImage (.. &quot;dn1_&quot; x &quot;.png&quot;)))) (for [x 1 10] (table.insert (. frames 2) (love.graphics.newImage (.. &quot;dn2_&quot; x &quot;.png&quot;)))) ;Load audio (global audio { :tick (love.audio.newSource &quot;metrotick.wav&quot; &quot;static&quot;)}) (global arrows { :left (love.graphics.newImage &quot;arrowlt.png&quot;) :right (love.graphics.newImage &quot;arrowrt.png&quot;) :up (love.graphics.newImage &quot;arrowup.png&quot;) :down (love.graphics.newImage &quot;arrowdn.png&quot;)}) (global arrowIndexes [ arrows.left arrows.down arrows.right arrows.up ]) (music:setLooping true) ;Initialize game, but then go straight to dormant state (kludgey) (reInit) (set state.failed true) (set state.failEffect FAIL_EFFECT_TIME) (music:stop) (set state.message (love.graphics.newText font &quot;Press Space&quot;))) ;; Called when player fails (fn setFail [reason] (unless state.failed (set state.failed true) (set state.failEffect 0) (set state.message (love.graphics.newText font reason)))) ;; Actually perform a move (fn startItemMove [i dx dy pl] (set i.dx dx) (set i.dy dy) (update i.x (+ dx)) (update i.y (+ dy)) (set i.moveTime (if (= pl 1) PLAYER_MOVE_TIME MOVE_TIME)) (set i.moveSpeed (/ GRID_SIZE i.moveTime))) ;; Set intended move (fn intendItemMove [i dx dy idir] (set i.idx dx) (set i.idy dy) (set i.idir idir)) (fn intendedDest [i] {:x (+ i.x i.idx) :y (+ i.y i.idy)}) ;; Resolve moves based on listed intentions. (fn resolveIntendedMoves [] (var ok false) ;; Bounds checks (for [x 1 (length state.items)] (set ok true) (let [i (. state.items x) ip (intendedDest i)] (if (&lt; ip.x 0) (set ok false) (&gt;= ip.x GRID_WIDTH) (set ok false) (&lt; ip.y 0) (set ok false) (&gt;= ip.y GRID_HEIGHT) (set ok false)) (unless ok (intendItemMove i 0 0 0) (when (= x 1) (setFail &quot;Floor Out!&quot;))))) ;; Check intended moves for collisions. (for [x 1 (length state.items)] (set ok true) (let [i (. state.items x) ip (intendedDest i)] (for [y (+ 1 x) (length state.items)] (let [j (. state.items y) jp (intendedDest j)] (when (and (= ip.x jp.x) (= ip.y jp.y)) (set ok false) (intendItemMove j 0 0 0)))) (unless ok (intendItemMove i 0 0 0) (when (= x 1) (setFail &quot;Crashed!&quot;))))) ;; Make moves that weren't eliminated above. (for [x 1 (length state.items)] (let [i (. state.items x)] (when (or (~= 0 i.idx) (~= 0 i.idy)) (startItemMove i i.idx i.idy x) (intendItemMove i 0 0 0))))) (fn advanceLevel [] (update state.level (+ 1)) (if (&gt; state.level (length LEVELS)) (do (set state.level 1) (set state.failed true) (set state.failEffect FAIL_EFFECT_TIME) (set state.message (love.graphics.newText font (.. &quot;Done! &quot; (math.ceil (* state.masterTime 10)))))) (do (set state.seqStep 1) (set state.seq (. (curlevel) :seq)) (set state.leadIn 4) (set state.message (love.graphics.newText font &quot;Change!&quot;))))) (fn beatMoveItems [] ;; Convert pending control to intended move. (when (not (or state.failed (&gt; state.leadIn 0))) (let [p (. state.items 1)] (if (= 1 state.pendingControl) (intendItemMove p -1 0 1) (= 2 state.pendingControl) (intendItemMove p 0 1 2) (= 3 state.pendingControl) (intendItemMove p 1 0 3) (= 4 state.pendingControl) (intendItemMove p 0 -1 4)))) ;; If there's a step this beat.. (let [st (. state.seq state.seqStep)] (when (&gt; st 0) ;; Fail player if pending control didn't match (when (and (~= state.pendingControl st) (= 0 state.leadIn) (not cheat)) (setFail (if (= state.pendingControl 0) &quot;Missed it!&quot; &quot;Wrong way!&quot;))) ;; Move all NPCs based on step (for [x 2 (length state.items)] (let [i (. state.items x) dst (. DIRECTIONS st)] (intendItemMove i dst.dx dst.dy st))))) ;; Clear pending control and advance step (set state.pendingControl 0) (update state.seqStep (addListWrap 1 (length state.seq))) (resolveIntendedMoves)) (fn love.update [dt] (update state.beatTime (+ dt)) (update state.masterTime (+ dt)) (update state.aniTime (+ dt)) (when (and state.failed (&lt; state.failEffect FAIL_EFFECT_TIME)) (update state.failEffect (+ dt)) (if (&gt;= state.failEffect FAIL_EFFECT_TIME) (music:stop) (music:setPitch (- 1 (/ state.failEffect FAIL_EFFECT_TIME))))) (unless state.failed (if (love.keyboard.isDown &quot;left&quot;) (set state.pendingControl 1) (love.keyboard.isDown &quot;down&quot;) (set state.pendingControl 2) (love.keyboard.isDown &quot;right&quot;) (set state.pendingControl 3) (love.keyboard.isDown &quot;up&quot;) (set state.pendingControl 4))) (when (and state.failed (love.keyboard.isDown &quot;space&quot;)) (reInit)) (let [musicTime (music:tell)] (when (&gt; (math.abs (- musicTime state.masterTime)) SYNC_TOLERANCE) (music:seek state.masterTime))) (when (&gt;= state.beatTime BEAT_FREQ) (update state.beatTime (- BEAT_FREQ)) (when (and (&gt; state.leadIn 0) (not state.failed)) (update state.leadIn (- 1)) (love.audio.play audio.tick) (set state.message (love.graphics.newText font (tostring state.leadIn)))) (beatMoveItems)) (let [p (. state.items 1)] (when (and (= p.x (. (curlevel) :tx)) (= p.y (. (curlevel) :ty)) (= p.moveTime 0)) (advanceLevel))) (let [doAni (&gt;= state.aniTime ANIMATION_SPEED)] (for [x 1 (length state.items)] (let [i (. state.items x)] (when (&gt; i.moveTime 0) (update i.moveTime (- dt)) (when (&lt;= i.moveTime 0) (set i.moveTime 0) (set i.dx 0) (set i.dy 0))) (when doAni (if (= x 1) (update i.frame (addListWrap 1 (if (= state.pcsprite 2) 10 8))) (update i.frame (addListWrap 1 (if (= state.npcsprite 2) 10 8))))))) (when doAni (update state.aniTime (- ANIMATION_SPEED))))) (fn drawGrid [] (for [x 0 SCREEN_WIDTH GRID_SIZE] (love.graphics.line x 0 x GRID_BOTTOM)) (for [y 0 GRID_BOTTOM GRID_SIZE] (love.graphics.line 0 y SCREEN_WIDTH y)) (let [tx (* GRID_SIZE (. (curlevel) :tx)) ty (* GRID_SIZE (. (curlevel) :ty))] (love.graphics.line tx ty (+ tx GRID_SIZE) (+ ty GRID_SIZE)) (love.graphics.line tx (+ ty GRID_SIZE) (+ tx GRID_SIZE) ty))) (fn drawItems [] (love.graphics.setColor 1 1 1 1) ; Without this, images are tinted (for [x 1 (length state.items)] (let [i (. state.items x) mi (* i.moveTime i.moveSpeed) realX (- (* i.x GRID_SIZE) (* i.dx mi)) realY (- (* i.y GRID_SIZE) (* i.dy mi)) goX (+ realX (/ GRID_SIZE 2)) goY (+ realY (/ GRID_SIZE 2))] (love.graphics.translate goX goY) (love.graphics.rotate state.sillyAngle) (love.graphics.translate (- 0 goX) (- 0 goY)) (if (= x 1) (if (= state.pendingControl 0) (love.graphics.draw (. (. frames state.pcsprite) i.frame) realX realY) (do (love.graphics.origin) (love.graphics.draw (. arrowIndexes state.pendingControl) realX realY))) (love.graphics.draw (. (. frames state.npcsprite) i.frame) realX realY))) (love.graphics.origin))) (fn drawRibbon [] (darkColor) (let [midLineX (/ (* (/ BEAT_FREQ 2) RIBBON_TIME_FACTOR) 2)] (love.graphics.line midLineX GRID_BOTTOM midLineX SCREEN_HEIGHT)) (love.graphics.setColor 1 1 1 1) ; Without this, images are tinted (var rSeqStep state.seqStep) (unless (= state.pendingControl 0) (love.graphics.draw (. arrowIndexes state.pendingControl) 0 GRID_BOTTOM)) (for [x 1 BEATS_ON_RIBBON] (let [beatStart (* x (* BEAT_FREQ RIBBON_TIME_FACTOR)) beatOffset (* state.beatTime RIBBON_TIME_FACTOR) beatX (- beatStart beatOffset)] (if (&gt; (. state.seq rSeqStep) 0) (do (love.graphics.setColor 1 1 1 1) (love.graphics.draw (. arrowIndexes (. state.seq rSeqStep)) beatX GRID_BOTTOM)) (do (darkColor) (love.graphics.line beatX (+ 10 GRID_BOTTOM) (+ 20 beatX) (+ 10 GRID_BOTTOM))))) (update rSeqStep (addListWrap 1 (length state.seq))))) (fn drawMessage [] (lightColor) (let [fx (- (/ SCREEN_WIDTH 2) (/ FAIL_WIDTH 2)) fy (- (/ SCREEN_HEIGHT 2) (/ FAIL_HEIGHT 2))] (love.graphics.rectangle &quot;fill&quot; fx fy FAIL_WIDTH FAIL_HEIGHT) (darkColor) (love.graphics.setLineWidth 3) (love.graphics.rectangle &quot;line&quot; fx fy FAIL_WIDTH FAIL_HEIGHT) (love.graphics.setLineWidth 1) (love.graphics.draw state.message (- (/ SCREEN_WIDTH 2) (/ (state.message:getWidth) 2)) (+ 3 fy)))) (fn love.wheelmoved [x y] (update state.sillyAngle (- (* math.pi 0.1 y)))) (fn love.draw [] (darkColor) (drawGrid) (drawItems) (drawRibbon) (when (or state.failed (&gt; state.leadIn 0)) (drawMessage))) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T21:18:54.863", "Id": "251836", "Score": "3", "Tags": [ "lisp" ], "Title": "LOVE2D-based grid-movement rhythm game in Fennel" }
251836
<p>I created a assembly REPL using some ctypes hacks to run the assembly code. Any suggestions on how I could improve it? I am unconcerned about some of the &quot;obvious&quot; security issues such as running raw assembly or using eval, since it only affects the user.</p> <p>Main script:</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3 import ctypes import re import readline import textwrap import traceback from keystone import KS_ARCH_X86, KS_MODE_64, Ks, KsError from utils.hazmat.shellcode import run_shellcode #ignore rbp and rsp REG_NAMES = [ &quot;rax&quot;, &quot;rbx&quot;, &quot;rcx&quot;, &quot;rdx&quot;, &quot;rsi&quot;, &quot;rdi&quot;, &quot;r8&quot;, &quot;r9&quot;, &quot;r10&quot;, &quot;r11&quot;, &quot;r12&quot;, &quot;r13&quot;, &quot;r14&quot;, &quot;r15&quot; ] FLAG_NAMES = { 0: (&quot;CF&quot;, &quot;carry&quot;), 2: (&quot;PF&quot;, &quot;parity&quot;), 4: (&quot;AF&quot;, &quot;adjust&quot;), 6: (&quot;ZF&quot;, &quot;zero&quot;), 7: (&quot;SF&quot;, &quot;sign&quot;), 8: (&quot;TF&quot;, &quot;trap&quot;), 9: (&quot;IF&quot;, &quot;interrupt&quot;), 10: (&quot;DF&quot;, &quot;direction&quot;), 11: (&quot;OF&quot;, &quot;overflow&quot;), 14: (&quot;NT&quot;, &quot;nested_task&quot;), 16: (&quot;RF&quot;, &quot;resume&quot;), 17: (&quot;VM&quot;, &quot;virtual_x86&quot;), 18: (&quot;AC&quot;, &quot;alignment_check&quot;), 19: (&quot;VIF&quot;, &quot;virtual_interrupt&quot;), 20: (&quot;VIP&quot;, &quot;virtual_interrupt_pending&quot;), 21: (&quot;ID&quot;, &quot;cpuid&quot;) } def create_array(length): array = (ctypes.c_uint64 * length)() addr = ctypes.cast(array, ctypes.c_void_p).value return (array, addr) class AsmRepl(): def __init__(self, to_print=None, stack_size=128): if to_print is None: self.to_print = {&quot;regs&quot;} else: self.to_print = to_print self.stack_size = stack_size self.regs = {reg: 0 for reg in REG_NAMES} self.ks = Ks(KS_ARCH_X86, KS_MODE_64) self.libc = ctypes.CDLL(&quot;libc.so.6&quot;) self.reg_save, self.reg_save_addr = create_array(len(self.regs)) self.stack, self.stack_addr = create_array(self.stack_size) self.rsp_save, self.rsp_save_addr = create_array(1) self.rbp_save, self.rbp_save_addr = create_array(1) self.flags, self.flags_addr = create_array(1) #4. save all the regs in the buffer #5. save flags to buffer #6. mov the saved rsp and rbp to rsp and rbp self.epilogue = self.ks.asm( &quot;; &quot;.join( f&quot;mov rax, {reg}; mov [{self.reg_save_addr+i*8}], rax&quot; for i, reg in enumerate(self.regs) ) + f&quot;;mov rax, [{self.rsp_save_addr}]; mov rsp, rax; &quot; + f&quot;mov rax, [{self.rbp_save_addr}]; mov rbp, rax; &quot; f&quot;pushfq; pop rax; mov [{self.flags_addr}], rax; ret; &quot;, as_bytes=True )[0] def loop(self): while True: try: inp = input(&quot;iasm&gt; &quot;) except KeyboardInterrupt: print() continue except EOFError: break if inp.startswith(&quot;!&quot;): self.run_python(inp[1:]) elif inp.startswith(&quot;set &quot;): self.set_display(inp.split(&quot; &quot;)[1:]) elif inp.startswith(&quot;reset &quot;) or inp.startswith(&quot;clear &quot;): self.clear_values(inp.split(&quot; &quot;)[1:]) elif inp in (&quot;help&quot;, &quot;?&quot;): self.print_help() elif inp in (&quot;exit&quot;, &quot;quit&quot;): return else: self.run(inp) def get_libc_address(self, func): return ctypes.cast(self.libc[func], ctypes.c_void_p).value def run_python(self, code): try: print( eval(code, { &quot;stack&quot;: list(self.stack), &quot;flags&quot;: list(self.flags), **self.regs }, {}) ) except Exception: traceback.print_exc() def set_display(self, values): &quot;&quot;&quot;add/remove values from to_print&quot;&quot;&quot; if not values: print(&quot;No arg provided&quot;) return if &quot;all&quot; in values: values = [&quot;stack&quot;, &quot;flags&quot;, &quot;regs&quot;] for val in values: if val.startswith(&quot;-&quot;): if val[1:] in self.to_print: self.to_print.remove(val[1:]) else: print(f&quot;{val} not in to_print&quot;) else: self.to_print.add(val) def clear_values(self, values): if not values: print(&quot;No arg provided&quot;) return if &quot;all&quot; in values: values = [&quot;stack&quot;, &quot;regs&quot;] for val in values: if val == &quot;stack&quot;: self.stack, self.stack_addr = create_array(self.stack_size) elif val == &quot;regs&quot;: self.regs = {reg: 0 for reg in REG_NAMES} else: print(f&quot;Invalid value {val}&quot;) def print_help(self): print( textwrap.dedent( &quot;&quot;&quot;\ Help: You can provide any valid x64 assembly code to be run. For example, &quot;mov rax, 1;&quot;. Other Commands: !&lt;code&gt; : evals python code with all registers, stack and flags as globals set [ stack | regs | flags_short | flags | all ] : set display of provided arg. Default is only regs. all sets stack, regs and flags. clear/reset [ stack | regs | all ] : clears value of provided arg help/? : prints this help page exit/quit/Ctrl-D : quits REPL&quot;&quot;&quot; ) ) def print_vals(self): if &quot;stack&quot; in self.to_print: print(list(self.stack)) flags = self.flags[0] if &quot;flags_short&quot; in self.to_print: print(&quot; &quot;.join(short for i, (short, _) in FLAG_NAMES.items() if flags &amp; (1 &lt;&lt; i))) if &quot;flags&quot; in self.to_print: print(&quot; &quot;.join(name for i, (_, name) in FLAG_NAMES.items() if flags &amp; (1 &lt;&lt; i))) if &quot;regs&quot; in self.to_print: print(self.regs) def assemble(self, asm): &quot;&quot;&quot;assemble into machine code&quot;&quot;&quot; #1. clear flags #2. set rsp and rbp to the stack location and save the original rsp and rbp #3. mov all of the saved regs to the right spot code = self.ks.asm( &quot;push 0; popfq;&quot; &quot;mov rbx, rsp; mov rcx, rbp;&quot; + f&quot;mov rbp, {self.stack_addr + len(self.stack) * 8}; mov rsp, rbp;&quot; + f&quot;mov rax, rbx; mov [{self.rsp_save_addr}], rax;&quot; + f&quot;mov rax, rcx; mov [{self.rbp_save_addr}], rax; &quot; + &quot;; &quot;.join(f&quot;mov {name}, {val}&quot; for name, val in self.regs.items()), as_bytes=True )[0] #4. run the user input # this is a separate function call to reset rip to 0 user_code = self.ks.asm(asm, as_bytes=True)[0] if user_code is not None: code += user_code #5. save all the regs in the buffer #6. save flags to buffer #7. mov the saved rsp and rbp to rsp and rbp code += self.epilogue return code def run(self, asm): &quot;&quot;&quot;run the assembly code&quot;&quot;&quot; #replaces &lt;func&gt; with libc address try: asm = re.sub(r&quot;&lt;(\w+)&gt;&quot;, lambda m: str(self.get_libc_address(m.group(1))), asm) except IndexError as e: print(e) return try: code = self.assemble(asm) except KsError as e: print(e) return if &quot;code&quot; in self.to_print: print(code) run_shellcode(code) self.regs = {reg: val for reg, val in zip(REG_NAMES, self.reg_save)} self.print_vals() if __name__ == &quot;__main__&quot;: import sys args = {&quot;regs&quot;} for arg in sys.argv[1:]: if arg.startswith(&quot;-&quot;) and arg[1:] in args: args.remove(arg[1:]) else: args.add(arg) AsmRepl(args).loop() </code></pre> <p>shellcode.py:</p> <pre class="lang-py prettyprint-override"><code>import ctypes libc = ctypes.CDLL(&quot;libc.so.6&quot;) #based on https://hacktracking.blogspot.com/2015/05/execute-shellcode-in-python.html def shellcode_to_func(shellcode: bytes, func_type=None): if func_type is None: func_type = ctypes.CFUNCTYPE(ctypes.c_int) buf = ctypes.c_void_p(libc.valloc(len(shellcode))) # allocate page aligned libc.mprotect(buf, len(shellcode), 7) # set to rwx ctypes.memmove(buf, shellcode, len(shellcode)) return ctypes.cast(buf, func_type) def run_shellcode(shellcode: bytes): return shellcode_to_func(shellcode)() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T22:40:32.147", "Id": "251839", "Score": "3", "Tags": [ "python", "python-3.x", "assembly" ], "Title": "Assembly REPL in Python using ctypes" }
251839
<p>Here is the sender and handler interfaces:</p> <pre><code>public interface ISender { Task SendAsync(object e); } public interface IHandler&lt;in TEvent&gt; { Task HandleAsync(TEvent e); } </code></pre> <p>So I register in IoC container a sender service implementation, which dispatches events to all the compatible <code>IHandler&lt;in T&gt;</code> implementations. I use Autofac with a contravariance source, but there could be something else:</p> <pre><code>[Service] public class Sender : ISender { public Sender(IServiceProvider provider) =&gt; Provider = provider; IServiceProvider Provider { get; } public async Task SendAsync(object e) { var eventType = e.GetType(); var handlerType = typeof(IHandler&lt;&gt;).MakeGenericType(eventType); var handlerListType = typeof(IEnumerable&lt;&gt;).MakeGenericType(handlerType); var method = handlerType.GetMethod(&quot;HandleAsync&quot;, new[] { eventType }); var handlers = ((IEnumerable)Provider.GetService(handlerListType)).OfType&lt;object&gt;(); await Task.WhenAll( handlers.Select(h =&gt; Task.Run(() =&gt; (Task)method.Invoke(h, new[] { e })) .ContinueWith(_ =&gt; { }))); } } </code></pre>
[]
[ { "body": "<p>I think the code would be more readable and easier to maintain if there was a method that handled the main calling of the other handlers.</p>\n<p>Unless there is a reason for provider to be a property I would make it a readonly field instead.</p>\n<pre><code>public class Sender : ISender\n{\n private readonly MethodInfo handlerMethodInfo;\n private readonly IServiceProvider provider;\n \n public Sender(IServiceProvider provider)\n {\n this.provider = provider;\n Func&lt;Task, object&gt; handlerMethod = HandleAsync&lt;object&gt;;\n handlerMethodInfo = handlerMethod.Method.GetGenericMethodDefinition(); \n }\n\n private async Task HandleAsync&lt;TEvent&gt;(TEvent e)\n {\n var handlers = provider.GetService&lt;IEnumerable&lt;IHandler&lt;TEvent&gt;&gt;&gt;();\n await Task.WhenAll(handlers.Select(h =&gt; h.HandleAsync(e)));\n }\n\n public async Task SendAsync(object e)\n {\n // Call the HandleAsync method\n var eventType = e.GetType();\n var method = handlerMethodInfo.MakeGenericMethod(eventType);\n await (Task)method.Invoke(this, new object[] { e });\n }\n}\n</code></pre>\n<p>In the constructor just getting a reference to the method needed to call and in a way that's type safe. Then in the SendAsync we will use reflection to call the private method to call the other classes. Now the reflection code is a lot smaller but the main logic is still in &quot;normal&quot; code in the HandleAsync method.</p>\n<p>We could turn the SendAsync into ExpressionTrees to only require reflection once but they come with a high price. Typically code would need to be called ~500 to make up the speed hit of compiling the expression vs reflection.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T03:34:40.490", "Id": "251846", "ParentId": "251840", "Score": "2" } } ]
{ "AcceptedAnswerId": "251846", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-08T23:22:29.187", "Id": "251840", "Score": "4", "Tags": [ "c#", "reflection", "task-parallel-library" ], "Title": "In-proc event dispatching through IoC container" }
251840
<p>This is my first time web scraping, and here is the code I whipped up:</p> <pre><code>from bs4 import BeautifulSoup import requests import time keywords = ['python'] for n in range(1000): res = requests.get(f&quot;https://stackoverflow.com/questions?tab=newest&amp;page={n}&quot;) time.sleep(3) # Sleep to avoid getting rate limited again soup = BeautifulSoup(res.text, &quot;html.parser&quot;) questions = soup.select(&quot;.question-summary&quot;) # List of all question summaries in the current page for que in questions: found = False tagged = False q = que.select_one('.question-hyperlink').getText() # Store the title of the question for a in que.find_all('a', href=True): u = a['href'] # Store the link if u.split('/')[1] == 'questions' and u.split('/')[2] != 'tagged': # If this link is a question and not a tag res2 = requests.get(&quot;https://stackoverflow.com&quot; + u) # Send request for that question time.sleep(3) # Extra precaution to avoid getting rate limited again soup2 = BeautifulSoup(res2.text, &quot;html.parser&quot;) body = str(soup2.select(&quot;.s-prose&quot;)) # This is the body of the question if any(key in body for key in keywords): found = True if 'tagged/python' in u: tagged = True if found and not tagged: print(q) </code></pre> <p>My code basically scrapes Stack Overflow posts newest first, and prints out all the posts that has the keyword &quot;python&quot; in its body, but no <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> tag. I want to know, <strong>did I implement the algorithm optimally? Can you show me where to improve?</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T21:31:22.663", "Id": "496034", "Score": "0", "body": "Can you comment/explain some of the code, especially towards the end?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T02:40:37.537", "Id": "496046", "Score": "0", "body": "@AMC Okay, done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T03:23:26.687", "Id": "496048", "Score": "0", "body": "@pacmaninbw Hello, what's up?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T03:50:36.560", "Id": "496052", "Score": "0", "body": "Didn't realize the comments were requested by the poster of the answer. It is better not to edit the question after it has been answered since everyone should see what the person that answered saw." } ]
[ { "body": "<p>The most important change: Check the tags <em>before</em> even getting the question's page. If it's tagged with <code>python</code>, then you know the question doesn't fit your criteria, regardless of what's in the body. Considering how popular the python tag is, this should save a good amount of time and processing.</p>\n<p>I introduced a <a href=\"https://requests.readthedocs.io/en/master/user/advanced/#session-objects\" rel=\"nofollow noreferrer\">requests.Session</a> object, which could improved performance. I also tweaked the variable names, and replaced the CSS selectors with the <code>find()</code>/<code>find_all()</code> methods. It's mostly a matter of personal preference, though.</p>\n<p>Keep in mind that this code contains no error handling.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import requests\nfrom bs4 import BeautifulSoup\n\ntag_keywords = ['python']\ncontent_keywords = ['python'.casefold()]\n\nres = []\n\nwith requests.Session() as sess:\n for page_num in range(1):\n new_questions_page_req = sess.get(f'https://stackoverflow.com/questions?tab=newest&amp;page={page_num}')\n soup = BeautifulSoup(new_questions_page_req.content, 'lxml')\n questions_container = soup.find('div', attrs={'id': 'questions', 'class': 'flush-left'})\n questions_list = questions_container.find_all('div', attrs={'class': 'question-summary'}, recursive=False)\n\n for curr_question_cont in questions_list:\n question_id = curr_question_cont['id'][17:]\n summary_elem = curr_question_cont.find('div', attrs={'class': 'summary'})\n tags_container = summary_elem.find('div', attrs={'class': 'tags'})\n tag_names = [elem.get_text() for elem in tags_container.find_all('a', recursive=False)]\n\n if not any(curr_tag in tag_keywords for curr_tag in tag_names):\n question_rel_url = summary_elem.find('h3').find('a', attrs={'class': 'question-hyperlink'})['href']\n question_page_req = sess.get(f'https://stackoverflow.com/q/{question_id}')\n question_page_soup = BeautifulSoup(question_page_req.content, 'lxml')\n question_body = question_page_soup.find('div', attrs={'class': 's-prose'})\n question_body_text = question_body.get_text().casefold()\n\n if any(curr_keyword in question_body_text for curr_keyword in content_keywords):\n res.append(question_id)\n\nprint(res)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T14:07:09.830", "Id": "496081", "Score": "0", "body": "Wouldn't `'python'.casefold()` do nothing because you've evaluated it before you used it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T03:07:58.560", "Id": "496148", "Score": "0", "body": "@Chocolate What do you mean? The result of the case-folding is used as the element in the list literal." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T23:06:05.053", "Id": "251877", "ParentId": "251841", "Score": "1" } } ]
{ "AcceptedAnswerId": "251877", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T02:23:46.543", "Id": "251841", "Score": "2", "Tags": [ "python", "performance", "beautifulsoup" ], "Title": "Beautifulsoup scrape posts that has the word python in it with no python tag" }
251841
<p>I want to create a wrapper around this third party package class so that I don't litter my app with calls to it. The idea being that if there are breaking changes to the package (rename the class or one of its members), or if I want to delete the package, I can just change my implementation of it in this one file. Here is the third party package class:</p> <pre><code>abstract class GetWidget&lt;T extends DisposableInterface&gt; extends GetStatelessWidget { GetWidget({Key key}) : super(key: key); final Set&lt;T&gt; _value = &lt;T&gt;{}; final String tag = null; T get controller { if (_value.isEmpty) _value.add(GetInstance().find&lt;T&gt;(tag: tag)); return _value.first; } @override Widget build(BuildContext context); } </code></pre> <p>Here is my attempt to wrap it (Vp is my app prefix identifying that it was created by my app):</p> <pre><code>abstract class VpWidget&lt;T extends DisposableInterface&gt; extends GetWidget&lt;T&gt; { VpWidget({Key key}) : super(key: key); @override T get controller { return super.controller; } } </code></pre> <p>It seems to work. The class is so small anyway so i don't think I can wrap anything more from it. Just wondering if this is an effective use of a wrapper for decoupling my app from the package, or if there is no use and I should just call the package class directly?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T03:41:17.687", "Id": "251847", "Score": "1", "Tags": [ "wrapper" ], "Title": "Wrapping a third party package class to achieve decoupling from the package" }
251847
<p>I saw this <a href="https://codereview.stackexchange.com/questions/85746/finding-pattern-score">problem in C++</a> on here and decided to try it in Python, which was much simpler. I've used the same problem blurb as in the link above, so they are consistent. I'm sure my code can be improved.</p> <p>You are given 3 strings: text, pre_text and post_text. Let L be a substring of text. For each substring L of text, we define pattern_score as follows:</p> <p><code>pre_text_pattern_score</code> = highest n, such that first n characters of L are equal to the last n characters of pre_text and occur in the same exact order.</p> <p><code>post_text_pattern_score</code> = highest n such that last n characters of L are equal to the first n characters of post_text and occur in the same exact order.</p> <p><code>pattern_score = pre_text_pattern_score + post_text_pattern_score</code>. For example, if L = &quot;nothing&quot;, pre_text = &quot;bruno&quot;, and post_text = &quot;ingenious&quot;, then</p> <p><code>pre_text_pattern_score</code> of L is 2 because the substring &quot;no&quot; is matched, and</p> <p><code>post_text_pattern_score</code> is 3 because the substring &quot;ing&quot; is matched.</p> <p><code>pattern_score</code> is 5 = 2 + 3 Your program should find a non-empty substring of text that maximizes <code>pattern_score</code>.</p> <p>If there is a tie, return the substring with the maximal <code>pre_text_pattern_score</code>.</p> <p>If multiple answers still have a tied score, return the answer that comes first lexicographically. Complete the definition of function string <code>calculateScore(string text, string prefix,string suffix)</code></p> <p>Constraints:</p> <ul> <li>text, pre_text, and post_text contain only lowercase letters ('a' - 'z')</li> <li>1 &lt;= |text| &lt;= 50</li> <li>1 &lt;= |pre-text| &lt;= 50</li> <li>1 &lt;= |post-text| &lt;= 50 (where |S| denotes the number of characters in string S)</li> </ul> <p>Sample case #1 text: &quot;nothing&quot; prefix: &quot;bruno&quot; suffix: &quot;ingenious&quot; Returns: &quot;nothing&quot; this is &quot;no&quot; from &quot;bru<strong>no</strong>&quot; and &quot;ing&quot; from &quot;<strong>ing</strong>enious&quot;, so &quot;nothing&quot; is returned.</p> <p>Sample case #2 text: &quot;<strong>a</strong>b&quot; prefix: &quot;b&quot; suffix: &quot;<strong>a</strong>&quot; Returns: &quot;a&quot;</p> <pre><code>def calculateScore(text, prefixString, suffixString): result = {} lenText = len(text) while lenText &gt; 0: for i in range(len(text) + 1 - lenText): substring = text[i:i + lenText] # calc the pre_text_pattern_score pre_text_pattern_score = min(len(prefixString), len(substring)) while pre_text_pattern_score &gt; 0 and substring[:pre_text_pattern_score] != prefixString[-pre_text_pattern_score:]: pre_text_pattern_score -= 1 # calc the post_text_pattern_score post_text_pattern_score = min(len(suffixString), len(substring)) while post_text_pattern_score &gt; 0 and substring[-post_text_pattern_score:] != suffixString[:post_text_pattern_score]: post_text_pattern_score-= 1 # calculate the pattern_score pattern_score = pre_text_pattern_score + post_text_pattern_score if not pattern_score in result: # resets the dictionary key result[pattern_score] = [] result[pattern_score].append(substring) lenText -= 1 # reduce lenText by 1 # store the highest key, so we can sort the right item to return maximum_pattern_score = max(result.keys()) # make sure to sort the lexicographically lowest string of the highest key result[maximum_pattern_score].sort() # return the lexicographically highest key return result[maximum_pattern_score][0] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T06:48:38.217", "Id": "495973", "Score": "2", "body": "The problem says the last n chars of the prefix hve to match the begining of the substring L, So, in sample case #2 the end of the prefix should be highlighted: \"habrah**abr**\"" } ]
[ { "body": "<h3>Code Style</h3>\n<p>Remember to follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> where you can. In particular, you should use <code>snake_case</code> rather than <code>camelCase</code>.</p>\n<h3>Making your Intentions Clear</h3>\n<p>Be sure to use comments to explain why your steps are needed rather than just what your code does:</p>\n<pre><code>lenText -= 1 # reduce lenText by 1\n</code></pre>\n<p>It is reasonably clear <em>what</em> your code is doing, but you could comment to explain why you're doing this. I'd be tempted to rewrite your substring finding loop as:</p>\n<pre><code># Iterate over all possible substrings of text\nfor start_index in range(0, len(text)):\n for end_index in range(start_index + 1, len(text) + 1):\n L = text[start_index:end_index]\n # Your logic here\n</code></pre>\n<h3>Storing Results</h3>\n<p>If you preferred, you could save some memory by only storing the patterns that have the highest score we've seen so far.</p>\n<pre><code># Stores the highest seen pattern score so far.\nhighest_score = 0\n# Stores the substrings of text that give highest_score.\nhighest_substrings = []\n</code></pre>\n<p>You then just need to check if your current score is strictly greater than the highest score seen so far and empty <code>highest_substrings</code>, then if you see a score greater than or equal to <code>highest_score</code> you add that substring to <code>highest_substrings</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T10:08:50.313", "Id": "251855", "ParentId": "251851", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T06:29:40.227", "Id": "251851", "Score": "4", "Tags": [ "python", "python-3.x", "strings", "regex" ], "Title": "Finding Pattern Score in Python" }
251851
<p>I have built this <a href="https://django-google-mailer.readthedocs.io/en/latest/" rel="nofollow noreferrer">Django Package</a> which is an alternative for sending mail to users using Gmail API. Everything is working fine. But the <strong>verify(self, request)</strong> method inside <code>gmailer/gmail.py</code> is not feeling great with the way I coded.</p> <p>I need to optimize this code and understand if there is a better style of coding that I can adapt here regarding error handling and writing testcases for this code. Here is the <a href="https://github.com/nikhiljohn10/django-google-mailer/" rel="nofollow noreferrer">source</a> to the Django package.</p> <pre><code>from base64 import urlsafe_b64encode from django.conf import settings from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from googleapiclient.errors import HttpError from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow _GMAIL_CONSTS = { 'GMAIL_SECRET': 'google_client_secret.json', 'GMAIL_SCOPES': [ &quot;https://www.googleapis.com/auth/gmail.metadata&quot;, &quot;https://www.googleapis.com/auth/gmail.send&quot;, ], 'GMAIL_REDIRECT': 'http://localhost:8000/gmailer/verify', 'GMAIL_USER': 'Django Mail Admin' } class Gmail: def __init__(self, client_secrets_file, scopes, redirect_uri, user): self.activated = False self.user = user self.outbox = [] self.flow = InstalledAppFlow.from_client_secrets_file( client_secrets_file=client_secrets_file, scopes=scopes, redirect_uri=redirect_uri) def authorize(self): return self.flow.authorization_url() def verify(self, request): code = request.GET.get('code', '') state = request.GET.get('state', '') if code and 'oauth_state' in request.session and state == request.session['oauth_state']: try: self.flow.fetch_token(code=code) self.credentials = self.flow.credentials self.service = build( 'gmail', 'v1', credentials=self.credentials) self.email = (self.service.users().getProfile( userId=&quot;me&quot;).execute())['emailAddress'] self.activated = True return { 'user': self.user, 'email': self.email, 'credentials': { 'token': self.credentials.token, 'refresh_token': self.credentials.refresh_token, 'token_uri': self.credentials.token_uri, 'client_id': self.credentials.client_id, 'client_secret': self.credentials.client_secret, 'scopes': self.credentials.scopes, }, } except Exception as err: self.revoke() return {'message': 'Unable to authorize request', 'error': str(err)} else: raise self.StateError() def revoke(self): if hasattr(self, 'service'): self.service.close() self.activated = False self.credentials = None self.service = None self.email = '' self.outbox = [] def _create_message(self, subject, message_text, from_email, recipient_list, html): message = MIMEMultipart() message['to'] = ', '.join(recipient_list) message['from'] = from_email message['subject'] = subject if html: message.attach(MIMEText(message_text, 'html')) else: message.attach(MIMEText(message_text, 'plain')) raw = urlsafe_b64encode(message.as_bytes()).decode() return {'raw': raw} def send_mail(self, subject, message, recipient_list, html=False): if self.activated: try: body = self._create_message( subject, message, self.user + &quot; &lt;&quot; + self.email + &quot;&gt;&quot;, recipient_list, html) sent_message = (self.service.users().messages().send( userId=&quot;me&quot;, body=body).execute()) print('Message sent with id: %s' % sent_message['id']) return sent_message except HttpError as error: pass else: raise self.UnauthorizedAPIError() def test_mail(self, subject=None, message=None, recipient_list=None): if self.activated: try: sub = subject or &quot;Django Google Mailer&quot; msg = message or &quot;Hi,\n\nWelcome to Django Site&quot; to = recipient_list or [self.email] sent_message = self.send_mail(sub, msg, to) self.outbox.append(sent_message) except Exception as e: print(e) else: raise self.UnauthorizedAPIError() @staticmethod def add_settings(): for attr in ['GMAIL_SECRET', 'GMAIL_SCOPES', 'GMAIL_REDIRECT', 'GMAIL_USER']: if not hasattr(settings, attr): setattr(settings, attr, _GMAIL_CONSTS[attr]) installed_apps = getattr(settings, 'INSTALLED_APPS', []) installed_apps += ['gmailer', ] setattr(settings, 'INSTALLED_APPS', installed_apps) return True class SettingError(Exception): def __init__(self, setting_name, error=None): self.message = setting_name + ' is missing/misconfigured inside Django Settings' self.error = error super().__init__(self.message) class StateError(Exception): def __init__(self, message=None, error=None): self.message = message or &quot;The state/code is not valid. Check the verification url.&quot; self.error = error super().__init__(self.message) class UnauthorizedAPIError(Exception): def __init__(self, message=None, error=None): self.message = message or &quot;Gmail API Service is not authorized. Contact site administrator.&quot; self.error = error super().__init__(self.message) if Gmail.add_settings(): mailer = Gmail( client_secrets_file=settings.GMAIL_SECRET, scopes=settings.GMAIL_SCOPES, redirect_uri=settings.GMAIL_REDIRECT, user=settings.GMAIL_USER) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T10:07:31.840", "Id": "251854", "Score": "2", "Tags": [ "python", "unit-testing", "django", "oauth" ], "Title": "Google Mailer app inside Django using OAuth 2.0" }
251854
<p>This is a simple game I am making in the arcade library of Python. I am quite new to object-oriented programming as well as game development. I feel like a lot of the code is inefficient, so I was hoping to get some improvements on the code. Any kind of suggestion is appreciated.</p> <pre><code>import os import random import arcade SPRITE_SCALING = 0.5 SPRITE_SCALING_COIN = 0.3 SPRITE_NATIVE_SIZE = 128 SPRITE_SIZE = int(SPRITE_NATIVE_SIZE * SPRITE_SCALING) SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 SCREEN_TITLE = &quot;Help Nick Adams!&quot; # Physics MOVEMENT_SPEED = 5 JUMP_SPEED = 12 GRAVITY = 0.5 class Room: # Class to hold info about rooms/levels def __init__(self): self.wall_list = self.goal_list = self.enemy_list = self.victory_sprite = None self.collectedCoins = 0 self.numCoins = 0 self.background = None def setup_room_1(): room = Room() room.wall_list = arcade.SpriteList(use_spatial_hash=True) room.enemy_list = arcade.SpriteList() room.goal_list = arcade.SpriteList(use_spatial_hash=True) room.victory_sprite = arcade.SpriteList(use_spatial_hash=True) # Draw platforms and ground for x in range(0, SCREEN_WIDTH, SPRITE_SIZE): wall = arcade.Sprite(&quot;:resources:images/tiles/grassMid.png&quot;, SPRITE_SCALING) wall.bottom = 0 wall.left = x room.wall_list.append(wall) for x in range(SPRITE_SIZE * 3, SPRITE_SIZE * 8, SPRITE_SIZE): wall = arcade.Sprite(&quot;:resources:images/tiles/grassMid.png&quot;, SPRITE_SCALING) wall.bottom = SPRITE_SIZE * 3 wall.left = x room.wall_list.append(wall) # Draw the crates for x in range(0, SCREEN_WIDTH, SPRITE_SIZE * 5): wall = arcade.Sprite(&quot;:resources:images/tiles/boxCrate_double.png&quot;, SPRITE_SCALING) wall.bottom = SPRITE_SIZE wall.left = x room.wall_list.append(wall) # Draw an enemy 1 enemy = arcade.Sprite(&quot;:resources:images/enemies/wormGreen.png&quot;, SPRITE_SCALING) enemy.bottom = SPRITE_SIZE enemy.left = SPRITE_SIZE * 2 enemy.change_x = 2 room.enemy_list.append(enemy) # -- Draw enemy2 on the platform enemy = arcade.Sprite(&quot;:resources:images/enemies/wormGreen.png&quot;, SPRITE_SCALING) enemy.bottom = SPRITE_SIZE * 4 enemy.left = SPRITE_SIZE * 4 # Set boundaries for enemy enemy.boundary_right = SPRITE_SIZE * 8 enemy.boundary_left = SPRITE_SIZE * 3 enemy.change_x = 2 room.enemy_list.append(enemy) # Set up coins for pos in [[128, 96], [418, 300], [670, 150]]: goal = arcade.Sprite(&quot;:resources:images/items/coinGold.png&quot;, SPRITE_SCALING) goal.center_x = pos[0] goal.center_y = pos[1] room.goal_list.append(goal) room.numCoins += 1 # Set up checkpoint/level clear flag = arcade.Sprite(&quot;:resources:images/tiles/signExit.png&quot;, SPRITE_SCALING) flag.center_x = 770 flag.center_y = 96 room.victory_sprite.append(flag) # Load the background image for this level. room.background = arcade.load_texture(&quot;:resources:images/backgrounds/abstract_1.jpg&quot;) return room def setup_room_2(): room = Room() room.wall_list = arcade.SpriteList(use_spatial_hash=True) room.enemy_list = arcade.SpriteList() room.goal_list = arcade.SpriteList(use_spatial_hash=True) room.victory_sprite = arcade.SpriteList(use_spatial_hash=True) # Set up walls for y in range(0, 800, 200): for x in range(100, 700, 64): wall = arcade.Sprite(&quot;:resources:images/tiles/boxCrate_double.png&quot;, SPRITE_SCALING) wall.center_x = x wall.center_y = y room.wall_list.append(wall) for pos in [[35, 40], [765, 80], [35, 280], [765, 480]]: wall = arcade.Sprite(&quot;:resources:images/tiles/grassHalf.png&quot;, SPRITE_SCALING) wall.center_x = pos[0] wall.center_y = pos[1] room.wall_list.append(wall) # Create the coins for i in range(50): # Create the coin instance # Coin image from kenney.nl goal = arcade.Sprite(&quot;:resources:images/items/coinGold.png&quot;, SPRITE_SCALING_COIN) # Boolean variable if we successfully placed the coin coin_placed_successfully = False # Keep trying until success while not coin_placed_successfully: # Position the coin goal.center_x = random.randrange(100, 700) goal.center_y = random.randrange(SCREEN_HEIGHT) # See if the coin is hitting a wall wall_hit_list = arcade.check_for_collision_with_list(goal, room.wall_list) # See if the coin is hitting another coin coin_hit_list = arcade.check_for_collision_with_list(goal, room.goal_list) if len(wall_hit_list) == 0 and len(coin_hit_list) == 0: coin_placed_successfully = True room.numCoins += 1 # Add the coin to the lists room.goal_list.append(goal) # Draw an enemy1 enemy = arcade.Sprite(&quot;:resources:images/enemies/fly.png&quot;, SPRITE_SCALING_COIN) enemy.bottom = SPRITE_SIZE enemy.left = SPRITE_SIZE * 2 enemy.boundary_right = SPRITE_SIZE * 8 + 60 enemy.boundary_left = SPRITE_SIZE * 1 + 60 enemy.change_x = 3 room.enemy_list.append(enemy) # Draw a enemy2 enemy = arcade.Sprite(&quot;:resources:images/enemies/fly.png&quot;, SPRITE_SCALING_COIN) enemy.bottom = SPRITE_SIZE * 4 enemy.left = SPRITE_SIZE * 4 enemy.boundary_right = SPRITE_SIZE * 8 enemy.boundary_left = SPRITE_SIZE * 3 enemy.change_x = 4 room.enemy_list.append(enemy) # Draw a enemy3 enemy = arcade.Sprite(&quot;:resources:images/enemies/fly.png&quot;, SPRITE_SCALING_COIN) enemy.bottom = SPRITE_SIZE * 7.2 enemy.left = SPRITE_SIZE * 4 enemy.boundary_right = SPRITE_SIZE * 8 + 80 enemy.boundary_left = SPRITE_SIZE * 3 enemy.change_x = 5.2 room.enemy_list.append(enemy) # Draw victory point flag = arcade.Sprite(&quot;:resources:images/tiles/signExit.png&quot;, SPRITE_SCALING) flag.center_x = 765 flag.center_y = 545 room.victory_sprite.append(flag) # Load the background image for this level. room.background = arcade.load_texture(&quot;:resources:images/backgrounds/abstract_1.jpg&quot;) return room def setup_room_3(): room = Room() room.wall_list = arcade.SpriteList(use_spatial_hash=True) room.goal_list = arcade.SpriteList() room.victory_sprite = arcade.SpriteList(use_spatial_hash=True) # Draw boundaries for y in (0, SCREEN_HEIGHT - SPRITE_SIZE): # Loop for each box going across for x in range(0, SCREEN_WIDTH, SPRITE_SIZE): wall = arcade.Sprite(&quot;:resources:images/tiles/stoneCenter.png&quot;, SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) # Create left and right column of boxes for x in (0, SCREEN_WIDTH - SPRITE_SIZE): # Loop for each box going across for y in range(SPRITE_SIZE, SCREEN_HEIGHT - SPRITE_SIZE, SPRITE_SIZE): wall = arcade.Sprite(&quot;:resources:images/tiles/stoneCenter.png&quot;, SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) # Create boxes in the middle for x in range(128, SCREEN_WIDTH, 134): for y in range(140, SCREEN_HEIGHT - 50, 170): wall = arcade.Sprite(&quot;:resources:images/tiles/brickGrey.png&quot;, 0.4) wall.center_x = x wall.center_y = y # wall.angle = 45 room.wall_list.append(wall) # Create coins for i in range(50): coin = arcade.Sprite(&quot;:resources:images/enemies/fishPink.png&quot;, 0.25) coin.center_x = random.randrange(100, 700) coin.center_y = random.randrange(100, 500) while coin.change_x == 0 and coin.change_y == 0: coin.change_x = random.randrange(-4, 5) coin.change_y = random.randrange(-4, 5) room.goal_list.append(coin) room.background = arcade.load_texture(&quot;:resources:images/backgrounds/abstract_1.jpg&quot;) return room class MainGame(arcade.Window): def __init__(self): super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) file_path = os.path.dirname(os.path.abspath(__file__)) os.chdir(file_path) # Sprites and set up player self.player_list = self.rooms = self.player_sprite = self.physics_engine = None self.current_room = self.view_left = self.view_bottom = self.collectedCoins = self.score = 0 self.game_over = False # Load sounds self.collect_goal_sound = arcade.load_sound(&quot;:resources:sounds/coin1.wav&quot;) self.jump_sound = arcade.load_sound(&quot;:resources:sounds/jump1.wav&quot;) # Starting room number self.current_room = 2 # list of rooms self.rooms = [] # Create the rooms room = setup_room_1() self.rooms.append(room) room = setup_room_2() self.rooms.append(room) room = setup_room_3() self.rooms.append(room) self.totalScore = 0 self.set_mouse_visible(False) def setup(self): &quot;&quot;&quot; Set up the game and initialize the variables. &quot;&quot;&quot; self.score = 0 # -- Set up the player self.player_sprite = arcade.Sprite(&quot;:resources:images/animated_characters/female_person/femalePerson_idle.png&quot;, SPRITE_SCALING) # Player start position according to room number if self.current_room == 0: self.player_sprite.center_x = 64 self.player_sprite.center_y = 270 elif self.current_room == 1: self.player_sprite.center_x = 35 self.player_sprite.center_y = 55 self.player_list = arcade.SpriteList() self.player_list.append(self.player_sprite) if self.current_room == 2: self.player_sprite = arcade.Sprite(&quot;:resources:images/animated_characters/female_person&quot; &quot;/femalePerson_climb0.png&quot;, SPRITE_SCALING) self.player_sprite.center_x = 340 self.player_sprite.center_y = 300 self.player_list.append(self.player_sprite) # Create a physics engine self.physics_engine = arcade.PhysicsEnginePlatformer(self.player_sprite, self.rooms[self.current_room].wall_list) def on_draw(self): arcade.start_render() arcade.draw_lrwh_rectangle_textured(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, self.rooms[self.current_room].background) self.rooms[self.current_room].wall_list.draw() self.rooms[self.current_room].goal_list.draw() if self.current_room != 2: self.rooms[self.current_room].enemy_list.draw() self.rooms[self.current_room].victory_sprite.draw() if self.current_room == 0: arcade.draw_text(&quot;Help Nick collect items for his coffee!&quot;, 250, 570, arcade.color.BLACK, 20) elif self.current_room == 1: arcade.draw_text(&quot;Help Nick collect grasshoppers!&quot;, 250, 570, arcade.color.BLACK, 20) elif self.current_room == 2: arcade.draw_text(&quot;Help Nick collect all the fish (use your mouse to catch them)&quot;, 250, 570, arcade.color.BLACK, 20) output1 = f&quot;Score: {self.score}&quot; arcade.draw_text(output1, 10, 560, arcade.color.WHITE, 14) output2 = f&quot;Total Score: {self.totalScore}&quot; arcade.draw_text(output2, 10, 540, arcade.color.WHITE, 14) # Draw all the sprites. self.player_list.draw() def on_key_press(self, key, modifiers): if key == arcade.key.UP: if self.physics_engine.can_jump(): self.player_sprite.change_y = JUMP_SPEED elif key == arcade.key.LEFT: self.player_sprite.change_x = -MOVEMENT_SPEED elif key == arcade.key.RIGHT: self.player_sprite.change_x = MOVEMENT_SPEED def on_key_release(self, key, modifiers): if key == arcade.key.LEFT or key == arcade.key.RIGHT: self.player_sprite.change_x = 0 def on_mouse_motion(self, x, y, dx, dy): if self.current_room == 2: self.player_sprite.center_x = x self.player_sprite.center_y = y def on_update(self, delta_time): if not self.game_over: if self.current_room == 0 or self.current_room == 1: # Move the enemies self.rooms[self.current_room].enemy_list.update() # Check each enemy for enemy in self.rooms[self.current_room].enemy_list: # If the enemy hit a wall, reverse if len(arcade.check_for_collision_with_list(enemy, self.rooms[self.current_room].wall_list)) &gt; 0: enemy.change_x *= -1 # If the enemy hit the left boundary, reverse elif enemy.boundary_left is not None and enemy.left &lt; enemy.boundary_left: enemy.change_x *= -1 # If the enemy hit the right boundary, reverse elif enemy.boundary_right is not None and enemy.right &gt; enemy.boundary_right: enemy.change_x *= -1 # Update the player using the physics engine self.physics_engine.update() # See if we hit any coins goal_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.rooms[self.current_room].goal_list) # Loop through each coin we hit (if any) and remove it for goal in goal_hit_list: # Remove the coin goal.remove_from_sprite_lists() # Play a sound arcade.play_sound(self.collect_goal_sound) # Count number of coins collected self.collectedCoins += 1 self.score += 1 self.totalScore += 1 if self.player_sprite.center_x &lt;= -10 or self.player_sprite.center_x &gt;= 800: self.player_sprite.change_x = 0 self.player_sprite.change_y = 0 self.player_sprite.center_x = 64 self.player_sprite.center_y = 270 # See if the player hit a worm if len(arcade.check_for_collision_with_list(self.player_sprite, self.rooms[self.current_room].enemy_list)) &gt; 0: self.game_over = True # See if the player hit the flag. If so, progress to next level if arcade.check_for_collision_with_list(self.player_sprite, self.rooms[ self.current_room].victory_sprite) and self.collectedCoins &gt;= self.rooms[ self.current_room].numCoins: # self.game_over = True self.current_room += 1 self.setup() elif self.current_room == 2: for coin in self.rooms[self.current_room].goal_list: coin.center_x += coin.change_x walls_hit = arcade.check_for_collision_with_list(coin, self.rooms[self.current_room].wall_list) for wall in walls_hit: if coin.change_x &gt; 0: coin.right = wall.left elif coin.change_x &lt; 0: coin.left = wall.right if len(walls_hit) &gt; 0: coin.change_x *= -1 coin.center_y += coin.change_y walls_hit = arcade.check_for_collision_with_list(coin, self.rooms[self.current_room].wall_list) for wall in walls_hit: if coin.change_y &gt; 0: coin.top = wall.bottom elif coin.change_y &lt; 0: coin.bottom = wall.top if len(walls_hit) &gt; 0: coin.change_y *= -1 # Generate a list of all sprites that collided with the player. hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.rooms[self.current_room].goal_list) # Loop through each colliding sprite, remove it, and add to the score. for coin in hit_list: coin.remove_from_sprite_lists() arcade.play_sound(self.collect_goal_sound) self.score += 1 self.totalScore += 1 if self.score &gt;= 50: self.game_over = True self.current_room = 0 self.setup() def main(): window = MainGame() window.setup() arcade.run() if __name__ == &quot;__main__&quot;: main() </code></pre>
[]
[ { "body": "<hr />\n<p>All the <code>range(0, number)</code> can be simplified to just <code>range(number)</code>.</p>\n<hr />\n<p>You can change</p>\n<pre><code>if self.current_room == 0 or self.current_room == 1:\n</code></pre>\n<p>to</p>\n<pre><code>if self.current_room in [0, 1]:\n</code></pre>\n<hr />\n<pre><code>if len(wall_hit_list) == 0 and len(coin_hit_list) == 0:\n</code></pre>\n<p>can be</p>\n<pre><code>if not wall_hit_list and not coin_hit_list:\n</code></pre>\n<hr />\n<p>You can change</p>\n<pre><code>if len(arcade.check_for_collision_with_list(self.player_sprite,\n self.rooms[self.current_room].enemy_list)) &gt; 0:\n self.game_over = True\n</code></pre>\n<p>to</p>\n<pre><code>if arcade.check_for_collision_with_list(self.player_sprite, self.rooms[self.current_room].enemy_list):\n self.game_over = True\n</code></pre>\n<hr />\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T10:27:33.173", "Id": "496064", "Score": "0", "body": "`if not (wall_hit_list or coin_hit_list):` using de morgan's law" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T15:42:26.877", "Id": "251862", "ParentId": "251857", "Score": "1" } } ]
{ "AcceptedAnswerId": "251862", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T10:45:19.047", "Id": "251857", "Score": "3", "Tags": [ "python", "performance", "object-oriented", "game" ], "Title": "Made a simple platformer game in arcade library of Python" }
251857
<p>I found one project on Internet and after I downloaded it, I got this message from <code>SonarQube</code>:</p> <blockquote> <p>Move constants to a class or enum.</p> </blockquote> <p>But, when I downloaded <code>SonarLint</code>, it did not report any code smell.</p> <p>This is the code:</p> <pre><code>@Repository public interface TaskRepository extends JpaRepository&lt;Task, Long&gt; { String QUERY = &quot;update Task t set t.isDeleted = true where t.id = :taskId&quot;; @Modifying @Query(QUERY) void deleteTaskById(@Param(value = &quot;taskId&quot;) long taskId); } </code></pre> <p>My question is: <strong>Should I remove constant <code>QUERY</code> and write it directly into <code>@Query</code> or I can leave it like this?</strong></p> <p><strong>Note:</strong> This is a short query and it can easily be put inside <code>@Query</code>. But I am also interested what would be the best practice if this query was longer(ex. if it had 300 characters or more).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T17:26:44.623", "Id": "496023", "Score": "0", "body": "The code provided isn't yours?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T18:36:03.927", "Id": "496024", "Score": "1", "body": "This reads like a Stack Overflow question. You have a specific problem with which you want help. Not a Code Review post where you are interested in any improvements to a section of code which you wrote. At minimum, I would suggest trying to remove QUERY. Because I don't think that's even your problem. QUERY is not a constant. It's a variable. The two constants in that code are \"taskId\" and \"update Task t set t.isDeleted = true where t.id = :taskId\". I would think that it is complaining about \"taskId\", as that looks like the kind of thing that could be stored as an enum." } ]
[ { "body": "<p>Personally, I do not see the reason why this needs to be a variable in the first place. If I were you I would either move this into the <code>@Query</code> annotation or better yet I would create a <code>@NamedQuery</code> under your <code>Task</code> entity class.</p>\n<p>Also on a side note, I would avoid naming the repository method <code>deleteTaskById</code> as this name implies that a matching object will be deleted from the database. Since this is not the case here, I would rename the method to <code>markTaskAsDeleted</code> to avoid ambiguity.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T16:12:39.630", "Id": "496015", "Score": "0", "body": "I agree with you.\nBut, can you tell me what would you do if query was not short as this one(for example if it had 200 characters or more)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T16:19:30.910", "Id": "496017", "Score": "1", "body": "It depends on your use case. If this concerns static queries (i.e ones that do not change dynamically) I would have them all organized under their entity class as named queries. Otherwise, I would look into using the `Criteria` API." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T16:10:48.063", "Id": "251864", "ParentId": "251863", "Score": "2" } } ]
{ "AcceptedAnswerId": "251864", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T15:59:06.230", "Id": "251863", "Score": "1", "Tags": [ "java", "spring" ], "Title": "Sonar: Move constants to a class or enum" }
251863
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251764/231235">A ones Function for Boost.MultiArray in C++</a>. Thanks to <a href="https://codereview.stackexchange.com/a/251832/231235">G. Sliepen's answer</a>, the mentioned method which can set various initial value is better in generic purpose usage. However, the previous function specified the input type which must be <code>boost::detail::multi_array::extent_gen&lt;NumDims&gt;</code>. The type issue happened in some cases, an example is as below. The object <code>filled_multi_array1</code> is created first with <code>filled_multi_array(boost::extents[3][4][2], 1.0)</code>. This works well. I want to create a <code>filled_multi_array2</code> object which size is as same as <code>filled_multi_array1</code> and the initial value is <code>2.0</code>. This doesn't work in existed version of <code>filled_multi_array</code> function.</p> <pre><code>auto filled_multi_array1 = filled_multi_array(boost::extents[3][4][2], 1.0); auto filled_multi_array2 = filled_multi_array&lt;double, filled_multi_array1.dimensionality&gt;(filled_multi_array1.shape(), 2.0); for (decltype(filled_multi_array2)::index i = 0; i != 3; ++i) for (decltype(filled_multi_array2)::index j = 0; j != 4; ++j) for (decltype(filled_multi_array2)::index k = 0; k != 2; ++k) std::cout &lt;&lt; filled_multi_array2[i][j][k] &lt;&lt; std::endl; </code></pre> <p>Then, I found that the type returned from <code>.shape()</code> function is this one <code>const boost::detail::multi_array::multi_array_base::size_type*</code>. It seems that the another function overloading is needed to handle the above <code>filled_multi_array2</code> case. The experimental code of the <code>filled_multi_array</code> function with the input type <code>const boost::detail::multi_array::multi_array_base::size_type*</code> is as follows.</p> <pre><code>template&lt;class T, std::size_t NumDims&gt; auto filled_multi_array(const boost::detail::multi_array::multi_array_base::size_type* size, const T&amp; value) { boost::multi_array&lt;T, NumDims&gt; output(reinterpret_cast&lt;boost::array&lt;size_t, NumDims&gt; const&amp;&gt;(*size)); std::fill_n(output.data(), output.num_elements(), value); return output; } </code></pre> <p>With this overloaded function, <code>filled_multi_array2</code> object can be generated successfully and the output is like:</p> <pre><code>2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 </code></pre> <p>The full implementation of <code>filled_multi_array</code> template function:</p> <pre><code>template&lt;class T, std::size_t NumDims&gt; auto filled_multi_array(boost::detail::multi_array::extent_gen&lt;NumDims&gt; size, const T&amp; value) { boost::multi_array&lt;T, NumDims&gt; output(size); std::fill_n(output.data(), output.num_elements(), value); return output; } template&lt;class T, std::size_t NumDims&gt; auto filled_multi_array(const boost::detail::multi_array::multi_array_base::size_type* size, const T&amp; value) { boost::multi_array&lt;T, NumDims&gt; output(reinterpret_cast&lt;boost::array&lt;size_t, NumDims&gt; const&amp;&gt;(*size)); std::fill_n(output.data(), output.num_elements(), value); return output; } </code></pre> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/251764/231235">A ones Function for Boost.MultiArray in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>The another overloaded <code>filled_multi_array</code> function has been added here.</p> </li> <li><p>Why a new review is being asked for?</p> <p>I am trying to handle both cases, including the one with the specified shape directly and the other one with <code>.shape()</code> function (the shape is referenced from another Boost.MultiArray object). If there is any possible improvement, please let me know.</p> </li> </ul>
[]
[ { "body": "<p>It looks bad, but that's not your fault. <code>boost::multi_array</code> just has a terrible interface. In any case, you want to avoid passing the shape twice, because this can give problems:</p>\n<pre><code>auto large_array = filled_multi_array(boost::extents[1][2][3][4][5], 1.0);\nauto small_array = filled_multi_array(boost::extents[1], 1.0);\nauto another_array = filled_multi_array&lt;double, large_array.dimensionality&gt;(small_array.shape(), 2.0);\n</code></pre>\n<p>The above will compile without errors, but might crash at runtime, since <code>small_array.shape()</code> is a pointer to an array that doesn't have as many elements as expected. I don't know why the interface is so terrible, if they would have <code>.shape()</code> return a (reference to a) <code>boost::array&lt;size_t, NumDims&gt;</code> it would all be checkable at compile time and without needing <code>reinterpret_cast</code>s.</p>\n<p>So to prevent errors, you want to avoid having to pass two separate pieces of information. One possibility is just passing the array whose shape you want to copy as an argument:</p>\n<pre><code>template&lt;class T, std::size_t NumDims&gt;\nauto filled_multi_array(const boost::multi_array&lt;T, NumDims&gt; &amp;input, const T&amp; value) {\n boost::multi_array&lt;T, NumDims&gt; output(reinterpret_cast&lt;boost::array&lt;size_t, NumDims&gt; const&amp;&gt;(input.shape()));\n std::fill_n(output.data(), output.num_elements(), value);\n return output;\n}\n</code></pre>\n<p>But that interface will create confusion: does the following line modify the input?</p>\n<pre><code>filled_multi_array(filled_multi_array1, 2.0);\n</code></pre>\n<p>Another possibility is to keep just the first <code>filled_multi_array()</code> variant, but create a helper function to create a <code>extent_gen</code> from a <code>multi_array</code>:</p>\n<pre><code>template&lt;std::size_t NumDims&gt;\nauto get_extents(const boost::multi_array &amp;input) {\n boost::detail::multi_array::extent_gen&lt;NumDims&gt; output;\n\n // Set the shape of output according to input.shape(),\n // left as an exercise to the reader.\n ...\n\n return output;\n}\n</code></pre>\n<p>And then you can use it like so:</p>\n<pre><code>auto filled_multi_array1 = filled_multi_array(boost::extents[3][4][2], 1.0);\nauto filled_multi_array2 = filled_multi_array(get_extents(filled_multi_array1), 2.0);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T23:10:34.867", "Id": "251880", "ParentId": "251865", "Score": "2" } } ]
{ "AcceptedAnswerId": "251880", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T16:27:09.110", "Id": "251865", "Score": "3", "Tags": [ "c++", "boost" ], "Title": "A filled_multi_array Template Function for Boost.MultiArray in C++" }
251865
<p>I have implemented a structure to handle BitVector64 (default System library support only 32 bits). In the implementation i have added some custom method to manipulate bits inside the vector.</p> <p>I would like comments and suggestions about the implementation, because i am concerned about correctness and performance.</p> <p>Ps : i had to omit an output string, because text inside create problem to the parser here (so the code is was not displayed well in the page). Any way you can find the full code in this git repository : <a href="https://github.com/ItSkary/BitVector64" rel="nofollow noreferrer">https://github.com/ItSkary/BitVector64</a></p> <pre><code>public struct BitVector64 : ICloneable { private readonly static UInt64[] _MASK = new UInt64[] { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000, 0x10000, 0x20000, 0x40000, 0x80000, 0x100000, 0x200000, 0x400000, 0x800000, 0x1000000, 0x2000000, 0x4000000, 0x8000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000, 0x100000000, 0x200000000, 0x400000000, 0x800000000, 0x1000000000, 0x2000000000, 0x4000000000, 0x8000000000, 0x10000000000, 0x20000000000, 0x40000000000, 0x80000000000, 0x100000000000, 0x200000000000, 0x400000000000, 0x800000000000, 0x1000000000000, 0x2000000000000, 0x4000000000000, 0x8000000000000, 0x10000000000000, 0x20000000000000, 0x40000000000000, 0x80000000000000, 0x100000000000000, 0x200000000000000, 0x400000000000000, 0x800000000000000, 0x1000000000000000, 0x2000000000000000, 0x4000000000000000, 0x8000000000000000, }; private readonly static Byte[] _REVERSE = new Byte[] { 0 , 128 , 64 , 192 , 32 , 160 , 96 , 224 , 16 , 144 , 80 , 208 , 48 , 176 , 112 , 240 , 8 , 136 , 72 , 200 , 40 , 168 , 104 , 232 , 24 , 152 , 88 , 216 , 56 , 184 , 120 , 248 , 4 , 132 , 68 , 196 , 36 , 164 , 100 , 228 , 20 , 148 , 84 , 212 , 52 , 180 , 116 , 244 , 12 , 140 , 76 , 204 , 44 , 172 , 108 , 236 , 28 , 156 , 92 , 220 , 60 , 188 , 124 , 252 , 2 , 130 , 66 , 194 , 34 , 162 , 98 , 226 , 18 , 146 , 82 , 210 , 50 , 178 , 114 , 242 , 10 , 138 , 74 , 202 , 42 , 170 , 106 , 234 , 26 , 154 , 90 , 218 , 58 , 186 , 122 , 250 , 6 , 134 , 70 , 198 , 38 , 166 , 102 , 230 , 22 , 150 , 86 , 214 , 54 , 182 , 118 , 246 , 14 , 142 , 78 , 206 , 46 , 174 , 110 , 238 , 30 , 158 , 94 , 222 , 62 , 190 , 126 , 254 , 1 , 129 , 65 , 193 , 33 , 161 , 97 , 225 , 17 , 145 , 81 , 209 , 49 , 177 , 113 , 241 , 9 , 137 , 73 , 201 , 41 , 169 , 105 , 233 , 25 , 153 , 89 , 217 , 57 , 185 , 121 , 249 , 5 , 133 , 69 , 197 , 37 , 165 , 101 , 229 , 21 , 149 , 85 , 213 , 53 , 181 , 117 , 245 , 13 , 141 , 77 , 205 , 45 , 173 , 109 , 237 , 29 , 157 , 93 , 221 , 61 , 189 , 125 , 253 , 3 , 131 , 67 , 195 , 35 , 163 , 99 , 227 , 19 , 147 , 83 , 211 , 51 , 179 , 115 , 243 , 11 , 139 , 75 , 203 , 43 , 171 , 107 , 235 , 27 , 155 , 91 , 219 , 59 , 187 , 123 , 251 , 7 , 135 , 71 , 199 , 39 , 167 , 103 , 231 , 23 , 151 , 87 , 215 , 55 , 183 , 119 , 247 , 15 , 143 , 79 , 207 , 47 , 175 , 111 , 239 , 31 , 159 , 95 , 223 , 63 , 191 , 127 , 255 , }; private UInt64 _data; /// &lt;devdoc&gt; /// &lt;para&gt;Initializes a new instance of the BitVector64 structure with the specified internal data.&lt;/para&gt; /// &lt;/devdoc&gt; public BitVector64(UInt64 data = 0) { _data = (UInt64)data; } /// &lt;devdoc&gt; /// &lt;para&gt;Initializes a new instance of the BitVector64 structure with the information in the specified /// value.&lt;/para&gt; /// &lt;/devdoc&gt; public BitVector64(BitVector64 value) { _data = value.Data; } /// &lt;devdoc&gt; /// &lt;para&gt;Initializes a new instance of the BitVector64 structure with the information in the specified /// value. /// Note : not particulary efficient /// &lt;/para&gt; /// &lt;/devdoc&gt; public BitVector64(bool[] value) { if (value == null) throw new ArgumentNullException(&quot;value&quot;); if (value.Length &lt;= 0 || value.Length &gt; 64) throw new IndexOutOfRangeException(&quot;The array provided sould be bound to the lenght between [1,64].&quot;); _data = 0; for (int i = 0; i &lt; value.Length; i++) { if (value[i]) this.Set(i); } } /// &lt;devdoc&gt; /// returns the raw data stored in this bit vector... /// &lt;/devdoc&gt; public UInt64 Data { get { return (UInt64)_data; } } public override bool Equals(object o) { if (!(o is BitVector64)) { return false; } return _data == ((BitVector64)o).Data; } public override int GetHashCode() { return base.GetHashCode(); } /// &lt;summary&gt; /// Return the current status of a flag in the BitVector /// &lt;/summary&gt; /// &lt;param name=&quot;index&quot;&gt;&gt;ndex of the bit to get&lt;/param&gt; /// &lt;returns&gt;State of selected bit&lt;/returns&gt; public bool Get(int index) { if (index &lt; 0 || index &gt; 63) throw new IndexOutOfRangeException($&quot;Index should be bount to [0-63] values, actual Index :{index}&quot;); return (_data &amp; _MASK[index]) != 0; } /// &lt;summary&gt; /// Mark as On a bit in the vector /// &lt;/summary&gt; /// &lt;param name=&quot;index&quot;&gt;Index of the bit to mark (left to right from 0 to 63)&lt;/param&gt; public BitVector64 Set(int index) { if (index &lt; 0 || index &gt; 63) throw new IndexOutOfRangeException($&quot;Index should be bount to [0-63] values, actual Index :{index}&quot;); _data |= _MASK[index]; return this; } /// &lt;summary&gt; /// Mark as Off a bit in the vector /// &lt;/summary&gt; /// &lt;param name=&quot;index&quot;&gt;Index of the bit to mark (left to right from 0 to 63)&lt;/param&gt; public BitVector64 Unset(int index) { if (index &lt; 0 || index &gt; 63) throw new IndexOutOfRangeException($&quot;Index should be bount to [0-63] values, actual Index :{index}&quot;); _data &amp;= ~_MASK[index]; return this; } /// &lt;summary&gt; /// Change the bit status /// &lt;/summary&gt; /// &lt;param name=&quot;index&quot;&gt;Index of bit to change&lt;/param&gt; /// &lt;param name=&quot;status&quot;&gt;The new bit status (true = 1, false = 0)&lt;/param&gt; public BitVector64 Apply(int index, bool status) { return status ? this.Set(index) : this.Unset(index); } public override string ToString() { StringBuilder sb = new StringBuilder(64); UInt64 locdata = _data; for (int i = 0; i &lt; 64; i++) { if ((locdata &amp; 0x01) != 0) { sb.Append(&quot;1&quot;); } else { sb.Append(&quot;0&quot;); } locdata &gt;&gt;= 1; } return sb.ToString(); } /// &lt;summary&gt; /// Debug only, print a formatted bitString /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string StringFormatted() { char[] bits = this.ToString().ToCharArray(); List&lt;char&gt; temp = bits.ToList(); temp.Reverse(); bits = temp.ToArray(); string[] trunk = new string[8]; for (int i = 7; i &gt;= 0; i--) trunk[7-i] = string.Join(&quot; &quot;, bits.Skip(i * 8).Take(8)); string result = $@&quot;!!Omitted!!&quot;; return result; } /// &lt;summary&gt; /// Apply the bits starting form certain bit of the bitvector, till a certain length of the supplied bits. /// &lt;/summary&gt; /// &lt;param name=&quot;bits&quot;&gt;UInt64 that retain the interesting bits&lt;/param&gt; /// &lt;param name=&quot;bitVectorApplyPoint&quot;&gt;Starting point in the current bitvector [0,63]&lt;/param&gt; /// &lt;param name=&quot;bitsLength&quot;&gt;Define how many of the supplied bits have to be taken into account [1,64].If there is not enought space after the apply point, bits are discarded.&lt;/param&gt; public BitVector64 InsertBits (UInt64 bits, int bitVectorApplyPoint, int bitsLength) { if (bitVectorApplyPoint &lt; 0 || bitVectorApplyPoint &gt; 63) throw new IndexOutOfRangeException($&quot;BitVectorApplyPoint should be bount to [0,63] values, actual Value :{bitVectorApplyPoint}&quot;); if (bitsLength &lt; 1 || bitsLength &gt; 64) throw new IndexOutOfRangeException($&quot;BitsLength should be bount to [1,64] values, actual Value :{bitsLength}&quot;); UInt64 temporary = 0; int firstStageBlankShift = 0; int secondStageBlankShift = 64 - bitsLength; int thirdStageBlankShift = 0; //first stage of original data, if any if (bitVectorApplyPoint &gt; 0) { firstStageBlankShift = 64 - bitVectorApplyPoint; temporary = (_data &lt;&lt; firstStageBlankShift) &gt;&gt; firstStageBlankShift; } //second stage of inserted data (mandatory) { secondStageBlankShift = 64 - bitsLength; temporary |= ((bits &lt;&lt; secondStageBlankShift) &gt;&gt; secondStageBlankShift) &lt;&lt; bitVectorApplyPoint; } //third stage of original data, if any thirdStageBlankShift = bitVectorApplyPoint + secondStageBlankShift; if (thirdStageBlankShift &lt; 64) { temporary |= (_data &gt;&gt; thirdStageBlankShift) &lt;&lt; thirdStageBlankShift; } _data = temporary; return this; } /// &lt;summary&gt; /// Reverse the bits of the current BitVector64 /// &lt;/summary&gt; /// &lt;returns&gt;Return the current BitVector64&lt;/returns&gt; public BitVector64 Reverse() { UInt64 b0 = _data &amp; 0xFF; UInt64 b1 = _data &amp; 0xFF00; UInt64 b2 = _data &amp; 0xFF0000; UInt64 b3 = _data &amp; 0xFF000000; UInt64 b4 = _data &amp; 0xFF00000000; UInt64 b5 = _data &amp; 0xFF0000000000; UInt64 b6 = _data &amp; 0xFF000000000000; UInt64 b7 = _data &amp; 0xFF00000000000000; b0 = _REVERSE[b0]; b1 = _REVERSE[b1&gt;&gt;8 ]; b2 = _REVERSE[b2&gt;&gt;16]; b3 = _REVERSE[b3&gt;&gt;24]; b4 = _REVERSE[b4&gt;&gt;32]; b5 = _REVERSE[b5&gt;&gt;40]; b6 = _REVERSE[b6&gt;&gt;48]; b7 = _REVERSE[b7&gt;&gt;56]; _data = 0; _data |= (b0 &lt;&lt; 56) | (b1 &lt;&lt; 48) | (b2 &lt;&lt; 40) | (b3 &lt;&lt; 32) | (b4 &lt;&lt; 24) | (b5 &lt;&lt; 16) | (b6 &lt;&lt; 8) | b7 ; return this; } /// &lt;summary&gt; /// Rotate the current array by a given numer of bits. /// &lt;/summary&gt; /// &lt;param name=&quot;bits&quot;&gt;Numbe of bits that need to be rotate [-256,256]&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public BitVector64 Rotate(int bits) { if (bits &lt; -256 || bits &gt; 256) throw new IndexOutOfRangeException($&quot;Bits should be bount to [-256,256] values, actual Value :{bits}&quot;); _data = (_data &lt;&lt; bits) | (_data &gt;&gt; (64 - bits)); return this; } /// &lt;summary&gt; /// Shift the current array by a given numer of bits. /// &lt;/summary&gt; /// &lt;param name=&quot;bits&quot;&gt;Numbe of bits that need to be rotate [-64,64]&lt;/param&gt; public BitVector64 Shift(int bits) { if (bits &lt; -63 || bits &gt; 63) throw new IndexOutOfRangeException($&quot;Bits should be bount to [-63,63] values, actual Value :{bits}&quot;); _data = (bits &gt; 0) ? (_data &lt;&lt; bits) : (_data &gt;&gt; -bits); return this; } /// &lt;summary&gt; /// Join the data of two vector /// &lt;/summary&gt; /// &lt;param name=&quot;vector&quot;&gt;Vector to join with current vector&lt;/param&gt; /// &lt;returns&gt;The current vector update&lt;/returns&gt; public BitVector64 Union(BitVector64 vector) { _data |= vector.Data; return this; } /// &lt;summary&gt; /// Intersect the data of two vector /// &lt;/summary&gt; /// &lt;param name=&quot;vector&quot;&gt;Vector to intersect with current vector&lt;/param&gt; /// &lt;returns&gt;The current vector update&lt;/returns&gt; public BitVector64 Intersect(BitVector64 vector) { _data &amp;= vector.Data; return this; } /// &lt;summary&gt; /// Flip all bits in the current BitVector64 /// &lt;/summary&gt; /// &lt;returns&gt;Return the updated BitVector64&lt;/returns&gt; public BitVector64 Negate() { _data = ~_data; return this; } /// &lt;summary&gt; /// Join the data of two vector, excluding the intersection /// &lt;/summary&gt; /// &lt;param name=&quot;vector&quot;&gt;Vector to exclusevelly unite with current vector&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public BitVector64 ExclusiveUnion(BitVector64 vector) { _data ^= vector.Data; return this; } /// &lt;summary&gt; /// Get the bit that are in current BitVector64 but not in the given one. /// &lt;/summary&gt; /// &lt;param name=&quot;vector&quot;&gt;Provided BitVector64&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public BitVector64 Left(BitVector64 vector) { _data |= vector.Data; _data &amp;= (~vector.Data); return this; } /// &lt;summary&gt; /// Get the bit that are in the given BitVector64 but not in the current one /// &lt;/summary&gt; /// &lt;param name=&quot;vector&quot;&gt;Provided BitVector64&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public BitVector64 Right (BitVector64 vector) { UInt64 original = _data; _data |= vector.Data; _data &amp;= (~original); return this; } /// &lt;summary&gt; /// Return a new BitVector64 built arround the given subset /// &lt;/summary&gt; /// &lt;param name=&quot;subsetStart&quot;&gt;Start of selection [0,63]&lt;/param&gt; /// &lt;param name=&quot;subsetEnd&quot;&gt;End of selection [0,63]&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public BitVector64 SubsetAtoB(ushort subsetStart, ushort subsetEnd) { if (subsetStart &lt; 0 || subsetStart &gt; 63 || subsetEnd &lt; 0 || subsetEnd &gt; 63) throw new IndexOutOfRangeException($&quot;Boundaries must be in the range [0,63] , actual : [{subsetStart},[{subsetEnd}]&quot;); UInt64 internalState = _data; internalState &lt;&lt;= 63-subsetEnd; internalState &gt;&gt;= subsetStart + (63 - subsetEnd); return new BitVector64(internalState); } /// &lt;summary&gt; /// Return a new BitVector64 built arround the given subset /// &lt;/summary&gt; /// &lt;param name=&quot;subsetStart&quot;&gt;Start of selection [0,63]&lt;/param&gt; /// &lt;param name=&quot;subsetLength&quot;&gt;Number of bits to select (could be negative if you would take bits before start)&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public BitVector64 SubsetATillLength(ushort subsetStart, short subsetLength = 0) { if (subsetStart &lt; 0 || subsetStart &gt; 63) throw new IndexOutOfRangeException($&quot;SubsetStart must be in the range [0,63] , actual : {subsetStart}&quot;); if (subsetLength == 0) subsetLength = (short)(63 - subsetStart); int firstBoundary = subsetStart; int secondBoundary = subsetStart + subsetLength + (subsetLength &gt; 0 ? -1 : 1); if (firstBoundary &gt; secondBoundary) { int tempBoundary = secondBoundary; secondBoundary = firstBoundary; firstBoundary = tempBoundary; } if (firstBoundary &lt; 0 || firstBoundary &gt; 63 || secondBoundary &lt; 0 || secondBoundary &gt; 63) throw new IndexOutOfRangeException($&quot;Boundaries must be in the range [0,63] , actual : [{firstBoundary},[{secondBoundary}]&quot;); return this.SubsetAtoB((ushort)firstBoundary, (ushort)secondBoundary); } /// &lt;summary&gt; /// Generate a deepcopy of current element /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public object Clone() { return new BitVector64(_data); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-12T22:34:39.247", "Id": "496414", "Score": "1", "body": "Tip: `private readonly static ulong[] _MASK = Enumerable.Range(0, 63).Select(x => 1ul << x).ToArray()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-13T09:35:46.640", "Id": "496448", "Score": "0", "body": "@aepot right thx, nice trick to write a more compact code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-13T09:54:40.627", "Id": "496449", "Score": "0", "body": "Also you may use one of methods from [here](https://stackoverflow.com/q/3587826/12888024) to instantiate the `_REVERSE` array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-13T09:59:40.350", "Id": "496451", "Score": "0", "body": "One more tip: pattern matching with assignment and expression-like method body `public override bool Equals(object o) => o is BitVector64 vector ? _data == vector.Data : false`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-13T10:05:31.480", "Id": "496452", "Score": "0", "body": "`_data = (UInt64)data` redundant cast in `BitVector64` ctor and `Data` property. The property may be written simply as `public UInt64 Data => _data`. Check out [this article](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members) to ensure that you have a full compartibility with expression bodies." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-13T10:17:46.060", "Id": "496453", "Score": "0", "body": "An finally this one `public override string ToString() => Convert.ToString(_data, 2)`. There's a built-in `Convert` method." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T17:36:00.807", "Id": "251869", "Score": "3", "Tags": [ "c#", "bitwise", "bitset" ], "Title": "BitVector64 implementation" }
251869
<p>I have the following code that takes user input &quot;path&quot; and adds the current time into the filename after the name part and before any extension (if it exists). It seems a little hacky to me just looking at it. What do you think?</p> <pre><code>#include &lt;string.h&gt; #include &lt;stdio.h&gt; #include &lt;libgen.h&gt; int main() { char buf1[256] = {0}; char path[] = &quot;/var/log/mine.log&quot;; char *tmp = NULL; char time[] = &quot;20201110120305&quot;; char *dir = NULL; char *base = NULL; char *file = NULL; char *ext = NULL; //split path to base and dir tmp = strdup(path); dir = dirname(tmp); tmp = strdup(path); base = basename(tmp); //split base to file and ext tmp = strchr(base,'.'); if (tmp) { ext = strdup(tmp); file = strndup(base,(strlen(base)-strlen(ext))); } else file = strdup(base); // concat dir / file / time / ext if (dir) strcat(buf1,dir); strcat(buf1,&quot;/&quot;); if (file) strcat(buf1,file); strcat(buf1,&quot;-&quot;); if (time) strcat(buf1,time); if (ext) strcat(buf1,ext); printf(&quot;%s\n&quot;,buf1); } </code></pre> <p>This will output <code>/var/log/mine-20201110120305.log</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T13:52:48.487", "Id": "496078", "Score": "1", "body": "I've added the [tag:posix] tag, as I don't think that `strdup()` and `<libgen.h>` are generally available on other platforms." } ]
[ { "body": "<p>Okay, you're doing a <em>lot</em> of [unnecessary] <code>strdup</code>. If we put all the code into a reusable function of its own, you don't <code>free</code> any of the strings, so you are leaking memory.</p>\n<p>One way to alleviate that is to use <code>strdupa</code> instead of <code>strdup</code>. This does an <code>alloca</code> to get a stack frame allocation, so <em>these</em> strings don't have to be freed [they disappear with the stack frame when the function returns].</p>\n<p>In fact, with better use of pointers, there's really no need to duplicate these intermediate strings at all.</p>\n<p>And, there's still a lot of extra scanning/rescanning and <code>strcpy/strcat</code>.</p>\n<p>Stylistically, <code>tmp</code> isn't too descriptive. And, it gets reused for two <em>different</em> purposes.</p>\n<hr />\n<p>I've refactored your program to put the code into functions. I've added a test framework. And, I've created three additional versions that show what I would do to simplify and speed things up:</p>\n<pre><code>// logtod.c -- add timestamp to log file name\n\n#define _GNU_SOURCE\n#include &lt;string.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;libgen.h&gt;\n#include &lt;stddef.h&gt;\n#include &lt;time.h&gt;\n\nint opt_e;\nint opt_n;\n\ntime_t stamptod; // previous time\nint stamplen; // length of stampbuf\nchar stampbuf[100]; // timestamp string\n\n// todget -- generate timestamp\n// RETURNS: stamp in stampbuf and length in stamplen\nvoid\ntodget(time_t tod)\n{\n struct tm *tm;\n\n if (tod == 0)\n tod = time(NULL);\n\n do {\n // use cached buffer [if possible]\n if (tod == stamptod)\n break;\n stamptod = tod;\n\n tm = localtime(&amp;tod);\n\n stamplen = sprintf(stampbuf,&quot;-%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d&quot;,\n tm-&gt;tm_year + 1900,tm-&gt;tm_mon + 1,tm-&gt;tm_mday,\n tm-&gt;tm_hour,tm-&gt;tm_min,tm-&gt;tm_sec);\n } while (0);\n}\n\n// logof_orig -- original code [leaks memory]\nchar *\nlogof_orig(char *buf1,const char *path,time_t tod)\n{\n char *tmp = NULL;\n char *dir = NULL;\n char *base = NULL;\n char *file = NULL;\n char *ext = NULL;\n\n // get timestamp\n todget(tod);\n\n // split path to base and dir\n tmp = strdup(path);\n dir = dirname(tmp);\n tmp = strdup(path);\n base = basename(tmp);\n\n // split base to file and ext\n tmp = strchr(base,'.');\n if (tmp) {\n ext = strdup(tmp);\n file = strndup(base,strlen(base) - strlen(ext));\n }\n else\n file = strdup(base);\n\n buf1[0] = 0;\n\n // concat dir / file / time / ext\n if (dir)\n strcat(buf1,dir);\n strcat(buf1,&quot;/&quot;);\n if (file)\n strcat(buf1,file);\n strcat(buf1,stampbuf);\n if (ext)\n strcat(buf1,ext);\n\n return buf1;\n}\n\n// logof_alloca -- original code [using strdupa et. al]\nchar *\nlogof_alloca(char *buf1,const char *path,time_t tod)\n{\n //char buf1[1024] = { 0 };\n char *tmp = NULL;\n char *dir = NULL;\n char *base = NULL;\n char *file = NULL;\n char *ext = NULL;\n\n // get timestamp\n todget(tod);\n\n // split path to base and dir\n tmp = strdupa(path);\n dir = dirname(tmp);\n tmp = strdupa(path);\n base = basename(tmp);\n\n // split base to file and ext\n tmp = strchr(base,'.');\n if (tmp) {\n ext = strdupa(tmp);\n file = strndupa(base,strlen(base) - strlen(ext));\n }\n else\n file = strdupa(base);\n\n buf1[0] = 0;\n\n // concat dir / file / time / ext\n if (dir)\n strcat(buf1,dir);\n strcat(buf1,&quot;/&quot;);\n if (file)\n strcat(buf1,file);\n strcat(buf1,stampbuf);\n if (ext)\n strcat(buf1,ext);\n\n return buf1;\n}\n\n// logof_stpcpy -- original code [using stpcpy vs. strcat]\nchar *\nlogof_stpcpy(char *buf1,const char *path,time_t tod)\n{\n char *tmp = NULL;\n char *dir = NULL;\n char *base = NULL;\n char *file = NULL;\n char *ext = NULL;\n\n // get timestamp\n todget(tod);\n\n // split path to base and dir\n tmp = strdupa(path);\n dir = dirname(tmp);\n tmp = strdupa(path);\n base = basename(tmp);\n\n // split base to file and ext\n tmp = strchr(base,'.');\n if (tmp) {\n ext = strdupa(tmp);\n file = strndupa(base,strlen(base) - strlen(ext));\n }\n else\n file = strdupa(base);\n\n buf1[0] = 0;\n\n // concat dir / file / time / ext\n char *dst = buf1;\n if (dir)\n dst = stpcpy(dst,dir);\n dst = stpcpy(dst,&quot;/&quot;);\n if (file)\n dst = stpcpy(dst,file);\n dst = stpcpy(dst,stampbuf);\n if (ext)\n dst = stpcpy(dst,ext);\n\n return buf1;\n}\n\n// copyout -- fill in destination buffer\nchar *\ncopyout(char *buf1,const char *path,int pathlen,time_t tod,\n const char *base,const char *ext)\n{\n char *dst;\n ptrdiff_t cpylen;\n\n // get timestamp\n todget(tod);\n\n // get enough buffer space\n if (buf1 == NULL)\n buf1 = malloc(pathlen + stamplen + 1);\n\n dst = buf1;\n\n // ext must be to the right of base\n do {\n if (ext == NULL)\n break;\n if (base == NULL)\n break;\n if (ext &gt;= base)\n break;\n ext = NULL;\n } while (0);\n\n // copy over all but extension\n if (ext != NULL)\n cpylen = ext - path;\n else\n cpylen = pathlen;\n dst = mempcpy(dst,path,cpylen);\n\n // copy over the date stamp\n dst = mempcpy(dst,stampbuf,stamplen);\n\n // copy over the extension\n if (ext != NULL) {\n cpylen = &amp;path[pathlen] - ext;\n dst = mempcpy(dst,ext,cpylen);\n }\n\n *dst = 0;\n\n return buf1;\n}\n\n// logof_fix1 -- single malloc version\nchar *\nlogof_fix1(char *buf1,const char *path,time_t tod)\n{\n\n // get length of path\n size_t pathlen = strlen(path);\n\n // find &quot;base&quot; in &quot;/dir/base&quot;\n const char *base = strrchr(path,'/');\n if (base != NULL)\n ++base;\n\n // find the file extension\n const char *ext;\n if (base != NULL)\n ext = strchr(base,'.');\n else\n ext = strrchr(path,'.');\n\n buf1 = copyout(buf1,path,pathlen,tod,base,ext);\n\n return buf1;\n}\n\n// logof_fix2 -- single pass scan\nchar *\nlogof_fix2(char *buf1,const char *path,time_t tod)\n{\n const char *ext = NULL;\n const char *base = path;\n\n // find &quot;base.ext&quot; and &quot;.ext&quot; in &quot;/dir/base.ext&quot;\n const char *src = path;\n for (int chr = *src++; chr != 0; chr = *src++) {\n switch (chr) {\n case '/':\n base = src;\n ext = NULL;\n break;\n case '.':\n if (ext == NULL)\n ext = src - 1;\n break;\n }\n }\n\n // full length of path\n ptrdiff_t pathlen = (src - 1) - path;\n\n // get enough buffer space\n buf1 = copyout(buf1,path,pathlen,tod,base,ext);\n\n return buf1;\n}\n\n// logof_fix3 -- single pass scan [using strcspn]\nchar *\nlogof_fix3(char *buf1,const char *path,time_t tod)\n{\n const char *ext = NULL;\n const char *base = path;\n\n // find &quot;base.ext&quot; and &quot;.ext&quot; in &quot;/dir/base.ext&quot;\n const char *src = path;\n while (1) {\n int len = strcspn(src,&quot;/.&quot;);\n\n // point to start of separater\n src += len;\n\n // get the character\n int chr = *src;\n\n // end of string\n if (chr == 0)\n break;\n\n // separater is at the start of the source string\n if (len == 0) {\n src += 1;\n continue;\n }\n\n switch (chr) {\n case '/':\n base = src + 1;\n ext = NULL;\n break;\n case '.':\n if (ext == NULL)\n ext = src;\n break;\n }\n }\n\n // full length of path\n ptrdiff_t pathlen = src - path;\n\n buf1 = copyout(buf1,path,pathlen,tod,base,ext);\n\n return buf1;\n}\n\n// fixname -- compensensate for dirname changing &quot;foo&quot; into &quot;./foo&quot;\nconst char *\nfixname(const char *out)\n{\n\n if ((out[0] == '.') &amp;&amp; (out[1] == '/'))\n out += 2;\n\n return out;\n}\n\ntypedef long long tsc_t;\n\ntsc_t\ntscget(void)\n{\n struct timespec ts;\n tsc_t tsc;\n\n clock_gettime(CLOCK_MONOTONIC,&amp;ts);\n tsc = ts.tv_sec;\n tsc *= 1000000000;\n tsc += ts.tv_nsec;\n\n return tsc;\n}\n\ndouble\ntscsec(tsc_t tsc)\n{\n double sec;\n\n sec = tsc;\n sec /= 1e9;\n\n return sec;\n}\n\n// test control\ntypedef char *(*logof_p)(char *buf1,const char *path,time_t tod);\ntypedef struct {\n logof_p tst_fnc;\n const char *tst_tag;\n const char *tst_reason;\n} dotest_t;\n\n#define DOTEST(_fnc,_reason) \\\n { .tst_fnc = logof_##_fnc, .tst_tag = #_fnc, .tst_reason = _reason },\n\n// list of tests\ndotest_t tstlist[] = {\n DOTEST(orig,&quot;original code [leaks memory]&quot;)\n DOTEST(alloca,&quot;original code [using strdupa et. al]&quot;)\n DOTEST(stpcpy,&quot;original code [using stpcpy vs. strcat]&quot;)\n DOTEST(fix1,&quot;single malloc version&quot;)\n DOTEST(fix2,&quot;single pass scan&quot;)\n DOTEST(fix3,&quot;single pass scan [using strcspn]&quot;)\n { .tst_fnc = NULL }\n};\n\nint fnclen; // maximum length of a function name\nchar *dotest_prevbuf; // previous output buffer\ntsc_t dotest_prevtsc; // best time for previous test\ntsc_t dotest_origtsc; // best time for original test\n\n// dotest_ratio -- show ratio of times\nvoid\ndotest_ratio(tsc_t curtsc,tsc_t prevtsc,const char *who)\n{\n double ratio;\n const char *tag;\n\n if (curtsc &gt; prevtsc) {\n tag = &quot;slower&quot;;\n ratio = curtsc;\n ratio /= prevtsc;\n }\n else {\n tag = &quot;faster&quot;;\n ratio = prevtsc;\n ratio /= curtsc;\n }\n\n printf(&quot; -- %.3fx %s&quot;,ratio,tag);\n}\n\n// dotest -- perform test of single function\nvoid\ndotest(dotest_t *tst,const char *path)\n{\n char *out;\n tsc_t tscbest = 1LL &lt;&lt; 62;\n int showout = 0;\n int fail = 0;\n\n out = malloc(1000);\n\n // do test multiple times to eliminate variations in caching, speed step,\n // timeslicing, etc. and take the best/minimum time\n for (int iter = 10; iter &gt; 0; --iter) {\n tsc_t tscbeg = tscget();\n\n out = tst-&gt;tst_fnc(out,path,stamptod);\n\n // get elapsed time\n tsc_t tscend = tscget();\n tscend -= tscbeg;\n\n // get best time\n if (tscend &lt; tscbest)\n tscbest = tscend;\n }\n\n if (dotest_origtsc == 0)\n dotest_origtsc = tscbest;\n\n // compare against previous test data\n do {\n if (dotest_prevbuf == NULL) {\n showout = 1;\n break;\n }\n\n const char *curfix = fixname(out);\n const char *oldfix = fixname(dotest_prevbuf);\n if (strcmp(curfix,oldfix) != 0)\n fail = 1;\n } while (0);\n\n printf(&quot;%.9f %-*s&quot;,\n tscsec(tscbest),fnclen,tst-&gt;tst_tag);\n\n // compare against previous test timing\n do {\n if (dotest_prevbuf == NULL)\n break;\n\n dotest_ratio(tscbest,dotest_origtsc,&quot;orig&quot;);\n dotest_ratio(tscbest,dotest_prevtsc,&quot;prev&quot;);\n } while (0);\n\n if (opt_n)\n printf(&quot;\\n&quot;);\n\n if (showout || fail)\n printf(&quot; %s (%s)&quot;,out,fail ? &quot;FAIL&quot; : &quot;PASS&quot;);\n\n //if (! opt_n)\n printf(&quot;\\n&quot;);\n\n free(dotest_prevbuf);\n dotest_prevbuf = out;\n dotest_prevtsc = tscbest;\n}\n\nvoid\ndoall(const char *path)\n{\n\n printf(&quot;\\n&quot;);\n printf(&quot;PATH: %s\\n&quot;,path);\n\n dotest_origtsc = 0;\n for (dotest_t *tst = tstlist; tst-&gt;tst_fnc != NULL; ++tst)\n dotest(tst,path);\n\n free(dotest_prevbuf);\n dotest_prevbuf = NULL;\n}\n\nint\nmain(int argc,char **argv)\n{\n\n --argc;\n ++argv;\n\n for (; argc &gt; 0; --argc, ++argv) {\n char *cp = *argv;\n if (*cp != '-')\n break;\n\n cp += 2;\n switch (cp[-1]) {\n case 'e':\n opt_e = ! opt_e;\n break;\n case 'n':\n opt_n = ! opt_n;\n break;\n }\n }\n\n // get maximum length of a function name\n for (dotest_t *tst = tstlist; tst-&gt;tst_fnc != NULL; ++tst) {\n int curlen = strlen(tst-&gt;tst_tag);\n if (curlen &gt; fnclen)\n fnclen = curlen;\n }\n\n // show the function names and their descriptions\n for (dotest_t *tst = tstlist; tst-&gt;tst_fnc != NULL; ++tst)\n printf(&quot;%-*s -- %s\\n&quot;,fnclen,tst-&gt;tst_tag,tst-&gt;tst_reason);\n\n // use the same timestamp for all tests\n todget(0);\n\n doall(&quot;/var/log/mine.log&quot;);\n doall(&quot;/var/log/mine&quot;);\n doall(&quot;/var/log.xxx/mine&quot;);\n doall(&quot;mine.log&quot;);\n doall(&quot;mine&quot;);\n doall(&quot;/var/log/mine.log.gz&quot;);\n doall(&quot;/.log&quot;);\n doall(&quot;/.&quot;);\n\n printf(&quot;complete\\n&quot;);\n\n return 0;\n}\n</code></pre>\n<p>Note that I did the <code>fix2</code> version. But, I thought that using <code>strcspn</code> might be faster, so I added <code>fix3</code>.</p>\n<p>That's because <code>strcspn</code> [under <code>glibc</code>, at least] is <em>insanely</em> optimized to very wide memory fetches. But, a side effect is that there's some extra table lookup initialization at entry to the function, so the strings should be long enough to overcome that initial deficit.</p>\n<p>After looking at the resultant code, I'm thinking that the number of times <code>strcspn</code> has to be called, the extra complexity of the code, would make <code>fix3</code> [probably] slower and less desirable than <code>fix2</code></p>\n<hr />\n<p>Here's the program output:</p>\n<pre><code>orig -- original code [leaks memory]\nalloca -- original code [using strdupa et. al]\nstpcpy -- original code [using stpcpy vs. strcat]\nfix1 -- single malloc version\nfix2 -- single pass scan\nfix3 -- single pass scan [using strcspn]\n\nPATH: /var/log/mine.log\n0.000000274 orig /var/log/mine-20201110175328.log (PASS)\n0.000000150 alloca -- 1.827x faster -- 1.827x faster\n0.000000132 stpcpy -- 2.076x faster -- 1.136x faster\n0.000000063 fix1 -- 4.349x faster -- 2.095x faster\n0.000000067 fix2 -- 4.090x faster -- 1.063x slower\n0.000000137 fix3 -- 2.000x faster -- 2.045x slower\n\nPATH: /var/log/mine\n0.000000197 orig /var/log/mine-20201110175328 (PASS)\n0.000000095 alloca -- 2.074x faster -- 2.074x faster\n0.000000097 stpcpy -- 2.031x faster -- 1.021x slower\n0.000000049 fix1 -- 4.020x faster -- 1.980x faster\n0.000000052 fix2 -- 3.788x faster -- 1.061x slower\n0.000000093 fix3 -- 2.118x faster -- 1.788x slower\n\nPATH: /var/log.xxx/mine\n0.000000219 orig /var/log.xxx/mine-20201110175328 (PASS)\n0.000000104 alloca -- 2.106x faster -- 2.106x faster\n0.000000106 stpcpy -- 2.066x faster -- 1.019x slower\n0.000000058 fix1 -- 3.776x faster -- 1.828x faster\n0.000000062 fix2 -- 3.532x faster -- 1.069x slower\n0.000000103 fix3 -- 2.126x faster -- 1.661x slower\n\nPATH: mine.log\n0.000000268 orig ./mine-20201110175328.log (PASS)\n0.000000126 alloca -- 2.127x faster -- 2.127x faster\n0.000000106 stpcpy -- 2.528x faster -- 1.189x faster\n0.000000061 fix1 -- 4.393x faster -- 1.738x faster\n0.000000051 fix2 -- 5.255x faster -- 1.196x faster\n0.000000071 fix3 -- 3.775x faster -- 1.392x slower\n\nPATH: mine\n0.000000208 orig ./mine-20201110175328 (PASS)\n0.000000088 alloca -- 2.364x faster -- 2.364x faster\n0.000000089 stpcpy -- 2.337x faster -- 1.011x slower\n0.000000056 fix1 -- 3.714x faster -- 1.589x faster\n0.000000042 fix2 -- 4.952x faster -- 1.333x faster\n0.000000047 fix3 -- 4.426x faster -- 1.119x slower\n\nPATH: /var/log/mine.log.gz\n0.000000278 orig /var/log/mine-20201110175328.log.gz (PASS)\n0.000000154 alloca -- 1.805x faster -- 1.805x faster\n0.000000132 stpcpy -- 2.106x faster -- 1.167x faster\n0.000000062 fix1 -- 4.484x faster -- 2.129x faster\n0.000000071 fix2 -- 3.915x faster -- 1.145x slower\n0.000000139 fix3 -- 2.000x faster -- 1.958x slower\n\nPATH: /.log\n0.000000256 orig //-20201110175328.log (PASS)\n0.000000134 alloca -- 1.910x faster -- 1.910x faster\n0.000000110 stpcpy -- 2.327x faster -- 1.218x faster\n0.000000058 fix1 -- 4.414x faster -- 1.897x faster /-20201110175328.log (FAIL)\n0.000000047 fix2 -- 5.447x faster -- 1.234x faster\n0.000000063 fix3 -- 4.063x faster -- 1.340x slower /.log-20201110175328 (FAIL)\n\nPATH: /.\n0.000000254 orig //-20201110175328. (PASS)\n0.000000134 alloca -- 1.896x faster -- 1.896x faster\n0.000000109 stpcpy -- 2.330x faster -- 1.229x faster\n0.000000053 fix1 -- 4.792x faster -- 2.057x faster /-20201110175328. (FAIL)\n0.000000042 fix2 -- 6.048x faster -- 1.262x faster\n0.000000063 fix3 -- 4.032x faster -- 1.500x slower /.-20201110175328 (FAIL)\ncomplete\n</code></pre>\n<hr />\n<p><strong>UPDATE:</strong></p>\n<blockquote>\n<p>I see your point about too much <code>strdup()</code>, but it's necessary with <code>dirname()</code> and <code>basename()</code> as they will mangle their argument.</p>\n</blockquote>\n<p>As I mentioned, raw <code>strdup</code> leaks memory. And, even with <code>dirname/basename</code> some of the dups aren't needed.</p>\n<p>And, I've never used either <code>dirname</code> and/or <code>basename</code> for pretty much the same reason [they modify their arguments]. So, I've written my own variants that copy the results to a buffer selected from a pool of static buffers</p>\n<blockquote>\n<p>I like the approach you took with fix1 as it is still very obvious what is going on.</p>\n</blockquote>\n<p>I intended to provide a progression from simple/slow to faster, so you can choose.</p>\n<blockquote>\n<p>Although fix2 is arguably faster, it's a little obfuscated</p>\n</blockquote>\n<p>Perhaps, but it's actually [loosely] derived from production code I have for doing the same thing. You wanted [some] comments. Personally, I felt your code was difficult to follow.</p>\n<blockquote>\n<p>and would not handle extensions such as <code>.log.gz</code> correctly</p>\n</blockquote>\n<p>That wasn't part of your original test data. But, my production code handled it, just not what I recreated for this post. It's a three line fix:</p>\n<pre><code>diff --git a/logtod/logtod.c b/logtod/logtod.c\nindex 28f5702..c212ba9 100644\n--- a/logtod/logtod.c\n+++ b/logtod/logtod.c\n@@ -264,9 +264,11 @@ logof_fix2(char *buf1,const char *path,time_t tod)\n switch (chr) {\n case '/':\n base = src;\n+ ext = NULL;\n break;\n case '.':\n- ext = src - 1;\n+ if (ext == NULL)\n+ ext = src - 1;\n break;\n }\n }\n</code></pre>\n<p>I've updated the original code block and the output</p>\n<hr />\n<p><strong>UPDATE #2:</strong></p>\n<p>I've updated the code and program output [again ;-)].</p>\n<p>I moved the setting of the timestamp buffer to <em>outside</em> the benchmarked/timed area to [better] compare <em>just</em> the times for the scanning/output code (e.g. because <code>sprintf</code> is somewhat heavyweight and took up the bulk of the time spent).</p>\n<p>And, I replaced a <code>strlen</code> call in <code>copyout</code> with just a pointer/offset calculation.</p>\n<p>And, I added calculation of the speed ratio of the various methods against one another.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T13:49:59.600", "Id": "496077", "Score": "1", "body": "Although `strdup()` is specified by POSIX, `strdupa()` is less widely available (GNU only, I think)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T14:15:15.560", "Id": "496083", "Score": "1", "body": "@TobySpeight When I was first forming the answer, I started with a macro I wrote [have had for 10+ years] that did the same. I was looking at the man page for `strdup` [for reference] and found `strdupa`. The man page defines it as a function but, I was curious since I thought it had to be a macro [and it was]. It's easy to create it. Anyway, it's only an interim step as I mentioned because the [massive] duping isn't necessarily the best approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T15:30:59.730", "Id": "496096", "Score": "0", "body": "@CraigEstey I see your point about too much strdup(), but it's necessary with dirname() and basename() as they will mangle their argument. I like the approach you took with fix1 as it is still very obvious what is going on. Although fix2 is arguably faster, it's a little obfuscated and would not handle extensions such as .log.gz correctly." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T01:15:18.673", "Id": "251883", "ParentId": "251870", "Score": "3" } }, { "body": "<h1>Structure</h1>\n<p>This doesn't look like a completed program - everything in <code>main()</code> with hard-coded values. A simpler version of a program that does the same thing is:</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nint main(void)\n{\n puts(&quot;/var/log/mine-20201110120305.log&quot;);\n}\n</code></pre>\n<p>We probably want to accept an argument, and use a function. I'd recommend writing the function with a similar signature to <code>snprintf()</code> and similar - accept a buffer pointer and size, and return the number of characters which would be written if the size were large enough. Whilst not always ideal, this doesn't impose memory allocation on programs that don't need it, and the interface is at least familial and predictable.</p>\n<p>It's easy to wrap such a function in an interface that does <code>malloc()</code> if wanted.</p>\n<h1>Avoid <code>basename()</code> and <code>dirname()</code></h1>\n<p>These POSIX functions require a modifiable string, but we can write simpler code that just returns a pointer or index to the start/end of a read-only string.</p>\n<h1>Multiple <code>strcat()</code> is inefficient</h1>\n<p>Although this isn't performance-sensitive code, we'd do well to avoid repeated <code>strcat()</code>, where we start at the beginning of the target string in every call - labelled by Joel Spolsky as using <a href=\"https://www.joelonsoftware.com/2001/12/11/back-to-basics/\" rel=\"nofollow noreferrer\">Shlemiel the Painter's algorithm</a>.</p>\n<hr />\n<h1>Modified version</h1>\n<p>Here's one that addresses the concerns in my review, and only copies the string data once:</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;time.h&gt;\n\nint make_log_name(char *outbuf, size_t maxlen, time_t timestamp, const char *template)\n{\n /* Format the time value */\n struct tm timeval;\n if (!localtime_r(&amp;timestamp, &amp;timeval)) {\n return -1;\n }\n char timebuf[14]; /* match size to next line's format string */\n if (!strftime(timebuf, sizeof timebuf, &quot;-%Y%m%d%H%M&quot;, &amp;timeval)) {\n return -1;\n }\n\n /* Find the insertion point in the template */\n const char* slash = strrchr(template, '/');\n if (!slash) {\n /* not found - use beginning of string */\n slash = template;\n }\n const char* dot = strchr(slash, '.');\n if (!dot) {\n /* not found - use end of basename */\n dot = slash + strlen(slash);\n }\n\n return snprintf(outbuf, maxlen, &quot;%.*s%s%s&quot;,\n (int)(dot-template), template, timebuf, dot);\n}\n</code></pre>\n\n<pre><code>/* A simple test of the provided input templates */\nint main(int argc, char **argv)\n{\n const time_t timestamp = time(NULL);\n for (int i = 1; i &lt; argc; ++i) {\n char buf[FILENAME_MAX];\n int len = make_log_name(buf, sizeof buf, timestamp, argv[i]);\n if (len &lt; 0 || (size_t)len &gt;= sizeof buf) {\n fprintf(stderr, &quot;Failed for %s\\n&quot;, argv[i]);\n continue;\n }\n puts(buf);\n }\n}\n</code></pre>\n<p>And demonstration of it working with various input values:</p>\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>./251870 /tmp/mine.log /tmp/log mine.log log .test /a.b/c.d\n/tmp/mine-202011111312.log\n/tmp/log-202011111312\nmine-202011111312.log\nlog-202011111312\n-202011111312.test\n/a.b/c-202011111312.d\n</code></pre>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T13:24:52.793", "Id": "251945", "ParentId": "251870", "Score": "2" } } ]
{ "AcceptedAnswerId": "251883", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T18:38:24.527", "Id": "251870", "Score": "5", "Tags": [ "c", "strings", "posix" ], "Title": "Log file name adjustment" }
251870
<p>Here is my task: Create classes for a menu plan. With the help of the classes it should be possible to create a menu card for a restaurant in a hotel.</p> <p>There should be a 'MenuCard' class for this purpose. This should include a date for the card and one or more course menus. Use an appropriate data type in Python for the date. It should be possible to add the courses to a menu card one after the other with a method add_course. There should be a class 'Course' for the course menu. This has a name (e.g. starter or first course). Furthermore, each course has one or more dishes, which can be added with the 'add_dish' method. For this purpose, the 'Dish' class is to be assembled, which is the name of the food administration and whether it is vegetarian. Use the str function in all classes to display the menu card on the screen.</p> <p>Additional task: Create a class for a three-course menu ThreeCourseMenuCard, which the existing class sequences. With this class you have to make sure that there are no more than (or exactly) three courses.</p> <p>Create your own personal map by controlling instances from the classes.</p> <p>I already programmed this, but its to complicated for some users i know. Can someone give me any ideas on how to simplify this program. Thank you in advance.</p> <p>Here is my code:</p> <pre><code>#! /usr/bin/python3 import datetime, locale class Dish(): def __init__(self, name, veggy): self.__name = name self.__veggy = veggy def __str__(self): if self.__veggy == bool(1): return &quot;{} (vegetarisch)&quot;.format(self.__name) else: return &quot;{}&quot;.format(self.__name) class Course(): def __init__(self, name): self.__name = name def add_dish(self): for i in range(len(self.__name[1])): print(Dish(self.__name[1][i][0], self.__name[1][i][1])) if i &lt; len(self.__name[1])-1: print(&quot;oder&quot;) def __str__(self): return &quot;\n\n{}\n&quot;.format(self.__name[0][0]) class MenuCard(): def __init__(self, date): self.__date = date.strftime('%A, %d.%m.%Y') def add_course(self, new_course): print(Course(new_course)) Course(new_course).add_dish() def __str__(self): return &quot;\n\nMenukarte fuer {}&quot;.format(self.__date) vorspeise = [[&quot;Vorspeise&quot;],[ [&quot;Carpaggio vom Rind auf knackigem Blattsalat&quot;, 0], [&quot;Honigmelone mit hausgemachtem Speck vom Hängebauchschwein&quot;, 0] ]] suppe = [[&quot;Suppe&quot;],[ [&quot;Kräftige Rindssuppe mit Eiertörtchen&quot;, 1] ]] erster_gang = [[&quot;1. Gang&quot;],[ [&quot;Salat vom Buffet&quot;, 0] ]] zweiter_gang = [[&quot;2. Gang&quot;],[ [&quot;Wiener Schnitzel mit Kartoffelsalat&quot;, 0], [&quot;Wildsaibling an Herbstgemüse auf Safranrisotto&quot;, 0], [&quot;Saftiges Hirschgulasch mit Kastanienrotkraut und Semmelknödel&quot;, 0], [&quot;Spinatlasagne mit frischen Tomaten&quot;, 1] ]] nachspeise = [[&quot;Nachspeise&quot;],[ [&quot;Vanilleparfait auf Himbeerspiegel&quot;, 1], [&quot;Luftige Topfenknödel mit roter Grütze&quot;, 0] ]] locale.setlocale(locale.LC_ALL, 'de_DE.utf8') menu = MenuCard(datetime.datetime(2020, 11, 9)) print(menu) gaenge = [vorspeise, suppe, erster_gang, zweiter_gang, nachspeise] for gang in gaenge: menu.add_course(gang) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T20:46:37.820", "Id": "496029", "Score": "0", "body": "Which Python version are you using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T20:48:09.920", "Id": "496030", "Score": "0", "body": "Python version 3.8" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T21:26:25.683", "Id": "496032", "Score": "0", "body": "Can you clarify what you mean by _but its to complicated for some users i know_ ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T21:29:33.900", "Id": "496033", "Score": "0", "body": "My friend doesn't understand the code on how it is written. So he asked me if there is another way to solve this (more basic). Like if I can remove those nested lists and solve it on another way." } ]
[ { "body": "<p><code>MenuCard</code> should have two variables, <code>courses_list</code> and <code>menu_date</code>. In my opinion, the method <code>add_course</code> should take in a <code>Course</code> object as parameter instead of taking in the name of the course.</p>\n<pre><code>def add_course(self, new_course: Course):\n self.__courses_list.append(new_course)\n</code></pre>\n<p><code>Course</code> should have two variables, <code>name</code> and <code>dishes_list</code>. The <code>add_dish</code> method should take in a <code>Dish</code> object as parameter and append it to the <code>dishes_list</code>.\n<code>Dish</code> seems alright. You should probably change <code>if self.__veggy == bool(1):</code> to <code>if self.__veggy is True:</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T20:19:48.663", "Id": "496025", "Score": "0", "body": "Could you change it in the code and sent it here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T08:31:12.280", "Id": "496061", "Score": "3", "body": "We can't really do all of your homework for you ;-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T20:11:07.977", "Id": "251874", "ParentId": "251872", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T19:40:01.927", "Id": "251872", "Score": "3", "Tags": [ "python", "object-oriented" ], "Title": "Can I simplify my Restaurant MenuCard program?" }
251872
<p>This is bad. I've been hacking away at Sympy for a few hours and the only solution I've come up with to yield the data I want is brute-force:</p> <h2>Code</h2> <pre><code>from sympy import Interval, Naturals0, Q, Symbol, refine, solveset N = 10 digit_interval = Interval.Ropen(0, N) digits = digit_interval.intersect(Naturals0) # equivalent to range(N) # These don't seem to have any useful impact on solveset assumptions = { 'nonnegative': True, 'noninteger': False, 'real': True, } a = Symbol('a', **assumptions) b = Symbol('b', **assumptions) c = Symbol('c', **assumptions) symbols = (a, b, c) left = a / (b + c) right = 3 soln = solveset(left - right, symbols[-1], digits) # Useless - has no effect for sym in symbols: soln = refine(soln, Q.positive(N - sym)) print(f'Set solution to {left}={right} for {symbols[-1]} is {soln}') # Number of variables is so small that recursion is fine(ish) def recurse_determine(inner_soln, vars=(), depth=0): if depth == len(symbols) - 1: yield from (vars + (v,) for v in inner_soln) else: for val in digits: yield from recurse_determine( inner_soln.subs(symbols[depth], val), vars + (val,), depth+1, ) for values in recurse_determine(soln): print(', '.join(str(v) for v in values)) </code></pre> <p>The crux of the problem is that it seems difficult (impossible?) to have Sympy find a solution to such a multivariate integer problem and meaningfully constrain it to known bounds, so I'm left doing the brute-force approach: iterate through every possible value of every variable, and only when a (probably invalid) selection of variable values has been substituted can I ask Sympy to tell me that the result is an empty set. It works (for about the worst definition of &quot;works&quot;) but there has to be a better way.</p> <p>I should add that the bounds will remain the same but the equation will be subject to change in the future, so a suggested solution that replaces Sympy with (e.g.) hard-coded Numpy or bare Python will not help me.</p> <h2>Output</h2> <pre class="lang-none prettyprint-override"><code>Set solution to a/(b + c)=3 for c is Intersection(FiniteSet(a/3 - b), Range(0, 10, 1)) 0, 0, 0 3, 0, 1 3, 1, 0 6, 0, 2 6, 1, 1 6, 2, 0 9, 0, 3 9, 1, 2 9, 2, 1 9, 3, 0 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T23:49:47.443", "Id": "496039", "Score": "0", "body": "What sort of equations are you looking at? What operations are allowed? How many variables will there be? I mean, for example, in general it is not possible to find the roots of a polynomial symbolically." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T00:05:20.430", "Id": "496042", "Score": "0", "body": "@Andrew Only those definable by the standard Python operators, nothing from `math`; up to ten variables. I'm not too concerned about what Sympy can and can't solve in terms of equation types - I'll take the \"basics\" for now, even algebraic expressions of order 1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T09:04:28.080", "Id": "496063", "Score": "0", "body": "IMHO this question is a better fit for StackOverflow than Code Review." } ]
[ { "body": "<p>You're more running into the limitations of SymPy than anything. Most of the things you are doing <em>should</em> work, they just aren't implemented presently.</p>\n<p>Your best bet for solving this kind of problem in a way that is smarter than naive brute force iteration of all possible values is to use the Diophantine solvers:</p>\n<pre><code>&gt;&gt;&gt; diophantine(a/(b + c) - 3, t, syms=(a, b, c))\n{(3*t_0, t_1, t_0 - t_1)}\n</code></pre>\n<p>This tells you that a solution set is</p>\n<pre><code>a = 3*t0\nb = t1\nc = t0 - t1\n</code></pre>\n<p>where <code>t0</code> and <code>t1</code> are arbitrary integers. Given the form of the solution, it is quite easy to see that for a, b, c to be in the range [0, N], t1 must be in [0, N] and t0 must be in [0, N/3].</p>\n<pre><code>&gt;&gt;&gt; N = 10\n&gt;&gt;&gt; for t0 in range(0, N//3 + 1):\n... for t1 in range(0, N + 1):\n... a, b, c = 3*t0, t1, t0 - t1\n... if all(0 &lt;= i &lt;= N for i in (a, b, c)) and b + c != 0:\n... print(a, b, c)\n3 0 1\n3 1 0\n6 0 2\n6 1 1\n6 2 0\n9 0 3\n9 1 2\n9 2 1\n9 3 0\n</code></pre>\n<p>Actually in this case, brute force is also fine because there are only N^3 = 1000 combinations, but Diophantine reduced it to only N^2, so that's an improvement asymptotically. There's no need to do it recursively. You can build a substitution dictionary and pass it to subs (like <code>expr.subs({a: 1, b: 2, c: 3})</code>).</p>\n<p>You can see the <a href=\"https://docs.sympy.org/latest/modules/solvers/diophantine.html\" rel=\"nofollow noreferrer\">documentation</a> for more information on what kinds of Diophantine equations are implemented. I'll leave it to you to implement the general code to do the above. It really depends on what form your equations take in general as to what their Diophantine solutions will look like, including whether SymPy can solve them at all.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T15:27:58.613", "Id": "496095", "Score": "0", "body": "That's really promising! Diophantine, with a fallback to brute-force, seems like the best approach." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T09:03:01.630", "Id": "251890", "ParentId": "251873", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T19:42:45.493", "Id": "251873", "Score": "5", "Tags": [ "python", "sympy" ], "Title": "Sympy reduction of a multivariate, bounded, under-determined system" }
251873
<p>I'm a beginning programmer and wrote a little code for a mathematical question. There are 6 rounds where each time the pile of cupcakes is divided into five equal groups, with one extra cupcake (which is discarded). Then one fifth is taken away and the next round starts. I've written the code, but there must be a way to write this shorter, a loop instead of nested if-statements. My code:</p> <pre><code> import sys getal = 1 while True: if getal % 5 == 1: a = (getal - 1)/5 if (a*4) % 5 == 1: b = (a*4-1)/5 if (b*4) % 5 == 1: c = (b*4-1)/5 if (c*4) % 5 == 1: d = (c*4-1)/5 if (d*4) % 5 == 1: e = (d*4-1)/5 if (e*4) % 5 == 1: print(getal) sys.exit() else: getal = getal + 1 else: getal = getal + 1 else: getal = getal + 1 else: getal = getal + 1 else: getal = getal + 1 else: getal = getal + 1 continue </code></pre> <p>Thanks in advance!</p> <p>PS: <em>getal</em> is Dutch for number (the number of cupcakes at the start, which is the result of my question).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T23:22:44.027", "Id": "496037", "Score": "3", "body": "Can you expand on what the code is meant to do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T08:07:28.120", "Id": "496058", "Score": "0", "body": "You start with a number op cupcakes x. Then 5 people come in seperately and divide the cupcakes in 5 equal groups + a remainder that they discard. Then they hide one part (‘their part’) and thus the next one does the same with less cupcakes (since their is 1/5 + 1 removed. At the end (sixth step): they divide it again in 5 groups and again they have a remainder of one." } ]
[ { "body": "<p>I'm not sure what your code is doing. As it currently stands, it will print the first number that satisfies the requirement of being composed of various parts, all divisible by 5 with a remainder of 1.</p>\n<p>If that is your objective, then you should certainly compute the number as an equation: (0*5)+1 *5 ... etc.</p>\n<p>If you are working up to determining whether any given number meets the condition, then you can certainly continue as you are doing.</p>\n<p>Here are some tips to improve your efficiency and clarity:</p>\n<ol>\n<li><p>Get rid of the <code>continue</code> at the bottom of the loop. It is not needed.</p>\n</li>\n<li><p>Get rid of the various statements <code>getal = getal + 1</code> in your else branches. By inspection, I can see that this adjustment is always done whenever you loop (since you <code>sys.exit()</code> on success) so just move the statement to the <em>top</em> of the loop, and adjust your incoming variable:</p>\n<pre><code> getal -= 1\n while True:\n getal += 1\n # many, many if statements\n</code></pre>\n</li>\n<li><p>Perform your multiplication as part of your adjustment to <code>getal</code>, not as a separate part of your <code>if</code> statements:</p>\n<pre><code> a = ((getal - 1) / 5) * 4\n if a % 5 == 1:\n</code></pre>\n</li>\n<li><p>Consider negating your tests. Instead of looking for &quot;good&quot; values, look for &quot;bad&quot; values. Because you are testing for &quot;failure,&quot; and because the response to failure is to jump away (<code>continue</code>), you can replace nesting with a series of tests at the same level:</p>\n<pre><code> if a % 5 != 1:\n continue\n b = ...\n if b % 5 != 1:\n continue\n c = ...\n if c % 5 != 1:\n continue\n</code></pre>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T08:24:47.550", "Id": "496060", "Score": "0", "body": "However, step 3 results in an overflow error. But it is better anyway, thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T23:45:48.860", "Id": "251882", "ParentId": "251875", "Score": "3" } }, { "body": "<p>Code readability is a very much asked for trait in code. The code, while nice looking at a glance, is not really great, readability-wise. Perhaps newlines would help, for example:</p>\n<pre><code>import sys\n\ngetal = 1\n\nwhile True:\n\n if getal % 5 == 1:\n a = (getal - 1)/5\n\n if (a*4) % 5 == 1:\n b = (a*4-1)/5\n\n if (b*4) % 5 == 1:\n c = (b*4-1)/5\n\n if (c*4) % 5 == 1:\n d = (c*4-1)/5\n\n if (d*4) % 5 == 1:\n e = (d*4-1)/5\n\n if (e*4) % 5 == 1:\n print(getal)\n sys.exit()\n\n else:\n getal = getal + 1\n\n\n else:\n getal = getal + 1\n\n\n else:\n getal = getal + 1\n\n\n else:\n getal = getal + 1\n\n\n else:\n getal = getal + 1\n\n\n else:\n getal = getal + 1\n continue\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-30T19:34:24.683", "Id": "520508", "Score": "0", "body": "While this does improve readability, it isn't a response to my question (write it shorter). Question was already answered." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-13T18:08:41.647", "Id": "263005", "ParentId": "251875", "Score": "-1" } } ]
{ "AcceptedAnswerId": "251882", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T22:13:18.400", "Id": "251875", "Score": "2", "Tags": [ "python", "beginner" ], "Title": "How to make a loop of nested if-statements to find the smallest number of something?" }
251875
<p>I have created this simple currency convertor to learn VueJs more. Any code review/comment on coding standard and best practice for Vue? Thanks in advance.</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>new Vue({ el: "#app", data() { return { currency_from_amount: 0, currency_to_amount: 0, result: '', currencyFromOptions: [], currencyToOptions: [], loading: true, errored: false, info: null, currencyFromSelected: '', currencyToSelected: '' }; }, methods: { validation: function() { return (this.currency_from_amount &gt; 0 &amp;&amp; this.currencyFromSelected.length === 3 &amp;&amp; this.currencyToSelected.length === 3) }, convert: function() { debugger let payLoad = `${this.currencyFromSelected}_${this.currencyToSelected}`; //let payLoad = `USD_MYR`; console.log(payLoad); if(this.validation()) { this.loading = true; axios .get( `https://free.currconv.com/api/v7/convert?q=${payLoad}&amp;compact=ultra&amp;apiKey=afd6156ec2a14519570e` ) .then((response) =&gt; { debugger let exchangeRate = JSON.stringify(response).replace(/[^0-9\.]/g, ''); let conversionAmt = (parseFloat(this.currency_from_amount) * parseFloat( exchangeRate)).toFixed(2); this.currency_to_amount = conversionAmt; this.result = `${this.currency_from_amount} ${this.currencyFromSelected} equals ${conversionAmt} ${this.currencyToSelected}`; } ) .catch(error =&gt; { console.log(error); this.errored = true; }) .finally(() =&gt; (this.loading = false)); } } }, mounted() { axios .get("https://openexchangerates.org/api/currencies.json") .then(response =&gt; (this.currencyFromOptions = response.data, this.currencyToOptions = response .data)) .catch(error =&gt; { console.log(error); this.errored = true; }) .finally(() =&gt; (this.loading = false)); } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"&gt;&lt;/script&gt; &lt;!DOCTYPE html&gt; &lt;!--[if lt IE 7]&gt; &lt;html class="no-js lt-ie9 lt-ie8 lt-ie7"&gt; &lt;![endif]--&gt; &lt;!--[if IE 7]&gt; &lt;html class="no-js lt-ie9 lt-ie8"&gt; &lt;![endif]--&gt; &lt;!--[if IE 8]&gt; &lt;html class="no-js lt-ie9"&gt; &lt;![endif]--&gt; &lt;!--[if gt IE 8]&gt; &lt;html class="no-js"&gt; &lt;!--&lt;![endif]--&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;title&gt;Currency Convertor in vue&lt;/title&gt; &lt;meta name="description" content=""&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"&gt; &lt;style&gt; .form-group select { display: inline; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdn.jsdelivr.net/npm/vue"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"&gt;&lt;/script&gt; &lt;!--[if lt IE 7]&gt; &lt;p class="browsehappy"&gt;You are using an &lt;strong&gt;outdated&lt;/strong&gt; browser. Please &lt;a href="#"&gt;upgrade your browser&lt;/a&gt; to improve your experience.&lt;/p&gt; &lt;![endif]--&gt; &lt;div id="app"&gt; &lt;div v-if="loading"&gt;Loading...&lt;/div&gt; &lt;section v-else&gt; &lt;div class="alert alert-success" id="result" v-if="validation"&gt;{{result}}&lt;/div&gt; &lt;div class="col-xs-12"&gt; &lt;div class="form-group form-inline"&gt; &lt;input class="form-control" type="number" name="currency_from_amount" id="currency_from_amount" v-model="currency_from_amount" @keyup="convert"&gt; &lt;select class="form-control" required v-model="currencyFromSelected" @change="convert"&gt; &lt;option v-for="(value,key) in currencyFromOptions" :value="key"&gt;{{ value }}&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-xs-12"&gt; &lt;div class="form-group form-inline"&gt; &lt;input class="form-control" type="number" name="currency_to_amount" id="currency_to_amount" readonly v-model="currency_to_amount"&gt; &lt;select class="form-control" v-model="currencyToSelected" @change="convert"&gt; &lt;option v-for="(value,key) in currencyToOptions" :value="key"&gt;{{ value }}&lt;/option&gt; &lt;/div&gt; &lt;/div&gt; &lt;p&gt;Note: Data provided by CurrencyConverterApi.com for Currency&lt;/p&gt; &lt;/section&gt; &lt;/select&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>From my point of view, I think it would be better if you use same format in your <code>data()</code>. There you mixed between <code>camelCase</code> and <code>snake_case</code>. I don't know about your approach but make it more consistent would be better and I think it won't make you confused in the future.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>currency_from_amount: 0,\ncurrency_to_amount: 0,\n</code></pre>\n<p>to</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>currencyFromAmount: 0,\ncurrencyToAmount: 0,\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T02:06:16.837", "Id": "254294", "ParentId": "251878", "Score": "2" } }, { "body": "<p>I think that you should always use <code>const</code> instead of <code>let</code> or <code>var</code> if you are not going to be reassigning that variable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T09:36:36.127", "Id": "501510", "Score": "1", "body": "I agree, though it would help to add a reason." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T15:08:08.103", "Id": "501523", "Score": "0", "body": "I did I said if you are not going to be reassing that variable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T16:09:21.483", "Id": "501529", "Score": "1", "body": "That sounds like a condition - thus it could be reworded as \"_if you are not going to be reassigning that variable **then** you should use `const` instead of `let` or `var`_\"... Imagine you are not well-versed in the differences between those keywords - one might ask \"why?\"..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T16:10:22.090", "Id": "501530", "Score": "0", "body": "Thank you Sam I was not aware of this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T22:00:18.633", "Id": "512617", "Score": "1", "body": "The *reason* is to help prevent you from making mistakes in the future by accidentally overwriting a variable unexpectedly. See here: https://evertpot.com/javascript-let-const/" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T03:49:27.377", "Id": "254296", "ParentId": "251878", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T23:07:21.020", "Id": "251878", "Score": "2", "Tags": [ "vue.js" ], "Title": "Currency Convertor in VueJs" }
251878
<p><strong>(This is homework, however I have a working solution that I'm trying to improve upon)</strong></p> <p>I'm working on a program that adds or subtracts up to 15 decimal or hexadecimal numbers from the command line. You run the program with the arguments and then choose the option from a menu. I.e.:<code>./main 5 10 15 20</code> will take in those four arguments and allow you to either add or subtract.</p> <p>I have a working program, but I am trying to optimize it to reduce some redundancy. Basically my add and subtract functions are identical other than some sign switches, and I feel like there might be a better way. Here is what I have so far (the program can accept decimal input, or hex input formatted with a preceding 0x, which is why there are a sections dealing with those conversions):</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;ctype.h&gt; void menu(char **options){ for(int i = 0; i &lt; 3; ++i){ printf(&quot;%d. %s\n&quot;, i, options[i]); } printf(&quot;Menu Item: &quot;); } int isHex(char *argv, int len){ if(argv[0] == '0' &amp;&amp; (argv[1] == 'x' || argv[1] == 'X')){ for (int i = 2; i &lt; len; ++i) if(!isxdigit(argv[i])) return 0; return 1; } return 0; } int convertHex(char *hexVal, int len){ int dec_val = 0; int base = 1; for (int i=len-1; i&gt;=2; i--) { if (hexVal[i]&gt;='0' &amp;&amp; hexVal[i]&lt;='9'){ dec_val += (hexVal[i] - 48)*base; base = base * 16; } else if (hexVal[i]&gt;='A' &amp;&amp; hexVal[i]&lt;='F') { dec_val += (hexVal[i] - 55)*base; base = base*16; } } return dec_val; } void add(int argc, char **argv){ int i = 1, s = 0, x = 0; if(isHex(argv[i], strlen(argv[i]))) s = (x =convertHex(argv[i], strlen(argv[i]))); else s = atoi(argv[i]); printf(&quot;%s + &quot;, argv[i]); for(i = 2;i&lt;argc;i++){ if(isHex(argv[i], strlen(argv[i]))){ s += (x = convertHex(argv[i], strlen(argv[i]))); printf(&quot;%s&quot;, argv[i]); } else{ printf(&quot;%s&quot;, argv[i]); s += atoi(argv[i]); } if(i == argc-1) printf(&quot; = &quot;); else printf(&quot; + &quot;); } printf(&quot;%d\n&quot;, s); } void sub(int argc, char **argv){ int i = 1, s = 0, x = 0; if(isHex(argv[i], strlen(argv[i]))) s = (x =convertHex(argv[i], strlen(argv[i]))); else s = atoi(argv[i]); printf(&quot;%s - &quot;, argv[i]); for(i = 2;i&lt;argc;i++){ if(isHex(argv[i], strlen(argv[i]))){ s -= (x = convertHex(argv[i], strlen(argv[i]))); printf(&quot;%s&quot;, argv[i]); } else{ printf(&quot;%s&quot;, argv[i]); s -= atoi(argv[i]); } if(i == argc-1) printf(&quot; = &quot;); else printf(&quot; - &quot;); } printf(&quot;%d\n&quot;, s); } int main(int argc,char** argv){ char *choices[] = {&quot;Exit&quot;, &quot;Addition&quot;, &quot;Subtraction&quot;}; void (*calc[])(int, char**) = {NULL, add, sub}; if(argc &lt; 3) fprintf(stderr, &quot;You must enter at least two arguments.\n&quot;); else if(argc &gt; 16) fprintf(stderr, &quot;You cannot enter more than 15 arguments.\n&quot;); else{ int ch=1; while(ch!=0){ menu(choices); scanf(&quot;%d&quot;,&amp;ch); switch(ch){ case 0: exit(0); break; case 1: calc[1](argc,argv); break; case 2: calc[2](argc,argv); break; default: printf(&quot;Enter valid option\n&quot;); break; } } exit(EXIT_SUCCESS); } exit(EXIT_FAILURE); } </code></pre> <p>The relevant functions are add/sub. It gets tricky because of needing to output the operations to the user. My initial inclination was to go with something like an op-code 1 = add, 2 = sub, but I don't know if that just adds more if-checks in one function and ultimately makes it as long or harder to read.</p> <p>Example:</p> <pre><code>void calc(int argc, char **argv, int op){ int i = 1, s = 0, x = 0; char sign = (op == 1) ? '+' : '-'; if(isHex(argv[i], strlen(argv[i]))) s = (x =convertHex(argv[i], strlen(argv[i]))); else s = atoi(argv[i]); for(i = 2;i&lt;argc;i++){ //Add if(op == 1){ if(isHex(argv[i], strlen(argv[i]))){ s += (x = convertHex(argv[i], strlen(argv[i]))); printf(&quot;%s&quot;, argv[i]); } else{ printf(&quot;%s&quot;, argv[i]); s += atoi(argv[i]); } if(i == argc-1) printf(&quot; %c &quot;, sign); else printf(&quot; %c &quot;, sign); } //Repeat for subtract //Print total printf(&quot;%d\n&quot;, s); } } </code></pre> <p>But that seems like just making 1 function larger without really optimizing anything.</p> <p>Does anyone have any suggestions or helpful advice for reducing the redundancy with add/sub (if its even possible)? Its not entirely necessary, but I'd appreciate any assistance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T03:29:29.973", "Id": "496049", "Score": "2", "body": "Please edit the title to describe what the code does rather than what you want from a review. E.g. \"Calculator that handles up to fifteen operands\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T18:33:03.207", "Id": "496123", "Score": "2", "body": "Please do not edit the question after an answer has been posted, especially the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T18:34:38.033", "Id": "496124", "Score": "0", "body": "Ah ok, gotcha. Still learning protocols here. I didn't edit the original code, just posted the \"after\", so now it has a picture of both before and after." } ]
[ { "body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Eliminate &quot;magic numbers&quot;</h2>\n<p>Instead of hard-coding the constants such as 3, 48 and 55 in the code, it would be better to use a <code>#define</code> or <code>const</code> and name them. Or, in the case of the <code>convertHex</code> code, use the character constant '0' instead of 48.</p>\n<h2>Use standard functions where applicable</h2>\n<p>Instead of this:</p>\n<pre><code>if(isHex(argv[i], strlen(argv[i])))\n s = (x =convertHex(argv[i], strlen(argv[i])));\nelse\n s = atoi(argv[i]); \n</code></pre>\n<p>I think I'd write this:</p>\n<pre><code>s = strtol(argv[i], NULL, 0);\n</code></pre>\n<h2>Pass values rather than hardcoding them</h2>\n<p>I'd suggest changing the signature of the <code>menu</code> function to this:</p>\n<pre><code>int menu(size_t numoptions, const char *const *options)\n</code></pre>\n<p>Note that we use <code>const</code> to show that we are not changing the options and that we pass the number of options. Now we can use this with any number of options rather than only three. Also, since the next thing we always do after showing the menu is getting the choice from the user, why not have <code>menu</code> return that choice?</p>\n<h2>Refactor aggressively</h2>\n<p>There is not only a lot of repetition here, but also a mixing of tasks. For instance, the <code>add</code> routine converts the numbers, adds them and prints them. Also, the only difference between <code>add</code> and <code>subtract</code> is, of course, the operation applied. I'd separate those like this:</p>\n<pre><code>int applyOperator(int argc, char **argv, int (*op)(int, int)) {\n int retval = strtol(argv[0], NULL, 0);\n for (int i = 1; i &lt; argc; ++i) {\n retval = op(retval, strtol(argv[i], NULL, 0));\n }\n return retval;\n}\n\nvoid printList(int argc, char **argv, const char *sep) {\n printf(&quot;%s&quot;, argv[0]);\n for (int i = 1; i &lt; argc; ++i) {\n printf(&quot;%s%s&quot;, sep, argv[i]);\n }\n}\n</code></pre>\n<p>Now we can create trivially simple <code>add</code> and <code>subtract</code> functions:</p>\n<pre><code>int add(int a, int b) {\n return a+b;\n}\n\nint subtract(int a, int b) {\n return a-b;\n}\n</code></pre>\n<p>And within <code>main</code>, use them like this:</p>\n<pre><code>case 1:\n printList(argc, argv, &quot; + &quot;);\n printf(&quot; = %d\\n&quot;, applyOperator(argc, argv, add));\n break;\n</code></pre>\n<p>Note also that we adjust <code>argc</code> and <code>argv</code> within <code>main</code> so that the arguments passed to the functions start at zero.</p>\n<h2>Eliminate unused <code>case</code>s</h2>\n<p>There is no way that <code>case 0</code> will ever be executed. For that reason, I'd be inclined to omit it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T16:16:21.810", "Id": "496106", "Score": "0", "body": "Thank you, I will work on implementing some of these changes and see how it goes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T17:27:34.340", "Id": "496116", "Score": "0", "body": "with your section \"Use Standard Functions\", I had read up on strtol and never realized that using the special value 0 would detect the 0x ahead of a hex. This was extremely helpful." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T15:19:27.203", "Id": "251908", "ParentId": "251884", "Score": "3" } } ]
{ "AcceptedAnswerId": "251908", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T01:20:56.560", "Id": "251884", "Score": "6", "Tags": [ "performance", "c" ], "Title": "Addition or Subtraction Calculator that Processes Up to 15 Operands" }
251884
<p>I wrote the following method which would just call an API which would then update a user's subscription to something.</p> <pre><code>void updateSubscription(String userId, boolean subscribed){ try{ // some stuff restTemplate.exchange(.....) // some stuff }catch (HttpClientErrorException exception){ log.error(&quot;API EXCEPTION - Received Status: {} - Stack Trace:&quot;,exception.getStatusCode(), exception); throw new ExternalAPIException(&quot;Service unavailable&quot;, HttpStatus.SERVICE_UNAVAILABLE); }catch (Exception e){ log.error(&quot;API EXCEPTION - Stack Trace:&quot;, e); throw new ExternalAPIException(&quot;Internal Server Error&quot;, HttpStatus.INTERNAL_SERVER_ERROR); } } </code></pre> <p>I have two questions in particular:</p> <ol> <li>Is the void return type okay? I am actually leaning towards returning a boolean indicating if the request was successful.</li> <li>Is the error handling okay?</li> </ol> <p>Note - it is a service class without a controller, so I can't use @controller's advice.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T13:25:38.250", "Id": "496075", "Score": "1", "body": "Welcome to the Code Review Community. Please post the complete code of the function so that we have enough information to properly review it. The comments `// some stuff` make the question off-topic for code review. Please read our guidelines on [how to ask a good question](https://codereview.stackexchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T16:45:14.187", "Id": "496108", "Score": "0", "body": "What do you mean by \"@controller's advice\"? Is \"controller\" a user here? Referring to a now-deleted comment?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T17:49:50.397", "Id": "496118", "Score": "1", "body": "@peter-mortensen it's the [@Controller](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/stereotype/Controller.html) annotation (spring)" } ]
[ { "body": "<p>&quot;okay&quot; in programming often depends on context.</p>\n<p>You chose to perform error handling by throwing exceptions, so there is no point in having a boolean return value - there will be no case where <code>false</code> is returned.</p>\n<p>If you are asking whether it is better to return <code>false</code> rather than throw exception, that largely depends on the situation.</p>\n<p>Your current error handling is already more granular than just success / failure - you want to detect different types of errors and respond differently, so the exception method is more appropriate.</p>\n<p>Note that if you were to switch to <code>return</code> and maintain same granularity, you would need to use an <code>Enum</code> of possible results.</p>\n<p>As for &quot;Is error handling ok&quot; - again, that depends.\nHow much 'some stuff' do you have around the API call?\nWhat kind of stuff is it?</p>\n<p>You may want to limit the amount of code in the catch block, and have separate catch blocks for other parts of code that may fail independently of any server errors.</p>\n<p>Then again, how granular do you want to make your error handling?\nUsually, the more precise the error and the more information user of the function has regarding why it failed the better, but if there are some constraints or type of errors that are not important they may be omitted, consolidated, or handled silently.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T08:05:11.277", "Id": "251889", "ParentId": "251887", "Score": "3" } }, { "body": "<p>If you're already using exceptions for error handling, adding an ok/fail return status alongside it adds no more additional useful information. Even if it was an error code structure with status and message, it adds nothing that is not already provided in the standard Java exception handling mechanism. You would just lose the stack trace information and exception chaining.</p>\n<p>Adding a separate domain specific error reporting mechanism places an additional burden to the caller as they have to wade through your JavaDocs (which, if my industry experience is anything to take from, are most likely missing :)) to figure out how the status code should be handled. So I would rather not try to bury the exception handling logic inside a specialized error reporting mechanism. Especially as you will eventually run into more exceptions again down the stream, so whatever you achieve with your solution would be just a temporary win.</p>\n<p>Also in this particular case, changing the method return value to ok/fail requires the caller to implement two different error handling routines for the same method call. So in this particular case it is absolutely not okay.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T13:41:23.090", "Id": "496076", "Score": "0", "body": "Are you referring the throwing of ExternalApiException as specialised error handling?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T09:35:52.917", "Id": "251891", "ParentId": "251887", "Score": "3" } } ]
{ "AcceptedAnswerId": "251889", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T06:13:34.583", "Id": "251887", "Score": "2", "Tags": [ "java", "rest", "spring" ], "Title": "API call return type and error handling" }
251887
<p><a href="https://leetcode.com/problems/is-subsequence/" rel="noreferrer">https://leetcode.com/problems/is-subsequence/</a></p> <p>Given a string s and a string t, check if s is subsequence of t.</p> <p>A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, &quot;ace&quot; is a subsequence of &quot;abcde&quot; while &quot;aec&quot; is not).</p> <p>Follow up: If there are lots of incoming S, say S1, S2, ... , Sk where k &gt;= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?</p> <p>Credits: Special thanks to @pbrother for adding this problem and creating all test cases.</p> <p>Example 1:</p> <p>Input: s = &quot;abc&quot;, t = &quot;ahbgdc&quot; Output: true Example 2:</p> <p>Input: s = &quot;axc&quot;, t = &quot;ahbgdc&quot; Output: false</p> <p>Constraints:</p> <p>0 &lt;= s.length &lt;= 100 0 &lt;= t.length &lt;= 10^4 Both strings consists only of lowercase characters.</p> <p>Please review for performance.</p> <pre><code>using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace RecurssionQuestions { /// &lt;summary&gt; /// https://leetcode.com/problems/is-subsequence/ /// &lt;/summary&gt; [TestClass] public class IsSubsequenceTest { [TestMethod] public void TestMethod1() { string s = &quot;abc&quot;, t = &quot;ahbgdc&quot;; Assert.IsTrue(IsSubsequence(s, t)); Assert.IsTrue(IsSubsequence2(s, t)); } [TestMethod] public void TestMethod2() { string s = &quot;axc&quot;, t = &quot;ahbgdc&quot;; Assert.IsFalse(IsSubsequence(s, t)); Assert.IsFalse(IsSubsequence2(s, t)); } public bool IsSubsequence(string s, string t) { return Helper(s, t, 0, 0); } /// &lt;summary&gt; /// if the letters are equal (letter is found) continue to the next letter of s /// if the letter is not found in t continue to the next letter of t. /// if you reached the end of s, then s is a subsequence of t. /// if you reach the end of t. then s is not a subsequence of t /// &lt;/summary&gt; /// &lt;param name=&quot;s&quot;&gt;&lt;/param&gt; /// &lt;param name=&quot;t&quot;&gt;&lt;/param&gt; /// &lt;param name=&quot;sIndex&quot;&gt;&lt;/param&gt; /// &lt;param name=&quot;tIndex&quot;&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; private bool Helper(string s, string t, int sIndex, int tIndex) { if (sIndex == s.Length) { return true; } if (tIndex == t.Length) { return false; } if (s[sIndex] == t[tIndex]) { return Helper(s, t, sIndex + 1, tIndex + 1); } else { return Helper(s, t, sIndex, tIndex + 1); } } public bool IsSubsequence2(string s, string t) { if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(t)) { return false; } Dictionary&lt;char, List&lt;int&gt;&gt; map = new Dictionary&lt;char, List&lt;int&gt;&gt;(); //pre-process t for (int i = 0; i &lt; t.Length; i++) { if (!map.ContainsKey(t[i])) { map.Add(t[i], new List&lt;int&gt;()); } map[t[i]].Add(i); } int prev = -1; for (int i = 0; i &lt; s.Length; i++) { if (!map.ContainsKey(s[i])) { return false; } else { var list = map[s[i]]; prev = BinarySearch(prev, list, 0, list.Count - 1); if (prev == -1) { return false; } prev++; } } return true; } private int BinarySearch(int prev, List&lt;int&gt; list, int start, int end) { while (start &lt;= end) { int mid = (end - start) / 2 + start; if (list[mid] &lt; prev) { start = mid + 1; } else { end = mid - 1; } } if (start == list.Count) { return -1; } return list[start]; } } } </code></pre>
[]
[ { "body": "<p>From a performance point of perspective, <code>IsSubsequence</code> will always be faster than <code>IsSubsequence2</code>, because it only needs to iterate 2 arrays simultaneously and has no further allocations on the heap.</p>\n<p>If you want to improve on performance and also make sure, you never get a <code>StackOverFlowException</code>, you should get rid of the recursion in your <code>Helper</code> method and instead use a loop.</p>\n<pre><code>public static bool IsSubsequence3(string s, string t)\n{\n var sIndex = 0;\n for (var tIndex = 0; tIndex &lt; t.Length; tIndex++)\n {\n if (s[sIndex] == t[tIndex])\n sIndex++;\n \n if(sIndex == s.Length)\n return true;\n }\n \n return false;\n}\n</code></pre>\n<p>When running a Debug build, using the input <code>string s = &quot;abc&quot;, t = &quot;ahbgdc&quot;;</code> and executing the Method more than 1,000,000 times, <code>IsSubsequence4</code> becomes faster. However when you run it in a Release build, the performance is the same, as compiler optimizations kick in and they will implicitly do what is written here explicitly (trade the property access for a local field).</p>\n<pre><code>public static bool IsSubsequence4(string s, string t)\n{\n var sIndex = 0;\n var sLength = s.Length;\n var tLength = t.Length;\n for (var tIndex = 0; tIndex &lt; tLength; tIndex++)\n {\n if (s[sIndex] == t[tIndex])\n sIndex++;\n \n if(sIndex == sLength)\n return true;\n }\n \n return false;\n}\n</code></pre>\n<p>I also tried using <code>AsSpan()</code> and <code>ToCharArray()</code> and the strings to get rid of the <code>callvirt System.String.get_Chars</code> in the IL code and I tried using an Enumerator. Both where slower than <code>IsSubsequence3</code></p>\n<pre><code>public static bool IsSubsequence5(string s, string t)\n{\n var sIndex = 0;\n var sLength = s.Length;\n var tLength = t.Length;\n var sChars = s.AsSpan();\n var tChars = t.AsSpan();\n for (var tIndex = 0; tIndex &lt; tLength; tIndex++)\n {\n if (sChars[sIndex] == tChars[tIndex])\n sIndex++;\n \n if(sIndex == sLength)\n return true;\n }\n \n return false;\n}\n</code></pre>\n<pre><code>public static bool IsSubsequence6(string s, string t)\n{\n using var sEnum = s.GetEnumerator();\n sEnum.MoveNext();\n using var tEnum = t.GetEnumerator();\n while (tEnum.MoveNext())\n {\n if (sEnum.Current == tEnum.Current)\n {\n if(!sEnum.MoveNext())\n return true;\n }\n }\n \n return false;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T12:06:55.080", "Id": "497020", "Score": "0", "body": "Thank you very much for the review. And the experminents you did!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T07:40:23.507", "Id": "252289", "ParentId": "251888", "Score": "3" } } ]
{ "AcceptedAnswerId": "252289", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T07:52:36.513", "Id": "251888", "Score": "5", "Tags": [ "c#", "interview-questions" ], "Title": "LeetCode: is subsequence C#" }
251888
<p>Could you please give me some feedback on the use of class methods in this Python script? The code retrieves time entries from the <a href="https://github.com/toggl/toggl_api_docs" rel="nofollow noreferrer">Toggl API</a> and works as expected. My question is, do the methods make sense? The methods <code>first_api_call</code> and <code>make_subsequent_calls</code> change <code>self.data</code>. Is this okay or should all the changes to <code>self.data</code> be made in <code>retrieve_data</code>?</p> <pre><code>from datetime import datetime import requests today = datetime.today().date() since = datetime(today.year, 1, 1) class Toggl: def __init__(self): self.data = [] self.total_calls = None self.params = { 'workspace_id': '5604761', 'since': since, 'until': today, 'user_agent': 'john@doe.com', 'page': 1, } def retrieve_data(self): r = self.first_api_call() self.total_calls = self.calculate_number_of_extra_calls_needed(r) self.make_subsequent_calls() def first_api_call(self): r = requests.get('https://toggl.com/reports/api/v2/details', params=self.params, auth=('APIKEY', 'api_token')) r.raise_for_status() r = r.json() self.data = r['data'] return r def calculate_number_of_extra_calls_needed(self, r): &quot;&quot;&quot; Calculate the number of pages that need to be retrieved. The second part is True/False to round up. Finally minus 1 because we got the first page already. &quot;&quot;&quot; total_calls = r['total_count'] // 50 + (r['total_count'] % 50 &gt; 0) - 1 return total_calls def make_subsequent_calls(self): &quot;&quot;&quot;Make the new API calls and store the data&quot;&quot;&quot; for i in range(self.total_calls): self.params['page'] = self.params['page'] + 1 r = requests.get('https://toggl.com/reports/api/v2/details', params=self.params, auth=('APIKEY', 'api_token')) r.raise_for_status() r = r.json() for d in r['data']: self.data.append(d) if __name__ == &quot;__main__&quot;: toggl = Toggl() toggl.retrieve_data() print(toggl.data) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T11:20:19.593", "Id": "496068", "Score": "0", "body": "In general is a good practice to have the requests.get operations on a try block, so if there is an issue on the network, or auth your program can continue" } ]
[ { "body": "<p>It might be best to move</p>\n<pre><code>today = datetime.today().date()\nsince = datetime(today.year, 1, 1)\n</code></pre>\n<p>into the class's <code>__init__</code>. As it is, the code will just be run once when the module loads, whereas it would make more sense to work out the date when you construct <code>Toggl</code>.</p>\n<p>I'd also say that having two methods for what is essentially the exact same task could be streamlined. Perhaps something like this?</p>\n<pre class=\"lang-py prettyprint-override\"><code>import math\n\n# Default page size in the Toggl API.\nPAGE_SIZE = 50\n\nclass Toggl:\n def __init__(self):\n today = datetime.today().date()\n since = datetime(today.year, 1, 1)\n self.data = []\n self.total_calls = None\n self.params = {\n 'workspace_id': '5604761',\n 'since': since,\n 'until': today,\n 'user_agent': 'john@doe.com'\n }\n\n def fetch_page(self, page_number):\n params = self.params\n params['page'] = page_number\n r = requests.get('https://toggl.com/reports/api/v2/details',\n params=params,\n auth=('APIKEY', 'api_token'))\n r.raise_for_status()\n return r.json()\n\n def retrieve_data(self):\n r = self.fetch_page(1)\n self.data = r['data']\n pages = self.total_pages(r['total_count'])\n for i in range(2, pages + 1):\n r = self.fetch_page(i)\n self.data += r['data']\n\n def total_pages(self, total_count):\n return math.ceil(total_count / PAGE_SIZE)\n</code></pre>\n<p>In particular, any &quot;magic number&quot; constants should be taken out and put at the top as constants (by convention in <code>SCREAMING_SNAKE_CASE</code>). I tweaked the function names to be more descriptive, and replaced <code>first_api_call</code> and <code>make_subsequent_calls</code> with a function that doesn't affect the state: instead it just makes a call to fetch the required page and <code>retreive_data</code> decides what to do with it. I don't think there's anything inherently wrong with doing it as you did though, I just personally thought <code>fetch_page</code> seemed cleaner and reduced duplication.</p>\n<p>You can simplify the calculation to work out how many pages you need using <code>math.ceil</code> as I demonstrate above too: for example 101 / 50 = 2.02, which is mapped to 3 by <code>math.ceil</code>.</p>\n<p>To make the code even better, you could avoid storing the API key hard coded: take it as a parameter in the constructor and store it in <code>self</code>. You could also take <code>since</code> and <code>today</code> as parameters so the user can choose the range that they want to obtain.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T11:13:07.613", "Id": "496067", "Score": "1", "body": "Thank you very much, this is exactly what I meant. API responses are almost always paginated. I like how you encapsulated it in the retrieval method. Great other recommendations too, I'll incorporate them all in my code. (BTW: the API keys live in environment variables, just hardcoded them to simplify the example). Thanks again, it is very much appreciated!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T10:52:50.037", "Id": "251895", "ParentId": "251892", "Score": "2" } } ]
{ "AcceptedAnswerId": "251895", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T09:55:27.140", "Id": "251892", "Score": "3", "Tags": [ "python", "object-oriented" ], "Title": "Python: Use of class methods to change data" }
251892
<p>I am trying to resolve below question in order to prepare for an interview xD</p> <blockquote> <p>An XOR linked list is a more memory efficient doubly linked list. Instead of each node holding next and prev fields, it holds a field named both, which is an XOR of the next node and the previous node. Implement an XOR linked list; it has an add(element) which adds the element to the end, and a get(index) which returns the node at index.</p> </blockquote> <p>Please suggest how this implementation can be improved. Thank you in prior.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; typedef struct { int value; long both; } StNode; typedef StNode *pStNode; pStNode add(pStNode lastNode, int value) { pStNode newNode = (StNode *) malloc(sizeof(StNode)); newNode-&gt;value = value; //[both]=value of previous node pointer if it is last node newNode-&gt;both = (long)lastNode; //calculating previous node [both] value lastNode-&gt;both = (long)newNode ^ lastNode-&gt;both; return newNode; } pStNode get(pStNode headNode, int index) { pStNode prevNode; pStNode currNode; long tmp; //special handling //case: cur=1, prev=0 //we have set previous node of head node value to be 0 manually currNode = (StNode *) ((headNode-&gt;both) ^ 0); prevNode = headNode; //skim through linked list for(int i=2; i&lt;=index; i++) { tmp = (long)prevNode; prevNode = currNode; currNode = (StNode *)(currNode-&gt;both ^ tmp); } return currNode; } int main() { //I named first node as headNode, and last node as tailNode //create head node with both=0 since there is no previous node to it pStNode headNode = (StNode *) malloc(sizeof(StNode)); headNode-&gt;both = 0; headNode-&gt;value = 2; //assign pointers pStNode tailNode = headNode; //lets add 10 nodes after head, and assign values for(int i=3; i&lt;13; i++) { tailNode = add(tailNode, i); } //get node value where index=3 pStNode iNode = get(headNode, 3); printf( &quot;result: %d\n&quot;, iNode-&gt;value); return 0; } </code></pre>
[]
[ { "body": "<p><code>long</code> isn't necessarily a good choice of integer type for storing pointers - luckily <code>&lt;stdint.h&gt;</code> provides us with <code>uintptr_t</code> which is guaranteed to be wide enough for this purpose (always prefer an unsigned type when working with bitwise operations).</p>\n<p>I dislike hiding pointer types behind typedefs such as <code>pStNode</code>. I think it's clearer to use the pointer type directly - or a pointer to <code>const StNode</code> where appropriate. For example, <code>get()</code> should take a pointer to const.</p>\n<p>It's unnecessary (and generally considered unwise) to cast the result of <code>malloc()</code>. <code>void*</code> can be assigned to any kind of pointer in C.</p>\n<p>There's quite a lot missing from the code that I would expect from something claiming to be an <em>implementation</em> of the list. There's no function for removing elements, and the only accessor provided is the poorly-performing random-access getter.</p>\n<p>In particular, you haven't provided <code>next()</code> and <code>prev()</code> functions, which I'd expect to see if you want to demonstrate that both directions of traversal work correctly.</p>\n<p>Why does <code>get()</code> accept a signed integer for the index? It appears that negative values are all equivalent to 0; we should either make those work or accept an unsigned type instead. Also, we can safely reduce the scope of <code>tmp</code> to within the loop.</p>\n<p>It's best to write <code>main()</code> as a function prototype <code>int main(void)</code> (i.e. taking no arguments, rather than an unspecified number of arguments). And unlike other functions, <code>main()</code> doesn't need to return a value for success, so that line can be omitted.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T05:51:32.327", "Id": "496154", "Score": "0", "body": "In my opinion, it will be impossible to implement next(), and prev() functions unless current and previous or next node pointers are referenced as a parameter. I think that is why the original question asked to extract Nth element (assuming swiping down from head node). Correct me if I am wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T05:57:45.083", "Id": "496155", "Score": "0", "body": "about the rest, I will implement new method according to your suggestion also" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T06:17:13.927", "Id": "496156", "Score": "0", "body": "Please take a look at new version: https://codereview.stackexchange.com/questions/251932/xor-linked-list-implementation-follow-up" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T13:29:44.553", "Id": "251898", "ParentId": "251894", "Score": "7" } }, { "body": "<pre><code>long both;\n</code></pre>\n<ol>\n<li>Using a <code>long</code> for storing a cast pointer can be both wasteful and too little. Just use the dedicated <a href=\"https://en.cppreference.com/w/c/types/integer\" rel=\"nofollow noreferrer\"><code>uintptr_t</code></a>. Even if your implementation might not be fully up to C99 (MS greets), it probably has <code>&lt;stdint.h&gt;</code> and the typedef.</li>\n</ol>\n<pre><code>pStNode newNode = (StNode *) malloc(sizeof(StNode));\n</code></pre>\n<p>The above line demonstrates three bad ideas:</p>\n<ol start=\"2\">\n<li><p>More pieces to keep track of means more complexity, which is bad. Thus hiding pointers behind typedefs is a bad idea, unless that pointer-type is never dereferenced, and is thus the one true type used.</p>\n</li>\n<li><p>Casting a <code>void*</code> is superfluous and error-prone.<br />\nSee &quot;<em><a href=\"//stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc\">Do I cast the result of malloc?\n</a></em>&quot;.</p>\n</li>\n<li><p>Don't use <code>sizeof(TYPE)</code> unless unavoidable. Getting it right even if the types aren't obscured is error-prone. Just use <code>sizeof *pointer</code>.</p>\n</li>\n</ol>\n<pre><code>pStNode get(pStNode headNode, int index)\n</code></pre>\n<ol start=\"5\">\n<li><p>There is a type uniquely suited as an index: <code>size_t</code>. Alternatively, if you want something signed, you might be interested in <code>ptrdiff_t</code>. Though yes, if your use-case guarantees few enough nodes, <code>int</code> might work.</p>\n</li>\n<li><p>You really should encapsulate your list somehow. Currently, you are creating a one-off in <code>main()</code>.<br />\nAlso, cleanup should be possible without terminating the program.</p>\n</li>\n<li><p>If you use at least C99, <code>main()</code> has an implicit <code>return 0;</code>.</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T06:17:28.060", "Id": "496157", "Score": "0", "body": "Please check my new version: https://codereview.stackexchange.com/questions/251932/xor-linked-list-implementation-follow-up" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T13:47:44.463", "Id": "251900", "ParentId": "251894", "Score": "8" } } ]
{ "AcceptedAnswerId": "251898", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T10:27:22.910", "Id": "251894", "Score": "6", "Tags": [ "c", "linked-list", "interview-questions" ], "Title": "XOR linked list implementation" }
251894
<p>This is my first attempt to learn Rust by applying it for a problem that I assume is suitable for the language. It's the Intcode computer from <a href="https://adventofcode.com/2019" rel="noreferrer">https://adventofcode.com/2019</a>.</p> <p>I've implemented all the features of the computer, and the result is the following:</p> <pre><code>use crate::ComputeResult::{CanContinue, Halt, WaitingForInput}; use std::sync::mpsc; use std::sync::mpsc::{Receiver, Sender}; use std::thread; fn main() { let input = &quot;1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,6,1,19,1,19,5,23,2,9,23,27,1,5,27,31,1,5,31,35,1,35,13,39,1,39,9,43,1,5,43,47,1,47,6,51,1,51,13,55,1,55,9,59,1,59,13,63,2,63,13,67,1,67,10,71,1,71,6,75,2,10,75,79,2,10,79,83,1,5,83,87,2,6,87,91,1,91,6,95,1,95,13,99,2,99,13,103,1,103,9,107,1,10,107,111,2,111,13,115,1,10,115,119,1,10,119,123,2,13,123,127,2,6,127,131,1,13,131,135,1,135,2,139,1,139,6,0,99,2,0,14,0&quot;; println!(&quot;Hello, world, {:?}&quot;, str_to_intcode(input)); } fn str_to_intcode(string: &amp;str) -&gt; Vec&lt;i64&gt; { string .split_terminator(&quot;,&quot;) .map(|s| s.parse().unwrap()) .collect() } struct State { instruction_pointer: u32, intcode: Vec&lt;i64&gt;, input: Vec&lt;i64&gt;, output: Vec&lt;i64&gt;, relative_base: i64, } enum ComputeResult { Halt, CanContinue, WaitingForInput, } //todo turn into an enumeration instead of using u8 for the parameter modes? fn parameter_modes(opcode: i64) -&gt; (u8, u8, u8, u8) { let a = opcode / 10000; let b = (opcode - a * 10000) / 1000; let c = (opcode - a * 10000 - b * 1000) / 100; let d = opcode - a * 10000 - b * 1000 - c * 100; (a as u8, b as u8, c as u8, d as u8) } fn state_from_string(string: &amp;str) -&gt; State { State { instruction_pointer: 0, intcode: str_to_intcode(string), input: vec![], output: vec![], relative_base: 0, } } //todo how to deal with the situation when the state is invalid or the parameter mode isn't supported? fn get_value(parameter_mode: u8, pointer: u32, state: &amp;State) -&gt; i64 { //position mode if parameter_mode == 0 { let at_index = state.intcode[pointer as usize]; state.intcode[at_index as usize] } //immediate mode else if parameter_mode == 1 { state.intcode[pointer as usize] } else if parameter_mode == 2 { let at_index = state.intcode[pointer as usize] + state.relative_base as i64; state.intcode[at_index as usize] } else { panic!(&quot;parameter mode {} not supported&quot;, parameter_mode) } } fn extend_memory(memory_index: u32, state: &amp;mut State) { if memory_index &gt;= state.intcode.len() as u32 { state.intcode.resize((memory_index + 1) as usize, 0); } } fn get_memory_address(parameter_mode: u8, pointer: u32, state: &amp;State) -&gt; i64 { //position mode if parameter_mode == 0 { state.intcode[pointer as usize] } //immediate mode else if parameter_mode == 1 { panic!(&quot;writing to memory will never be in immediate mode&quot;) } //relative mode else if parameter_mode == 2 { state.intcode[pointer as usize] + state.relative_base as i64 } else { panic!(&quot;parameter mode {} not supported&quot;, parameter_mode) } } fn five_amplifiers_in_sequence(intcode: &amp;str, phase_setting: Vec&lt;i64&gt;) -&gt; i64 { computer(intcode, vec![0, phase_setting[0]]) //todo refactor pop for something immutable? .and_then(|mut o| computer(intcode, vec![o.pop().unwrap(), phase_setting[1]])) .and_then(|mut o| computer(intcode, vec![o.pop().unwrap(), phase_setting[2]])) .and_then(|mut o| computer(intcode, vec![o.pop().unwrap(), phase_setting[3]])) .and_then(|mut o| computer(intcode, vec![o.pop().unwrap(), phase_setting[4]])) .ok() .unwrap() .pop() .unwrap() } fn computer(intcode: &amp;str, input: Vec&lt;i64&gt;) -&gt; Result&lt;Vec&lt;i64&gt;, &amp;str&gt; { let mut state = state_from_string(intcode); state.input = input; loop { match compute(&amp;mut state) { Ok(r) =&gt; match r { Halt | WaitingForInput =&gt; break Ok(state.output), CanContinue =&gt; continue, }, //todo refactor the nested match and simplify the error mapping Err(_) =&gt; break Err(&quot;bam&quot;), } } } fn pop_and_send(state: &amp;mut State, rx: &amp;Sender&lt;i64&gt;) -&gt; i64 { let mut last = 0; loop { //todo for future use-cases, this might not be desired behaviour, replace with drain match state.output.pop() { None =&gt; break last, Some(v) =&gt; { last = v; rx.send(v) } }; } } fn five_amplifiers_in_a_feedback_loop( intcode: &amp;'static str, phase_setting: Vec&lt;i32&gt;, ) -&gt; Option&lt;i64&gt; { assert_eq!( phase_setting.len(), 5, &quot;phase sequence of length five expected, while {} provided&quot;, phase_setting.len() ); let (tx_a, rx_a): (Sender&lt;i64&gt;, Receiver&lt;i64&gt;) = mpsc::channel(); let (tx_b, rx_b): (Sender&lt;i64&gt;, Receiver&lt;i64&gt;) = mpsc::channel(); let (tx_c, rx_c): (Sender&lt;i64&gt;, Receiver&lt;i64&gt;) = mpsc::channel(); let (tx_d, rx_d): (Sender&lt;i64&gt;, Receiver&lt;i64&gt;) = mpsc::channel(); let (tx_e, rx_e): (Sender&lt;i64&gt;, Receiver&lt;i64&gt;) = mpsc::channel(); let lambda = move |name: &amp;str, tx: Sender&lt;i64&gt;, rx: Receiver&lt;i64&gt;| -&gt; i64 { let mut state = state_from_string(intcode); loop { match compute(&amp;mut state) { Ok(r) =&gt; match r { Halt =&gt; { break pop_and_send(&amp;mut state, &amp;tx); } WaitingForInput =&gt; { pop_and_send(&amp;mut state, &amp;tx); match rx.recv() { Ok(v) =&gt; { state.input.push(v); continue; } Err(e) =&gt; panic!(&quot;{} error: {}&quot;, name, e), } } CanContinue =&gt; continue, }, //todo refactor the nested match and simplify the error mapping Err(_) =&gt; panic!(&quot;{} &quot;,), } } }; tx_a.send(phase_setting[0] as i64) .and_then(|_| tx_a.send(0)) .and_then(|_| tx_b.send(phase_setting[1] as i64)) .and_then(|_| tx_c.send(phase_setting[2] as i64)) .and_then(|_| tx_d.send(phase_setting[3] as i64)) .and_then(|_| tx_e.send(phase_setting[4] as i64)) .unwrap(); let _a = thread::spawn(move || lambda(&quot;A&quot;, tx_b, rx_a)); let _b = thread::spawn(move || lambda(&quot;B&quot;, tx_c, rx_b)); let _c = thread::spawn(move || lambda(&quot;C&quot;, tx_d, rx_c)); let _d = thread::spawn(move || lambda(&quot;D&quot;, tx_e, rx_d)); let e = thread::spawn(move || lambda(&quot;E&quot;, tx_a, rx_e)); e.join().ok() } fn compute(state: &amp;mut State) -&gt; Result&lt;ComputeResult, String&gt; { let offset = state.instruction_pointer; //todo is this defensive programming a good idea? assert!( offset &lt; state.intcode.len() as u32, &quot;offset {} out of bounds, intcode length {}&quot;, offset, state.intcode.len() ); assert!(state.intcode.len() &gt; 0, &quot;no intcode to process&quot;); let (a, b, c, opcode) = parameter_modes(state.intcode[offset as usize]); //add if opcode == 1 { let memory_address = get_memory_address(a, offset + 3, state); extend_memory(memory_address as u32, state); let first_parameter = get_value(c, offset + 1, state); let second_parameter = get_value(b, offset + 2, state); state.intcode[memory_address as usize] = first_parameter + second_parameter; state.instruction_pointer += 4; Ok(CanContinue) } //multiply else if opcode == 2 { let memory_address = get_memory_address(a, offset + 3, state); extend_memory(memory_address as u32, state); let first_parameter = get_value(c, offset + 1, state); let second_parameter = get_value(b, offset + 2, state); state.intcode[memory_address as usize] = first_parameter * second_parameter; state.instruction_pointer += 4; Ok(CanContinue) } //input else if opcode == 3 { let memory_address = get_memory_address(c, offset + 1, state); //attempt to read from the input match state.input.pop() { Some(v) =&gt; { extend_memory(memory_address as u32, state); state.intcode[memory_address as usize] = v as i64; state.instruction_pointer += 2; Ok(CanContinue) } None =&gt; Ok(WaitingForInput), } } //output else if opcode == 4 { let value_to_output = get_value(c, offset + 1, state); state.output.push(value_to_output); state.instruction_pointer += 2; Ok(CanContinue) } //jump it true else if opcode == 5 { let first_parameter = get_value(c, offset + 1, state); let second_parameter = get_value(b, offset + 2, state); if first_parameter != 0 { state.instruction_pointer = second_parameter as u32; } else { state.instruction_pointer += 3; } Ok(CanContinue) } //jump it false else if opcode == 6 { let first_parameter = get_value(c, offset + 1, state); let second_parameter = get_value(b, offset + 2, state); if first_parameter == 0 { state.instruction_pointer = second_parameter as u32; } else { state.instruction_pointer += 3; } Ok(CanContinue) } //less than //todo refactor because the only difference in the logic for opcode 7 and 8 is '&lt;' vs. '==', lambda or something? else if opcode == 7 { let memory_address = get_memory_address(a, offset + 3, state); extend_memory(memory_address as u32, state); let first_parameter = get_value(c, offset + 1, state); let second_parameter = get_value(b, offset + 2, state); let value = if first_parameter &lt; second_parameter { 1 } else { 0 }; state.intcode[memory_address as usize] = value; state.instruction_pointer += 4; Ok(CanContinue) } //equals else if opcode == 8 { let memory_address = get_memory_address(a, offset + 3, state); extend_memory(memory_address as u32, state); let first_parameter = get_value(c, offset + 1, state); let second_parameter = get_value(b, offset + 2, state); let value = if first_parameter == second_parameter { 1 } else { 0 }; state.intcode[memory_address as usize] = value; state.instruction_pointer += 4; Ok(CanContinue) } //adjust relative base else if opcode == 9 { let first_parameter = get_value(c, offset + 1, state); state.relative_base += first_parameter; state.instruction_pointer += 2; Ok(CanContinue) } else if opcode == 99 { Ok(Halt) } else { let error = format!(&quot;{} {}&quot;, &quot;Unknown opcode&quot;, opcode); Err(error) } } #[cfg(test)] mod tests { use crate::{ computer, five_amplifiers_in_a_feedback_loop, five_amplifiers_in_sequence, str_to_intcode, }; use permutohedron::Heap; #[test] fn can_parse_intcode() { assert_eq!(vec![1, 0, 0, 0, 99], str_to_intcode(&quot;1,0,0,0,99&quot;)); } #[test] fn input_output() { assert_output(&quot;3,0,4,0,99&quot;, Some(55), vec![55]) } #[test] fn parameter_modes() { assert_output(&quot;1002,4,3,4,33&quot;, None, vec![]) } fn input_day5() -&gt; &amp;'static str { &quot;3,225,1,225,6,6,1100,1,238,225,104,0,1,192,154,224,101,-161,224,224,4,224,102,8,223,223,101,5,224,224,1,223,224,223,1001,157,48,224,1001,224,-61,224,4,224,102,8,223,223,101,2,224,224,1,223,224,223,1102,15,28,225,1002,162,75,224,1001,224,-600,224,4,224,1002,223,8,223,1001,224,1,224,1,224,223,223,102,32,57,224,1001,224,-480,224,4,224,102,8,223,223,101,1,224,224,1,224,223,223,1101,6,23,225,1102,15,70,224,1001,224,-1050,224,4,224,1002,223,8,223,101,5,224,224,1,224,223,223,101,53,196,224,1001,224,-63,224,4,224,102,8,223,223,1001,224,3,224,1,224,223,223,1101,64,94,225,1102,13,23,225,1101,41,8,225,2,105,187,224,1001,224,-60,224,4,224,1002,223,8,223,101,6,224,224,1,224,223,223,1101,10,23,225,1101,16,67,225,1101,58,10,225,1101,25,34,224,1001,224,-59,224,4,224,1002,223,8,223,1001,224,3,224,1,223,224,223,4,223,99,0,0,0,677,0,0,0,0,0,0,0,0,0,0,0,1105,0,99999,1105,227,247,1105,1,99999,1005,227,99999,1005,0,256,1105,1,99999,1106,227,99999,1106,0,265,1105,1,99999,1006,0,99999,1006,227,274,1105,1,99999,1105,1,280,1105,1,99999,1,225,225,225,1101,294,0,0,105,1,0,1105,1,99999,1106,0,300,1105,1,99999,1,225,225,225,1101,314,0,0,106,0,0,1105,1,99999,1108,226,226,224,102,2,223,223,1005,224,329,101,1,223,223,107,226,226,224,1002,223,2,223,1005,224,344,1001,223,1,223,107,677,226,224,102,2,223,223,1005,224,359,101,1,223,223,7,677,226,224,102,2,223,223,1005,224,374,101,1,223,223,108,226,226,224,102,2,223,223,1006,224,389,101,1,223,223,1007,677,677,224,102,2,223,223,1005,224,404,101,1,223,223,7,226,677,224,102,2,223,223,1006,224,419,101,1,223,223,1107,226,677,224,1002,223,2,223,1005,224,434,1001,223,1,223,1108,226,677,224,102,2,223,223,1005,224,449,101,1,223,223,108,226,677,224,102,2,223,223,1005,224,464,1001,223,1,223,8,226,677,224,1002,223,2,223,1005,224,479,1001,223,1,223,1007,226,226,224,102,2,223,223,1006,224,494,101,1,223,223,1008,226,677,224,102,2,223,223,1006,224,509,101,1,223,223,1107,677,226,224,1002,223,2,223,1006,224,524,1001,223,1,223,108,677,677,224,1002,223,2,223,1005,224,539,1001,223,1,223,1107,226,226,224,1002,223,2,223,1006,224,554,1001,223,1,223,7,226,226,224,1002,223,2,223,1006,224,569,1001,223,1,223,8,677,226,224,102,2,223,223,1006,224,584,101,1,223,223,1008,677,677,224,102,2,223,223,1005,224,599,101,1,223,223,1007,226,677,224,1002,223,2,223,1006,224,614,1001,223,1,223,8,677,677,224,1002,223,2,223,1005,224,629,101,1,223,223,107,677,677,224,102,2,223,223,1005,224,644,101,1,223,223,1108,677,226,224,102,2,223,223,1005,224,659,101,1,223,223,1008,226,226,224,102,2,223,223,1006,224,674,1001,223,1,223,4,223,99,226&quot; } #[test] fn day5_part_one() { assert_output( input_day5(), Some(1), vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 11049715], ) } #[test] fn day5_part_two() { assert_output(input_day5(), Some(5), vec![2140710]) } fn input_day7() -&gt; &amp;'static str { &quot;3,8,1001,8,10,8,105,1,0,0,21,42,67,84,97,118,199,280,361,442,99999,3,9,101,4,9,9,102,5,9,9,101,2,9,9,1002,9,2,9,4,9,99,3,9,101,5,9,9,102,5,9,9,1001,9,5,9,102,3,9,9,1001,9,2,9,4,9,99,3,9,1001,9,5,9,1002,9,2,9,1001,9,5,9,4,9,99,3,9,1001,9,5,9,1002,9,3,9,4,9,99,3,9,102,4,9,9,101,4,9,9,102,2,9,9,101,3,9,9,4,9,99,3,9,102,2,9,9,4,9,3,9,1002,9,2,9,4,9,3,9,1001,9,2,9,4,9,3,9,102,2,9,9,4,9,3,9,102,2,9,9,4,9,3,9,1001,9,2,9,4,9,3,9,1002,9,2,9,4,9,3,9,102,2,9,9,4,9,3,9,1001,9,2,9,4,9,3,9,101,2,9,9,4,9,99,3,9,1001,9,1,9,4,9,3,9,101,2,9,9,4,9,3,9,1001,9,2,9,4,9,3,9,1002,9,2,9,4,9,3,9,101,2,9,9,4,9,3,9,1002,9,2,9,4,9,3,9,102,2,9,9,4,9,3,9,1002,9,2,9,4,9,3,9,101,1,9,9,4,9,3,9,101,2,9,9,4,9,99,3,9,101,1,9,9,4,9,3,9,1001,9,1,9,4,9,3,9,1002,9,2,9,4,9,3,9,1002,9,2,9,4,9,3,9,1002,9,2,9,4,9,3,9,1001,9,2,9,4,9,3,9,102,2,9,9,4,9,3,9,102,2,9,9,4,9,3,9,101,2,9,9,4,9,3,9,1001,9,2,9,4,9,99,3,9,102,2,9,9,4,9,3,9,102,2,9,9,4,9,3,9,1001,9,2,9,4,9,3,9,102,2,9,9,4,9,3,9,1001,9,2,9,4,9,3,9,102,2,9,9,4,9,3,9,102,2,9,9,4,9,3,9,101,1,9,9,4,9,3,9,1001,9,2,9,4,9,3,9,1002,9,2,9,4,9,99,3,9,101,1,9,9,4,9,3,9,101,1,9,9,4,9,3,9,102,2,9,9,4,9,3,9,1001,9,2,9,4,9,3,9,1001,9,2,9,4,9,3,9,1002,9,2,9,4,9,3,9,101,1,9,9,4,9,3,9,102,2,9,9,4,9,3,9,1001,9,1,9,4,9,3,9,1001,9,2,9,4,9,99&quot; } #[test] fn day7_examples() { assert_eq!( five_amplifiers_in_sequence( &quot;3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0&quot;, vec![4, 3, 2, 1, 0] ), 43210 ); assert_eq!( five_amplifiers_in_sequence( &quot;3,23,3,24,1002,24,10,24,1002,23,-1,23,101,5,23,23,1,24,23,23,4,23,99,0,0&quot;, vec![0, 1, 2, 3, 4] ), 54321 ); assert_eq!( five_amplifiers_in_sequence( &quot;3,31,3,32,1002,32,10,32,1001,31,-2,31,1007,31,0,33,1002,33,7,33,1,33,31,31,1,32,31,31,4,31,99,0,0,0&quot;, vec![1, 0, 4, 3, 2] ), 65210 ); assert_eq!( five_amplifiers_in_a_feedback_loop(&quot;3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5&quot;, vec![9, 8, 7, 6, 5]), Some(139629729)); assert_eq!( five_amplifiers_in_a_feedback_loop(&quot;3,52,1001,52,-5,52,3,53,1,52,56,54,1007,54,5,55,1005,55,26,1001,54,-5,54,1105,1,12,1,53,54,53,1008,54,0,55,1001,55,1,55,2,53,55,53,4,53,1001,56,-1,56,1005,56,6,99,0,0,0,0,10&quot;, vec![9, 7, 8, 5, 6]), Some(18216)) } #[test] fn day7_part_two() { let mut data = vec![5, 6, 7, 8, 9]; let heap = Heap::new(&amp;mut data); let mut permutations = Vec::new(); for data in heap { permutations.push(data.clone()); } let mut res: Vec&lt;i64&gt; = permutations .into_iter() .map(|phase_setting| { five_amplifiers_in_a_feedback_loop(input_day7(), phase_setting).unwrap() }) .collect(); res.sort(); assert_eq!(*res.last().unwrap(), 70602018) } fn input_day9() -&gt; &amp;'static str { &quot;1102,34463338,34463338,63,1007,63,34463338,63,1005,63,53,1102,3,1,1000,109,988,209,12,9,1000,209,6,209,3,203,0,1008,1000,1,63,1005,63,65,1008,1000,2,63,1005,63,904,1008,1000,0,63,1005,63,58,4,25,104,0,99,4,0,104,0,99,4,17,104,0,99,0,0,1102,1,30,1010,1102,1,38,1008,1102,1,0,1020,1102,22,1,1007,1102,26,1,1015,1102,31,1,1013,1102,1,27,1014,1101,0,23,1012,1101,0,37,1006,1102,735,1,1028,1102,1,24,1009,1102,1,28,1019,1102,20,1,1017,1101,34,0,1001,1101,259,0,1026,1101,0,33,1018,1102,1,901,1024,1101,21,0,1016,1101,36,0,1011,1102,730,1,1029,1101,1,0,1021,1102,1,509,1022,1102,39,1,1005,1101,35,0,1000,1102,1,506,1023,1101,0,892,1025,1101,256,0,1027,1101,25,0,1002,1102,1,29,1004,1102,32,1,1003,109,9,1202,-3,1,63,1008,63,39,63,1005,63,205,1001,64,1,64,1106,0,207,4,187,1002,64,2,64,109,-2,1208,-4,35,63,1005,63,227,1001,64,1,64,1105,1,229,4,213,1002,64,2,64,109,5,1206,8,243,4,235,1106,0,247,1001,64,1,64,1002,64,2,64,109,14,2106,0,1,1105,1,265,4,253,1001,64,1,64,1002,64,2,64,109,-25,1201,4,0,63,1008,63,40,63,1005,63,285,1106,0,291,4,271,1001,64,1,64,1002,64,2,64,109,14,2107,37,-7,63,1005,63,313,4,297,1001,64,1,64,1106,0,313,1002,64,2,64,109,-7,21101,40,0,5,1008,1013,37,63,1005,63,333,1105,1,339,4,319,1001,64,1,64,1002,64,2,64,109,-7,1207,0,33,63,1005,63,355,1106,0,361,4,345,1001,64,1,64,1002,64,2,64,109,7,21102,41,1,9,1008,1017,41,63,1005,63,387,4,367,1001,64,1,64,1106,0,387,1002,64,2,64,109,-1,21102,42,1,10,1008,1017,43,63,1005,63,411,1001,64,1,64,1106,0,413,4,393,1002,64,2,64,109,-5,21101,43,0,8,1008,1010,43,63,1005,63,435,4,419,1106,0,439,1001,64,1,64,1002,64,2,64,109,16,1206,3,455,1001,64,1,64,1106,0,457,4,445,1002,64,2,64,109,-8,21107,44,45,7,1005,1017,479,4,463,1001,64,1,64,1106,0,479,1002,64,2,64,109,6,1205,5,497,4,485,1001,64,1,64,1106,0,497,1002,64,2,64,109,1,2105,1,6,1105,1,515,4,503,1001,64,1,64,1002,64,2,64,109,-10,2108,36,-1,63,1005,63,535,1001,64,1,64,1105,1,537,4,521,1002,64,2,64,109,-12,2101,0,6,63,1008,63,32,63,1005,63,561,1001,64,1,64,1105,1,563,4,543,1002,64,2,64,109,25,21108,45,46,-2,1005,1018,583,1001,64,1,64,1105,1,585,4,569,1002,64,2,64,109,-23,2108,34,4,63,1005,63,607,4,591,1001,64,1,64,1106,0,607,1002,64,2,64,109,3,1202,7,1,63,1008,63,22,63,1005,63,633,4,613,1001,64,1,64,1106,0,633,1002,64,2,64,109,12,21108,46,46,3,1005,1015,651,4,639,1106,0,655,1001,64,1,64,1002,64,2,64,109,-5,2102,1,-1,63,1008,63,35,63,1005,63,679,1001,64,1,64,1105,1,681,4,661,1002,64,2,64,109,13,21107,47,46,-7,1005,1013,701,1001,64,1,64,1105,1,703,4,687,1002,64,2,64,109,-2,1205,2,715,1106,0,721,4,709,1001,64,1,64,1002,64,2,64,109,17,2106,0,-7,4,727,1105,1,739,1001,64,1,64,1002,64,2,64,109,-23,2107,38,-6,63,1005,63,759,1001,64,1,64,1106,0,761,4,745,1002,64,2,64,109,-3,1207,-4,40,63,1005,63,779,4,767,1105,1,783,1001,64,1,64,1002,64,2,64,109,-8,2101,0,-1,63,1008,63,35,63,1005,63,809,4,789,1001,64,1,64,1105,1,809,1002,64,2,64,109,-6,2102,1,8,63,1008,63,32,63,1005,63,835,4,815,1001,64,1,64,1106,0,835,1002,64,2,64,109,6,1201,5,0,63,1008,63,37,63,1005,63,857,4,841,1106,0,861,1001,64,1,64,1002,64,2,64,109,2,1208,0,32,63,1005,63,883,4,867,1001,64,1,64,1106,0,883,1002,64,2,64,109,23,2105,1,-2,4,889,1001,64,1,64,1106,0,901,4,64,99,21102,27,1,1,21101,0,915,0,1106,0,922,21201,1,55337,1,204,1,99,109,3,1207,-2,3,63,1005,63,964,21201,-2,-1,1,21101,0,942,0,1105,1,922,21202,1,1,-1,21201,-2,-3,1,21102,957,1,0,1105,1,922,22201,1,-1,-2,1106,0,968,21201,-2,0,-2,109,-3,2105,1,0&quot; } #[test] fn relative_base() { assert_output( &quot;109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99&quot;, None, vec![ 109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99, ], ) } #[test] fn large_numbers() { assert_output(&quot;104,1125899906842624,99&quot;, None, vec![1125899906842624]); assert_output( &quot;1102,34915192,34915192,7,4,7,99,0&quot;, None, vec![1219070632396864], ) } #[test] fn day9_part_one() { assert_output(input_day9(), Some(1), vec![3765554916]) } fn assert_output(intcode: &amp;str, input: Option&lt;i64&gt;, expected_output: Vec&lt;i64&gt;) { assert_eq!( computer(intcode, input.map_or(vec![], |v| vec![v])).unwrap(), expected_output ) } #[test] fn day9_part_two() { assert_output(input_day9(), Some(2), vec![76642]) } } </code></pre> <p>I'd appreciate any input on how to improve the code and make it more Rusty.</p> <p>I also have a few specific questions:</p> <ul> <li>Is it a common practice to validate function input in Rust, like I did in <code>five_amplifiers_in_a_feedback_loop</code> for example?</li> <li>The <code>pop_and_send</code> function does two things instead of one: it not only empties a vector, but it sends the last value to a channel. What would be a better way to break this down?</li> <li>In <code>five_amplifiers_in_sequence</code> I'm &quot;chaining&quot; five computers in sequence and pass on the output from one computer to the next one. Is there a way to further abstract this, maybe my choice for <code>State</code> can be improved?</li> <li>In <code>five_amplifiers_in_a_feedback_loop</code> I attempted multithreading in Rust. Is this the way to do it?</li> </ul> <p>Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T22:10:49.890", "Id": "496230", "Score": "0", "body": "Have you ever heard of the type state pattern?" } ]
[ { "body": "<p>That is quite a lot of code, and fun to review.</p>\n<p>Let's start with the big picture.</p>\n<h1>Code organization</h1>\n<p>The general organization of the code can be improved. In its current\nform, the code is scattered in a bunch of functions, some of which are\nhard to understand without context. The order of functions is also a\nbit puzzling.</p>\n<p>I would envision an interface along the lines of: (naming and other\ndetails here are quite arbitrary)</p>\n<ul>\n<li><p><code>pub mod Intcode</code></p>\n<ul>\n<li><p><code>pub struct Program</code></p>\n<ul>\n<li><code>pub fn parse_from</code> — corresponding to <code>str_to_intcode</code></li>\n</ul>\n</li>\n<li><p><code>pub struct Computer { instruction_pointer: usize, ... }</code></p>\n<ul>\n<li><p><code>pub fn new</code> — constructs a computer (with settings, if\nany)</p>\n</li>\n<li><p><code>pub fn compute</code> — takes a program, executes it, and\nreturns the result</p>\n</li>\n<li><p>private helper functions</p>\n</li>\n</ul>\n</li>\n<li><p><code>pub fn execute</code> — combines all steps in one for convenience</p>\n</li>\n</ul>\n</li>\n</ul>\n<p>and other necessary items. Now, instead of passing <code>State</code>s\neverywhere, the functions become methods and associated functions of\nthe <code>Computer</code> struct.</p>\n<p>I would probably start the development with something like this, and\ngradually refine it as I complete the code.</p>\n<h1>Error handling</h1>\n<p>Instead of <code>&amp;str</code> and <code>String</code>, it is preferable to raise proper error\nclasses and embed the error message in its <code>Display</code> implementation.\nSee <a href=\"https://softwareengineering.stackexchange.com/q/278949\">Why do many exception messages not contain useful details?</a></p>\n<p>I recommend using the <a href=\"https://docs.rs/anyhow/1.0.38/anyhow/\" rel=\"nofollow noreferrer\"><code>anyhow</code></a> crate to handle errors. It\nremoves a lot of boilerplate and simplifies the propagation of errors.</p>\n<h1>Naming</h1>\n<p>The naming throughout your code also leaves room for improvement; I'll\ntouch on this later.</p>\n<h1>Types</h1>\n<p>Personally, I would type aliases to clarify the meaning of types like\n<code>i64</code>, <code>u8</code>, etc.:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>type Word = i64;\ntype ParameterMode = u8;\n</code></pre>\n<p>For memory indexes, <code>usize</code> seems to be a better fit than <code>u32</code>, as\nyou are spamming <code>as usize</code> everywhere.</p>\n<h1>Details</h1>\n<p>Now let's go through the code and pay attention to the details.</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>use crate::ComputeResult::{CanContinue, Halt, WaitingForInput};\n</code></pre>\n<p>Glob-imports (or variations thereof), especially global ones, are\ngenerally considered bad form (with some exceptions).</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>use std::sync::mpsc;\nuse std::sync::mpsc::{Receiver, Sender};\nuse std::thread;\n</code></pre>\n<p>These <code>use</code> declarations can be condensed:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::{\n sync::mpsc::{self, Receiver, Sender},\n thread,\n};\n</code></pre>\n<p>The <a href=\"https://doc.rust-lang.org/stable/reference/paths.html?highlight=path#self\" rel=\"nofollow noreferrer\"><code>self</code></a> keyword resolves to the current module in a path\n— in this case, <code>std::sync::mpsc</code>.</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>fn main() {\n let input = /* ... */;\n\n println!(&quot;Hello, world, {:?}&quot;, str_to_intcode(input));\n}\n</code></pre>\n<p>The <code>main</code> function is supposed to be the entry point to a binary. In\nyour code, it looks like the remnant of debugging. Simply remove it\nif your code is intended as a library.</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>fn str_to_intcode(string: &amp;str) -&gt; Vec&lt;i64&gt; {\n string\n .split_terminator(&quot;,&quot;)\n .map(|s| s.parse().unwrap())\n .collect()\n}\n</code></pre>\n<p>Seeing as you used <code>split_terminator</code> instead of the regular <code>split</code>\nhere, are you sure that the last number, which isn't followed by a\ncomma, does not count as part of the program? If so, it might make\nsense to explicitly indicate this in the code.</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>struct State {\n instruction_pointer: u32,\n intcode: Vec&lt;i64&gt;,\n input: Vec&lt;i64&gt;,\n output: Vec&lt;i64&gt;,\n relative_base: i64,\n}\n</code></pre>\n<p>As I mentioned before, it makes sense to expand this into a\nfull-fledged <code>Computer</code> struct.</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>enum ComputeResult {\n Halt,\n CanContinue,\n WaitingForInput,\n}\n</code></pre>\n<p><code>Status</code> might be a better name. Also, perhaps <code>Halt / Success / Blocked</code>?</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>//todo turn into an enumeration instead of using u8 for the parameter modes?\n</code></pre>\n<p>I agree.</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>fn extend_memory(memory_index: u32, state: &amp;mut State) {\n if memory_index &gt;= state.intcode.len() as u32 {\n state.intcode.resize((memory_index + 1) as usize, 0);\n }\n}\n</code></pre>\n<p>Following the precedent set by the standard library, <code>reserve</code> may be\nmore descriptive than <code>extend</code>.</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>fn five_amplifiers_in_sequence(intcode: &amp;str, phase_setting: Vec&lt;i64&gt;) -&gt; i64 {\n computer(intcode, vec![0, phase_setting[0]])\n //todo refactor pop for something immutable?\n .and_then(|mut o| {\n computer(intcode, vec![o.pop().unwrap(), phase_setting[1]])\n })\n .and_then(|mut o| {\n computer(intcode, vec![o.pop().unwrap(), phase_setting[2]])\n })\n .and_then(|mut o| {\n computer(intcode, vec![o.pop().unwrap(), phase_setting[3]])\n })\n .and_then(|mut o| {\n computer(intcode, vec![o.pop().unwrap(), phase_setting[4]])\n })\n .ok()\n .unwrap()\n .pop()\n .unwrap()\n}\n</code></pre>\n<p>Phew ... are you sure you don't want a loop here?</p>\n<p>I assume there is a logic to the number <code>5</code> here. Consider using a\n<code>const</code> to signify.</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>fn computer(intcode: &amp;str, input: Vec&lt;i64&gt;) -&gt; Result&lt;Vec&lt;i64&gt;, &amp;str&gt; {\n let mut state = state_from_string(intcode);\n state.input = input;\n\n loop {\n match compute(&amp;mut state) {\n Ok(r) =&gt; match r {\n Halt | WaitingForInput =&gt; break Ok(state.output),\n CanContinue =&gt; continue,\n },\n //todo refactor the nested match and simplify the error mapping\n Err(_) =&gt; break Err(&quot;bam&quot;),\n }\n }\n}\n</code></pre>\n<p>The error handling seems sub-optimal. Also, the <a href=\"https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator\" rel=\"nofollow noreferrer\"><code>?</code> operator</a> is\nhandy.</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>fn pop_and_send(state: &amp;mut State, rx: &amp;Sender&lt;i64&gt;) -&gt; i64 {\n let mut last = 0;\n loop {\n //todo for future use-cases, this might not be desired behaviour, replace with drain\n match state.output.pop() {\n None =&gt; break last,\n Some(v) =&gt; {\n last = v;\n rx.send(v)\n }\n };\n }\n}\n</code></pre>\n<p>Basically <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.inspect\" rel=\"nofollow noreferrer\"><code>inspect</code></a> + <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.last\" rel=\"nofollow noreferrer\"><code>last</code></a>.</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>fn five_amplifiers_in_a_feedback_loop(\n intcode: &amp;'static str,\n phase_setting: Vec&lt;i32&gt;,\n) -&gt; Option&lt;i64&gt; {\n assert_eq!(\n phase_setting.len(),\n 5,\n &quot;phase sequence of length five expected, while {} provided&quot;,\n phase_setting.len()\n );\n\n let (tx_a, rx_a): (Sender&lt;i64&gt;, Receiver&lt;i64&gt;) = mpsc::channel();\n let (tx_b, rx_b): (Sender&lt;i64&gt;, Receiver&lt;i64&gt;) = mpsc::channel();\n let (tx_c, rx_c): (Sender&lt;i64&gt;, Receiver&lt;i64&gt;) = mpsc::channel();\n let (tx_d, rx_d): (Sender&lt;i64&gt;, Receiver&lt;i64&gt;) = mpsc::channel();\n let (tx_e, rx_e): (Sender&lt;i64&gt;, Receiver&lt;i64&gt;) = mpsc::channel();\n\n let lambda = move |name: &amp;str, tx: Sender&lt;i64&gt;, rx: Receiver&lt;i64&gt;| -&gt; i64 {\n let mut state = state_from_string(intcode);\n\n loop {\n match compute(&amp;mut state) {\n Ok(r) =&gt; match r {\n Halt =&gt; {\n break pop_and_send(&amp;mut state, &amp;tx);\n }\n\n WaitingForInput =&gt; {\n pop_and_send(&amp;mut state, &amp;tx);\n\n match rx.recv() {\n Ok(v) =&gt; {\n state.input.push(v);\n continue;\n }\n Err(e) =&gt; panic!(&quot;{} error: {}&quot;, name, e),\n }\n }\n\n CanContinue =&gt; continue,\n },\n //todo refactor the nested match and simplify the error mapping\n Err(_) =&gt; panic!(&quot;{} &quot;,),\n }\n }\n };\n\n tx_a.send(phase_setting[0] as i64)\n .and_then(|_| tx_a.send(0))\n .and_then(|_| tx_b.send(phase_setting[1] as i64))\n .and_then(|_| tx_c.send(phase_setting[2] as i64))\n .and_then(|_| tx_d.send(phase_setting[3] as i64))\n .and_then(|_| tx_e.send(phase_setting[4] as i64))\n .unwrap();\n\n let _a = thread::spawn(move || lambda(&quot;A&quot;, tx_b, rx_a));\n let _b = thread::spawn(move || lambda(&quot;B&quot;, tx_c, rx_b));\n let _c = thread::spawn(move || lambda(&quot;C&quot;, tx_d, rx_c));\n let _d = thread::spawn(move || lambda(&quot;D&quot;, tx_e, rx_d));\n let e = thread::spawn(move || lambda(&quot;E&quot;, tx_a, rx_e));\n\n e.join().ok()\n}\n</code></pre>\n<p>Again, consider using loops. Most of the <code>match</code>es can also be\neliminated using the <a href=\"https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator\" rel=\"nofollow noreferrer\"><code>?</code> operator</a> or <a href=\"https://doc.rust-lang.org/std/result/enum.Result.html#method.expect\" rel=\"nofollow noreferrer\"><code>expect</code></a>.</p>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>fn compute(state: &amp;mut State) -&gt; Result&lt;ComputeResult, String&gt; {\n let offset = state.instruction_pointer;\n\n //todo is this defensive programming a good idea?\n assert!(\n offset &lt; state.intcode.len() as u32,\n &quot;offset {} out of bounds, intcode length {}&quot;,\n offset,\n state.intcode.len()\n );\n assert!(state.intcode.len() &gt; 0, &quot;no intcode to process&quot;);\n\n let (a, b, c, opcode) = parameter_modes(state.intcode[offset as usize]);\n\n // ...\n}\n</code></pre>\n<p>Is it a good idea? If you consider this to be the logical place to\nvalidate the internal state, then go ahead. With proper\nencapsulation, however, the check can be safety elided (or changed to\n<code>debug_assert!</code>) if the code is refactored to make class invariants.</p>\n<p>Also, <code>opcode</code> does not look like a parameter mode.</p>\n<p>This entire <code>compute</code> function is too long; break it down into smaller\nfunctions. Also, addition and multiplication can be merged by passing\nan argument that determines the operation to use; the same applies to\nsome other operations.</p>\n<hr />\n<p>I didn't go into the details to save space, so feel free to ping me if\nyou find any part of this unclear.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T13:07:52.300", "Id": "504952", "Score": "0", "body": "Thank you very, very much! I appreciate the time and attention you've put into reviewing my code. I'll make an attempt to improve it based on your remarks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T13:13:31.480", "Id": "504953", "Score": "0", "body": "@NikolaKasev That's great to hear :) If you find my answer helpful, you can accept it to remove the question from the unanswered pool." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T12:06:05.753", "Id": "255754", "ParentId": "251896", "Score": "2" } } ]
{ "AcceptedAnswerId": "255754", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T11:00:05.417", "Id": "251896", "Score": "10", "Tags": [ "rust" ], "Title": "Intcode computer in Rust" }
251896
<h1>Here's Some Context</h1> <p>So I was messing around in <em>Minecraft</em> and decided to make some code that basically makes you god. While making the code and testing it I noticed there were some problems that I didn't know how to fix, and came here to see if there were at least a semi-professional coder that could review my code for mistakes or problems.</p> <h1>What It's Supposed To Do.</h1> <p>This code is made to do the following:</p> <ol> <li>Give the player the best equipment, resources, and potion effects possible in <em>MCPE</em> (Or <em>Minecraft Bedrock Edition</em>).</li> <li>Give the best possible enchantments to the player on the requested piece of equipment.</li> <li>Re-give the player their potion effects.</li> </ol> <h1>What It Does</h1> <p>It tends to work <strong>most</strong> of the time, but, I've noticed that it only occasionally does the following things: 1. Only applies certain affects, 2. Only gives certain items while leaving some out, and 3. Sometimes doesn't apply the enchantments on the requested item.</p> <h1>How the code is run (How I Run it)</h1> <p>I have the <em>Minecraft</em> world where I test my code open. Here when I finish the code on the coding application I'm using I will press the big green &quot;Run Program&quot; button which in this case is just a preparatory command which makes sure that when I type the required message it will go through each line of code, and step by step, complete each of the given tasks. To better help those who may not understand I have taken some screenshots of the basic process.</p> <p><a href="https://i.stack.imgur.com/1ysvH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1ysvH.png" alt="Random code I made in the program." /></a></p> <p><a href="https://i.stack.imgur.com/EKu1j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EKu1j.png" alt="The program's run button." /></a></p> <p><a href="https://i.stack.imgur.com/zUywe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zUywe.png" alt="The program's executionary command that enables the random code to start running." /></a></p> <p><a href="https://i.stack.imgur.com/eU52O.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eU52O.png" alt="The result after the program is done running the random code." /></a></p> <h1>The Code in JavaScript</h1> <pre><code> mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;fire protection&quot;, 4 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;thorns&quot;, 3 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;unbreaking&quot;, 3 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;mending&quot;, 1 ) }) player.onChat(&quot;Enchant my helmet&quot;, function () { mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;projectile protection&quot;, 4 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;respiration&quot;, 5 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;aqua affinity&quot;, 1 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;thorns&quot;, 3 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;unbreaking&quot;, 3 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;mending&quot;, 1 ) }) player.onChat(&quot;i want zombies&quot;, function () { for (let index = 0; index &lt; 10; index++) { mobs.spawn(mobs.monster(ZOMBIE), pos(0, 0, 0)) } }) player.onChat(&quot;i wanna be god&quot;, function () { mobs.applyEffect(REGENERATION, mobs.target(LOCAL_PLAYER), 600, 255) mobs.applyEffect(STRENGTH, mobs.target(LOCAL_PLAYER), 600, 4) mobs.applyEffect(HEALTH_BOOST, mobs.target(LOCAL_PLAYER), 600, 74) mobs.applyEffect(JUMP_BOOST, mobs.target(LOCAL_PLAYER), 600, 4) mobs.applyEffect(SPEED, mobs.target(LOCAL_PLAYER), 600, 4) mobs.applyEffect(ABSORPTION, mobs.target(LOCAL_PLAYER), 600, 4) mobs.applyEffect(HASTE, mobs.target(LOCAL_PLAYER), 600, 4) mobs.applyEffect(WATER_BREATHING, mobs.target(LOCAL_PLAYER), 600, 4) mobs.applyEffect(FIRE_RESISTANCE, mobs.target(LOCAL_PLAYER), 600, 4) mobs.applyEffect(RESISTANCE, mobs.target(LOCAL_PLAYER), 600, 4) mobs.applyEffect(NIGHT_VISION, mobs.target(LOCAL_PLAYER), 600, 4) gameplay.setGameRule(NATURAL_REGENERATION, true) mobs.give( mobs.target(LOCAL_PLAYER), DIAMOND_SWORD, 1 ) mobs.give( mobs.target(LOCAL_PLAYER), BOW, 1 ) mobs.give( mobs.target(LOCAL_PLAYER), DIAMOND_PICKAXE, 1 ) mobs.give( mobs.target(LOCAL_PLAYER), DIAMOND_AXE, 1 ) mobs.give( mobs.target(LOCAL_PLAYER), DIAMOND_SHOVEL, 1 ) mobs.give( mobs.target(LOCAL_PLAYER), TORCH, 128 ) mobs.give( mobs.target(LOCAL_PLAYER), COOKED_BEEF, 200 ) mobs.give( mobs.target(LOCAL_PLAYER), ENCHANTED_APPLE, 64 ) mobs.give( mobs.target(ALL_PLAYERS), DIAMOND_HELMET, 1 ) mobs.give( mobs.target(ALL_PLAYERS), ELYTRA, 1 ) mobs.give( mobs.target(ALL_PLAYERS), DIAMOND_LEGGINGS, 1 ) mobs.give( mobs.target(ALL_PLAYERS), DIAMOND_BOOTS, 1 ) mobs.give( mobs.target(ALL_PLAYERS), ARROW, 128 ) mobs.give( mobs.target(ALL_PLAYERS), ENCHANTED_APPLE, 64 ) mobs.give( mobs.target(ALL_PLAYERS), BOW, 1 ) }) player.onChat(&quot;Creepers&quot;, function () { for (let index = 0; index &lt; 10; index++) { mobs.spawn(mobs.monster(SPIDER), pos(0, 0, 0)) } }) player.onChat(&quot;Enchant my shovel&quot;, function () { mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;effeciency&quot;, 5 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;fortune&quot;, 3 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;unbreaking&quot;, 3 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;silk touch&quot;, 1 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;mending&quot;, 1 ) }) player.onChat(&quot;i want my effects back&quot;, function () { mobs.applyEffect(REGENERATION, mobs.target(LOCAL_PLAYER), 600, 255) mobs.applyEffect(STRENGTH, mobs.target(LOCAL_PLAYER), 600, 4) mobs.applyEffect(HEALTH_BOOST, mobs.target(LOCAL_PLAYER), 600, 74) mobs.applyEffect(JUMP_BOOST, mobs.target(LOCAL_PLAYER), 600, 4) mobs.applyEffect(SPEED, mobs.target(LOCAL_PLAYER), 600, 4) mobs.applyEffect(ABSORPTION, mobs.target(LOCAL_PLAYER), 600, 4) mobs.applyEffect(HASTE, mobs.target(LOCAL_PLAYER), 600, 4) mobs.applyEffect(WATER_BREATHING, mobs.target(LOCAL_PLAYER), 600, 4) mobs.applyEffect(FIRE_RESISTANCE, mobs.target(LOCAL_PLAYER), 600, 4) mobs.applyEffect(RESISTANCE, mobs.target(LOCAL_PLAYER), 600, 4) mobs.applyEffect(NIGHT_VISION, mobs.target(LOCAL_PLAYER), 600, 4) }) player.onChat(&quot;i want spiders&quot;, function () { for (let index = 0; index &lt; 10; index++) { mobs.spawn(mobs.monster(SPIDER), pos(0, 0, 0)) } }) player.onChat(&quot;Enchant my boots&quot;, function () { mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;protection&quot;, 4 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;feather falling&quot;, 4 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;depth strider&quot;, 3 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;frost walker&quot;, 2 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;thorns&quot;, 3 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;unbreaking&quot;, 3 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;mending&quot;, 1 ) }) player.onChat(&quot;Enchant my axe&quot;, function () { mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;smite&quot;, 5 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;effeciency&quot;, 5 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;fortune&quot;, 3 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;unbreaking&quot;, 3 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;mending&quot;, 1 ) }) player.onChat(&quot;Enchant my sword&quot;, function () { mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;fire aspect&quot;, 2 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;knockback&quot;, 3 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;looting&quot;, 3 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;sharpness&quot;, 5 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;unbreaking&quot;, 3 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;mending&quot;, 1 ) }) player.onChat(&quot;Enchant my pick&quot;, function () { mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;effeciency&quot;, 5 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;fortune&quot;, 3 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;unbreaking&quot;, 3 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;mending&quot;, 1 ) }) player.onChat(&quot;Enchant my chesplate&quot;, function () { mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;blast protection&quot;, 4 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;thorns&quot;, 3 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;unbreaking&quot;, 3 ) mobs.enchant( mobs.target(LOCAL_PLAYER), &quot;mending&quot;, 1 ) }) player.onChat(&quot;i want skeletons&quot;, function () { for (let index = 0; index &lt; 10; index++) { mobs.spawn(mobs.monster(SKELETON), pos(0, 0, 0)) } }) </code></pre> <h1>Friendly Reminder</h1> <p>If you wish to edit this question please don't change too much. Just do things like correct grammar and formatting.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-24T20:07:06.220", "Id": "497808", "Score": "1", "body": "Why do you think someone will edit out all the content?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-27T01:51:35.423", "Id": "498122", "Score": "0", "body": "@Penguin I don't think they will edit out all content I'm just politely asking that if they do edit out content that they do edit TOO much as to keep the message basically the same." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T13:45:14.733", "Id": "251899", "Score": "2", "Tags": [ "javascript", "beginner", "minecraft" ], "Title": "Minecraft Code That Gives Player God Like Abilities" }
251899
<p>I am in learning process, even though its a very easy project, I still want experts to please review it and share the improvement that can be done, if anyone wants to use other modules to shorten the code then you can also use them, I already thank you to the people who wants to spend their precious time for this. other beginners will also find it helpful.</p> <pre><code>import pyinputplus as pyp menu = True # price of all ingredients prices = {'wheat': 2, 'white': 1, 'sour dough': 3, 'chicken': 2, 'turkey': 3, 'ham': 2, 'tofu': 1, 'cheddar': 1, 'swiss': 2, 'mozzarella': 3, 'mayo': 1, 'mustard': 1, 'lettuce': 1, 'ketchup': 1} while menu: # options to select bread, protein, cheese with inputMenu() method bread = pyp.inputMenu(['wheat', 'white', 'sour dough'], prompt='Please select the type of bread you want for your sandwich: \n', numbered=True) protein = pyp.inputMenu(['chicken', 'Turkey', 'Ham', 'Tofu'], prompt='Which type of protein you would like: \n', numbered=True) cheese = pyp.inputYesNo('Do you want Cheese in your sandwich?(Y/N)\n') cheese_type = '' if cheese == 'yes': cheese_type = pyp.inputMenu(['cheddar', 'swiss', 'mozzarella'], numbered=True) # using inputYesNo() for single ingredients with no further types mayo = pyp.inputYesNo('Do you want mayo?(Y/N) \n') mustard = pyp.inputYesNo('Do you want mustard?(Y/N) \n') lettuce = pyp.inputYesNo('Do you want lettuce?(Y/N) \n') ketchup = pyp.inputYesNo('Do you want tomato ketchup?(Y/N) \n') # using inputInt() and blockRegexes that do not allow negative integer, float or 0 sandwichQT = pyp.inputInt('How much sandwiches you would like to order?\n', blockRegexes=['[0|-|.]']) total_amount = 0 # using for loop to print items, prices and adding their amount to total_amount variable for item, price in prices.items(): if bread == item: print(f'Your sandwich ingredients and prices are as follows: \n' f'{item}= {price}') total_amount += price if protein == item: print(f'{item}= {price}') total_amount += price if cheese_type == item: print(f'{item}= {price}') total_amount += price # for items that have yes and no values stored and also adding their amount to total if mayo == 'yes': print(f&quot;mayo = {prices['mayo']}&quot;) total_amount += prices['mayo'] if mustard == 'yes': print(f&quot;mustard = {prices['mustard']}&quot;) total_amount += prices['mustard'] if lettuce == 'yes': print(f&quot;lettuce = {prices['lettuce']}&quot;) total_amount += prices['lettuce'] if ketchup == 'yes': print(f&quot;ketchup = {prices['ketchup']}&quot;) total_amount += prices['ketchup'] # at the end printing total amount and how much sandwiches have been ordered print(f&quot;sandwich cost x sandwich Qt ordered = {total_amount}x{sandwichQT} = &quot; f&quot;{total_amount*sandwichQT}&quot;) # confirming if the user need to reorder or user wants to confirm the order by simple yes/no # if user confirm by typing yes or y then menu will become false and while loop will terminate order_confirm = pyp.inputYesNo('Please confirm your order: (Y/N)\n') if order_confirm == 'yes': print('Please take your order number from the machine and you will be notified when ' 'its ready') menu = False </code></pre>
[]
[ { "body": "<h3><code>while True</code></h3>\n<p>First of all, using &quot;flag&quot; variables is not customary in Python. Instead of using a boolean variable to control a <code>while</code> loop, you can just do <code>while True: ... break</code>.</p>\n<h3>Avoiding many <code>if</code>s</h3>\n<p>You might notice the repeating structure of:</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(f'{item}= {price}')\ntotal_amount += price\n</code></pre>\n<p>under every <code>if</code>. This is because your logic is reversed. You are currently iterating over <em><strong>ALL</strong></em> possible ingredients and checking if you need them. But there might be many that are not in use. It makes more sense to create a list of <em><strong>ingredients in use</strong></em> and then just take their price in a loop. This will require changing how you save your sauces. Instead of saving them as <code>'yes'</code>, we will save them with their name - to match with the <code>prices</code> dict keys.</p>\n<p>So we will create a list of <code>ingredients</code>, and add the sauces as well:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if pyp.inputYesNo('Do you want mayo?(Y/N) \\n') == 'yes':\n ingredients.append('mayo')\n</code></pre>\n<p>And now the printing loop will be <code>if</code>-free:</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(f'Your sandwich ingredients and prices are as follows: \\n')\nfor item in ingredients:\n price = prices[item]\n print(f'{item}= {price}')\n total_amount += price\n</code></pre>\n<h3>Full Code</h3>\n<pre class=\"lang-py prettyprint-override\"><code>import pyinputplus as pyp\n\n# price of all ingredients\nprices = {'wheat': 2, 'white': 1, 'sour dough': 3, 'chicken': 2, 'turkey': 3, 'ham': 2, 'tofu': 1,\n 'cheddar': 1, 'swiss': 2, 'mozzarella': 3, 'mayo': 1, 'mustard': 1, 'lettuce': 1,\n 'ketchup': 1}\n\nwhile True:\n ingredients = []\n # options to select bread, protein, cheese with inputMenu() method\n ingredients.append(pyp.inputMenu(['wheat', 'white', 'sour dough'],\n prompt='Please select the type of bread you want for your sandwich: \\n',\n numbered=True))\n\n ingredients.append(pyp.inputMenu(['chicken', 'Turkey', 'Ham', 'Tofu'],\n prompt='Which type of protein you would like: \\n',\n numbered=True))\n\n if pyp.inputYesNo('Do you want Cheese in your sandwich?(Y/N)\\n')== 'yes':\n ingredients.append(pyp.inputMenu(['cheddar', 'swiss', 'mozzarella'], numbered=True))\n\n # using inputYesNo() for single ingredients with no further types\n if pyp.inputYesNo('Do you want mayo?(Y/N) \\n') == 'yes':\n ingredients.append('mayo')\n if pyp.inputYesNo('Do you want mustard?(Y/N) \\n') == 'yes':\n ingredients.append('mustard')\n if pyp.inputYesNo('Do you want lettuce?(Y/N) \\n') == 'yes':\n ingredients.append('lettuce')\n if pyp.inputYesNo('Do you want tomato ketchup?(Y/N) \\n') == 'yes':\n ingredients.append('ketchup')\n\n # using inputInt() and blockRegexes that do not allow negative integer, float or 0\n sandwichQT = pyp.inputInt('How much sandwiches you would like to order?\\n',\n blockRegexes=['[0|-|.]'])\n\n total_amount = 0\n # using for loop to print items, prices and adding their amount to total_amount variable\n print(f'Your sandwich ingredients and prices are as follows: \\n')\n for item in ingredients:\n price = prices[item]\n print(f'{item}= {price}')\n total_amount += price\n\n # at the end printing total amount and how much sandwiches have been ordered\n print(f&quot;sandwich cost x sandwich Qt ordered = {total_amount}x{sandwichQT} = &quot;\n f&quot;{total_amount*sandwichQT}&quot;)\n\n # confirming if the user need to reorder or user wants to confirm the order by simple yes/no\n # if user confirm by typing yes or y then menu will become false and while loop will terminate\n if pyp.inputYesNo('Please confirm your order: (Y/N)\\n')== 'yes':\n print('Please take your order number from the machine and you will be notified when '\n 'its ready')\n break\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T16:23:23.427", "Id": "496107", "Score": "0", "body": "Yup! that was really helpful, your method reduced the coding. I remembered that how If statement slows the program execution, it will not matter in this program but when i was making few games in pygame, a lot of if statements were really giving me low FPS. thanks today i learned 2 new techniques. i never thought i can do this thing: ingredients.append(pyp.inputMenu() i never appended something like this, maybe in list comprehension but not like this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-12T19:56:17.987", "Id": "496384", "Score": "0", "body": "@MuhammadAhmad _I remembered that how If statement slows the program execution, it will not matter in this program but when i was making few games in pygame, a lot of if statements were really giving me low FPS._ It's likely a result of what you were computing for each statement, not the baseline performance of the if statements themselves. Are you sure the issue was with the if statements?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T12:05:24.350", "Id": "496769", "Score": "0", "body": "@AMC yeah it was alien invasion i think where I changed the if condition for arrow keys to elif, Before that the spaceship always take 1 sec delay in response to the key i press. But after that i started responding fast, i should not have said the higher FPS because its not related to the frames, it is just the execution of the program." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T01:31:42.580", "Id": "496953", "Score": "0", "body": "@MuhammadAhmad How many if statements were there?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T15:02:56.193", "Id": "251907", "ParentId": "251902", "Score": "5" } } ]
{ "AcceptedAnswerId": "251907", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T13:59:43.700", "Id": "251902", "Score": "5", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "Automate the Boring Stuff with Python 2nd Edition - Sandwich Maker Practice Project" }
251902
<p>I have a random forest model I built to predict if NFL teams will score more combined points than the line Vegas has set. The features I use are <code>Total</code> - the total number of combined points Vegas thinks both teams will score, <code>over_percentage</code> - the percentage of public bets on the over, and <code>under_percentage</code> - the percentage of public bets on the under. The over means people are betting that both team's combined scores will be greater than the number Vegas sets and under means the combined score will go under the Vegas number. When I run my model I'm getting a confusion_matrix like this</p> <p><a href="https://i.stack.imgur.com/VfFRO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VfFRO.png" alt="enter image description here" /></a></p> <p>and an accuracy_score of 76%. However, the predictions do not perform well. Right now I have it giving me the probability the classification will be 0. I'm wondering if there are parameters I can tune or solutions to prevent my model from overfitting. I have over 30K games in the training data set so I don't think lack of data is causing the issue.</p> <p>Here is the code:</p> <pre><code>import pandas as pd import numpy as np import json from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, confusion_matrix, accuracy_score from sklearn.preprocessing import StandardScaler training_data = pd.read_csv( '/Users/aus10/NFL/Data/Betting_Data/Training_Data_Betting.csv') test_data = pd.read_csv( '/Users/aus10/NFL/Data/Betting_Data/Test_Data_Betting.csv') df_model = training_data.copy() df_model = df_model.dropna() X = df_model.loc[:, [&quot;Total&quot;, &quot;Over_Percentage&quot;, &quot;Under_Percentage&quot;]] # independent columns y = df_model[&quot;Over_Under&quot;] # target column results = [] model = RandomForestClassifier(n_estimators=1000, random_state=100) model.fit(X, y) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, random_state=100) y_train_pred = model.predict(X_train) y_test_pred = model.predict(X_test) model.fit(X_train, y_train) y_pred = model.predict(X_test) print(confusion_matrix(y_test, y_pred)) print(classification_report(y_test, y_pred)) print(round(accuracy_score(y_test, y_pred), 2)) index = 0 count = 0 while count &lt; len(test_data): team = test_data.loc[index].at['Team'] total = test_data.loc[index].at['Total'] over_perc = test_data.loc[index].at['Over_Percentage'] under_perc = test_data.loc[index].at['Under_Percentage'] Xnew = [[total, over_perc, under_perc]] # make a prediction ynew = model.predict_proba(Xnew) # show the inputs and predicted outputs results.append( { 'Team': team, 'Over': ynew[0][0] }) index += 1 count += 1 sorted_results = sorted(results, key=lambda k: k['Over'], reverse=True) df = pd.DataFrame(sorted_results, columns=[ 'Team', 'Over']) writer = pd.ExcelWriter('/Users/aus10/NFL/Data/ML_Results/Over_Probability.xlsx', # pylint: disable=abstract-class-instantiated engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1', index=False) df.style.set_properties(**{'text-align': 'center'}) pd.set_option('display.max_colwidth', 100) pd.set_option('display.width', 1000) writer.save() </code></pre> <p>And here are links the the google docs with the test and training data.</p> <p>Test Data</p> <p><a href="https://docs.google.com/spreadsheets/d/1IWZ6UPDd8ZZXsON_3kQCVynb2XDu4l1zza2lDL5vBbA/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1IWZ6UPDd8ZZXsON_3kQCVynb2XDu4l1zza2lDL5vBbA/edit?usp=sharing</a></p> <p>Training Data</p> <p><a href="https://docs.google.com/spreadsheets/d/1Z36dIrin7Xtup6qbAKfQycWD4cChX4g7nneaAzL1UdQ/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1Z36dIrin7Xtup6qbAKfQycWD4cChX4g7nneaAzL1UdQ/edit?usp=sharing</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T14:56:18.433", "Id": "496085", "Score": "2", "body": "Interesting problem. If you are seeking help debugging the code then this is the wrong site and you should delete the question here and ask it on stack overflow. We don't debug code here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T14:57:25.317", "Id": "496086", "Score": "0", "body": "It's not a bug just a way to improve the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T15:21:04.950", "Id": "496090", "Score": "2", "body": "Most feedback here - https://codereview.meta.stackexchange.com/questions/8781/when-are-machine-learning-questions-on-topic - would suggest that issues of ML accuracy are likely off-topic for CR." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T14:38:39.330", "Id": "251904", "Score": "1", "Tags": [ "python", "machine-learning" ], "Title": "How to handle overfitting in Random Forest" }
251904
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251865/231235">A filled_multi_array Template Function for Boost.MultiArray in C++</a>. Based on <a href="https://codereview.stackexchange.com/a/251880/231235">G. Sliepen's answer</a>, there is another <code>get_extents</code> template function mentioned for handling retrieving <code>boost::detail::multi_array::extent_gen&lt;NumDims&gt;</code> type size information from a <code>multi_array</code>. I am trying to implement this <code>get_extents</code> template function here.</p> <pre><code>template&lt;class T, std::size_t NumDims&gt; auto get_extents(const boost::multi_array&lt;T, NumDims&gt;&amp; input) { boost::detail::multi_array::extent_gen&lt;NumDims&gt; output; std::vector&lt;size_t&gt; shape_list; for (size_t i = 0; i &lt; NumDims; i++) { shape_list.push_back(input.shape()[i]); } std::copy(shape_list.begin(), shape_list.end(), output.ranges_.begin()); return output; } </code></pre> <p>I am trying to copy shape content into the <code>output</code> object. In general cases, <code>boost::detail::multi_array::extent_gen</code> object is always constructed by <code>boost::extents[][][]...</code>. However, I am not sure how to use <code>boost::extents</code> in this context and I fill the values of shape information into <code>output.ranges_</code> instead. It works with the following testing code.</p> <pre><code>auto filled_multi_array1 = filled_multi_array(boost::extents[3][4][2], 1.0); auto filled_multi_array2 = filled_multi_array(get_extents(filled_multi_array1), 2.0); // Checking shape std::cout &lt;&lt; &quot;filled_multi_array2.shape()[0]:&quot; &lt;&lt; filled_multi_array2.shape()[0] &lt;&lt; std::endl; std::cout &lt;&lt; &quot;filled_multi_array2.shape()[1]:&quot; &lt;&lt; filled_multi_array2.shape()[1] &lt;&lt; std::endl; std::cout &lt;&lt; &quot;filled_multi_array2.shape()[2]:&quot; &lt;&lt; filled_multi_array2.shape()[2] &lt;&lt; std::endl; for (decltype(filled_multi_array2)::index i = 0; i != filled_multi_array2.shape()[0]; ++i) for (decltype(filled_multi_array2)::index j = 0; j != filled_multi_array2.shape()[1]; ++j) for (decltype(filled_multi_array2)::index k = 0; k != filled_multi_array2.shape()[2]; ++k) std::cout &lt;&lt; filled_multi_array2[i][j][k] &lt;&lt; std::endl; </code></pre> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/251865/231235">A filled_multi_array Template Function for Boost.MultiArray in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>The <code>extent_gen</code> function implementation is the main part in this question.</p> </li> <li><p>Why a new review is being asked for?</p> <p>The <code>shape_list</code> which type is <code>std::vector&lt;size_t&gt;</code> in <code>get_extents</code> function is used just for copying shape data into <code>output.ranges_</code>. The reason why I create a <code>std::vector</code> for this operation is that there is neither <code>.begin()</code> function nor <code>.end()</code> function in <code>input.shape()</code>. Something like <code>std::copy(input.shape().begin(), input.shape().end(), output.ranges_.begin());</code> doesn't work. If there is any possible improvement, please let me know.</p> </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T21:33:06.000", "Id": "496138", "Score": "0", "body": "May I ask, What are you developing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T23:32:08.720", "Id": "496144", "Score": "0", "body": "Some programs for multidimensional data processing experiment." } ]
[ { "body": "<h1>Avoid unnecessary temporary variables</h1>\n<p>There still is no need for the temporary vector <code>shape_list</code>, just use <a href=\"https://en.cppreference.com/w/cpp/algorithm/copy_n\" rel=\"nofollow noreferrer\"><code>std::copy_n</code></a>:</p>\n<pre><code>boost::detail::multi_array::extent_gen&lt;NumDims&gt; output;\nstd::copy_n(input.shape(), NumDims, output.ranges_.begin());\n</code></pre>\n<p>Please take some time to look at the list of all the <a href=\"https://en.cppreference.com/w/cpp/algorithm\" rel=\"nofollow noreferrer\">STL algorithms</a>. There are lots of useful functions there that will save you a lot of time. You don't have to remember them all, but get a feel for the type of functionality it provides, and next time you have a problem you might remember that some existing algorithm might solve it for you. The <a href=\"https://www.fluentcpp.com/getthemap/\" rel=\"nofollow noreferrer\">World Map of C++ STL Algorithms</a> is also a great resource to build intuition for it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T20:39:25.927", "Id": "251924", "ParentId": "251909", "Score": "0" } } ]
{ "AcceptedAnswerId": "251924", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T15:41:36.620", "Id": "251909", "Score": "1", "Tags": [ "c++", "boost" ], "Title": "A get_extents helper function for Boost.MultiArray in C++" }
251909
<p>I'm fairly new to c++ programming. It would be helpful if I could get a feedback on a dice game I wrote. I would really appreciate some tips as well as your opinions.</p> <p>This program will begin by asking the user to enter an amount to bet (from $1- $1000). Next, the user is asked to guess the total that will occur when two dice are rolled. The program then “rolls two dice” (using random numbers) and visually displays the result. Then, if the player’s guess was correct, the player wins 8 times their bet divided by the number of possible way to get that roll. If the player’s guess was wrong, they lose their bet times the number of possible ways to get their guess.</p> <p><code> </code></p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; #include &lt;time.h&gt; using namespace std; //main program int main() { int guess;//user guess for the value of the dice float bet;//the bet placed by the user float possibility;//number of combinations each number can come int dice1, dice2;//the random value between 1-6 for each dice int total;//the total number after the value of dice1 and dice2 is added float earned_or_lost_money;//earned or lost money depending on whether you win/lose srand(time(0));//random number seed cout &lt;&lt; endl;//blank line cout &lt;&lt; &quot; What do you guess the result will be?(2-12): &quot;; cin &gt;&gt; guess;//user input for guess cout &lt;&lt; &quot; Enter amount of money to bet ($1-$1000): &quot;; cin &gt;&gt; bet;//user input for bet cout &lt;&lt; endl;//blank line dice1 = rand() % 6 + 1;//value of first dice(1-6) dice2 = rand() % 6 + 1;//value of second dice(1-6) total = dice1 + dice2;//value of dice1+dice2 switch (guess)// values for possible combinations for the total value of the dices added { case 2: possibility = 1; break; case 3: possibility = 2; break; case 4: possibility = 3; break; case 5: possibility = 4; break; case 6: possibility = 5; break; case 7: possibility = 6; break; case 8: possibility = 5; break; case 9: possibility = 4; break; case 10: possibility = 3; break; case 11: possibility = 2; break; case 12: possibility = 1; break; }//switch cout &lt;&lt; &quot; For your $&quot; &lt;&lt; bet &lt;&lt; &quot; bet, the roll is&quot; &lt;&lt; endl; cout &lt;&lt; endl;//blank line if (dice1 == 1)//drawing if the value of dice1 is 1 { cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 1 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; }//if else if (dice1 == 2)//drawing if the value of dice1 is 2 { cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 2 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 2 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; }//else if else if (dice1 == 3)//drawing if the value of dice1 is 3 { cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 3 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 3 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 3 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; }//else if else if (dice1 == 4)//drawing if the value of dice1 is 4 { cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 4 4 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 4 4 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; }//else if else if (dice1 == 5)//drawing if the value of dice1 is 5 { cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 5 5 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 5 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 5 5 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; }//else if else if (dice1 == 6)//drawing if the value of dice1 is 6 { cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 6 6 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 6 6 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 6 6 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; }//else if cout &lt;&lt; endl;//blank line if (dice2 == 1)//drawing if the value of dice2 is 1 { cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 1 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; }//if else if (dice2 == 2)//drawing if the value of dice2 is 2 { cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 2 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 2 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; }//else if else if (dice2 == 3)//drawing if the value of dice2 is 3 { cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 3 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 3 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 3 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; }//else if else if (dice2 == 4)//drawing if the value of dice2 is 4 { cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 4 4 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 4 4 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; }//else if else if (dice2 == 5)//drawing if the value of dice2 is 5 { cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 5 5 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 5 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 5 5 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; }//else if else if (dice2 == 6)//drawing if the value of dice2 is 6 { cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 6 6 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 6 6 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;| 6 6 |&quot; &lt;&lt; endl; cout &lt;&lt; &quot;=============&quot; &lt;&lt; endl; }//else if cout &lt;&lt; endl;//blank line cout &lt;&lt; &quot; For a total of &quot; &lt;&lt; total &lt;&lt; endl; cout &lt;&lt; endl;//blank line if (guess == total)//if the user guessed correctly { earned_or_lost_money = bet * 8 / possibility;//calculation for money earned cout &lt;&lt; &quot; You were correct... since &quot; &lt;&lt; guess &lt;&lt; &quot; can come up &quot; &lt;&lt; possibility &lt;&lt; &quot; ways,&quot; &lt;&lt; endl; cout &lt;&lt; &quot;You win $&quot; &lt;&lt; bet &lt;&lt; &quot;*8/&quot; &lt;&lt; possibility &lt;&lt; &quot;= $&quot; &lt;&lt; earned_or_lost_money &lt;&lt; endl; }//if else//if the user guessed wrong { earned_or_lost_money = possibility * bet;//calculation for lost money cout &lt;&lt; &quot; You were wrong... since &quot; &lt;&lt; guess &lt;&lt; &quot; can come up &quot; &lt;&lt; possibility &lt;&lt; &quot; ways,&quot; &lt;&lt; endl; cout &lt;&lt; &quot; You lost &quot; &lt;&lt; possibility &lt;&lt; &quot;*$&quot; &lt;&lt; bet &lt;&lt; &quot;= $&quot; &lt;&lt; earned_or_lost_money &lt;&lt; &quot; dollars!!!!!!&quot; &lt;&lt; endl; cout &lt;&lt; &quot; Thanks for your donation :)&quot; &lt;&lt; endl; }//else return 0; }//end </code></pre>
[]
[ { "body": "<p>Depending of what you want, there is some things you can do:</p>\n<ul>\n<li>refactor dice drawing function as there is a lot of redounding code</li>\n<li>a check for all inputs (nothing prevent your user to input bet out of 2-12 and money out of 0-1000, even negative bet or non numeric ones</li>\n<li>add a loop allowing player to play multiples games (with money carried between)</li>\n<li>i probably would have used a table to store possibilities of bet</li>\n</ul>\n<p>Without further informations about what you want to improve, it's hard to be more specific</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T16:57:56.270", "Id": "251911", "ParentId": "251910", "Score": "6" } }, { "body": "<p>For a beginner, this is a nice attempt.</p>\n<h1>Avoid &quot;using namespace std&quot;</h1>\n<p>Though this is trivial for a ten lines of code project, it immediately starts leading to issues when code size increases. Avoid it now. You can alternatively type <code>std::cout</code> or rather <code>using std::cout</code>, here the effect is localized to just <code>cout</code>. Check <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">here</a> for more info on why &quot;using namespace std&quot; is consider bad.</p>\n<h1>Prefer double to floating-point values</h1>\n<p>Double has 2x precision than floating-point values, thereore, provides more accuracy when performing calculations. Double on most machines is 8bytes whereas float is 4bytes, but the precision gain is worth it.</p>\n<h1>Make use of <code>random</code> header</h1>\n<p><code>rand</code> requires a seed to generate its pseudorandom numbers, if this seed is the same at each run, it produces the same output. This leads to some sort of dependency on the seed. <code>rand</code> also uses <code>srand</code> making it impossible to use with other random engine</p>\n<h1>Consider using a class</h1>\n<p>Your <code>main</code> function is cluttered with code here and there, move them to separate class, you could have a class that handles everything concerning the dice and the rest other functionalities.</p>\n<h1>Prefer <code>\\n</code> to <code>endl</code></h1>\n<p>Whenever you need a newline but don't explicitly need to flush the buffer, use <code>\\n</code>. <code>endl</code> adds a newline and flushes the buffer, this would result to a slight drop in performance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T17:54:46.653", "Id": "496120", "Score": "3", "body": "Actually for accuracy reasons backs use 2 integers for money values, one for dollars and one for cents. This prevents floating point errors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T18:19:11.543", "Id": "496122", "Score": "1", "body": "@pacmaninbw I totally agree." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T20:48:31.300", "Id": "496135", "Score": "3", "body": "Integers for money, sure. But why break it down into two, when handling just one is more efficient and convenient? And if it has twice the bits, you can store even bigger totals." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T17:25:55.347", "Id": "251912", "ParentId": "251910", "Score": "7" } }, { "body": "<p>The 2 previous answers provide a lot of good points, here are a few more suggestions:</p>\n<h2>Generating Random Numbers</h2>\n<p>As of C++11 there are better random number generators to use that the C standard library <code>rand()</code> function. This <a href=\"https://stackoverflow.com/questions/19665818/generate-random-numbers-using-c11-random-library/19666713\">stackoverflow question</a> provides the following:</p>\n<pre><code>#include &lt;random&gt;\n#include &lt;iostream&gt;\n\nint main() {\n std::random_device rd;\n std::mt19937 mt(rd());\n std::uniform_real_distribution&lt;double&gt; dist(1.0, 10.0);\n\n for (int i=0; i&lt;16; ++i)\n std::cout &lt;&lt; dist(mt) &lt;&lt; &quot;\\n&quot;;\n}\n</code></pre>\n<p>This provides a better distribution than the C function <code>rand()</code>.</p>\n<h2>Representing Money in Software</h2>\n<p>Banks don't like to lose money due to floating point error, nor can they legally cheat the costumers so they don't use floating point numbers to represent money, they use 2 integer values, one for dollars and one for cents. This prevents floating point errors from affecting the cash values involved.</p>\n<h2>Complexity</h2>\n<p>Any function larger than one screen in most IDEs or editors is to large, it is very hard to write, read, debug and maintain functions this large. You can create a class as one of the other answers suggested, you can also just create a number of functions called from <code>main()</code>. If you continue learning software you will learn principles on why this is important.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T20:46:02.513", "Id": "496134", "Score": "4", "body": "Two integers? Too wasteful and cumbersome. Better a single integer with twice the bits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T10:37:01.233", "Id": "496171", "Score": "0", "body": "Or for JPY just the yen - or more likely some multi didgit library or if old enough BCD rather than binary integers" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T18:20:48.597", "Id": "251917", "ParentId": "251910", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T16:32:14.217", "Id": "251910", "Score": "7", "Tags": [ "c++", "dice" ], "Title": "c++ dice game using random numbers" }
251910
<p>I did this Tic-Tac-Toe as an exercise for OOP.</p> <p>I would like to know possible improvements (the method main loop is too rock and roll, if you have suggestion to reduce it and improve readability).</p> <h3>Code:</h3> <pre><code>import numpy as np class Game(): &quot;&quot;&quot;Core of the game, contains the loop and victory checking&quot;&quot;&quot; def __init__(self): &quot;&quot;&quot;Initialization of the matrix and game launch&quot;&quot;&quot; self.__init_matrix() self.__init_launch_game() def __init_matrix(self): &quot;&quot;&quot;Fill matrix 3 by 3 of nan&quot;&quot;&quot; self.matrix = np.empty((3,3,)) self.matrix[:] = np.nan def __init_launch_game(self): &quot;&quot;&quot;Instantiate the two players and launch the loop&quot;&quot;&quot; self.player1 = Player(1) self.player2 = Player(2) self.__loop_game() def __loop_game(self): &quot;&quot;&quot;Ask the player to play as long as there is no victory or no full matrix&quot;&quot;&quot; while not(self.__is_victory()) and not(self.__is_full()): row, col = 5, 5 while not(self.__is_case_empty(row, col)): row,col = self.player1.tick_case() self.__is_case_empty(row, col) print(self.__is_case_empty(row, col)) self.__set_case(row, col, 1) if not(self.__is_victory()) and not(self.__is_full()): row, col = 5, 5 while not(self.__is_case_empty(row, col)): row,col = self.player2.tick_case() self.__is_case_empty(row, col) self.__set_case(row, col, 2) if self.__is_victory(): print('player2 wins') else: print('player1 wins') print(not(self.__is_victory()) and self.__is_full()) if not(self.__is_victory()) and self.__is_full(): print('no winner') def __is_case_empty(self, row, col): &quot;&quot;&quot;Check if the case has a nan&quot;&quot;&quot; if row == 5 and col == 5: return False elif np.isnan(self.matrix[row, col]): return True else: return False def __is_victory(self): &quot;&quot;&quot;check if the victory condition is met&quot;&quot;&quot; for nb in range(3): if np.isnan(np.min(self.matrix[nb,:])) != True: # Check row if np.sum(self.matrix[nb,:]) % 3 == 0: return True if np.isnan(np.min(self.matrix[:,nb])) != True:# Check col if np.sum(self.matrix[:,nb]) % 3 == 0: return True diag1 = self.matrix[0,0]+self.matrix[1,1]+self.matrix[2,2] # Check diag1 if np.isnan(np.min(diag1)) != True: if np.sum(diag1) % 3 == 0: return True diag2 = self.matrix[0,2]+self.matrix[1,1]+self.matrix[2,0] # Check diag2 if np.isnan(np.min(diag2)) != True: if np.sum(diag2) % 3 == 0: return True return False def __is_full(self): &quot;&quot;&quot;check if the matrix is full&quot;&quot;&quot; if np.isnan(self.matrix).any(): return False else: return True def __set_case(self, row, col, player): &quot;&quot;&quot;Change the value of a case in the matrix&quot;&quot;&quot; if player == 1: self.matrix[row , col] = 0 elif player == 2: self.matrix[row, col] = 1 print(self.matrix) class Player(): &quot;&quot;&quot;Player role, which ask what case shall be ticked and if the entered number is valid&quot;&quot;&quot; def __init__(self, player_id): &quot;&quot;&quot;init player id&quot;&quot;&quot; self.player_id = str(player_id) def tick_case(self): &quot;&quot;&quot;ask the player a case to tick&quot;&quot;&quot; row, col = 10, 10 while not(self.__is_case_valid(row, col)): print('Player ' + self.player_id + ' , this is your turn') row = input('which row do you want to enter?' ) col = input('which row do you want to enter?' ) return(int(row), int(col)) def __is_case_valid(self, row, col): &quot;&quot;&quot;check the validity of the ticked case&quot;&quot;&quot; if int(row) &lt; 0 or int(row)&gt;3 or int(col) &lt; 0 or int(col)&gt;3: print('value must be between 0 and 3') return False else: return True A = Game() </code></pre>
[]
[ { "body": "<p>Here are some ideas how you could improve your program which I hope will be helpful.</p>\n<h2>Documentation</h2>\n<p>Your use of docstrings is good to see. If you've never read it before, <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP 257</a> (Docstring Conventions) is useful so you can follow the norms in Python.</p>\n<h2>Name Mangling</h2>\n<p>I see you've used the double underscore for most methods, e.g. <code>__is_full</code>. This has the effect of mangling the names so it's not so easy to access the methods from outside the class (like <code>private</code> in many other languages). Python tends to have a different attitude to other languages though on private methods: generally you can default to leaving everything unmangled and public, which has the added bonus of making your uses of the method a bit less underscore-filled. Further discussion is available on <a href=\"https://stackoverflow.com/q/7456807/14591225\">Stack Overflow</a> if you're interested.</p>\n<h2>Sentinel Values</h2>\n<p>It took me a couple of minutes to realise that you're using position (5, 5) to represent an impossible slot, and later you use (10, 10) to do the same. It might make more sense just to use <code>None</code> to represent an invalid value and check <code>if row is None</code> etc.</p>\n<pre class=\"lang-py prettyprint-override\"><code># Initialise row and column with invalid value before we take user input\nrow, col = None, None\n</code></pre>\n<h2>Boolean Logic</h2>\n<p>You can save a few lines like so:</p>\n<pre><code>def __is_full(self):\n &quot;&quot;&quot;check if the matrix is full&quot;&quot;&quot;\n return not np.isnan(self.matrix).any()\n</code></pre>\n<p>There are a few other spots where you could simplify your boolean logic, although it's up to you how readable you think this is. You also don't need some brackets here: <code>not(self.__is_victory())</code>. You may just write <code>not self.__is_victory()</code> and this is probably more conventional.</p>\n<h2>Constructors</h2>\n<p>It is unconventional that the constructor of <code>Game</code> actually launches the game. I'd expect it just to create the game object, and have a separate <code>run</code> method.</p>\n<h2>Main Guard</h2>\n<p>It is convention in Python to use a <em>main guard</em> to check whether to run your code as a script. So you might write</p>\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == '__main__':\n game = Game()\n game.run()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T19:51:48.380", "Id": "496127", "Score": "1", "body": "Thank you. Understood each points. Took me some time to get Constructors but with Main Guard it was ok. I was not aware that mangling was a bad practice" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T18:57:18.673", "Id": "251918", "ParentId": "251913", "Score": "4" } }, { "body": "<h1><code>__</code> prefix</h1>\n<pre class=\"lang-py prettyprint-override\"><code> while not(self.__is_victory()) and not(self.__is_full()):\n row, col = 5, 5\n while not(self.__is_case_empty(row, col)):\n row,col = self.player1.tick_case()\n self.__is_case_empty(row, col)\n print(self.__is_case_empty(row, col))\n self.__set_case(row, col, 1)\n\n if not(self.__is_victory()) and not(self.__is_full()):\n row, col = 5, 5\n while not(self.__is_case_empty(row, col)):\n row,col = self.player2.tick_case()\n self.__is_case_empty(row, col)\n self.__set_case(row, col, 2)\n if self.__is_victory():\n print('player2 wins')\n else:\n print('player1 wins')\n print(not(self.__is_victory()) and self.__is_full())\n if not(self.__is_victory()) and self.__is_full():\n print('no winner')\n</code></pre>\n<p>Do you feel your code is very legible here? Not to me at least, the problem is that the member functions have a <code>__</code> prefix which makes the code look convoluted for no good reason. <br>\nThe exact same thing without the prefix</p>\n<pre class=\"lang-py prettyprint-override\"><code> while not(self.is_victory()) and not(self.is_full()):\n row, col = 5, 5\n while not(self.is_case_empty(row, col)):\n row,col = self.player1.tick_case()\n self.is_case_empty(row, col)\n print(self.is_case_empty(row, col))\n self.set_case(row, col, 1)\n\n if not(self.is_victory()) and not(self.is_full()):\n row, col = 5, 5\n while not(self.is_case_empty(row, col)):\n row,col = self.player2.tick_case()\n self.is_case_empty(row, col)\n self.set_case(row, col, 2)\n if self.is_victory():\n print('player2 wins')\n else:\n print('player1 wins')\n \n print(not(self.is_victory()) and self.is_full())\n if not(self.is_victory()) and self.is_full():\n print('no winner')\n</code></pre>\n<hr />\n<h1>Re-think Code structure</h1>\n<p>What I don't see is the need for a very huge <code>Player</code> What is the need for having two <code>Player</code> objects in your <code>Game</code>? Why can't you have just <strong>one</strong> variable that will either say <code>Player1</code> or <code>Player2</code> depending on whose turn it is to play? That way you can easily validate moves without the extra convoluted code in your current <code>Player</code> class.</p>\n<p>What you need to do is create an attribute that your <code>Game</code> class can hold, I would prefer an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">Enum</a>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from enum import Enum\n\nclass Player(Enum):\n one = 'x'\n two = 'o'\n</code></pre>\n<p>Now in your <code>__init__</code> method of <code>Game</code>, you can simply do</p>\n<pre class=\"lang-py prettyprint-override\"><code> def __init__(self):\n self.player = Player.one\n</code></pre>\n<p>Each time a player makes a move, you can simply update it this way</p>\n<pre class=\"lang-py prettyprint-override\"><code> def switch_player(self):\n if self.player == Player.one: \n self.player = Player.two\n else: \n self.player = Player.one\n</code></pre>\n<p>And whenever you need to value of Player-1 or 2, that is if you want to print the board, you can always do</p>\n<pre class=\"lang-py prettyprint-override\"><code>self.player.value\n</code></pre>\n<hr />\n<h1>Catch bad input</h1>\n<pre class=\"lang-py prettyprint-override\"><code> row, col = 10, 10\n while not(self.__is_case_valid(row, col)):\n print('Player ' + self.player_id + ' , this is your turn')\n row = input('which row do you want to enter?' ) \n col = input('which row do you want to enter?' ) \n return(int(row), int(col))\n</code></pre>\n<p>There is a problem here. Imagine this scenario</p>\n<blockquote>\n<p>which row do you want to enter? Code review<br>\nwhich row do you want to enter? 2</p>\n</blockquote>\n<p>I have three problems here</p>\n<ol>\n<li>The second message should ask <code>which column do you want to enter?</code></li>\n<li>After entering bad input the first time, the code happily accepts it and lets me enter the second one.</li>\n<li>After the code discovers that I entered invalid input, it doesn't ask me for new input, it gives me `ValueError: invalid literal for int() with base 10: 'Code review'</li>\n</ol>\n<p>you need to <a href=\"https://www.w3schools.com/python/python_try_except.asp\" rel=\"nofollow noreferrer\">try and except</a> and catch the <code>ValueError</code> and ask the user to enter valid input again. I would make a simple function</p>\n<pre class=\"lang-py prettyprint-override\"><code>def input_field(prompt, err_msg):\n while True:\n try:\n field = int(input(prompt))\n except ValueError:\n print(err_msg)\n continue\n break \n return field \n</code></pre>\n<p>and then do the validation process separately for <code>row</code> and <code>column</code> so the user doesn't have to repeat the same input if he messes up.</p>\n<pre class=\"lang-py prettyprint-override\"><code> while True:\n row = input_field(&quot;Enter row: &quot;, &quot;Error row...&quot;)\n if(not (is_row_valid(row))): \n print(&quot;error row...&quot;)\n continue\n break\n \n while True:\n col = input_field(&quot;Enter col&quot;, &quot;Error col...&quot;)\n ...\n</code></pre>\n<hr />\n<h1>Print a nicer board</h1>\n<p>When you print the current state of the board, you are printing</p>\n<pre><code>[[nan nan 1]\n [ 0. nan nan]\n [nan nan nan]]\n</code></pre>\n<p>How about printing this</p>\n<pre><code> . | . | o\n -----------\n x | . | .\n -----------\n . | . | .\n\n</code></pre>\n<hr />\n<h1>Make <code>case</code> a class</h1>\n<p>How about you represent any move with a class? A class that can hold three things, a row, a col, and the player</p>\n<p>You can use a <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"nofollow noreferrer\">data class</a></p>\n<pre class=\"lang-py prettyprint-override\"><code>@dataclass\nclass Move:\n row : int\n col : int\n player : Player\n</code></pre>\n<p>in your <code>Game</code> class, you can simplify it into</p>\n<pre class=\"lang-py prettyprint-override\"><code># After receiving row and col from user\n\nmove = Move(row, col, self.player)\n</code></pre>\n<p>Now you can pass around this <code>Move</code> object wherever you need it, for example, if you wanna validate this move</p>\n<pre class=\"lang-py prettyprint-override\"><code>def validate_move(self, move):\n if move.row &lt; 0 or move.row &gt; 3:\n return False\n if move.col &lt; 0 or move.col &gt; 3:\n return False\n\n return not(cell_is_occupied(move.row, move.col))\n</code></pre>\n<hr />\n<h1>Anti-pattern</h1>\n<pre class=\"lang-py prettyprint-override\"><code> if np.isnan(self.matrix).any():\n return False\n else:\n return True \n</code></pre>\n<p>This basically translates to</p>\n<pre class=\"lang-py prettyprint-override\"><code> if True:\n return False\n else:\n return True\n</code></pre>\n<p>Why not just</p>\n<pre class=\"lang-py prettyprint-override\"><code> return not (True):\n</code></pre>\n<p>So basically</p>\n<pre class=\"lang-py prettyprint-override\"><code> return not(np.isnan(self.matrix).any())\n</code></pre>\n<hr />\n<h1>Possible code structure</h1>\n<p>I wrote out a very basic design of how this game can be re-structured. Most of the big functions are left our for your implementation, I have filled in for some minor ones</p>\n<pre class=\"lang-py prettyprint-override\"><code>from enum import Enum\nfrom dataclasses import dataclass\n\n\nclass Player(Enum):\n one = 'o'\n two = 'x'\n none = '.'\n\n \n@dataclass\nclass Move:\n row : int\n col : int \n player : Player \n\nclass Game:\n def __init__(self):\n self.player = Player.one \n self.board = ...\n self.number_of_turns = 0\n\n def switch_player(self):\n # Switch players. If player is 1, player becomes 2 and vice-versa\n\n \n def print_board(self):\n # print a neat representation of the game board \n\n \n def victory(self):\n # return the Player that won, if nobody won the game return None \n\n \n def draw(self):\n return (self.victory() is None) and (number_of_turns == size_of_board):\n \n def input_move(self):\n # handle move input and valdation, you can create more functions if you want\n # receive row, col from user\n return Move(row, col, self.player)\n\n def perform_move(self, move):\n # make the move changes using move.row, move.col and move.player, and then self.switch_player()\n # also self.number_of_turns += 1\n def game_loop(self):\n while True:\n self.print_board()\n move = input_move()\n self.perform_move(move)\n if self.victory():\n ...\n else if self.draw():\n ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T19:15:56.867", "Id": "496204", "Score": "0", "body": "Thanks a lot, I like the elegance of having a player class and you switch player with attributes. I am not familiar with enum and dataclass but will study. Will definitly rewrite with your advices along with advices of the other people." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T19:37:02.207", "Id": "496213", "Score": "0", "body": "@Kerdiorp Well, I can't impose anything on you. it's your program :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T20:19:24.790", "Id": "251922", "ParentId": "251913", "Score": "12" } }, { "body": "<p>I'll just add some additional points that aren't brought up by the other users.</p>\n<h2>Initialize all your variables in <code>__init__</code></h2>\n<p>When looking at a class, you should be able to tell all its attributes by looking in the <code>__init__</code> method. Here it's not clear why you have <code>self.matrix</code> in some methods until you manually follow through all the calls in the initializer. Considering you never use <code>__init_launch_game</code> or <code>__init_matrix</code> anywhere, I'd suggest removing them and keep everything in your initializer.</p>\n<pre><code>def __init__(self): \n &quot;&quot;&quot;Initialization of the matrix&quot;&quot;&quot;\n self.matrix = np.empty((3,3,))\n self.matrix[:] = np.nan\n self.player1 = Player(1)\n self.player2 = Player(2)\n</code></pre>\n<p>If you want a <code>setup</code> or <code>restart</code> function, still declare the attributes with bogus values in the initializer.</p>\n<pre><code>def __init__(self): \n &quot;&quot;&quot;Initialization of the matrix&quot;&quot;&quot;\n self.matrix = None\n self.player1 = None\n self.player2 = None\n self.setup()\n</code></pre>\n<h2>Remove magic numbers</h2>\n<p>Don't use <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"noreferrer\">magic numbers</a>. What does <code>3</code> mean? It very much depend on the context. But if I ask what <code>MAXIMUM_ROWS</code> means, then you could very easily figure out that it's a value for the maximum amount of rows. So try to avoid raw literals in your code (unless they're easily understandable in context, which is usually numbers as 0 or maybe 1) and declare them once. You can have them as either global variables, class variables or instance variables. For your use-case, I think it make sense to have them ass class variables.</p>\n<pre><code>class Game:\n MAXIMUM_ROWS = 5\n MAXIMUM_COLUMNS = 5\n\n # ... And in later in the code you'll use it with:\n if row == Game.MAXIMUM_ROWS and col == Game.MAXIMUM_COLUMNS:\n</code></pre>\n<h2>Remove unnecessary tokens</h2>\n<p>Some tokens (i.e. characters or sequence of characters that represent some semantic) are used unnecessarily. For example <code>class Game():</code>. The parenthesis are meant to contain a list of classes to inherit from. Since you don't inherit from any classes, simply remove it (<code>class Game:</code>).</p>\n<p>The same goes for all your conditions. <code>not(self.__is_victory()) and not(self.__is_full())</code> can be just <code>not self.__is_victory() and not self.__is_full()</code>. Since parenthesis is just for so much (logical grouping, method calls, tuples, mathematical precedence) removing them makes the code a whole lot cleaner and easier to read.</p>\n<h2>Be consistent!</h2>\n<p>Minor nitpick, but be consistent when you write. Sometimes you have spaces after colon (<code>row, col = 5, 5</code>) and sometimes not (<code>row,col = self.player2.tick_case()</code>). Sometimes you have spaces between operators and sometimes not (<code>if int(row) &lt; 0 or int(row)&gt;3</code>). This might seem arbitrary, but can help you when the code is getting bigger in size and you need to search for specific patterns in your code base. It also helps with readability.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T14:06:37.183", "Id": "496181", "Score": "1", "body": "Welcome to the Code Review Community, nice first answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T19:34:30.430", "Id": "496212", "Score": "0", "body": "Thanks, I will keep my init simple, improve consistency and I really like the idea to avoid magic numbers" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T13:23:34.020", "Id": "251944", "ParentId": "251913", "Score": "4" } }, { "body": "<p>Many aspects have been addressed in the other answers so this answer will focus\non a higher-level software engineering consideration but, first, a few nitpicks:</p>\n<ul>\n<li><p><strong>algorithmic considerations are important!</strong> In particular, avoid doing\nunnecessary work: when a player plays a move, they only ever touch a single\nrow and a single column and, furthermore, might not even touch the diagonals.\nYet, your implementation checks every single row, column, and diagonal every\nsingle time. This is a waste of effort and the implementation could be made\nmore efficient by only checking a row/column/diagonal if it has been affected\nby the move.</p>\n</li>\n<li><p><strong>Don't be afraid of <code>while True</code></strong>: there are many instances where you need to\ncheck something as the condition of your loop but that something is only set\ninside of the loop and you therefore initialize it, before the loop, with\ngarbage so that your program doesn't crash the first time it checks the\ncondition. Don't do that!</p>\n<p>Instead, use <code>while True</code>, set that something, and check your condition to see\nif the loop is over. This is particularly powerful when the loop is the body\nof a function. For example (BTW, the <code>10</code> made me waste a couple of seconds\nwondering <em>why <code>10</code>?</em> ... don't make your reader waste their time!):</p>\n<pre><code>row, col = 10, 10\nwhile not(self.__is_case_valid(row, col)):\n print('Player ' + self.player_id + ' , this is your turn')\n row = input('which row do you want to enter?')\n col = input('which row do you want to enter?')\nreturn(int(row), int(col))\n</code></pre>\n<p>becomes (ignoring issues in the rest of the code for now):</p>\n<pre><code>while True:\n print('Player ' + self.player_id + ' , this is your turn')\n row = input('which row do you want to enter?')\n col = input('which row do you want to enter?')\n if self.__is_case_valid(row, col):\n return(int(row), int(col))\n</code></pre>\n</li>\n<li><p>Writing high-quality code inevitably relies on <strong>well-named variables and\nfunctions</strong>: although your code is pretty good in that aspect, I will use <em>cell</em>\nin the following when referring to what you call a <em>case</em> and <em>board</em> instead\nof your <code>matrix</code>: this improves readability, IMO.</p>\n</li>\n<li><p>Implement your <strong>algorithms as intuitively as possible</strong>, instead of evolving them\nbased of artificial constraints. For example, in <code>__is_case_empty</code>, you\neffectively check if a <em>cell</em> (see previous point) is empty or not, given its\ncoordinates; I'm convinced that the algorithm that would naturally come to you\nwould be something like &quot;check if the coordinates or valid and, if so, check\nwhat value I have stored at the corresponding address&quot; and nowhere would you\nthink of checking &quot;if the coordinates are (5,5)&quot;. Then why do it in your\nimplementation? Instead, something like <code>if not (0 &lt;= row &lt; 3 and 0 &lt;= col &lt; 3):</code> would be more appropriate.</p>\n</li>\n<li><p><strong>Don't rely on <a href=\"https://en.wikipedia.org/wiki/Magic_number_%28programming%29\" rel=\"nofollow noreferrer\">magic numbers</a></strong>: instead of <code>self.matrix = np.empty((3,3,))</code>,\ndefine <code>self.size = 3</code> and use it in place of the literal <code>3</code>, this way, we\nimmediately understand what you mean (see my previous point about <code>row, col = 10, 10</code>) and it can be programmatically accessed from elsewhere, instead of\nrepeating <code>3</code> throughout the code. What if you wanted to upgrade your game to\na 4-by-4 board?</p>\n</li>\n<li><p><strong>Think twice about dependencies</strong>: adding a dependency to your code is a trade-off as\nyour code itself becomes simpler thanks to the functionality of the library\nbut, at the same time, your project complexity increases. People will need to\ndownload that extra dependency, leading to potential issues with deployment\nand you are now wed to that library: bugs in your application might come from\ncode you don't own, changes in functionality might break your code (remember\nthat the library developers will certainly not care about <em>your code</em>) and\nwhat if the license of the code changes or if the library simply stops being\nmaintained altogether? Of course, NumPy isn't going away but, in general,\nadding a dependency to your code should be seriously thought through. NumPy is\nan incredibly powerful library but, in your case, what do you really gain from\nthe dependency you added to your project? In the way you use it, <code>NaN</code>s could\neasily be replaced by <code>None</code> and <code>self.matrix[i][j]</code> is really not that much\nharder to type than <code>self.matrix[i,j]</code> so are the pros really outweighing the\ncons?</p>\n</li>\n<li><p><strong><code>not</code>, <code>return</code>, ... are not functions</strong>: don't &quot;call&quot; them and, if parentheses\nare necessary (<em>e.g.</em> for operator priority), add a space before them, as you\nwould do in English: <code>return (int(row), int(col))</code> (BTW, the parentheses here\nare okay because the statement creates a <a href=\"https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences\" rel=\"nofollow noreferrer\">tuple</a> but I would personally write\n<code>return int(row), int(col)</code>) and <code>while not self.__is_case_valid(row, col):</code>.</p>\n</li>\n<li><p>Drop the <code>()</code> from <code>class Class():</code></p>\n</li>\n</ul>\n<hr />\n<p>Now the main point of this answer:</p>\n<h1>Use proper encapsulation</h1>\n<p><a href=\"https://en.wikipedia.org/wiki/Object-oriented_programming\" rel=\"nofollow noreferrer\">OOP</a> is a very powerful paradigm as it reflects our natural vision of the world.\nThings interact with each other and when representing this in code, it becomes\nmore intuitive to follow. However, as with real-world objects, properties of a\nclass should be contained in that class: that's called encapsulation.</p>\n<h2>The issue</h2>\n<p>In your case, <code>Player</code> knows details about the board (owned by an instance of\n<code>Game</code>) which are not supposed to be relevant to a player's actions. In\nparticular, <code>Player</code> is the one checking <code>is_case_valid</code>: that doesn't makes\nsense as that check and those properties are those of the board. Furthermore,\nhave you noticed how similar <code>Player.__is_case_valid</code> and <code>Game.__is_case_empty</code>\nare, conceptually? One of those has to be in the wrong place (actually, it's\nboth; see below)!</p>\n<p>This is even more obvious when you look at the name of your methods: <code>tick_case</code>\nand <code>is_case_valid</code> both have &quot;<code>case</code>&quot; in their names, the <em>cell</em> (case) should\neither be part of the object (which doesn't make sense for a <code>Player</code>) or be a\nparameter of the method but it's neither.</p>\n<p>The fact that your <code>Game</code> class holds your board data (<code>matrix</code>) is itself\nanother leaked encapsulation: the board <strong>is</strong> and object and should be treated\nas so. Just read your methods out loud: does <code>Game().__is_full()</code> really make\nsense? Is it really the <em>game</em> that is full? Yet another symptom of this missed\nopportunity is the fact that your code has to deal with so many unnecessary\ndetails that its actual purpose becomes unclear at first sight to the reader.\nCompare your</p>\n<pre><code>for nb in range(3):\n if np.isnan(np.min(self.matrix[nb,:])) != True: # Check row\n if np.sum(self.matrix[nb,:]) % 3 == 0:\n return True\n if np.isnan(np.min(self.matrix[:,nb])) != True:# Check col\n if np.sum(self.matrix[:,nb]) % 3 == 0:\n return True\ndiag1 = self.matrix[0,0]+self.matrix[1,1]+self.matrix[2,2] # Check diag1\nif np.isnan(np.min(diag1)) != True:\n if np.sum(diag1) % 3 == 0:\n return True\n\ndiag2 = self.matrix[0,2]+self.matrix[1,1]+self.matrix[2,0] # Check diag2\nif np.isnan(np.min(diag2)) != True:\n if np.sum(diag2) % 3 == 0:\n return True\nreturn False\n</code></pre>\n<p>with a more encapsulated example where all the details have been abstracted away\ninto a <code>Board</code> class:</p>\n<pre><code>for i in range(self.board.size):\n found_winner = self.board.unique_value_in_row(i)\n if found_winner:\n return found_winner\n found_winner = self.board.unique_value_in_col(i)\n if found_winner:\n return found_winner\n\nfound_winner = self.board.unique_value_in_diag()\nif found_winner:\n return found_winner\nreturn self.board.unique_value_in_sec_diag()\n</code></pre>\n<p>you might believe that this is not really a win as you might now have to write\nmore code: well it is better to have more lines of clearer code than fewer of\nhard-to-read code as it makes it easier to read and therefore easier to debug\nand, if your encapsulation is done right, it becomes <strong>by design</strong> harder to\nunknowingly add bugs because <strong>each layer of the problem is addressed\nin isolation</strong>. Also, notice something else: those comments explaining\nwhat the code does are gone as the <a href=\"https://en.wikipedia.org/wiki/Self-documenting_code\" rel=\"nofollow noreferrer\">code now documents itself</a> thanks to\nour well-picked function and variable names!</p>\n<p>Finally, for the previous method, we are still duplicating some code as the\nlogic is basically &quot;if this way of winning is verified, we've found the winner,\nelse if this other way of winning is verified, we've found the winner, else ...&quot;\nwhich still <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">&quot;smells&quot; as we duplicate the condition checking</a>. This can be\nsimplified even further by using <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generators</a> (a very powerful and central\nconcept in Python):</p>\n<pre><code>def winning_candidates(self):\n yield from (self.board.unique_value_in_row(i)\n for i in range(self.board.size))\n yield from (self.board.unique_value_in_col(i)\n for i in range(self.board.size))\n yield self.board.unique_value_in_diag()\n yield self.board.unique_value_in_sec_diag()\n\ndef find_winner(self):\n return next(winner for winner in self.winning_candidates() if winner, None)\n</code></pre>\n<p>In general, a function should do one (and only one) action, expressed clearly\nthrough its name (usually a verb/object combination). This is another important\naspect of proper class architecture: each method should do one thing <em>e.g.</em>\ninitialize (part of) its state (note that, as this is very common, Python even\nprovides the built-in <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__init__\" rel=\"nofollow noreferrer\"><code>__init__</code></a> method to do that!), check something,\nchange something else, ...</p>\n<h2><code>class Game:</code></h2>\n<p>In the case of <code>Game</code>, <code>__init__</code>, the method supposed to initialize a new\ninstance of the class, calls <code>__init__launch_game</code>, which does more\ninitialization and then launches the game through <code>__loop_game</code>: these 2 (3?)\nsteps are 2 actions and those 2 actions should be 2 function calls! Wouldn't it\nmake more sense, for the calling code, to do as follows?</p>\n<pre><code>game = Game() # obviously, this calls game.__init__()\ngame.play()\n</code></pre>\n<p>When you embrace this decomposition, you have more function calls and therefore\nget more return values (if a function is an action, a return value is the result\nof that action!), which can then be used to make your code even more readable.\nFor example:</p>\n<pre><code>game = Game()\nwinner = Game.play()\nif winner:\n print('Player {} wins!'.format(winner))\nelse:\n print('No winner.')\n</code></pre>\n<p>or, another possibility:</p>\n<pre><code>players = [Player(i) for i in range(2)]\ngame = Game(players)\nwinner = game.play()\nif winner:\n print(f'{winner} wins!')\nelse:\n print('No winner.')\n</code></pre>\n<p>where <code>Game.play()</code> now returns a (reference to a) <code>Player</code> instance!</p>\n<p>Notice the last <code>print</code> in the previous example: this is yet another instance of\nproper encapsulation! Although certainly not obvious the first time you see it,\nwhat happens there is that <code>{winner}</code> in the <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\">f-string</a> is replaced by the\nresult of <code>str(winner)</code> which itself returns <code>winner.__str__()</code>. The <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__str__\" rel=\"nofollow noreferrer\"><code>__str__</code></a>\nmethod is, similarly to <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__init__\" rel=\"nofollow noreferrer\"><code>__init__</code></a>, a <em>special method</em> supported by\nPython which is intended for returning the <em>nicely printable string\nrepresentation of an object</em>; see Python's <a href=\"https://docs.python.org/3/reference/datamodel.html\" rel=\"nofollow noreferrer\">data model</a> for more (and notice how\nit also follows this &quot;one action per function rule&quot; very closely).</p>\n<p>The reason why this implements encapsulation well is that, once you have your\nimplementation of <code>Player.__str__</code>, you can use it throughout your code and, if\nat any point, you want to change the way players are represented in your text\noutput, you only have to change <strong>one</strong> piece of code, <strong>inside <code>Player</code></strong> (as\nopposed to throughout your code). This is exactly why encapsulation is powerful:\nby programming against an abstract interface, you don't care about the <em>how</em> but\nonly about the <em>what</em> and even if the <em>how</em> changes, your calling code doesn't.</p>\n<h2><code>class Player:</code></h2>\n<p>To illustrate this, imagine you start with the following:</p>\n<pre><code>def Player:\n def __init__(self, player_id):\n self.id = player_id\n\n def __str__(self):\n return 'Player {}'.format(self.id)\n</code></pre>\n<p>and, whenever you need to print the player, you simply do:</p>\n<pre><code>player = Player(i)\n# ...\nprint(f'{player} plays very well!')\n# or: print('{} plays very well!'.format(player)) for Python pre-3.6\n</code></pre>\n<p>Now, imagine that you want to implement a new feature for referring to a player\nby their name. Then, with a properly encapsulated implementation, you only have\nto modify the code inside of <code>Player</code>. For example:</p>\n<pre><code>def Player:\n def __init__(self, player_id, name=None):\n self.id = player_id\n self.name = name\n\n def __str__(self):\n return self.name or 'Player {}'.format(self.id)\n</code></pre>\n<p>and those names having to come from somewhere, provide them to the\n<code>Player</code> constructor in the top-level script:</p>\n<pre><code>players = [Player(i, name=ask_name()) for _ in range(2)]\ngame = Game(players)\n# ...\n</code></pre>\n<p>At this point, by only having changed a couple of lines of code, we've also\nupdated the behaviour of all those <code>print(f'{player} ...</code> lines (potentially\nthousands of them); good luck doing this with your currently hard-coded <code>if is_player1: print('Player 1 ...') else: print('Player 2 ...')</code>!</p>\n<h2><code>class Board:</code></h2>\n<p>Now, let's move on to <code>Board</code>: obviously, when designing your classes, you'll\ndefine their methods to reflect what you expect to need from their instances. A\n<code>board</code> for a game of chess will certainly expose a completely different\ninterface from what is expected here! The following seemed to me to be what\nyour implementation required from the board:</p>\n<pre><code>class Board:\n def __init__(self, size):\n self.cells = [[None] * size for _ in range(size)]\n\n @property\n def size(self):\n return len(self.cells)\n\n def is_empty_cell(self, row, col):\n try:\n return self.cells[row][col] is None\n except:\n return False\n\n def is_full(self):\n cells = itertools.product(range(self.size))\n return not any(self.is_empty_cell(i, j) for i, j in cells)\n\n def unique_value_in_row(self, row):\n return unique_value(self.cells[row])\n\n def unique_value_in_col(self, col):\n return unique_value(row[col] for row in self.cells)\n\n def unique_value_in_diag(self):\n return unique_value(row[i] for i, row in enumerate(self.cells))\n\n def unique_value_in_sec_diag(self):\n return unique_value(row[~i] for i, row in enumerate(self.cells))\n\n def tick_cell_as(self, row, col, player):\n self.cells[row][col] = player.id\n</code></pre>\n<p>Based on this, you can then <em><a href=\"https://en.wikipedia.org/wiki/Object_composition\" rel=\"nofollow noreferrer\">compose</a></em> your <code>Game</code> instance from what makes up\na game (a board and players) and because most actions are performed by the\nplayers and the board, implementing the game itself becomes trivial:</p>\n<pre><code>class Game:\n def __init__(self, players):\n self.board = Board(3)\n self.players = players\n\n def play(self):\n while not (self.is_won() or self.board.is_full()):\n for player in self.players:\n player.tick_one_cell(self.board)\n return self.find_winner()\n\n def is_won(self):\n return self.find_winner() is not None\n\n def find_winner(self):\n # see above\n</code></pre>\n<p>while <code>Player</code> in turn interacts with the <code>board</code> (as would happen in real\nlife):</p>\n<pre><code>class Player:\n # ...\n def tick_one_cell(self, board):\n print(f'{self}, this is your turn')\n row, col = self.query_cell(board)\n board.tick_cell_as(row, col, self)\n\n def query_cell(self, board):\n while True:\n # ... get row and col from the user ...\n if board.is_empty_cell(row, col):\n return row, col\n</code></pre>\n<p>See how readable all of this is? You haven't written the code, yet you can\neasily understand (and therefore modify) it. This is exactly why readability is\nimportant in software engineering: the person maintaining the code might not\nhave been the one writing it! Once again, intuitive abstractions help a lot with\nthat.</p>\n<h2>Encapsulation and dependencies</h2>\n<p>Finally, regarding my previous point about dependencies, and on the topic of\nencapsulation, if you still decide to have them (or, in another project, if it's\na wise decision to do so), it is recommended to try to contain those\ndependencies as much as possible in encapsulated entities <em>e.g.</em> by only having\nNumPy calls inside of <code>Board</code> so that, if something goes wrong with that\ndependency, you can swap it out without having to re-write your whole\napplication. Instead, you would simply adapt those containing entities: once\nagain the modularity of the code provided by the abstraction of encapsulation\nsaves you!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T17:51:35.153", "Id": "496197", "Score": "1", "body": "This is an awesome first answer, keep it up!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T19:43:19.603", "Id": "496215", "Score": "0", "body": "@AryanParekh Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T20:19:07.747", "Id": "496218", "Score": "0", "body": "Thank you, detailed, clear and interesting, will reread it several time to diggest. I really like when you say to read loud the methods to see if it makes sense. I have difficulties to say what belong to what. I will focus on this and apply it to simple examples. With the quality of your answer and also the other answers, I will also spend time reading some other code reviews." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T13:57:42.480", "Id": "251947", "ParentId": "251913", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-10T17:58:01.967", "Id": "251913", "Score": "10", "Tags": [ "python", "python-3.x", "object-oriented", "tic-tac-toe" ], "Title": "TicTacToe in Python OOP" }
251913