body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Implementation of a Caesar cipher is a popular exercise and there are <a href="/questions/tagged/caesar-cipher%20c%2b%2b">many implementations</a> posted here on Code Review.</p> <p>My version is intended to be efficient and portable (subject to some limitations, below).</p> <hr /> <pre><code>#include &lt;algorithm&gt; #include &lt;array&gt; #include &lt;cctype&gt; #include &lt;climits&gt; #include &lt;cstdlib&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;numeric&gt; #include &lt;stdexcept&gt; class caesar_rotator { using char_table = std::array&lt;char, UCHAR_MAX+1&gt;; const char_table table; public: caesar_rotator(int rotation) noexcept : table{create_table(rotation)} {} char operator()(char c) const noexcept { return table[static_cast&lt;unsigned char&gt;(c)]; }; private: #define LETTERS &quot;abcdefghijklmnopqrstuvwxyz&quot; static char_table create_table(int rotation) { constexpr int len = (sizeof LETTERS) - 1; // don't count the terminating null static const auto* alpha2 = reinterpret_cast&lt;const unsigned char*&gt;(LETTERS LETTERS); // normalise to the smallest positive equivalent rotation = (rotation % len + len) % len; char_table table; // begin with a identity mapping std::iota(table.begin(), table.end(), 0); // change the mapping of letters for (auto i = 0; i &lt; len; ++i) { table[alpha2[i]] = alpha2[i+rotation]; table[std::toupper(alpha2[i])] = static_cast&lt;char&gt;(std::toupper(alpha2[i+rotation])); } return table; } #undef LETTERS }; int main(int argc, char **argv) { constexpr int default_rotation = 13; // Parse arguments int rotation; if (argc &lt;= 1) { rotation = default_rotation; } else if (argc == 2) { try { std::size_t end; rotation = std::stoi(argv[1], &amp;end); if (argv[1][end]) { throw std::invalid_argument(&quot;&quot;); } } catch (...) { std::cerr &lt;&lt; &quot;Invalid Caesar shift value: &quot; &lt;&lt; argv[1] &lt;&lt; &quot; (integer required)\n&quot;; return EXIT_FAILURE; } } else { std::cerr &lt;&lt; &quot;Usage: &quot; &lt;&lt; argv[0] &lt;&lt; &quot; [NUMBER]\nCaesar-shift letters in standard input by NUMBER places (default &quot; &lt;&lt; default_rotation &lt;&lt;&quot;)\n&quot;; return EXIT_FAILURE; } // Now filter the input std::transform(std::istreambuf_iterator&lt;char&gt;{std::cin}, std::istreambuf_iterator&lt;char&gt;{}, std::ostreambuf_iterator&lt;char&gt;{std::cout}, caesar_rotator{rotation}); } </code></pre> <hr /> <h1>Features and limitations</h1> <ul> <li>It's written using portable C++ which compiles with any compiler supporting C++11 or later. (But don't let that inhibit reviews from suggesting improvements that require newer versions - I am still interested!)</li> <li>We can shift by any representable integer (negative shift decodes a positive shift, and vice versa).</li> <li>It works with all single-byte character sets. Unlike many implementations, it works on systems where alphabetic characters are discontinuous, such as EBCDIC.</li> <li>It works with multi-byte character sets where the alphabetic characters are invariant (e.g. UTF-8). When using codings that shift out the alpha-chars, then non-alphabetic characters may be modified - but using the same program for the decoding will correctly restore the original input text.</li> <li>Because we use a table to produce output, we need storage for that table, sufficient to represent all character values. No problem for systems where <code>CHAR_BIT</code> is 8, but it may prevent use on systems with much wider character type.</li> <li>There is an overhead to constructing the table each run, which won't pay for itself with short input streams. But it's still small compared with the overhead of creating a process, and it's a big win for large inputs.</li> <li>I may write a separate wide-char implementation that addresses the limitations.</li> </ul> <hr /> <h1>The ugly stuff</h1> <ul> <li>I don't have access to an EBCDIC system to confirm my claim that it's correct on such platforms.</li> <li>Most of the ugliness is in <code>create_table()</code>, which in an earlier version had been an immediately-invoked lambda expression in the constructor's initialiser list; I moved it out to a named private function to make it easier to read and easier to skip when perusing the public interface.</li> <li>I don't like using a macro to concatenate two copies of the alphabet. But I couldn't find an alternative <code>constexpr</code> way to do that, even in C++20, other than writing the letters twice, which I didn't want to do. (And <code>alpha2</code> still isn't <code>constexpr</code>, because of the cast, but at least it enables reasonable compilers to store the string literal in <code>.text</code> segment or equivalent.)</li> <li>The <code>reinterpret_cast</code> offends me. And the <code>static_cast</code>s, though to a lesser extent. But we need unsigned values for <code>std::toupper()</code> and for array indexing, and plain <code>char</code> for the stream handling and string literal.</li> <li>I don't much like using <code>%</code> twice to get the positive modulo; is there a simpler way? I considered <code>rotation %= len; if (rotation &lt; 0) rotation += len;</code> but I'm not convinced that's better.</li> <li>In the main function, I throw an exception when argument has anything following an initial number, so that I handle all parsing errors in one place. Is that okay, or is there something better I could do?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T12:24:20.620", "Id": "531789", "Score": "0", "body": "An answer that improves any one of the \"ugly\" things is very welcome (even if it's just confirmation that the code functions correctly using EBCDIC)." } ]
[ { "body": "<h1>Avoid macros</h1>\n<p>There is absolutely no need for a macro here. Just write:</p>\n<pre><code>static const char *letters = &quot;abcdefghijklmnopqrstuvwxyz&quot;;\nauto alpha = reinterpret_cast&lt;const unsigned char *&gt;(letters);\n</code></pre>\n<p>And to access it safely:</p>\n<pre><code>table[alpha2[i]] = alpha2[(i + rotation) % len];\n</code></pre>\n<p>Alternatively, you could create a mutable string array holding the letters, and then use <code>std::rotate()</code> to create a rotated version of it.</p>\n<h1>Avoiding the <code>reinterpret_cast</code></h1>\n<p>Instead of creating a reinterpret-casted pointer to the string holding the letters, you can <code>static_cast</code> the individual characters. That's safer but arguably uglier because you then need more casts.</p>\n<p>A much better way would be to make <code>char_table</code> a class with an <code>operator[]</code> that takes a <code>char</code> as an argument, and which returns a reference. That way you can write:</p>\n<pre><code>char_table table;\n...\nfor (auto i = 0; i &lt; len; i++) {\n table[letters[i]] = letters[(i + rotation) % len];\n ...\n}\n</code></pre>\n<p>Of course, that pesky <code>std::toupper()</code> still gives trouble. Maybe you can create a helper function that takes care of doing <code>toupper()</code> safely on <code>char</code>s.</p>\n<h1>Optimizing table construction</h1>\n<p>Most of the inefficiency is in the modulo operation. But it can be largely avoided: first ensure <code>rot</code> is between 0 and 26, then you can make use of the fact that <code>i + rot</code> is between 0 and 52, and use <code>i + rot &lt; 26 ? i + rot : i + rot - 26</code> as an index. Again, you could make a little helper function for this to make the code more readable.</p>\n<p>Apart from that, consider making <code>build_table()</code> a <code>constexpr</code> function. This is rather trivial with <code>C++17</code> and later (the only thing to worry about is <code>std::iota()</code>, which isn't <code>constexpr</code> before C++20). It might be possible to make it <code>constexpr</code> in earlier C++ versions as well. With this, if <code>rot</code> is a compile-time constant, the table can also be built at compile-time.</p>\n<p>If you can build one table at compile-time, you could even build all 26 of them at compile-time, making it cheap to do the Caesar substitution with a rotation that you only know at runtime.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T12:49:54.053", "Id": "269547", "ParentId": "269544", "Score": "3" } }, { "body": "<p>Based on suggestions from <a href=\"/a/269547/75307\">G. Sliepen's answer</a>, I was able to eliminate the macro and localise most of the casts:</p>\n<pre><code>private:\n static constexpr int upper_int(char c)\n {\n return std::toupper(static_cast&lt;unsigned char&gt;(c));\n }\n static constexpr char upper_char(char c)\n {\n return static_cast&lt;char&gt;(upper_int(c));\n }\n\n static char_table create_table(int rotation)\n {\n constexpr auto* letters = &quot;abcdefghijklmnopqrstuvwxyz&quot;;\n constexpr int len = std::strlen(letters);\n\n // normalise to the smallest positive equivalent\n rotation = (rotation % len + len) % len;\n\n char_table table;\n // begin with a identity mapping\n std::iota(table.begin(), table.end(), 0);\n // change the mapping of letters\n for (auto i = 0, target = rotation; i &lt; len; ++i, ++target) {\n if (target == len) {\n target = 0;\n }\n table[letters[i]] = letters[target];\n table[upper_int(letters[i])] = upper_char(letters[target]);\n }\n return table;\n }\n</code></pre>\n<p>Not only that, but these changes reduce the maximum line length, for easier reading.<br />\n:-)</p>\n<p>Compared to the answer that inspired this, I did the computation of <code>target</code> differently: here, I help branch prediction by taking the forward path all but once. Yes, that is unnecessary micro-optimisation, but I'm here for a learning experience.</p>\n<p>For C++20 onwards, <code>create_table()</code> can be declared <code>constexpr</code>, though there's little point, as we never call it with a compile-time constant argument. With GCC, this even works with C++17, before <code>std::iota()</code> became <code>constexpr</code> - I think it's smart enough to examine the resultant code after expanding the template.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T19:18:06.227", "Id": "531808", "Score": "2", "body": "That looks great!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T13:53:34.723", "Id": "269548", "ParentId": "269544", "Score": "2" } }, { "body": "<p>You can avoid the <code>reinterpret_cast</code> without changing the logic, and at the same time drastically limit the scope of your macro:</p>\n<pre><code> #define LETTERS &quot;abcdefghijklmnopqrstuvwxyz&quot;\n+ static constexpr auto alphabet_size = sizeof LETTERS - 1;\n+ static constexpr unsigned char alpha2[sizeof LETTERS * 2 - 1] = LETTERS LETTERS;\n+#undef LETTERS\n+\n static char_table create_table(int rotation)\n {\n- constexpr int len = (sizeof LETTERS) - 1; // don't count the terminating null\n- static const auto* alpha2 = reinterpret_cast&lt;const unsigned char*&gt;(LETTERS LETTERS);\n+ constexpr int len = alphabet_size;\n\n@@ -44,3 +47,2 @@\n }\n-#undef LETTERS\n };\n</code></pre>\n<p>Still far from ideal (especially since it can’t be combined with AA style, which I’d otherwise follow) but much better.</p>\n<p>Secondly, and this is certainly subjective, but I really dislike implicit conversions to <code>bool</code>. I just about accept omitting <code>!= nullptr</code>; but implicit <code>int</code> to <code>bool</code> conversions just make the code less readable. Case in point, I had to actively think which exact condition was tested by <code>if (argv[1][end])</code>. I find it vastly more readable to write this explicitly, i.e.:</p>\n<pre><code>if (argv[1][end] != '\\0')\n</code></pre>\n<p>I’d probably also give <code>argv[1]</code> a dedicated name in this scenario since it’s used repeatedly, and requires nested array access. And I’d probably make <code>rotation</code> <code>const</code>, and use a conditional expression with a nested IIFE to initialise it. However, this will require a function-level <code>try</code> block (and admittedly this makes the code longer, which might not be a good trade-off in this simple case).</p>\n<p>Lastly, we probably don’t want to just catch <code>...</code> because if there’s an unexpected exception that’s a bug in the code, and catching the exception obliterates the stack trace.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T15:59:51.627", "Id": "531864", "Score": "1", "body": "I tried initializing a `std::array<unsigned char>` from string literal, but that's an error. I didn't realise I could initialise a `unsigned char[]` without a warning. I guess the array size should be `alphabet_size * 2` or `sizeof LETTERS * 2 - 2` to not have a couple of wasted elements? Remember that `sizeof` measures the whole string including the final null character that we don't need here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T16:01:13.240", "Id": "531865", "Score": "0", "body": "I did originally \"scope\" `LETTERS` around the two lines within the function, but that was hard to read. Your suggestion of extracting the constants is much better. (I only changed to a class quite late - originally, `rotate()` just returned a lambda containing the translation table)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T16:01:53.103", "Id": "531866", "Score": "0", "body": "@TobySpeight Yes, of course, my mistake. It does need to be `sizeof LETTERS - 1` though, otherwise the array will be too small to hold the string literal incl. zero termination." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T16:08:08.297", "Id": "531869", "Score": "0", "body": "@TobySpeight That’s only valid in C, [not in C++](https://stackoverflow.com/questions/56105682/how-to-initialize-a-char-array-without-the-null-terminator#comment98847166_56105835)!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T16:19:55.407", "Id": "531872", "Score": "0", "body": "Ah, [`dcl.init.string`](https://eel.is/c++draft/dcl.init.string), and the consensus interpretation is that you're right: [What language standards allow ignoring null terminators on fixed size arrays?](//stackoverflow.com/q/37861600/4850040)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T19:06:41.313", "Id": "531883", "Score": "0", "body": "In general, I agree on catching `(...)`. But in this specific case, I claim that all exceptions within that block indicate a failure to parse the shift value, and therefore we're handling them appropriately." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T15:43:49.770", "Id": "269587", "ParentId": "269544", "Score": "1" } }, { "body": "<p>I suggest a different approach:</p>\n<p>Nail the locale to the C locale, write the 26 possible translation-table as read-only data, and let the constructor just choose the right one.</p>\n<p>It probably takes a bit more space in the executable (6.5K data for 8bit char), but it will certainly be faster and needs less per-instance space at runtime.</p>\n<pre><code>#include &lt;array&gt;\n#include &lt;numeric&gt;\n\nconstexpr auto translation_tables = []{\n const char* bands[]{\n &quot;abcdefghijklmnopqrstuvwxyz&quot;,\n &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;\n };\n std::array&lt;std::array&lt;unsigned char, 1 + (unsigned char)-1&gt;, 26&gt; r;\n for (int rotate = 0; rotate &lt; 26; ++rotate) {\n auto&amp; table = r[rotate];\n std::iota(table.begin(), table.end(), (unsigned char)'\\0');\n for (auto band : bands)\n for (int i = 0; i &lt; 26; ++i)\n table[band[i]] = table[band[(i + rotate) % 26]];\n }\n return r;\n}();\n\nconstexpr auto caesar_rotator(int shift) noexcept {\n if ((shift %= 26) &lt; 0)\n shift += 26;\n auto table = translation_tables[shift].data();\n return [=](unsigned char c) noexcept { return table[c]; };\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T16:41:00.233", "Id": "531964", "Score": "0", "body": "You only need two consecutive copies of 'a'..'Z', not 26. Just point a pointer to the starting point based on the shift. That is, work the same as the old \"decoding rings\". Having the list repeat prevents the modulo operation, which is your real performance point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T17:23:42.623", "Id": "531974", "Score": "0", "body": "@JDługosz You know the two shifted rings are embedded in a block of 256 symbols (for 8-bit, aka minimal, bytes), the rest being identity-mapped? Thus, really need one mapping per shift-value, of which there are 26 different ones, as the rings are 26 unique symbols long." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T22:33:25.587", "Id": "532001", "Score": "0", "body": "I see. I thought you were just avoiding the expensive modulo operation, not the range test for ischar." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T20:29:46.323", "Id": "269592", "ParentId": "269544", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T12:00:02.097", "Id": "269544", "Score": "4", "Tags": [ "c++", "caesar-cipher" ], "Title": "Portable and efficient Caesar cipher" }
269544
<p>I am trying to build a personal content aggregator and I started off with Reddit.<br /> My aim is to build something that is designed properly for this task so that I could add more sources and delivery options easily.</p> <p>If possible, I'd like you to focus your reviews on the design of the code (any other feedback is welcome as well)</p> <pre><code>from abc import ABC, abstractmethod import praw import os CLIENT_ID = os.environ.get('REDDIT_CLIENT_ID') CLIENT_SECRET = os.environ.get('REDDIT_CLIENT_SECRET') class Source(ABC): @abstractmethod def connect(self): pass @abstractmethod def fetch(self): pass class RedditSource(Source): def connect(self): self.reddit_con = praw.Reddit(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, grant_type_access='client_credentials', user_agent='script/1.0') return self.reddit_con def fetch(self): pass class RedditHotProgramming(RedditSource): def __init__(self) -&gt; None: self.reddit_con = super().connect() self.hot_submissions = [] def fetch(self, limit: int): for submission in self.reddit_con.subreddit('programming').hot(limit=limit): self.hot_submissions.append(submission) def __repr__(self): urls = [] for submission in self.hot_submissions: urls.append(vars(submission)['url']) return '\n'.join(urls) if __name__ == '__main__': assert CLIENT_ID, CLIENT_SECRET reddit_top_programming = RedditHotProgramming() reddit_top_programming.fetch(limit=10) print(reddit_top_programming) </code></pre> <p>I am also pondering on how should I add a delivery module. as of now, my idea was to create a separate class with the strategy pattern in mind to allow different types of deliveries (email, IM, etc)</p>
[]
[ { "body": "<p>Your class tree is kind of scrambled. It doesn't make sense to have an abstract <code>connect</code> - not all sources will need connection, and any connection can just happen in the constructor.</p>\n<p><code>RedditSource.connect</code> is confused because it both sets a member - when best practices discourage setting new members outside of <code>__init__</code> - and returns it, only for the return value to be used in <code>super().connect()</code> - only to overwrite the same member variable. I would refactor this so that there is no <code>connect</code> method at all; and <code>RedditSource.__init__</code> instantiates the <code>praw.Reddit</code> object.</p>\n<p>Is the return value of <code>hot()</code> a source-agnostic type? I suspect not. It looks like your conversion from source-specific to source-agnostic data occurs in your <code>__repr__</code>. This is a problem because the type of <code>hot_submissions</code> will differ from the type of a similar member in a different source. One solution is</p>\n<ul>\n<li>Don't have a <code>hot_submissions</code> member at all, making the source class a source only and not a repository of data;</li>\n<li>Do not mutate <code>self</code> during <code>fetch</code>;</li>\n<li>Yield submissions from your <code>fetch</code>; and</li>\n<li>have the format of those submissions be whatever common format you care about from all of your sources, non-specific to Reddit. If you only care about a URL list, the return type of <code>fetch</code> should be an iterable of URLs with conversion happening in <code>fetch</code> or a subroutine.</li>\n</ul>\n<p>Do not include <code>assert</code> in production code as it can be trivially disabled.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T16:10:01.483", "Id": "269779", "ParentId": "269545", "Score": "1" } } ]
{ "AcceptedAnswerId": "269779", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T12:12:23.433", "Id": "269545", "Score": "0", "Tags": [ "python", "reddit" ], "Title": "Content aggregator with Python" }
269545
<p>first time posting here, as well as being new to coding in Java. I am trying to create a movie queue with an array that is able to contain 100 elements, but will only read and print the elements the user enters. I got the first section where a user enters a movie and it stores it and prints it working properly, I am just having problems getting my code to replace a movie that is entered. Here is what I have so far. The issue I am having is within case 2. Thanks for your time.</p> <pre><code>public static void main(String[] args) { Scanner input = new Scanner(System.in); String [] list = new String [100]; int count = -1; boolean cont = true; while (cont){ System.out.println( &quot;Please make a selection:\n&quot; + &quot;1 - Add a new movie\n&quot; + &quot;2 - Update a movie\n&quot; + &quot;3 - Print entire collection\n&quot; + &quot;4 - Quit&quot;); int response = input.nextInt(); String dummy = input.nextLine(); switch (response){ case 1: System.out.print(&quot;You have chosen to add a movie\n&quot;); System.out.print(&quot;Please enter a title:\n&quot;); String title = input.nextLine(); count++; list[count]=title; String [] newlist = new String [count+1]; newlist[count] = list[count]; break; case 2: System.out.println(&quot;You have chosen to update a movie&quot;); System.out.println(&quot;Please enter a title:&quot;); String original = input.nextLine(); System.out.println(&quot;Please enter a new title:&quot;); String newtitle = input.nextLine(); for (int i = 0; i &lt; list.length; i++){ if (list[i] == original){ list[i]=newtitle; } } break; case 3: System.out.println(&quot;You have chosen to print your collection&quot;); for (int i = 0; i &lt; count+1;i++){ System.out.print(list[i]); System.out.println(); } break; case 4: System.out.println(&quot;You have chosen to exit the application&quot;); System.out.println(&quot;Goodbye!&quot;); cont = false; break; } } } } </code></pre>
[]
[ { "body": "<p>I changed the starting count to 0, because it felt more natural and moved the increment after the assignment.</p>\n<p>I also implemented Java 17 switch, this way you can drop the <code>break;</code> keywords, and a <strong>text block</strong>.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n Scanner input = new Scanner(System.in);\n String [] list = new String [100];\n int count = 0;\n boolean cont = true;\n while (cont){\n System.out.println(&quot;&quot;&quot;\n Please make a selection:\n 1 - Add a new movie\n 2 - Update a movie\n 3 - Print entire collection\n 4 - Quit&quot;&quot;&quot;);\n int response = input.nextInt();\n input.nextLine();\n switch (response) {\n case 1 -&gt; {\n System.out.print(&quot;You have chosen to add a movie\\n&quot;);\n System.out.print(&quot;Please enter a title:\\n&quot;);\n String title = input.nextLine();\n list[count] = title;\n count++;\n }\n case 2 -&gt; {\n System.out.println(&quot;You have chosen to update a movie&quot;);\n System.out.println(&quot;Please enter a title:&quot;);\n String original = input.nextLine();\n for (int i = 0; i &lt; count; i++) {\n if (list[i].equals(original)) {\n System.out.println(&quot;Please enter a new title:&quot;);\n String newTitle = input.nextLine();\n list[i] = newTitle;\n break;\n }\n System.out.println(&quot;Movie not found&quot;);\n }\n }\n case 3 -&gt; {\n System.out.println(&quot;You have chosen to print your collection&quot;);\n for (int i = 0; i &lt; count; i++) {\n System.out.print(list[i]);\n System.out.println();\n }\n }\n case 4 -&gt; {\n System.out.println(&quot;You have chosen to exit the application&quot;);\n System.out.println(&quot;Goodbye!&quot;);\n cont = false;\n }\n }\n }\n}\n</code></pre>\n<p>These lines didn't seem to serve any function:</p>\n<pre class=\"lang-java prettyprint-override\"><code>String [] newlist = new String [count+1]; \nnewlist[count] = list[count]; \n</code></pre>\n<p>I also removed the dummy variable, you only need to call nextLine() to consume the <code>\\n</code> before calling it again.</p>\n<p>Apart from that, I would use a <strong>List</strong> instead of an array, that way you:</p>\n<ul>\n<li>Can use <code>size()</code> instead of keeping a count</li>\n<li>Don't have a fixed limit of movies</li>\n<li>Can easily delete movies without open coded bulk copy</li>\n<li>Don't need to reinvent <code>indexOf()</code></li>\n</ul>\n<p><em>Unless you are coding for some really old device with very limited memory, you are almost always better of with a List.</em></p>\n<p>You might also want to add a <strong>default</strong> to the switch to handle other cases.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T12:03:11.123", "Id": "531846", "Score": "1", "body": "`use [a List] instead of an array[…]don't need to keep count […no fixed] limit […] easily delete movies without [open coded bulk] copy` + no need to reinvent [`indexOf()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/List.html#indexOf(java.lang.Object))" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T18:51:32.947", "Id": "269554", "ParentId": "269549", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T13:56:47.117", "Id": "269549", "Score": "1", "Tags": [ "java", "array" ], "Title": "Removing a string element from an array when the array is set to 100 but only contains and prints the elements a user enters" }
269549
<h1>Goal</h1> <p>My program takes a yaml config file as parameter <code>python myprogram.py cfg.yml</code>.</p> <ul> <li>all modules can access the cfg content with a simple module import</li> <li>the imported <code>config</code> behaves like the loaded top-level yaml dictionary for reading operations</li> </ul> <pre><code># module_a.py from config_module import cfg_class as config print(config['pi']) </code></pre> <h1>Reasoning</h1> <p>I wanted to follow the official python FAQ to <a href="https://docs.python.org/3/faq/programming.html#how-do-i-share-global-variables-across-modules" rel="nofollow noreferrer">share config global variables across modules</a> but I could only define the parameters in a pre-defined file that cannot be changed by the user:</p> <pre><code># config_module.py pi = 3.14 </code></pre> <p>To let the user choose a yaml config file, I changed config.py to:</p> <pre><code># config_module.py class cfg_class: pass </code></pre> <p>and the very top of <code>myprogram.py</code> to</p> <pre><code># myprogram.py from config_module import cfg_class as config import yaml if __name__=='__main__': with open(sys.argv[1], 'r') as f: cfg_dict = yaml.safe_load(f) config.cfg_dict = cfg_dict </code></pre> <p>As a result all modules have access to the config content</p> <pre><code># module_a.py from config_module import cfg_class as config print(config.cfg_dict['pi']) </code></pre> <p>Instead of using <code>config.cfg_dict['pi']</code> I wanted to use <code>config['pi']</code>. To do that I defined the <code>__getitem__</code> for the <code>cfg_class</code>:</p> <pre><code>class cfg_class: def __getitem__(self, x): return self.cfg_dict[x] </code></pre> <p>It failed with <code>TypeError: 'type' object is not subscriptable</code>. An explanation to this problem is <a href="https://stackoverflow.com/a/12447078">given here</a>. It indicates that we need a metaclass for cfg_class:</p> <pre><code># config.py class Meta(type): def __getitem__(self, x): return cfg_class.cfg_dict[x] class cfg_class(metaclass=Meta): pass </code></pre> <p>And now it works. Below is the code for</p> <pre><code>config_module.py myprogram.py module_a.py module_b.py cfg.yml </code></pre> <p>Any feedback?</p> <h1>Working code</h1> <pre><code># config_module.py class Meta(type): def __getitem__(self, x): return cfg_class.cfg_dict[x] class cfg_class(metaclass=Meta): pass </code></pre> <pre><code># myprogram.py import sys import yaml from config_module import cfg_class as config import module_a import module_b if __name__=='__main__': with open(sys.argv[1], 'r') as f: cfg_dict = yaml.safe_load(f) config.cfg_dict = cfg_dict module_a.a_class_from_module_a() module_b.a_class_from_module_b() </code></pre> <pre><code># module_a.py from config_module import cfg_class as config class a_class_from_module_a: def __init__(self): print( 'I am an instance of a_class_from_module_a' ' and I have access to config: ', config['pi'] ) </code></pre> <pre><code># module_b.py from config_module import cfg_class as config class a_class_from_module_b: def __init__(self): print( 'I am an instance of a_class_from_module_b' ' and I have access to config: ', config['pi'] ) </code></pre> <pre><code># cfg.yml --- pi: 3.14 ... </code></pre> <p>Result:</p> <pre><code>$ python myprogram.py cfg.yml &gt;&gt; I am an instance of a_class_from_module_a and I have access to config: 3.14 &gt;&gt; I am an instance of a_class_from_module_b and I have access to config: 3.14 </code></pre> <h3>Edit: simpler solution thanks to @MiguelAlorda who almost got it all right and @RootTwo who fixed the problem</h3> <pre><code># config_module.py import yaml config = {} def load_config(file_str: str) -&gt; None: global config with open(file_str) as f: # config = yaml.safe_load(f) # does not work because it unbinds config, see comment from @RootTwo config.update(yaml.safe_load(f)) </code></pre> <pre><code># myprogram.py import sys import config_module import module_a import module_b if __name__=='__main__': config_module.load_config(sys.argv[1]) x = module_a.a_class_from_module_a() y = module_b.a_class_from_module_b() print(x,y) </code></pre> <pre><code># module_a.py from config_module import config class a_class_from_module_a: def __init__(self): print( 'I am an instance of a_class_from_module_a' ' and I have access to config: ', config['pi'] ) </code></pre> <pre><code># module_b.py from config_module import config class a_class_from_module_b: def __init__(self): print( 'I am an instance of a_class_from_module_b' ' and I have access to config: ', config['pi'] ) </code></pre> <pre><code>#cfg.yml --- pi: 3.14 ... </code></pre> <p>Output:</p> <pre><code>$ python myprogram.py cfg.yml I am an instance of a_class_from_module_a and I have access to config: 3.14 I am an instance of a_class_from_module_b and I have access to config: 3.14 &lt;module_a.a_class_from_module_a object at 0x000002391D5F8F48&gt; &lt;module_b.a_class_from_module_b object at 0x000002391D5FB288&gt; </code></pre>
[]
[ { "body": "<p>welcome to Code Review!</p>\n<p>I think this approach is a bit overkill. You could simply have a <code>config</code> dict in the <code>config_module</code>, and have a <code>config_module.load_config(file_str: str) -&gt; None</code> function:</p>\n<pre class=\"lang-py prettyprint-override\"><code># config_module.py\nimport yaml\n\nconfig = {}\n\ndef load_config(file_str: str) -&gt; None:\n global config\n with open(file_str) as f:\n config.update(yaml.safe_load(f))\n</code></pre>\n<p>And then in you main:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import sys\n\nimport config_module\n\nif __name__ == &quot;__main__&quot;:\n config_module.load_config(sys.argv[1])\n</code></pre>\n<p>Using the config:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from config_module import config\n\nconfig[&quot;some_config_key&quot;]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T07:58:58.403", "Id": "269570", "ParentId": "269550", "Score": "2" } } ]
{ "AcceptedAnswerId": "269570", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T17:36:16.607", "Id": "269550", "Score": "1", "Tags": [ "python", "configuration" ], "Title": "Python - Share global variables across modules from user-defined config file" }
269550
<p>The problem is as below:</p> <blockquote> <p>Two archery teams A and B compete with the same number of members. If the score of team A[i] is higher than that of team B[i], the total score of team A will be +1, so given team A and B with any number of members, please calculate how total score of team A will be the highest value and write down the best order of team A members.<br> <br> Input: A = [2,7,11,15]; B = [1,10,4,11]; <br> <br> Output: [2,11,7,15]</p> </blockquote> <p>This is the question asked in a group, I don't know other test cases. So I change the order of team A, B to test my code.</p> <p>Here is my code:</p> <pre><code>function sortTeam(a, b){ let result = []; const asort = a.slice().sort((a,b) =&gt; a - b); for (let i = 0; i &lt; b.length; i++){ let bi = b[i]; for (let j = 0; j &lt; asort.length; j++){ let aj = asort[j]; if (!result.includes(aj) &amp;&amp; aj &gt; bi){ result.push(aj); break; } } } //console.log('result', result); return result; } </code></pre> <p>Here is the version of using <code>splice</code> to reduce complexity:</p> <pre><code>function sortTeam(a, b){ let result = []; const asort = a.slice().sort((a,b) =&gt; a - b); for (let i = 0; i &lt; b.length; i++){ let bi = b[i]; for (let j = 0; j &lt; asort.length; j++){ let aj = asort[j]; if (aj &gt; bi){ result.push(aj); asort.splice(j, 1); break; } } } //console.log('result', result); return result; } </code></pre> <p>My questions are:</p> <ul> <li>Is there a way that I can reduce the complexity of this code?</li> <li>I can remove the <code>includes</code> check by using <code>splice</code> on asort but it's still 2 loops. And splice mutates the array -&gt; should I use it? (I'm not into FP in anyway, just asking in general)</li> <li>As for FP, I was trying to using <code>forEach</code> but it doesn't let me using <code>break</code>, so if you guys have a FP version, please let me know (reduce is kind of a normal for-loop to me, I mean the look doesn't clean as other high order functions)</li> <li>What kind of problem is this? (I want to know the pattern or name so that I can find more similar problems to practice)</li> </ul>
[]
[ { "body": "<p>Several things.</p>\n<p>Firstly, the code as it is throws a syntax error. You can fix this by removing the <code>=&gt;</code>.</p>\n<p>Secondly, since you're not using the variables <code>i</code> and <code>j</code> except to index into the lists <code>a</code> and <code>b</code>, you can just use a for-of loop:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function sortTeam(a, b){\n let result = [];\n const asort = a.slice().sort((a,b) =&gt; a - b);\n for (let bi of b){\n for (let aj of asort){\n if (!result.includes(aj) &amp;&amp; aj &gt; bi){\n result.push(aj);\n break;\n }\n }\n }\n console.log('result', result);\n return result;\n}\n</code></pre>\n<p>Finally, you probably want to use more descriptive variable names (although <code>(a,b) =&gt; a - b</code> is fine), and you don't need the <code>console.log</code> call - if you want to log the result, log the return value of the function: If you're calling this function thousands of times, you don't want to fill up the screen with its results.</p>\n<pre class=\"lang-js prettyprint-override\"><code>function sortTeam(teamA, teamB){\n let result = [];\n const sortedTeamA = teamA.slice().sort((a,b) =&gt; a - b);\n for (let playerB of teamB){\n for (let playerA of sortedTeamA){\n if (!result.includes(playerA) &amp;&amp; playerA &gt; playerB){\n result.push(playerA);\n break;\n }\n }\n }\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T06:38:51.433", "Id": "531910", "Score": "0", "body": "Great! Thanks for your comment, I updated the code so that it won't throw error again :D" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T02:26:47.080", "Id": "269596", "ParentId": "269551", "Score": "1" } }, { "body": "<h3>Verifying assumptions</h3>\n<p>The implementation only works under some assumptions not mentioned in the problem statement:</p>\n<ul>\n<li>There exists an ordering of <code>A</code> such that for all index <code>i</code>, <code>A[i] &gt; B[i]</code></li>\n<li>There are no duplicate values in <code>A</code></li>\n</ul>\n<p>If any of these assumptions is not true,\nthe implementation will produce incorrect results (smaller array than the original).</p>\n<p>Also, the implementation mutates one of the input arrays,\neffectively assuming this is acceptable.</p>\n<p>It's important to clarify and verify assumptions in order to solve the right problem, correctly.</p>\n<h3>Inefficient algorithm</h3>\n<p>For each element of <code>B</code>,\nthe implementation loops over elements of <code>A</code>.\nAs often the case with such nested loops,\nthe algorithm has <span class=\"math-container\">\\$O(n^2)\\$</span> time complexity.</p>\n<p>A more efficient algorithm exists:</p>\n<ul>\n<li>Sort <code>A</code></li>\n<li>Build an array of ranks from the elements of <code>B</code>.\n<ul>\n<li>For example for <code>[5, 6, 4]</code> the ranks would be <code>[1, 2, 0]</code></li>\n</ul>\n</li>\n<li>Map the ranks to values in sorted <code>A</code></li>\n</ul>\n<p>The smallest part of this algorithm is the sorting of arrays (of <code>A</code>, and when building the ranks). That gives an improved time complexity of <span class=\"math-container\">\\$O(n \\log n)\\$</span>.</p>\n<pre><code>// returns an array where each value is the rank\n// of the corresponding value in nums.\n// for example: given [1, 8, 4, 9] -&gt; [0, 2, 1, 3]\nfunction buildRanks(nums) {\n // build array of indexes (&quot;identity map&quot;: 0 -&gt; 0, 1 -&gt; 1, ...)\n const indexes = Array(nums.length);\n for (let i = 0; i &lt; nums.length; i++) {\n indexes[i] = i;\n }\n\n // reorder the indexes to match the ordering of values in nums\n indexes.sort((a, b) =&gt; nums[a] - nums[b]);\n\n // build array of ranks, using sorted indexes\n const ranks = Array(nums.length);\n for (let rank = 0; rank &lt; nums.length; rank++) {\n ranks[indexes[rank]] = rank;\n }\n return ranks;\n}\n\nfunction sortTeam(A, B) {\n // using [...A] to avoid mutating A itself\n const sortedA = [...A].sort((a, b) =&gt; a - b);\n\n // map ranks of B to sorted values of A\n return buildRanks(B)\n .map(rank =&gt; sortedA[rank]);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T11:49:12.667", "Id": "532253", "Score": "0", "body": "I need some times to digest your algo. In the mean time, I want to ask if using \"splice\" helps achieve the complexity of O(nlogn) as your solution? (I added the splice version in the original post)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T14:13:32.020", "Id": "269638", "ParentId": "269551", "Score": "2" } }, { "body": "<p>From a short review</p>\n<ul>\n<li><code>asort</code> is not a great name, <code>sortedA</code> could have been better?</li>\n<li>As mentioned by another user, it is bad practice to change lists you receive as a parameter</li>\n<li>You only us <code>bi</code> once. I would use <code>b[i]</code> in that one place for readability</li>\n<li><code>aj</code> is not a great name, your two letter variables make your code hard to read</li>\n<li>Once you realize that you can just match equal <em>relative</em> strenghths, the code can be easier</li>\n<li>A number of the <code>let</code> statements could and should be <code>const</code> statements</li>\n</ul>\n<p>This is my rewrite;</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>let a = [2,7,11,15]; \nlet b = [1,10,4,11];\n\nfunction stackTeam(ourTeam, theirTeam){\n\n const ourTeamSorted = Array.from(ourTeam).sort((a,b)=&gt;a-b);\n const theirTeamSorted = Array.from(theirTeam).sort((a,b)=&gt;a-b);\n const out = [];\n\n //Go over every opposing player in the order of their team\n for(let player of theirTeam){\n const playerPosition = theirTeamSorted.indexOf(player); \n //deal with opposing players with equal score\n theirTeamSorted[playerPosition] = undefined\n out.push(ourTeamSorted[playerPosition]);\n }\n return out;\n}\n\n console.log(\"Expected:\", [2,11,7,15]);\n console.log(stackTeam(a, b));</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-11-08T09:25:04.513", "Id": "269869", "ParentId": "269551", "Score": "1" } } ]
{ "AcceptedAnswerId": "269869", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T18:25:19.503", "Id": "269551", "Score": "2", "Tags": [ "javascript", "array", "sorting" ], "Title": "Sort one array base on another array" }
269551
<p>I have a Spring MVC controller but I'm not sure that it is a good or bad design. As far as I know, api versioning is missing but apart from that I implemented Swagger for documentation and added SpringSecurity and tried to follow YARAS(Yet Another RESTful API Standard) to build it but I need another eye on that to comment it.</p> <pre><code>@Slf4j @Controller @RequestMapping @RequiredArgsConstructor public class XGameController implements GameController { private final GameService gameService; private final ObjectMapper mapper; @RequestMapping(value = &quot;/&quot;, method= RequestMethod.GET) public String index() { return &quot;game&quot;; } @RequestMapping(value = &quot;/login&quot;, method= RequestMethod.GET) public String login() { return &quot;login&quot;; } @Secured(&quot;ROLE_USER&quot;) @RequestMapping(value = &quot;/games&quot;, method= RequestMethod.POST) public String initializeGame(Model model) { log.info(&quot;New XGame is initializing...&quot;); Game game = new Game(); game = gameService.initializeGame(game.getId()); try { model.addAttribute(&quot;game&quot;, mapper.writeValueAsString(game)); } catch (JsonProcessingException e) { log.error(e.getMessage()); } log.info(&quot;New XGame is initialized successfully!&quot;); return &quot;game&quot;; } @Secured(&quot;ROLE_USER&quot;) @RequestMapping(value = &quot;/games/{gameId}&quot;, method= RequestMethod.PUT) public @ResponseBody Game play(@PathVariable(&quot;gameId&quot;) String gameId, @RequestParam Integer pitNumber, @RequestParam String action) { log.info(&quot;Sowing stone is triggered...&quot;); return gameService.executeGameRules(UUID.fromString(gameId), pitNumber); } @RequestMapping(value = &quot;/403&quot;, method= RequestMethod.GET) public String error403() { return &quot;/error/403&quot;; } } </code></pre> <p>My swagger snapshot;</p> <p><a href="https://i.stack.imgur.com/0dFDJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0dFDJ.png" alt="enter image description here" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T19:35:09.427", "Id": "531810", "Score": "1", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<p>I like to work with the request specific annotation. Also, you don't need <code>@RequestMapping</code>, unless you want to version your API with URL versioning or have some fixed path for all your endpoints.</p>\n<pre class=\"lang-java prettyprint-override\"><code>@Slf4j\n@Controller\n@RequiredArgsConstructor\npublic class XGameController implements GameController {\n\n private final GameService gameService;\n\n private final ObjectMapper mapper;\n\n @GetMapping\n public String index() {\n return &quot;game&quot;;\n }\n\n @GetMapping(&quot;/login&quot;)\n public String login() {\n return &quot;login&quot;;\n }\n\n @Secured(&quot;ROLE_USER&quot;)\n @PostMapping(&quot;/games&quot;)\n public String initializeGame(Model model) {\n log.info(&quot;New XGame is initializing...&quot;);\n Game game = new Game();\n game = gameService.initializeGame(game.getId());\n\n try {\n model.addAttribute(&quot;game&quot;, mapper.writeValueAsString(game));\n } catch (JsonProcessingException e) {\n log.error(e.getMessage());\n }\n log.info(&quot;New XGame is initialized successfully!&quot;);\n return &quot;game&quot;;\n }\n\n @Secured(&quot;ROLE_USER&quot;)\n @PutMapping(&quot;/games/{gameId}&quot;)\n public @ResponseBody\n Game play(@PathVariable(&quot;gameId&quot;) String gameId,\n @RequestParam Integer pitNumber,\n @RequestParam String action) {\n log.info(&quot;Sowing stone is triggered...&quot;);\n return gameService.executeGameRules(UUID.fromString(gameId), pitNumber);\n }\n}\n</code></pre>\n<p>I would create a separate Controller for <strong>error handling</strong>:</p>\n<pre><code>@Controller\npublic class CustomErrorController implements ErrorController {\n\n @RequestMapping(&quot;/error&quot;)\n public String handleError(HttpServletRequest request) {\n Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);\n if (status != null) {\n int statusCode = Integer.parseInt(status.toString());\n if (statusCode == HttpStatus.NOT_FOUND.value()) {\n return &quot;404&quot;;\n } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {\n return &quot;500&quot;;\n } else if (statusCode == HttpStatus.FORBIDDEN.value()) {\n return &quot;403&quot;;\n }\n }\n return &quot;error&quot;;\n }\n}\n</code></pre>\n<p>When using Spring Boot you don't even need a controller, because Spring will look for specific error pages (like <strong>403.html</strong>) in <code>src/main/resources/templates/error/</code> before defaulting to the generic <strong>error.html</strong> page whenever your application encounters an error or exception.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T17:37:06.730", "Id": "531876", "Score": "0", "body": "request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE) returns null for 403 forbidden page as request doesn't have a attribute of RequestDispatcher.ERROR_STATUS_CODE. What should I do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T05:34:25.880", "Id": "531907", "Score": "2", "body": "i had a similar review ad advised to separate the errorhandling as well - good proposal!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T12:37:21.247", "Id": "531931", "Score": "0", "body": "@Burak Where is this request originating from? Maybe you can ask a question on Stack Overflow and show your new code. If you link it in a comment I will find it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T19:48:08.467", "Id": "531983", "Score": "0", "body": "@H3AR7B3A7 I can edit this question and post the new code. By the way, I solved that problem so you can just review my new version of controller?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T20:01:31.863", "Id": "269561", "ParentId": "269552", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T18:25:20.593", "Id": "269552", "Score": "3", "Tags": [ "java", "api", "spring", "spring-mvc" ], "Title": "A controller for a Game Service" }
269552
<p>I have made a program that does what the title explains. It also hashes the file to check for changes. I will be doing this for a project to keep track of files that has been changed when doing different things in that certain filetree. I need this to be done as an sqlite/python app to make information easily available regarding the files of interest. This will later be used in an TKinter GUI app and the Parent column contains the rowid for its parent folder to make it work with TKinter. I will make it able to use the Tags column for searching within the app as i progress.</p> <p>I have been programming for a few years, but not much, I feel a lack in confidence and therefore I am throwing my code out here to get some review. I need to get better at OOP, efficiency and my logical sense needs an update from some bright minds. Please see the full code below, it is two files: filesystemScanner.py:</p> <pre><code>import os import hashlib from pathlib import Path from mydatabasemanagerfile import MyDatabaseManager path = &quot;C:\\Users\Skaft\\Documents\\GitHub&quot; isFolder = True fullList = [] currhash = &quot;&quot; db_name = &quot;parenttest.db&quot; table_name = &quot;Windows10&quot; my_current_db = MyDatabaseManager(db_name, table_name) ##################################################################### # copied from https://stackoverflow.com/questions/24937495/ # how-can-i-calculate-a-hash-for-a-filesystem-directory-using-python ##################################################################### def md5_update_from_dir(directory, my_hash): assert Path(directory).is_dir() for hash_path in sorted(Path(directory).iterdir(), key=lambda p: str(p).lower()): my_hash.update(hash_path.name.encode()) if hash_path.is_file(): with open(hash_path, &quot;rb&quot;) as f: for chunk in iter(lambda: f.read(4096), b&quot;&quot;): my_hash.update(chunk) elif hash_path.is_dir(): my_hash = md5_update_from_dir(hash_path, my_hash) return my_hash def md5_dir(directory): return md5_update_from_dir(directory, hashlib.md5()).hexdigest() #################################################### # End of copy #################################################### def file_hasher(hashing_file): try: if not isFolder: with open(hashing_file, &quot;rb&quot;) as current: readfile = current.read() current_hash = hashlib.md5(readfile).hexdigest() return current_hash except PermissionError: current_hash = &quot;Could not hash due to permission&quot; return current_hash for (dirpath, dirnames, filenames) in os.walk(path): isFolder = True full_dirpath = dirpath + &quot;\\&quot; fullList.append([full_dirpath, md5_dir(full_dirpath), isFolder]) for file in filenames: file_path = dirpath + &quot;\\&quot; + file isFolder = False fullList.append([file_path, file_hasher(file_path), isFolder]) my_current_db.initialize_db() for file_info in fullList: my_current_db.my_updater(file_info[0], file_info[1], file_info[2]) my_current_db.inserting_parentID() my_current_db.inserting_suffix() my_current_db.close_db() </code></pre> <p>And mydatabasemanagerfile.py</p> <pre><code>import sqlite3 import datetime import pathlib class MyDatabaseManager: def __init__(self, db_name, table_name): self.db_name = db_name self.table_name = table_name self.conn = sqlite3.connect(self.db_name) self.cur = self.conn.cursor() def initialize_db(self): &quot;&quot;&quot;Function to open database, create if not exists&quot;&quot;&quot; print(&quot;Opened database successfully&quot;) # drop_if_exist = &quot;DROP TABLE IF EXISTS {}&quot;.format(self.table_name) # self.cur.execute(drop_if_exist) create_table = '''CREATE TABLE IF NOT EXISTS {} (&quot;Path&quot; TEXT NOT NULL, &quot;Information&quot; TEXT, &quot;Tags&quot; TEXT, &quot;Parent&quot; INTEGER, &quot;isFolder&quot; INTEGER, &quot;fileExt&quot; TEXT, &quot;MD5&quot; TEXT, &quot;Updated&quot; TEXT, &quot;See also&quot; TEXT )'''.format(self.table_name) self.cur.execute(create_table) print(&quot;Table created successfully&quot;) def my_updater(self, path, md5, isFolder): query_path = '''SELECT rowid, Path FROM {} WHERE Path = &quot;{}&quot;'''.format(self.table_name, path) if self.conn.execute(query_path).fetchone() is None: # Test if returns None. result_path = &quot;Please add me&quot; # Placeholder to specify that it needs to be inserted, it does not exist result_hash = &quot;Please add me&quot; else: result_path = self.conn.execute(query_path).fetchone()[1] rowid = self.conn.execute(query_path).fetchone()[0] query_hash = '''SELECT MD5 FROM {} WHERE rowid = &quot;{}&quot;'''.format(self.table_name, rowid) result_hash = self.conn.execute(query_hash).fetchone()[0] current_time = datetime.datetime.now() if path == result_path and md5 != result_hash: query = '''UPDATE {} SET MD5=?, Updated=? WHERE rowid = &quot;{}&quot;'''.format(self.table_name, rowid) self.cur.execute(query, (md5, current_time)) elif path != result_path: query = '''INSERT INTO {} (Path, MD5, isFolder, Updated) VALUES (?, ?, ?, ?)'''.format(self.table_name) self.cur.execute(query, (path, md5, isFolder, current_time)) else: #print(&quot;Path: &quot;, path, &quot;\n&quot;, &quot;result_path: &quot;, result_path, &quot;\n&quot;, &quot;md5 : &quot;, md5, &quot;\n&quot;, &quot;result_hash: &quot;, # result_hash, &quot;\n&quot;) pass self.conn.commit() def inserting_parentID(self): query = '''SELECT rowid, Path FROM {}'''.format(self.table_name) all_paths = self.cur.execute(query).fetchall() for rowid, path in all_paths: parent_path_split = path.split(&quot;\\&quot;) if rowid == 1: continue if path[-1] == &quot;\\&quot;: parent_path_joined = &quot;\\&quot;.join(parent_path_split[:-2]) + &quot;\\&quot; parent_path_joinedads = &quot;\\&quot;.join(parent_path_split[:-2]) + &quot;\\&quot; else: parent_path_joined = &quot;\\&quot;.join(parent_path_split[:-1]) + &quot;\\&quot; parent_query = '''SELECT rowid FROM {} WHERE Path = &quot;{}&quot;'''.format(self.table_name, parent_path_joined) parent_paths = self.cur.execute(parent_query).fetchone() update_parentID = '''UPDATE {} SET Parent=? WHERE rowid = &quot;{}&quot;'''.format(self.table_name, rowid) self.cur.execute(update_parentID, (parent_paths)) self.conn.commit() def inserting_suffix(self): query = '''SELECT rowid, Path FROM {}'''.format(self.table_name) all_paths = self.cur.execute(query).fetchall() for rowid, path in all_paths: ext = pathlib.Path(path).suffix if ext == &quot;&quot;: continue update_ext_query = '''UPDATE {} SET fileExt=? WHERE rowid = &quot;{}&quot;'''.format(self.table_name, rowid) self.cur.execute(update_ext_query, (ext,)) self.conn.commit() def close_db(self): self.conn.close() </code></pre> <p>Any feedback is appreciated to get a more professional and standardized result. I find this a good way to learn, to view and discuss improvement on my own code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T23:10:01.807", "Id": "531821", "Score": "1", "body": "Why is this going to SQLite? What can it do that the filesystem itself can't?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T06:23:39.373", "Id": "531827", "Score": "0", "body": "I need to keep track of changes made to the files and there is an \"Imformation\" column as you can see from the creation of the table. This will be filled by hand to note important info regarding a few of the files. After this is done I need the parent ID for use with TKinter to recreate the filetree structure as it cant make the logic based on the path names itself. Doing this withinin the filesystem removes a lot of the educational angle I need for my project." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T09:00:34.457", "Id": "531834", "Score": "0", "body": "Why not create a .info file or something similar in the folders itself?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T09:54:31.290", "Id": "531837", "Score": "0", "body": "Because size. I only need the representation of the filestructure. Some of the files involved will be larger than 4gb. And the app will be shared" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T14:30:51.290", "Id": "532700", "Score": "0", "body": "Perhaps you should consider using [QFileSystemWatcher](https://doc.qt.io/archives/qtforpython-5.12/PySide2/QtCore/QFileSystemWatcher.html)" } ]
[ { "body": "<p>Avoid hard-coding file paths like this:</p>\n<pre><code>path = &quot;C:\\\\Users\\Skaft\\\\Documents\\\\GitHub&quot;\n</code></pre>\n<p>That path should be parametric.</p>\n<p>Variable names like <code>isFolder</code> should be <code>is_folder</code> (snake_case) via PEP8.</p>\n<p>Run-time assertions of the kind seen here:</p>\n<pre><code>assert Path(directory).is_dir()\n</code></pre>\n<p>can be <a href=\"https://stackoverflow.com/a/43668496/313768\">trivially disabled in Python</a> and are not appropriate for production code. Raise an exception instead.</p>\n<p>You say you have files of multiple GB. You've done the right thing here:</p>\n<pre><code> for chunk in iter(lambda: f.read(4096), b&quot;&quot;):\n my_hash.update(chunk)\n</code></pre>\n<p>and reimplemented it, incorrectly, here:</p>\n<pre><code> current_hash = hashlib.md5(readfile).hexdigest()\n</code></pre>\n<p>Consider factoring out a single file-hashing method that uses the chunked approach to go easy on your RAM.</p>\n<p>Do not use string interpolation to add query parameters:</p>\n<pre><code> query_path = '''SELECT rowid, Path FROM {} WHERE Path = &quot;{}&quot;'''.format(self.table_name, path)\n</code></pre>\n<p>That's the classic vector for injection attacks. Instead use <code>?</code> parameter substitution; <a href=\"https://docs.python.org/3.9/library/sqlite3.html\" rel=\"nofollow noreferrer\">read the documentation</a>.</p>\n<p>Don't use in-band error signalling, like here:</p>\n<pre><code>except PermissionError:\n current_hash = &quot;Could not hash due to permission&quot;\n return current_hash\n</code></pre>\n<p>If both a hash and your error message are a string, it's problematic for a caller to tell them apart. Just let the permission error exception fall through and catch it on the calling side.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T22:27:13.193", "Id": "532673", "Score": "1", "body": "Really appreciate your feedback! Ill work on it!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T15:53:57.340", "Id": "269777", "ParentId": "269565", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T22:32:10.687", "Id": "269565", "Score": "4", "Tags": [ "python", "performance", "object-oriented", "file-system", "sqlite" ], "Title": "Code to scan filesystem, store every path into sqlite and update only when something has changed" }
269565
<p>This code compares data from two spreadsheets generated from our clinic's software. The goal is to eliminate all the rows from the <code>PaymentsSheet</code> (our most recent transactions) that are duplicated on the <code>InvoicesSheet</code> (already uploaded transactions) to avoid duplicating info when we upload it to our account software, matching multiple columns to confirm that it is an actual duplicate.</p> <p>The sheets have a few thousand rows each and will only be getting bigger. Right now it's moving very, very slowly so I'm trying to make my code more efficient with very little success. Any suggestions you have to speed it up or other areas I can improve on would be greatly appreciated. I've included the whole piece just in case but the bottom section with the loops seems to be the big problem area.</p> <pre><code>Sub cleanInvoices() Application.EnableEvents = False ActiveSheet.DisplayPageBreaks = False Application.ScreenUpdating = False Dim PaymentsWorkbook As Workbook Set PaymentsWorkbook = ThisWorkbook Dim PaymentsSheet As Worksheet Set PaymentsSheet = PaymentsWorkbook.Sheets(4) Dim wb As Workbook For Each wb In Application.Workbooks wb.Save Next wb Dim fileLocation As Variant fileLocation = Application.GetOpenFilename(Title:=&quot;Please choose a Excel File to Open&quot;, MultiSelect:=False) If VarType(fileLocation) = vbBoolean Then MsgBox &quot;No file selected, Please rerun macro&quot;, vbExclamation, &quot;No File Selected!&quot; Exit Sub End If Dim InvoicesWorkbook As Workbook Set InvoicesWorkbook = Workbooks.Open(fileLocation) Dim InvoicesSheet As Worksheet Set InvoicesSheet = InvoicesWorkbook.Sheets(1) Dim InvoiceRow As Integer Dim PaymentsRow As Integer Dim lastCellinPaymentsRow As Integer Dim lastCellinInvoicesSheet As Integer Dim lastCellinPaymentsSheet As Integer Dim lastCellinInvoicesRow As Integer Dim numMatches As Integer 'clears blank rows on sheets (This part seems to move fairly quickly) PaymentsSheet.Activate lastCellinPaymentsSheet = Cells(Rows.Count, 1).End(xlUp).Row PaymentsSheet.Range(&quot;A2&quot;).Select PaymentsSheet.Range(Selection, Selection.End(xlDown)).Select lastCellinPaymentsRow = Selection.Rows.Count + 1 While (lastCellinPaymentsRow &lt;&gt; lastCellinPaymentsSheet) PaymentsSheet.Range(&quot;A&quot; &amp; lastCellinPaymentsRow + 1, &quot;G&quot; &amp; lastCellinPaymentsRow + 1) = PaymentsSheet.Range(&quot;A&quot; &amp; lastCellinPaymentsRow, &quot;G&quot; &amp; lastCellinPaymentsRow) PaymentsSheet.Range(&quot;A2&quot;).Select PaymentsSheet.Range(Selection, Selection.End(xlDown)).Select lastCellinPaymentsRow = Selection.Rows.Count + 1 Wend PaymentsSheet.Range(&quot;A2&quot;).Select PaymentsSheet.Range(Selection, Selection.End(xlDown)).Select lastCellinPaymentsRow = Selection.Rows.Count InvoicesSheet.Activate lastCellinInvoicesSheet = Cells(Rows.Count, 4).End(xlUp).Row InvoicesSheet.Range(&quot;D2&quot;).Select InvoicesSheet.Range(Selection, Selection.End(xlDown)).Select lastCellinInvoicesRow = Selection.Rows.Count + 1 While (lastCellinInvoicesRow &lt; lastCellinInvoicesSheet) InvoicesSheet.Range(&quot;B&quot; &amp; lastCellinInvoicesRow + 1, &quot;F&quot; &amp; lastCellinInvoicesRow + 1) = InvoicesSheet.Range(&quot;B&quot; &amp; lastCellinInvoicesRow, &quot;F&quot; &amp; lastCellinInvoicesRow) InvoicesSheet.Range(&quot;D2&quot;).Select InvoicesSheet.Range(Selection, Selection.End(xlDown)).Select lastCellinInvoicesRow = Selection.Rows.Count Wend 'compares sheets and deletes appropriate rows (This part is where it starts to run very slow and lock up) PaymentsSheet.Activate For p = 2 To lastCellinPaymentsRow For i = 2 To lastCellinInvoicesRow PaymentsSheet.Application.StatusBar = &quot;Completed &quot; &amp; p &amp; &quot; of &quot; &amp; lastCellinPaymentsRow If StrComp(PaymentsSheet.Cells(p, 1).Value, InvoicesSheet.Cells(i, 4).Value) = 0 Then If StrComp(PaymentsSheet.Cells(p, 2).Value, InvoicesSheet.Cells(i, 25).Value) = 0 Then If StrComp(PaymentsSheet.Cells(p, 4).Value, InvoicesSheet.Cells(i, 5).Value) = 0 Then If StrComp(PaymentsSheet.Cells(p, 7).Value, InvoicesSheet.Cells(i, 42).Value) = 0 Then numMatches = numMatches + 1 PaymentsSheet.Cells(p, 7).EntireRow.Delete End If End If End If End If Next i Next p PaymentsSheet.Application.ScreenUpdating = True End Sub </code></pre>
[]
[ { "body": "<p>One area of 'opportunity' for optimization is that the nested loops are not 'short-circuited' once a match is found. So, even though a matching payment/invoice pair have been found, the code continues to search through the remainder of the invoices every time. Also, the current code deletes a payment row as soon as it finds a match. Which means that the loop is going to operate past the rows of interest if any payment rows are deleted.</p>\n<p>The code modifications below focus on improving the last portion with the nested loops within a dedicated method. It makes use of <code>Dictionary</code> classes to help organize the comparisons and 'short circuiting' the interior loop. Also, rather than working through nested <code>If</code> statements with <code>StrComp</code> evaluations, the code sets up a single string comparison for each row.</p>\n<p>The nested loops span too many lines of code in both the original form and in this answer. The modified code will definitely not win any 'style' points. The nested loop code should be refactored to call helper functions and reduce the nesting in order to make it easier to read. That said, it was left in this form thinking that, at least initially, it may be easier to compare with the original code.</p>\n<pre><code>'Collate/organize the set of strings to compare\nPrivate Type TComparisons\n First As String\n Second As String\n Third As String\n Fourth As String\nEnd Type\n\nSub cleanInvoices()\n\n Dim originalScreenUpdateSetting As Boolean\n originalScreenUpdateSetting = Application.ScreenUpdating\n\n Application.EnableEvents = False\n ActiveSheet.DisplayPageBreaks = False\n Application.ScreenUpdating = False\n\n'Ensure that Application.EnableEvents is reset in case of an error \nOn Error GoTo ErrorExit\n \n &lt;original code - unchanged&gt;\n\n 'compares sheets and deletes appropriate rows (This part is where it starts to run very slow and lock up)\n PaymentsSheet.Activate\n \n EvaluateMatches PaymentsSheet, InvoicesSheet\n\nErrorExit:\n 'Note: the other flags modified at the to of the Subroutine are left as-is..intentional?\n PaymentsSheet.Application.ScreenUpdating = originalScreenUpdateSetting\n\nEnd Sub\n\nPrivate Sub EvaluateMatches(ByVal PaymentsSheet As Worksheet, ByVal InvoicesSheet As Worksheet)\n Dim toCompare As TComparisons\n \n 'use a Dictionary to cache the Invoice compare strings\n Dim invoices As Dictionary\n Set invoices = New Dictionary\n \n 'Store the rows to delete rather than actually deleting the rows within the nested loops\n Dim rowsToDelete As Collection\n Set rowsToDelete = New Collection\n \n 'Declaring a Dictionary to leverage the &quot;Exists&quot; member\n Dim invoiceRowsMatched As Dictionary\n Set invoiceRowsMatched = New Dictionary\n \n Dim pmtCompareString As String\n For p = 2 To lastCellinPaymentsRow\n With PaymentsSheet\n toCompare.First = .Cells(p, 1).Value\n toCompare.Second = .Cells(p, 2).Value\n toCompare.Third = .Cells(p, 4).Value\n toCompare.Fourth = .Cells(p, 7).Value\n End With\n\n pmtCompareString = MakeSingleCompareString(toCompare)\n\n For i = 2 To lastCellinInvoicesRow\n 'Load up the invoices Dictionary during the first iteration\n If p = 2 Then\n With InvoicesSheet\n toCompare.First = .Cells(i, 4).Value\n toCompare.Second = .Cells(i, 25).Value\n toCompare.Third = .Cells(i, 5).Value\n toCompare.Fourth = .Cells(i, 42).Value\n End With\n \n invoices.Add i, MakeSingleCompareString(toCompare)\n End If\n\n 'Only look at invoices that have not been matched\n If Not invoiceRowsMatched.Exists(i) Then \n If StrComp(pmtCompareString , invoices(i)) = 0 Then\n rowsToDelete.Add p\n invoiceRowsMatched.Add i, i\n 'Short ciruit the inner loop since a match has been found\n i = lastCellinInvoicesRow \n End If\n End If\n Next i\n Next p\n \n Dim rowToDelete As Variant\n Dim rowToDeleteOffset As Long\n rowToDeleteOffset = 0\n For Each rowToDelete In rowsToDelete\n PaymentsSheet.Cells(rowToDelete - rowToDeleteOffset , 1).EntireRow.Delete\n rowToDeleteOffset = rowToDeleteOffset + 1\n Next\nEnd Sub\n\nPrivate Function MakeSingleCompareString(toCompare As TComparisons) As String\n MakeSingleCompareString = Trim$(toCompare.First) &amp; &quot;|&quot; &amp; Trim$(toCompare.Second) &amp; &quot;|&quot; &amp; Trim$(toCompare.Third) &amp; &quot;|&quot; &amp; Trim$(toCompare.Fourth)\nEnd Function\n\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T20:51:29.150", "Id": "531988", "Score": "0", "body": "I think the way the rows are deleted here is not correct. The problem is that deleting a row will change the row indices. You either have to delete them in descending order, which leaves the row induces of the still to be deleted rows intact, or delete them all at once." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T21:51:51.123", "Id": "531999", "Score": "0", "body": "@M.Doerner is correct that deleting the rows as originally posted is a bug. The intent was to make finding the rows to delete 'one responsibility' and the actual deletion of the rows a `different responsibility`. So, the deletion loop has been modified to ensure rows are deleted in descending order. The original code contained a bug that would skip a matching payment row if it directly followed a deleted payment row." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T06:07:07.650", "Id": "269568", "ParentId": "269566", "Score": "2" } }, { "body": "<p>You asked primarily for some help improving the performance of your code. So I will start with that. Then, I will go on with a few things that can help to generally improve the code.</p>\n<h1>Performance</h1>\n<h2>Context switching</h2>\n<p>One if the primary things slowing down code looping over cell ranges is the constant context switching between the VBA and Excel. It is usually preferable to read the entire relevant data into memory, then iterate over that and finally write data in one operation back to the file. In your case, the last part would not really consist of writing data, but deleting rows.</p>\n<p>You can read the contents of a Range into a 2d Variant array using the Value member. The indexing of the array works the same as with <code>Cells</code> (or actually the implicit call to <code>Item</code>).</p>\n<p>So, to get all values from a sheet <code>wks</code> into a variable <code>data</code> declared as <code>Variant</code>, you can simply use <code>data = wks.UsedRange.Value</code>.</p>\n<p>Reading in both the payment sheet and invoice sheet this way, allows you to iterate over both without switching back to Excel for every value.</p>\n<h2>Reference key lookups</h2>\n<p>To determine whether a corresponding record exists in the invoice sheet, your code iterates over the entire invoice sheet each time. If there are only a few hundred items in there, that can really be ok. However, should there be more, you might want to generate a joined key by concatenation the strings with a distinct separator and store them in a dictionary for fast existence checks.</p>\n<h1>Correctness</h1>\n<h2>Deleting in one go</h2>\n<p>If I see this correctly, your code actually has a typical bug you might not have realized it has. When you delete a row, you skip the next one.</p>\n<p>Let me explain the issue. When you delete a row, all row indices of the rows below are adjusted by subtracting one. This means that the row index of the one after the just deleted row is then the same as the one of the deleted row. Your code then checks the row with the next higher row index, which is the one two after the deleted one.</p>\n<p>To avoid this, you can in principle iterate in descending order, or just delete in descending order, if you follow the advice to read out all data and determine the rows to delete from there. However, I heard somewhere that this approach sometimes has issues, too, I think with filters.</p>\n<p>One way to delete all the rows at once is to use the <code>Application.Union</code> method to construct a range containing all rows to delete and then to call <code>Delete</code> on it.</p>\n<h2>Type for row numbers</h2>\n<p>In your code, the variables holding row numbers are of type <code>Integer</code>. That is a bad idea. In VBA the largest <code>Integer</code> is 32767, but a sheet in modern Excel can have millions of rows. You should really use <code>Long</code> instead.</p>\n<h1>General</h1>\n<h2>Single responsibility principle</h2>\n<p>This principle of good software design says that a unit of work, e.g. a procedure, should be responsible for just one thing at once. More practically, it should only have to change for a single reason.</p>\n<p>Your procedure has a lot of responsibilities: it saves all workbooks; it asks the user for the invoice filename; it gets the sheets; it removes blank rows ; it removes payment rows found in the invoice sheet.</p>\n<p>All of these responsibilities could be their own procedure or function taking appropriate parameters as needed. Then, these could be called from a coordinating procedure.</p>\n<p>The result of such a separation is that the code is much simpler to read since the coordinating procedure reads like a table of contents and individual procedures are more focused. Moreover, with the separation, the code is easier to debug, because it is clear which part dies what.</p>\n<h2>Selecting and activating</h2>\n<p>It is next to never necessary to activate a sheet or select a range in VBA code. Instead, the references should simply be saved in correspondingly typed variables. This has the neet side-effect that one does not mess with the users selection.</p>\n<h1>Advanced</h1>\n<p>As an advanced suggestion, I would like to present a way to guarantee that application settings like <code>ScreenUpdating</code> are reset at the end of a procedure, no matter what.</p>\n<p>Since VBA has deterministic object lifetimes you can follow the RAII (resource allocation is instantiation) principle known from C++. This encapsulates resource allocation or, in extension, global settings changes in objects that get destroyed when they fall out of scope, e.g. at the end of a procedure.</p>\n<p>Let my explain how that works for the <code>ScreenUpdating</code> settings. You define a new class module, say <code>NoScreenUpdatingContainer</code> and insert the following code.</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Option Explicit\n\nPrivate Sub initialState as Boolean\n\nPrivate Sub Class_Initiate() \n initialState = Application.ScreenUpdating\n Application.ScreenUpdating = False\nEnd Sub\n\nPrivate Sub Class_Terminate() \n Application.ScreenUpdating = initialState\nEnd Sub\n</code></pre>\n<p>When you bind an instance of this class to a variable, it will deactivate screen updating. Once the variable goes out of scope, the initial state will be restored.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T11:48:09.613", "Id": "532038", "Score": "0", "body": "Do you have any idea _why_ context switching is slow? Why it's not just a matter of reading an array of values from Excel into VBA?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T21:46:44.727", "Id": "269624", "ParentId": "269566", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T03:06:33.250", "Id": "269566", "Score": "2", "Tags": [ "performance", "vba", "excel" ], "Title": "Comparing Multiple Columns to Remove Duplicates" }
269566
<p>For my project I have a sorted array of objects of timestamps (in milliseconds) and I need two functions. One function should find the closest time that doesn't go <em>over</em> a specific amount, and the other function should find the closest time that doesn't go <em>under</em> a specific amount. Also, they should return the indices of values.</p> <p>For example, if I have this data:</p> <pre><code>let a = [ { t: 50 }, { t: 100 }, { t: 400 }, { t: 800 }, { t: 850 } ]; </code></pre> <p>Then <code>closestUnder(arr, 375)</code> should return the index for <code>{ t: 100 }</code>, which would be <code>1</code></p> <p>And <code>closestOver(arr, 450)</code> would return the index for <code>{ t: 800 }</code>, which is <code>3</code></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 binarySearchNearest(a, value) { if (value &lt; a[0].t) { return 0; } if (value &gt; a[a.length - 1].t) { return a.length - 1; } let lo = 0; let hi = a.length - 1; while (lo &lt;= hi) { let mid = Math.floor((hi + lo) / 2); if (value &lt; a[mid].t) { hi = mid - 1; } else if (value &gt; a[mid].t) { lo = mid + 1; } else { return mid; } } return a[lo].t - value &lt; value - a[hi].t ? lo : hi; } function closestOver(arr, value) { let i = binarySearchNearest(arr, value); let entryIndex = arr[i].t &lt; value &amp;&amp; i + 1 &lt; arr.length ? i + 1 : i; return arr[entryIndex].t &gt;= value ? entryIndex : -1; } function closestUnder(arr, value) { let i = binarySearchNearest(arr, value); let entryIndex = arr[i].t &gt; value &amp;&amp; i - 1 &gt;= 0 ? i - 1 : i; return arr[entryIndex].t &lt;= value ? entryIndex : -1; } let a = [ { t: 50 }, { t: 100 }, { t: 400 }, { t: 800 }, { t: 850 } ]; console.log(closestUnder(a, 375)); console.log(closestOver(a, 450));</code></pre> </div> </div> </p>
[]
[ { "body": "<h3>Simplify the logic</h3>\n<p>The simplest form of binary search function returns the index where the target value would be inserted to keep the list sorted. This would imply that:</p>\n<ul>\n<li>When an exact match exists in the list, its index is returned</li>\n<li>Otherwise the index of the next higher element is returned</li>\n<li>If there is no next higher element, the length of the list is returned</li>\n</ul>\n<p>This last point is the most important caveat to watch out for:\nbefore using the returned index on the list, you must check that it's less than the length.</p>\n<p>The implementation of this more classic form is simpler than <code>binarySearchNearest</code>.</p>\n<pre><code>function binarySearch(arr, value) {\n let lo = 0;\n let hi = arr.length - 1;\n\n while (lo &lt;= hi) {\n const mid = Math.floor((hi + lo) / 2);\n\n if (value &lt; arr[mid].t) {\n hi = mid - 1;\n } else if (value &gt; arr[mid].t) {\n lo = mid + 1;\n } else {\n return mid;\n }\n }\n\n return lo;\n}\n</code></pre>\n<p>Based on this simpler logic, the other functions become simpler too:</p>\n<pre><code>function closestOver(arr, value) {\n const index = binarySearch(arr, value);\n return index == arr.length ? -1 : index;\n}\n\nfunction closestUnder(arr, value) {\n const index = binarySearch(arr, value);\n return index &lt; arr.length &amp;&amp; arr[index].t == value ? index : index - 1;\n}\n</code></pre>\n<p>In conclusion, it's good to work with the simplest possible building blocks.\n<code>binarySearchNearest</code> has extra logic to make the result &quot;nearest&quot;, which makes it a bit harder to understand, and it also increased the mental burden in its callers.</p>\n<h3>Generalize the sorting order</h3>\n<p>Currently there are multiple places in the code that refer to the <code>.t</code> property of the elements, used as the <em>search key</em>. This makes the otherwise generic binary search logic only applicable for the specific use case of items that have a numeric <code>.t</code> property. Also, if you ever need to change that property (for example to something more descriptive), then you'll have to change it on many lines.</p>\n<p>You could generalize this using a <code>key</code> function that maps an item to the value to use to determine sorting order, and passing that function as a parameter to the search algorithm:</p>\n<pre><code>function binarySearch(arr, target, keyFunction) {\n let lo = 0;\n let hi = arr.length - 1;\n\n while (lo &lt;= hi) {\n const mid = lo + Math.floor((hi - lo) / 2);\n\n const value = keyFunction(arr[mid]);\n if (target &lt; value) {\n hi = mid - 1;\n } else if (target &gt; value) {\n lo = mid + 1;\n } else {\n return mid;\n }\n }\n\n return lo;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T08:22:26.530", "Id": "531832", "Score": "1", "body": "Ah, this makes complete sense! And it seems to work perfectly as well. Thanks a bunch!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T08:09:26.203", "Id": "269571", "ParentId": "269567", "Score": "1" } } ]
{ "AcceptedAnswerId": "269571", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T04:30:11.150", "Id": "269567", "Score": "1", "Tags": [ "javascript", "algorithm", "array", "binary-search" ], "Title": "Finding the closest values in a sorted list that don't go under/over" }
269567
<p>I've been trying this <a href="https://www.spoj.com/problems/FUSC/" rel="nofollow noreferrer">question</a> from SPOJ, which asks for the user to enter a number <code>n</code>, and they will receive a maximum <strong>fusc</strong> value that lies in between 0 to <code>n</code>. The conditions for the function are:</p> <ul> <li>F(0) and F(1) is 0 and 1 respectively</li> <li>For any even number, the value is F(n) = F(n/2)</li> <li>For any odd number, the value is F(n) = F(n/2) + F(n/2 + 1)</li> </ul> <p>This is my take on the problem:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;algorithm&gt; #include &lt;vector&gt; #include &lt;stdio.h&gt; int fusc(int num, std::vector&lt;int&gt; reg) { if(num==0) return 0; if(num==1) return 1; if(num%2==0) return reg[num/2]; return (reg[num/2] + reg[num/2 + 1]); } int main() { int n; scanf(&quot;%d&quot;, &amp;n); std::vector&lt;int&gt; reg(n+1); for(int i=0;i&lt;=n; i++) reg[i] = fusc(i, reg); auto it=std::max_element(std::begin(reg), std::end(reg)); printf(&quot;%d\n&quot;, *it); } </code></pre> <p>I am not sure about why it is taking a lot of time. It would be great if the poor practices in the code would be highlighted.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T13:47:33.203", "Id": "531941", "Score": "0", "body": "Aside: when you write \"For any odd number, the value is F(n) = F(n/2) + F(n/2 + 1)\", I didn't realize at first that you were using integer division. But now I know. And now anyone else will as well." } ]
[ { "body": "<h1>Don't mix C and C++ code</h1>\n<p>Your code is a mix of C and C++. While you can use functions from C's standard library in C++ code, I recommend you avoid it and write as much as possible using just functions from C++'s standard library. In particular:</p>\n<pre><code>#include &lt;iostream&gt;\n...\nint n;\nstd::cin &gt;&gt; n;\n...\nstd::cout &lt;&lt; *it &lt;&lt; '\\n';\n</code></pre>\n<h1>Use <code>std::uint64_t</code> for <code>n</code></h1>\n<p>According to the problem statement, <span class=\"math-container\">\\$0 &lt;= n &lt;= 10^{15}\\$</span>. But an <code>int</code>, which is usually only 32 bits, can only hold values up to a little over <span class=\"math-container\">\\$10^9\\$</span>. So you have to ensure you pack an integer type that is large enough to hold the maximum possible input value. Also, since <code>n</code> will never be negative, use an unsigned type. The standard library provides various fixed-width <a href=\"https://en.cppreference.com/w/cpp/types/integer\" rel=\"noreferrer\">integer types</a>, the right one here is <code>std::uint64_t</code>.</p>\n<p>While the maximum fusc value of <code>n</code> doesn't grow very fast, I would also use a <code>std::vector&lt;std::uint64_t&gt;</code> to store the fusc values, unless you can prove that the maximum fusc value of <span class=\"math-container\">\\$10^{15}\\$</span> is less than <span class=\"math-container\">\\$2^{31}\\$</span>.</p>\n<h1>Pass large objects by reference where appropriate</h1>\n<p>When you call <code>fusc()</code>, you are passing it the vector with results so far by value. That means a complete copy is made. Since you do that <code>n</code> times, that is very costly. Pass it by reference instead::</p>\n<pre><code>int fusc(int num, std::vector&lt;std::uint64_t&gt; &amp;reg) {\n ...\n}\n</code></pre>\n<h1>Keep track of the maximum while building <code>reg</code></h1>\n<p>You are first building the vector <code>reg</code> by adding elements to it, and then you call <code>std::max_element()</code> which goes over the whole vector again. It is faster to just keep track of the maximum value while you are building the vector <code>reg</code>:</p>\n<pre><code>std::uint64_t max_fusc = 0;\n\nfor (uint64_t i = 0; i &lt;= n; ++i) {\n reg[i] = fusc(i, reg);\n max_fusc = std::max(max_fusc, reg[i]);\n}\n\nstd::cout &lt;&lt; max_fusc &lt;&lt; '\\n';\n</code></pre>\n<h1>Use <code>reserve()</code> and <code>push_back()</code></h1>\n<p>If you declare a vector of a given size like so:</p>\n<pre><code>std::vector&lt;int&gt; reg(n+1);\n</code></pre>\n<p>It will actually cause all elements of the vector to be filled with zeroes. But you are going to overwrite them later anyway, so this is wasting some time. You can avoid it by not specifying the size up front, but instead using the <a href=\"https://en.cppreference.com/w/cpp/container/vector/reserve\" rel=\"noreferrer\"><code>reserve()</code></a> method to let the vector allocate all the memory you are going to need for it, and then use <code>push_back()</code> to add the values you calculated:</p>\n<pre><code>std::vector&lt;std::uint64_t&gt; reg;\nreg.reserve(n + 1);\nreg.push_back(0);\nreg.push_back(1);\nstd::uint64_t max_fusc = n ? 1 : 0;\n\nfor(std::uint64_t i = 2; i &lt;= n; ++i) {\n reg.push_back(i % 2 == 0 ? reg[i / 2] : reg[i / 2] + reg[i / 2 + 1]);\n max_fusc = std::max(max_fusc, reg.back());\n}\n</code></pre>\n<h1>Other optimizations</h1>\n<p>I did some other optimizations in the code above. In your <code>fusc()</code>, you were checking if <code>num</code> was 0 or 1. This is only necessary for the first two calls to <code>fusc()</code>, afterwards it is redundant. You can just add the first two elements to <code>reg</code> manually, then you don't have to deal with these special cases anymore. With this, <code>fusc()</code> is so simple that I just removed it.</p>\n<p>The initialization of <code>max_fusc</code> is also done such that your program will still give the correct output if <code>n</code> is 0 or 1.</p>\n<p>You can probably do more optimizations as well, by using knowledge about how the <a href=\"https://oeis.org/A002487\" rel=\"noreferrer\">fusc sequence</a> progresses. There is already some information on the <a href=\"https://www.spoj.com/problems/FUSC/\" rel=\"noreferrer\">SPOJ page</a> you mentioned: if you split the sequence in to groups of size 1, 2, 4, 8 and so on, you will notice some structure: each group is a mirror of itself, and the maximum of a group is always a <a href=\"https://en.wikipedia.org/wiki/Fibonacci_number\" rel=\"noreferrer\">Fibonacci number</a>. This means that for half the possible values of <span class=\"math-container\">\\$n\\$</span>, you can just get away with calculating the <span class=\"math-container\">\\$2+\\left\\lfloor\\log_2{n}\\right\\rfloor\\$</span>th Fibonacci number, and for the other half of the possible values of <span class=\"math-container\">\\$n\\$</span> you at least know that that Fibonacci number is the upper bound, and the previous Fibonacci number is a lower bound.</p>\n<p>Also look at the Wikipedia page about the <a href=\"https://en.wikipedia.org/wiki/Calkin%E2%80%93Wilf_tree\" rel=\"noreferrer\">Calkin-Wilf tree</a> for an interesting read of where the fusc sequence pops up.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T09:57:44.313", "Id": "531838", "Score": "0", "body": "Competitive programmer guys use scanf/printf because they believe cin/cout is slow. Better to mention std::ios_base::sync_with_stdio(false)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T11:05:39.767", "Id": "531843", "Score": "4", "body": "@frozenca It shouldn't matter here, it's just reading and printing a single number. It might be different if I/O is a large part of the work that has to be done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T13:17:19.303", "Id": "531852", "Score": "0", "body": "There's so much more to exploit; the first occurrence of a Fibonacci number is at an index which is a [Jacobsthal number](https://oeis.org/A001045), `fucs(2 * n)` is always smaller than `fucs(2 * n - 1)` and `fucs(2 * n + 1)`. I suspect there must be some way to use a binary search to get the answer, but I'm already nerdsniped enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T18:07:45.597", "Id": "531878", "Score": "0", "body": "@G.Sliepen not sure what's happening when I submit the answer online, but it is throwing a runtime error (SIGABRT). What do you suspect could be the issue? It runs fine locally, by the way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T19:36:18.193", "Id": "531885", "Score": "0", "body": "@AshvithShetty What values of `n` did you try? It might be that when you submit it, they try a value of `n` such that your code allocates too much memory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T19:41:50.110", "Id": "531886", "Score": "0", "body": "@G.Sliepen I've tried with basic ones like 10, or 1500. I've even tried replacing with `long long`, and I have the same issue. Maybe it has something to do with the machine the tests run on? It is an Intel G860, while mine is an Intel i5 8265u." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T19:47:01.890", "Id": "531887", "Score": "0", "body": "I doubt it matters. Again, the problem statement says `n` can be up to 10^15, and just naively allocating a vector of 10^15 elements will surely use more memory than is available." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T13:13:41.953", "Id": "532043", "Score": "1", "body": "@G.Sliepen I doubt using vectors to calculate each and every value would be a good idea. Instead, I believe that maybe using the arithmetic progression would be beneficial. But I am not sure how we can implement that - although I can see that the next series progresses with adding the two numbers, and placing the product between them in the new array. For example, if we start with (1, 2), then add 1+2, which gives 3. Now place the new sum before 2, and mirror the pattern, but remove 1 - we get (1, 3, 2 | 3). The next pattern will be (1, 4, 3, 5, 2 | 5, 3, 4)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T19:07:13.183", "Id": "532093", "Score": "0", "body": "@AshvithShetty That's good thinking. It might also be interesting at looking at the [ranking of accepted solutions](https://www.spoj.com/ranks/FUSC/). There you can see in what amount of time and memory usage people have been able to solve the problem. It strongly hints that there's an O(1) or an O(log `n`) solution." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T09:38:56.073", "Id": "269573", "ParentId": "269569", "Score": "6" } }, { "body": "<h1>Don't ignore crucial return values</h1>\n<p>G. Sliepen has covered nearly all the things I was going to say (in particular, passing the array by value is your key performance problem).</p>\n<p>The only thing I have to add to that answer is in regard to this line:</p>\n<blockquote>\n<pre><code> scanf(&quot;%d&quot;, &amp;n);\n</code></pre>\n</blockquote>\n<p>If we ignore the return value from <code>std::scanf()</code>, we have no idea whether <code>n</code> was successfully assigned to. If there's any conversion failure, we will be operating on an <em>uninitialized value</em>, rather than reporting the error to the user.</p>\n<p>The equivalent when using C++ I/O is testing the state of <code>std::cin</code> after using the <code>&gt;&gt;</code> streaming operator - again, without that test, the program is faulty.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T19:17:38.263", "Id": "269590", "ParentId": "269569", "Score": "3" } }, { "body": "<blockquote>\n<p>I am not sure about why it is taking a lot of time</p>\n</blockquote>\n<p>Well, this pops out: <code>int fusc(int num, std::vector&lt;int&gt; reg)</code></p>\n<p>Why are you passing <code>reg</code> <strong>by value</strong>? You are copying the entire vector each time you call the function, and then throwing away the local copy after each function call. This causes memory allocation and deallocation, which is slow.</p>\n<p>It is very unusual to pass non-primitive things by value in C++, so this should stand out as an immediate red flag when you look over the code. We expect to see <code>const std::vector&lt;int&gt;&amp; reg</code> instead.</p>\n<p>If you're new to C++ and used to languages with reference semantics (where &quot;objects&quot; are actually pointers), this might go unnoticed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T14:35:18.720", "Id": "269640", "ParentId": "269569", "Score": "0" } } ]
{ "AcceptedAnswerId": "269573", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T06:37:45.023", "Id": "269569", "Score": "3", "Tags": [ "c++", "time-limit-exceeded", "dynamic-programming" ], "Title": "Find maximum value of recursively-defined \"fusc\" function" }
269569
<p>I wanted to have a factory-method, but without the <code>if</code> statements that are often seen in examples of this pattern. So I came up with this, and would like to know: is this a right approach, should there be any impovements?</p> <p>some things I considered:</p> <ul> <li>It is using Enum because that makes it possible to iterate or list the possible options.</li> <li>using <code>getattr</code> to call the class dynamically</li> </ul> <pre class="lang-py prettyprint-override"><code>class Red: name = &quot;red&quot; class Blue: name = &quot;blue&quot; class Colors(Enum): red = Red blue = Blue @classmethod def factory(cls, name): if any(e.name == name for e in cls): target = cls[name] else: #default target = cls.blue return getattr(sys.modules[__name__], target.value.__name__)() print(Colors.factory(&quot;red&quot;)) print(Colors.factory(&quot;red&quot;)) print(Colors.factory(&quot;red2&quot;)) print(list(Colors)) </code></pre> <pre><code>### result &lt;__main__.Red object at 0x7fd7cc2e2250&gt; &lt;__main__.Red object at 0x7fd7cc2e2430&gt; &lt;__main__.Blue object at 0x7fd7cc30c700&gt; [&lt;Colors.red: &lt;class '__main__.Red'&gt;&gt;, &lt;Colors.blue: &lt;class '__main__.Blue'&gt;&gt;] </code></pre>
[]
[ { "body": "<h3>Using enums in Python</h3>\n<p>The posted code doesn't take advantage of most of the benefits provides by enums in Python.</p>\n<p>The typical use case of enums is to make decisions depending on a given enum member.\nFor example,\nin the context of the posted code,\nI can imagine a <code>create_foo</code> method which takes as parameter a value of <code>Color</code> type that is an enum,\nand callers would use <code>create_foo(Color.RED)</code> to create a foo object with one of the supported colors.</p>\n<p>Another common use case would be iterating over an enum type,\nfor example to display the available choices to users.</p>\n<p>In the posted code, only the iteration capability is used, and only internally.\nFor this simpler purpose, a simpler and better option would be using a dictionary:</p>\n<pre><code>SUPPORTED_COLORS = {\n &quot;red&quot;: Red,\n &quot;blue&quot;: Blue,\n}\n\ndef create_color(name):\n if name in SUPPORTED_COLORS:\n return SUPPORTED_COLORS[name]()\n\n return Blue()\n</code></pre>\n<hr />\n<p>Since the parameter of the factory method is a string,\nit doesn't help to find the accepted values.\nI have to read the implementation to know, which violates good encapsulation.</p>\n<p>You may argue that taking a string parameter makes it possible to accept unsupported values and fall back to a default. I think that without a specific use case to justify this need, it's likely to be more harmful than beneficial to bypass type safety this way.</p>\n<p>I find it unexpected to have a factory method as part of an enum type.\nI would not look for a factory method there.\nWhen I see an enum, I expect to use its members, or iterate over it.</p>\n<hr />\n<p>Based on the documentation of <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\">enum support</a>,\n<em>enum members</em> should be named with <code>UPPER_CASE</code>, for example:</p>\n<pre><code>class Color(Enum):\n RED = auto\n BLUE = auto\n</code></pre>\n<p>Based on the examples on the page, it seems that singular noun is recommended as the name of the enum (<code>Color</code> rather than <code>Colors</code>).</p>\n<h3>Implementing the factory method pattern in Python</h3>\n<blockquote>\n<p>I wanted to have a factory-method, but without the if statements that are often seen in examples of this pattern.</p>\n</blockquote>\n<p>Why is that, really? What is the real problem you're trying to solve?\nWhen you try to do something that is different from what is &quot;often seen&quot;,\nI suggest to take a step back,\nand ask yourself if you really have a good reason to not follow a well established pattern.\nChances are that you are missing something, or you don't have a real need.</p>\n<p>Also keep in mind that &quot;often seen&quot; patterns are easier for everyone to understand, <em>because they are often seen</em>.\nWhen you take a different approach,\nthere is a high risk that readers will be surprised by it.\nSo it had better have a good justification to exist, and be rock solid.</p>\n<p>There is nothing fundamentally wrong with if statements in the factory method in general. On the other hand, I can imagine situations where a complex if-else chain could be replaced with something better, but I would have to be more specific about the problem to justify the need for improvement.</p>\n<p>I was surprised by the posted code, at multiple points.\nWhen I read the question title &quot;Factory pattern using enum&quot;, I expected to see:</p>\n<ul>\n<li>A factory method that takes an enum parameter</li>\n<li>The factory method decides what to return based on the enum parameter</li>\n</ul>\n<p>Reading on, when I saw &quot;but without the <code>if</code> statements&quot;, I expected a dictionary mapping enum members to some value or creator function, replacing if-else chain with dictionary lookup.</p>\n<hr />\n<p>I think <a href=\"https://realpython.com/factory-method-python/\" rel=\"noreferrer\">this tutorial on realpython.com</a> explains very nicely how to implement this pattern well in Python.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T16:12:58.367", "Id": "531870", "Score": "0", "body": "\"I find it unexpected to have a factory method as part of an enum type.\" So do I , that is why I posted the code here. But the reasoning was simple: first I used a regular class, but that would require some extra methods to make it iterable - Enum is a quick way to solve this, and works well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T11:50:27.537", "Id": "269580", "ParentId": "269572", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T09:04:16.237", "Id": "269572", "Score": "2", "Tags": [ "python", "factory-method" ], "Title": "Factory pattern using enum" }
269572
<p>My game is a grid in which you have to change cells color by clicking on them. When I generate a grid I have to know all the possible combinations of blue and white cells my game allows, to know the difficulty level of the grid.</p> <p>Each time I create a scenario I have to update an important parameter which is groups of white cells that touch each other.</p> <p>I use 3 tables in my functions :</p> <p>The first contains positions of all the white cells</p> <pre><code>// example for a 3,3 grid : [y0 =&gt; [x0 =&gt; x0, x1 =&gt; x1], y1 =&gt; [x0 =&gt; x0], y2 =&gt; [x1 =&gt; x1, x2 =&gt; x2]] </code></pre> <p>The second one contains positions of the grouped white cells that touch each other</p> <pre><code>// same example [ [[y0,x0],[y0,x1],[y1,x0]], [[y2,x1],[y2,x2]] ] </code></pre> <p>The third one is only one group of the second table</p> <pre><code>// same example [[y0,x0],[y0,x1],[y1,x0]] </code></pre> <p>I created several function :</p> <p>This one needs only the first table and return the second table. I use it to initialize the parameter when I create a grid.</p> <pre><code>function rec($p, $po, $t){ // $p table containing white cases : [y0 =&gt; [x0 =&gt; x0, x1 =&gt; x1,..], y1 =&gt; [x0 =&gt; x0, x1 =&gt; x1],..] // $po position of the first case : [y,x] // $t table to record groups $u = []; if(isset($p[$po[0]][$po[1]+1]) &amp;&amp; !in_array([$po[0],$po[1]+1], $t)){ $u[] = [$po[0],$po[1]+1]; $t = array_merge($t, [[$po[0],$po[1]+1]]); } if(isset($p[$po[0]][$po[1]-1]) &amp;&amp; !in_array([$po[0],$po[1]-1], $t)){ $u[] = [$po[0],$po[1]-1]; $t = array_merge($t, [[$po[0],$po[1]-1]]); } if(isset($p[$po[0]-1][$po[1]]) &amp;&amp; !in_array([$po[0]-1,$po[1]], $t)){ $u[] = [$po[0]-1,$po[1]]; $t = array_merge($t, [[$po[0]-1,$po[1]]]); } if(isset($p[$po[0]+1][$po[1]]) &amp;&amp; !in_array([$po[0]+1,$po[1]], $t)){ $u[] = [$po[0]+1,$po[1]]; $t = array_merge($t, [[$po[0]+1,$po[1]]]); } if(count($u) &gt; 0){ foreach($u as $v){ $t = rec($p, $v, $t); } return $t; } else{ return $t; } } $p = [ // an example 0 =&gt; [0 =&gt; 0, 2 =&gt; 2, 4 =&gt; 4], 1 =&gt; [0 =&gt; 0, 4 =&gt; 4], 2 =&gt; [0 =&gt; 0, 2 =&gt; 2, 4 =&gt; 4], 3 =&gt; [0 =&gt; 0, 4 =&gt; 4], 4 =&gt; [0 =&gt; 0, 1 =&gt; 1, 2 =&gt; 2, 3 =&gt; 3, 4 =&gt; 4] ]; $u = [[]]; $z = []; $c = 0; foreach($p as $a =&gt; $n){ foreach($n as $b){ //var_dump($u); if(!in_array([$a,$b], $z)){ $o = []; $o = rec($p, [$a,$b], [[$a,$b]]); $u[$c++] = $o; $z = array_merge($z, $o); } } } var_dump($u); </code></pre> <p>You can test it here : <a href="http://jdoodle.com/ia/iTi" rel="nofollow noreferrer">jdoodle.com/ia/iTi</a></p> <p>This function needs only the second table, it updates a group of white cells that I know one of it cells has become blue. I don't use it because it is too slow.</p> <pre><code>function updateGroup($group){ // $gp is only one group a white cells : [[y1,x1],[y1,x2],[y2,x1],..] $groupTemp = $group; $allNewGroups = []; do{ foreach($group as $x =&gt; $cellSearch){ unset($group[$x]); unset($groupTemp[$x]); $cellSearchTab = [$cellSearch]; $newGroup = []; $check = false; $index = 0; do{ $cellTouchTab = []; foreach($cellSearchTab as $cell){ if($index == 0){ $newGroup[] = $cell; } foreach($groupTemp as $k =&gt; $cellTouch){ if((abs($cell[0]-$cellTouch[0]) == 1 &amp;&amp; $p[1]-$cellTouch[1] == 0) || (abs($cell[1]-$cellTouch[1]) == 1 &amp;&amp; $p[0]-$cellTouch[0] == 0)){ unset($groupTemp[$k]); unset($group[$k]); $cellTouchTab[] = $cellTouch; } } } if(!empty($t)){ $newGroup = array_merge($newGroup, $cellTouchTab); $cellSearchTab = $cellTouchTab; if(empty($groupTemp)){ $check = true; } } else{ $check = true; } $index++; } while($check == false); $allNewGroups[] = $newGroup; break; } } while(!empty($group)); return $allNewGroups; } </code></pre> <p>To test it : <a href="http://jdoodle.com/ia/iU2" rel="nofollow noreferrer">jdoodle.com/ia/iU2</a></p> <p>This function is the one I use because it is the fastest, it needs the second table and the position of cell which has become blue, it update all groups of white cells :</p> <pre><code>function rec5($allGroups, $cellDel){ // $allGroups is the table containing all the groups of white cells that touch each other [[y1,x1],[y1,x2],[y2,x1],..] // $cellDel is the position of the cell that has become blue [y,x] $allGroupsTemp = $allGroups; foreach($allGroupsTemp as $k2 =&gt; $group){ $indexCellDel = array_search([$cellDel[0],$cellDel[1]], $group); if(is_int($indexCellDel)){ unset($allGroupsTemp[$k2][$indexCellDel]); if(!empty($allGroupsTemp[$k2])){ $newGroups = []; foreach($allGroupsTemp[$k2] as $cell){ $check = false; $cellsTouch = []; foreach($newGroups as $k3 =&gt; $newGrp){ if( in_array([$cell[0]-1,$cell[1]], $newGrp) || in_array([$cell[0],$cell[1]-1], $newGrp) || in_array([$cell[0]+1,$cell[1]], $newGrp) || in_array([$cell[0],$cell[1]+1], $newGrp)){ $cellsTouch[] = $k3; $check = true; } } if(!$check){ $newGroups[] = [$cell]; } else{ if(count($cellsTouch) == 1){ $newGroups[$cellsTouch[0]][] = $cell; } else{ $d = []; foreach($cellsTouch as $bb){ $d = array_merge($d, $newGroups[$bb]); unset($newGroups[$bb]); } $d = array_merge([$cell], $d); $newGroups[] = $d; } } } if(count($newGroups) &gt; 1){ unset($allGroupsTemp[$k2]); foreach($newGroups as $newGrp){ $allGroupsTemp[] = $newGrp; } } } else{ unset($allGroupsTemp[$k2]); } } } return $allGroupsTemp; } </code></pre> <p>To test it : <a href="http://jdoodle.com/ia/iU3" rel="nofollow noreferrer">jdoodle.com/ia/iU3</a></p> <p><strong>According to the size of the grid, my game allows a lot of combinations of blue and white cells (for a 5x5 grid I can have tens of thousands), and my problem is that all the functions I created are too slow, do you think I can make my functions faster?</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T09:44:40.353", "Id": "531916", "Score": "1", "body": "I can see you tried your best, but I miss a clear explanation of what this code is used for. Is this some sort of game? *What problem does this code solve?* I cannot work on code without having any idea what the code is intended for. If you are intentionally obfuscating the purpose of this code, then this code is not suitable for review. See also: [Asking Questions](https://codereview.meta.stackexchange.com/questions/2436/how-to-get-the-best-value-out-of-code-review-asking-questions)" } ]
[ { "body": "<p>OK, I tried my hand at your first function. I haven't got time for the others. First the code, then I'll try to explain it:</p>\n<pre><code>$gameSize = 5;\n$gameGrid = [[1, 0, 1, 0, 1],\n [1, 0, 0, 0, 1],\n [1, 0, 1, 0, 1],\n [1, 0, 0, 0, 1],\n [1, 1, 1, 1, 1]];\n\nfunction touchingCells(&amp;$grid, $y, $x, $cells = [])\n{\n $grid[$y][$x] = 0;\n $cells[] = ['y' =&gt; $y, 'x' =&gt; $x];\n foreach ([-1, 0, 1] as $offsetY) {\n $scanY = $y + $offsetY;\n foreach ([-1, 0, 1] as $offsetX) {\n $scanX = $x + $offsetX;\n if ($grid[$scanY][$scanX] ?? 0 &gt; 0) {\n $cells = touchingCells($grid, $scanY, $scanX, $cells);\n }\n }\n }\n return $cells;\n}\n\n$groups = [];\n$tempGrid = $gameGrid;\nforeach ($gameGrid as $y =&gt; $row) {\n foreach ($row as $x =&gt; $value) {\n if ($tempGrid[$y][$x] &gt; 0) {\n $groups[] = touchingCells($tempGrid, $y, $x);\n }\n }\n}\n\nvar_export($groups);\n</code></pre>\n<p>The result is:</p>\n<pre><code>[0 =&gt; [0 =&gt; ['y' =&gt; 0, 'x' =&gt; 0],\n 1 =&gt; ['y' =&gt; 1, 'x' =&gt; 0],\n 2 =&gt; ['y' =&gt; 2, 'x' =&gt; 0],\n 3 =&gt; ['y' =&gt; 3, 'x' =&gt; 0],\n 4 =&gt; ['y' =&gt; 4, 'x' =&gt; 0],\n 5 =&gt; ['y' =&gt; 4, 'x' =&gt; 1],\n 6 =&gt; ['y' =&gt; 4, 'x' =&gt; 2],\n 7 =&gt; ['y' =&gt; 4, 'x' =&gt; 3],\n 8 =&gt; ['y' =&gt; 3, 'x' =&gt; 4],\n 9 =&gt; ['y' =&gt; 2, 'x' =&gt; 4],\n 10 =&gt; ['y' =&gt; 1, 'x' =&gt; 4],\n 11 =&gt; ['y' =&gt; 0, 'x' =&gt; 4],\n 12 =&gt; ['y' =&gt; 4, 'x' =&gt; 4]], \n 1 =&gt; [0 =&gt; ['y' =&gt; 0, 'x' =&gt; 2]],\n 2 =&gt; [0 =&gt; ['y' =&gt; 2, 'x' =&gt; 2]]];\n</code></pre>\n<p>I don't think this code is much faster than yours; they're both pretty fast, but I tried to make the code slightly less unreadable, although it is far from optimal in that regard.</p>\n<p>The input grid is redefined here, so it is recognizable as a grid. The <code>1</code> means a white cell, the <code>0</code> means a blue cell.</p>\n<p>I use a <code>$tempGrid</code> for checking touching cells. As soon as I detect that an used cell touches, I set it to zero, so it won't be detected again and it is stored in an array called <code>$cells</code>.</p>\n<p>There are several things in this code that may be new to you.</p>\n<ul>\n<li>This routine checks around a cell using offsets in <code>foreach</code> loops. Although that means I need to use two extra loops it also means I only need one <code>if ()</code> inside the <code>touchingCells()</code> function.</li>\n<li>Instead of using <code>isset()</code> first, I use the <a href=\"https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce\" rel=\"nofollow noreferrer\">null coalescing operator</a> to check if a cell touches. I could have even left out the <code>&gt; 0</code> from <code>($grid[$scanY][$scanX] ?? 0 &gt; 0)</code> but I always prefer clarity over brevity.</li>\n<li>Also note the lack of array functions like <code>array_merge()</code>.</li>\n</ul>\n<p>Perhaps I'll try to work on the other functions later. Still I think a brute force approach is not wise, but since you won't give us all the details about this game, all we can do it play a bit with the given routines.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T17:48:55.893", "Id": "531975", "Score": "0", "body": "That's great thanks! I don't understand \"&$grid\". The mecanisms of your function are totally different from mine so it is a little difficult to understand it but I will test it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T17:58:13.117", "Id": "531976", "Score": "0", "body": "I will change the names of my variables to make my functions more readable. The second and third functions in my post have the same goal and they are used thousands of times unlike the first function. If you wanna know a little more about my game : I generate a grid with blue and white cells. Then I try to find all the possible paths whicl lead to fill the grid in blue with a minimum of moves. When I move to a cell it change its color. This a post related to my game : https://math.stackexchange.com/questions/4293598/how-to-demonstrate-the-shortest-path-to-fill-a-grid-of-blue-and-white-cells" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T18:21:17.013", "Id": "531978", "Score": "0", "body": "The `&$grid` means that `$grid` is [passed by reference](https://www.php.net/manual/en/language.references.pass.php). I notice that `if ((($scanY != $y) || ($scanX != $x)) && ($grid[$scanY][$scanX] ?? 0 > 0))` can be replace by `if ($grid[$scanY][$scanX] ?? 0 > 0)` without changing the functionality. I'll do that, it makes the code quite a bit simpler." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T19:34:51.857", "Id": "531982", "Score": "0", "body": "@RomainCharles: I looked at your other question. I think I sort of understand what you're asking there. I'm not surprised nobody answered. It is a very complicated question and you ask two different things: 1. what is shortest path and 2. minimum blue cells to go through. I also still don't understand what problem the functions in this question are trying to solve. This is a prerequisite of a question in the Code Review community." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T19:58:05.950", "Id": "531984", "Score": "0", "body": "When I generate a grid like in the other question, I need to get every possible path with less possible moves. It helps me evaluate the complexity of the grid and configure the party. To get every possible paths with less moves, I have to generate every possible path and gradually filter them with parameters. The number of groups of white cells is one of them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T20:43:31.670", "Id": "531987", "Score": "0", "body": "If I have the minimum number of blue cells to go through, it will give me the minimum length of all the possible paths, I just have to get the number of white cells and to add the minimum number of blue cells multiplied by two (first move the blue cell becomes white, second move the white cell becomes blue again)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T21:10:44.380", "Id": "531989", "Score": "0", "body": "@KikoSoftware do revisions [5](https://codereview.stackexchange.com/revisions/269575/5) and [6](https://codereview.stackexchange.com/revisions/269575/6) of the question invalidate your answer? if so, they can be rolled back per site convention - see [the help center page _What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T21:27:54.080", "Id": "531995", "Score": "1", "body": "@SᴀᴍOnᴇᴌᴀ: No, those revisions do not invalidate my answer. They only help to clarify what the variables in the question stand for." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T16:51:59.497", "Id": "269617", "ParentId": "269575", "Score": "2" } } ]
{ "AcceptedAnswerId": "269617", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T10:41:50.573", "Id": "269575", "Score": "0", "Tags": [ "performance", "php", "recursion" ], "Title": "PHP game - changing color of cells in a blue and white grid => updating groups of white cells that touch each other" }
269575
<p>I am currently trying to better my understanding of python and good coding practices and would really like some input on a question i have been thinking over for weeks now.</p> <p>I am currently working on building a virtual microprocessor out of basic logic gates (And, Or,...). The idea is to assemble more and more complex components out of parts that already exist. Once a component is created, i can reuse it whenever needed.</p> <p>Almost all components are structured in the same way. They take one or more inputs and use these to create some inner logic which results in one or more outputs.</p> <p>This component for example takes an 8-bit input (<code>in_data</code>) and inverts all its bits if another input (<code>in_invert</code>) carries a current:</p> <pre><code>class OnesComplement(IntegratedComponent): def __init__(self, in_data: list[ElectricComponent] = None, in_invert: ElectricComponent = None): self.in_data = in_data if in_data is not None else [ LooseWire() for x in range(8)] self.in_invert = in_invert if in_invert is not None else LooseWire() self.out_main = [XOR(inp, self.in_invert) for inp in self.in_data] </code></pre> <p>Some inputs might not be available at initialization. In that a case one or more instances of <code>LooseWire</code> is created in order to keep track of all the components that depend on the missing input. This is also one of the reasons why the inputs are registered as instance attributes.</p> <p>This code works perfectly fine, but it is very repetitive. In the example above, only a single line of code is used to implement the logic of the component. Everything else is just for setting defaults and registering instance attributes. This is annoying because I am writing a lot of components. It also leads to copy/paste errors and fails to highlight the occasional processing of non-input parameters.</p> <p>As a way around this I tried using a decorator:</p> <pre><code>from functools import wraps def _lwd(n=1): &quot;&quot;&quot; ONLY for use with the @autoparse decorator. LooseWires are temporary and will be exchanged by the decorator. &quot;&quot;&quot; if n == 1: return LooseWire() else: return [LooseWire() for _ in range(n)] def autoparse(init): parnames = init.__code__.co_varnames[1:] defaults = init.__defaults__ @wraps(init) def wrapped_init(self, *args, **kwargs): # Turn args into kwargs kwargs.update(zip(parnames[:len(args)], args)) # apply default parameter values default_start = len(parnames) - len(defaults) for i in range(len(defaults)): if parnames[default_start + i] not in kwargs: kwargs[parnames[default_start + i]] = defaults[i] # generate new instance for each LooseWire for arg in kwargs: if isinstance(kwargs[arg], LooseWire): kwargs[arg] = LooseWire() if isinstance(kwargs[arg], list): for i in range(len(kwargs[arg])): if isinstance(kwargs[arg][i], LooseWire): kwargs[arg][i] = LooseWire() # attach attributes to instance for arg in kwargs: setattr(self, arg, kwargs[arg]) init(self, **kwargs) return wrapped_init </code></pre> <p>This allows me to write the component from above like this:</p> <pre><code>class OnesComplement(IntegratedComponent): @autoparse def __init__(self, in_in: list[ElectricComponent] = _lwd(8), in_invert: ElectricComponent = _lwd()): self.out_main = [XOR(inp, self.in_invert) for inp in self.in_in] </code></pre> <p>I feel like this solves all of my problems. It is concise and also highlights the width of the input. However, i am worried about introducing some unwanted side-effects that i am not thinking about. Is it safe to decorate the <code>__init__</code> like that? And if so, would it be considered good practice?</p> <p><strong>edit</strong>: more code as requested</p> <p>code for the base class <code>ElectricComponent</code>:</p> <pre><code>class ElectricComponent: &quot;&quot;&quot; Parent class for all components of the electric circuit &quot;&quot;&quot; def connect_input(self, input_name: str, input_circuit: 'ElectricComponent'): &quot;&quot;&quot; Should be used if not all inputs were available at initialization. Replaces LooseWires. &quot;&quot;&quot; old_input = getattr(self, input_name) islist = isinstance(old_input, list) if not islist: old_input = [old_input] input_circuit = [input_circuit] for i in range(len(input_circuit)): for fc in old_input[i].forward_connections: setattr(fc[0], fc[1], input_circuit[i]) input_circuit[i].add_connection(fc[0], fc[1]) fc[0].update() if not islist: input_circuit = input_circuit[0] # Not functional, just for tracking setattr(self, input_name, input_circuit) </code></pre> <p>There are two types of components that inherit from <code>ElectricComponent</code>: <code>CoreComponent</code> and <code>IntegratedComponent</code>.</p> <p>Most of the logic in maintaining connections and propagating state changes is handled by <code>CoreComponent</code>s. They have their own state, stored as a bool in self.out_main.</p> <pre><code>class CoreComponent(ElectricComponent): &quot;&quot;&quot; Parent Class for all core components These are the basic buidling blocks that all other components are assembled from All core components have a singlaur output-line called 'out_main' &quot;&quot;&quot; def setup(self): self.forward_connections = [] self.build_circuit() self.compute_state() def get_state(self): &quot;&quot;&quot;Returns the current state of the output&quot;&quot;&quot; return self.out_main is_on = property(get_state) def add_connection(self, con, port): &quot;&quot;&quot;Called by downstream elements to add them as a forward connection&quot;&quot;&quot; if (con, port) not in self.forward_connections: self.forward_connections.append((con, port)) def forward_pass(self): for fc in self.forward_connections: fc[0].update() def update(self): old_state = self.out_main self.compute_state() if self.out_main != old_state: self.forward_pass() def __str__(self): return str(int(self.out_main)) </code></pre> <p>All <code>CoreComponents</code> (for now):</p> <pre><code>class Switch(CoreComponent): &quot;&quot;&quot; Simple Switch. It is used to control a gate. When the gate is closed it carries a current. &quot;&quot;&quot; def __init__(self, closed: bool = False): self.out_main = closed self.setup() def build_circuit(self): pass def compute_state(self): pass def flip(self): self.out_main = not self.out_main self.forward_pass() def open(self): self.out_main = False self.forward_pass() def close(self): self.out_main = True self.forward_pass() class LooseWire(CoreComponent): &quot;&quot;&quot; This component is used solely for initializing unconnected inputs It never carries a current &quot;&quot;&quot; def __init__(self): self.setup() def build_circuit(self): pass def compute_state(self): self.out_main = False class BaseGate(CoreComponent): &quot;&quot;&quot; Parent for the baisc logic gates &quot;&quot;&quot; def __init__(self, in_a: ElectricComponent = None, in_b: ElectricComponent = None): self.in_a = in_a if in_a is not None else LooseWire() self.in_b = in_b if in_b is not None else LooseWire() self.setup() def build_circuit(self): self.in_a.add_connection(self, 'in_a') self.in_b.add_connection(self, 'in_b') class INV(CoreComponent): &quot;&quot;&quot;Inverts the input&quot;&quot;&quot; def __init__(self, in_a: ElectricComponent = None): self.in_a = in_a if in_a is not None else LooseWire() self.setup() def build_circuit(self): self.in_a.add_connection(self, 'in_a') def compute_state(self): self.out_main = True if self.in_a.is_on: self.out_main = False class AND(BaseGate): &quot;&quot;&quot;AND-Gate&quot;&quot;&quot; def compute_state(self): self.out_main = False if self.in_a.is_on: if self.in_b.is_on: self.out_main = True class OR(BaseGate): &quot;&quot;&quot;OR-Gate&quot;&quot;&quot; def compute_state(self): self.out_main = False if self.in_a.is_on: self.out_main = True if self.in_b.is_on: self.out_main = True class NOR(BaseGate): &quot;&quot;&quot;NOR-Gate&quot;&quot;&quot; def compute_state(self): self.out_main = True if self.in_a.is_on: self.out_main = False if self.in_b.is_on: self.out_main = False class NAND(BaseGate): &quot;&quot;&quot;NAND-Gate&quot;&quot;&quot; def compute_state(self): self.out_main = True if self.in_a.is_on: if self.in_b.is_on: self.out_main = False </code></pre> <p>The other class that inherits from <code>ElectricComponent</code> is <code>IntegratedComponent</code>. Components of this type are assembled out of <code>CoreComponents</code>. Most of the components i build are of this type. They do not posses a state of their own. The class itself is empty for now. It used to contain some methods i factored out but i am keeping it around for structuring and future use.</p> <p>There are too many <code>IntegratedComponent</code>s to post them all. One example of an <code>IntegratedComponent</code> would be the <code>OnesComplement</code> i originally posted. Another is the XOR-gate which is used in the <code>OnesComplement</code></p> <pre><code>class IntegratedComponent(ElectricComponent): pass class IntegratedLogicGate(IntegratedComponent): # TODO: think about moving this to a class for all # IntegratedComponents with a single 'out_main' &quot;&quot;&quot; This allows for its children to be used like basegates and other core components and1 = AND(s1) xor1 = XOR(s1, s2) xor.out_main.is_on can be written as xor.is_on and1.connect_input('in_b', xor1.out_main) can be written as if XOR were a CoreComponent and1.connect_input('in_b', xor1) &quot;&quot;&quot; def get_state(self): return self.out_main.get_state() is_on = property(get_state) def add_connection(self, con, port): self.out_main.add_connection(con, port) class XOR(IntegratedLogicGate): &quot;&quot;&quot;XOR-Gate&quot;&quot;&quot; def __init__(self, in_a: ElectricComponent = None, in_b: ElectricComponent = None): self.in_a = in_a if in_a is not None else LooseWire() self.in_b = in_b if in_b is not None else LooseWire() self.or1 = OR(self.in_a, self.in_b) self.nand1 = NAND(self.in_a, self.in_b) self.out_main = AND(self.or1, self.nand1) </code></pre> <p>One example of a component that needs a <code>LooseWire</code> because it has its own output as an input is the <code>RSFlipFlop</code></p> <pre><code>class RSFlipFlop(IntegratedComponent): def __init__(self, in_r: ElectricComponent = None, in_s: ElectricComponent = None): self.in_r = in_r if in_r is not None else LooseWire() self.in_s = in_s if in_s is not None else LooseWire() self.nor1 = NOR(self.in_r) self.nor2 = NOR(self.nor1, self.in_s) self.nor1.connect_input(&quot;in_b&quot;, self.nor2) self.out_q = self.nor1 self.out_qb = self.nor2 </code></pre> <p><strong>edit 2</strong>:</p> <p>I should have been more clear as to what my goals for this project are. I am currently reading trough Charles Petzold's book <em>Code: The Hidden Language of Hardware and Software</em>. In it, he is shows how to assemble a microprocessor out of basic logic gates constructed from relays and switches. I am trying to replicate this virtually. The 5 logic gates I use as core components are the 5 gates he uses as building blocks in his book. This is also why those gates only have two inputs and why i chose nested if-clauses for them. I can't use logic operators before building them myself.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T10:36:24.900", "Id": "531918", "Score": "0", "body": "@Reinderien I added more code as requested" } ]
[ { "body": "<p>In no particular order:</p>\n<ul>\n<li>Your input model is too complicated. Don't <code>isinstance(old_input, list)</code>; just assume that every component has a <code>Collection[]</code> (sized, iterable, unordered) of (potentially only one) input.</li>\n<li>Similarly, your output model is sometimes too complicated. There's not a lot of benefit in representing your <code>OnesComplement</code> as a byte bus - just represent it as a single bit (which really just evaluates to a <code>XOR</code>). If you want to generalize an arbitrary gate to a byte bus you should do that separately, possible for all components, not just <code>OnesComplement</code>.</li>\n<li><code>CoreComponent</code> is effectively an abstract class due to <code>compute_state</code> not being defined - fine. However, <code>build_circuit(self): pass</code> should exist on <code>CoreComponent</code> itself, and <code>compute_state</code> should also be declared there as <code>compute_state(self): raise NotImplementedError()</code>.</li>\n<li>Relying on <code>getattr</code>/<code>setattr</code> as much as this code does is a code smell.</li>\n<li>In most cases, it doesn't benefit you to hard-code <code>in_a</code> / <code>in_b</code>. It's less work for an OR, AND etc. to just accept an arbitrary number of inputs.</li>\n<li>Don't auto-convert <code>in_a</code> from a <code>None</code> to a <code>LooseWire</code>; just accept a component that can never be <code>None</code>. Also, your <code>in_a</code> annotation is currently incorrect because it's missing an <code>Optional[]</code>. Further: you probably shouldn't allow for a <code>LooseWire</code> at all.</li>\n<li><code>build_circuit</code> and <code>add_connection</code> probably shouldn't exist. You should just be able to assume that your inputs are your connections.</li>\n<li>As to your original question, no, your decorator is really not a good idea. Magic conversion of constructor parameters is more complicated and difficult to understand than it should be.</li>\n</ul>\n<h2>State and forward propagation</h2>\n<p>All but two of your components - <code>RSFlipFlop</code> and <code>Switch</code> - should be stateless - just as they are in real life. As such, it is not a good idea to hold a <code>self.out_main</code>. Just define an evaluation function, basically your <code>compute_state</code>, that returns a boolean.</p>\n<p>It's not a good idea to keep <code>forward_connections</code>, at least in its current form. In real life, the behaviour of a component should not rely on the components after it.</p>\n<p>Since you're encountering performance issues, it is possible to be a little more clever (I have not shown that in the suggested code):</p>\n<ul>\n<li>Approach this in a general manner, keeping only one boolean output: this includes your FF, where you can simplify its model to only have non-inverting output. If you need an inverter afterward, keep that as a separate component.</li>\n<li>Cache the old value of the output, similar to your <code>out_main</code>.</li>\n<li>Only forward-propagate changes if the old value is not equal to the new value. You had already done this (albeit a little inconsistently) in <code>if self.out_main != old_state</code>.</li>\n<li>Use <code>__slots__</code>.</li>\n<li>Consider finalizing a circuit using run-time code objects and <a href=\"https://docs.python.org/3/library/functions.html#compile\" rel=\"nofollow noreferrer\">compile</a>.</li>\n</ul>\n<h2>Suggested code</h2>\n<pre><code>from functools import reduce\nfrom operator import xor\nfrom sys import maxsize\nfrom typing import ClassVar, Collection, Callable, Iterable, List\n\n\nclass Component:\n &quot;&quot;&quot;\n Parent class for all components of the electric circuit\n &quot;&quot;&quot;\n def __init__(self) -&gt; None:\n self.change_hooks: List[Callable[[], None]] = []\n\n @property\n def out(self) -&gt; bool:\n raise NotImplementedError()\n\n def __bool__(self) -&gt; bool:\n return self.out\n\n def changed(self) -&gt; None:\n for hook in self.change_hooks:\n hook()\n\n\nclass InputComponent(Component):\n def __init__(self, inputs: Iterable['Component']) -&gt; None:\n super().__init__()\n for input in inputs:\n input.change_hooks.append(self.changed)\n\n\nclass InputCollectionComponent(InputComponent):\n MIN_INPUTS: ClassVar[int]\n MAX_INPUTS: ClassVar[int]\n\n def __init__(self, inputs: Collection['Component']) -&gt; None:\n super().__init__(inputs)\n if not (self.MIN_INPUTS &lt;= len(inputs) &lt;= self.MAX_INPUTS):\n raise ValueError(f'{len(inputs)} inputs for {type(self).__name__} '\n f'not between {self.MIN_INPUTS}-{self.MAX_INPUTS}')\n self.inputs = inputs\n\n\nclass Switch(Component):\n def __init__(self, closed: bool) -&gt; None:\n super().__init__()\n self.closed = closed\n\n def flip(self) -&gt; None:\n self.closed = not self.closed\n self.changed()\n\n @property\n def out(self) -&gt; bool:\n return self.closed\n\n\nclass INV(InputComponent):\n def __init__(self, input: Component) -&gt; None:\n super().__init__((input,))\n self.input = input\n\n @property\n def out(self) -&gt; bool:\n return not self.input\n\n\nclass Gate(InputCollectionComponent):\n MIN_INPUTS = 2\n MAX_INPUTS = maxsize\n\n\nclass AND(Gate):\n @property\n def out(self) -&gt; bool:\n return all(self.inputs)\n\n\nclass OR(Gate):\n @property\n def out(self) -&gt; bool:\n return any(self.inputs)\n\n\nclass NOR(Gate):\n @property\n def out(self) -&gt; bool:\n return not any(self.inputs)\n\n\nclass NAND(Gate):\n @property\n def out(self) -&gt; bool:\n return not all(self.inputs)\n\n\nclass XOR(Gate):\n @property\n def out(self) -&gt; bool:\n return reduce(xor, self.inputs, False)\n\n\nclass RSFlipFlop(InputComponent):\n def __init__(self, *, in_r: Component, in_s: Component) -&gt; None:\n super().__init__((in_r, in_s))\n self.in_r, self.in_s = in_r, in_s\n self.update()\n\n @property\n def out(self) -&gt; bool:\n return self.state\n\n def update(self) -&gt; None:\n self.state = self.in_s.out and not self.in_r.out\n\n def changed(self) -&gt; None:\n self.update()\n super().changed()\n\n\nclass OnesComplement(XOR):\n def __init__(self, in_in: Component, in_invert: Component) -&gt; None:\n super().__init__((in_in, in_invert))\n\n\ndef test() -&gt; None:\n swa = Switch(closed=False)\n swb = Switch(closed=False)\n or_ = OR((swa, swb))\n ff = RSFlipFlop(in_r=swa, in_s=or_)\n\n assert not swa\n assert not swb\n assert not or_\n assert not ff\n\n swb.flip()\n assert not swa\n assert swb\n assert or_\n assert ff\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T16:51:14.040", "Id": "531968", "Score": "0", "body": "Thank you for taking the time to read trough this and respond. I very much look forward to your suggested implementation. Fwiw, I did start out without forward connections and everything being stateless, but as the circuits grew bigger this started to become slow because i was recursing trough the whole circuit for every bit in the output. This is why i introduced the forward connections. The idea was that a change in component A would only affect the components (forward_connections) that depend on the state of component A and that forward propagation would stop for unaffected components." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T08:23:21.037", "Id": "532021", "Score": "0", "body": "Thanks again. Many good pointers. I learned a lot from this and will try my hands at a recursive solution again. Unfortunately your code does not really work for what i'm trying to achieve (see my latest edit). I'm sorry i wasn't more clear about that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T13:17:12.367", "Id": "532044", "Score": "0", "body": "@LoePhi That's.. fine, but if you want a review that takes the new information into account you're going to have to repost." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T15:46:04.270", "Id": "269615", "ParentId": "269579", "Score": "4" } } ]
{ "AcceptedAnswerId": "269615", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T11:40:44.800", "Id": "269579", "Score": "6", "Tags": [ "python", "python-3.x" ], "Title": "Decorating __init__ for automatic attribute assignment: Safe and good practice?" }
269579
<blockquote> <p>Task description A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.</p> <p>For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.</p> <p>Write a function:</p> <p>function solution(N);</p> <p>that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.</p> <p>For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.</p> <p>Write an efficient algorithm for the following assumptions:</p> <p>N is an integer within the range [1..2,147,483,647].</p> </blockquote> <p>I don't believe the code itself is bad, but I'm not sure if it's good either.</p> <p>I had one bug once I tested my solution against the test cases codility provides before submitting the task.</p> <p>The bug I found was related to this line, and was fixed.</p> <blockquote> <p>return pos - 1; //since it got out of the loop because powOfTwo was bigger than the decimal representation</p> </blockquote> <p>I was returning just <code>pos</code>, which is clearly a mistake, since it gets out of the loop when it finds a bigger number than the decimal representation the function's receiving, there must be a way for me to avoid thinking about this kind of stuff.</p> <p>(I know we can get the binary representation of a number using a js function, I just thought the way I did it was a &quot;bit&quot; more challenging).</p> <p>I didn't realize at first that if it went out of the loop in the <code>getHeaviestOnePositionInBinaryRep</code> function was because the power of two was bigger than the decimal representation of the number the function was receiving, so something that could have taken like 40 minutes ended up taking 60 minutes because I couldn't find the bug (actually I thought about it for like a minute when I was first writing the code and decided that I was wrong in considering to return <code>pos-1</code> -ikr? 'think twice, code once' seems to failed for me here-). If Mr. Robot taught us something is that bugs are very important to us, and we need to learn from them.</p> <p>Anyways, here is the code: (thanks for stopping by)</p> <pre><code>const getHeaviestOnePositionInBinaryRep = (decimalRep) =&gt; { let powOfTwo = 1, pos = 0; while (powOfTwo &lt;= decimalRep) { if (powOfTwo == decimalRep) { return pos; } powOfTwo *= 2; pos++; } return pos - 1; //since it got out of the loop because powOfTwo was bigger than the decimal representation }; const biggestGap = (decimalRepresentation) =&gt; { let ones = []; while (decimalRepresentation &gt; 0) { ones.push(getHeaviestOnePositionInBinaryRep(decimalRepresentation)); decimalRepresentation -= 2 ** ones[ones.length - 1]; //substract 2 to the power of the heaviest one found } let biggestGap = 0; let secondHeaviestOneFoundTillNow = ones.pop(); let heaviestOneFoundTillNow; while (ones.length &gt; 0) { heaviestOneFoundTillNow = ones.pop(); currentGap = heaviestOneFoundTillNow - secondHeaviestOneFoundTillNow - 1; biggestGap = biggestGap &lt; currentGap ? currentGap : biggestGap; secondHeaviestOneFoundTillNow = heaviestOneFoundTillNow; } return biggestGap; }; </code></pre>
[]
[ { "body": "<h3>Avoid unnecessary array creation</h3>\n<p>The code creates an array of the bit positions of ones in a first pass,\nto iterate over in a second pass to find the biggest gap.\nIt's not a big deal, since the size of the array is bound by the number of bits (32).\nBut it's unnecessary, because you could as well compute the biggest gap during the first pass, without ever creating an array.</p>\n<pre><code>const biggestGap = (n) =&gt; {\n if (n == 0) return 0;\n \n // skip 0s until the first 1 from the end\n var work = n; \n while ((work &amp; 1) == 0) {\n work &gt;&gt;= 1;\n }\n \n // skip the 1\n work &gt;&gt;= 1;\n\n // start tracking the length of sequences of 0s\n var longest = 0;\n var length = 0;\n \n while (work) {\n if (work &amp; 1) {\n longest = Math.max(longest, length);\n length = 0;\n } else {\n length++;\n }\n work &gt;&gt;= 1;\n }\n \n return longest;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T16:14:23.383", "Id": "269588", "ParentId": "269585", "Score": "5" } } ]
{ "AcceptedAnswerId": "269588", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T15:08:07.983", "Id": "269585", "Score": "3", "Tags": [ "javascript", "node.js" ], "Title": "Codility's biggest binary gap [100% score]" }
269585
<p>I was busy writing an answer for this <a href="https://codereview.stackexchange.com/questions/269541/i-made-a-simple-score-game-in-c-console">question</a> when I realized that I was busy creating a new solution without explaining what the original poster did wrong, again.</p> <p>So I decided to rather post what I came up with as a new question. Please feel free to rip it apart or see if you can beat my pathetic high score =)</p> <p><a href="https://i.stack.imgur.com/1QJqO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1QJqO.png" alt="enter image description here" /></a></p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Generic; using System.Linq; using System.Timers; namespace Snake { public record Position { public int Row { get; set; } public int Col { get; set; } } public class State { public State(int rows, int cols, int foodCount = 1) { _rand = new Random(); _rows = rows; _cols = cols; _foodCount = foodCount; _gameOver = false; _crashBorder = false; _crashSnake = false; var head = GenRandomPos(); _snake.Add(head); _directionVert = 0; _directionHorz = head.Col &gt; _cols / 2 ? -1 : 1; AddFood(); _eating = 0; } private Position GenRandomPos() { var pos = new Position(); pos.Row = _rand.Next(0, _rows); pos.Col = _rand.Next(0, _cols); return pos; } private void AddFood() { while (_food.Count &lt; _foodCount) { var pos = GenRandomPos(); if (_snake.Contains(pos) == false &amp;&amp; _food.Contains(pos) == false) _food.Add(pos); } } public void UpdateDirection(ConsoleKey input) { switch (input) { case ConsoleKey.UpArrow: case ConsoleKey.W: _directionHorz = 0; _directionVert = -1; break; case ConsoleKey.DownArrow: case ConsoleKey.S: _directionHorz = 0; _directionVert = 1; break; case ConsoleKey.LeftArrow: case ConsoleKey.A: _directionHorz = -1; _directionVert = 0; break; case ConsoleKey.RightArrow: case ConsoleKey.D: _directionHorz = 1; _directionVert = 0; break; } } public void Move() { if (_gameOver == false) { _prevSnake = _snake.ToList(); var head = _snake.Last(); var pos = new Position(); pos.Row += head.Row + _directionVert; pos.Col += head.Col + _directionHorz; _snake.Add(pos); if (_eating == 0) _snake.RemoveAt(0); else _eating--; } } private bool SnakeCrashed() { var head = _snake.Last(); // check if snake is out of boundaries if (head.Col &lt; 0 || head.Col &gt;= _cols || head.Row &lt; 0 || head.Row &gt;= _rows) { _crashBorder = true; return true; } // check if snake crashed into itself for (int i=0; i&lt;_snake.Count - 2; i++) { if (head == _snake[i]) { _crashSnake = true; return true; } } return false; } public bool Evaluate() { if (SnakeCrashed() == true) { _gameOver = true; return false; } var head = _snake.Last(); int index = _food.IndexOf(head); if (index != -1) { _food.RemoveAt(index); AddFood(); _score++; _eating = 2; } return true; } public void Render(bool crashed = false) { if (crashed) _snake = _prevSnake.ToList(); Console.SetCursorPosition(0, 0); Console.CursorVisible = false; Console.WriteLine(&quot;Score = &quot; + _score); Console.ForegroundColor = _crashBorder ? ConsoleColor.Red : ConsoleColor.White; Console.WriteLine('╔' + new String('═', _cols) + '╗'); var pos = new Position(); for (pos.Row = 0; pos.Row &lt; _rows; pos.Row++) { Console.Write('║'); for (pos.Col = 0; pos.Col &lt; _cols; pos.Col++) { Console.ForegroundColor = ConsoleColor.Gray; if (_snake.Contains(pos)) { Console.ForegroundColor = _crashSnake ? ConsoleColor.Red : ConsoleColor.Green; Console.Write('█'); } else if (_food.Contains(pos)) { Console.ForegroundColor = ConsoleColor.Cyan; Console.Write('■'); } else { Console.ForegroundColor = ConsoleColor.DarkGray; Console.Write('-'); } } Console.ForegroundColor = _crashBorder ? ConsoleColor.Red : ConsoleColor.White; Console.WriteLine(&quot;║&quot;); } Console.WriteLine(&quot;╚&quot; + new String('═', _cols) + &quot;╝&quot;); Console.ForegroundColor = ConsoleColor.White; } private Random _rand; private int _rows; private int _cols; private int _foodCount; private int _directionVert; private int _directionHorz; private int _eating; private bool _gameOver; private List&lt;Position&gt; _snake = new List&lt;Position&gt;(); private List&lt;Position&gt; _food = new List&lt;Position&gt;(); private List&lt;Position&gt; _prevSnake = new List&lt;Position&gt;(); private bool _crashBorder; private bool _crashSnake; private int _score; public bool GameDone { get =&gt; _gameOver; } public int Score { get =&gt; _score; } } class Game { public Game(int rows, int cols) { var state = new State(rows, cols, rows / 4); state.Render(); var timer = new Timer(150); timer.Elapsed += (sender, e) =&gt; OnTimedEvent(sender, e, state); timer.Enabled = true; while (state.GameDone == false) System.Threading.Thread.Sleep(100); timer.Stop(); timer.Dispose(); state.Render(true); _score = state.Score; } private static void OnTimedEvent(Object source, ElapsedEventArgs e, State state) { lock (state) { if (Console.KeyAvailable) { var keyinfo = Console.ReadKey(true); state.UpdateDirection(keyinfo.Key); } state.Move(); if (state.Evaluate()) state.Render(); } } private int _score; public int Score { get =&gt; _score; } } class Program { static int Introduction(bool start) { if (start) Console.WriteLine(&quot;Welcome to Snake#\n&quot;); Console.WriteLine(&quot;Control your snake by using the arrow keys or AWSD. Press one of the following to start or Q to quit:&quot;); Console.WriteLine(&quot;1: Small Grid&quot;); Console.WriteLine(&quot;2: Medium grid&quot;); Console.WriteLine(&quot;3: Large grid&quot;); Console.CursorVisible = true; for (; ; ) { var keyinfo = Console.ReadKey(true); switch (keyinfo.Key) { case ConsoleKey.D1: return 10; case ConsoleKey.D2: return 15; case ConsoleKey.D3: return 19; case ConsoleKey.Q: return -1; } } } static void Main() { bool firstGame = true; int highScore = 0; for (; ; ) { int input = Introduction(firstGame); if (input &lt; 0) return; Console.Clear(); var game = new Game(input, input * 2); var score = game.Score; if (highScore &lt; score) highScore = score; Console.WriteLine(String.Format(&quot;\nGame Over! High score = {0}\n&quot;, highScore)); firstGame = false; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T10:43:27.893", "Id": "531919", "Score": "0", "body": "From a bird view: 1) `== true` can be ommited 2) `Position` properties can be immutable like `get; init;`" } ]
[ { "body": "<p>I always find it a bit strange when people answer their own questions, but after looking at this a day later I made the following observation.</p>\n<h1>Using <code>Timer</code> and <code>lock</code> is stupid and unnecessary!</h1>\n<p>Consider changing <code>public Game</code> like so:</p>\n<pre><code>public Game(int rows, int cols)\n{\n var state = new State(rows, cols, rows / 4);\n state.Render();\n const long interval = 150;\n var sw = new Stopwatch();\n while (state.GameDone == false)\n {\n sw.Restart();\n if (Console.KeyAvailable)\n {\n var keyinfo = Console.ReadKey(true);\n state.UpdateDirection(keyinfo.Key);\n }\n state.Move();\n if (state.Evaluate())\n {\n state.Render();\n sw.Stop();\n if (interval &gt; sw.ElapsedMilliseconds)\n System.Threading.Thread.Sleep((int)(interval - sw.ElapsedMilliseconds));\n }\n }\n state.Render(true);\n _score = state.Score;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T20:25:42.397", "Id": "269659", "ParentId": "269591", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T19:32:49.140", "Id": "269591", "Score": "5", "Tags": [ "c#", "console" ], "Title": "C# Console Snake Game" }
269591
<p>I have been obtaining financial information on an annuity I have which is invested in multiple funds which are proprietary to the insurance company.</p> <p>The asset value is not available other than on their website.</p> <p>I have been obtaining the information using VBA and Internet Explorer. Due to the rumor that IE will be discontinued in Windows 11, I am trying to implement a Selenium-VBA solution. This is my first time working with Selenium.</p> <p>The posted code seems to work OK in both Edge and Chrome, but I'd appreciate someone more knowledgeable critiquing it. The biggest problem I run into is that the site somewhat randomly, but frequently, presents one or multiple CAPTCHA's consisting of a nine-segment set of pictures that have to be analyzed. This may take several minutes to run through. With Selenium, I am using the <code>timeout</code> argument when <code>finding</code> an element, and that seems to take care of that problem without inducing unneeded delays.</p> <p>Thank you for taking a look at this.</p> <p>Unfortunately, because of the confidentiality of the information, I cannot provide URL/credentials that will function. If that makes this question off-topic for this forum, I will withdraw it.</p> <pre><code>Option Explicit 'reference Selenium type library Sub test2() Dim dr As Selenium.ChromeDriver Dim Username As Selenium.WebElement, Password As Selenium.WebElement, Login As Selenium.WebElement Dim roth As Selenium.WebElement, details As Selenium.WebElement, fundView As Selenium.WebElement Dim funds As Selenium.WebElements, EL As Selenium.WebElement Dim fundsText As Collection Const sURL As String = &quot;https://www.nationwide.com/access/web/login.htm&quot; 'just a throwaway for testing Dim v Set dr = New Selenium.ChromeDriver With dr .Start &quot;chrome&quot; .Get sURL Set Username = .FindElementByCss(&quot;input#user.text-field&quot;, timeout:=20000) Set Password = .FindElementByCss(&quot;input#password.text-field&quot;, timeout:=20000) Set Login = .FindElementByName(&quot;submitBtn&quot;, timeout:=20000) Username.SendKeys &quot;xxxxxxxxxx&quot; Password.SendKeys &quot;xxxxxxxxxx&quot; Login.Click 'this can take a long time as there are intermittenly complex CAPTCHA's to solve ' with multiple instances of 9 picture frames at a time to analyze Set roth = .FindElementById(&quot;xxxxxxxxxx&quot;, timeout:=300000) roth.Click Set details = .FindElementByXPath(&quot;//*[@id=&quot;&quot;skip-main-content&quot;&quot;]/div/section/div[3]/div[4]/a[1]&quot;, timeout:=20000) details.Click Set fundView = .FindElementByCss(&quot;#viewByFund&quot;, timeout:=20000) fundView.Click 'Also display the short fund name .FindElementByCss(&quot;#displayShortFundName&quot;, timeout:=5000).Click Set funds = .FindElementsByXPath(&quot;//*[@id='fundByFundOnly']/tbody/child::*&quot;, timeout:=20000) 'store results of the scraping into a collection Set fundsText = New Collection For Each EL In funds fundsText.Add EL.Text Next EL .Close End With Stop 'write the results to a worksheet for review 'will be processing differently when &quot;for real&quot; Dim r As Range, i As Long Set r = Sheet1.Cells(1, 1) For i = 1 To fundsText.Count r(i) = fundsText(i) Next i End Sub <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T21:13:17.873", "Id": "269593", "Score": "2", "Tags": [ "vba", "excel", "web-scraping", "selenium", "webdriver" ], "Title": "My first vba-selenium code" }
269593
<p>Recently, I wrote a class which can load an .obj file into vector array, and save the vector array as an .obj file. The .obj file looks something like this:</p> <pre><code>v 0.041159 -0.342570 1.029412 //vertices position : x, y,z v 0.015579 -0.341674 1.077751 v 0.014664 -0.341184 1.031222 v 0.041923 -0.343100 1.073583 v 0.064655 -0.344713 1.068008 vt 0.516780 0.631480 // vertices' texture coordinate vt 0.491540 0.621580 vt 0.495720 0.621740 vt 0.500000 0.621740 vt 0.504300 0.624760 vt 0.508540 0.628060 vt 0.512810 0.631590 vt 0.487450 0.621300 f 6497/6542 6321/6366 6319/6364 // triangles compounded by three vertices f 6498/6543 6495/6540 6496/6541 // the number is index of vertices f 6498/6543 6496/6541 6497/6542 f 6499/6544 6494/6539 6495/6540 f 6499/6544 6495/6540 6498/6543 f 6500/6545 6492/6537 6494/6539 f 6500/6545 6494/6539 6499/6544 f 6501/6546 6497/6542 6319/6364 f 6501/6546 6319/6364 6316/6361 f 6502/6547 6498/6543 6497/6542 f 6502/6547 6497/6542 6501/6546 f 6503/6548 6499/6544 6498/6543 f 6503/6548 6498/6543 6502/6547 f 6504/6549 6501/6546 6316/6361 </code></pre> <p>I use <code>double</code> type for vertices and vertices' texture coordinates, <code>unsigned int</code> for faces.</p> <p>Here is my header and implementation. The code can be compiled and run successfully. Are there any lurking errors here? How can I improve it?</p> <h2><code>trimesh.h</code></h2> <pre><code>#ifndef TRIMESH_H #define TRIMESH_H #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; using namespace std; class trimesh { public: std::vector&lt;std::vector&lt;double &gt; &gt; vertices; std::vector&lt;std::vector&lt;double &gt; &gt; tex_coords; std::vector&lt;std::vector&lt;double &gt; &gt; vert_normal; std::vector&lt;std::vector&lt;double &gt; &gt; vert_color; std::vector&lt;std::vector&lt;unsigned int&gt; &gt; faces; std::vector&lt;std::vector&lt;unsigned int&gt; &gt; faces_tc; void load(const std::string filename);// load .obj file from given path void save(const std::string save_path, const bool with_color = true, const bool with_vt = true); // save the current mesh to the given save_path }; #endif </code></pre> <h2><code>trimesh.cpp</code></h2> <pre><code>#include &quot;trimesh.h&quot; #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;vector&gt; using namespace std; using std::ofstream; void trimesh::load(const std::string filename) { std::ifstream file(filename); if (file.is_open()) { std::string line; while (std::getline(file, line)) { // using printf() in all tests for consistency //printf(&quot;%s&quot;, line.c_str()); istringstream in(line); vector&lt;string&gt; vec_line; string line_s; while (in &gt;&gt; line_s) { vec_line.push_back(line_s); } //std::cout &lt;&lt; &quot;vec_line:&quot; &lt;&lt; vec_line[0] &lt;&lt; std::endl; std::vector&lt;double&gt; double_line; std::vector&lt;double&gt; double_line_color; std::vector&lt;unsigned int&gt; unint_line; std::vector&lt;unsigned int&gt; unint_line_tc; if (vec_line[0]==&quot;v&quot;) { double v0 = std::stod(vec_line[1]); double v1 = std::stod(vec_line[2]); double v2 = std::stod(vec_line[3]); double_line.push_back(v0); double_line.push_back(v1); double_line.push_back(v2); vertices.push_back(double_line); double_line.clear(); if (vec_line.size()==7) { double c1 = std::stod(vec_line[4]); double c2 = std::stod(vec_line[5]); double c3 = std::stod(vec_line[6]); double_line_color.push_back(c1); double_line_color.push_back(c2); double_line_color.push_back(c3); vert_color.push_back(double_line_color); double_line_color.clear(); } } else if (vec_line[0]==&quot;vt&quot;) { double vt0 = std::stod(vec_line[1]); double vt1 = std::stod(vec_line[2]); double_line.push_back(vt0); double_line.push_back(vt1); tex_coords.push_back(double_line); double_line.clear(); } else if (vec_line[0]==&quot;f&quot;) { size_t idx1 = vec_line[1].find(&quot;/&quot;); unsigned int v_idx_f_1 = std::stod(vec_line[1].substr(0, idx1)); size_t idx2 = vec_line[1].find(&quot;/&quot;, idx1 + 1); unsigned int v_idx_ftc_1 = std::stod(vec_line[1].substr(idx1 + 1, idx2)); size_t idx3 = vec_line[2].find(&quot;/&quot;); unsigned int v_idx_f_2 = std::stod(vec_line[2].substr(0, idx3)); size_t idx4 = vec_line[2].find(&quot;/&quot;, idx3 + 1); unsigned int v_idx_ftc_2 = std::stod(vec_line[2].substr(idx3 + 1, idx4)); size_t idx5 = vec_line[3].find(&quot;/&quot;); unsigned int v_idx_f_3 = std::stod(vec_line[3].substr(0, idx5)); size_t idx6 = vec_line[3].find(&quot;/&quot;, idx5 + 1); unsigned int v_idx_ftc_3 = std::stod(vec_line[3].substr(idx5 + 1, idx6)); unint_line.push_back(v_idx_f_1); unint_line.push_back(v_idx_f_2); unint_line.push_back(v_idx_f_3); faces.push_back(unint_line); unint_line_tc.push_back(v_idx_ftc_1); unint_line_tc.push_back(v_idx_ftc_2); unint_line_tc.push_back(v_idx_ftc_3); faces_tc.push_back(unint_line_tc); } } file.close(); } else { printf (&quot;loading obj: %s doesn't exists!\n&quot;, filename.c_str()); throw; } } void trimesh::save(const std::string save_path, const bool with_color, const bool with_vt) { ofstream outdata; outdata.open(save_path); if( !outdata ) { // file couldn't be opened std::cout &lt;&lt; &quot;Error: file could not be opened&quot; &lt;&lt; std::endl; exit(1); } if (with_color &amp;&amp; (vertices.size()==vert_color.size())) //write the vertices and colors { for (size_t i=0; i&lt;vertices.size(); i++) { outdata &lt;&lt; &quot;v &quot;; outdata &lt;&lt; vertices[i][0] &lt;&lt; &quot; &quot; &lt;&lt; vertices[i][1] &lt;&lt; &quot; &quot; &lt;&lt; vertices[i][2] &lt;&lt; &quot; &quot; &lt;&lt; vert_color[i][0] &lt;&lt; &quot; &quot; &lt;&lt; vert_color[i][1] &lt;&lt; &quot; &quot; &lt;&lt; vert_color[i][2] &lt;&lt;endl; } } else // only write the vertices { for (size_t i = 0; i &lt; vertices.size(); i++) { outdata &lt;&lt; &quot;v &quot;; outdata &lt;&lt; vertices[i][0] &lt;&lt; &quot; &quot; &lt;&lt; vertices[i][1] &lt;&lt; &quot; &quot; &lt;&lt; vertices[i][2]&lt;&lt;endl; } } if (with_vt) { for (size_t j=0; j&lt;tex_coords.size(); j++) { outdata &lt;&lt; &quot;vt &quot;; outdata &lt;&lt; tex_coords[j][0] &lt;&lt; &quot; &quot; &lt;&lt; tex_coords[j][1] &lt;&lt; endl; } } if (faces.size() == faces_tc.size()) { for (size_t k = 0; k &lt; faces.size(); k++) { outdata &lt;&lt; &quot;f &quot;; outdata &lt;&lt; faces[k][0] &lt;&lt; &quot;/&quot; &lt;&lt; faces_tc[k][0] &lt;&lt; &quot; &quot; &lt;&lt; faces[k][1] &lt;&lt; &quot;/&quot; &lt;&lt; faces[k][1] &lt;&lt; &quot; &quot; &lt;&lt; faces[k][2] &lt;&lt; &quot;/&quot; &lt;&lt; faces_tc[k][2] &lt;&lt;endl; } } else { for (size_t k = 0; k &lt; faces.size(); k++) { outdata &lt;&lt; &quot;f &quot;; outdata &lt;&lt; faces[k][0] &lt;&lt; &quot; &quot; &lt;&lt; faces[k][1] &lt;&lt; &quot; &quot; &lt;&lt; faces[k][2] &lt;&lt; endl; } } outdata.close(); } </code></pre>
[]
[ { "body": "<h1>Header</h1>\n<p>The header file includes a couple of headers that it doesn't need:</p>\n<blockquote>\n<pre><code>#include &lt;fstream&gt;\n#include &lt;iostream&gt;\n</code></pre>\n</blockquote>\n<p>That said, I would consider including <code>&lt;iosfwd&gt;</code> and declaring functions that work on streams (probably using <code>&gt;&gt;</code> and <code>&lt;&lt;</code>) rather than files, to make unit-testing possible.</p>\n<p>It also has <code>using namespace std;</code>, which is harmful - especially so in headers, where that affects every translation unit that includes the header. It's much better to qualify names as you use them, or to import just the names you need into a much smaller scope (e.g. at the function level).</p>\n<p>A class with all its data <code>public</code> is usually written <code>struct</code>. Usually, we then make the functions that operate on it not be members.</p>\n<p>I don't like vectors of vectors - it's a good idea to at least give a name to the inner vector. For example:</p>\n<pre><code>using vertex = std::vector&lt;double&gt;;\nstd::vector&lt;vertex&gt; vertices;\n</code></pre>\n<p>However, I'm not sure a vertex needs to be resizable - if they always have three members, then</p>\n<pre><code>using vertex = std::array&lt;double,3&gt;;\n</code></pre>\n<p><code>save()</code> shouldn't modify the object, so declare it as a <code>const</code> member function.</p>\n<p>The filenames should be passed as references to constant strings, rather than copying the string arguments. And the <code>bool</code> arguments shouldn't be declared <code>const</code> here, as that makes no difference to the caller (we can, and should, still use <code>const</code> where we <em>define</em> the functions):</p>\n<pre><code>void load(const std::string&amp; filename);\nvoid save(const std::string&amp; save_path,\n bool with_color = true,\n bool with_vt = true) const;\n</code></pre>\n<p>Consider using <code>std::filesystem::path</code> instead of <code>std::string</code>, for clarity. Note also that adding <code>bool</code> arguments to a function like that can make the call sites hard to read (because it's not clear what each argument does). Consider using a &quot;flags&quot; enum instead:</p>\n<pre><code>enum save_option {\n color = 1;\n vt = 2;\n // then 4, 8, etc\n};\n</code></pre>\n<p>Decide how errors are to be reported. If <code>load()</code> and <code>save()</code> are to return <code>void</code>, then we should document which exceptions may be thrown.</p>\n<h1>Implementation: <code>load()</code></h1>\n<p>Again, it's a bad idea to <code>using namespace std;</code> at file scope.</p>\n<p>Perhaps <code>load()</code> should clear its members before reading from the file? I'd write <em>two</em> member functions here:</p>\n<pre><code>void append(…);\n\nvoid load(…) { clear(); append(…); }\n</code></pre>\n<p>In <code>load()</code> the test for file opening would be easier to read if inverted:</p>\n<pre><code>if (!file.is_open()) {\n printf(&quot;loading obj: %s doesn't exists!\\n&quot;, filename.c_str());\n throw;\n}\n/// no need for &quot;else&quot; here\nstd::string line;\nwhile (std::getline(file, line)) {\n</code></pre>\n<p>The content of the failure case needs some attention:</p>\n<ul>\n<li><code>printf</code> isn't defined (<code>std::printf</code> is in <code>&lt;cstdio&gt;</code>).</li>\n<li>Error messages should go to the standard error stream (<code>std::cerr</code> if we use C++ streams rather than C-style I/O).</li>\n<li><code>throw</code> without an object is only usable when we have a <em>current exception</em> - i.e. if we're within a <code>catch</code> - which is not the case here.</li>\n<li>The <code>open</code> could fail for reasons other than the file not existing - perhaps it exists, but is a directory, or doesn't have sufficient permission for us. We could use <code>std::strerror(errno)</code> to create a more informative message.</li>\n<li>We probably don't want to be printing a message at all here - pass the information to the caller (which might be a GUI program, for example) and let it choose how to deal with it.</li>\n</ul>\n<hr />\n<p>It's good to read a line at a time and then parse it:</p>\n<blockquote>\n<pre><code> std::istringstream in(line);\n std::vector&lt;std::string&gt; vec_line;\n std::string line_s;\n while (in &gt;&gt; line_s) {\n vec_line.push_back(line_s);\n }\n</code></pre>\n</blockquote>\n<p>We could eliminate the loop, if we include <code>&lt;algorithm&gt;</code>\nand <code>&lt;iterator&gt;</code>:</p>\n<pre><code> std::istringstream in(line);\n std::vector&lt;std::string&gt; vec_line;\n std::copy(std::istream_iterator&lt;std::string&gt;{in},\n std::istream_iterator&lt;std::string&gt;{},\n std::back_inserter(vec_line));\n</code></pre>\n<p>Either way, we'll want to check that <code>in</code> isn't in error after reading it all, and that <code>vec_line</code> has at least one element before we attempt to use <code>vec_line[0]</code>.</p>\n<hr />\n<p>When parsing each line, we're breaking it up into a <code>std::vector&lt;std::string&gt;</code>, and then we parse some of those strings. But we can do better. If we read just the first word, we can then use that to determine how to read the rest of the line:</p>\n<pre><code> std::istringstream in(line);\n std::string linetype;\n in &gt;&gt; linetype;\n if (in.eof()) {\n continue; // blank line - ignore\n }\n if (!in) {\n throw parse_failed();\n }\n\n if (linetype==&quot;v&quot;) {\n vertex v;\n in &gt;&gt; v.x &gt;&gt; v.y &gt;&gt; v.z;\n if (!in) {\n throw parse_failed();\n }\n color c;\n if (in &gt;&gt; c.red &gt;&gt; c.green &gt;&gt; c.blue) {\n // we have a color; store it in the vertex\n }\n vertices.push_back(vertex);\n } else if (linetype==&quot;vt&quot;) {\n point vt;\n in &gt;&gt; vt.x &gt;&gt; vt.y;\n if (!in) {\n throw parse_failed();\n }\n tex_coords.push_back(vt);\n } else if (linetype==&quot;f&quot;) {\n face f;\n char a, b, c; // separators\n in &gt;&gt; f.f1 &gt;&gt; a &gt;&gt; f.ftc1\n &gt;&gt; f.f2 &gt;&gt; b &gt;&gt; f.ftc2\n &gt;&gt; f.f3 &gt;&gt; c &gt;&gt; f.ftc3;\n if (!in || a != '/' || b != '/' || c != '/') {\n throw parse_failed();\n }\n faces.push_back(f);\n }\n</code></pre>\n<p>This actually gets quite a bit simpler if we make <code>vertex</code>, <code>point</code> and <code>face</code> into object types with their own <code>&gt;&gt;</code> operators:</p>\n<pre><code> if (linetype==&quot;v&quot;) {\n vertex v;\n in &gt;&gt; v;\n vertices.push_back(vertex);\n } else if (linetype==&quot;vt&quot;) {\n point vt;\n in &gt;&gt; vt;\n tex_coords.push_back(vt);\n } else if (linetype==&quot;f&quot;) {\n face f;\n in &gt;&gt; f;\n faces.push_back(f);\n }\n</code></pre>\n<p>We might choose to set our stream to throw exceptions - e.g. <code>in.exceptions(std::istream::failbit|std::istream::badbit);</code>. We could improve reporting by keeping count of the number of lines we have read, so we can be more informative in our <code>parse_failed</code> exception.</p>\n<h1>Implementation: <code>save()</code></h1>\n<p>The <code>save()</code> function is simpler than <code>load()</code>, but I spotted the following:</p>\n<ul>\n<li><p>Don't use <code>std::exit()</code> - it terminates the process immediately, without running destructors. We really need to be able to report errors back rather than abandoning the program anyway (it would be really annoying for a user to lose all their work when trying to save to a directory where they don't have permission, without being given a chance to select an alternative location!).</p>\n</li>\n<li><p>The two alternatives for the <code>with_color</code> test are very similar. We can reduce the duplication there:</p>\n<pre><code> if (vertices.size() != vert_color.size()) {\n // something's wrong - we can't write the colors\n with_color = false;\n }\n for (std::size_t i=0; i&lt;vertices.size(); i++) {\n outdata &lt;&lt; &quot;v &quot; &lt;&lt; vertices[i][0] &lt;&lt; &quot; &quot; &lt;&lt; vertices[i][1] &lt;&lt; &quot; &quot; &lt;&lt; vertices[i][2];\n if (with_color) {\n out &lt;&lt; &quot; &quot; &lt;&lt; vert_color[i][0] &lt;&lt; &quot; &quot; &lt;&lt; vert_color[i][1] &lt;&lt; &quot; &quot; &lt;&lt; vert_color[i][2];\n }\n out &lt;&lt; '\\n';\n }\n</code></pre>\n</li>\n<li><p>Don't use <code>std::endl</code> when all you need is a newline. Flushing the output buffer every line unnecessarily slows the program.</p>\n</li>\n<li><p>There's no point calling <code>ofstream::close()</code> unless we are going to check the state of the stream before it goes out of scope.</p>\n</li>\n</ul>\n<hr />\n<h1>Summary</h1>\n<ul>\n<li>Create and use specific types, and enable each to read and write itself.</li>\n<li>Improve the error checking and reporting.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T09:23:02.150", "Id": "269601", "ParentId": "269598", "Score": "10" } }, { "body": "<h1>Don't overuse <code>std::vector</code></h1>\n<p>You are using <code>std::vector</code> for many things that shouldn't be vectors. For example, storing a single vertex should be done in a <code>struct</code> that holds the x, y and z coordinates:</p>\n<pre><code>struct dvec3 {\n double x;\n double y;\n double z;\n};\n</code></pre>\n<p>I named it <code>dvec3</code> because it is a vector (in the <a href=\"https://en.wikipedia.org/wiki/Vector_(mathematics_and_physics)\" rel=\"noreferrer\">mathematical sense</a>) of 3 <code>double</code>s, and it follows the naming convention of <a href=\"https://www.khronos.org/opengl/wiki/Data_Type_(GLSL)\" rel=\"noreferrer\">GLSL</a>.\nInside <code>class trimesh</code>, you can then store the list of vertices like so:</p>\n<pre><code>std::vector&lt;dvec3&gt; vertices;\n</code></pre>\n<p>And when reading a vertex:</p>\n<pre><code>dvec3 vertex;\nvertex.x = std::stod(vec_line[1]);\nvertex.y = std::stod(vec_line[2]);\nvertex.z = std::stod(vec_line[3]);\nvertices.push_back(vertex);\n</code></pre>\n<p>Everything that has a fixed number of elements should probably not be a <code>std::vector</code>. For texture coordinates you should create a <code>struct dvec2</code>,\nfor the vertex indices you should create a <code>struct ivec3</code>.</p>\n<p>I strongly recommend you use the <a href=\"https://github.com/g-truc/glm\" rel=\"noreferrer\">OpenGL Mathematics library</a>, as it provides all these types for you.</p>\n<p>Finally, splitting the string into the vector <code>vec_line</code> is also not necessary. Consider that you can rewrite the parsing code like so:</p>\n<pre><code>std::istringstream in(line);\n\nchar type;\nin &gt;&gt; type;\n\nswitch (type) {\ncase 'v':\n{\n dvec3 vertex;\n in &gt;&gt; vertex.x &gt;&gt; vertex.y &gt;&gt; vertex.z;\n vertices.push_back(vertex);\n break;\n}\ncase 't':\n ...\n</code></pre>\n<h1>Missing error checking</h1>\n<p>You check if opening the file was succesful, but you never check if it was completely read or written without errors. You can check if a file was completely read by checking that <code>file.eof()</code> is <code>true</code> after reading in all the lines. When writing files, you can check whether <code>file.bad()</code> is <code>false</code>.</p>\n<h1>Use range-<code>for</code> where appropriate</h1>\n<p>Since C++11 you can iterate over containers much easier using range-<code>for</code> notation. For example, when writing out all the vertices:</p>\n<pre><code>for (auto &amp;vertex: vertices)\n outdata &lt;&lt; &quot;v &quot; &lt;&lt; vertex.x &lt;&lt; ' ' &lt;&lt; vertex.y &lt;&lt; ' ' &lt;&lt; vertex.z &lt;&lt; '\\n';\n</code></pre>\n<h1>Use <code>\\n</code> instead of <code>std::endl</code></h1>\n<p>Prefer using <a href=\"https://stackoverflow.com/questions/213907/stdendl-vs-n\"><code>\\n</code> instead of <code>std::endl</code></a>. The latter is equivalent to the former, except it also forces the output to be flushed, which is usually not necessary and is bad for performance.</p>\n<h1>Pass string by reference when appropriate</h1>\n<p>Strings can be large, and if you pass them by value to a function, a copy has to be made. You can avoid that by passing them as <code>const</code> references:</p>\n<pre><code>void trimesh::load(const std::string &amp;filename)\n{\n ...\n</code></pre>\n<h1>How to handle errors</h1>\n<p>If opening the file did not succeed, your code does:</p>\n<pre><code>printf (&quot;loading obj: %s doesn't exists!\\n&quot;, filename.c_str());\nthrow;\n</code></pre>\n<p>This has several issues, the least of them is using the C <code>printf()</code> function when you should just use the C++ way if printing in C++ code.\nSecond, always print error messages to the standard error output, so:</p>\n<pre><code>std::cerr &lt;&lt; &quot;Loading obj file failed: &quot; &lt;&lt; filename &lt;&lt; &quot; does not exist!\\n&quot;;\n</code></pre>\n<p>But worst is <a href=\"https://en.cppreference.com/w/cpp/language/throw\" rel=\"noreferrer\"><code>throw</code></a>. This doesn't even throw an exception, it is meant to <em>rethrow</em> an exception. If there is no active exception, this will just immediately terminate the process. There is no way for the caller to catch this.</p>\n<p>The proper way is to throw an exception object that is one of the <a href=\"https://en.cppreference.com/w/cpp/error/exception\" rel=\"noreferrer\">standard exception types</a>, or a custom type that inherits from one of the standard ones. Almost always, you can just use <code>std::runtime_error</code>, like so:</p>\n<pre><code>throw std::runtime_error(&quot;Could not load obj file&quot;);\n</code></pre>\n<p>This allows the caller to catch the exception and handle it gracefully if so\ndesired.</p>\n<p>Alternatively, you could have the <code>load()</code> and <code>save()</code> member functions return a <code>bool</code> or another type that can indicate success or failure.</p>\n<h1>Pass <code>std::istream</code> and <code>std::ostream</code> instead of filenames</h1>\n<p>Your <code>load()</code> and <code>save()</code> functions expect to be given a filename, and those functions will take care of opening the file. Consider however passing a reference to a <code>std::istream</code> or <code>std::ostream</code> object instead. This means these functions no longer have the responsibility of opening the file, but also that they are much more flexible; they could read or write from any stream, not just files. For example, you can rewrite the <code>save()</code> function like so:</p>\n<pre><code>void trimesh::save(std::ostream &amp;outdata, const bool with_color, const bool with_vt)\n{\n if (with_color &amp;&amp; vertices.size() == vert_color.size())\n {\n ...\n</code></pre>\n<p>And then the caller can either take care of opening the file:</p>\n<pre><code>trimesh mesh;\n...\nofstream outdata(&quot;path/to/data.obj&quot;);\nmesh.save(outdata, true, true);\n</code></pre>\n<p>But if it wanted to print the mesh to the terminal instead, it can just do:</p>\n<pre><code>mesh.save(std::cout, true, true);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T10:44:04.997", "Id": "531921", "Score": "0", "body": "Thanks @G. Sliepen for your patient of checking my codes and give me so many valueble suggestions. Excellent skill of C++" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T17:45:07.310", "Id": "532077", "Score": "0", "body": "due to the struggles of glsl with dealing with packed vec3 data, I suggest just making your vector a vec4 and not using the 4th component (maybe you can store some other type of information in that component later, like normals or material info)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T09:28:44.823", "Id": "269602", "ParentId": "269598", "Score": "5" } } ]
{ "AcceptedAnswerId": "269601", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T06:59:13.363", "Id": "269598", "Score": "6", "Tags": [ "c++", "beginner", "file" ], "Title": "Read and write triangulated surfaces" }
269598
<p>Last night I was practicing incrementing strings. What it needs to do is increment the last character if it is a digit or letter. Special characters are ignored.</p> <p>The code that I have written does the job but I have a feeling it can be accomplished in a more elegant way. Or a faster way.</p> <p>Can somebody suggest faster, easier, more elegant approaches.</p> <p>Below the code I have written:</p> <pre><code>public static string Increment(this String str) { var charArray = str.ToCharArray(); for(int i = charArray.Length - 1; i &gt;= 0; i--) { if (Char.IsDigit(charArray[i])) { if(charArray[i] == '9') { charArray[i] = '0'; continue; } charArray[i]++; break; } else if(Char.IsLetter(charArray[i])) { if(charArray[i] == 'z') { charArray[i] = 'a'; continue; } else if(charArray[i] == 'Z') { charArray[i] = 'A'; continue; } charArray[i]++; break; } } return new string(charArray); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T11:09:13.507", "Id": "531924", "Score": "1", "body": "Is the intent to alter only the *last* character in the string or *each* character or the last known letter or digit, which may not be the last character in the string. Perhaps you could provide some examples of before and after strings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T19:34:26.977", "Id": "531981", "Score": "0", "body": "Your code fails to increment `999` and `ZZZ` correctly. I would have expected `1000` and `AAAA`. but it shouldn't be too hard to fix =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T07:04:04.127", "Id": "532015", "Score": "0", "body": "@RickDavin, It is intended to only alter the last character of the string. For example A1A becomes A1B, H98 becomes H99 etc. It is intended to only go up to the number of characters in the orignal string. So what upkajdt says is true but intended." } ]
[ { "body": "<p><strong>Update 2</strong></p>\n<p>Correct increment when invalid char (not digit nor letter) between valid chars.</p>\n<p><strong>Update</strong></p>\n<p>Without changing too much of code, you could solve it by using the mod operator. And by the tip from @upkajdt, it would be:</p>\n<pre><code>public static string Increment(string str)\n{\n var charArray = str.ToCharArray();\n for (int i = charArray.Length - 1; i &gt;= 0; i--)\n {\n if (Char.IsDigit(charArray[i]))\n {\n charArray[i] = (char)((charArray[i] + 1 - '0') % 10 + '0');\n }\n else if (Char.IsLower(charArray[i]))\n {\n charArray[i] = (char)((charArray[i] + 1 - 'a') % 26 + 'a');\n }\n else if (Char.IsUpper(charArray[i]))\n {\n charArray[i] = (char)((charArray[i] + 1 - 'A') % 26 + 'A');\n }\n else \n { \n continue;\n }\n if (charArray[i] == '0' || charArray[i] == 'a' || charArray[i] == 'A')\n continue;\n break;\n }\n return new string(charArray);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T20:34:54.897", "Id": "531985", "Score": "0", "body": "I don't think this is exactly what the OP had in mind, although I'm not really sure what he trying to accomplish =) You know that in C# you can also use character constants such as `charArray[i] = (char)((charArray[i] + 1 - 'a') % 26 + 'a');`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T21:29:53.383", "Id": "531996", "Score": "0", "body": "I assumed this was what OP meant, because he said \"The code that I have written does the job\". Nice tip to use char constants." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T21:46:19.557", "Id": "531998", "Score": "0", "body": "The code in the question looks *incrementing a big-endian mixed base-26/10 number*: start at the last \"digit\", proceed to preceding digit when there was \"a wrap-around/overflow/carry\", only. `The breaks you are using are not necessary` they are quintessential, on the contrary, while not indispensable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T22:33:07.293", "Id": "532000", "Score": "0", "body": "@greybeard, i agree with most of what you say but fail to see how endianness is relevant here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T00:09:19.767", "Id": "532007", "Score": "0", "body": "@greybeard I know get what the OP meant, I will modify my code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T05:19:29.167", "Id": "532012", "Score": "1", "body": "Relevance of endianness: You start with the least significant \"digit\" and propagate carries in the direction of increasing significance. When the least significant end is the last, the first is the most significant: big-endian (and loop from *length* down). (No relation to or relevance of the endianness of the runtime-platform.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T13:30:54.150", "Id": "532047", "Score": "0", "body": "@IbramReda I just had updated my answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T13:35:51.460", "Id": "532048", "Score": "0", "body": "@takihama I was posting before the update ... now this method passes the unit tests, but the method become a little hard to read" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T19:44:37.577", "Id": "269621", "ParentId": "269604", "Score": "0" } }, { "body": "<p>Whenever you get a non-elegant method, first thing, try to break your logic into smaller logic</p>\n<pre><code> private static bool isMaxChar(this char ch)\n {\n return ch == '9' || ch == 'z' || ch == 'Z';\n }\n\n public static char Increment(this char ch)\n {\n if (Char.IsDigit(ch))\n return (char)((ch + 1 - '0') % 10 + '0');\n if (Char.IsLower(ch))\n return (char)((ch + 1 - 'a') % 26 + 'a');\n if (Char.IsUpper(ch))\n return (char)((ch + 1 - 'A') % 26 + 'A');\n\n return ch;\n }\n</code></pre>\n<p>by using the above helper methods, your code will be clearer and elegant</p>\n<pre><code> public static string Increment(this String str)\n {\n var charArray = str.ToCharArray();\n for (int i = charArray.Length - 1; i &gt;= 0; i--)\n {\n char originalChar = charArray[i];\n charArray[i] = charArray[i].Increment();\n\n if (!originalChar.isMaxChar() &amp;&amp; char.IsLetterOrDigit(originalChar))\n break; // break when update the first alphanumeric char and it's not a max char \n }\n return new string(charArray);\n }\n</code></pre>\n<p>I have written unit tests and run against the above code, and it gives the same results as your code</p>\n<pre><code>[Theory]\n[InlineData(&quot;a&quot;, &quot;b&quot;)]\n[InlineData(&quot;z&quot;, &quot;a&quot;)]\n[InlineData(&quot;c&quot;, &quot;d&quot;)]\n\n[InlineData(&quot;az&quot;, &quot;ba&quot;)]\n[InlineData(&quot;a9&quot;, &quot;b0&quot;)]\n\n[InlineData(&quot;a1a&quot;, &quot;a1b&quot;)]\n[InlineData(&quot;AAA&quot;, &quot;AAB&quot;)]\n[InlineData(&quot;abc&quot;, &quot;abd&quot;)]\n\n[InlineData(&quot;H98&quot;, &quot;H99&quot;)]\n[InlineData(&quot;H99&quot;, &quot;I00&quot;)]\n[InlineData(&quot;a99&quot;, &quot;b00&quot;)]\n[InlineData(&quot;I00&quot;, &quot;I01&quot;)]\n[InlineData(&quot;azz&quot;, &quot;baa&quot;)]\n\n[InlineData(&quot;bl9Zz&quot;, &quot;bm0Aa&quot;)]\n\n[InlineData(&quot;zzz&quot;, &quot;aaa&quot;)]\n[InlineData(&quot;ZZZ&quot;, &quot;AAA&quot;)]\n[InlineData(&quot;999&quot;, &quot;000&quot;)]\n[InlineData(&quot;z99&quot;, &quot;a00&quot;)]\n\n[InlineData(&quot;__a__&quot;, &quot;__b__&quot;)]\n[InlineData(&quot;__z__&quot;, &quot;__a__&quot;)]\npublic void stringIncremental(string input, string expected)\n{\n string result = input.Increment();\n Assert.Equal(result, expected);\n\n}\n\n[Theory]\n[InlineData('a', 'b')]\n[InlineData('z', 'a')]\n[InlineData('c', 'd')]\n[InlineData('k', 'l')]\n\n[InlineData('A', 'B')]\n[InlineData('Z', 'A')]\n[InlineData('G', 'H')]\n[InlineData('K', 'L')]\n\n[InlineData('1', '2')]\n[InlineData('9', '0')]\n[InlineData('0', '1')]\n[InlineData('5', '6')]\n\n[InlineData('%', '%')]\n[InlineData('-', '-')]\n[InlineData('_', '_')]\n[InlineData('/', '/')]\npublic void charIncremental(char input, char expected)\n{\n char result = input.Increment();\n Assert.Equal(result, expected);\n}\n\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T08:55:28.557", "Id": "269628", "ParentId": "269604", "Score": "2" } } ]
{ "AcceptedAnswerId": "269628", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T09:46:00.393", "Id": "269604", "Score": "3", "Tags": [ "c#", "strings" ], "Title": "string increment" }
269604
<p><strong>Hello everyone.</strong></p> <p>I wrote my own test module, which is responsible for measuring the timing of algorithms, I used it mainly for sorting algorithms this is so to say a very early beta version, which I would like to expand with various functionalities, in general I would like to take care of the appearance of the code. I look forward to your opinions and comments, possibly your own ideas.</p> <p>So here is my testing_module code:</p> <pre><code>import random import matplotlib.pyplot as plt accident = [&quot;x&quot;, &quot;random.randint(1, 100)&quot;, &quot;x&quot;] history = [&quot;Optimistic&quot;, &quot;Average&quot;, &quot;Pessimistic&quot;] def make_data(numbers, y): data = [] for element in numbers: data.append([eval(accident[y]) for x in range(element)]) return data def make_plot(numbers, measures, name): for x in range(3): plt.plot(numbers, measures[x], label = history[x]) plt.title(name) plt.legend() plt.show() def test(method, numbers, measures): name_function = method.__name__ for x in range(3): if x != 2: for element in make_data(numbers, x): method(element, x) else: for element in make_data(numbers, x): element.reverse() method(element, x) make_plot(numbers, measures, name_function) </code></pre> <p>And this is how i was using it in my code:</p> <pre><code>import testing_module as test import time measures = [[], [], []] numbers = [10, 100, 300, 500, 700] def insertion_sort(array, x=0): start = time.time() for j in range(1, len(array)): key = array[j] i = j - 1 while (i &gt; -1) and key &lt; array[i]: array[i + 1] = array[i] i = i - 1 array[i + 1] = key end = time.time() measures[x].append(end - start) test.test(insertion_sort, numbers, measures) </code></pre> <p>Thanks in advance for any tips and ideas how to improve my solution. <em><strong>Have a great day!</strong></em></p>
[]
[ { "body": "<p>If I had to summarise this code, it would be: magical, spooky and puzzling. It works (which is a great start!) but you can make life easier on yourself and your maintainers.</p>\n<p>You've invoked the root of all <code>eval</code>. Don't do this. There are many, many alternatives; the one I'll show uses simple polymorphism.</p>\n<p>Many of your variable names need work. <code>element</code> is actually equivalent to your <code>array</code>; <code>numbers</code> is actually <code>lengths</code>; <code>accident</code> is really a sequence of test series generators.</p>\n<p>Reduce your reliance on inferred figures and axes via the <code>plt.</code> functions, and instead use your figure and axis objects explicitly.</p>\n<p>Avoid forcing a <code>plt.show()</code> inside of your <code>make_plot</code>; let the caller decide what to do with the figure.</p>\n<p>Do not use <code>plot()</code>. For these data, <code>Optimistic</code> is basically flat. Use <code>loglog</code> instead.</p>\n<p>Do not do timing and <code>measures</code> construction on the inside of your UUT (unit under test).</p>\n<p>Do not call <code>test.test</code> from with the global namespace; use a <code>__main__</code> guard. Similarly, do not leave <code>measures</code> and <code>numbers</code> in the global namespace.</p>\n<p>Introduce PEP484 type hints.</p>\n<p>Avoid calling <code>reverse()</code>. Your generated test series are just as easily made via <code>range</code> calls, which will be more efficient and avoid mutation.</p>\n<h2>Suggested</h2>\n<pre><code>from random import randrange\nfrom time import time\nfrom typing import Callable, Iterable, List, Iterator, Sequence, Tuple\n\nimport matplotlib.pyplot as plt\n\n\nMethod = Callable[[List[int]], None]\n\n\nclass History:\n def __init__(self, lengths: Sequence[int], method: Method) -&gt; None:\n self.measures: Tuple[float] = tuple(self.test(lengths, method))\n\n @staticmethod\n def make_data(length: int) -&gt; Iterable[int]:\n raise NotImplementedError()\n\n @classmethod\n def test(cls, lengths: Sequence[int], method: Method) -&gt; Iterator[float]:\n for length in lengths:\n array = list(cls.make_data(length))\n start = time()\n method(array)\n end = time()\n yield end - start\n\n\nclass Optimistic(History):\n @staticmethod\n def make_data(length: int) -&gt; Iterable[int]:\n return range(length)\n\n\nclass Pessimistic(History):\n @staticmethod\n def make_data(length: int) -&gt; Iterable[int]:\n return range(length-1, -1, -1)\n\n\nclass Average(History):\n @staticmethod\n def make_data(length: int) -&gt; Iterable[int]:\n for _ in range(length):\n yield randrange(1000)\n\n\ndef make_plot(\n lengths: Sequence[int],\n histories: Iterable[History],\n name: str,\n) -&gt; plt.Figure:\n fig, ax = plt.subplots()\n for history in histories:\n ax.loglog(lengths, history.measures, label=type(history).__name__)\n ax.set_title(name)\n ax.legend()\n return fig\n\n\ndef test(\n method: Method,\n lengths: Sequence[int],\n) -&gt; Iterator[History]:\n for history_t in (Optimistic, Average, Pessimistic):\n yield history_t(lengths, method)\n\n\ndef insertion_sort(array: List[int]) -&gt; None:\n for j in range(1, len(array)):\n key = array[j]\n i = j - 1\n while (i &gt; -1) and key &lt; array[i]:\n array[i + 1] = array[i]\n i = i - 1\n array[i + 1] = key\n\n\ndef main() -&gt; None:\n lengths = (10, 100, 300, 500, 700)\n histories = test(method=insertion_sort, lengths=lengths)\n make_plot(\n lengths=lengths, histories=histories,\n name=insertion_sort.__name__,\n )\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/l3KPH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/l3KPH.png\" alt=\"plot\" /></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T23:18:41.900", "Id": "532312", "Score": "1", "body": "Perhaps useful if OP is not used to working with figure/axes: [pyplot vs object-oriented interface](https://matplotlib.org/matplotblog/posts/pyplot-vs-object-oriented-interface/#pyplot-vs-object-oriented-interface)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T21:56:46.357", "Id": "533158", "Score": "0", "body": "I was testing it right now on the Python 3.9.8 and results are pretty weird... Everything's fine on 3.6.7" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T22:42:36.677", "Id": "269748", "ParentId": "269611", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T13:08:58.633", "Id": "269611", "Score": "2", "Tags": [ "python" ], "Title": "Testing module for measuring time of function" }
269611
<p>My mission is to solve this:</p> <blockquote> <p>Write a function that will take an array of numbers, and will return the average of all numbers in the array that are prime number.</p> </blockquote> <p>So far I wrote this:</p> <pre><code>function average(a){ var arr=[]; var newarr=[]; var i,j,sum,sum1,average,counter,counter1; counter=counter1=sum=sum1=0; for(i=0;i&lt;a.length;i++){ for(j=2;j&lt;(Math.floor(a[i]/2));j++){ if((a[i]%j===0) &amp;&amp; (a[i]&gt;2)){ arr.push(a[i]); break; } } } for(i=0;i&lt;a.length;i++){ sum=sum+a[i]; counter++; } for(i=0;i&lt;arr.length;i++){ sum1=sum1+arr[i]; counter1++; } average=(sum-sum1)/(counter-counter1); return average; } var a=[88,44,32,30,31,19,74,169,143,109,144,191]; console.log(average(a)); </code></pre> <p>I am allowed to use only: conditions (<code>if</code>), loops, <code>--</code>, <code>++</code>, <code>%</code>, <code>/</code>, <code>*</code>, <code>-</code>, <code>+</code>, <code>==</code>, <code>=!</code>, <code>=&gt;</code>, <code>&gt;</code>, <code>=&lt;</code>, <code>&lt;</code>, <code>||</code>, <code>&amp;&amp;</code>, <code>=%</code>, <code>=/</code>, <code>=*</code>, <code>+-</code>, <code>=+</code>, <code>array.length</code>, <code>array.pop()</code> and <code>concat</code>.</p> <p>Any suggestions? Feedback on what I wrote? Thank you!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T18:04:00.517", "Id": "531977", "Score": "1", "body": "I think `=!`, `=+` and many others are not operators in JavaScript. Can you please double-check the description? (I suspect these should be `!=` and `+=`, respectively. There are several other odd ones too.) Also, I assume you can also use `function`, since you are in fact using it. Right?" } ]
[ { "body": "<h3>Single responsibility</h3>\n<p>Try to organize your programs in a way that every function has a single responsibility. For example checking if a number is a prime or not stands out here as a clear example that should be in its own function:</p>\n<pre><code>function isPrime(num) {\n var factor;\n for (factor = 2; factor &lt; Math.floor(num / 2); factor++) {\n if (num % factor == 0) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n<h3>Simplify the logic</h3>\n<p>The code implements the following algorithm:</p>\n<ul>\n<li>Build an array of non-primes</li>\n<li>Compute the sum of all values</li>\n<li>Compute the sum of non-primes</li>\n<li>Subtract the sum of non-primes from the sum of all numbers, and divide this by the count of non-primes</li>\n</ul>\n<p>Consider the simpler alternative:</p>\n<ul>\n<li>Compute the sum of primes, and also count them</li>\n<li>Return the sum of primes divided by their count</li>\n</ul>\n<p>This alternative is matches well the problem description too,\nso it's easy to understand. And so is the code.</p>\n<pre><code>function average(nums) {\n var i;\n var sum = 0;\n var count = 0;\n\n for (i = 0; i &lt; nums.length; i++) {\n if (isPrime(nums[i])) {\n sum += nums[i];\n count++;\n }\n }\n\n return sum / count;\n}\n</code></pre>\n<h3>Use better names</h3>\n<p>The code is very hard to read because most of the variable names don't describe well their purpose, for example:</p>\n<ul>\n<li><code>arr</code> stores non-prime numbers -&gt; <code>nonPrimes</code> would describe this</li>\n<li><code>a</code> is an array of numbers -&gt; <code>nums</code> would describe this</li>\n<li><code>newarr</code>... is not even used -&gt; should not be there</li>\n<li>And so on! (<code>counter1</code>, <code>sum1</code> are poor names too, more on that later</li>\n</ul>\n<h3>Avoid unnecessary array creation</h3>\n<p>The code used <code>arr</code> to collect non-primes,\nto compute their sum in a next step.\nYou could compute the sum directly, without building an array for it.</p>\n<p>Creating arrays consumes memory, and therefore can be expensive, and can make your program inefficient.\nWhen there is an easy way to avoid it, then avoid it.</p>\n<h3>Use whitespace more generously</h3>\n<p>This is hard to read:</p>\n<blockquote>\n<pre><code>for(i=0;i&lt;a.length;i++){\n</code></pre>\n</blockquote>\n<p>This is much easier to read, and a widely used writing style:</p>\n<pre><code>for (i = 0; i &lt; a.length; i++) {\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T18:46:18.680", "Id": "269618", "ParentId": "269613", "Score": "5" } } ]
{ "AcceptedAnswerId": "269618", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T14:11:29.777", "Id": "269613", "Score": "3", "Tags": [ "javascript", "array", "primes" ], "Title": "Average prime number from array- Javascript" }
269613
<p>I need to estimate risk differences for marginal models. I have worked on the <a href="https://rdrr.io/cran/epitools/src/R/probratio.r" rel="nofollow noreferrer">Probratio function</a> to create an equivalent function for RDs that works.</p> <p>Please provide feedback on accuracy or comments to improve efficiency where necessary.</p> <pre><code> probdiff &lt;- function(object, parm, subset, method=c('ML', 'delta', 'bootstrap'), scale='linear', level=0.95, seed, NREPS=1000, ...) { if (length(match('glm', class(object))) &lt; 0) stop('Non GLM input to &quot;object&quot;') if (family(object)$family != 'binomial') stop('object not a logistic regression model') nc &lt;- length(cf &lt;- coef(object)) if (missing(subset)) subset &lt;- T if (missing(parm)) parm &lt;- seq(2, nc) cf &lt;- cf[parm] method &lt;- match.arg(method, c('ML', 'delta', 'bootstrap')) scale &lt;- 'linear' if (is.na(scale)) stop('scale cannot take values outside of linear') if (scale == 'linear') { f &lt;- function(x) x[2] - x[1] name &lt;- c('Risk difference') null &lt;- 0 } else{ (is.na(scale)) stop('scale cannot take values outside of linear') } cilevel &lt;- c({1-level}/2, 1-{1-level}/2) ciname &lt;- paste0(c('Lower', 'Upper'), ' ', formatC(100*cilevel, format='f', digits=1), '% CI') if (method == 'ML') { newfit &lt;- glm(object, family=binomial(link=&quot;identity&quot;), subset=subset, ...) out &lt;- coef(summary(newfit))[parm, , drop=F] if (scale == 'linear') { out &lt;- cbind(out[, 1], out[, 2], out[, 3], out[, 4], out[, 1] + qnorm((1-level)/2)*out[, 2], out[, 1] + qnorm(1-(1-level)/2)*out[, 2]) } else { newfit &lt;- glm(object, family=gaussian(link = &quot;identity&quot;), subset=subset, ...) if (family(object)$family != 'binomial') out &lt;- coef(summary(newfit))[parm, , drop=F] out = lmtest::coeftest(out, vcov.=sandwich::vcovHC(out, type=&quot;HC3&quot;)) val &lt;- out[, 1] se &lt;- val * out[, 2] out &lt;- cbind(val, se, z &lt;- abs(val-1)/se, pnorm(z, lower.tail = F)*2, val + qnorm((1-level)/2)*se, val + qnorm(1-(1-level)/2)*se) } colnames(out) &lt;- c(name, 'Std. Error', 'Z-value', 'p-value', ciname) return(out) }## endif MLe code here Mod1 &lt;- Mod0 &lt;- model.matrix(object)[subset, ] n &lt;- nrow(Mod0) Nvec &lt;- matrix(rep(c(1/n,0,0,1/n),each=n), n*2, 2) if (method == 'delta') { if (scale == 'linear') { df &lt;- deriv( ~y/x, c('x', 'y')) # y depends on x } out &lt;- sapply(parm, function(p) { Mod0[, p] &lt;- 0 Mod1[, p] &lt;- 1 Mod &lt;- rbind(Mod0, Mod1) allpreds &lt;- family(object)$linkinv(Mod %*% coef(object)) avgpreds &lt;- t(Nvec) %*% allpreds val &lt;- f(avgpreds) V &lt;- sweep(chol(vcov(object)) %*% t(Mod), allpreds*(1-allpreds), '*', MARGIN = 2) %*% Nvec V &lt;- t(V) %*% V dxdy &lt;- matrix(attr(eval(df, list('x'=avgpreds[1], 'y'=avgpreds[2])), 'gradient')) se &lt;- sqrt(t(dxdy) %*% V %*% dxdy) out &lt;- c(val, se, z &lt;- abs({val-null}/se), 2*pnorm(abs(val/se), lower.tail=FALSE), val + qnorm(cilevel[1])*se, val + qnorm(cilevel[2])*se) names(out) &lt;- c(name, 'Std. Error', 'Z-value', 'p-value', ciname) out }) # / sqrt( n ) out &lt;- t(out) rownames(out) &lt;- names(cf) return(out) } ## endif deltaMod1 &lt;- Mod0 &lt;- model.matrix(object)[subset, ] n &lt;- nrow(Mod0) Nvec &lt;- matrix(rep(c(1/n,0,0,1/n),each=n), n*2, 2) if (method == 'delta') { if (scale == 'linear') { df &lt;- deriv( ~y/x, c('x', 'y')) # y depends on x } out &lt;- sapply(parm, function(p) { Mod0[, p] &lt;- 0 Mod1[, p] &lt;- 1 Mod &lt;- rbind(Mod0, Mod1) allpreds &lt;- family(object)$linkinv(Mod %*% coef(object)) avgpreds &lt;- t(Nvec) %*% allpreds val &lt;- f(avgpreds) V &lt;- sweep(chol(vcov(object)) %*% t(Mod), allpreds*(1-allpreds), '*', MARGIN = 2) %*% Nvec V &lt;- t(V) %*% V dxdy &lt;- matrix(attr(eval(df, list('x'=avgpreds[1], 'y'=avgpreds[2])), 'gradient')) se &lt;- sqrt(t(dxdy) %*% V %*% dxdy) out &lt;- c(val, se, z &lt;- abs({val-null}/se), 2*pnorm(abs(val/se), lower.tail=FALSE), val + qnorm(cilevel[1])*se, val + qnorm(cilevel[2])*se) names(out) &lt;- c(name, 'Std. Error', 'Z-value', 'p-value', ciname) out }) # / sqrt( n ) out &lt;- t(out) rownames(out) &lt;- names(cf) return(out) } ## endif delta code here if (method == 'bootstrap') { if (missing(seed)) stop('seed must be supplied by the user when obtaining results from random number generation') set.seed(seed) out &lt;- replicate(NREPS, { index &lt;- sample(1:n, n, replace=T) Mod &lt;- model.matrix(object)[subset, ][index, ] newbeta &lt;- glm.fit(Mod, object$y[index], family=binomial())$coef out &lt;- sapply(parm, function(p) { Mod1 &lt;- Mod0 &lt;- Mod Mod1[, p] &lt;- 1 Mod0[, p] &lt;- 0 Mod &lt;- rbind(Mod0, Mod1) newpreds &lt;- family(object)$linkinv(Mod %*% newbeta) f(t(Nvec) %*% newpreds) }) out }) if (length(parm) == 1) { out &lt;- c(val &lt;- mean(out), se &lt;- sd(out), z &lt;- abs({val - null}/se), 2*pnorm(abs(val/se), lower.tail=FALSE), val + qnorm((1-level)/2)*se, val + qnorm(1-(1-level)/2)*se) names(out) &lt;- c(name, 'Std. Error', 'Z-value', 'p-value', ciname) } else { out &lt;- cbind(val &lt;- rowMeans(out), se &lt;- apply(out, 1, sd), z &lt;- abs({val - null}/se), 2*pnorm(abs(val/se), lower.tail=FALSE), val + qnorm(cilevel[1])*se, val + qnorm(cilevel[2])*se) colnames(out) &lt;- c(name, 'Std. Error', 'Z-value', 'p-value', ciname) rownames(out) &lt;- names(cf) } return(out) } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T17:06:31.587", "Id": "531971", "Score": "2", "body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/revisions/269614/3) 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." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T14:46:53.793", "Id": "269614", "Score": "1", "Tags": [ "performance", "r" ], "Title": "Estimating risk differences for marginal models" }
269614
<h1>Abstract</h1> <p>The bash shell utility <code>mkdir</code> is a tool used to create directories in most POSIX environments. I thought it would be fun to implement such functionality from C++ and maybe forge in some of my own features in the future. I will be using the C++ library Boost to handle the command line options and the Standard Template Libary (std) to work work with the filesystem. I would appreciate some sustains, nays, and comments on the 50 so lines of code I have written.</p> <h1>Code</h1> <p>mkdir.cpp</p> <pre><code>#include &lt;boost/program_options.hpp&gt; namespace po = boost::program_options; #include &lt;filesystem&gt; #include &lt;iostream&gt; #include &lt;string.h&gt; #include &lt;string&gt; #include &lt;vector&gt; // Define the LOG() macro in order to be able to add // a logger in the future without too much refactoring //#define LOG(x) BOOST_LOG_TRIVIAL(x) #define LOG(x) std::cout int main(int argc, char **argv) { // Declare the supported options. po::options_description desc(&quot;Allowed options&quot;); desc.add_options() (&quot;help,h&quot;, &quot;produce help message&quot;) (&quot;parents,p&quot;, po::bool_switch(), &quot;no error if existing, make parent directories as needed&quot;) (&quot;verbose,v&quot;, po::bool_switch(), &quot;print a message for each created directory&quot;); const po::parsed_options parsed = po::command_line_parser(argc, argv) .options(desc).allow_unregistered().run(); const std::vector&lt;std::string&gt; unrecognized = collect_unrecognized(parsed.options, po::include_positional); po::variables_map vm; po::store(parsed, vm); po::notify(vm); for (const auto &amp;opt : unrecognized) { if (opt[0] == '-') { LOG(error) &lt;&lt; &quot;Unknown option '&quot; &lt;&lt; opt &lt;&lt; &quot;'\n&quot;; return 1; } } if (vm.count(&quot;help&quot;) || argc &lt;= 1) { LOG(info) &lt;&lt; desc; return 1; } std::error_code ec; for (const auto &amp;dir_name : unrecognized) { auto path = std::filesystem::absolute(std::filesystem::path(dir_name)); if (vm[&quot;parents&quot;].as&lt;bool&gt;()) std::filesystem::create_directories(path, ec); else std::filesystem::create_directory(path, ec); if (errno) { LOG(error) &lt;&lt; &quot;Cannot create directory '&quot; &lt;&lt; dir_name &lt;&lt; &quot;': &quot; &lt;&lt; strerror(errno) &lt;&lt; '\n'; errno = 0; } else { LOG(info) &lt;&lt; &quot;Created directory '&quot; &lt;&lt; dir_name &lt;&lt; &quot;'\n&quot;; } } return 0; } </code></pre> <h2>Try it!</h2> <p>In order to compile this utility the following packages are needed:</p> <p><code>sudo apt install build-essential libboost-program-options-dev</code></p> <p>Then you can compile <code>mkdir.cpp</code> with:</p> <p><code>g++ mkdir.cpp -o mkdir -lboost_program_options -std=c++2a</code></p> <p>Then you can test it out with:</p> <p><code>./mkdir &lt;options&gt; &lt;directory names&gt;</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T21:27:02.760", "Id": "531994", "Score": "0", "body": "I was looking at Boost Log as I was already using boost; I had considered using spdlog or glog but decided to consolidate my sources when writing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T07:50:33.897", "Id": "532020", "Score": "1", "body": "I didn't want to post answer as I don't know C++ at all, but.. The `-m` option is missing, `mkdir -p foo` succeeds even when `foo` is a regular file, `mkdir -p foo/bar` prints an error message but actually works, `-lboost_options` doesn't work on Ubuntu (`-lboost_program_options` does), and `libboost-program-options-dev` takes 145 MB of disk space." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T14:23:00.127", "Id": "532054", "Score": "0", "body": "@oguzismail: Probably going to be disappointed, but presumably you could statically link `libboost-program-options-dev` so it wasn't a runtime dependency, and other users of pre-built binaries would only pay for the disk space consumed by the components actually used?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T14:45:40.970", "Id": "532055", "Score": "0", "body": "@ShadowRanger That's a huge improvement. The resulting binary is 2.5 megabytes in size (whereas `/bin/mkdir` is 88 kilobytes), but yeah, far better than having to install such a ridiculously large library for a program with such limited functionality. Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T15:24:24.143", "Id": "532058", "Score": "1", "body": "@oguzismail: Woo! Always nice to learn the library was written well enough that using parts of it doesn't pull the whole thing in for static linkage. If it provides fat LTO static libs, and the whole program is compiled with LTO enabled it might get even smaller (as it can extract *just* the functions/data it actually uses, inlining where it makes sense, making it even more granular than the \"per-object\" rules for non-LTO linkage)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T16:52:59.237", "Id": "532068", "Score": "0", "body": "@oguzismail I make a mistake with the linking instructions for boost program options, I have updated it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T18:22:39.720", "Id": "532083", "Score": "0", "body": "I would rename `unrecognized` to `remaining_args`, or something similar." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T03:18:00.830", "Id": "532115", "Score": "0", "body": "@AShelly yeah makes more sense." } ]
[ { "body": "<h3>Exit codes</h3>\n<p>Invoking the help of commands is usually not considered an error, so an exit code of 0 would be expected.</p>\n<p>When the real <code>mkdir</code> fails to create a directory, it exits with a non-zero value.</p>\n<h3>Decompose work to functions</h3>\n<p>Currently the <code>main</code> function does everything:</p>\n<ul>\n<li>Argument parsing</li>\n<li>Perform appropriate actions</li>\n</ul>\n<p>If you plan to build this further,\nit already makes sense to decompose a bit more now.</p>\n<h3>Unimplemented features</h3>\n<p>The verbose flag is not implemented ;-)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T19:06:09.263", "Id": "269619", "ParentId": "269616", "Score": "3" } }, { "body": "<p>Many filesystems allow directory name to start with <code>-</code>. To support such names (not just in the <code>mkdir</code> context, but in general) POSIX-compliant utility shall treat <code>--</code> as an &quot;end-of-options&quot; option.</p>\n<p>Boost supports this idea. Everything after <code>--</code> is treated as a positional argument. However, as you <code>include_positional</code> while collecting unrecognized, the program still treat such directories as options, and refuses to process them.</p>\n<hr />\n<p>Since you use the <code>error_code</code> overload, you should use <code>ec</code>, rather than <code>errno</code> to report errors. And if you do want to use <code>errno</code>, you should not rely on <code>&lt;cerrno&gt;</code> being magically included, but <code>#include &lt;cerrno&gt;</code> explicitly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T21:15:26.323", "Id": "531992", "Score": "0", "body": "I had no idea about the end of options option! also, I will revise it to use std::error_code" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T19:23:10.293", "Id": "269620", "ParentId": "269616", "Score": "7" } }, { "body": "<p>Use braces around one line in <code>if</code> blocks. See <a href=\"https://stackoverflow.com/questions/30311986/why-does-this-if-statement-require-brackets\">this Q&amp;A</a> and <a href=\"https://wiki.sei.cmu.edu/confluence/display/c/EXP19-C.+Use+braces+for+the+body+of+an+if%2C+for%2C+or+while+statement\" rel=\"nofollow noreferrer\">EXP19-C misra rule</a>.</p>\n<p>You do not need <code>return 0;</code> at the end. That is the default return value in C++ programs.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T18:21:41.003", "Id": "532082", "Score": "0", "body": "Although return 0 is not needed I would never suggest omitting it. Leaving it in make's it clear to the reader what is happening, rather than relying on them knowing the somewhat esoteric rule that `int main` doesn't need an explicit return value, but every other function that returns an int does." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T09:52:29.190", "Id": "269630", "ParentId": "269616", "Score": "2" } }, { "body": "<p>POSIX <code>mkdir</code> also supports the <code>-m</code> option for setting the permissions of the directory as it is created (avoiding race conditions). Consider supporting that as an enhancement.</p>\n<p>Since <code>std::filesystem</code> doesn't give expose that aspect of the <code>mkdir()</code> system call, you will need to call it directly (and perhaps <code>#ifdef</code> to support non-POSIX platforms). The alternative is a suitable call to <code>std::filesystem::permissions()</code> immediately after creating the directory, but that leaves a window of time in which the initial default permissions are effective. That's the kind of thing that leads to security bugs, and a weakness in <code>std::filesystem</code> if I'm correct.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T09:56:51.693", "Id": "269632", "ParentId": "269616", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T16:03:39.023", "Id": "269616", "Score": "7", "Tags": [ "c++" ], "Title": "C++ mkdir shell utility" }
269616
<p>I wrote a small program that connects to a minecraft rcon and provides an easy to use control panel. It is written in python 3.9 and uses the kivy module for the GUI.</p> <p>What could I improve in the code? Are the variable names easy to understand and if not, how could I improve them?</p> <p>Here is the main.py and the pmcp.kv:</p> <p>main.py:</p> <pre><code>from kivy.app import App from kivy.uix.boxlayout import BoxLayout from mcrcon import MCRcon as r from kivy.lang import Builder from kivy.resources import resource_add_path from kivy.properties import StringProperty import sys import os class MainWindow(BoxLayout): connection_refused = True while connection_refused: ip = str(input('enter ip or hostname of the server:\n&gt;')) try: port = int(input('enter the server port (default: 25575):\n&gt;')) if port not in range(0,65535+1): raise ValueError except ValueError: print('invalid value! using default.') port = 25575 pw = str(input('enter server password:\n&gt;')) try: with r (host=ip, port=port, password=pw) as mcr: mcr.command('list') connection_refused = False except ConnectionRefusedError: print('connection refused, try again!') connection_refused = True player_count = StringProperty('') selected_player = StringProperty('') lives_to_add = StringProperty('') def player_count_refresh(self): with r (host=self.ip, port=self.port, password=self.pw) as mcr: self.player_count = mcr.command('list') def selected_player_submit(self): self.selected_player = str(self.ids.textinput_selected_player.text) def player_heal(self): with r (host=self.ip, port=self.port, password=self.pw) as mcr: self.player_count = mcr.command('effect give '+self.selected_player+' minecraft:instant_health 1 50') def player_tp_to_spawn(self): with r (host=self.ip, port=self.port, password=self.pw) as mcr: self.player_count = mcr.command('tp '+self.selected_player+' 0 ~ 0') def player_add_lives(self): self.lives_to_add = str(self.ids.slider_player_lives_to_add.value) with r (host=self.ip, port=self.port, password=self.pw) as mcr: self.player_count = mcr.command('setlives '+self.selected_player+' '+self.lives_to_add) def player_revoke_progress(self): with r (host=self.ip, port=self.port, password=self.pw) as mcr: self.player_count = mcr.command('advancement revoke '+self.selected_player+' everything') def player_give_op(self): with r (host=self.ip, port=self.port, password=self.pw) as mcr: self.player_count = mcr.command('op '+self.selected_player) def player_revoke_op(self): with r (host=self.ip, port=self.port, password=self.pw) as mcr: self.player_count = mcr.command('deop '+self.selected_player) def player_kick(self): with r (host=self.ip, port=self.port, password=self.pw) as mcr: self.player_count = mcr.command('kick '+self.selected_player) class PyMinecraftContolPanel(App): def build(self): Builder.load_file('pmcp.kv') return MainWindow() if __name__ == '__main__': if hasattr(sys, '_MEIPASS'): resource_add_path(os.path.join(sys._MEIPASS)) PyMinecraftContolPanel().run() </code></pre> <p>pmcp.kv:</p> <pre><code>#:kivy 2.0.0 &lt;MainWindow&gt;: orientation: 'vertical' BoxLayout: orientation: 'horizontal' size_hint: 1,None size: 1, '60dp' Label: id: label_player_count text: root.player_count Button: id: button_player_count_refresh text: 'refresh' on_press: root.player_count_refresh() size_hint: None, None size: '60dp', '60dp' BoxLayout: orientation: 'horizontal' size_hint: 1,None size: 1, '60dp' TextInput: id: textinput_selected_player text: 'enter player to select:' multiline: False on_focus: self.text = '' Button: id: button_selected_player_submit text: 'select\nplayer' on_press: root.selected_player_submit() size_hint: None, None size: '60dp', '60dp' GridLayout: cols: 8 Button: id: button_player_heal text: 'heal player' on_press: root.player_heal() Button: id: button_player_tp_to_spawn text: 'tp to spawn' on_press: root.player_tp_to_spawn() Button: id: button_player_add_lives text: 'add lives' on_press: root.player_add_lives() BoxLayout: orientation: 'vertical' Label: text: 'lives\nto\nadd' size_hint_y: None size_hint_x: 1 text_size: self.width, None halign: 'center' Label: text: str(slider_player_lives_to_add.value) size_hint_y: None size_hint_x: 1 text_size: self.width, None halign: 'center' Slider: id: slider_player_lives_to_add min: 1 max: 10 step: 1 orientation: 'vertical' Button: id: button_player_revoke_progress text: 'revoke\nprogress' on_press: root.player_revoke_progress() Button: id: button_player_give_op text: 'give op' on_press: root.player_give_op() Button: id: button_player_revoke_op text: 'revoke op' on_press: root.player_revoke_op() Button: id: button_player_kick text: 'kick' on_press: root.player_kick() MainWindow: </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T16:54:54.447", "Id": "532390", "Score": "1", "body": "I have rolled back Rev 2 → 1. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)." } ]
[ { "body": "<p>It is unlikely that running the code from <code>connection_refused = True</code> onward in <code>MainWindow</code>'s static scope is a good idea. Maybe you intended on this being in the constructor? In which case you need an <code>__init__</code>.</p>\n<p>This loop:</p>\n<pre><code> connection_refused = True\n while connection_refused:\n # ...\n try:\n with r (host=ip, port=port, password=pw) as mcr: \n mcr.command('list')\n connection_refused = False\n except ConnectionRefusedError:\n print('connection refused, try again!')\n connection_refused = True\n</code></pre>\n<p>should not need a flag variable, and should instead be</p>\n<pre><code> while True:\n # ...\n try:\n with r (host=ip, port=port, password=pw) as mcr: \n mcr.command('list')\n break\n except ConnectionRefusedError:\n print('connection refused, try again!')\n</code></pre>\n<p>You should not need to use a <code>str</code> cast here:</p>\n<pre><code> ip = str(input('enter ip or hostname of the server:\\n&gt;')) \n</code></pre>\n<p>since the return of <code>input</code> is already a <code>str</code>.</p>\n<p>Your error handling here:</p>\n<pre><code> try: \n port = int(input('enter the server port (default: 25575):\\n&gt;'))\n if port not in range(0,65535+1):\n raise ValueError \n except ValueError:\n print('invalid value! using default.')\n port = 25575\n</code></pre>\n<p>first of all would benefit from showing two separate, more specific error messages; and also have a constant defined for the default port:</p>\n<pre><code>DEFAULT_PORT = 25575\n\ntry: \n port = int(input(f'enter the server port (default: {DEFAULT_PORT}):\\n&gt;'))\nexcept ValueError:\n print('Invalid integer! Using default.')\n port = DEFAULT_PORT\n\nif not (0 &lt;= port &lt; 65536):\n print('Port out of range! Using default.')\n port = DEFAULT_PORT\n</code></pre>\n<p>This import:</p>\n<pre><code>from mcrcon import MCRcon as r\n</code></pre>\n<p>is mysterious and converts a good name into a bad name. Just leave it as <code>from mcrcon import MCRcon</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T16:31:40.427", "Id": "532383", "Score": "1", "body": "Thanks for your time and help, i will look into everything you mentioned and will post an update when i got everything sorted. This import: \"from mcrcon import MCRcon as r\" was suggested from the mcrcon module documentation, but you are totally right, in a more complex program this \"r\" import would be unnecessarily complicated to understand." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T20:19:10.450", "Id": "269742", "ParentId": "269622", "Score": "1" } }, { "body": "<p>Is there more that I could improve? This is the updated code:</p>\n<pre><code>from kivy.app import App\nfrom kivy.uix.boxlayout import BoxLayout\nfrom mcrcon import MCRcon\nfrom kivy.lang import Builder\nfrom kivy.resources import resource_add_path\nfrom kivy.properties import StringProperty\nimport sys\nimport os\nfrom kivy.config import Config\n\nConfig.set('graphics', 'width', '600')\nConfig.set('graphics', 'height', '300')\nConfig.write()\n\nclass MainWindow(BoxLayout):\n DEFAULT_PORT = 25575\n \n while True:\n try: \n ip = input('enter ip or hostname of the server:\\n&gt;')\n port = int(input('enter the server port (default: 25575):\\n&gt;'))\n if not(0 &lt;= port &lt; 65536):\n print('invalid port! using default port(25575)') \n port = DEFAULT_PORT \n\n except ValueError:\n print('invalid value, only integer! using default port(25575).')\n port = DEFAULT_PORT\n\n try:\n pw = input('enter server password:\\n&gt;')\n with MCRcon (host=ip, port=port, password=pw) as mcr: \n mcr.command('list') \n if sys.platform==&quot;win32&quot;:\n import ctypes\n ctypes.windll.user32.ShowWindow( ctypes.windll.kernel32.GetConsoleWindow(), 0 )\n break\n\n except ConnectionRefusedError:\n print('connection refused, try again!')\n except TimeoutError:\n print('connection timed out, try again!')\n \n player_count = StringProperty('')\n selected_player = StringProperty('')\n lives_to_set = StringProperty('') \n\n def player_count_refresh(self): \n with MCRcon (host=self.ip, port=self.port, password=self.pw) as mcr:\n self.player_count = mcr.command('list')\n \n def selected_player_submit(self):\n self.selected_player = str(self.ids.textinput_selected_player.text) \n \n def player_heal(self): \n with MCRcon (host=self.ip, port=self.port, password=self.pw) as mcr:\n self.player_count = mcr.command('effect give '+self.selected_player+' minecraft:instant_health 1 50')\n \n def player_tp_to_spawn(self):\n with MCRcon (host=self.ip, port=self.port, password=self.pw) as mcr:\n self.player_count = mcr.command('tp '+self.selected_player+' 0 ~ 0')\n \n def player_set_lives(self):\n self.lives_to_set = str(self.ids.slider_player_lives_to_set.value)\n with MCRcon (host=self.ip, port=self.port, password=self.pw) as mcr:\n self.player_count = mcr.command('setlives '+self.selected_player+' '+self.lives_to_set)\n \n def player_revoke_progress(self): \n with MCRcon (host=self.ip, port=self.port, password=self.pw) as mcr:\n self.player_count = mcr.command('advancement MCRconevoke '+self.selected_player+' everything') \n\n def player_give_op(self):\n with MCRcon (host=self.ip, port=self.port, password=self.pw) as mcr:\n self.player_count = mcr.command('op '+self.selected_player) \n\n def player_revoke_op(self):\n with MCRcon (host=self.ip, port=self.port, password=self.pw) as mcr:\n self.player_count = mcr.command('deop '+self.selected_player) \n \n def player_kick(self):\n with MCRcon (host=self.ip, port=self.port, password=self.pw) as mcr:\n self.player_count = mcr.command('kick '+self.selected_player) \n \nclass PyMinecraftContolPanel(App):\n def build(self):\n Builder.load_file('pymcp.kv') \n return MainWindow()\n\nif __name__ == '__main__':\n if hasattr(sys, '_MEIPASS'):\n resource_add_path(os.path.join(sys._MEIPASS))\n\n PyMinecraftContolPanel().run()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T18:15:52.413", "Id": "269787", "ParentId": "269622", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T21:34:19.887", "Id": "269622", "Score": "1", "Tags": [ "python", "python-3.x", "kivy" ], "Title": "easy to use control panel for minecraft rcon" }
269622
<p>Here is an implementation of binary search. Please give feedback on any part but a few specific areas I was wondering about.</p> <ol> <li>Is <code>size_t</code> used appropriately or should <code>int</code> or <code>unsigned int</code> be used instead?</li> <li>How can I shorten <code>selfTest()</code> and in general make it better? I know it's clunky how it returns a value and prints an error message to <code>std::cout</code>.</li> </ol> <pre><code>#include &lt;iostream&gt; #include &lt;cmath&gt; /*function prototypes*/ int selfTest(); int binarySearch(const int data[], const size_t length, const int findMe); int main() { auto failed = selfTest(); std::cout &lt;&lt; &quot;failed tests: &quot; &lt;&lt; failed &lt;&lt; std::endl; return 0; } int binarySearch(const int data[], const size_t length, const int findMe) { size_t start = 0; size_t end = length - 1; while(start &lt;= end) { const auto mid = start + ((end - start) / 2); if(data[mid] &lt; findMe) { start = mid + 1; } else if(data[mid] &gt; findMe) { end = mid - 1; } else { return mid; } } return -1; } int selfTest() { auto failed = 0; int test1[7] = {1,2,3,4,5,6,7}; int test2[8] = {1,2,3,4,5,6,7,8}; int test3[7] = {1,2,3,4,5,7,7}; int test4[8] = {1,2,3,4,5,7,8,8}; int test5[3] = {1,2,3}; int test6[3] = {5,5,5}; int test7[5] = {-10, -2, 5, 6, 10}; int result; result = binarySearch(test1, 7, 4); if(test1[result] != 4) { std::cout &lt;&lt; &quot;Test A failed. Expected 2, got &quot; &lt;&lt; result &lt;&lt; std::endl; failed++; } result = binarySearch(test1, 7, 1); if(result != 0) { std::cout &lt;&lt; &quot;Test B failed. Expected 0, got &quot; &lt;&lt; result &lt;&lt; std::endl; failed++; } result = binarySearch(test1, 7, 2); if(result != 1) { std::cout &lt;&lt; &quot;Test C failed. Expected 1, got &quot; &lt;&lt; result &lt;&lt; std::endl; failed++; } result = binarySearch(test2, 8, 5); if(result != 4) { std::cout &lt;&lt; &quot;Test D failed. Expected 4, got &quot; &lt;&lt; result &lt;&lt; std::endl; failed++; } result = binarySearch(test3, 7, 7); if(test3[result] != 7) { std::cout &lt;&lt; &quot;Test E failed. Expected 5, got &quot; &lt;&lt; result &lt;&lt; std::endl; failed++; } result = binarySearch(test4, 8, 8); if(result != 6 &amp;&amp; result != 7) { std::cout &lt;&lt; &quot;Test F failed. Expected 6 or 7, got &quot; &lt;&lt; result &lt;&lt; std::endl; failed++; } result = binarySearch(test5, 3, 1); if(result != 0) { std::cout &lt;&lt; &quot;Test G failed. Expected 0, got &quot; &lt;&lt; result &lt;&lt; std::endl; failed++; } result = binarySearch(test6, 3, 5); if(result != 0 &amp;&amp; result != 1 &amp;&amp; result != 2) { std::cout &lt;&lt; &quot;Test H failed. Expected 0 or 1, got &quot; &lt;&lt; result &lt;&lt; std::endl; failed++; } result = binarySearch(test6, 3, 0); if(result != -1) { std::cout &lt;&lt; &quot;Test I failed. Expected -1, got &quot; &lt;&lt; result &lt;&lt; std::endl; failed++; } result = binarySearch(test7, 5, -10); if(test7[result] != -10) { std::cout &lt;&lt; &quot;Test J failed. Expected 0, got &quot; &lt;&lt; result &lt;&lt; std::endl; failed++; } result = binarySearch(test7, 5, -2); if(test7[result] != -2) { std::cout &lt;&lt; &quot;Test K failed. Expected 1, got &quot; &lt;&lt; result &lt;&lt; std::endl; failed++; } result = binarySearch(test7, 5, 6); if(test7[result] != 6) { std::cout &lt;&lt; &quot;Test L failed. Expected 3, got &quot; &lt;&lt; result &lt;&lt; std::endl; failed++; } return failed; } </code></pre>
[]
[ { "body": "<p><code>size_t</code> is in the <code>std</code> namespace, so should be written <code>std::size_t</code>.</p>\n<p>We don't need to include <code>&lt;cmath&gt;</code>.</p>\n<p><code>main()</code> should return non-zero if any of the tests failed.</p>\n<hr />\n<p>Length+size is one way to pass a collection (and yes, <code>std::size_t</code> is the appropriate type for the size here); a more flexible (but more advanced) way is to write a general template that accepts a C++ <em>Range</em> object.</p>\n<p>If we're returning an index, that also should be a <code>std::size_t</code>, as <code>int</code> might not be sufficient. However, that leaves a problem - we can no longer use <code>-1</code> to indicate that the value is before the 0th element of the array. Our options for that case include:</p>\n<ul>\n<li>return <code>(std::size_t)-1</code></li>\n<li>add 1 to the result (so we return the position <em>after</em> the found position, and caller must subtract 1 to use it)</li>\n<li>return the index of the first element greater or equal to target (caller can check if it's equal or not) - <strong>this is the convention used by <code>std::lower_bound()</code></strong></li>\n<li>throw an exception (this is expensive, so not a good choice for a &quot;normal&quot; result)</li>\n<li>return a <code>std::optional</code>.</li>\n</ul>\n<p>I recommend the third option, for the reason I've highlighted.</p>\n<hr />\n<blockquote>\n<pre><code> const auto mid = start + ((end - start) / 2);\n</code></pre>\n</blockquote>\n<p>That's good - you've avoided a common mistake there. (If we were to write <code>(start + end) / 2</code>, we would be at risk of integer overflow).</p>\n<hr />\n<p>As you observed, the test cases are very repetitive. We can extract the common parts to a separate function. My function looks something like this (most of the complexity is in giving good diagnostic output):</p>\n<pre><code>#include &lt;vector&gt;\n\nstatic int test_binary_search(const std::vector&lt;int&gt;&amp; v,\n int target,\n std::size_t min_result,\n std::size_t max_result = 0)\n{\n if (max_result == 0) {\n // fill in optional argument\n max_result = min_result;\n }\n\n auto const result = binarySearch(v.data(), v.size(), target);\n if (min_result &lt;= result &amp;&amp; result &lt;= max_result) {\n // test passed\n return 0;\n }\n\n // We failed - emit some diagnostics\n std::cerr &lt;&lt; &quot;Test failed: search for &quot; &lt;&lt; target\n &lt;&lt; &quot; in {&quot;;\n auto *sep = &quot;&quot;;\n for (auto i: v) {\n std::cerr &lt;&lt; sep &lt;&lt; i;\n sep = &quot;,&quot;;\n }\n std::cerr &lt;&lt; &quot;} returned &quot; &lt;&lt; result\n &lt;&lt; &quot;; expected &quot; &lt;&lt; min_result;\n if (min_result != max_result) {\n std::cerr &lt;&lt; &quot;-&quot; &lt;&lt; max_result;\n }\n std::cerr &lt;&lt; '\\n';\n\n return 1;\n}\n</code></pre>\n<p>Then it's very easy to use:</p>\n<pre><code>int selfTest()\n{\n return test_binary_search({1,2,3,4,5,6,7}, 4, 3)\n + test_binary_search({1,2,3,4,5,6,7}, 1, 0)\n + test_binary_search({1,2,3,4,5,6,7}, 7, 6)\n + test_binary_search({1,2,2,2,2,3}, 2, 1, 4)\n + test_binary_search({-10, -2, 5, 6, 10}, -2, 1);\n}\n</code></pre>\n<p>A couple of things I fixed in passing: error messages should go to <code>std::cerr</code> rather than <code>std::cout</code>, and prefer plain newline (<code>\\n</code>) rather than <code>std::endl</code> (which also flushes the output stream).</p>\n<p>Having the test function print the inputs and expected result range helps avoid inconsistencies like this one:</p>\n<blockquote>\n<pre><code>result = binarySearch(test1, 7, 4);\nif(test1[result] != 4)\n{\n std::cout &lt;&lt; &quot;Test A failed. Expected 2, got &quot; &lt;&lt; result &lt;&lt; std::endl;\n failed++;\n}\n</code></pre>\n</blockquote>\n<p>(In fact, almost all the tests have wrong &quot;Expected&quot; value in the string).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T09:48:25.213", "Id": "532342", "Score": "0", "body": "Regarding the \"that leaves a problem\": If the value isn't found, would throwing an exception be a good solution?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T10:29:13.620", "Id": "532343", "Score": "0", "body": "Good point - that's another option. I'll edit that in." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T07:38:50.760", "Id": "532951", "Score": "0", "body": "This made me wonder, any time an array is being iterated should the type be `std::size_t` or `unsigned int`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T07:56:44.147", "Id": "532954", "Score": "0", "body": "I'd always recommend `std::size_t` (unless there's a good reason we can guarantee that the result will always be no more than `UINT_MAX` - which could be as small as 65535)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T09:41:29.950", "Id": "269629", "ParentId": "269625", "Score": "1" } }, { "body": "<p><code>/*function prototypes*/</code><br />\nA C comment, bearing C nomenclature?<br />\nC++ doesn't have &quot;prototypes&quot;. Declaring your functions at the top is not helpful since C++ supports overloading, and any difference between this declaration and the later definition will not cause any error at compile time but a confusing link-time error.</p>\n<p>Just define the functions in the right order. Put <code>main</code> at the bottom, and define the function <em>before</em> you call it.</p>\n<hr />\n<p><code>int binarySearch(const int data[], const size_t length, const int findMe)</code></p>\n<ul>\n<li><p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#i13-do-not-pass-an-array-as-a-single-pointer\" rel=\"nofollow noreferrer\">⧺I.13</a> Do not pass an array as a single pointer (includes pointer and count parameters in the discussion)</p>\n</li>\n<li><p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r14-avoid--parameters-prefer-span\" rel=\"nofollow noreferrer\">⧺R.14</a> Avoid <code>[]</code> parameters, prefer <code>span</code></p>\n</li>\n<li><p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f24-use-a-spant-or-a-span_pt-to-designate-a-half-open-sequence\" rel=\"nofollow noreferrer\">⧺F.24</a> Use a <code>span&lt;T&gt;</code> or a <code>span_p&lt;T&gt;</code> to designate a half-open sequence</p>\n</li>\n</ul>\n<p>It would be more normal to do this <a href=\"https://en.cppreference.com/w/cpp/algorithm/find\" rel=\"nofollow noreferrer\">how the standard library functions</a> do it: take a pair of <em>iterators</em>, not a starting position and length.</p>\n<p>If you do pass a contiguous sequence of values in memory rather than being more general, don't use <code>[]</code> as an alias for pointer (what it means in a parameter list), and don't pass the starting position and length as separate parameters.</p>\n<hr />\n<p>I see you used top-level <code>const</code> on the <code>length</code> and <code>findMe</code> parameters. That's fine (though often omitted), but also showed them on the function declaration at the top of the file. If you do have a separate function declaration (say, in a header file), note that the top-level <code>const</code> is not part of the contract and does not affect the caller. Its presence or absence in the definition does not change the function's signature. So, where you only <em>declare</em> the function, don't include such top-level <code>const</code> modifiers. Where you <em>define</em> the function, you can use them as befits the implementation of the function.</p>\n<hr />\n<p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slio50-avoid-endl\" rel=\"nofollow noreferrer\">⧺SL.io.50</a> Don't use <code>endl</code>.</p>\n<hr />\n<h1>The Good</h1>\n<p>I want to acknowledge some of the good practices and decisions found in the code as well.</p>\n<ul>\n<li><p>You made the search a separate function rather than stuffing everything inside <code>main</code>, and made it reusable for the real use and testing. That's something I'm often trying to get across to newcomers, and it seems to be missing from so many class curriculums!</p>\n</li>\n<li><p>You declared <code>mid</code> locally inside the loop, where needed, and made it <code>const</code>. Again, that's something I'm always trying to impress upon students.</p>\n</li>\n<li><p>Use of <code>const</code> in general. This deserves double bonus points.</p>\n</li>\n</ul>\n<h1>test code structure</h1>\n<p>The test code is highly repetitive. You should not repeat the same boilerplate over and over. Rather, put the data in an array and loop through it.</p>\n<pre><code> const auto result = binarySearch(data.arr, data.findme);\n if(data.arr[result] != data.findme)\n {\n std::cout &lt;&lt; .... ;\n failed++;\n }\n</code></pre>\n<p>You can make an array of simple structures and use a range-based <code>for</code> loop to go through it.</p>\n<pre><code>constexpr int TestArr1[] = {1,2,3,4,5,6,7};\nconstexpr int TestArr2[] = {1,2,2,2,2,3};\n\nconstexpr struct {\n std::span&lt;int&gt; arr;\n int findme;\n } data[] = {\n { TestArr1, 3 },\n ⋮\n};\n</code></pre>\n<p>You can also look at testing frameworks, such as <a href=\"https://github.com/catchorg/Catch2\" rel=\"nofollow noreferrer\">Catch2</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T15:15:29.050", "Id": "269641", "ParentId": "269625", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T04:15:46.847", "Id": "269625", "Score": "0", "Tags": [ "c++", "unit-testing" ], "Title": "Binary search with self-test" }
269625
<p>I did the following</p> <ol> <li>Created DB and table in prepate_table function</li> <li>Extracted data from binance in GetHistoricalData function</li> <li>Saved the data to DB</li> </ol> <p>My code works fine but I want to optimize my code and remove redundant steps</p> <p><strong>My solution</strong></p> <pre><code>import os import pandas as pd import time import clickhouse_driver import datetime from binance.client import Client # Binance test_key https://testnet.binance.vision/key/generate API_KEY = &quot;--&quot; API_SECRET = &quot;--&quot; def GetHistoricalData( timedelta_days=10, ticker=&quot;BTCUSDT&quot;, kline_interval=Client.KLINE_INTERVAL_1HOUR ): # Calculate the timestamps for the binance api function untilThisDate = datetime.datetime.now() sinceThisDate = untilThisDate - datetime.timedelta(days=timedelta_days) client = Client(API_KEY, API_SECRET) client.API_URL = 'https://testnet.binance.vision/api' candle = client.get_historical_klines(ticker, kline_interval, str(sinceThisDate), str(untilThisDate)) # Create a dataframe to label all the columns returned by binance so we work with them later. df = pd.DataFrame(candle, columns=['dateTime', 'open', 'high', 'low', 'close', 'volume', 'closeTime', 'quoteAssetVolume', 'numberOfTrades', 'takerBuyBaseVol', 'takerBuyQuoteVol', 'ignore']) # as timestamp is returned in ms, let us convert this back to proper timestamps. df.dateTime = pd.to_datetime(df.dateTime, unit='ms').dt.strftime(&quot;%Y-%m-%d %X&quot;) df.set_index('dateTime', inplace=True) # Get rid of columns we do not need df = df.drop(['quoteAssetVolume', 'numberOfTrades', 'takerBuyBaseVol','takerBuyQuoteVol', 'ignore'], axis=1) return df def prepare_table(): client = clickhouse_driver.Client.from_url(f'clickhouse://default:{os.getenv(&quot;CLICK_PASSWORD&quot;)}@localhost:9000/crypto_exchange') # field names from binance API client.execute(''' CREATE TABLE IF NOT EXISTS historical_data_binance ( dateTime DateTime, closeTime Int64, open Float64, high Float64, low Float64, close Float64, volume Float64, kline_type String, ticker String ) ENGINE = Memory ''') return client def insert_data(client, insert_data, db_name=&quot;crypto_exchange&quot;, table_name=&quot;historical_data_binance&quot;): &quot;&quot;&quot; insert_data = { &quot;dateTime&quot;: dateTime, &quot;closeTime&quot;: closeTime, &quot;open&quot;: open, &quot;high&quot;: hign, &quot;low&quot;: low, &quot;close&quot;: close, &quot;volume&quot;: volume, &quot;kline_type&quot;: kline_type, &quot;ticker&quot;: ticker } &quot;&quot;&quot; columns = ', '.join(insert_data.keys()) query = 'insert into {}.{} ({}) values'.format(db_name, table_name, columns) data = [] data.append(insert_data) client.execute(query, data) client_db = prepare_table() hist_data = GetHistoricalData(kline_interval=Client.KLINE_INTERVAL_1HOUR, ticker=&quot;BTCUSDT&quot;,) for row in hist_data.iterrows(): data = row[1].to_dict() data[&quot;dateTime&quot;] = datetime.datetime.strptime(row[0], &quot;%Y-%m-%d %X&quot;) data[&quot;closeTime&quot;] = int(data[&quot;closeTime&quot;]) data[&quot;open&quot;] = float(data[&quot;open&quot;]) data[&quot;high&quot;] = float(data[&quot;high&quot;]) data[&quot;low&quot;] = float(data[&quot;low&quot;]) data[&quot;close&quot;] = float(data[&quot;close&quot;]) data[&quot;volume&quot;] = float(data[&quot;volume&quot;]) data[&quot;kline_type&quot;] = Client.KLINE_INTERVAL_1HOUR data[&quot;ticker&quot;] = &quot;BTCUSDT&quot; insert_data(client_db, data) </code></pre> <p>What can be improved?</p>
[]
[ { "body": "<ul>\n<li>By PEP8, <code>GetHistoricalData</code> should be <code>get_historical_data</code>; likewise for your local variables like <code>until_this_date</code></li>\n<li>Introduce PEP484 type hints, for instance <code>timedelta_days: Real</code> (if it's allowed to be floating-point) or <code>int</code> otherwise</li>\n<li>You should not be redefining <code>'https://testnet.binance.vision/api'</code>; that's already defined as <code>BaseClient.API_TESTNET_URL</code> - see <a href=\"https://python-binance.readthedocs.io/en/latest/_modules/binance/client.html\" rel=\"nofollow noreferrer\">the documentation</a>. This also suggests that you should be using <code>testnet=True</code> upon construction.</li>\n<li>This date conversion:</li>\n</ul>\n<pre><code> df.dateTime = pd.to_datetime(df.dateTime, unit='ms').dt.strftime(&quot;%Y-%m-%d %X&quot;)\n</code></pre>\n<p>is only half good idea. Datetime data should be stored in machine format instead of rendered user presentation data, so keep the <code>to_datetime</code> and drop the <code>strftime</code>.</p>\n<ul>\n<li>When you call <code>df.drop</code>, pass <code>inplace=True</code> since you overwrite <code>df</code> anyway.</li>\n<li>Your use of <code>iterrows</code> broken down into individual ClickHouse insert statements is going to be slow. <a href=\"https://clickhouse.com/docs/en/sql-reference/statements/insert-into/\" rel=\"nofollow noreferrer\">ClickHouse supports multi-row <code>values()</code> syntax.</a> Try making insertion batches that use this syntax to reduce the total number of inserts that you perform.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T20:07:56.173", "Id": "269741", "ParentId": "269626", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T06:21:59.040", "Id": "269626", "Score": "1", "Tags": [ "python", "database", "pandas" ], "Title": "Get data from binance api and save to ClickHouse DB" }
269626
<p>I have written a function that randomly picks one element from a set with different probabilities for each element, anyway it takes a dictionary as argument, the keys of the dictionary are the choices and can be of any type, the values of the dictionary are weights and must be non-zero integers. It randomly chooses a choice based on weights and returns the choice.</p> <p>I have tried a bunch of different methods and used the most efficient method I have found in this implementation, I intend to call the function with same arguments repeatedly and the dictionaris aren't supposed to change during execution, so I thought memoization would be a good idea, so I did memoize it - using a <code>dict</code>, and the performance improvement is huge, as expected.</p> <h2>Code</h2> <pre class="lang-py prettyprint-override"><code>import random from bisect import bisect from itertools import accumulate from typing import Any cache = dict() def weighted_choice(dic: dict) -&gt; Any: mark = id(dic) if mark not in cache: if not isinstance(dic, dict): raise TypeError('The argument of the function should be a dictionary') choices, weights = zip(*dic.items()) if set(map(type, weights)) != {int}: raise TypeError('The values of the argument must be integers') if 0 in weights: raise ValueError('The values of the argument shouldn\'t contain 0') accreted = list(accumulate(weights)) cache[mark] = (choices, accreted) else: choices, accreted = cache[mark] chosen = random.random() * accreted[-1] return choices[bisect(accreted, chosen)] </code></pre> <h2>Example</h2> <pre class="lang-py prettyprint-override"><code>LETTER_FREQUENCY = { &quot;a&quot;: 80183, &quot;b&quot;: 17558, &quot;c&quot;: 42724, &quot;d&quot;: 28914, &quot;e&quot;: 100093, &quot;f&quot;: 11308, &quot;g&quot;: 20298, &quot;h&quot;: 24064, &quot;i&quot;: 80469, &quot;j&quot;: 1440, &quot;k&quot;: 6103, &quot;l&quot;: 52184, &quot;m&quot;: 28847, &quot;n&quot;: 63640, &quot;o&quot;: 64730, &quot;p&quot;: 29325, &quot;q&quot;: 1741, &quot;r&quot;: 66553, &quot;s&quot;: 54738, &quot;t&quot;: 63928, &quot;u&quot;: 34981, &quot;v&quot;: 8877, &quot;w&quot;: 6020, &quot;x&quot;: 2975, &quot;y&quot;: 19245, &quot;z&quot;: 2997 } weighted_choice(LETTER_FREQUENCY) # returns a letter and the bigger the weight the more likely the letter will be returned </code></pre> <h2>Performance</h2> <pre class="lang-py prettyprint-override"><code>#nonmemoized In [57]: def weighted_choice(dic: dict) -&gt; Any: ...: choices, weights = zip(*dic.items()) ...: accreted = list(accumulate(weights)) ...: chosen = random.random() * accreted[-1] ...: return choices[bisect(accreted, chosen)] In [58]: %timeit weighted_choice(LETTER_FREQUENCY) 4.03 µs ± 293 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) #memoized In [59]: cache = dict() ...: ...: def weighted_choice(dic: dict) -&gt; Any: ...: mark = id(dic) ...: if mark not in cache: ...: if not isinstance(dic, dict): ...: raise TypeError('The argument of the function should be a dictionary') ...: choices, weights = zip(*dic.items()) ...: if set(map(type, weights)) != {int}: ...: raise TypeError('The values of the argument must be integers') ...: if 0 in weights: ...: raise ValueError('The values of the argument shouldn\'t contain 0') ...: accreted = list(accumulate(weights)) ...: cache[mark] = (choices, accreted) ...: else: ...: choices, accreted = cache[mark] ...: chosen = random.random() * accreted[-1] ...: return choices[bisect(accreted, chosen)] In [60]: %timeit weighted_choice(LETTER_FREQUENCY) 702 ns ± 25.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) </code></pre> <p>I want to know how to properly implement the memoization, in this function there are two properties that need to be remembered for each input, assuming the variables will never change which in practice is true; The properties are <code>choices</code> and <code>accreted</code> (the accumulated weights), they are unique to each input, determined by the inputs and won't change.</p> <p>However the function is non-deterministic, it should return different outputs for same inputs, there is one and only one non-deterministic variable, the <code>chosen</code> variable, and the output is determined by the random variable.</p> <p>The only memoization technique I know of is <code>functools.lrucache</code> decorator and the functions wrapped by it return same outputs for same inputs which is obviously not suitable here, unless I write a helper function that processes the inputs which as you see consists the bulk of the function, I think this is excessive and Python function calls are expensive.</p> <p>So what is the proper way to memoize the function?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T11:03:57.033", "Id": "532031", "Score": "0", "body": "The [docs](https://docs.python.org/3/library/functions.html#id) state: *Two objects with non-overlapping lifetimes may have the same id() value*. This might cause bugs in your current implementation in some (probably rare) cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T13:22:33.947", "Id": "532045", "Score": "0", "body": "Why not use the `p` argument to numpy's [choice](https://numpy.org/doc/stable/reference/random/generated/numpy.random.Generator.choice.html#numpy.random.Generator.choice) ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T14:02:25.297", "Id": "532052", "Score": "0", "body": "@Reinderien Actually I have tested that, and even with memoization, generating a single output costs about 44 microseconds, the overhead of numpy is simply too high, however if I use the same argument to get samples in batch it is indeed faster than the running the iteration one in batch, however I need to sample one element from each distribution, adjacent calls will have different arguments and the distributions are reused very frequently..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T14:07:21.437", "Id": "532053", "Score": "0", "body": "OK, but you don't show this reuse or your outer loop. Please show all of your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T00:06:56.600", "Id": "532221", "Score": "0", "body": "What makes you think your current implementations is not proper? As you pointed out, the function is non-deterministic, so it can't be cached. However, there are expensive calculations that can be cached. It looks like a reasonable implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T08:24:58.153", "Id": "532449", "Score": "0", "body": "Why not write a `FrequencyDict` class with a `.choice()` method instead? It looks like you want a special method for a particular type of dict." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T13:44:46.960", "Id": "532698", "Score": "0", "body": "You might be interested in [this method](https://lips.cs.princeton.edu/the-alias-method-efficient-sampling-with-many-discrete-outcomes/)." } ]
[ { "body": "<p>I'd prefer a separation between &quot;distribution objects&quot; and sampling.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class WeightedDiscrete:\n def __init__(self, weighted_items: dict):\n if not isinstance(weighted_items, dict):\n raise TypeError('The argument of the function should be a dictionary')\n\n items, weights = weighted_items.keys(), weighted_items.values()\n \n if any(not isinstance(w, int) for w in weights):\n raise TypeError('The values of the argument must be integers')\n if any(w &lt;= 0 for w in weights):\n raise ValueError('The values of the argument be less than 0')\n\n self.items = list(items)\n self.accreted = list(accumulate(weights))\n\n def choice(self):\n chosen = random.random() * self.accreted[-1]\n return self.items[bisect(self.accreted, chosen)]\n</code></pre>\n<p>Given that, you can manage caching the <code>WeightedDiscrete</code> object given different <code>weighted_items</code> separately, and the cache design becomes an orthogonal problem.</p>\n<p><code>lru_cache</code> unfortunately still won't work, since dicts are unhashable, but for the specific use a custom id-based cache might be appropriate:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class IdCache:\n def __init__(self):\n self.cache = dict()\n\n def __setitem__(self, key, value):\n self.cache[id(key)] = value\n \n def __getitem__(self, key):\n return self.cache[id(key)]\n \n def __contains__(self, key):\n return id(key) in self.cache\n \n\ncache = IdCache()\n\ndef get_distribution(weighted_items):\n if weighted_items not in cache:\n w = WeightedDiscrete(weighted_items)\n cache[weighted_items] = w\n\n return cache[weighted_items]\n</code></pre>\n<p>In case you have a lot of different distributions, the <code>WeightedDiscrete</code> class could perhaps be further optimized by inheriting form a named tuple to reduce space.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T14:37:56.947", "Id": "269917", "ParentId": "269627", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T07:26:06.813", "Id": "269627", "Score": "0", "Tags": [ "python", "performance", "python-3.x", "random", "memoization" ], "Title": "Python 3 weighted random choice function memoized version" }
269627
<p>I need to convert objects (potentially nested) and collections (<code>int[]</code>, <code>IEnumerable</code>s, <code>object[]</code>) into a query string that I can pass to a <code>GET</code> <code>HTTP</code> call.</p> <p>I didn't find any complete answer on SO so I had to merge some answers and add something to make them all work together.</p> <p>This is the current version that works with all the aforementioned data structures.</p> <p>Performance shouldn't be a big issue as this has to work with relatively small objects anyway, but at the current state it's hard to read and I'm sure there are better ways to do that... that I cannot find myself.</p> <pre class="lang-cs prettyprint-override"><code> public static string ToQueryString(this object obj, string prefix = &quot;&quot;) { bool IsDefaultType(Type type) =&gt; type.IsPrimitive || type == typeof(string) || type == typeof(DateTime); var properties = new Dictionary&lt;string, object&gt;(); var queryString = new List&lt;string&gt;(); if (typeof(IEnumerable).IsAssignableFrom(obj.GetType()) &amp;&amp; obj.GetType() != typeof(string)) { if (string.IsNullOrEmpty(prefix)) { throw new InvalidOperationException(&quot;You should not serialize an array without a prefix&quot;); } var enumerator = ((IEnumerable)obj).GetEnumerator(); int i = 0; while (enumerator.MoveNext()) { properties.Add(i.ToString(), enumerator.Current); i++; } } else { properties = obj.GetType().GetProperties() .Where(x =&gt; x.CanRead &amp;&amp; x.GetValue(obj, null) != null) .ToDictionary(x =&gt; x.Name, x =&gt; x.GetValue(obj, null)); if (properties.Count == 0 &amp;&amp; IsDefaultType(obj.GetType())) { properties.Add(prefix, obj); } } foreach (var prop in properties.Where(kv =&gt; kv.Value != null)) { string key = string.IsNullOrEmpty(prefix) ? prop.Key : $&quot;{prefix}[{prop.Key}]&quot;; var value = prop.Value; var valueType = value.GetType(); if (IsDefaultType(valueType)) { if (valueType == typeof(DateTime)) { value = ((DateTime)value).ToString(&quot;yyyy-MM-ddTHH:mm:ss&quot;); } queryString.Add(key + &quot;=&quot; + value.ToString()); } else { queryString.Add(value.ToQueryString(key)); } } return string.Join(&quot;&amp;&quot;, queryString); } </code></pre> <p>Thank you!</p>
[]
[ { "body": "<p>I would suggest that you split the function into two parts. The first simply deals with formatting a single object and making it safe for the query string:</p>\n<pre><code>private static string FormatValue(object obj)\n{\n string value;\n if (obj.GetType() == typeof(DateTime))\n value = ((DateTime)obj).ToString(&quot;yyyy-MM-ddTHH:mm:ss&quot;);\n else\n value = obj.ToString();\n return HttpUtility.UrlEncode(value);\n}\n</code></pre>\n<p>With this in place, you can simplify <code>ToQueryString</code> to the following:</p>\n<pre><code>public static string ToQueryString(this object obj, string prefix = &quot;&quot;, int level = 0)\n{\n if (string.IsNullOrEmpty(prefix))\n throw new InvalidOperationException(&quot;You should not serialize without a prefix&quot;);\n if (typeof(IEnumerable).IsAssignableFrom(obj.GetType()) &amp;&amp; obj.GetType() != typeof(string))\n {\n var items = (IEnumerable)obj;\n var index = 0;\n string queryString = &quot;&quot;;\n foreach (var item in items)\n {\n if (queryString != &quot;&quot;)\n queryString += &quot;&amp;&quot;;\n queryString += item.ToQueryString(String.Format(&quot;{0}[{1}]&quot;, prefix, index++), level + 1);\n }\n return queryString;\n }\n else\n {\n return String.Format(&quot;{0}={1}&quot;, prefix, FormatValue(obj));\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T18:58:41.127", "Id": "269657", "ParentId": "269633", "Score": "0" } }, { "body": "<p>Your <code>ToQueryString</code> implementation has clearly three separate parts:</p>\n<ul>\n<li>Get properties of an object</li>\n<li>Get members of a collection</li>\n<li>Format key value pairs</li>\n</ul>\n<h3>Get properties of an object</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>private static bool IsDefaultType(object @object)\n =&gt; @object.GetType().IsPrimitive || @object is string || @object is DateTime;\n\npublic static string ToQueryString(this object @object, string prefix = &quot;&quot;)\n{\n if (IsDefaultType(@object))\n return FormatDictionary(new() { { prefix, @object } }, prefix);\n\n var properties = @object.GetType().GetProperties()\n .Where(x =&gt; x.CanRead &amp;&amp; x.GetValue(@object, null) != null)\n .ToDictionary(x =&gt; x.Name, x =&gt; x.GetValue(@object, null));\n\n return FormatDictionary(properties, prefix);\n}\n</code></pre>\n<ul>\n<li>I've made your <code>IsDefaultType</code> method <code>private static</code>\n<ul>\n<li>I've changed the type check to utilize <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/is\" rel=\"nofollow noreferrer\">is operator</a></li>\n</ul>\n</li>\n<li>I've moved the type check of the <code>ToQueryString</code> to the very first statement</li>\n<li>The <code>new () { { ... } }</code> creates a new <code>Dictionary&lt;string, object&gt;</code> with a single element\n<ul>\n<li>It relies on the <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/target-typed-new\" rel=\"nofollow noreferrer\">target type new expression</a> (<code>new ()</code>), <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers#collection-initializers\" rel=\"nofollow noreferrer\">collection initializer</a> (<code>Dictionary)</code> and <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers#object-initializers\" rel=\"nofollow noreferrer\">object initializer</a> (<code>KeyValuePair</code>) features of C#</li>\n</ul>\n</li>\n</ul>\n<h3>Get members of a collection</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>public static string ToQueryString(this IEnumerable collection, string prefix = &quot;&quot;)\n{\n if (collection is string)\n return ToQueryString((object)collection, prefix);\n\n if (string.IsNullOrEmpty(prefix))\n throw new InvalidOperationException(&quot;You should not serialize an array without a prefix&quot;);\n\n var members = collection\n .Cast&lt;object&gt;()\n .Select((value, idx) =&gt; new KeyValuePair&lt;string, object&gt;(idx.ToString(), value))\n .ToDictionary(item =&gt; item.Key, item =&gt; item.Value);\n \n return FormatDictionary(members, prefix);\n}\n</code></pre>\n<ul>\n<li>I've created another overload which accepts <code>IEnumerable</code>\n<ul>\n<li>If the extension method is called on a <code>string</code> then I'm delegating the handling to the previous method</li>\n<li>Please note that explicit cast to <code>object</code>\n<ul>\n<li>If you forgot that then you will have an infinite recursion</li>\n</ul>\n</li>\n</ul>\n</li>\n<li>I've replaced your while loop with a Linq query\n<ul>\n<li>The non-generic <code>IEnumerable</code> does not have <code>Select</code> extension method that's why I had to call <code>Cast&lt;object&gt;</code> first</li>\n<li>Then I've used the <code>Select</code> to get the <a href=\"https://stackoverflow.com/questions/43021/how-do-you-get-the-index-of-the-current-iteration-of-a-foreach-loop\">value and the index of the enumerable</a></li>\n<li>Finally I've used the <code>ToDictionary</code> to convert the <code>IEnumerable&lt;KeyValuePair&lt;string, object&gt;&gt;</code> to the desired type</li>\n</ul>\n</li>\n</ul>\n<h3>Format key value pairs</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>private static string FormatDictionary(Dictionary&lt;string, object&gt; properties, string prefix)\n{\n var keyValues = new List&lt;string&gt;();\n foreach (var prop in properties.Where(kv =&gt; kv.Value != null))\n {\n string key = string.IsNullOrEmpty(prefix) ? prop.Key : $&quot;{prefix}[{prop.Key}]&quot;;\n var value = prop.Value;\n\n if (IsDefaultType(value))\n {\n if (value is DateTime date)\n value = date.ToString(&quot;yyyy-MM-ddTHH:mm:ss&quot;);\n \n keyValues.Add(key + &quot;=&quot; + value.ToString());\n }\n else\n keyValues.Add(value.ToQueryString(key));\n }\n\n return string.Join(&quot;&amp;&quot;, keyValues);\n}\n</code></pre>\n<ul>\n<li>I've get rid of the <code>valueType</code> variable and used the <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/is\" rel=\"nofollow noreferrer\">is operator with declaration pattern</a></li>\n</ul>\n<hr />\n<p>I've tested the implementation with these test cases:</p>\n<pre><code>Hashtable table = new Hashtable();\ntable.Add(&quot;1&quot;, &quot;1&quot;);\ntable.Add(2, DateTime.UtcNow);\nConsole.WriteLine(table.ToQueryString(&quot;table&quot;));\n\nList&lt;int&gt; list = new List&lt;int&gt;();\nlist.Add(1);\nlist.Add(10);\nConsole.WriteLine(list.ToQueryString(&quot;list&quot;));\n\nDictionary&lt;string, string&gt; dict = new Dictionary&lt;string, string&gt;();\ndict.Add(&quot;1&quot;, &quot;1&quot;);\ndict.Add(&quot;2&quot;, DateTime.UtcNow.ToString());\nConsole.WriteLine(dict.ToQueryString(&quot;dict&quot;));\n\nConsole.WriteLine(DateTime.UtcNow.ToQueryString(&quot;date&quot;));\n\nConsole.WriteLine(&quot;hello world&quot;.ToQueryString(&quot;string&quot;));\n</code></pre>\n<p>the output was the following:</p>\n<pre class=\"lang-none prettyprint-override\"><code>table[0][Key]=2&amp;table[0][Value]=2021-11-03T13:37:47&amp;table[1][Key]=1&amp;table[1][Value]=1\n\nlist[0]=1&amp;list[1]=10\n\ndict[0][Key]=1&amp;dict[0][Value]=1&amp;dict[1][Key]=2&amp;dict[1][Value]=11/3/2021 1:37:47 PM\n\ndate[date]=2021-11-03T13:37:47\n\nstring[string]=hello world\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T13:32:14.610", "Id": "269697", "ParentId": "269633", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T11:35:29.033", "Id": "269633", "Score": "2", "Tags": [ "c#" ], "Title": "Serialize nested objects and arrays to querystring" }
269633
<p>I have this code to remove duplicates (all occurrences) from an associative array, does PHP have methods to do this ? Or is there a way to improve the code ?</p> <p>I looked for array_unique, array_search, array_map, array_reduce...</p> <pre><code>$articles = [ [ &quot;id&quot; =&gt; 0, &quot;title&quot; =&gt; &quot;lorem&quot;, &quot;reference&quot; =&gt; &quot;A&quot; ], [ &quot;id&quot; =&gt; 1, &quot;title&quot; =&gt; &quot;ipsum&quot;, &quot;reference&quot; =&gt; &quot;B&quot; ], [ &quot;id&quot; =&gt; 2, &quot;title&quot; =&gt; &quot;dolor&quot;, &quot;reference&quot; =&gt; &quot;C&quot; ], [ &quot;id&quot; =&gt; 3, &quot;title&quot; =&gt; &quot;sit&quot;, &quot;reference&quot; =&gt; &quot;A&quot; ] ]; $references = array_column($articles, &quot;reference&quot;); $duplicates = array_values(array_unique(array_diff_assoc($references, array_unique($references)))); foreach($duplicates as $duplicate) { foreach($references as $index =&gt; $reference) { if($duplicate === $reference) { unset($articles[$index]); } } } /** * $articles = [ * [ * &quot;id&quot; =&gt; 1, * &quot;title&quot; =&gt; &quot;ipsum&quot;, * &quot;reference&quot; =&gt; &quot;B&quot; * ], * [ * &quot;id&quot; =&gt; 2, * &quot;title&quot; =&gt; &quot;dolor&quot;, * &quot;reference&quot; =&gt; &quot;C&quot; * ] * ] */ </code></pre>
[]
[ { "body": "<blockquote>\n<h3><em>is there a way to improve the code ?</em></h3>\n</blockquote>\n<p>Instead of having two <code>foreach</code> loops:</p>\n<blockquote>\n<pre><code>foreach($duplicates as $duplicate) {\n foreach($references as $index =&gt; $reference) {\n if($duplicate === $reference) {\n unset($articles[$index]);\n }\n }\n}\n</code></pre>\n</blockquote>\n<p>It can be simplified using <a href=\"https://www.php.net/in_array\" rel=\"nofollow noreferrer\"><code>in_array()</code></a>:</p>\n<pre><code>foreach($references as $index =&gt; $reference) {\n if (in_array($reference, $duplicates, true)) {\n unset($articles[$index]);\n }\n}\n</code></pre>\n<p>While it would still technically have the same complexity (i.e. two loops) it would have one less indentation level, and utilize a built-in function to check if the reference is in the list of duplicate references.</p>\n<p>Another solution would be to use <a href=\"https://www.php.net/manual/en/function.array-flip.php\" rel=\"nofollow noreferrer\"><code>array_flip()</code></a> to map the last index to references, then loop through the articles and if the index of the current article does not match the index of the last reference (meaning its a duplicate) then remove both the article at the current index as well as the article at the last index that has the reference.</p>\n<pre><code>$references = array_column($articles, &quot;reference&quot;);\n$lastIndexes = array_flip($references);\n\nforeach ($articles as $index =&gt; $article) {\n if ($lastIndexes[$article['reference']] !== $index) {\n unset($articles[$index], $articles[$lastIndexes[$article['reference']]]);\n }\n}\n</code></pre>\n<p>Or to make it more readable, the last index can be assigned to a variable:</p>\n<pre><code>foreach($articles as $index =&gt; $article) {\n $lastIndex = $lastIndexes[$article['reference']];\n if ($lastIndex !== $index) {\n unset($articles[$index], $articles[$lastIndex]);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T16:15:51.170", "Id": "269646", "ParentId": "269636", "Score": "1" } }, { "body": "<p>This task can and should be done with a single loop with no pre-looping variable population and no inefficient <code>in_array()</code> calls. Searching keys in php is always more efficient than searching values.</p>\n<p>Code: (<a href=\"https://3v4l.org/cRU6e\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n<pre><code>$found = [];\nforeach ($articles as $index =&gt; ['reference' =&gt; $ref]) {\n if (!isset($found[$ref])) {\n $found[$ref] = $index;\n } else {\n unset($articles[$index], $articles[$found[$ref]]);\n }\n}\nvar_export($articles);\n</code></pre>\n<p>Output:</p>\n<pre><code>array (\n 1 =&gt; \n array (\n 'id' =&gt; 1,\n 'title' =&gt; 'ipsum',\n 'reference' =&gt; 'B',\n ),\n 2 =&gt; \n array (\n 'id' =&gt; 2,\n 'title' =&gt; 'dolor',\n 'reference' =&gt; 'C',\n ),\n)\n</code></pre>\n<p>I am using array destructuring syntax in my <code>foreach()</code> for brevity and because I don't need the other column values.</p>\n<p>Finally, it doesn't matter if there are triplicates (or more instances of a <code>reference</code> value), the script will handle these in the same fashion. <code>unset()</code> will not generate any notices, warnings, or errors if it is given a non-existent element (as a parameter) -- this is why it is safe to unconditionally unset the first found <code>reference</code> potentially multiple times.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T22:34:06.843", "Id": "269671", "ParentId": "269636", "Score": "2" } } ]
{ "AcceptedAnswerId": "269671", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T13:37:25.530", "Id": "269636", "Score": "2", "Tags": [ "php", "array" ], "Title": "remove ALL duplicate elements from an array" }
269636
<p>There are many debouncer and throttle implementations created using <code>Grand Central Dispatch</code>, and even one built into <code>Combine</code>. I wanted to create one using the new <code>Swift Concurrency</code> feature in Swift 5.5+.</p> <p>Below is what I put together with <a href="https://stackoverflow.com/q/69787568">help from others</a>:</p> <pre><code>actor Limiter { enum Policy { case throttle case debounce } private let policy: Policy private let duration: TimeInterval private var task: Task&lt;Void, Never&gt;? init(policy: Policy, duration: TimeInterval) { self.policy = policy self.duration = duration } nonisolated func callAsFunction(task: @escaping () async -&gt; Void) { Task { switch policy { case .throttle: await throttle(task: task) case .debounce: await debounce(task: task) } } } private func throttle(task: @escaping () async -&gt; Void) { guard self.task?.isCancelled ?? true else { return } Task { await task() } self.task = Task { try? await sleep() self.task?.cancel() self.task = nil } } private func debounce(task: @escaping () async -&gt; Void) { self.task?.cancel() self.task = Task { do { try await sleep() guard !Task.isCancelled else { return } await task() } catch { return } } } private func sleep() async throws { try await Task.sleep(nanoseconds: UInt64(duration * 1_000_000_000)) } } </code></pre> <p>I created tests to go with it, but <code>testThrottler</code> and <code>testDebouncer</code> are failing randomly which means there's some race condition somewhere or my assumptions in the tests are incorrect:</p> <pre><code>final class LimiterTests: XCTestCase { func testThrottler() async throws { // Given let promise = expectation(description: &quot;Ensure first task fired&quot;) let throttler = Limiter(policy: .throttle, duration: 1) var value = &quot;&quot; var fulfillmentCount = 0 promise.expectedFulfillmentCount = 2 func sendToServer(_ input: String) { throttler { value += input // Then switch fulfillmentCount { case 0: XCTAssertEqual(value, &quot;h&quot;) case 1: XCTAssertEqual(value, &quot;hwor&quot;) default: XCTFail() } promise.fulfill() fulfillmentCount += 1 } } // When sendToServer(&quot;h&quot;) sendToServer(&quot;e&quot;) sendToServer(&quot;l&quot;) sendToServer(&quot;l&quot;) sendToServer(&quot;o&quot;) await sleep(2) sendToServer(&quot;wor&quot;) sendToServer(&quot;ld&quot;) wait(for: [promise], timeout: 10) } func testDebouncer() async throws { // Given let promise = expectation(description: &quot;Ensure last task fired&quot;) let limiter = Limiter(policy: .debounce, duration: 1) var value = &quot;&quot; var fulfillmentCount = 0 promise.expectedFulfillmentCount = 2 func sendToServer(_ input: String) { limiter { value += input // Then switch fulfillmentCount { case 0: XCTAssertEqual(value, &quot;o&quot;) case 1: XCTAssertEqual(value, &quot;old&quot;) default: XCTFail() } promise.fulfill() fulfillmentCount += 1 } } // When sendToServer(&quot;h&quot;) sendToServer(&quot;e&quot;) sendToServer(&quot;l&quot;) sendToServer(&quot;l&quot;) sendToServer(&quot;o&quot;) await sleep(2) sendToServer(&quot;wor&quot;) sendToServer(&quot;ld&quot;) wait(for: [promise], timeout: 10) } func testThrottler2() async throws { // Given let promise = expectation(description: &quot;Ensure throttle before duration&quot;) let throttler = Limiter(policy: .throttle, duration: 1) var end = Date.now + 1 promise.expectedFulfillmentCount = 2 func test() { // Then XCTAssertLessThan(.now, end) promise.fulfill() } // When throttler(task: test) throttler(task: test) throttler(task: test) throttler(task: test) throttler(task: test) await sleep(2) end = .now + 1 throttler(task: test) throttler(task: test) throttler(task: test) await sleep(2) wait(for: [promise], timeout: 10) } func testDebouncer2() async throws { // Given let promise = expectation(description: &quot;Ensure debounce after duration&quot;) let debouncer = Limiter(policy: .debounce, duration: 1) var end = Date.now + 1 promise.expectedFulfillmentCount = 2 func test() { // Then XCTAssertGreaterThan(.now, end) promise.fulfill() } // When debouncer(task: test) debouncer(task: test) debouncer(task: test) debouncer(task: test) debouncer(task: test) await sleep(2) end = .now + 1 debouncer(task: test) debouncer(task: test) debouncer(task: test) await sleep(2) wait(for: [promise], timeout: 10) } private func sleep(_ duration: TimeInterval) async { await Task.sleep(UInt64(duration * 1_000_000_000)) } } </code></pre> <p>I'm hoping for help in seeing anything I missed in the <code>Limiter</code> implementation, or maybe if there's a better way to do debounce and throttle with <code>Swift Concurrency</code>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T15:22:31.357", "Id": "269642", "Score": "0", "Tags": [ "swift" ], "Title": "Debounce and throttle tasks using Swift Concurrency" }
269642
<p>This program converts from number system A to number system B as soon as you input something in it, as a rookie it took a lot of thinking to make it work a seamless and fool-proof way.</p> <p>It converts the number from base A to base 10 and then to base B because the formulas are always the same.</p> <p>It is based on this website's version: <a href="https://codebeautify.org/all-number-converter" rel="nofollow noreferrer">https://codebeautify.org/all-number-converter</a></p> <p>That said i still wanted to post the code here to receive feedback on the way it's structured so i don't pick up some bad habits:</p> <pre><code>import tkinter as tk from tkinter import ttk class MainApplication: numtoletter = { 0: &quot;0&quot;, 1: &quot;1&quot;, 2: &quot;2&quot;, 3: &quot;3&quot;, 4: &quot;4&quot;, 5: &quot;5&quot;, 6: &quot;6&quot;, 7: &quot;7&quot;, 8: &quot;8&quot;, 9: &quot;9&quot;, 10: &quot;A&quot;, 11: &quot;B&quot;, 12: &quot;C&quot;, 13: &quot;D&quot;, 14: &quot;E&quot;, 15: &quot;F&quot;, 16: &quot;G&quot;, 17: &quot;H&quot;, 18: &quot;I&quot;, 19: &quot;J&quot;, 20: &quot;K&quot;, 21: &quot;L&quot;, 22: &quot;M&quot;, 23: &quot;N&quot;, 24: &quot;O&quot;, 25: &quot;P&quot;, 26: &quot;Q&quot;, 27: &quot;R&quot;, 28: &quot;S&quot;, 29: &quot;T&quot;, 30: &quot;U&quot;, 31: &quot;V&quot;, 32: &quot;W&quot;, 33: &quot;X&quot;, 34: &quot;Y&quot;, 35: &quot;Z&quot;, } lettertonum = { &quot;0&quot;: 0, &quot;1&quot;: 1, &quot;2&quot;: 2, &quot;3&quot;: 3, &quot;4&quot;: 4, &quot;5&quot;: 5, &quot;6&quot;: 6, &quot;7&quot;: 7, &quot;8&quot;: 8, &quot;9&quot;: 9, &quot;A&quot;: 10, &quot;B&quot;: 11, &quot;C&quot;: 12, &quot;D&quot;: 13, &quot;E&quot;: 14, &quot;F&quot;: 15, &quot;G&quot;: 16, &quot;H&quot;: 17, &quot;I&quot;: 18, &quot;J&quot;: 19, &quot;K&quot;: 20, &quot;L&quot;: 21, &quot;M&quot;: 22, &quot;N&quot;: 23, &quot;O&quot;: 24, &quot;P&quot;: 25, &quot;Q&quot;: 26, &quot;R&quot;: 27, &quot;S&quot;: 28, &quot;T&quot;: 29, &quot;U&quot;: 30, &quot;V&quot;: 31, &quot;W&quot;: 32, &quot;X&quot;: 33, &quot;Y&quot;: 34, &quot;Z&quot;: 35, } numbercheck = { 2: &quot;01&quot;, 3: &quot;012&quot;, 4: &quot;0123&quot;, 5: &quot;01234&quot;, 6: &quot;012345&quot;, 7: &quot;0123456&quot;, 8: &quot;01234567&quot;, 9: &quot;012345678&quot;, 10: &quot;0123456789&quot;, 11: &quot;0123456789A&quot;, 12: &quot;0123456789AB&quot;, 13: &quot;0123456789ABC&quot;, 14: &quot;0123456789ABCD&quot;, 15: &quot;0123456789ABCDE&quot;, 16: &quot;0123456789ABCDEF&quot;, 17: &quot;0123456789ABCDEFG&quot;, 18: &quot;0123456789ABCDEFGH&quot;, 19: &quot;0123456789ABCDEFGHI&quot;, 20: &quot;0123456789ABCDEFGHIJ&quot;, 21: &quot;0123456789ABCDEFGHIJK&quot;, 22: &quot;0123456789ABCDEFGHIJKL&quot;, 23: &quot;0123456789ABCDEFGHIJKLM&quot;, 24: &quot;0123456789ABCDEFGHIJKLMN&quot;, 25: &quot;0123456789ABCDEFGHIJKLMNO&quot;, 26: &quot;0123456789ABCDEFGHIJKLMNOP&quot;, 27: &quot;0123456789ABCDEFGHIJKLMNOPQ&quot;, 28: &quot;0123456789ABCDEFGHIJKLMNOPQR&quot;, 29: &quot;0123456789ABCDEFGHIJKLMNOPQRS&quot;, 30: &quot;0123456789ABCDEFGHIJKLMNOPQRST&quot;, 31: &quot;0123456789ABCDEFGHIJKLMNOPQRSTU&quot;, 32: &quot;0123456789ABCDEFGHIJKLMNOPQRSTUV&quot;, 33: &quot;0123456789ABCDEFGHIJKLMNOPQRSTUVW&quot;, 34: &quot;0123456789ABCDEFGHIJKLMNOPQRSTUVWX&quot;, 35: &quot;0123456789ABCDEFGHIJKLMNOPQRSTUVWXY&quot;, 36: &quot;0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;, } base = [&quot;Base-2 (Binary)&quot;, &quot;Base-3&quot;, &quot;Base-4&quot;, &quot;Base-5&quot;, &quot;Base-6&quot;, &quot;Base-7&quot;, &quot;Base-8 (Octal)&quot;, &quot;Base-9&quot;, &quot;Base-10 (Decimal)&quot;, &quot;Base-11&quot;, &quot;Base-12&quot;, &quot;Base-13&quot;, &quot;Base-14&quot;, &quot;Base-15&quot;, &quot;Base-16 (Hexadecimal)&quot;, &quot;Base-17&quot;, &quot;Base-18&quot;, &quot;Base-19&quot;, &quot;Base-20&quot;, &quot;Base-21&quot;, &quot;Base-22&quot;, &quot;Base-23&quot;, &quot;Base-24&quot;, &quot;Base-25&quot;, &quot;Base-26&quot;, &quot;Base-27&quot;, &quot;Base-28&quot;, &quot;Base-29&quot;, &quot;Base-30&quot;, &quot;Base-31&quot;, &quot;Base-32&quot;, &quot;Base-33&quot;, &quot;Base-34&quot;, &quot;Base-35&quot;, &quot;Base-36&quot;, ] inputnum = &quot;&quot; # number to be converted outputnum = &quot;&quot; # result of the conversion inputbase = &quot;&quot; # base of the inputnum outputbase = &quot;&quot; # base of the outputnum outputnumto = 0 # where the outputnum goes varx = 0 # to make it so the function &quot;convert&quot; doesn't run when the value of stringvar is changed not through user input vary = 0 # to make it so the &quot;convert&quot; function doesn't run infinitely at line 233 def __init__(self, master): # setting up the window and calling functions for gui creation self.master = master self.master.title(&quot;Number system converter&quot;) self.master.geometry(&quot;600x200&quot;) self.master.resizable(False, False) self.label_title, self.label_equals = self.create_text() self.stringvar_number1, self.entry_number1, self.stringvar_number2, self.entry_number2 = self.create_number_input() self.combobox_base1, self.combobox_base2 = self.create_base_selection() def create_text(self): label_title = tk.Label(self.master, text=&quot;NUMBER SYSTEM CONVERTER&quot;, font=( &quot;Calibri&quot;, 20, &quot;bold&quot;), anchor=tk.CENTER,) label_title.place(x=100, y=0, width=400, height=50) label_equals = tk.Label(self.master, text=&quot;=&quot;, font=( &quot;Calibri&quot;, 20), anchor=tk.CENTER, justify=tk.CENTER) label_equals.place(x=275, y=65, width=50, height=30) return label_title, label_equals def create_number_input(self): # entry(s) for input and stringvars stringvar_number1 = tk.StringVar() stringvar_number1.set(&quot;1&quot;) stringvar_number1.trace(&quot;w&quot;, lambda x, y, z: self.convert(2)) entry_number1 = tk.Entry(self.master, textvariable=stringvar_number1, font=( &quot;Calibri&quot;, 16), borderwidth=0, bg=&quot;white&quot;,) entry_number1.place(x=50, y=65, width=225, height=30) stringvar_number2 = tk.StringVar() stringvar_number2.set(&quot;1&quot;) stringvar_number2.trace(&quot;w&quot;, lambda x, y, z: self.convert(1)) entry_number2 = tk.Entry(self.master, textvariable=stringvar_number2, font=( &quot;Calibri&quot;, 16), borderwidth=0, bg=&quot;white&quot;,) entry_number2.place(x=325, y=65, width=225, height=30) return stringvar_number1, entry_number1, stringvar_number2, entry_number2 def create_base_selection(self): # combobox(s) for selecting the base combobox_base1 = ttk.Combobox( self.master, values=self.base, font=(&quot;Calibri&quot;, 14), state=&quot;readonly&quot;) combobox_base1.place(x=50, y=100, width=225, height=30) popdown_base1 = self.master.tk.call( &quot;ttk::combobox::PopdownWindow&quot;, combobox_base1) self.master.tk.call(f&quot;{popdown_base1}.f.l&quot;, &quot;configure&quot;, &quot;-font&quot;, &quot;Calibri 14&quot;) combobox_base1.current(0) combobox_base1.bind(&quot;&lt;&lt;ComboboxSelected&gt;&gt;&quot;, lambda x: self.inputbase_or_outputbase()) combobox_base2 = ttk.Combobox( self.master, values=self.base, font=(&quot;Calibri&quot;, 14), state=&quot;readonly&quot;) combobox_base2.place(x=325, y=100, width=225, height=30) popdown_base2 = self.master.tk.call( &quot;ttk::combobox::PopdownWindow&quot;, combobox_base2) self.master.tk.call(f&quot;{popdown_base2}.f.l&quot;, &quot;configure&quot;, &quot;-font&quot;, &quot;Calibri 14&quot;) combobox_base2.current(0) combobox_base2.bind(&quot;&lt;&lt;ComboboxSelected&gt;&gt;&quot;, lambda x: self.inputbase_or_outputbase()) return combobox_base1, combobox_base2 def inputbase_or_outputbase(self): # determining if a base belongs to the input or output number if self.outputnumto == 2: self.inputbase = self.combobox_base1.get()[5:7] self.outputbase = self.combobox_base2.get()[5:7] elif self.outputnumto == 1: self.inputbase = self.combobox_base2.get()[5:7] self.outputbase = self.combobox_base1.get()[5:7] if self.vary == 0: self.convert(self.outputnumto) def convert(self, n): # determining which entry modified last (through stringvar tracing) + the process of converting input number in output base (outputbase determined through the previous function) if self.varx == 1: self.varx = 0 return self.outputnumto = n if self.outputnumto == 2: self.inputnum = self.entry_number1.get().upper() elif self.outputnumto == 1: self.inputnum = self.entry_number2.get().upper() self.vary = 1 self.inputbase_or_outputbase() self.vary = 0 if not self.inputbase or not self.outputbase: return for x in self.inputnum: if not x in self.numbercheck[int(self.inputbase)]: if self.outputnumto == 1: self.varx = 1 self.stringvar_number1.set(&quot;Invalid input&quot;) elif self.outputnumto == 2: self.varx = 1 self.stringvar_number2.set(&quot;Invalid input&quot;) return base10num = self.convert_to_base10(self.inputbase, self.inputnum) outputnum = self.convert_to_baseo(self.outputbase, base10num) if self.outputnumto == 1: self.varx = 1 self.stringvar_number1.set(outputnum) elif self.outputnumto == 2: self.varx = 1 self.stringvar_number2.set(outputnum) def convert_to_base10(self, inputbase, inputnum): # converting inputnum to base10 inputbase = int(inputbase) inputnum = inputnum[::-1] multiply = 1 base10num = 0 for x in inputnum: x = self.lettertonum[x] base10num = (x * multiply) + base10num multiply = multiply * inputbase return base10num def convert_to_baseo(self, outputbase, base10num): # converting inputnum to outputbase outputbase = int(outputbase) base10num = int(base10num) outputnum = &quot;&quot; while base10num &gt; 0: outputnum = outputnum + self.numtoletter[base10num % outputbase] base10num = base10num // outputbase outputnum = outputnum[::-1] return outputnum if __name__ == &quot;__main__&quot;: root = tk.Tk() app = MainApplication(root) root.mainloop() </code></pre>
[]
[ { "body": "<p>In no particular order:</p>\n<ul>\n<li><code>numtoletter</code> and similar variables and method names should be <code>num_to_letter</code> (lower_snake_case)</li>\n<li><code>numtoletter</code> and <code>lettertonum</code> should not be written out like that, and should be formed via loops - which computers are good at</li>\n<li><code>numbercheck</code> is not necessary if you listen for <code>ValueError</code>s from <code>int()</code></li>\n<li><code>base</code> should also be formed via a loop</li>\n<li>you have a bunch of symbols initialized in static scope of your class. Moving your constants between there and global scope is debatable, but <code>inputnum</code> through <code>varx</code> should not exist at all.</li>\n<li><a href=\"https://www.theserverside.com/feature/Why-GitHub-renamed-its-master-branch-to-main\" rel=\"nofollow noreferrer\">Don't call things <code>master</code></a>.</li>\n<li>You've accepted a parent widget parameter to your constructor - this is good. In theory it means that you could populate <em>any</em> widget with your converter. However, it also means that your class instance does not <em>own</em> the parent, and so it should not be responsible for setting title and geometry.</li>\n<li>Your title label is unnecessary - you've already set a title on the parent window decorator.</li>\n<li>You should generally avoid <code>place</code> and instead favour grid-like placement. This is less fragile and manual. You can still add padding, etc. if you want to.</li>\n<li>Some of your visual modifications such as giant font aren't all that useful. Generic UI scaling in tkinter is <a href=\"https://stackoverflow.com/questions/34132203/scaling-of-tkinter-gui-in-4k-38402160-resolution\">sort of a mess</a>, and would still require that you modify your fonts; but my opinion is: the user has control of their window manager, and all self-respecting window managers have some kind of utility to apply zoom.</li>\n<li>You do not need to save references to any of your widgets - just your variables.</li>\n<li>You should always pass parent, <code>name</code> and <code>value</code> parameters to your tk variables on construction. This will obviate your first call to <code>set</code>.</li>\n<li>Avoid lambdas. You can just make a bound method on your class for your traces. Do not fake the names <code>x</code>, <code>y</code> and <code>z</code>; those are actually <code>name</code>, <code>index</code> and <code>mode</code>.</li>\n<li>When tk sets the background colour of a combo box to grey, it's trying communicate something: that the input half of the combo box is read-only, and can only be changed via dropdown. My opinion is that it's confusing to set this to white, and the default should be left.</li>\n<li>You used <code>StringVar</code> on your inputs - good! You should do the same with your combo boxes! This will obviate your call to <code>current()</code>.</li>\n<li>Don't call <code>bind</code> at all. This whole machinery of input-or-output-base and last-known-edited-input is too complicated. You can figure out which input was just edited by which trace was called; and assuming that a change in base of the left-hand side auto-converts the right-hand value is intuitive enough that I don't find it useful to do anything more complex.</li>\n<li>The <code>n</code> parameter to <code>convert</code> is only ever one of two values, so I recommend changing it to a <code>forward: bool</code>. Or, as I've shown, just accept a source and destination group object that holds references to your number and base variables.</li>\n<li>Add PEP484 type hints.</li>\n<li><code>trace()</code> is deprecated and should be <code>trace_add()</code>.</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>from string import ascii_uppercase\nimport tkinter as tk\nfrom tkinter import ttk\nfrom typing import Tuple, Iterator, Dict, List, Callable\n\n\ndef base_pairs() -&gt; Iterator[Tuple[str, int]]:\n for base in range(2, 37):\n desc = f'Base-{base}'\n name = BASE_NAMES.get(base)\n if name is not None:\n desc += f' ({name})'\n yield desc, base\n\n\nBASE_NAMES = {\n 2: 'Binary',\n 8: 'Octal',\n 10: 'Decimal',\n 16: 'Hexadecimal',\n}\nBASES: Dict[str, int] = dict(base_pairs())\nDEFAULT_BASE = next(iter(BASES.keys()))\nNUM_TO_LETTER: List[str] = [\n *(str(x) for x in range(10)),\n *ascii_uppercase,\n]\n\n\ndef convert_to_base(output_base: int, base10_num: int) -&gt; str:\n &quot;&quot;&quot;converting inputnum to outputbase&quot;&quot;&quot;\n output_num = ''\n\n while base10_num &gt; 0:\n base10_num, remainder = divmod(base10_num, output_base)\n output_num = NUM_TO_LETTER[remainder] + output_num\n\n return output_num\n\n\nclass InputGroup:\n def __init__(\n self, parent: tk.Tk, index: int,\n convert: Callable[[], None],\n ) -&gt; None:\n self.convert = convert\n\n self.number_var = tk.StringVar(\n parent, name=f'number{index}', value='1',\n )\n self.set_trace()\n tk.Entry(\n parent, textvariable=self.number_var,\n ).grid(row=0, column=2*index)\n\n self.base_var = tk.StringVar(\n parent, name=f'base{index}', value=DEFAULT_BASE,\n )\n self.base_var.trace_add(mode='write', callback=self.trace)\n\n names = tuple(BASES.keys())\n ttk.Combobox(\n parent, values=names, state='readonly',\n textvariable=self.base_var,\n ).grid(row=1, column=2*index)\n\n def set_trace(self) -&gt; None:\n self.trace_id = self.number_var.trace_add(mode='write', callback=self.trace)\n\n def trace(self, name: str, index: str, mode: str) -&gt; None:\n self.convert()\n\n @property\n def base(self) -&gt; int:\n return BASES[self.base_var.get()]\n\n @property\n def value(self) -&gt; int:\n value = self.number_var.get().upper()\n return int(value, self.base)\n\n @value.setter\n def value(self, value: int) -&gt; None:\n as_base = convert_to_base(self.base, value)\n self.set_output(as_base)\n\n def set_output(self, value: str) -&gt; None:\n self.number_var.trace_remove(mode='write', cbname=self.trace_id)\n try:\n self.number_var.set(value)\n finally:\n self.set_trace()\n\n\nclass MainApplication:\n def __init__(self, parent: tk.Tk) -&gt; None:\n &quot;&quot;&quot;setting up the window and calling functions for gui creation&quot;&quot;&quot;\n self.parent = parent\n\n tk.Label(self.parent, text='=').grid(row=0, column=1)\n\n self.groups = (\n InputGroup(parent, index=0, convert=self.convert_forward),\n InputGroup(parent, index=1, convert=self.convert_backward),\n )\n\n def convert_forward(self) -&gt; None:\n self.convert(*self.groups)\n\n def convert_backward(self) -&gt; None:\n self.convert(*self.groups[::-1])\n\n def convert(self, source: InputGroup, dest: InputGroup) -&gt; None:\n try:\n dest.value = source.value\n except ValueError:\n dest.set_output('Invalid input')\n\n\ndef main() -&gt; None:\n root = tk.Tk()\n root.title('Number system converter')\n root.resizable(width=False, height=False)\n MainApplication(root)\n root.mainloop()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T02:50:32.897", "Id": "269678", "ParentId": "269643", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T15:25:50.103", "Id": "269643", "Score": "3", "Tags": [ "python", "tkinter", "number-systems" ], "Title": "Number system converter GUI" }
269643
<p>Below is my code:</p> <pre><code>private double GetImageValue(Bitmap Image) { double ImageValue = 0; for (int X = 0; X &lt; Image.Width; X++) { for (int Y = 0; Y &lt; Image.Height; Y++) { Color CurrentPixel = Image.GetPixel(X, Y); ImageValue += CurrentPixel.A + CurrentPixel.B + CurrentPixel.G + CurrentPixel.R; } } return ImageValue; } </code></pre> <p>The following code returns the total value of each pixel in the image. Is there a way to speed up the procedure? Thanks for any help.</p>
[]
[ { "body": "<p>Bitmap data is stored in an unmanaged GDI object. Every time you call <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.drawing.bitmap.getpixel?view=windowsdesktop-5.0\" rel=\"nofollow noreferrer\"><code>GetPixel</code></a> the system needs to access this object. You can speed it up by using <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.drawing.bitmap.lockbits?view=windowsdesktop-5.0\" rel=\"nofollow noreferrer\"><code>LockBits</code></a> to directly access the raw image data.</p>\n<pre><code>private double GetImageValue(Bitmap image)\n{\n double imageValue = 0;\n\n // Lock the bitmap's bits. \n var rect = new Rectangle(0, 0, image.Width, image.Height);\n var bmpData = image.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);\n\n // Get the address of the first line.\n var ptr = bmpData.Scan0;\n\n // Declare an array to hold the bytes of the bitmap.\n var bytes = Math.Abs(bmpData.Stride) * image.Height;\n var values = new byte[bytes];\n\n // Copy the RGB values into the array.\n System.Runtime.InteropServices.Marshal.Copy(ptr, values, 0, bytes);\n\n // Add the rgb values to ImageValue\n for (int y = 0; y &lt; image.Height; y++)\n {\n int lineStart = y * Math.Abs(bmpData.Stride);\n for (int x = 0; x &lt; image.Width * 3; x++)\n {\n imageValue += values[lineStart + x];\n }\n }\n\n // Unlock the bits.\n image.UnlockBits(bmpData);\n\n return imageValue;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T17:49:29.273", "Id": "269651", "ParentId": "269644", "Score": "7" } } ]
{ "AcceptedAnswerId": "269651", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T15:38:06.037", "Id": "269644", "Score": "4", "Tags": [ "c#", "image" ], "Title": "Get image value total" }
269644
<p>I have a List of Car with 2 props are String and Integer like this: (A,6) (B,2) (C,9) (D,17) (E,8) (F,17) (G,2)</p> <p>and the result look like this: (A,6) (D,17) (C,9) (B,2) (E,8) (G,2) (F,17)</p> <p>Purpose: Swap 2 obj that once has MIN Integer and once has MAX Integer in the List</p> <p>Here is my code:</p> <pre><code>Class car { private String maker; private int rate; } public void f2(List&lt;Car&gt; t) { int max = t.get(0).getRate(); int min = max; for (Car car : t) { if(max &lt; car.getRate()) max = car.getRate(); if(min &gt; car.getRate()) min = car.getRate(); } System.out.println(min + &quot;\t&quot; + max); int indexMin = 0; int indexMax = 0; for (int i = 0; i &lt; t.size(); i++) { if(t.get(i).getRate() == min) indexMin = i; if(t.get(i).getRate() == max){ indexMax = i; } } System.out.println(indexMin + &quot;\t&quot; + indexMax); Collections.swap(t, indexMin, indexMax); int a = 0; int b = 0; int count = indexMax; for (int i = 0; i &lt; count; i++) { if(t.get(i).getRate() == min) a = i; if(t.get(i).getRate() == max) { b = i; break; } } Collections.swap(t, a, b); } </code></pre> <p>My code is inefficient if the List has lots of pair of MIN and MAX int. I want to improve it but got stuck. Please help me!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T18:14:14.887", "Id": "532081", "Score": "0", "body": "Welcome to Stack Review, please provide an explanation with input and output about what your code does and if you can format the code because it is difficult to read at the moment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T18:25:02.200", "Id": "532084", "Score": "2", "body": "It's not clear why B was replaced by D and not by F, or why G was replaced by F and not D. Please add an explanation for this behavior." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T09:21:03.523", "Id": "532136", "Score": "0", "body": "I took this task from my test, it’s just said that swap MIN and MAX in the list and gave me a test case like above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T09:22:24.737", "Id": "532137", "Score": "0", "body": "I think that may be the purpose is swap MIN MAX that located near together." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T16:32:56.167", "Id": "269649", "Score": "0", "Tags": [ "java", "performance" ], "Title": "Swap MIN, MAX object in a list" }
269649
<p>For a hobby project I want to visualize the current crypto market in bubbles. The idea is to clone cryptobubbles.net. I've already made a prototype at the moment, but the frames are on the low side. How can I optimize my code to get more frames?</p> <p>The application is made in JavaScript with react and d3</p> <pre><code>import React, { Component } from &quot;react&quot;; import &quot;../styles/style.css&quot;; import $ from &quot;jquery&quot;; import * as d3 from &quot;d3&quot;; const crypto = require(&quot;../data/cryptoData.json&quot;); const coins = []; var data = []; for (let i = 0; i &lt; crypto.length; i++) { var coin = crypto[i]; var minplus = String(coin.market_data.price_change_percentage_24h); if (minplus.includes(&quot;-&quot;)) { coin[&quot;color&quot;] = &quot;red&quot;; } else { coin[&quot;color&quot;] = &quot;green&quot;; } coins.push(coin); } coins.forEach((coin) =&gt; { var text = coin.symbol; var r = coin.market_data.market_cap.usd / 6000000000; if (r &lt; 5) { r = 10; } data.push({ text: text, category: coin.market_data.price_change_percentage_24h + &quot;%&quot;, image: coin.image.large, color: coin.color, r: r, }); }); function collide(alpha) { var quadtree = d3.geom.quadtree(data); return function (d) { var r = d.r + 10, nx1 = d.x - r, nx2 = d.x + r, ny1 = d.y - r, ny2 = d.y + r; quadtree.visit(function (quad, x1, y1, x2, y2) { if (quad.point &amp;&amp; quad.point !== d) { var x = d.x - quad.point.x, y = d.y - quad.point.y, l = Math.sqrt(x * x + y * y), r = d.r + quad.point.r; if (l &lt; r) { l = ((l - r) / l) * (1 + alpha); d.x -= x *= l; d.y -= y *= l; quad.point.x += x; quad.point.y += y; } } return x1 &gt; nx2 || x2 &lt; nx1 || y1 &gt; ny2 || y2 &lt; ny1; }); }; } const bubbleCloud = (element) =&gt; { var container = d3.select(&quot;.bubble-cloud&quot;); var $container = $(&quot;.bubble-cloud&quot;); var containerWidth = $container.width(); var containerHeight = $container.height(); var svgContainer = container .append(&quot;svg&quot;) .attr(&quot;width&quot;, containerWidth) .attr(&quot;height&quot;, containerHeight); // prepare layout var force = d3.layout .force() .size([containerWidth, containerHeight]) .gravity(0) .charge(0) .friction(1); // load data force.nodes(data).start(); // create item groups var node = svgContainer .selectAll(&quot;.node&quot;) .data(data) .enter() .append(&quot;g&quot;) .attr(&quot;class&quot;, &quot;node&quot;) .call(force.drag); var zoom = d3.behavior .zoom() .scaleExtent([1, 50]) .on(&quot;zoom&quot;, function () { var e = d3.event, tx = Math.min( 0, Math.max(e.translate[0], containerWidth - containerWidth * e.scale) ), ty = Math.min( 0, Math.max(e.translate[1], containerHeight - containerHeight * e.scale) ); zoom.translate([tx, ty]); node.attr( &quot;transform&quot;, [&quot;translate(&quot; + [tx, ty] + &quot;)&quot;, &quot;scale(&quot; + e.scale + &quot;)&quot;].join(&quot; &quot;) ); }); node.call(zoom); // create circles var defs = node.append(&quot;defs&quot;); function makeFiter(id, color) { //make a filter if filter id not present if (defs.selectAll(&quot;#&quot; + id).empty()) { var filter = defs .append(&quot;filter&quot;) .attr(&quot;id&quot;, id) .attr(&quot;height&quot;, &quot;300%&quot;) .attr(&quot;width&quot;, &quot;300%&quot;) .attr(&quot;x&quot;, &quot;-100%&quot;) .attr(&quot;y&quot;, &quot;-100%&quot;); filter .append(&quot;feGaussianBlur&quot;) .attr(&quot;in&quot;, &quot;SourceAlpha&quot;) .attr(&quot;stdDeviation&quot;, 10) .attr(&quot;result&quot;, &quot;blur&quot;); filter .append(&quot;feOffset&quot;, 0) .attr(&quot;in&quot;, &quot;blur&quot;) .attr(&quot;result&quot;, &quot;offsetBlur&quot;); filter .append(&quot;feFlood&quot;) .attr(&quot;in&quot;, &quot;offsetBlur&quot;) .attr(&quot;flood-color&quot;, color) .attr(&quot;flood-opacity&quot;, &quot;1&quot;) .attr(&quot;result&quot;, &quot;offsetColor&quot;); filter .append(&quot;feComposite&quot;) .attr(&quot;in&quot;, &quot;offsetColor&quot;) .attr(&quot;in2&quot;, &quot;offsetBlur&quot;) .attr(&quot;operator&quot;, &quot;in&quot;) .attr(&quot;result&quot;, &quot;offsetBlur&quot;); var feMerge = filter.append(&quot;feMerge&quot;); feMerge.append(&quot;feMergeNode&quot;).attr(&quot;in&quot;, &quot;offsetBlur&quot;); feMerge.append(&quot;feMergeNode&quot;).attr(&quot;in&quot;, &quot;SourceGraphic&quot;); } return &quot;url(#&quot; + id + &quot;)&quot;; //return the filter id } function getFilter(d) { if (d.color === &quot;red&quot;) { return makeFiter(&quot;fill-text-red&quot;, &quot;red&quot;); } else if (d.color === &quot;green&quot;) { return makeFiter(&quot;fill-text-green&quot;, &quot;green&quot;); } } defs .selectAll(null) .data(data) .enter() .append(&quot;pattern&quot;) .attr(&quot;id&quot;, function (d) { return d.image; }) .attr(&quot;height&quot;, &quot;100%&quot;) .attr(&quot;width&quot;, &quot;100%&quot;) .attr(&quot;patternContentUnits&quot;, &quot;objectBoundingBox&quot;) .append(&quot;image&quot;) .attr(&quot;height&quot;, 1) .attr(&quot;width&quot;, 1) .attr(&quot;preserveAspectRatio&quot;, &quot;none&quot;) .attr(&quot;xlink:href&quot;, function (d) { return d.image; }); node .append(&quot;circle&quot;) .attr(&quot;r&quot;, 1e-6) .style(&quot;fill&quot;, function (d) { return &quot;url(#&quot; + d.image + &quot;)&quot;; }) .attr(&quot;filter&quot;, function (d) { return getFilter(d); }) .on(&quot;mouseover&quot;, function (d) { d3.select(this) .attr(&quot;r&quot;, 10) .style(&quot;stroke&quot;, &quot;white&quot;) .style(&quot;cursor&quot;, &quot;pointer&quot;); }) .on(&quot;mouseout&quot;, function (d) { d3.select(this).attr(&quot;r&quot;, 5.5).style(&quot;stroke&quot;, &quot;none&quot;); }); // create labels node .append(&quot;text&quot;) .text(function (d) { return d.text; }) .classed(&quot;text&quot;, true) .style({ fill: &quot;#141823 &quot;, &quot;text-anchor&quot;: &quot;middle&quot;, &quot;font-size&quot;: &quot;1vw&quot;, &quot;font-weight&quot;: &quot;bold&quot;, &quot;text-transform&quot;: &quot;uppercase&quot;, &quot;font-family&quot;: &quot;Open Sans, sans-serif&quot;, }); //.attr(&quot;stroke&quot;, &quot;black&quot;) //.attr(&quot;stroke-width&quot;, &quot;1px&quot;); node .append(&quot;text&quot;) .text(function (d) { return d.category; }) .classed(&quot;category&quot;, true) .style(&quot;fill&quot;, function (d) { return d.category.match(&quot;-&quot;) ? &quot;red&quot; : &quot;green&quot;; }) .style({ &quot;text-anchor&quot;: &quot;middle&quot;, &quot;font-size&quot;: &quot;12px&quot;, &quot;font-weight&quot;: &quot;bold&quot;, &quot;text-transform&quot;: &quot;uppercase&quot;, &quot;font-family&quot;: &quot;Open Sans, sans-serif&quot;, }); //.attr(&quot;stroke&quot;, &quot;black&quot;) //.attr(&quot;stroke-width&quot;, &quot;1px&quot;); node //.append(&quot;line&quot;) //.classed(&quot;line&quot;, true) //.attr({ // x1: 0, // y1: 0, // x2: 0, // y2: 0, //}) .attr(&quot;stroke-width&quot;, 1) .attr(&quot;stroke&quot;, function (d) { return d.stroke; }); // put circle into movement force.on(&quot;tick&quot;, function (e) { d3.selectAll(&quot;circle&quot;) .each(collide(0.1)) .attr(&quot;r&quot;, function (d) { return d.r; }) .attr(&quot;cx&quot;, function (d) { // boundaries if (d.x &lt;= d.r) { d.x = d.r + 1; } if (d.x &gt;= containerWidth - d.r) { d.x = containerWidth - d.r - 1; } return d.x; }) .attr(&quot;cy&quot;, function (d) { // boundaries if (d.y &lt;= d.r) { d.y = d.r + 1; } if (d.y &gt;= containerHeight - d.r) { d.y = containerHeight - d.r - 1; } return d.y; }); d3.selectAll(&quot;line&quot;).attr({ x1: function (d) { return d.x - d.r + 10; }, y1: function (d) { return d.y; }, x2: function (d) { return d.x + d.r - 10; }, y2: function (d) { return d.y; }, }); d3.selectAll(&quot;.text&quot;) .attr(&quot;x&quot;, function (d) { return d.x; }) .attr(&quot;y&quot;, function (d) { return d.y - 10; }); d3.selectAll(&quot;.category&quot;) .attr(&quot;x&quot;, function (d) { return d.x; }) .attr(&quot;y&quot;, function (d) { return d.y + 20; }); force.alpha(0.1); }); }; class Bubbles extends Component { render() { return &lt;div className=&quot;bubble-cloud&quot; ref={bubbleCloud}&gt;&lt;/div&gt;; } } export default Bubbles; </code></pre> <p>The demo: <a href="https://cryptobubbles.netlify.app/" rel="nofollow noreferrer">https://cryptobubbles.netlify.app/</a></p> <p>If there are other things that stand out about my code, I'd like to hear about them too.</p> <p>Maybe I have to look at p5.js?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T17:30:38.907", "Id": "269650", "Score": "3", "Tags": [ "javascript", "performance", "react.js", "jsx", "data-visualization" ], "Title": "Cryptomarket data visualization" }
269650
<p>I'm at an intermediate-ish level in java programming in school (using repl.it), and I have a math related project I'm working on. After the user inputs their own measurements, &quot;calculating.......&quot; is outputted into the console and the periods are &quot;animated&quot; so to say. The code works fine but I'm convinced there has to be a way to condense this mess of 50 some odd lines that just moves some dots around, any input is greatly appreciated.</p> <pre><code>class Main { public static void main(String[] args) { System.out.print(&quot;\n\n\n\ncalculating.......&quot;); for(int i = 0; i &lt; 3; ++i) { try {Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace();} System.out.print(&quot;\b &quot;); try {Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace();} System.out.print(&quot;\b\b &quot;); try {Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace();} System.out.print(&quot;\b\b\b &quot;); try {Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace();} System.out.print(&quot;\b\b\b\b &quot;); try {Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace();} System.out.print(&quot;\b\b\b\b\b &quot;); try {Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace();} System.out.print(&quot;\b\b\b\b\b\b &quot;); try {Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace();} System.out.print(&quot;\b\b\b\b\b\b\b &quot;); try {Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace();} System.out.print(&quot;\b.&quot;); try {Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace();} System.out.print(&quot;\b\b..&quot;); try {Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace();} System.out.print(&quot;\b\b\b...&quot;); try {Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace();} System.out.print(&quot;\b\b\b\b....&quot;); try {Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace();} System.out.print(&quot;\b\b\b\b\b.....&quot;); try {Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace();} System.out.print(&quot;\b\b\b\b\b\b......&quot;); try {Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace();} System.out.print(&quot;\b\b\b\b\b\b\b.......&quot;); } } } </code></pre>
[]
[ { "body": "<ol>\n<li><p>Write a function. You have code that is repetitious? Write a function to hide it away!</p>\n<pre><code>private static void show_string(String s) {\n try {\n Thread.sleep(200);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n\n System.out.print(s);\n}\n</code></pre>\n</li>\n<li><p>In fact, write several functions! Use function names to explain what you are doing. Also, it would be good if you wrote the functions in such a way as to facilitate other refactorings:</p>\n<pre><code>public static final int ANIMATION_DELAY_MSEC = 200;\npublic static final String BKSP = &quot;\\b&quot;;\npublic static final String DOT = &quot;.&quot;;\npublic static final String SPACE = &quot; &quot;;\n\nprivate static void delay_msec(int msec) {\n try {\n Thread.sleep(msec);\n } catch (InterruptedException e) {\n e.printStackTrace();\n } \n}\n\nprivate static void print_ntimes(String s, int n) {\n if (n &lt; 0) n = 0;\n for (int i = 0; i &lt; n; ++i)\n System.out.print(s);\n}\n\nprivate static void hide_dots(int count) {\n print_ntimes(BKSP, count);\n print_ntimes(SPACE, count);\n}\n\nprivate static void show_dots(int count) {\n print_ntimes(BKSP);\n print_ntimes(DOT);\n}\n\n\n// main\n{\n // ...\n for (int i = 0; i &lt; MAX_DOTS; ++i) {\n hide_dots(i); \n delay_msec(ANIMATION_DELAY_MSEC);\n }\n\n for (int i = 0; i &lt; MAX_DOTS; ++i) { \n show_dots(i);\n delay_msec(ANIMATION_DELAY_MSEC);\n }\n // ...\n}\n</code></pre>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T02:42:12.757", "Id": "269676", "ParentId": "269653", "Score": "3" } }, { "body": "<p>@aghast makes many good points, but I'd add a few more.</p>\n<p>Firstly, the string being printed can be simplified. In the first half of the processing, a single period character is being cleared at each step, so &quot;\\b \\b&quot; could be used. In the second half, we're just adding one period...</p>\n<p>Secondly, on Unix-like systems standard output is line-buffered, so no output appears until either a new line is written or <code>flush()</code> is called.</p>\n<p>Thirdly, the handling of <code>InterruptedException</code> is ugly. If a sleep received an interrupt in this context we'd probably want to restart it for the remaining time not dump a stack trace. So you'd need to have calculated an end time for the sleep and recalculate the sleep time on interrupt. I'd therefore wrap the sleep in a loop, but I can imagine a recursive approach working.</p>\n<p>Finally, I'd prefer to stick to Java conventions, so in place of @aghast's &quot;functions&quot; I'd use the term &quot;methods&quot;, and I'd use <code>camelCase</code> naming rather than <code>snake_case</code> so methods were called (for example) <code>hideDots</code> rather than <code>hide_dots</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T03:52:04.143", "Id": "269679", "ParentId": "269653", "Score": "2" } }, { "body": "<p><strong>First Welcome to CodeReview</strong>.</p>\n<p>Some comments on your code:</p>\n<ol>\n<li><p>The code need a clear indentation, most IDE can help formatting code easily with one shortcut.</p>\n</li>\n<li><p>You may separate sections with new line, it will ease readability, also it may help to spot new method candidate.</p>\n</li>\n<li><p>If your see a value repeated many times in your method/class, it's preferable to declare it as constant.</p>\n</li>\n<li><p>Main method is too long, better to create methods (or classes) <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">with only one responsibility</a>.</p>\n</li>\n<li><p>I see no testing in your code, starting with test before writing production code, gives more understanding of the feature and also help to refactor your code later with confidence, so you may give <a href=\"https://en.wikipedia.org/wiki/Test-driven_development\" rel=\"nofollow noreferrer\">TDD</a> a try.</p>\n</li>\n<li><p>Better to give a descriptive name to your class instead of generic one like <code>Main</code> for better readability.</p>\n</li>\n<li><p>Thank you! I learnt how to do a text animation from your code.</p>\n</li>\n</ol>\n<p>Your original code might be better like:</p>\n<pre><code>class TextAnimation {\n \n public static void main(String[] args) {\n System.out.print(&quot;\\n\\n\\n\\ncalculating.......&quot;);\n \n for (int i = 0; i &lt; 3; ++i) {\n try {\n Thread.sleep(200);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n System.out.print(&quot;\\b &quot;);\n \n try {\n Thread.sleep(200);\n } catch (InterruptedException e) {\n e.printStackTrace();\n } \n System.out.print(&quot;\\b\\b &quot;);\n \n try {\n Thread.sleep(200);\n } catch (InterruptedException e) {\n e.printStackTrace();\n } \n System.out.print(&quot;\\b\\b\\b &quot;);\n \n try {\n Thread.sleep(200);\n } catch (InterruptedException e) {\n e.printStackTrace();\n } \n System.out.print(&quot;\\b\\b\\b\\b &quot;);\n \n try {\n Thread.sleep(200);\n } catch (InterruptedException e) {\n e.printStackTrace();\n } \n System.out.print(&quot;\\b\\b\\b\\b\\b &quot;);\n \n try {\n Thread.sleep(200);\n } catch (InterruptedException e) {\n e.printStackTrace();\n } \n System.out.print(&quot;\\b\\b\\b\\b\\b\\b &quot;);\n \n try {\n Thread.sleep(200);\n } catch (InterruptedException e) {\n e.printStackTrace();\n } \n System.out.print(&quot;\\b\\b\\b\\b\\b\\b\\b &quot;);\n \n try {\n Thread.sleep(200);\n } catch (InterruptedException e) {\n e.printStackTrace();\n } \n System.out.print(&quot;\\b.&quot;);\n \n try {\n Thread.sleep(200);\n } catch (InterruptedException e) {\n e.printStackTrace();\n } \n System.out.print(&quot;\\b\\b..&quot;);\n \n try {\n Thread.sleep(200);\n } catch (InterruptedException e) {\n e.printStackTrace();\n } \n System.out.print(&quot;\\b\\b\\b...&quot;);\n \n try {\n Thread.sleep(200);\n } catch (InterruptedException e) {\n e.printStackTrace();\n } \n System.out.print(&quot;\\b\\b\\b\\b....&quot;);\n \n try {\n Thread.sleep(200);\n } catch (InterruptedException e) {\n e.printStackTrace();\n } \n System.out.print(&quot;\\b\\b\\b\\b\\b.....&quot;);\n \n try {\n Thread.sleep(200);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n System.out.print(&quot;\\b\\b\\b\\b\\b\\b......&quot;);\n \n try { \n Thread.sleep(200);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n System.out.print(&quot;\\b\\b\\b\\b\\b\\b\\b.......&quot;);\n }\n }\n\n}\n</code></pre>\n<hr />\n<p><strong>Back to your original question</strong>, and in order to make the code better, I will suggest the following code (<em>I put a comment in code just to explain the usage in this context, but I don't recommend to do so in your production code</em>):</p>\n<pre><code>class TextAnimation {\n\n public static void main(String[] args) {\n int maxDots = 7;\n int animationCycleCount = 3;\n\n System.out.print(&quot;\\n&quot;.repeat(4) + &quot;calculating&quot; + &quot;.&quot;.repeat(maxDots));\n\n for(int i = 0; i &lt; animationCycleCount; ++i) {\n waiting();\n hideDots(maxDots);\n showDots(maxDots);\n }\n }\n\n// Each method is declared directly below its caller.\n \n private static void waiting() {\n try {\n TimeUnit.MILLISECONDS.sleep(200);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt(); // set interrupt flag\n }\n }\n\n private static void hideDots(int countDotsToHide) {\n animateWithString(&quot; &quot;, countDotsToHide);\n }\n\n private static void animateWithString(String value, int maxOccurrence) {\n IntStream.rangeClosed(1, maxOccurrence).forEach(times -&gt; { // Use java 8+ stream\n System.out.print(getNewSuffix(value, times));\n waiting();\n });\n }\n\n static String getNewSuffix(String c, int times) {\n return &quot;\\b&quot;.repeat(times) + c.repeat(times);\n }\n\n private static void showDots(int countDotsToShow) {\n animateWithString(&quot;.&quot;, countDotsToShow);\n }\n\n}\n</code></pre>\n<p>And a Test for <code>getNewSuffix</code> method, (you may add other tests as well):</p>\n<pre><code>import org.junit.Test; \nimport static org.junit.Assert.assertEquals;\n\npublic class TextAnimationTest {\n\n @Test\n public void getNewSuffix_should_get_n_occurrences_with_n_back_spaces() {\n // When\n var suffix = TextAnimation.getNewSuffix(&quot;.&quot;, 3);\n\n // Then\n var expectedSuffix = &quot;\\b\\b\\b...&quot;;\n assertEquals(expectedSuffix, suffix);\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T00:16:37.860", "Id": "269835", "ParentId": "269653", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T17:56:19.030", "Id": "269653", "Score": "1", "Tags": [ "java" ], "Title": "I'm printing an \"animated\" ellipsis into the console but the code is incredibly clunky and repetitive, can I condense it somehow?" }
269653
<p>I am creating a .NET Framework MVC EF application for PC components. I wanted to make full use of inheritance, polymorphism and generic repository pattern - but was wondering if my initial design implementation is the best way to go about it.</p> <p>The major sections of the codebase are below:</p> <hr /> <h1>Repository</h1> <p>I wrote this intending for it to be a generic repository for each component to call to retrieve records from the db, but as you'll see in the controller class I end up declaring several repository instances anyway.</p> <p><strong>ComponentRepository.cs</strong></p> <pre><code>public class ComponentsRepository&lt;T&gt; : IComponentRepository&lt;T&gt; where T : class, IComponent { private readonly ApplicationDbContext _context; private DbSet&lt;T&gt; table = null; public ComponentsRepository() { _context = new ApplicationDbContext(); table = _context.Set&lt;T&gt;(); } public ComponentsRepository(ApplicationDbContext context) { _context = context; table = context.Set&lt;T&gt;(); } public void Delete(int id) { table.Remove(GetById(id)); } public IEnumerable&lt;T&gt; GetAll() { return table; } public T GetById(int id) { return table.Find(id); } public void Insert(T component) { table.Add(component); } public void Save() { _context.SaveChanges(); } public void Update(T component) { table.Attach(component); _context.Entry(component).State = EntityState.Modified; } private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { _context.Dispose(); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } </code></pre> <h1>Component Models</h1> <p>I require all components to have a shared parent class for grouping in lists, basket, etc. Each component has unique properties that act as the specifications. (e.g. Core clock)</p> <p><strong>Component.cs</strong></p> <pre><code>public class Component : Interfaces.IComponent { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [DisplayName(&quot;Name&quot;)] public string Name { get; set; } [DisplayName(&quot;Description&quot;)] public string Description { get; set; } [DisplayName(&quot;Price&quot;)] public decimal Price { get; set; } public Manufacturer Manufacturer { get; set; } [DisplayName(&quot;Component Type&quot;)] public virtual ComponentType ComponentType =&gt; ComponentType.NoType; public virtual string GetComponentTypeLink =&gt; &quot;&quot;; } </code></pre> <p><strong>CPU.cs</strong></p> <pre><code>public class CPU : Component { [DisplayName(&quot;Component Type&quot;)] public override ComponentType ComponentType =&gt; ComponentType.CPU; public override string GetComponentTypeLink =&gt; new UrlHelper(HttpContext.Current.Request.RequestContext).Action(&quot;CPU&quot;, &quot;Products&quot;); [DisplayName(&quot;Core Count&quot;)] public int CoreCount { get; set; } [DisplayName(&quot;Core Clock&quot;)] public string CoreClock { get; set; } } </code></pre> <p><strong>Storage.cs</strong></p> <pre><code>public class Storage : Component { [DisplayName(&quot;Component Type&quot;)] public override ComponentType ComponentType =&gt; ComponentType.Storage; public override string GetComponentTypeLink =&gt; new UrlHelper(HttpContext.Current.Request.RequestContext).Action(&quot;Storage&quot;, &quot;Products&quot;); [DisplayName(&quot;Size&quot;)] public decimal Size { get; set; } [DisplayName(&quot;Read Speed&quot;)] public int ReadSpeed { get; set; } [DisplayName(&quot;Write Speed&quot;)] public int WriteSpeed { get; set; } } </code></pre> <h1>Controller</h1> <p><strong>ComponentsController.cs</strong></p> <pre><code>public class ComponentsController : Controller { private readonly IComponentRepository&lt;CPU&gt; _CPURepository; private readonly IComponentRepository&lt;Storage&gt; _StorageRepository; private readonly IComponentRepository&lt;CPUCooler&gt; _CPUCoolerRepository; private readonly IComponentRepository&lt;Memory&gt; _MemoryRepository; public ComponentsController() { _CPURepository = new ComponentsRepository&lt;CPU&gt;(); _StorageRepository = new ComponentsRepository&lt;Storage&gt;(); _CPUCoolerRepository = new ComponentsRepository&lt;CPUCooler&gt;(); _MemoryRepository = new ComponentsRepository&lt;Memory&gt;(); } public ActionResult Index() { // Simulate list, basket, checkout, etc. List&lt;IComponent&gt; componentList = new List&lt;IComponent&gt;(); componentList.AddRange(_CPURepository.GetAll()); componentList.AddRange(_StorageRepository.GetAll()); componentList.AddRange(_CPUCoolerRepository.GetAll()); componentList.AddRange(_MemoryRepository.GetAll()); return View(componentList); } public ActionResult Details() { // Select view based on component type to view each sub-class specification return View(); } } </code></pre> <hr /> <p>Within the controller I'm creating a new repository instance for each concrete component implementation which gives of quite a bad smell. I don't know if this design would be elegant in handling CRUD functionalities down the line.</p> <p>Any comments or insight would be greatly appreciated, thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T12:51:48.047", "Id": "532153", "Score": "1", "body": "Ask yourself the question what you gain by this repository layer. Current consensus leans to: nothing. Just use a context. Also, please mention the exact EF version and show the database model. It's important to know how the class model maps to the database model." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T15:45:29.563", "Id": "532174", "Score": "0", "body": "Is this .NET or .NET Core? The feature set for EF and EF Core has not always been the same, and entity type inheritance has historically been different between the two." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T16:09:01.060", "Id": "532179", "Score": "0", "body": "@Flater .NET (4.7.2) - Sorry I forgot to mention" } ]
[ { "body": "<blockquote>\n<p>but as you'll see in the controller class I end up declaring several\nrepository instances anyway.</p>\n</blockquote>\n<p>Whenever you use a middle-ware that uses a design pattern, try to not enclose it with the same design pattern, because it's assumed that design pattern has shipped the middle-ware core functionality at its simplest form. So, there is no actual advantage of trying to simplify what's already simplified.</p>\n<p>Having said that, <code>DbSet&lt;T&gt;</code> in Entity Framework is actually a repository, and the <code>DbContext</code> is a <code>UnitOfWork</code>. So, doing a repository of another repository would not give any advantages, and it would actually add more complexity to your work. That's why <code>EF</code> has given some optionality to some features where you can customize them (like overriding <code>SaveChanges</code> or customizing the <code>CRUD</code> operations instead of using the pre-defined ones (<code>Add</code>, <code>Remove</code> ..etc).</p>\n<p>However, with Entity Framework, you can use <code>Service</code> design pattern if you have some custom business logic, or you can create <code>IDbSet</code> extensions (or both).</p>\n<p>If you use a <code>Service</code> then you only need to pass that service to the controller. A service can hold multiple repositories. so your final controller would be something like this :</p>\n<pre><code>public class ComponentsController : Controller\n{\n private readonly ComponentService _service;\n \n public ComponentsController()\n {\n _service = new ComponentService();\n }\n\n public ActionResult Index()\n {\n // Simulate list, basket, checkout, etc.\n List&lt;IComponent&gt; componentList = _service.GetComponents();\n return View(componentList);\n }\n}\n</code></pre>\n<p>For the models, inheritance is a good approach, however, when using models, it's better to unify the model purpose or role. In your case, you're using models for the database which would represent database schemas. Yet, you're mixing <code>DataAnnotations</code> attributes with other attributes that are not part of acceptable attributes to <code>Entity Framework</code>. same thing goes to <code>GetComponentTypeLink</code> property, which I think would be used on <code>Views</code> (or <code>Controller</code>s). So, keep the data models for the data layer, and create models to these models where needed. (e.g. view model, dto, poco ..etc.). The reason is basically you want to stabilize the data models, and have custom models from it, to be more maintainable.</p>\n<p>The <code>ComponentType</code> is redundant, because you can achieve the goal using <code>typeof(class)</code>.</p>\n<p>Finally, the class naming is too general, you need to follow a better naming convention that would describe the class role something like <code>HardwareComponent</code> and for derived class <code>CPUHardwareComponent</code> and so on.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T15:48:49.713", "Id": "532176", "Score": "0", "body": "_\"So, doing a repository of another repository would not give any advantages\"_ As much as I am a fan of not uow/repository-wrapping EF; it's not that there are _no_ advantages, it's that the advantage usually isn't worth the effort. If you need your domain to be independent of EF, then there is value to wrapping it. However, this is often dogmatically done in cases where there is no real expectation of ever moving away from EF, at which point the wrapper is a wasted effort." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T16:12:22.810", "Id": "532180", "Score": "0", "body": "Thanks for you detailed response. It's clearer to see that a repository pattern isn't necessarily always beneficial and I might have abstracted the problem more than needed.\n\nI did look into Entity Framework strategies after posting and found the 'Table per Type' strategy to be exactly what I was looking for - in terms of implementing the base class as its own table that then derived class' tables hold keys for in order to achieve relational mapping." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T13:44:48.623", "Id": "269699", "ParentId": "269654", "Score": "0" } } ]
{ "AcceptedAnswerId": "269699", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T18:05:45.190", "Id": "269654", "Score": "0", "Tags": [ "c#", ".net", "entity-framework", "polymorphism" ], "Title": "Entity Framework - component shop using polymorphism and generic repository" }
269654
<p>As you might probably know, a Caesar cipher involves shifting/unshifting and wrapping up characters when they overflow the first or last letter of the alphabet, it's useful to have a function to just handle character shifting. So I wrote a function that I intend to use in other places and was hoping to see if there are any edge cases or gotchas that I might be missing in my current implementation</p> <pre><code>fn char_shift(ch: char, shift: i8) -&gt; char { if shift == 0 || shift &gt; 25 || shift &lt; -25 { return ch; } let mut res = ch; let ch_i8 = ch as i8; match shift { // Positive Shift shift @ 0..=i8::MAX =&gt; { match ch_i8 { 65..=90 =&gt; { if ch_i8.overflowing_add(shift).1 || ch_i8.overflowing_add(shift).0 &gt; 90 { res = (ch_i8 + (shift - 90 + 64)) as u8 as char; } else { res = (ch_i8 + shift) as u8 as char; } } 97..=122 =&gt; { if ch_i8.overflowing_add(shift).1 || ch_i8.overflowing_add(shift).0 &gt; 122 { res = (ch_i8 + (shift - 122 + 96)) as u8 as char; } else { res = (ch_i8 + shift) as u8 as char; } } _ =&gt; { /* return the same character that it receieved */ } } } // Negative Shift unshift @ i8::MIN..=-1 =&gt; { let unshift = -unshift; match ch_i8 { 65..=90 =&gt; { if ch_i8 - unshift &lt; 65 { let diff = 65 - (ch_i8 - unshift); res = ((90 - diff) + 1) as u8 as char; } else { res = (ch_i8 - unshift) as u8 as char; } } 97..=122 =&gt; { if ch_i8 - unshift &lt; 97 { let diff = 97 - (ch_i8 - unshift); res = ((122 - diff) + 1) as u8 as char; } else { res = (ch_i8 - unshift) as u8 as char; } } _ =&gt; { /* return the same character that it receieved */ } } } } res } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T15:58:33.617", "Id": "534082", "Score": "0", "body": "\"I wrote a function that I intend to use in other places and was hoping to see if there are any edge cases ... \" for that you don't need a code review, you need unit testing." } ]
[ { "body": "<h2>Function design</h2>\n<p>The function itself is well named. The main problem is that it is specific to the ABC, while that is just one alphabet. I would make it generic and have a class accept an alphabet which then can be used anywhere. This makes it more valuable for reuse.</p>\n<p>Similarly, it handles upper and lowercase, while that is not clearly communicated. This is fine for a specific Caesar assignment, but it makes the function less useful. Things like upper / lowercase conversion or handling of characters outside of the alphabet can be performed by helper functions.</p>\n<h2>Code example</h2>\n<p>As I find it hard to comment on every line, and as this is a solved issue, I would like you to compare it with my code sample instead. The code does still adhere to your design (except for the handling of invalid shifts, although I have allowed for <code>0</code> after an edit).</p>\n<p>Things to note:</p>\n<ul>\n<li>The use of constants, so that <strong>no</strong> literals are used in the function itself.</li>\n<li>The use of build-in methods that make the code that much more readable.</li>\n<li>The use of explicit guard statements on top of the code.</li>\n<li>The conversion to an index 0..25 before doing the shift.</li>\n<li>The use of modular addition (<code>rem_euclid</code> for the modulo-operation) on the shift instead of mucking around with characters.</li>\n<li>The use of the same block for positive and negative shifts, using the modular addition trick above (also, see &quot;Remarks&quot; below).</li>\n<li>The little trick of always calling <code>to_ascii_uppercase</code> and then checking if the input was lowercase at the end.</li>\n<li>The use of variable names that reflect their usage, not their type (<code>input</code> instead of <code>ch</code>, for example)</li>\n</ul>\n<p>But the main thing I would like you to look at is the readability. Just show this to any one of your friends and ask them which one they think is more readable.</p>\n<pre><code>const ASCII_A: i8 = 'A' as i8;\nconst ASCII_Z: i8 = 'Z' as i8;\nconst ABC_SIZE: i8 = ASCII_Z - ASCII_A + 1;\n\nfn char_shift(input: char, shift: i8) -&gt; char {\n // --- guard statements\n if !input.is_ascii_alphabetic() {\n return input;\n }\n\n if shift &gt;= ABC_SIZE || shift &lt;= -ABC_SIZE {\n panic!(&quot;invalid shift&quot;);\n }\n\n // --- let's focus on uppercase only\n let input_upper = input.to_ascii_uppercase();\n\n // --- char to index within alphabet\n let input_index = input_upper as i8 - ASCII_A;\n\n // --- shift\n let output_index = (input_index + shift).rem_euclid(ABC_SIZE);\n\n // --- index to char\n let output_upper = ((output_index + ASCII_A) as u8) as char;\n\n // --- return, possibly after converting to lowercase\n if input.is_ascii_lowercase() {\n output_upper.to_ascii_lowercase();\n }\n output_upper\n}\n</code></pre>\n<h2>Remarks</h2>\n<p>Never just return the value if another parameter is out of bounds. This requires some way of error handling. Just returning an unencoded or worse unencrypted value is a security hazard.</p>\n<p>A negative shift is the same as a positive shift mod 26, the size of the ABC, so there is no need for a separate code block. For ASCII you should really use <code>u8</code> instead of <code>i8</code>. All calculations can be easily performed using <code>u8</code> if you first convert the shift to a value in the range 0..25.</p>\n<p>Note that they way that the function is written makes testing it a lot simpler too. Without so many literals (3 in total, and those are for the constant definitions) there aren't really (m)any &quot;edge cases&quot; left.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T06:00:59.943", "Id": "534131", "Score": "0", "body": "Appreciate the feedback, you have some good points, thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T15:55:59.397", "Id": "270451", "ParentId": "269655", "Score": "2" } } ]
{ "AcceptedAnswerId": "270451", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T18:23:56.053", "Id": "269655", "Score": "1", "Tags": [ "rust", "caesar-cipher" ], "Title": "A character shift function in Rust" }
269655
<p>I needed the ability to truncate the trailing end of path strings in a routine that builds new search paths as it recursively searches directories. After not finding what I was looking for I created function below.</p> <p>Expected behavior is that function <code>remove_trailing_chars()</code> will update <code>in</code> to remove any occurrences of chars contained in <code>rem</code>, <em>iff</em> they exist contiguously at the very end of the original version of <code>in</code>.</p> <p>Once a character in the <code>in</code> string becomes <em>the trailing char</em> and it is not included in <code>rem</code>, then function updates <code>in</code> with latest version and returns.</p> <p>it has been tested for several variations of input <code>char</code> arrays <code>in</code> and <code>rem</code>, including these.</p> <pre><code> char in[] = &quot;this is a string with \\ *\\*&quot;;//edit this string as needed to test char rem[] = &quot;\\* &quot;;//edit this string as needed to test </code></pre> <p>results in <code>&quot;this is a string with&quot;</code> without following space</p> <pre><code> char in[] = &quot;this is a string with *\\*&quot;;//edit this string as needed to test char rem[] = &quot;\\*&quot;;//edit this string as needed to test </code></pre> <p>results in <code>&quot;this is a string with &quot;</code> includes following space</p> <p>I am interested in suggestions for efficiency improvements in speed, and readability improvements. (suggestions on more idiomatic methods are welcome.) I do not believe memory should be an issue with this for my usage, but if there are thoughts on any pitfalls in that area, please include them as well.</p> <p>Here is the code, including one usage case... (Compiler command line and its disassembly are included further down as well.)</p> <pre><code>#include &lt;stdbool.h&gt;//bool #include &lt;string.h&gt;//strlen, strcpy #include &lt;stdlib.h&gt; //prototypes void remove_trailing_chars(char *in, const char *rem); /// demonstrate removing all chars in 'rem' if trailing in 'in'. int main(void) { char in[] = &quot;this is a string with \\ *\\*&quot;;//edit this string as needed to test char rem[] = &quot;\\* &quot;;//edit this string as needed to test remove_trailing_chars(in, rem); return 0; } /// remove all occurrences of chars in 'rem' from end of 'in' void remove_trailing_chars(char *in, const char *rem) { bool found = true;//when false, last char of 'in' found no matches in 'rem' int len = strlen(in); char in_dup[len+1]; strcpy(in_dup, in); while(found) { found = false;//for this element of rem len = strlen(in_dup); int i = 0; while(rem[i]) { if(in_dup[len-1] == rem[i]) { in_dup[len - 1] = 0; found = true; break; } else { i++; } } } strcpy(in, in_dup); } </code></pre> <p>Using GCC, build was done with:</p> <p>Release target:</p> <pre><code>mingw32-gcc.exe -Wall -O2 -Wall -std=c99 -g -c C:\tempExtract\remove_trainling_chars\main.c -o obj\Release\main.o </code></pre> <p>Debug target: (to allow viewing disassembly)</p> <pre><code>gcc.exe -Wall -g -Wall -std=c99 -g -c C:\tempExtract\remove_trainling_chars\main.c -o obj\Debug\main.o </code></pre>
[]
[ { "body": "<h3>Accessing array out of bounds</h3>\n<p>The code here may try access <code>in_dup[-1]</code> in some cases:</p>\n<blockquote>\n<pre><code>len = strlen(in_dup);\nint i = 0;\nwhile(rem[i])\n{\n if(in_dup[len-1] == rem[i])\n ^^^^^^^^^^^^^\n</code></pre>\n</blockquote>\n<p>That is, when the input string is empty, or when the entire input string is made of characters in <code>rem</code>, then <code>in_dup</code> will become empty, <code>len</code> becomes 0, and <code>len - 1</code> will be an illegal access on <code>in_dup</code>.</p>\n<p>In short, the code is missing a check on reaching the beginning of the input.</p>\n<h3>Avoid unnecessary copying</h3>\n<p>The code copies <code>in</code> to <code>in_dup</code>, works with <code>in_dup</code>, then copies back from it to <code>in</code>. This is unnecessary, you could work directly with <code>in</code>.</p>\n<h3>Avoid unnecessary computations</h3>\n<p><code>len = strlen(in_dup)</code> is executed every time after some characters are removed from the end. This is inefficient, because <code>strlen</code> needs to loop over the entire string. Instead, you could count the number of characters removed, and then you'll know exactly the end of the input string.</p>\n<h3>Simplify algorithm</h3>\n<p>Consider this simpler algorithm:</p>\n<ul>\n<li>Loop from the end of the input, going backwards, until the beginning</li>\n<li>Loop over the characters in <code>rem</code>, check if it matches the last character of the input\n<ul>\n<li>If there is a match, delete the last character and break out of this inner loop</li>\n<li>If there is no match, then we're done, break out of the outer loop</li>\n</ul>\n</li>\n</ul>\n<p>Implementation, including the other tips above applied as well:</p>\n<pre><code>void remove_trailing_chars(char *in, const char *rem)\n{\n int remLength = strlen(rem);\n\n for (int i = strlen(in) - 1; i &gt;= 0; i--) {\n int j = 0;\n while (j &lt; remLength) {\n if (in[i] == rem[j]) {\n in[i] = '\\0';\n break;\n }\n j++;\n }\n\n if (j == remLength) break;\n } \n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T12:49:59.637", "Id": "532152", "Score": "0", "body": "I appreciate the detail in your explanations, and follow most of them. I am unclear on your use of `strlen` in the `for` expression though. i.e. you had made the point earlier about removing `strlen` from being called repeatedly in a loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T13:41:27.047", "Id": "532161", "Score": "1", "body": "@ryyker the initializer of the loop is only executed once ;-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T20:30:50.060", "Id": "269661", "ParentId": "269656", "Score": "1" } }, { "body": "<ul>\n<li><p>Recomputing of <code>strlen(in_dup)</code> at each iteration of the <code>while</code> loop drive the time complexity to quadratic. Better compute it once, and subtract 1 per iteration.</p>\n</li>\n<li><p>I see no reason to copy <code>in</code> to <code>in_dup</code>, and then back. The second copy assumes that <code>in</code> is writable. Better operate directly on <code>in</code>.</p>\n</li>\n<li><p>Use standard library. <code>strchr</code> does precisely the same job as the inner loop, and likely does it better.</p>\n</li>\n<li><p>A variable like <code>bool found</code> is usually a red flag.</p>\n</li>\n</ul>\n<p>All that said, consider</p>\n<pre><code>char * end = in + strlen(in);\nwhile (end &gt; in) {\n char ch = *--end;\n if (strchr(rem, ch) {\n *end = 0;\n } else {\n break;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T13:45:45.213", "Id": "532163", "Score": "0", "body": "Great list of suggestions. All good except one question: Why does `bool found` usually indicate a _red flag_? btw, suggested code segment has one small typo: `(strchr(rem, ch)` -> `(strchr(rem, ch))`. Other than that, very clean. Thank you for reviewing." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T20:31:42.907", "Id": "269662", "ParentId": "269656", "Score": "1" } } ]
{ "AcceptedAnswerId": "269661", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T18:30:19.957", "Id": "269656", "Score": "1", "Tags": [ "algorithm", "strings", "c99" ], "Title": "Function to remove set of trailing characters from string" }
269656
<p>I'm creating a program that finds the roots of Bhaskara’s formula and prints them.</p> <p>I'm looking for advice to improve my logic more and more.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;math.h&gt; int main () { double os; double four; int a; int b; int c; int robf; double x1; double x2; double qisma; double jidr; //int test; os = 2; four = 4; printf(&quot;Enter Number (a) : &quot;); scanf(&quot;%d&quot;,&amp;a); printf(&quot;Enter number(b) : &quot;); scanf(&quot;%d&quot;,&amp;b); printf(&quot;Enter number (c) : &quot;); scanf(&quot;%d&quot;,&amp;c); qisma = os*a; jidr = sqrt((double)(pow(b,os)-(four*a*c))); robf = pow(b,os)-(four*a*c); x1 = (-b+jidr)/qisma; x2 = (-b-jidr)/qisma; printf(&quot;%d\n&quot;,robf); if (robf &gt; 0 || robf &lt; 0) { printf(&quot;%s%f\n&quot;,&quot;Root1 = &quot;,x1); printf(&quot;%s%f\n&quot;,&quot;Root2 = &quot;,x2); } else { printf(&quot;it Imposible to find the roots cuz robf = \n&quot;); } return(0); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T07:56:15.410", "Id": "532124", "Score": "1", "body": "\"Bhaskara's formula\" seems to be another name for the quadratic formula." } ]
[ { "body": "<blockquote>\n<p>advice to improve my logic more and more.</p>\n</blockquote>\n<p><strong>Provide link</strong></p>\n<p>Rather than assume folks know of <em>Bhaskara’s formula</em>, provide a link, even in a code comment.</p>\n<p><strong>Use an auto formatter</strong></p>\n<p>Code lacks format consistency, betraying manual formatting. Use an auto formatter for a more professional look. Many IDEs incorporate them.</p>\n<p><strong>Check return values</strong></p>\n<p>User input is <em>evil</em>. Do not assume valid numeric text was entered.</p>\n<pre><code>// scanf(&quot;%d&quot;,&amp;a);\nif (scanf(&quot;%d&quot;,&amp;a) != 1) Handle_Error_or_other_TBD_code();\n</code></pre>\n<p><strong>Useless cast</strong></p>\n<p><code>(double)</code> serves no purpose in <code>sqrt((double)(pow(b,os)-(four*a*c)));</code></p>\n<p>Consider more direct coding. Use <code>double</code> constants to ensure <code>double</code> math.</p>\n<pre><code>sqrt(1.0*b*b - 4.0*a*c);\n</code></pre>\n<p><strong>Define and initialize</strong></p>\n<pre><code>// double qisma;\n...\n// qisma = os*a;\n// Instead\ndouble qisma = os*a\n \n</code></pre>\n<p><strong>Don't repeat</strong></p>\n<p>Don't repeat, Don't repeat.</p>\n<pre><code> //jidr = sqrt((double)(pow(b,os)-(four*a*c)));\n //robf = pow(b,os)-(four*a*c);\n robf = pow(b,os)-(four*a*c);\n jidr = sqrt(robf);\n</code></pre>\n<p><strong>Guard against <code>sqrt(some negative)</code></strong></p>\n<p>Not later.</p>\n<pre><code> robf = pow(b,os)-(four*a*c);\n if (robf &lt; 0) TBD_Code();\n jidr = sqrt(robf);\n</code></pre>\n<p><strong>Avoid cancellation</strong></p>\n<p>Consider the severe cancellation when <code>jidr</code> near <code>|b|</code>. The difference can incur severe lost of precision.</p>\n<pre><code> //x1 = (-b+jidr)/qisma;\n //x2 = (-b-jidr)/qisma;\n \n // Alternative\n if (b &lt; 0) {\n x1 = (-b+jidr)/qisma;\n x2 = c/x1;\n } else if (b &gt; 0) {\n x2 = (-b-jidr)/qisma;\n x1 = c/x2;\n } else {\n x1 = jidr/qisma;\n x2 = -x1;\n }\n</code></pre>\n<p><strong><code>()</code> not needed</strong></p>\n<p><code>()</code> here is <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself#WET\" rel=\"nofollow noreferrer\">wet</a>.</p>\n<pre><code>// return(0);\nreturn 0;\n</code></pre>\n<p><strong>Avoid cancellation 2</strong></p>\n<p>In <em>general</em>, <code>1.0*b*b - 4.0*a*c</code> is prone to cancellation. That inexactness does not apply much here as <code>a,b,c</code> are integers.</p>\n<p>When using <code>a,b,c</code> as <code>double</code>, code could use the more stable</p>\n<pre><code>double ac4 = 4.0*a*c;\nif (ac4 &gt; 0) {\n ac4 = sqrt(ac4);\n robf = (b + ac4)*(b - ac4);\n} else {\n robf = b*b - ac4;\n}\n</code></pre>\n<p>This is valuable when <code>b*b</code> is about <code>4.0*a*c</code>.</p>\n<p><strong>Useless test</strong></p>\n<p><code>robf &lt; 0</code> is worthless as prior code would have choked on <code>sqrt((double)(pow(b,os)-(four*a*c)))</code>.</p>\n<p><strong>Excessive horizontal indenting</strong></p>\n<p>IMO, 8 is a bit much. Go with your group's coding standard.</p>\n<p><strong>Better prompts</strong></p>\n<pre><code>// v v--spelling slang-v v--obscure variable name\n//&quot;it Imposible to find the roots cuz robf = \\n&quot;\n&quot;It is impossible to find the roots because the discriminant is negative\\n&quot;\n</code></pre>\n<p><strong>Form a helper function</strong></p>\n<p>Rather than code in <code>main()</code>, define a <code>int Bhaskara(double x[2], double a, double b, double c);</code>.</p>\n<p><strong>Clean up</strong></p>\n<p>What is <code>//int test;</code> in this post for?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T23:01:34.650", "Id": "269672", "ParentId": "269660", "Score": "2" } }, { "body": "<p>This looks like you have been told never to use magic numbers, and have mistaken that advice:</p>\n<blockquote>\n<pre><code> double four;\n\n four = 4;\n</code></pre>\n</blockquote>\n<p>The only place we use it is in calculating the discriminant (<code>4.0 * a * c</code>), but there it is a necessary part of the formula, not something that could ever be tweaked. If it was really a magic number, then <code>four</code> is the worst possible name for it!</p>\n<p>A worse instance of this is the use of <code>os</code> for two completely unrelated quantities that coincidentally happen to have the same value. That's replicating exactly the problem that magic numbers cause - when two constants are the same, we want to know whether or not they have to be identical, or just happen to be so.</p>\n<p>Also, we should use <code>const</code> for variables that should not change.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T15:21:32.600", "Id": "532169", "Score": "0", "body": "\"variables that should not change\" always _sounds_ wrong as variables are, well, variable. ;-) Perhaps \"for objects that should not change\"." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T13:38:04.260", "Id": "269698", "ParentId": "269660", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T20:27:38.717", "Id": "269660", "Score": "1", "Tags": [ "beginner", "c", "programming-challenge" ], "Title": "Evaluate the roots of Bhaskara’s formula" }
269660
<p>I'm trying to move a large number of files. I get the path of source and destination from database.</p> <p>It takes hours to move images, and I was wondering if there is a faster way for moving large numbers of files.</p> <p>Table example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>source</th> <th>destination</th> </tr> </thead> <tbody> <tr> <td>C:\x</td> <td>D:\y</td> </tr> <tr> <td>C:\z</td> <td>D:\y</td> </tr> </tbody> </table> </div> <p>This the code I'm using.</p> <pre><code>var datasource = @&quot;00.000.0.00&quot;; var database = &quot;maydatabase&quot;; var username = &quot;power&quot;; var password = &quot;123&quot;; string connString = @&quot;Data Source=&quot; + datasource + &quot;;Initial Catalog=&quot; + database + &quot;;Persist Security Info=True;User ID=&quot; + username + &quot;;Password=&quot; + password; SqlConnection conn = new SqlConnection(connString); static void moveImg(string getimg, SqlConnection conn) { using (SqlCommand command = new SqlCommand(getimg, conn)) { command.CommandTimeout = 0; using (var reader = command.ExecuteReader()) { while (reader.Read()) { if ((File.Exists(reader[&quot;source&quot;].ToString())) &amp;&amp; !(File.Exists(reader[&quot;destination&quot;].ToString()))) { File.Move(reader[&quot;source&quot;].ToString(), reader[&quot;destination&quot;].ToString(), true); } } } } } </code></pre> <h2>Note</h2> <p>The number of rows in database can exceed 1 million, meaning 1 million images to move. Each image has size between 16KB and 60KB.</p> <p>The query takes 1.30 mins to run. I don't know how can I get the timing for how long a file move takes, as not every file is same size. I can tell from the log file that it moves around 4 to 6 files in 1 second.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T07:48:11.400", "Id": "532123", "Score": "0", "body": "Welcome to CodeReview! Which .NET and C# version are you using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T08:05:03.583", "Id": "532125", "Score": "0", "body": "@PeterCsala Thanks, I'm using .net core 3.1 and C# 8.0" } ]
[ { "body": "<p>Quick suggestion:</p>\n<ol>\n<li>Iterate through all the records in the database</li>\n<li>Group them by folder</li>\n<li>See if there are other items in the folders</li>\n<li>Moving folders is exponentially faster than individual files</li>\n<li>If the files are on different drives, or you are not allowed to\nchange the directory structure, you are pretty much SOL and will\njust have to be patient =)</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T22:49:54.940", "Id": "532105", "Score": "0", "body": "I can't move it as a folder because there are other files within the folder that I don't want to move and also I'm not allowed to change the structure.\nI'm doing this on azure server I'm supposed to backup the files by the date of creation meaning I move all the files that been created in JUN for example 0.5 million file to another partition with much slower drive and much cheaper than the SSD we are using this partition is shared on this server so it takes traffic too. I think there is no way to improve it as traffic will make it slow and also the writing to the slow partition right ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T23:24:41.260", "Id": "532107", "Score": "0", "body": "You might get a marginal improvement in speed by batching operations etc. Perhaps somebody else has some sort of magic way to increase performance, let's see :-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T21:58:59.560", "Id": "269668", "ParentId": "269665", "Score": "0" } }, { "body": "<p>Here are my observations and suggestions:</p>\n<h3><code>connString</code></h3>\n<ul>\n<li>I would suggest to prefer <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated\" rel=\"nofollow noreferrer\">string interpolation</a> over string concatenation</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>string connString = $@&quot;Data Source={datasource};Initial Catalog={database};Persist Security Info=True;User ID={username};Password={password}&quot;;\n</code></pre>\n<ul>\n<li><a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated#special-characters\" rel=\"nofollow noreferrer\">Since C# 8</a> the ordering of <code>@</code> and <code>$</code> does not matter</li>\n</ul>\n<h3><code>using</code></h3>\n<ul>\n<li>You can use take advantage of C# 8's new <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations\" rel=\"nofollow noreferrer\">using declaration</a> over using statement</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>using var command = new SqlCommand(getimg, conn);\ncommand.CommandTimeout = 0;\nusing var reader = command.ExecuteReader();\n</code></pre>\n<h3>Fetch</h3>\n<ul>\n<li>I would suggest to separate database read from actual move operations</li>\n<li>Your database connection should not last long</li>\n</ul>\n<pre><code>static IEnumerable&lt;(string Source, string Destination)&gt; FetchMoveParameters(string getimg, SqlConnection conn)\n{\n var result = new List&lt;(string Source, string Destination)&gt;();\n using var command = new SqlCommand(getimg, conn);\n command.CommandTimeout = 0;\n using var reader = command.ExecuteReader();\n while (reader.Read())\n {\n result.Add(reader[&quot;source&quot;].ToString(), reader[&quot;destination&quot;].ToString());\n }\n\n return result;\n}\n</code></pre>\n<ul>\n<li>I've used <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple?view=net-5.0\" rel=\"nofollow noreferrer\">ValueTuple</a>s here but you can create your own structure for that</li>\n</ul>\n<h3><code>Move</code></h3>\n<ul>\n<li>If you want to increase the performance of move operations then you should consider to use parallelism</li>\n<li>You have to make sure that there are no two (or more) conflicting instructions in the fetched move parameters to avoid race condition</li>\n</ul>\n<pre><code>var moveParams = FetchMoveParameters(...);\nmoveParams.AsParallel().ForAll(moveParam =&gt;\n{\n //move source to destination\n});\n</code></pre>\n<p>Alternative</p>\n<pre><code>Parallel.ForEach(moveParams, moveParam =&gt;\n{\n //move source to destination\n});\n</code></pre>\n<ul>\n<li>And as always measure, measure and measure\n<ul>\n<li>Make sure that the newly applied changes are giving some performance gain</li>\n</ul>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T09:10:06.837", "Id": "532135", "Score": "1", "body": "Thanks, will try it and feed back." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T09:38:21.710", "Id": "532141", "Score": "1", "body": "@MickeyMan, I will like to see your feedback. I suspect that vectoring the move operations will most likely be slower, especially on a clunky old and fragmented HDD, but I have often been wrong :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T09:51:52.813", "Id": "532242", "Score": "0", "body": "@upkajdt Thank you a lot! It works Parallel.ForEach big increase in performance it takes 250mb from memory but file moving way faster, I have another issue now with serilog as it create a log file for each thread if you a way to solve let me know thanks again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T13:27:40.983", "Id": "532266", "Score": "0", "body": "@MickeyMan, I think you should have thanked Peter ;-) I have to say that I'm surprised that it made a difference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T13:56:43.350", "Id": "532268", "Score": "1", "body": "Peter thanks....my bad XD" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T14:01:20.107", "Id": "532272", "Score": "0", "body": "@upkajdt it's super fast now but I can't trigger the log method (serilog) as it keep keeps creating log file and deleting it I think I can't trigger the method with in Parallel.ForEach" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T14:05:16.627", "Id": "532273", "Score": "1", "body": "@MickeyMan, Sorry but I have no idea what is happening in your `serilog`. Can you perhaps disable it while moving the files?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T14:31:28.203", "Id": "532275", "Score": "0", "body": "@upkajdt well I want to log what images been moved." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T14:50:20.460", "Id": "532280", "Score": "0", "body": "@MickeyMan - I think you will need to do something like the following: 1. Set database into single-user mode. 2. Disable the trigger, 3. Iterate through all the records. 4. Move the files and keep track of the changes in some sort of collection. 5. Bulk insert changes into the log. 6. Re-enable the trigger. 7. Set database into multiuser mode." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T07:53:01.143", "Id": "532330", "Score": "0", "body": "@MickeyMan you can add more performance by calling the `FileMove` in `kernel32.dll` which what `File.Move` does internally. doing this would bypass all validations, and you will need to handle it, here is snippet https://www.codepile.net/pile/Ywpz0JjA" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T15:13:37.807", "Id": "532375", "Score": "0", "body": "@iSR5 will try and feedback." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T08:57:11.493", "Id": "269688", "ParentId": "269665", "Score": "0" } } ]
{ "AcceptedAnswerId": "269688", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T21:20:27.370", "Id": "269665", "Score": "1", "Tags": [ "c#", "sql", "file-system" ], "Title": "Moving files according to paths in database" }
269665
<p>I have completed my project which models the paths of particles in a plasma experiencing a <a href="https://en.wikipedia.org/wiki/Magnetic_mirror" rel="nofollow noreferrer">force</a>. The program creates phase diagrams of a particle's perpendicular velocity against its parallel velocity from 0 to 180 degrees.</p> <p>I would like your thoughts and improvements on my implementation.</p> <p>Here is the code:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np alpha_0 = [5, 30, 60, 85] # initial pitch angles in degrees degrees = np.linspace(0, 180, int(round(180/1 + 1))) # I choose to plot phase diagram from 0 to 180 deg v = 1 v_perp_5=v*np.sin(np.deg2rad(alpha_0[0] + degrees)) v_par_5=pow(v**2 - v_perp_5**2,0.5) v_perp_30=v*np.sin(np.deg2rad(alpha_0[1] + degrees)) v_par_30=pow(v**2 - v_perp_30**2,0.5) v_perp_60=v*np.sin(np.deg2rad(alpha_0[2] + degrees)) v_par_60=pow(v**2 - v_perp_60**2,0.5) v_perp_85=v*np.sin(np.deg2rad(alpha_0[3] + degrees)) v_par_85=pow(v**2 - v_perp_85**2,0.5) # plot lines plt.rcParams[&quot;figure.figsize&quot;] = [13,13] fig, axs = plt.subplots(2, 2) fig.suptitle('Phase Diagrams from ' + r'$0^\circ$' + ' to ' + r'$180^\circ$', fontsize=21) axs[0, 0].plot(v_par_5, v_perp_5) axs[0, 0].set_title(r'$\alpha_o = 5^\circ$', fontsize=15) axs[0, 0].set_xlim([-1,1]) axs[0, 0].set_ylim([-1,1]) axs[0, 0].set_xlabel(r'$v_{\parallel}$', fontsize=15) axs[0, 0].set_ylabel(r'$v_{\perp}$', fontsize=15) axs[0, 0].annotate(r'$\alpha_o$', (v_par_5[0], v_perp_5[0]), fontsize=14) cir_init_5 = plt.Circle((v_par_5[0], v_perp_5[0]), 0.05, color='r',fill=False) axs[0, 0].add_patch(cir_init_5) axs[0, 0].arrow(x=0, y=0.85, dx=0, dy=0.08, width=.015) axs[0, 0].text(-0.04, 0.79, r'$\alpha_m$', fontsize=14) axs[0, 1].plot(v_par_30, v_perp_30, 'tab:orange') axs[0, 1].set_title(r'$\alpha_o = 30^\circ$', fontsize=15) axs[0, 1].set_xlim([-1,1]) axs[0, 1].set_ylim([-1,1]) axs[0, 1].set_xlabel(r'$v_{\parallel}$', fontsize=15) axs[0, 1].set_ylabel(r'$v_{\perp}$', fontsize=15) axs[0, 1].annotate(r'$\alpha_o$', (v_par_30[0], v_perp_30[0]), fontsize=14) cir_init_30 = plt.Circle((v_par_30[0], v_perp_30[0]), 0.05, color='r',fill=False) axs[0, 1].add_patch(cir_init_30) axs[0, 1].arrow(x=0, y=0.85, dx=0, dy=0.08, width=.015) axs[0, 1].text(-0.04, 0.79, r'$\alpha_m$', fontsize=14) axs[1, 0].plot(v_par_60, v_perp_60, 'tab:green') axs[1, 0].set_title(r'$\alpha_o = 60^\circ$', fontsize=15) axs[1, 0].set_xlim([-1,1]) axs[1, 0].set_ylim([-1,1]) axs[1, 0].set_xlabel(r'$v_{\parallel}$', fontsize=15) axs[1, 0].set_ylabel(r'$v_{\perp}$', fontsize=15) axs[1, 0].annotate(r'$\alpha_o$', (v_par_60[0], v_perp_60[0]), fontsize=14) cir_init_60 = plt.Circle((v_par_60[0], v_perp_60[0]), 0.05, color='r',fill=False) axs[1, 0].add_patch(cir_init_60) axs[1, 0].arrow(x=0, y=0.85, dx=0, dy=0.08, width=.015) axs[1, 0].text(-0.04, 0.79, r'$\alpha_m$', fontsize=14) axs[1, 1].plot(v_par_85, v_perp_85, 'tab:red') axs[1, 1].set_title(r'$\alpha_o = 85^\circ$', fontsize=15) axs[1, 1].set_xlim([-1,1]) axs[1, 1].set_ylim([-1,1]) axs[1, 1].set_xlabel(r'$v_{\parallel}$', fontsize=15) axs[1, 1].set_ylabel(r'$v_{\perp}$', fontsize=15) axs[1, 1].annotate(r'$\alpha_o$', (v_par_85[0], v_perp_85[0]), fontsize=14) cir_init_85 = plt.Circle((v_par_85[0], v_perp_85[0]), 0.05, color='r',fill=False) axs[1, 1].add_patch(cir_init_85) axs[1, 1].arrow(x=0, y=0.85, dx=0, dy=0.08, width=.015) axs[1, 1].text(-0.04, 0.79, r'$\alpha_m$', fontsize=14) fig.tight_layout() </code></pre>
[]
[ { "body": "<ul>\n<li>Functions and type hints are your friend - use them</li>\n<li>Vectorise your separate alpha values and calculations to a single calculation for each of perpendicular and parallel arrays</li>\n<li><code>np.linspace(0, 180, int(round(180/1 + 1)))</code> is a slightly bizarre way of writing <code>np.arange(181)</code></li>\n<li>Do not <code>pow(x, 0.5)</code>; use <code>np.sqrt</code></li>\n<li>&quot;13&quot; is a quantity in inches. If you're rendering for print this will be larger than the standard 8.5x11. If you're rendering for the screen, most laptop screens are smaller than this as well. Between this and your custom font, the rendering was very poor and produced overlaps. I decreased this to 9&quot; and used default fonts and the problems went away.</li>\n<li>There isn't a benefit to your string concatenation for <code>suptitle</code>; you can have a single raw string.</li>\n<li>Factor out your copy-and-paste subplot code to one function.</li>\n<li>There is no semantic difference between your four subplots that hasn't already been explained by <code>set_title</code>, so there isn't a benefit to separate colours. Separate colours - with a legend - would be useful if you did not include the alpha value in the titles.</li>\n<li>Don't <code>^\\circ</code>; just use <code>\\degree</code>.</li>\n</ul>\n<h2>Coordinate space</h2>\n<p>Your conversion from polar to rectilinear coordinates is probably incorrect. Your use of the Euclidean norm drops a negative sign, so you're only ever seeing half of the coordinate space. Instead of <code>sqrt</code> for a reverse Pythagorean, just use <code>cos</code>.</p>\n<p>In the (maybe unlikely?) case that this was deliberate, you can just apply an <code>np.abs</code> to your parallel coordinate axis. However, the less surprising method to get a (I, IV) quadrant effect would be to construct the angles themselves prior to projection using <code>np.min</code> to make a piecewise angle function, and to then use a plain <code>sin</code>,<code>cos</code> projection with no <code>abs</code>.</p>\n<h2>Suggested</h2>\n<pre><code>from numbers import Real\nfrom typing import Tuple\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef calculate_v(v: Real) -&gt; Tuple[\n np.ndarray, # alpha: 4\n np.ndarray, # perpendicular: n_alpha * n_degrees\n np.ndarray, # parallel: n_alpha * n_degrees\n]:\n alpha_0 = np.array((5, 30, 60, 85), ndmin=2).T # initial pitch angles in degrees\n degrees = np.arange(181)[np.newaxis, :] # Plot phase diagram from 0 to 180 deg\n radians = np.deg2rad(alpha_0 + degrees)\n v_perp = v*np.sin(radians)\n v_par = v*np.cos(radians)\n return alpha_0[:, 0], v_perp, v_par\n\n\ndef plot_lines(alpha_0: np.ndarray, v_perp: np.ndarray, v_par: np.ndarray) -&gt; plt.Figure:\n plt.rcParams['figure.figsize'] = (9, 9)\n fig, axes_grid = plt.subplots(2, 2)\n fig.suptitle(\n r'Phase Diagrams from $0^\\circ$ to $180^\\circ$'\n )\n\n axes = [\n ax\n for row in axes_grid\n for ax in row\n ]\n for args in zip(axes, v_perp, v_par, alpha_0):\n subplot(*args)\n\n fig.tight_layout()\n return fig\n\n\ndef subplot(ax: plt.Axes, v_perp: np.ndarray, v_par: np.ndarray, alpha: int) -&gt; None:\n ax.plot(v_par, v_perp)\n ax.set_title(rf'$\\alpha_o = {alpha}^\\circ$')\n ax.set_xlim(left=-1, right=1)\n ax.set_ylim(bottom=-1, top=1)\n ax.set_xlabel(r'$v_{\\parallel}$')\n ax.set_ylabel(r'$v_{\\perp}$')\n ax.annotate(r'$\\alpha_o$', (v_par[0], v_perp[0]))\n cir_init = plt.Circle((v_par[0], v_perp[0]), 0.05, color='r', fill=False)\n ax.add_patch(cir_init)\n ax.arrow(x=0, y=0.85, dx=0, dy=0.08, width=.015)\n ax.text(-0.04, 0.79, r'$\\alpha_m$')\n\n\ndef main() -&gt; None:\n alpha, v_perp, v_par = calculate_v(v=1)\n plot_lines(alpha, v_perp, v_par)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/InlHG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/InlHG.png\" alt=\"separated plot\" /></a></p>\n<h2>Superimposed plots</h2>\n<p>A more informative and condensed visualisation superimposes all of your subplots and allows for easier comparison, including a legend:</p>\n<pre><code>from numbers import Real\nfrom typing import Tuple\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef calculate_v(v: Real) -&gt; Tuple[\n np.ndarray, # alpha: 4\n np.ndarray, # perpendicular: n_alpha * n_degrees\n np.ndarray, # parallel: n_alpha * n_degrees\n]:\n alpha_0 = np.array((5, 30, 60, 85), ndmin=2).T # initial pitch angles in degrees\n degrees = np.arange(181)[np.newaxis, :] # Plot phase diagram from 0 to 180 deg\n radians = np.deg2rad(alpha_0 + degrees)\n v_perp = v*np.sin(radians)\n v_par = v*np.cos(radians)\n return alpha_0[:, 0], v_perp, v_par\n\n\ndef plot_lines(alpha_0: np.ndarray, v_perp: np.ndarray, v_par: np.ndarray) -&gt; plt.Figure:\n plt.rcParams['figure.figsize'] = (9, 9)\n fig, ax = plt.subplots()\n fig.suptitle(\n r'Phase Diagrams from $0^\\circ$ to $180^\\circ$'\n )\n\n ax.set_xlim(left=-1, right=1)\n ax.set_ylim(bottom=-1, top=1)\n ax.set_xlabel(r'$v_{\\parallel}$')\n ax.set_ylabel(r'$v_{\\perp}$')\n ax.arrow(x=0, y=0.85, dx=0, dy=0.08, width=.015)\n ax.text(-0.04, 0.79, r'$\\alpha_m$')\n\n for args in reversed(tuple(zip(v_perp, v_par, alpha_0))):\n subplot(ax, *args)\n\n ax.legend(title=r'$\\alpha_o$')\n fig.tight_layout()\n return fig\n\n\ndef subplot(ax: plt.Axes, v_perp: np.ndarray, v_par: np.ndarray, alpha: int) -&gt; None:\n line, = ax.plot(\n v_par, v_perp,\n label=alpha,\n )\n ax.annotate(\n text=r'$\\alpha_o$', xy=(v_par[0], v_perp[0]),\n )\n cir_init = plt.Circle(\n xy=(v_par[0], v_perp[0]), radius=0.05,\n fill=False, color=line.get_color(),\n )\n ax.add_patch(cir_init)\n\n\ndef main() -&gt; None:\n alpha, v_perp, v_par = calculate_v(v=1)\n plot_lines(alpha, v_perp, v_par)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/Ea4FR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ea4FR.png\" alt=\"superimposed plots\" /></a></p>\n<h2>First-class Polar</h2>\n<p>It doesn't make a tonne of sense to use a Cartesian plot for your data, or to represent them in rectilinear coordinates. Everything is made more simple if you represent your data in polar coordinates - every single radius is just equal to 1, your angles are linear, and there's no need for <code>sin</code>, <code>cos</code> or <code>sqrt</code>.</p>\n<pre><code>from numbers import Real\nfrom typing import Tuple\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef calculate_v(v: Real) -&gt; Tuple[\n np.ndarray, # alpha: 4\n np.ndarray, # radians: n_alpha * n_degrees\n np.ndarray, # radii: n_alpha * n_degrees\n]:\n alpha_0 = np.array((5, 30, 60, 85), ndmin=2).T # initial pitch angles in degrees\n degrees = np.arange(181)[np.newaxis, :] # Plot phase diagram from 0 to 180 deg\n radians = np.deg2rad(alpha_0 + degrees)\n radii = np.full_like(radians, fill_value=v)\n return alpha_0[:, 0], radians, radii\n\n\ndef plot_lines(alpha_0: np.ndarray, radians: np.ndarray, radii: np.ndarray) -&gt; plt.Figure:\n plt.rcParams['figure.figsize'] = (9, 9)\n fig: plt.Figure\n ax: plt.PolarAxes\n fig, ax = plt.subplots(\n subplot_kw={'projection': 'polar'}\n )\n fig.suptitle(\n r'Phase Diagrams from $0^\\circ$ to $180^\\circ$'\n )\n\n ax.set_rlabel_position(-22.5)\n ax.arrow(x=np.pi/2, y=0.85, dx=0, dy=0.08, width=.015)\n ax.text(x=np.pi/2, y=0.79, s=r'$\\alpha_m$')\n\n for args in reversed(tuple(zip(radians, radii, alpha_0))):\n subplot(ax, *args)\n\n ax.grid(True)\n ax.legend(title=r'$\\alpha_o$')\n fig.tight_layout()\n return fig\n\n\ndef subplot(ax: plt.PolarAxes, radians: np.ndarray, radii: np.ndarray, alpha: int) -&gt; None:\n line, = ax.plot(radians, radii, label=alpha)\n ax.annotate(\n text=r'$\\alpha_o$', xy=(radians[0], radii[0]),\n )\n cir_init = plt.Circle(\n xy=(radians[0], radii[0]), radius=0.05,\n fill=False, color=line.get_color(),\n )\n ax.add_patch(cir_init)\n\n\ndef main() -&gt; None:\n alpha, radians, radii = calculate_v(v=1)\n plot_lines(alpha, radians, radii)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/EYeFv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EYeFv.png\" alt=\"polar plot\" /></a></p>\n<h2>Rays instead of markers</h2>\n<p>Your circles are basically non-standard markers. You could use standard markers and just have a <code>markevery</code> setting that only shows the first data point in each series. However, that doesn't help with highlighting the end of the series. One way to highlight both the beginning and end of each polar series is to draw a ray to the beginning and end point:</p>\n<pre><code>from numbers import Real\nfrom typing import Tuple\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef calculate_v(v: Real) -&gt; Tuple[\n np.ndarray, # alpha: 4\n np.ndarray, # radians: n_alpha * n_degrees\n np.ndarray, # radii: n_alpha * n_degrees\n]:\n alpha_0 = np.array((5, 30, 60, 85), ndmin=2).T # initial pitch angles in degrees\n degrees = np.arange(181)[np.newaxis, :] # Plot phase diagram from 0 to 180 deg\n radians = np.deg2rad(alpha_0 + degrees)\n radii = np.full_like(radians, fill_value=v)\n return alpha_0[:, 0], radians, radii\n\n\ndef plot_lines(alpha_0: np.ndarray, radians: np.ndarray, radii: np.ndarray) -&gt; plt.Figure:\n plt.rcParams['figure.figsize'] = (9, 9)\n fig: plt.Figure\n ax: plt.PolarAxes\n fig, ax = plt.subplots(\n subplot_kw={'projection': 'polar'}\n )\n ax.set_title(\n r'Phase Diagrams from $0\\degree$ to $180\\degree$, with bound rays'\n )\n\n ax.set_rlabel_position(-22.5)\n ax.arrow(x=np.pi/2, y=0.85, dx=0, dy=0.08, width=.015)\n ax.text(x=np.pi/2, y=0.79, s=r'$\\alpha_m$')\n\n for args in reversed(tuple(zip(radians, radii, alpha_0))):\n subplot(ax, *args)\n\n ax.grid(True)\n ax.legend(title=r'$\\alpha_o$')\n fig.tight_layout()\n return fig\n\n\ndef subplot(ax: plt.PolarAxes, radians: np.ndarray, radii: np.ndarray, alpha: int) -&gt; None:\n line, = ax.plot(\n radians, radii,\n label=rf'${alpha}\\degree$',\n )\n\n ax.plot(\n [radians[0], 0, radians[-1]],\n [radii[0], 0, radii[-1]],\n color=line.get_color(),\n linestyle='--',\n )\n\n\ndef main() -&gt; None:\n alpha, radians, radii = calculate_v(v=1)\n plot_lines(alpha, radians, radii)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/eEumG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eEumG.png\" alt=\"rays included\" /></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T16:46:13.563", "Id": "269706", "ParentId": "269666", "Score": "5" } } ]
{ "AcceptedAnswerId": "269706", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T21:48:56.233", "Id": "269666", "Score": "4", "Tags": [ "python", "physics" ], "Title": "Phase diagrams of particles in a mirror" }
269666
<p>For a college assignment, I was tasked with the following (excerpt from provided code file):</p> <blockquote> <p>Find one string of characters that is not present in the list. You are provided a function that loads the strings from the provided file, <code>sequences.txt</code>. You may not use any libraries that assist you in completing this solution. This specifically includes the <code>random</code> and <code>string</code> library. Your function must return two values: the string not present in the list, and a boolean value representing if the value is present in the list. Ensure to use documentation strings and comments to explain your program! Good luck!</p> </blockquote> <p>Below is my solution, with a description of the algorithm is provided in the docstring. The main thing I'm worried about is my solution. I'm concerned there is a much easier solution, just not as elegant; like switching the first character of the first string and comparing that. It's not a 100% sure solution, but I'm sure it works most of the time. Mine is a sure solution, from my understanding.</p> <p>I should mention, the file <code>sequences.txt</code> contains 1000 lines, where each line is 1000 characters long, each character either A or B.</p> <p>Any and all critiques and recommendations are welcome and considered!</p> <pre><code>&quot;&quot;&quot; Find one string of characters that is not present in the list. You are provided a function that loads the strings from the provided file, `sequences.txt`. You may not use any libraries that assist you in completing this solution. This specifically includes the `random` and `string` library. Your function must return two values: the string not present in the list, and a boolean value representing if the value is present in the list. Ensure to use documentation strings and comments to explain your program! Good luck! @professor XXXXXXXX @class CS 1350 @due Nov 15, 2021 Provide your details below: @author Ben Antonellis @date Nov 2nd, 2021 &quot;&quot;&quot; # PROVIDED FUNCTIONS # def load_sequences(): sequences = [] with open('sequences.txt', 'r') as input_file: for line in input_file: sequences.append(line.strip()) return sequences # PROVIDE YOUR SOLUTION BELOW # from typing import Tuple # For code clarity def find_excluded() -&gt; Tuple[str, bool]: &quot;&quot;&quot; This algorithm marches through each string in the list, and for every string flips the n-th character. By doing this, this ensures the string is different from each string by at least one character. &quot;&quot;&quot; strings = load_sequences() string_index = 0 result = &quot;&quot; for idx, _ in enumerate(strings): result += &quot;A&quot; if strings[idx][string_index] == &quot;B&quot; else &quot;B&quot; string_index += 1 return result, result in strings result, should_be_false = find_excluded() print(result) print(should_be_false) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T22:16:29.827", "Id": "532104", "Score": "0", "body": "I think you forgot to increment the string index. As is this would fail with the following input of 2 strings : 'AB', 'BA' . But would work with strings[idx][idx]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T04:23:08.810", "Id": "532116", "Score": "0", "body": "@kubatucka Thanks for the catch, somehow that didn't make it into the copy-paste!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T09:35:57.637", "Id": "532140", "Score": "1", "body": "How returning empty string (or any other less-then-1000-long string) fails to meet the requirements?" } ]
[ { "body": "<p>We should begin the habit of using a &quot;main guard&quot;:</p>\n<pre><code>if __name__ == &quot;__main__&quot;:\n result, should_be_false = find_excluded()\n print(result)\n print(should_be_false)\n</code></pre>\n<p>We don't need <code>strings[idx]</code>, since <code>enumerate()</code> is already giving us that. We just have to not ignore it. And <code>string_index</code> is always kept equal to <code>idx</code>, so no need to maintain a separate variable.</p>\n<pre><code>for idx, s in enumerate(strings):\n result += &quot;A&quot; if s[idx] == &quot;B&quot; else &quot;B&quot;\n</code></pre>\n<p>Or construct the result string from a comprehension (with a more cute selection, using array indexing):</p>\n<pre><code>result = ''.join(&quot;BA&quot;[s[i]==&quot;B&quot;] for i,s in enumerate(strings))\n</code></pre>\n<p>I note that the assignment is not yet due; if you've not submitted yet, remember to acknowledge the help you received here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T13:14:38.547", "Id": "269696", "ParentId": "269667", "Score": "2" } }, { "body": "<p>Your algorithm is correct and will always provide a correct answer as the list length equals the string length. As @Toby already pointed out you shall not maintain two indices as you walk row and column on a diagonal.</p>\n<p>Additionally I want to give two more points.</p>\n<h1>Do not mix in the I/O operation with your processing function</h1>\n<p>That does bind your algorithm to the filename and does not allow generic usage and testing. Instead do a function that takes a list of strings and returns a single string. As your algorithm always provides a solution there is no need to return the truth value other than your appointment of course.</p>\n<pre><code>def find_excluded(strings: str) -&gt; Tuple[str, bool]:\n s = ...\n return (s, False)\n</code></pre>\n<p>which you use then like</p>\n<pre><code>strings = load_sequences()\nresult, should_be_false = find_excluded(strings)\n</code></pre>\n<p>Now we can easily do simple tests like</p>\n<pre><code>strings = [&quot;AA&quot;, &quot;AB&quot;]\nresult, _ = find_excluded(strings)\nassert len(result) == len(strings)\nassert result not in strings\n</code></pre>\n<p>You can also test edge cases etc.</p>\n<h1>Try to think in algorithms/filters applied to sequences of data</h1>\n<p>This is very often much more readable and self documenting if you chose good names for your temporaries/functions/expressions. As your algorithm walks the diagonal we name a temporary like that. For the character replacemaent a name like 'invert' sounds nice as the code is binary.</p>\n<pre><code>def find_excluded(strings: str) -&gt; Tuple[str, bool]:\n diagonal = [s[i] for i, s in enumerate(strings)]\n invert = {'A':'B', 'B':'A'}\n inverted = [invert[c] for c in diagonal]\n return (''.join(inverted), False)\n</code></pre>\n<p>That is pretty readdable, isn't it? Note: you may replace the list comprehensions by generator expressions. That allows working on big iterables efficiently.</p>\n<pre><code>def find_excluded(strings: str) -&gt; Tuple[str, bool]:\n diagonal = (s[i] for i, s in enumerate(strings))\n invert = {'A':'B', 'B':'A'}\n inverted = (invert[c] for c in diagonal)\n return (''.join(inverted), False)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T19:15:22.140", "Id": "269712", "ParentId": "269667", "Score": "2" } } ]
{ "AcceptedAnswerId": "269712", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T21:55:52.977", "Id": "269667", "Score": "1", "Tags": [ "python", "python-3.x", "algorithm", "homework" ], "Title": "Generate a string that is not present in a list" }
269667
<p>I have written the following Sudoku checker in Python. I feel like this could be written much shorter and perhaps more efficient. Especially the part with <code>square_columns</code>.</p> <pre><code>rows = [] columns = [] squares = [] sudoku_sets = [] for i in range(9): if i == 0: row = input(&quot;Input the sudoku values row by row.\n&quot;) else: row = input(&quot;&quot;) while len(row) != 9 or not row.isnumeric(): row = input(f&quot;Wrong input. Please insert 9 numbers for row number {i+1}.\n&quot;) rows.append(row) for i in range(len(rows)): column = '' for j in range (len(rows)): column += rows[j][i] columns.append(column) for i in range(0,7,3): square_columns = [&quot;&quot;, &quot;&quot;, &quot;&quot;] for j in range(3): square_columns[0] += rows[j+i][:3] square_columns[1] += rows[j+i][3:6] square_columns[2] += rows[j+i][6:9] for square in square_columns: squares.append(square) sudoku_sets.append(rows) sudoku_sets.append(columns) sudoku_sets.append(squares) def check_sudoku(sets): for s in sets: for item in s: if len(item) == len(set(item)): continue else: return &quot;No&quot; return &quot;Yes&quot; print(check_sudoku(sudoku_sets)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T10:51:34.917", "Id": "532247", "Score": "1", "body": "Check out this answer from stackoverflow https://stackoverflow.com/a/17606526/13756061." } ]
[ { "body": "<p>Your code looks quite nice. Still there is some room for improvements.</p>\n<h1>Do not define variables in a single block at the beginning</h1>\n<p>This is a style from ancient C. Now the rule is to declare variables</p>\n<ul>\n<li>in the smallest possible scope</li>\n<li>as late as possible</li>\n</ul>\n<p>As you (currently) have a global scope only the latter rule applies. If you do</p>\n<pre><code>sudoku_sets = []\nsudoku_sets.append(rows)\nsudoku_sets.append(columns)\nsudoku_sets.append(squares)\n</code></pre>\n<p>the reader does not have to scan the 30 lines above if <code>sudoku_sets</code> is touched somewhere. It is absolutely clear what it holds.</p>\n<h1>Do not try to outsmart the language</h1>\n<pre><code>for i in range(0,7,3):\n</code></pre>\n<p>is a little strange. If you want to loop a range of 9 in steps of 3 - write it like that.</p>\n<pre><code>for i in range(0, 9, 3):\n</code></pre>\n<p>The language is designed to allow to write code in a way that does not require error prone hand knitting and fiddling.</p>\n<h1>Constants</h1>\n<p>Your checker only works for a square size of 9. That could be stated early in the file.\nWhile some of your code tries to be size agnostic there are many lines where hard coded numbers work for size 9 only.</p>\n<pre><code># rows fixed to nine \nfor i in range(9):\n\n# cols agnostic (but fixed to square)\nfor i in range(len(rows)):\n</code></pre>\n<h1>Functions</h1>\n<p>Functions are good to reduce scope and introduce better readability. Your code is nicely(!) structured into atomic tasks. Still one has to read and understand the code to recognize.\nWe can do an improvement and do a comment for each block or we can do a great improvement by extract the blocks into functions with a good name. We do 3 functions</p>\n<pre><code>def read_rows():\n ...\n return rows\n \ndef make_cols(rows):\n ...\n return cols\n\ndef make_squares(rows):\n ...\n return squares\n</code></pre>\n<p>That functions are self-contained and name the task and declare the dependencies. <code>make_squares</code> makes squares out of <code>rows</code>. It does not require <code>columns</code> and it does not fiddle with any other variable.\nWhen we use those functions we get a nicely readable top level code body.</p>\n<pre><code>rows = read_rows()\ncolumns = make_cols(rows)\nsquares = make_squares(rows)\ncheck_sudoku_sets([rows, columns, squares])\n</code></pre>\n<p>Also the nasty list initialisations are gone. They are inside the named functions and do not clutter the top level scope any more.</p>\n<h1>sudoku_sets</h1>\n<p>... is a bad name. It does not explain what it holds. Also there is no need for it as rows, cols and squares are not treated differently in the check. All 3 hold &quot;regions&quot;. So we can do</p>\n<pre><code>regions = rows + columns + squares\n</code></pre>\n<p>and simplify the check to</p>\n<pre><code>def check_sudoku(regions):\n for item in regions:\n if len(item) == len(set(item)):\n continue\n else:\n return &quot;No&quot;\n return &quot;Yes&quot;\n</code></pre>\n<h1>Do not I/O in your algorithms</h1>\n<p>That reduces usability and testability. You nearly did it right in your <code>check_sudoku</code> as there is no output. Still there is coupling to the output as you return strings designed for output. Return a bool instead and rename the function to a &quot;predicate style&quot;.</p>\n<pre><code>def is_valid_sudoku(regions):\n for item in regions:\n if len(item) == len(set(item)):\n continue\n else:\n return False\n return True\n</code></pre>\n<p>which can be shortened to</p>\n<pre><code>def is_valid_sudoku(regions):\n return all((len(item) == len(set(item)) for item in regions))\n</code></pre>\n<p>The translation to string shall be done in the output.</p>\n<h1>Result so far</h1>\n<p>The code now looks like</p>\n<pre><code># this implementation works for size = 9 only\n\ndef read_rows():\n rows = []\n for i in range(9):\n if i == 0:\n row = input(&quot;Input the sudoku values row by row.\\n&quot;)\n else:\n row = input(&quot;&quot;)\n while len(row) != 9 or not row.isnumeric():\n row = input(f&quot;Wrong input. Please insert 9 numbers for row number {i + 1}.\\n&quot;)\n rows.append(row)\n return rows\n\n\ndef make_cols(rows):\n columns = []\n for i in range(len(rows)):\n column = ''\n for j in range(len(rows)):\n column += rows[j][i]\n columns.append(column)\n return columns\n\n\ndef make_squares(rows):\n squares = []\n for i in range(0, 7, 3):\n square_columns = [&quot;&quot;, &quot;&quot;, &quot;&quot;]\n for j in range(3):\n square_columns[0] += rows[j + i][:3]\n square_columns[1] += rows[j + i][3:6]\n square_columns[2] += rows[j + i][6:9]\n for square in square_columns:\n squares.append(square)\n return squares\n\n\ndef is_valid_sudoku(regions):\n return all((len(item) == len(set(item)) for item in regions))\n\n\nrows = read_rows()\ncolumns = make_cols(rows)\nsquares = make_squares(rows)\nregions = rows + columns + squares\ntext = &quot;Yes&quot; if is_valid_sudoku(regions) else &quot;No&quot;\nprint(text)\n</code></pre>\n<h1>Loops</h1>\n<p>Avoid looping over indices but loop over elements. In <code>make_cols</code> do not loop like</p>\n<pre><code>for j in range(len(rows)):\n column += rows[j][i]\n</code></pre>\n<p>but do</p>\n<pre><code>for row in rows:\n column += row[i]\n</code></pre>\n<p>If you need the index as well loop like</p>\n<pre><code>for i, e in enumerate(some_list):\n</code></pre>\n<h1>Algorithms</h1>\n<p>You are concerned about <code>make_squares</code>. A simpler implementation would be to walk all cells by index and append the found digit to the corresponding square</p>\n<pre><code>def make_squares(rows):\n squares = [&quot;&quot; for _ in range(9)]\n for y, r in enumerate(rows):\n for x, e in enumerate(r):\n squares[(y//3)*3 + x//3] += e\n return squares\n</code></pre>\n<h1>More nitpicking</h1>\n<p>In your input function you have a special case for the first input line - pull that out of the loop like</p>\n<pre><code>def read_rows():\n print(&quot;Input the sudoku values row by row&quot;)\n rows = []\n for i in range(9):\n row = input(&quot;&quot;)\n ...\n \n</code></pre>\n<p>Also you do not check for valid symbols completely, you also accept the digit '0'.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T17:13:50.153", "Id": "269735", "ParentId": "269669", "Score": "2" } } ]
{ "AcceptedAnswerId": "269735", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T22:25:53.503", "Id": "269669", "Score": "1", "Tags": [ "python" ], "Title": "Sudoku Checker in Python" }
269669
<p>It's been a while since I've done any sort of programming, and my first time in Python. I'm just looking for any general feedback and tips since this is my first program.</p> <pre><code># rock, paper, scissors game import random playerWin = 0 aiWin = 0 guess = 0 print('You are playing rock, paper, scissors. If you would like to quit, type &quot;4&quot;') while int(guess) != 4: choices = ['', 'rock', 'paper', 'scissors'] aiGuess = random.randint(1, 3) # data validation while True: guess = input('Enter &quot;1&quot; for rock, &quot;2&quot; for paper, or &quot;3&quot; for scissors. &quot;4&quot; to quit: ') if str(guess) in ('1', '2', '3', '4'): break else: print('ERROR: NOT AN OPTION. TRY AGAIN.\n') # check player guess vs AI guess if int(guess) == aiGuess: # Tie game print('Tie game. The AI chose ' + choices[aiGuess] + '.') elif (int(guess) == 1 and aiGuess == 3) or (int(guess) == 2 and aiGuess == 1) or ( int(guess) == 3 and aiGuess == 2): # player wins print('You win! The AI chose ' + choices[aiGuess] + '.') playerWin += 1 elif int(guess) == 4: # quit break break else: # AI wins print('You lost. The AI chose ' + choices[aiGuess] + '.') aiWin += 1 print('SCORE: You have ' + str(playerWin) + ' points and the AI has ' + str(aiWin) + ' points.\n') # final score print print('\n################################################################') print('FINAL SCORE: You ended with ' + str(playerWin) + ' points and the AI had ' + str(aiWin) + ' points.') print('################################################################') </code></pre>
[]
[ { "body": "<p>First of all, great work! The program appears solid, the interface is decent and you handle bad input.</p>\n<p>I have a few suggestions for improvement:</p>\n<h3>UI/UX</h3>\n<ul>\n<li>The <code>&quot;1&quot;</code> <code>&quot;2&quot;</code> <code>&quot;3&quot;</code> <code>&quot;4&quot;</code> approach for input is nice in that the keys are near each other, but maybe <code>&quot;r&quot;</code> <code>&quot;p&quot;</code> <code>&quot;s&quot;</code> and <code>&quot;q&quot;</code> would make more semantic sense. You could generalize the input to allow <code>&quot;r&quot;</code> or full words like <code>&quot;rock&quot;</code> to be more flexible.</li>\n<li>After a while, <code>Enter &quot;1&quot; for rock, &quot;2&quot; for paper, or &quot;3&quot; for scissors. &quot;4&quot; to quit:</code> gets a little verbose and distracting, so you might want to abbreviate this after a few rounds, or have a special <code>&quot;help&quot;</code> command for instructions. Maybe show the reminder only after bad input was received.</li>\n<li><code>ERROR: NOT AN OPTION. TRY AGAIN.</code> is grating due to the caps. I prefer my apps to be gentle on me when I mess up, especially if I'm enjoying a relaxing game of RPS.</li>\n<li>Sending a <code>Ctrl+C</code> to kill the app raises a <code>KeyboardError</code>. You could <a href=\"https://stackoverflow.com/questions/18114560/python-catch-ctrl-c-command-prompt-really-want-to-quit-y-n-resume-executi\">catch this</a> and show final scores and exit cleanly.</li>\n<li>A &quot;play again?&quot; prompt, setting a target goal score, or allowing two humans to play would be nice.</li>\n</ul>\n<h3>Minor issues</h3>\n<ul>\n<li><p>Per <a href=\"https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles\" rel=\"nofollow noreferrer\">PEP-8</a>, always use <code>snake_case</code>, not <code>camelCase</code> in Python.</p>\n</li>\n<li><p>Add a line or two of vertical whitespace after imports. Check out <a href=\"https://github.com/psf/black\" rel=\"nofollow noreferrer\">black</a> which will format your code nicely.</p>\n</li>\n<li><p><code>int(guess)</code> <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">happens 6 times</a> and is rather hard on the eyes. If you even need to cast (you could just use strings throughout), I'd prefer to do it once up-front.</p>\n</li>\n<li><p>The code for the &quot;AI&quot;:</p>\n<pre><code>choices = ['', 'rock', 'paper', 'scissors']\naiGuess = random.randint(1, 3)\n</code></pre>\n<p>could be:</p>\n<pre><code>choices = [&quot;rock&quot;, &quot;paper&quot;, &quot;scissors&quot;]\nai_guess = random.randint(0, len(choices))\n</code></pre>\n<p>or better yet:</p>\n<pre><code>ai_guess = random.choice((&quot;rock&quot;, &quot;paper&quot;, &quot;scissors&quot;))\n</code></pre>\n</li>\n<li><p>In <code>if str(guess) in ('1', '2', '3', '4'):</code>, the <code>str()</code> cast is superfluous since <code>input()</code> always returns a string. It's best to move valid choices out of this hardcoded tuple and up to the top of the script.</p>\n</li>\n<li><p>Use f-strings instead of <code>+</code>:</p>\n<pre><code>print('SCORE: You have ' + str(playerWin) + ' points and the AI has ' + str(aiWin) + ' points.\\n')\n</code></pre>\n<p>becomes</p>\n<pre><code>print(f'SCORE: You have {playerWin} points and the AI has {aiWin} points.\\n')\n</code></pre>\n</li>\n<li><p><code>\\n################################################################'</code> could be <code>&quot;\\n&quot; + &quot;#&quot; * 64</code>.</p>\n</li>\n</ul>\n<h3>Design</h3>\n<p>If your goal is to get the code working as directly as possible, then plopping everything into one function in the global scope is fine. But for larger apps, you'll want to think through the design a bit more to make sure it's maintainable and extensible. For example, you might want to add <a href=\"https://en.wikipedia.org/wiki/Rock_paper_scissors#Additional_weapons\" rel=\"nofollow noreferrer\">lizard and spock</a>, a GUI, multiplayer over the network, or other features.</p>\n<p>A more maintainable design would be to separate user interaction and game logic and generalize where appropriate. Using functions is a good way to achieve this. Your code has comments delimiting sections like <code># data validation</code>, <code># check player guess vs AI guess</code> and <code># final score print</code>. These are good candidates for functions; the comments are a crutch here.</p>\n<p>Additionally, the code has high <a href=\"https://en.wikipedia.org/wiki/Cyclomatic_complexity\" rel=\"nofollow noreferrer\">cyclomatic complexity</a> (nested and wide branches and loops). Some of the conditions are lengthy and difficult to understand:</p>\n<pre class=\"lang-py prettyprint-override\"><code>elif (int(guess) == 1 and aiGuess == 3) or (int(guess) == 2 and aiGuess == 1) or (\n int(guess) == 3 and aiGuess == 2): # player wins\n ...\n</code></pre>\n<p>This would be another great refactoring opportunity; a function could help out quite a bit here, with the goal something like <code>if player_wins(player_guess, ai_guess): ...</code> from the client perspective.</p>\n<p>Dictionaries are a good way of encoding mappings between entities. For example, in RPS we have relationships between each of the items. By creating a dictionary of &quot;X beats Y&quot; relationships, we can avoid enumerating every possibility of the options and get an instant look-up to find out whether an item beats another.</p>\n<p>Since an RPS game is stateful and control flow passes back and forth between the UI and game engine, a class or two might be a reasonable design decision.</p>\n<h3>Suggested rewrite</h3>\n<pre class=\"lang-py prettyprint-override\"><code>import random\n\n\nclass RockPaperScissorsGame:\n PLAYER = 0\n COMPUTER = 1\n\n def __init__(self, objects):\n if len(objects) &lt; 3:\n raise ArgumentError(&quot;There must be at least 3 objects&quot;)\n\n self._objects = objects\n self._player_score = 0\n self._computer_score = 0\n\n @property\n def objects(self):\n return dict(self._objects)\n\n @property\n def player_score(self):\n return self._player_score\n\n @property\n def computer_score(self):\n return self._computer_score\n\n def validate_choice(self, choice):\n return choice in self._objects\n\n def handle_round(self, player_choice, computer_choice):\n if self._objects[player_choice] == computer_choice:\n self._player_score += 1\n return self.PLAYER\n elif self._objects[computer_choice] == player_choice:\n self._computer_score += 1\n return self.COMPUTER\n\n\nclass RockPaperScissorsUI:\n def __init__(self, objects):\n self.objects = objects\n self.abbrevations = {x[0]: x for x in objects}\n\n def play_one_game(self):\n self.game = game = RockPaperScissorsGame(self.objects)\n print(f'You are playing {&quot;, &quot;.join(self.objects)}.\\n'\n 'If you would like to quit, type &quot;quit&quot;\\n')\n \n while self.play_one_round():\n print(f&quot;You have {game.player_score} points and &quot;\n f&quot;the AI has {game.computer_score} points.\\n&quot;)\n\n print(f&quot;\\n{'#' * 64}\\nYou ended with {game.player_score} points and &quot;\n f&quot;the AI had {game.computer_score} points.\\n{'#' * 64}&quot;)\n\n def play_one_round(self):\n while True:\n prompt = f'Choose {&quot;, &quot;.join(self.objects)}: '\n user_input = input(prompt).lower()\n user_input = self.abbrevations.get(user_input, user_input)\n\n if user_input in (&quot;q&quot;, &quot;quit&quot;, &quot;exit&quot;):\n return False\n elif self.game.validate_choice(user_input):\n self.make_move(user_input)\n return True\n else:\n print(f&quot;Error: '{user_input}' is not an option. Try again.\\n&quot;)\n\n def make_move(self, user_input):\n computer_choice = random.choice(list(self.objects))\n result = self.game.handle_round(user_input, computer_choice)\n result_message = {\n self.game.PLAYER: &quot;You win!&quot;, \n self.game.COMPUTER: &quot;You lost!&quot;\n }.get(result, &quot;Tie game.&quot;)\n print(f&quot;{result_message} The computer chose {computer_choice}.&quot;)\n\n\nif __name__ == &quot;__main__&quot;:\n objects = {\n &quot;rock&quot;: &quot;scissors&quot;,\n &quot;paper&quot;: &quot;rock&quot;,\n &quot;scissors&quot;: &quot;paper&quot;,\n }\n game = RockPaperScissorsUI(objects)\n game.play_one_game()\n</code></pre>\n<p>Sample run:</p>\n<pre class=\"lang-none prettyprint-override\"><code>You are playing rock, paper, scissors.\nIf you would like to quit, type &quot;quit&quot;\n\nChoose rock, paper, scissors: Rock\nYou lost! The AI chose paper.\nYou have 0 points and the AI has 1 points.\n\nChoose rock, paper, scissors: rock\nYou lost! The AI chose paper.\nYou have 0 points and the AI has 2 points.\n\nChoose rock, paper, scissors: p\nYou lost! The AI chose scissors.\nYou have 0 points and the AI has 3 points.\n\nChoose rock, paper, scissors: asdasd\nError: 'asdasd' is not an option. Try again.\n\nChoose rock, paper, scissors: q\n\n################################################################\nYou ended with 0 points and the AI had 3 points.\n################################################################\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T18:02:37.637", "Id": "269709", "ParentId": "269675", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T02:33:21.043", "Id": "269675", "Score": "3", "Tags": [ "python", "beginner", "rock-paper-scissors" ], "Title": "Cliché Rock, Paper, Scissor, as first Python program" }
269675
<p>I've been working on a course assignment for 'The Odin Project' and was hoping to get a review of my code.</p> <p>As per the help guide, the code is fully functional.</p> <p>The criteria for this was pretty straight forward. Try to have as little global code as possible. (At this point I've learned about classes, and modules)</p> <p>I feel that I'm breaking some rules when it comes to clean code.</p> <p><strong>Live example:</strong><br /> <a href="https://ablueblaze.github.io/TicTacToe/" rel="nofollow noreferrer">https://ablueblaze.github.io/TicTacToe/</a></p> <p><strong>Repository:</strong><br /> <a href="https://github.com/ablueblaze/TicTacToe" rel="nofollow noreferrer">https://github.com/ablueblaze/TicTacToe</a></p> <p><strong>JavaScript:</strong></p> <pre class="lang-js prettyprint-override"><code>document.addEventListener(&quot;DOMContentLoaded&quot;, () =&gt; { // Event listener for all the cells document.querySelectorAll(&quot;.cell&quot;).forEach((cell) =&gt; cell.addEventListener(&quot;click&quot;, (e) =&gt; { gameControls.makePlay(e, player1, player2, testBoard); }) ); // Event listener for when the modal is active document .querySelector(&quot;[data-modal]&quot;) .addEventListener(&quot;click&quot;, displayControls.toggleModal); // Event listener for the new game button document.getElementById(&quot;new-game&quot;).addEventListener(&quot;click&quot;, () =&gt; { gameControls.newGameBtn(testBoard); }); // Event listener for the clear scores button document.querySelector(&quot;#clear-scores&quot;).addEventListener(&quot;click&quot;, () =&gt; { gameControls.clearAllScoresBtn(player1, player2); }); }); class GameBoard { constructor() { this.controlBoard = [1, 2, 3, 4, 5, 6, 7, 8, 9]; this.displayBoard = [&quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;]; } isFull() { let count = 0; for (let i = 1; i &lt; 10; i++) { if (this.controlBoard.includes(i)) { count++; } } if (count === 0) { return true; } } markBoard(play, playerMark) { if (this.controlBoard.includes(play)) { let index = this.controlBoard.findIndex((e) =&gt; e === play); this.controlBoard[index] = 0; this.displayBoard[index] = playerMark; return true; } } boardReset() { this.controlBoard = [1, 2, 3, 4, 5, 6, 7, 8, 9]; this.displayBoard = [&quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;]; } } // A player class that will hold the players marker, and all the plays that they have made class Player { constructor(marker, plays = [], score = 0) { this.marker = marker; this.plays = plays; this.score = score; } addPlay(play) { this.plays.push(play); } clearPlays() { this.plays = []; } clearScore() { this.score = 0; } scoreUp() { this.score++; } // returns true if player has a winning hand didIWin() { const winingHands = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7], ]; let count = 0; for (let i of winingHands) { for (let n of i) { if (this.plays.includes(n)) { count++; } } if (count === 3) { return true; } count = 0; } return false; } } const testBoard = new GameBoard(); let currentBoard = testBoard.displayBoard; const player1 = new Player(&quot;X&quot;); const player2 = new Player(&quot;O&quot;); const displayControls = (() =&gt; { // Updates the pages game board function boardUpdate(displayBoard) { for (let i = 0; i &lt; displayBoard.length; i++) { let activeCell = document.querySelector(`[data-cell-value=&quot;${i + 1}&quot;]`); activeCell.textContent = displayBoard[i]; } } // Updates the pages score board function scoreUpdate(player1Score, player2Score) { const pXScore = document.querySelector(&quot;#player-one-score&quot;); const pOScore = document.querySelector(&quot;#player-two-score&quot;); pXScore.textContent = player1Score; pOScore.textContent = player2Score; } // Update the current player banner, by flipping the return from current player function showCurrentPlayer(currentPLayerMarker) { const playerSpan = document.querySelector(&quot;#current-player&quot;); if (currentPLayerMarker === &quot;X&quot;) { playerSpan.textContent = &quot;O&quot;; return; } playerSpan.textContent = &quot;X&quot;; } // Set the Winner text in modal function setWinner(winningPlayerMarker) { const winner = document.querySelector(&quot;.winner&quot;); winner.textContent = `Winner: ${winningPlayerMarker}`; } // Set the Winner text in modal to Tie function showTie() { const winner = document.querySelector(&quot;.winner&quot;); winner.textContent = &quot;It's a Draw!&quot;; } function toggleModal() { const modal = document.querySelector(&quot;[data-modal]&quot;); if (modal.className === &quot;modal active&quot;) { modal.classList.remove(&quot;active&quot;); return; } modal.classList.add(&quot;active&quot;); } return { boardUpdate, scoreUpdate, showCurrentPlayer, setWinner, showTie, toggleModal, }; })(); const gameControls = (() =&gt; { // Toggle between the given players let playCounter = 1; function togglePlayer(player1, player2) { playCounter++; if (playCounter % 2 == 0) { return player1; } else { return player2; } } function resetCounter() { playCounter = 1; } function newGameBtn(activeBoard) { resetCounter(); activeBoard.boardReset(); displayControls.boardUpdate(activeBoard.displayBoard); displayControls.showCurrentPlayer(&quot;O&quot;); } function clearAllScoresBtn(player1, player2) { player1.clearScore(); player2.clearScore(); displayControls.scoreUpdate(player1.score, player2.score); } function clearPlays(player1, player2, activeBoard) { player1.clearPlays(); player2.clearPlays(); activeBoard.boardReset(); } // Runs after a game is finished function nextGame(player1, player2, activeBoard) { clearPlays(player1, player2, activeBoard); displayControls.boardUpdate(activeBoard.displayBoard); displayControls.toggleModal(); } // Check to see if a game is done function endGame(currentPlayer, player1, player2, activeBoard) { if (currentPlayer.didIWin()) { currentPlayer.scoreUp(); displayControls.setWinner(currentPlayer.marker); displayControls.scoreUpdate(player1.score, player2.score); nextGame(player1, player2, activeBoard); } else if (activeBoard.isFull()) { displayControls.showTie(); clearPlays(player1, player2, activeBoard); nextGame(player1, player2, activeBoard); } } function makePlay(event, player1, player2, activeBoard) { let currentPlayer = togglePlayer(player1, player2); let cellValue = parseFloat(event.target.dataset.cellValue); activeBoard.markBoard(cellValue, currentPlayer.marker); currentPlayer.addPlay(cellValue); displayControls.boardUpdate(activeBoard.displayBoard); displayControls.showCurrentPlayer(currentPlayer.marker); endGame(currentPlayer, player1, player2, activeBoard); } return { makePlay, clearPlays, newGameBtn, clearAllScoresBtn }; })(); </code></pre> <p>Thanks A bunch!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T11:49:13.130", "Id": "532801", "Score": "0", "body": "Thanks Sam for editing!" } ]
[ { "body": "<p>Welcome to Code Review, your game looks pretty nice!</p>\n<p>There is quite a lot of code to go through but here are some initial observations.</p>\n<h1>Constructor</h1>\n<p>You are using exactly the same code in the <code>GameBoard</code> constructor and in <code>boardReset</code>. You should rather simply call <code>boardReset</code> from the constructor:</p>\n<pre><code>constructor() {\n this.boardReset();\n}\n</code></pre>\n<h1>isFull</h1>\n<p>Note that <code>includes</code> does not work in all browsers, not that anybody should be using IE9 anymore =).</p>\n<p>This can be simplified by checking if there are any empty spaces left:</p>\n<pre><code>isFull() {\n return this.displayBoard.indexOf(&quot;&quot;) == -1;\n}\n</code></pre>\n<h1>markBoard</h1>\n<p>Here you first use <code>contains</code> to check if the item is in the list and then <code>indexOf</code> to get the index. You could have simplified this like so:</p>\n<pre><code>markBoard(play, playerMark) {\n let index = this.controlBoard.findIndex((e) =&gt; e === play);\n if (index != -1) {\n this.controlBoard[index] = 0;\n this.displayBoard[index] = playerMark;\n return true;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T15:15:19.683", "Id": "532168", "Score": "2", "body": "\"_Note that includes does not work in all browsers, not that anybody should be using IE9 anymore_\" the OP is also using es6 features like [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#browser_compatibility) and even [class expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/class#browser_compatibility) which are not supported by IE so the point is moot." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T15:46:32.027", "Id": "532175", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ, I agree but some of us unfortunate souls still have to cater for fools running IE :-(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T11:48:26.693", "Id": "532800", "Score": "0", "body": "Thank you for the feed back. I was afraid that my little project was to simple for anyone to take a look at. :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T12:36:12.800", "Id": "269694", "ParentId": "269683", "Score": "2" } }, { "body": "<p>The hardest thing about programming is creating a good project structure, but this is also the most important thing to get correct. Your project is structured well, and cleanly follows the model-view-controller structure, so great job! Your view logic is cleanly separated from the underlying model, and your controller is requesting updates on both the model and the view. They're not trying to do each other's jobs, or cross each other's boundaries.</p>\n<p>However, as we zoom into some smaller details, there are a number of things that could certainly be tidied up a bit.</p>\n<h2>DOMContentLoaded</h2>\n<p>There's really no need to use <code>.forEach()</code> anymore. for-of can do everything forEach does, and more (e.g. for-of lets you use continue/break within the loop).</p>\n<p>You're using both <code>getElementById()</code> and <code>querySelector()</code> to select elements by ID. Pick one and stick with it.</p>\n<h2>GameBoard</h2>\n<p>@jdt already gave some good suggestions on how to improve this class. I'll add a couple more things.</p>\n<p><code>isFull()</code>'s logic is a little odd. It looks like you're just trying to check if <code>controlBoard()</code> contains a number between 1 and 9. If so, you return true, if not you return undefined (why not return false instead of undefined?). However, the only other digit this array is able to contain is 0. I think the following code snippet does a better job at capturing the idea we're trying to accomplish:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>isFull() {\n for (let x of this.controlBoard) {\n if (x !== 0) return false;\n }\n return true;\n}\n</code></pre>\n<p>Or even better, we can use a higher-order function, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every\" rel=\"nofollow noreferrer\">array.every()</a>. (In general, it may be worthwhile to familiarize yourself with the numerous array methods available, so you can utilize them in times of need).</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>isFull() {\n return this.controlBoard.every((x) =&gt; x === 0);\n}\n</code></pre>\n<p>Instead of this:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>this.controlBoard.findIndex((e) =&gt; e === play);\n</code></pre>\n<p>you can do this:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>this.controlBoard.indexOf(play);\n</code></pre>\n<h2>Player</h2>\n<p>In didIWin(), you did <code>for (let i of winingHands) { ... }</code>, generally the &quot;i&quot; loop variable is only used to hold an array index. In this scenario, &quot;i&quot; is holding an array. It would be better to name it something else - anything else, even &quot;x&quot; would be better.</p>\n<p>Also, instead of resetting your &quot;count&quot; variable at the end of each iteration, why not move the initial declaration into the loop.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>didIWin() {\n const winingHands = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n [1, 4, 7],\n [2, 5, 8],\n [3, 6, 9],\n [1, 5, 9],\n [3, 5, 7],\n ];\n for (let winningHand of winingHands) {\n let count = 0;\n for (let n of winningHand) {\n if (this.plays.includes(n)) {\n count++;\n }\n }\n if (count === 3) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n<p>We can continue to clean this up a little more by using the higher-order function that we learned about earlier, <code>array.every()</code>, along with its companion <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some\" rel=\"nofollow noreferrer\">array.some()</a>.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>didIWin() {\n const winingHands = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n [1, 4, 7],\n [2, 5, 8],\n [3, 6, 9],\n [1, 5, 9],\n [3, 5, 7],\n ];\n const isHandInPlay = hand =&gt; hand.every(n =&gt; this.plays.includes(n));\n return winingHands.some(isHandInPlay);\n}\n</code></pre>\n<h2>gameControls</h2>\n<p>Don't use loose equality (==), use strict equality instead (===) (you correctly use strict equality everywhere else, so I assume this was simply a slip-up).</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>// before\nif (playCounter % 2 == 0) { ... }\n// after\nif (playCounter % 2 === 0) { ... }\n</code></pre>\n<h2>misc</h2>\n<p>Don't write comments that are trivially inferred by reading the code. For example:</p>\n<pre><code>// Updates the pages game board\nfunction boardUpdate(displayBoard) { ... }\n</code></pre>\n<p>There's nothing wrong with adding some comments to help explain the code, but try to reserve it for stuff that isn't self-explanatory.</p>\n<p>On naming functions: Prefer &quot;action&quot; verb-like names. i.e. &quot;scoreUpdate&quot; doesn't sound right. The function isn't a single &quot;score update&quot;, rather, it's a function that &quot;updates a score&quot;. So, a name like <code>updateScore()</code> may be more appropriate, Likewise, <code>resetBoard()</code> makes more sense than <code>boardReset()</code>. Above all, make sure your variable names don't lie, for example, the name <code>endGame()</code> is a lie. This function does not simply end the game, what it really does is check if the game is in an end-condition, and if so, it'll end the game. The difference is important - right now, if you read the definition of makePlay(), it sounds like at the end of each play the game ends, which is simply not true!</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>function makePlay(event, player1, player2, activeBoard) {\n let currentPlayer = togglePlayer(player1, player2);\n let cellValue = parseFloat(event.target.dataset.cellValue);\n activeBoard.markBoard(cellValue, currentPlayer.marker);\n displayControls.updateBoard(activeBoard.displayBoard);\n displayControls.showCurrentPlayer(currentPlayer.marker);\n endGame(currentPlayer, player1, player2, activeBoard); // The game does not end here!\n}\n</code></pre>\n<p>Renaming it to something like endGameIfAble() makes what's going on so much clearer.</p>\n<h2>GameBoard rewrite</h2>\n<p>Prefer keeping the amount of state in your application down to a minimum. For example, your GameBoard class is unnecessarily trying to keep two chunks of state in sync - the controlBoard array and the displayBoard array. If you think about it, the controlBoard array could be derived from the displayBoard array at any moment, by passing it through a function such as this:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>#getControlBoard() {\n return this.displayBoard.map((square, i) =&gt; square === &quot;&quot; ? i + 1 : 0)\n}\n</code></pre>\n<p>This would allow us to refactor the class as follows:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>class GameBoard {\n constructor() {\n this.resetBoard();\n }\n #getControlBoard() {\n return this.displayBoard.map((square, i) =&gt; square === &quot;&quot; ? i + 1 : 0);\n }\n isFull() {\n return this.#getControlBoard().every((x) =&gt; x === 0);\n }\n markBoard(play, playerMark) {\n let index = this.#getControlBoard().indexOf(play);\n if (index !== -1) {\n this.displayBoard[index] = playerMark;\n }\n // I made it so it's not returning a boolean anymore.\n // You didn't seem to be using the return value anywhere anyways.\n }\n resetBoard() {\n this.displayBoard = [&quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;];\n }\n}\n</code></pre>\n<p>This is a generic solution to get rid of duplicate state, but we can actually do even better in this scenario. There are only two places where #getControlBoard() is being used, and neither of them really need this particular data structure. We can simply make them rely on this.displayBoard instead, which actually simplifies the logic a bit.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>class GameBoard {\n constructor() {\n this.resetBoard();\n }\n isFull() {\n return this.displayBoard.every((x) =&gt; x !== &quot;&quot;);\n }\n markBoard(play, playerMark) {\n if (this.displayBoard[play - 1] === &quot;&quot;) {\n this.displayBoard[play - 1] = playerMark;\n }\n }\n resetBoard() {\n this.displayBoard = [&quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;];\n }\n}\n</code></pre>\n<p>I would recommend going further and turning the state into something that more naturally represents the board itself. Tic-tac-toe is played on a 2d board, so perhaps a 3x3 2d array would make more sense as a natural data structure to hold the current state of the board.</p>\n<p>There are other areas that keep unnecessary state as well, for example, gameControls keeps track of how many turns have passed since the last time you pushed the reset button (or since the game first started), but you don't actually need that much information anywhere. All you need to know is who's turn it currently is.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>// before\nlet playCounter = 1;\nfunction togglePlayer(player1, player2) {\n playCounter++;\n if (playCounter % 2 === 0) {\n return player1;\n } else {\n return player2;\n }\n}\n\n// after\nlet currentPlayer = 1;\nfunction togglePlayer(player1, player2) {\n currentPlayer = currentPlayer === 1 ? 2 : 1;\n return currentPlayer === 1 ? player1 : player2;\n}\n</code></pre>\n<p>Why does this matter? Because it's extra stuff to keep track of, when someone's first reading through your code. It looks like you care about how many turns have passed, when in reality, you don't, so there's no need to make code readers expect that you are using this sort of data in your program. Granted, this is a minor nit-picky thing, but the tiny things add up.</p>\n<p>Another locations with extra state would be the <code>players</code> array in the <code>Player</code> class. The plays that a player has done is already found within the game board, you don't need to duplicate pieces of this information across each player. Getting rid of this chunk of state would make it so you don't have to update both the board and the player, each time something changes on the board.</p>\n<h2>Conclusion</h2>\n<p>Alright, that's it. Overall, it looks pretty good. It's clean and readable, and you don't have any major issues going on. Keep up the good work :).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T15:48:12.883", "Id": "270450", "ParentId": "269683", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T05:40:38.590", "Id": "269683", "Score": "3", "Tags": [ "javascript", "beginner", "ecmascript-6", "tic-tac-toe" ], "Title": "Tic Tac Toe in object oriented JavaScript" }
269683
<p>Continued from the previous <a href="https://codereview.stackexchange.com/questions/269569/find-maximum-value-of-recursively-defined-fusc-function/269573?noredirect=1#comment532093_269573">post</a> - a brute-force approach to calculating all the vectors from 0 to n.</p> <p>I've come up with yet another solution, after I've realized that the vector takes up too much memory. But it is still not satisfactory, and is quite slow to the point that it is noticeable even on my local machine. I know that this code can be made in such a way that it only requires one for-loop, but I am not sure on how to implement that.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;math.h&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;iostream&gt; int main() { uint64_t number, leastMultipleOf2, powerOfTwo, maxFusc; std::vector&lt;uint64_t&gt; saveVector = {1, 2, 1}; std::cin &gt;&gt; number; if (number==0 || number==1) { maxFusc = number; } else { powerOfTwo = floor(log2(number)); leastMultipleOf2 = pow(2.0, powerOfTwo)/2; saveVector.reserve(leastMultipleOf2+1); for(int i=1; i&lt;powerOfTwo; i++) { maxFusc = *max_element(saveVector.begin(), saveVector.end()); for(int j=1; j &lt;= (2*pow(2.0, i))-1; j+=2) { saveVector.insert(saveVector.begin() + j, saveVector[j-1] + saveVector[j]); } } maxFusc = std::max(maxFusc, *max_element(saveVector.begin(), saveVector.begin()+(number-(2*leastMultipleOf2)+1))); } std::cout &lt;&lt; maxFusc &lt;&lt; std::endl; } </code></pre> <p>What improvements can be done on this snippet of code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T04:49:21.740", "Id": "532325", "Score": "0", "body": "It's worth mentioning that `fusc` is [Stern's diatomic series](https://mathworld.wolfram.com/SternsDiatomicSeries.html), [A002487](https://oeis.org/A002487), and so it would not be surprising to find that there was a well-known closed form for the answer. See [\"The amazing 'fusc' function\"](https://rhubbarb.wordpress.com/2013/04/16/sterns-brocot-calkin-wilf-dijkstra/) (Rob Hubbard, April 2013)." } ]
[ { "body": "<p>Prefer the C++ header <code>&lt;cmath&gt;</code>. This puts the relevant functions into the <code>std</code> namespace.</p>\n<p>Talking of namespace, several other identifiers are used without the necessary qualification (<code>std::uint64_t</code>, <code>std::max_element</code>).</p>\n<p>We use <code>&gt;&gt;</code> streaming without any checking for successful conversion.</p>\n<p>We use <code>std::endl</code> when a plain newline would be sufficient.</p>\n<p><code>std::uint64</code> isn't a required type - prefer one of the guaranteed types unless you need exactly 64 bits.</p>\n<p>Don't declare all the variables up front. Prefer to minimise scope, and if possible, declare and initialise in one.</p>\n<p>Prefer integer <code>&lt;&lt;</code> to <code>std::pow(2.0, x)</code>. It's more exact, and faster.</p>\n<p>Create a function instead of cramming everything into <code>main()</code>.</p>\n<p>Why are we examining the entire array with <code>std::max_element()</code> every time around the loop? Do it just once at the end, or update <code>maxFusc</code> as we go.</p>\n<p>Whilst we can reason about this particular sequence to come up with a faster method, I got several hundred times speedup simply using the obvious approach of computing each value from its previously-calculated dependent values:</p>\n<pre><code>#include &lt;cstdlib&gt;\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\n\nusing Number = std::int_fast64_t;\n\nNumber max_fusc(Number n)\n{\n if (n &lt;= 1) {\n return n;\n }\n\n std::vector&lt;Number&gt; cache(n);\n cache[1] = 1;\n\n Number max{0};\n for (Number i = 2; i &lt; n; ++i) {\n cache[i] = cache[i/2] + i % 2 * cache[i/2+1];\n if (cache[i] &gt; max) {\n max = cache[i];\n }\n }\n\n return max;\n}\n\nint main()\n{\n Number number;\n std::cin &gt;&gt; number;\n if (!std::cin) {\n std::cerr &lt;&lt; &quot;Invalid input\\n&quot;;\n return EXIT_FAILURE;\n }\n std::cout &lt;&lt; max_fusc(number) &lt;&lt; '\\n';\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T12:53:27.703", "Id": "532154", "Score": "0", "body": "This won't pass the SPOJ tester - says that the answer is wrong. But I've tested this locally, and it is working fine till 10^7 - greater than that, this code fails to run, just like the previous implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T13:16:24.820", "Id": "532155", "Score": "0", "body": "Perhaps the online challenge has other constraints - a common one is that it wants the results modulo some other number (often 1'000'000'007, I think)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T13:17:27.633", "Id": "532156", "Score": "0", "body": "If you want to evaluate the function for larger values, then we need to use more of the properties of the function. Works fine here with 10⁸ as input (giving result 317811) but larger values obviously require more memory for the result cache." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T13:24:32.967", "Id": "532160", "Score": "0", "body": "This was what I saw as generic - f(2n) = f(n) and f(2n+1) = f(n) + f(n+1) - using this would force us to use brute force. If we go down a little, it talks about arithmetic progression, and so I was thinking that maybe we could leverage that? But then, traversal of vectors is very slow, when we reach the order of 10^7. Should it be better that we use array?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T16:59:06.273", "Id": "532187", "Score": "1", "body": "The constraint given by SPOJ is \\$n \\le 10^{15}\\$. Paired with the memory limit of `1536 MB` it effectively prohibits any cache-based solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T17:00:38.617", "Id": "532188", "Score": "0", "body": "Thanks for the extra information @vnp. Shame that wasn't mentioned in the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T14:45:42.287", "Id": "532277", "Score": "0", "body": "@AshvithShetty traversing a vector should be the same speed as an array. They are both _contiguous_ collections." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T12:10:56.040", "Id": "269692", "ParentId": "269684", "Score": "1" } }, { "body": "<p>Given the constraints not mentioned in the question (namely that input may be as large as 10¹⁵ and memory use is limited to 1½ GB), this loop is not the way to approach this problem:</p>\n<blockquote>\n<pre><code> for(int i=1; i&lt;powerOfTwo; i++) {\n</code></pre>\n</blockquote>\n<p>Instead, we'll want to find ways to determine the maximum value by examining the properties of the sequence. It probably helps to consider the binary representation of numbers, given the importance of dividing by two to the definition of the function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T07:34:22.827", "Id": "269722", "ParentId": "269684", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T06:09:51.143", "Id": "269684", "Score": "1", "Tags": [ "c++", "performance", "time-limit-exceeded", "vectors" ], "Title": "RE: Find maximum value of recursively-defined \"fusc\" function" }
269684
<p>I'm trying to create a stack library from scratch. It stores generic elements which are passed in <code>void*</code> pointers.</p> <p>This is the defined structure:</p> <pre><code>typedef struct stackObject { void* obj; struct stackObject *next; } StackObject_t; typedef struct stackMeta { StackObject_t *stack; size_t objsize; int numelem; } StackMeta_t; </code></pre> <p>So far I have implemented the following:</p> <pre><code>#include &lt;stddef.h&gt; #include &lt;stdio.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; /* Creates a stack of c objects of size objsize and returns * a handle (pointer) to the just created stack. On error, * NULL is returned.*/ StackMeta_t *mystack_create(size_t objsize) { StackMeta_t *newstack = malloc(sizeof(StackMeta_t)); if(newstack != NULL &amp;&amp; objsize &gt; 0){ newstack-&gt;stack = NULL; newstack-&gt;objsize = objsize; newstack-&gt;numelem = 0; return newstack; } else{ return NULL; } } /* Pushes an object to the stack identified by its handle * returns 0 on success and -1 on an error*/ int mystack_push(StackMeta_t *stack, void* obj) { /* pointer to new object */ StackObject_t *newObj = malloc(sizeof(StackObject_t)); newObj-&gt;obj = malloc(stack-&gt;objsize); if(newObj != NULL){ newObj-&gt;obj = memcpy(newObj-&gt;obj, obj, stack-&gt;objsize); newObj-&gt;next = stack-&gt;stack; stack-&gt;stack = newObj; stack-&gt;numelem++; return 0; } else{ /* no space available */ return-1; } } /* Pops an object from the stack identified by its handle * returns 0 on success and -1 on an error*/ int mystack_pop(StackMeta_t *stack, void* obj) { StackObject_t *tempObj = stack-&gt;stack; if(tempObj != NULL){ obj = memcpy(obj, tempObj-&gt;obj, stack-&gt;objsize); stack-&gt;stack = tempObj-&gt;next; stack-&gt;numelem--; free(tempObj-&gt;obj); free(tempObj); return 0; } else{ return -1; } } /* Destroys and cleans the stack handle */ void mystack_destroy(StackMeta_t *stack) { StackObject_t *tempObj = stack-&gt;stack; StackObject_t *nextObj = NULL; while(tempObj != NULL){ nextObj = tempObj-&gt;next; free(tempObj-&gt;obj); free(tempObj); tempObj = nextObj; } stack = NULL; } /* Returns number of elements of the stack or -1 if invalid handle*/ int mystack_nofelem(StackMeta_t *stack) { if(stack != NULL){ return stack-&gt;numelem; } return -1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T08:45:09.573", "Id": "532134", "Score": "0", "body": "What is the purpose of the `objsize` parameter? It seems to be unused, as you only store pointers to the objects." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T16:19:26.913", "Id": "532181", "Score": "1", "body": "I can't help but point out that C++ has container types as part of its standard library, and language support for generic code." } ]
[ { "body": "<h1>Data structure</h1>\n<p>We've implemented a stack using a linked list. That will work, but is likely less efficient than using a growable array.</p>\n<p>We only store pointers to the objects in the stack, meaning that we are dependent on the owners of those objects for lifecycle. If any of the objects is freed while we hold a pointer, we don't know that the pointer is no longer valid.</p>\n<p>It might make sense to copy the passed objects to our stack instead (and if we did that, we would actually need the <code>objsize</code> member, to allocate sufficient storage).</p>\n<p>Why is <code>numelem</code> a (signed) <code>int</code>? I think <code>size_t</code> is more appropriate for a count of objects.</p>\n<h1>Code</h1>\n<p>The following headers are included but not needed:</p>\n<blockquote>\n<pre><code>#include &lt;stddef.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdbool.h&gt;\n#include &lt;string.h&gt;\n</code></pre>\n</blockquote>\n<p><code>malloc()</code> and related functions work with <code>void*</code>, so there's no need to cast when assigning to other pointer types. It's also good practice to use an expression rather than a type as argument to <code>sizeof</code> operator:</p>\n<pre><code> StackMeta_t *newstack = malloc(sizeof *newstack);\n</code></pre>\n<p>If we pass a zero size, we allocate <code>newstack</code> but then leak it. I would test for that before the allocation:</p>\n<pre><code>StackMeta_t *mystack_create(size_t objsize)\n{\n if (objsize == 0) {\n return NULL;\n }\n\n StackMeta_t *newstack = malloc(sizeof *newstack);\n if (newstack) {\n newstack-&gt;objsize = objsize;\n newstack-&gt;numelem = 0;\n newstack-&gt;stack-&gt;next = NULL;\n }\n return newstack;\n}\n</code></pre>\n<p>However, think about whether we really need the stack structure to be in allocated memory. Is there really a good reason we shouldn't be able to use automatic storage? It might be better to provide</p>\n<pre><code>bool mystack_init(StackMeta_t&amp;, size_t)\n</code></pre>\n<p>We can still provide <code>mystack_create()</code>, but now implemented by using the init function on our allocated object.</p>\n<p>Why does <code>mystack_push()</code> return <code>int</code>? We had an include of <code>&lt;stdbool.h&gt;</code> that we didn't use, and that would be a good choice of return type to indicate success or failure.</p>\n<p><code>mystack_pop()</code> looks like it might be better to return a pointer, with <code>NULL</code> indicating failure.</p>\n<p><code>mystack_nofelem()</code> can take its argument as pointer-to-const.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T16:22:53.837", "Id": "532182", "Score": "3", "body": "I have to emphasize the remark that linked lists are **slow** on modern architectures. Memory access time dominates, and jumping around gives you a cold cache. Allocating and freeing when pushing and popping will be slow. There are hour-long talks given at conferences and papers published showing that memory locality is king, and a std::vector beats a linked list even at things they teach you that linked lists are good for, for a _surprisingly large_ list size." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T16:46:24.187", "Id": "532185", "Score": "1", "body": "For very large stacks, a hybrid solution works well - a linked list of contiguous blocks of items, so we don't get problems when we `realloc()`. But don't do that until it's necessary, as it adds a lot of bookkeeping complexity (and if/when you do, then unit-test it half to death!)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T16:52:52.043", "Id": "532186", "Score": "0", "body": "yes, that would be how `std::deque` works." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T09:23:34.567", "Id": "269689", "ParentId": "269685", "Score": "1" } }, { "body": "<p><strong><code>objsize == 0</code></strong></p>\n<p>Why error? Code is (should be) certainly capable of handling <code>objsize == 0</code>.</p>\n<p>As is, code leaks memory when <code>objsize == 0</code> as <code>mystack_create()</code> allocation is lost.</p>\n<p><strong>Allocate to the size of the referenced type</strong></p>\n<p>Its easier to code right, review and maintain.</p>\n<pre><code>// newstack = malloc(sizeof(StackMeta_t));\nnewstack = malloc(sizeof *newstack);\n</code></pre>\n<p><strong>Missing <code>StackMeta.h</code></strong></p>\n<p>I'd expect a companion <code>StackMeta.h</code> with the public functions. Put the documentation there. Users do not need to see the implementation nor the details of <code>StackMeta_t</code>.</p>\n<p><strong>Info hiding</strong></p>\n<p>Consider adding access functions instead of exposing <code>struct</code> members to the public.</p>\n<p><strong>Use <code>const</code> as able</strong></p>\n<p>This allows greater application as <code>const</code> data may pushed.</p>\n<pre><code>// int mystack_push(StackMeta_t *stack, void* obj)\nint mystack_push(StackMeta_t *stack, const void* obj)\n</code></pre>\n<p><strong>Tolerate <code>mystack_destroy(NULL)</code></strong></p>\n<p>Like <code>free(NULL)</code> is OK, test the pointer. This simplifies calling code usage, especially in error handling.</p>\n<pre><code>void mystack_destroy(StackMeta_t *stack) {\n if (stack) {\n StackObject_t *tempObj = stack-&gt;stack;\n ...\n</code></pre>\n<p><strong>Pedantic: Pushing too much is OK?</strong></p>\n<p>No detection of impending <code>stack-&gt;numelem++</code> overflow.</p>\n<p><strong>Why clear <em>sometimes</em></strong></p>\n<p><code>stack = NULL;</code> at the end of <code>mystack_destroy()</code> has merit, so does clearing data before free'ing it - which is not done.</p>\n<p><strong>Consider a <code>peek()</code></strong></p>\n<p>Code some way to get the top without popping.</p>\n<pre><code>int mystack_peek(const StackMeta_t *stack, void* obj);\n</code></pre>\n<p><strong>Consider an <code>apply()</code></strong></p>\n<p>Code some way to apply a function to each member of the stack. Very useful.</p>\n<pre><code>int mystack_apply(const StackMeta_t *stack, int foo(void *state, void *obj), void *state) {\n // For each member of the stack, call foo(state, obj)\n // If return value is non-zero, quit loop early with that value.\n</code></pre>\n<p><strong>Reduce error</strong></p>\n<p>Now, <code>mystack_nofelem(NULL)</code> returns -1 (an error). I'd consider such benign function calls on <code>NULL</code> as OK and just return 0 here.</p>\n<p>I doubt calling code is going to check for -1.</p>\n<p><strong>Advanced: Research <code>restrict</code></strong></p>\n<p>Selectively use <code>restrict</code> on pointers for greater optimization potential.</p>\n<p>Example: The compiler can assume <code>stack</code> and <code>obj</code> do not point to overlapping data. (And you are letting the caller know not to attempt such pathological code.)</p>\n<pre><code>// int mystack_pop(StackMeta_t *stack, void* obj)\nint mystack_pop(StackMeta_t * restrict stack, void* restrict obj)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T22:06:23.587", "Id": "269718", "ParentId": "269685", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T07:21:50.803", "Id": "269685", "Score": "3", "Tags": [ "c", "stack" ], "Title": "Stack API for generic values" }
269685
<p>For my game I need to roll some values with a die. A die is formally described as:</p> <blockquote> <p><strong>nDs[+a]</strong></p> <ul> <li><em>n</em> amount of die (optional, 1 of not set, zero must be set explicitly)</li> <li><code>D</code> is a fixed part representing this expression as die</li> <li><em>s</em> amount sides of the die/dice</li> <li><em>+a</em> additional amount</li> </ul> </blockquote> <p>examples:</p> <ul> <li><code>2D6</code> : 2 six-sided dice, result 2..12</li> <li><code>2D6+1</code> : 2 six-sided dice + 1, result 3..13</li> <li><code>3D4+2</code> : 3 four-sided dice + 2, result 5..14</li> </ul> <h2>Implementation of class <code>Die</code></h2> <pre><code>public class Die { private static final String INPUT_VALIDATION_PATTERN = &quot;^\\d*D\\d*(\\+\\d+)?$&quot;; private static final String SINGLE_DIE_PATTERN = &quot;\\d*D\\d*&quot;; private static final String ADDITION_SEPARATOR_PATTERN = &quot;\\+&quot;; private static final String DIE_SEPARATOR_PATTERN = &quot;D&quot;; private static final String ADD_PATTERN = &quot;\\d*&quot;; private static final String WHITESPACE_PATTERN = &quot;\\s+&quot;; //package visible for testing final int amount; final int sides; final int addition; public Die(String input) { String adjusted = input.toUpperCase(Locale.ROOT).replaceAll(WHITESPACE_PATTERN,&quot;&quot;); if (!adjusted.matches(INPUT_VALIDATION_PATTERN)) { throw new IllegalArgumentException( &quot;invalid dice input pattern: &quot;+adjusted+&quot; - does not match &quot;+INPUT_VALIDATION_PATTERN); } String[] parts = input.split(ADDITION_SEPARATOR_PATTERN); if(parts[0].matches(SINGLE_DIE_PATTERN)){ String dicePart = parts[0]; int dIndex = dicePart.indexOf(DIE_SEPARATOR_PATTERN); if(dIndex == 0){ amount = 1; }else{ amount = Integer.parseInt(dicePart.substring(0,dIndex)); } sides = Integer.parseInt(dicePart.substring(dIndex+1)); }else{ amount = 0; sides = 0; } if(parts[0].matches(ADD_PATTERN)){ addition = Integer.parseInt(parts[0]); }else if(parts.length == 2 &amp;&amp; parts[1].matches(ADD_PATTERN)){ addition = Integer.parseInt(parts[1]); }else{ addition = 0; } } public int result(long seed){ Random random = new Random(seed); int result = 0; for(int roll = 0; roll &lt; amount; roll++){ result = result + random.nextInt(sides)+1; } result = result + addition; return result; } public int result(){ return result(0); } public int min(){ return amount + addition; } public int max(){ return amount * sides + addition; } } </code></pre> <p><strong>Test Case DieTest</strong><br></p> <pre><code>public class DieTest { @Test public void singleDieTest(){ Die d6 = new Die(&quot;D6&quot;); Assert.assertEquals(6, d6.sides); Assert.assertEquals(1, d6.amount); Assert.assertEquals(0,d6.addition); Assert.assertEquals(1,d6.min()); Assert.assertEquals(6,d6.max()); Die oneD6 = new Die(&quot;1D6&quot;); Assert.assertEquals(6, oneD6.sides); Assert.assertEquals(1, oneD6.amount); Assert.assertEquals(0,oneD6.addition); Assert.assertEquals(1,oneD6.min()); Assert.assertEquals(6,oneD6.max()); Die twoD6 = new Die(&quot;2D6&quot;); Assert.assertEquals(6, twoD6.sides); Assert.assertEquals(2, twoD6.amount); Assert.assertEquals(0,twoD6.addition); Assert.assertEquals(2,twoD6.min()); Assert.assertEquals(12,twoD6.max()); Die twentyD6 = new Die(&quot;20D6&quot;); Assert.assertEquals(6, twentyD6.sides); Assert.assertEquals(20, twentyD6.amount); Assert.assertEquals(0,twentyD6.addition); Assert.assertEquals(20,twentyD6.min()); Assert.assertEquals(120,twentyD6.max()); Die twentyD60 = new Die(&quot;20D60&quot;); Assert.assertEquals(60, twentyD60.sides); Assert.assertEquals(20, twentyD60.amount); Assert.assertEquals(0,twentyD60.addition); Assert.assertEquals(20,twentyD60.min()); Assert.assertEquals(1200,twentyD60.max()); } @Test public void dieWithSingleAdditionTest(){ Die d6 = new Die(&quot;D6+1&quot;); Assert.assertEquals(6, d6.sides); Assert.assertEquals(1, d6.amount); Assert.assertEquals(1,d6.addition); Assert.assertEquals(2,d6.min()); Assert.assertEquals(7,d6.max()); Die oneD6 = new Die(&quot;1D6+1&quot;); Assert.assertEquals(6, oneD6.sides); Assert.assertEquals(1, oneD6.amount); Assert.assertEquals(1,oneD6.addition); Assert.assertEquals(2,oneD6.min()); Assert.assertEquals(7,oneD6.max()); Die twoD6 = new Die(&quot;2D6+1&quot;); Assert.assertEquals(6, twoD6.sides); Assert.assertEquals(2, twoD6.amount); Assert.assertEquals(1,twoD6.addition); Assert.assertEquals(3,twoD6.min()); Assert.assertEquals(13,twoD6.max()); Die twentyD6 = new Die(&quot;20D6+1&quot;); Assert.assertEquals(6, twentyD6.sides); Assert.assertEquals(20, twentyD6.amount); Assert.assertEquals(1,twentyD6.addition); Assert.assertEquals(21,twentyD6.min()); Assert.assertEquals(121,twentyD6.max()); Die twentyD60 = new Die(&quot;20D60+1&quot;); Assert.assertEquals(60, twentyD60.sides); Assert.assertEquals(20, twentyD60.amount); Assert.assertEquals(1,twentyD60.addition); Assert.assertEquals(21,twentyD60.min()); Assert.assertEquals(1201,twentyD60.max()); } @Test public void dieWithTwoDigitAdditionTest(){ Die d6 = new Die(&quot;D6+13&quot;); Assert.assertEquals(6, d6.sides); Assert.assertEquals(1, d6.amount); Assert.assertEquals(13,d6.addition); Assert.assertEquals(14,d6.min()); Assert.assertEquals(19,d6.max()); Die oneD6 = new Die(&quot;1D6+13&quot;); Assert.assertEquals(6, oneD6.sides); Assert.assertEquals(1, oneD6.amount); Assert.assertEquals(13,oneD6.addition); Assert.assertEquals(14,oneD6.min()); Assert.assertEquals(19,oneD6.max()); Die twoD6 = new Die(&quot;2D6+13&quot;); Assert.assertEquals(6, twoD6.sides); Assert.assertEquals(2, twoD6.amount); Assert.assertEquals(13,twoD6.addition); Assert.assertEquals(15,twoD6.min()); Assert.assertEquals(25,twoD6.max()); Die twentyD6 = new Die(&quot;20D6+13&quot;); Assert.assertEquals(6, twentyD6.sides); Assert.assertEquals(20, twentyD6.amount); Assert.assertEquals(13,twentyD6.addition); Assert.assertEquals(33,twentyD6.min()); Assert.assertEquals(133,twentyD6.max()); Die twentyD60 = new Die(&quot;20D60+13&quot;); Assert.assertEquals(60, twentyD60.sides); Assert.assertEquals(20, twentyD60.amount); Assert.assertEquals(13,twentyD60.addition); Assert.assertEquals(33,twentyD60.min()); Assert.assertEquals(1213,twentyD60.max()); } @Test public void rangeTest(){ Die twoD6plus1 = new Die(&quot;2D6+1&quot;); for (int i = 0; i &lt; 100; i++){ Assert.assertTrue(twoD6plus1.result() &gt;= twoD6plus1.min() ); Assert.assertTrue(twoD6plus1.result() &lt;= twoD6plus1.max() ); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T08:25:28.083", "Id": "532128", "Score": "6", "body": "IMO not good enough for an answer, so I'll put in in a comment: I plugged your `INPUT_VALIDATION_PATTERN` into [regex101](https://regex101.com/) and found that it matches `\"D\"`. This causes a crash when trying to parse the `sides`. Are you sure that you need this amount of regex (or regex at all, for that matter)? It looks very overengineered." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T08:39:14.417", "Id": "532132", "Score": "0", "body": "@mindoverflow it is overengineered, it startet easy with one simply Die expression `2D6+1`... but then my code grew and grew... and now its a totally overengineered monster :-(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T09:30:13.917", "Id": "532138", "Score": "2", "body": "@mindoverflow, you say that's not enough for an answer, but I'd argue that even a very short answer is valuable if it identifies a bug in the code. Please write that in the answer box, and claim an upvote from me!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T09:47:37.853", "Id": "532142", "Score": "3", "body": "You state 0 must be set explicitly, but how exactly does one roll a 0D6? Wouldn't this result in stripping out the roll entirely, looking only at the +a modifier if applicable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T09:52:12.347", "Id": "532143", "Score": "0", "body": "i´m not sure how to handle constants... so this is more a hack than good programming... that looks like a big code smell, that should be handled in a proper way (good point for improvement)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T17:40:57.890", "Id": "532189", "Score": "2", "body": "If I was using a regular expression in Perl, I'd just capture the different parts. Why do you have multiple calls to different \"split\"? Just grab three captures if successful match. Off hand, `my ($n,$s,$a)=/(\\d+)D(\\d+)(?:\\+(\\d+))/`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T04:04:51.000", "Id": "532226", "Score": "1", "body": "Could you rename Die to Dice even if it's grammatically incorrect? I have a feeling that some people reviewing your code might see it as the code is telling them to die." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T05:42:14.037", "Id": "532228", "Score": "0", "body": "*yes, yes - that was my purpose: DIE!!* hahaha i'm really sorry for choosing this poor name - i looked that word up in [Leo](https://dict.leo.org/german-english/w%C3%BCrfel)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T05:43:28.087", "Id": "532229", "Score": "0", "body": "@JDługosz i think here is something definitly wrong, the `String`handling is done poorly - thats why i guess i'll accept the answer with this issue..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T12:02:20.717", "Id": "532255", "Score": "1", "body": "Note that 5d6-2 is also a valid die roll, which you don't account for. 0d5 is not. 5d0 is not. You should validate those after you apply the regex." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T12:50:24.097", "Id": "532261", "Score": "0", "body": "@EricStein this part of the regex is responsible check for a plus sign `\\+`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T12:51:43.940", "Id": "532262", "Score": "0", "body": "@EricStein the addition is always positiv - while it might me a logic die it is not a use case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T13:57:42.840", "Id": "532270", "Score": "4", "body": "My Strength and Dexterity are 8. I hit with a dagger. I roll 1d4-1 damage. This is not a use case for a DnD dice roller?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T20:37:33.403", "Id": "532306", "Score": "1", "body": "@CausingUnderflowsEverywhere personally I'd love to see a \"Die\" class in such a setting, something to chuckle about. So which is perferable on the meta level...depends on the audience ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T16:10:11.343", "Id": "532485", "Score": "0", "body": "You know, it is easily generalized: Separate on `+`, treat each token as Dice (`\\d*D\\d*`) or adjustment (`\\d*`). Parse into array, sort, simplify by merging, return." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T15:53:40.453", "Id": "532564", "Score": "0", "body": "For what it's worth, I deleted my original answer, since it contained factual errors, and wrote a new one." } ]
[ { "body": "<h3>Bug in the validation pattern</h3>\n<p>The <code>INPUT_VALIDATION_PATTERN</code> doesn't work correctly, as it matches the invalid input <code>&quot;D&quot;</code>. This is due to the pattern looking for any number of digits (<code>*</code>) after the <code>D</code>. Changing the pattern to look for at least one occurrence (<code>+</code>) seems to fix this.</p>\n<h3>Simple solution using capture groups</h3>\n<p>After some fiddling around with your pattern I found that regex can be used to solve this rather nicely, using <code>^(\\d+)?(D\\d+)(\\+\\d+)?$</code>.</p>\n<pre><code>String pattern = &quot;^(\\\\d+)?(D\\\\d+)(\\\\+\\\\d+)?$&quot;;\nPattern r = Pattern.compile(pattern);\nMatcher m = r.matcher(in);\n\nif (m.find()) {\n ...\n}\n</code></pre>\n<p>If the input matches, <code>m.find()</code> returns true. You then use <code>m.group(x)</code> to access the capture results, with <code>m.group(1)</code> being the number of dice, <code>m.group(2)</code> being the number of sides and <code>m.group(3)</code> being the addition. If there is no number for multiple dice/addition, then the groups 1/3 return <code>null</code>, which can easily be tested for. Do note that the strings in group 2 and 3 start with <code>D</code> and <code>+</code> respectively due to how the groups are set up. How the full constructor would look is left as an exercise for the reader :)</p>\n<p>Explaination:</p>\n<pre><code>^(\\d+)?(D\\d+)(\\+\\d+)?$\n^ $ // start/end of string\n ( ) // capture group 1: capture\n ? // one or zero of\n \\d+ // at least one digit\n ( ) // capture group 2: capture\n D\\d+ // a &quot;D&quot; followed by at least one digit\n ( ) // capture group 3: capture\n ? // one or zero of\n \\+\\d+ // a &quot;+&quot; followed by at least one digit\n</code></pre>\n<p>I'm no expert on regex, so please test this thoroughly. I've thrown your tests, some edge cases and random things at this regex and it worked, but you can't be too careful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T12:22:24.787", "Id": "532148", "Score": "0", "body": "Simple solution using capture groups - wonderful... [using the superpowers of regex](https://xkcd.com/208/)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T12:42:13.257", "Id": "532150", "Score": "3", "body": "With regex, it's either that or [this](https://xkcd.com/1171/)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T13:20:13.473", "Id": "532159", "Score": "0", "body": "hahahahaa - now you have 100 =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T17:42:10.813", "Id": "532190", "Score": "0", "body": "Can you use an \"extended\" modifier like in Perl, so the _Explaination_ can be the actual code instead of having to be given separately?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T18:11:03.243", "Id": "532200", "Score": "0", "body": "@JDługosz Yes, you can add `(?x)` at the start, and change the comments to start with `#` instead of `//`. This is the same as the `x` modifier in PCRE." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T08:41:23.837", "Id": "532237", "Score": "4", "body": "I'd probably change the regex to `^(\\d*)D(\\d+)(?:\\+(\\d+))?$` so it's easier to use capture groups 1, 2 and 3 for number of dice, sides, and additional amount without having to deal with pesky unnecessary letters. I've changed the first capture group to use `*` instead of `+)?` and made the third one non-capturing (`(?: ... )`) so the `+` is not captured." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T08:19:29.530", "Id": "532532", "Score": "0", "body": "since there are so many feedbacks on my code i cannot accept one answer as the right one - as said before you helped me to improve my code strongly - and therefore i am grateful for your answer..." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T12:11:34.993", "Id": "269693", "ParentId": "269687", "Score": "12" } }, { "body": "<p>We don't know how your <code>Die</code> fits into the game as a whole, but the way you're rolling your results seems counter-intuitive to me. I'd expect to be able to call <code>result</code> and get a unique value each time. However, if I roll 5D6+2, I'll always get the same answer (22 on my system), because it's always creating a <code>new Random</code> with a known seed (0). Consider moving <code>Random</code> outside of the <code>result </code> method, or having a different value for the default seed (such as something time-based), or separating the rolling responsibility out into a different class entirely.</p>\n<blockquote>\n<pre><code>public int result(long seed){\n Random random = new Random(seed);\n int result = 0;\n for(int roll = 0; roll &lt; amount; roll++){\n result = result + random.nextInt(sides)+1;\n }\n result = result + addition;\n return result;\n}\n\npublic int result(){\n return result(0);\n}\n</code></pre>\n</blockquote>\n<p>As a side note... should your class be called <code>Dice</code>? It seems to represent more than one Die? <code>amount</code> could then perhaps be <code>numberOfDie</code>..</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T13:17:42.373", "Id": "532157", "Score": "0", "body": "i tested so much and i still didn't see that one :-(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T13:19:21.340", "Id": "532158", "Score": "0", "body": "about Die/Dice - i'm no native english, these language obstacles are high for me ^^ Do you name classes in Plural if they can be both (`class Person(s){}`)? iam really stuck herre ^^ thanks for point that out, too.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T15:31:24.530", "Id": "532170", "Score": "0", "body": "@MartinFrank If I expect a class to support multiple instances of something then yes, I'd usually name it plural, in the same way that I would name a variable that was a collection, or have a `People` table in a database, where each row represented a `Person`. A `Dice` class could be implemented as a collection of `Die`, or using the sides/amount combination you're using, this is largely an implementation detail from the clients perspective. But maybe consider what you would do if you wanted to be able to handle `5D6+1D4` (I don't know how likely that is)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T11:07:41.813", "Id": "532249", "Score": "0", "body": "@forsvarir - I don't know how much things have changed since I was a young man, but in the structured analysis and design principles of my day, all objects (and database tables) were named in the singular, e.g. Person, Client, Company, Die. This was because at the most fundamental level, each object or record should be about one thing, and you named it after that thing. You may have instantiated multiple Person objects or have many Person records on the table, but each item represents only one. If you denormalized a table, for example, so that it had five people on each record, it would..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T11:08:16.910", "Id": "532250", "Score": "0", "body": "...be called Person Group or some such thing, depending on its purpose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T12:54:19.283", "Id": "532263", "Score": "0", "body": "@Spratty As with most things naming, it's somewhat subjective and consistency within the codebase you're working is the primary concern. Stackoverflow generally comes down on the side of singular naming for tables https://stackoverflow.com/q/338156/592182 but Ruby on Rails by default takes the opposite approach mapping singular class names to pluralised table names https://guides.rubyonrails.org/v5.0/active_record_basics.html#naming-conventions" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T14:32:15.743", "Id": "532276", "Score": "0", "body": "@forsvarir - I can see why that would make sense (and I instinctively agree with the RoR approach); thinking about it, it must have been thirty years since I took that course and I'm glad nothing's set in stone for that long. When it comes to my own database and object designs, though, I'm afraid I'm stuck firmly in the past - when you get old it's enough bother to learn new languages and frameworks without having to change all the stuff you learned years ago :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T08:19:47.633", "Id": "532534", "Score": "0", "body": "since there are so many feedbacks on my code i cannot accept one answer as the right one - as said before you helped me to improve my code strongly - and therefore i am grateful for your answer..." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T12:45:20.730", "Id": "269695", "ParentId": "269687", "Score": "9" } }, { "body": "<p>You can use <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#groupname\" rel=\"noreferrer\">named groups</a> in the pattern, as well, which will make the code less brittle to pattern changes. (Example: If you want to add in the feature of multiplication in the future then you could have, e.g., <code>3d6x2+1</code> meaning that the addition part would be the 4th matching group instead of the 3rd, and if you refer to groups by order you would have to update the addition part of your code. If you refer to groups by name, then the addition group is still the addition group regardless of where it moves to, so you would only have to touch the <em>new</em> code.) It can also make counting groups in general a lot easier.</p>\n<pre><code>String diceNotation = &quot;(?&lt;amount&gt;\\\\d+)?D(?&lt;faces&gt;\\\\d+)(\\\\+(?&lt;addition&gt;\\\\d))?&quot;;\nPattern dicePattern = Pattern.compile(diceNotation, Pattern.CASE_INSENSITIVE);\nMatcher diceMatcher = dicePattern.matcher(input);\n\nint amount = diceMatcher.group(&quot;amount&quot;) != null ? \n Integer.parseInt(diceMatcher.group(&quot;amount&quot;)) :\n 1;\nint faces = Integer.parseInt(diceMatcher.group(&quot;faces&quot;));\nint add = diceMatcher.group(&quot;add&quot;) != null ?\n Integer.parseInt(diceMatcher.group(&quot;add&quot;)) :\n 0;\n</code></pre>\n<p>Note that <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#group%28java.lang.String%29\" rel=\"noreferrer\"><code>Matcher.group</code></a> is returning null when a pattern doesn't match at all. There are some subtleties of regex here, such as <code>(?&lt;foo&gt;a*)</code> will match an empty string and return an empty string as the foo group, but <code>(?&lt;foo&gt;a+)?</code> will match an empty string with the whole pattern but return null as the foo group.</p>\n<p>Also, I have taken the liberty of including case_insensitive, because <code>3d6</code> is just as good as <code>3D6</code>. You could also liberally sprinkle <code>\\s*</code> between each group in order to allow arbitrary white space, so that <code>3 d 6 = 3d 6 = 3d6 = etc...</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T08:20:09.777", "Id": "532535", "Score": "0", "body": "since there are so many feedbacks on my code i cannot accept one answer as the right one - as said before you helped me to improve my code strongly - and therefore i am grateful for your answer..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T18:25:41.630", "Id": "269710", "ParentId": "269687", "Score": "6" } }, { "body": "<p>As others have mentioned, there is a bug in the pattern - see their answers for assistance on fixing it ;)</p>\n<p>Apart from this, I'd like to remind you to refactor your tests as well. The repeated pattern in the tests, along with the relatively large amount of boilerplate, make it hard to distinguish if there are any cases you have missed or if there are duplicates.</p>\n<p>There are solutions out there for helping to write tests that focus on what you are actually trying to test, instead of writing pages full of asserts. For instance, <a href=\"https://www.baeldung.com/parameterized-tests-junit-5\" rel=\"nofollow noreferrer\">https://www.baeldung.com/parameterized-tests-junit-5</a> :</p>\n<pre><code>private static Stream&lt;Arguments&gt; shouldParseDice() {\n return Stream.of(\n Arguments.of(&quot;D6&quot;, 1, 6, 0, 1, 6),\n Arguments.of(&quot;1D6&quot;, 1, 6, 0, 1, 6),\n Arguments.of(&quot;2D6&quot;, 2, 6, 0, 2, 12),\n Arguments.of(&quot;2D6+1&quot;, 2, 6, 1, 3, 13),\n// ...\n Arguments.of(&quot;30D11+40&quot;, 30, 11, 40, 70, 370)\n );\n}\n\n@ParameterizedTest\n@MethodSource \nvoid shouldParseDice(\n String input, \n Integer amount,\n Integer sides,\n Integer addition,\n Integer min,\n Integer max) {\n Die die = new Die(input);\n Assertions.assertEquals(amount, die.amount);\n Assertions.assertEquals(sides, die.sides);\n Assertions.assertEquals(addition, die.addition);\n Assertions.assertEquals(min, die.min());\n Assertions.assertEquals(max, die.max());\n}\n\nprivate static Stream&lt;String&gt; shouldFailDieParsing() {\n return Stream.of(&quot;D&quot;, &quot;G&quot;, &quot;2D6-4&quot;, &quot;&quot;, null, &quot;-23D-2&quot;, &quot;-2D1&quot;);\n}\n\n@ParameterizedTest\n@MethodSource \nvoid shouldFailDieParsing(String input) {\n \n Assertions.assertThrows&lt;IllegalArgumentException&gt;(() =&gt; new Die(input));\n}\n\n</code></pre>\n<p>If, for whatever reason, you are unable to make the move to junit5, you could simply roll your own in junit4, though it is slightly less tool supported and need some more explicit details to be able to easily understand the output when it fails:</p>\n<pre><code>@Test\npublic void shouldParseDice() {\n validateDieParsing(&quot;D6&quot;, 1, 6, 0, 1, 6);\n validateDieParsing(&quot;1D6&quot;, 1, 6, 0, 1, 6);\n validateDieParsing(&quot;2D6&quot;, 2, 6, 0, 2, 12);\n validateDieParsing(&quot;2D6+1&quot;, 2, 6, 1, 3, 13);\n// ...\n validateDieParsing(&quot;30D11+40&quot;, 30, 11, 40, 70, 370);\n}\n\nprivate void validateDieParsing(\n String input, \n Integer amount,\n Integer sides,\n Integer addition,\n Integer min,\n Integer max) {\n Die die = new Die(input);\n String message = &quot;input was: &quot; + input;\n Assert.assertEquals(message, amount, die.amount);\n Assert.assertEquals(message, sides, die.sides);\n Assert.assertEquals(message, addition, die.addition);\n Assert.assertEquals(message, min, die.min());\n Assert.assertEquals(message, max, die.max());\n}\n\n@Test\npublic void shouldFailDieParsing() {\n return Stream.of(&quot;D&quot;, &quot;G&quot;, &quot;2D6-4&quot;, &quot;&quot;, null, &quot;-23D-2&quot;, &quot;-2D1&quot;)\n .forEach(it -&gt; shouldFailDieParsing(it));\n}\n\nprivate void shouldFailDieParsing(String input) {\n try {\n new Die(input);\n fail(&quot;did not throw exception on expected bad input = &quot; + input); \n } catch (IllegalArgumentException e) {\n // expected, ignore\n } catch (Exception e) {\n e.printStackTrace():\n fail(&quot;Caught unexpected exception for input = &quot; + input);\n }\n}\n\n</code></pre>\n<p>Transforming your tests to a format where you can easily see which cases you have covered, makes it easier to write good tests. In this case, you may have discovered the &quot;D&quot; input giving you trouble early on.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T17:00:23.437", "Id": "532489", "Score": "0", "body": "thank you for pointing that out - this is indeed a good piece of advice, these test are not easy to read. (I'm glad i addem them, so here is a big chance for learning for me)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T08:20:19.067", "Id": "532536", "Score": "0", "body": "since there are so many feedbacks on my code i cannot accept one answer as the right one - as said before you helped me to improve my code strongly - and therefore i am grateful for your answer..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T11:44:50.790", "Id": "269765", "ParentId": "269687", "Score": "4" } }, { "body": "<p>From the design standpoint it seems you are mixing two things - abstraction of a die (that has certain properties like number of faces) and has some behavior associated with it (as it can be rolled for certain number to be a result) AND parsing (even though you call it differently see: <a href=\"https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/\" rel=\"nofollow noreferrer\">https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/</a>) seemingly arbitrary string.</p>\n<p>I don't know application of this class - which, imho, should be major driver the design of a class, but you might consider separating those two - especially if creating dice set from a raw string is somehow accidental (so if you ever have a need to roll dice but can do it without parsing strings - my guess would be for something like standard monsters having specific attack dices).</p>\n<p>Given bugs in parsing pointed out in other comments - you should probably consider if another implementation approach would allow you to avoid them by its nature. One of the problem sources was use of regex in parsing (I am not great fan of it in general) - are you sure you need regex (or in that amount)? Maybe you can just <code>&quot;text&quot;.indexOf(&quot;D&quot;)</code> and split the string by your local grammar in parts - writing simple parsers is really not that hard.\nThere is also another issue with regexes - if your class is anytime to parse <strong>untrusted input</strong> in current form it could be relatively easy to it make it use a lot of resources (see e.g. <a href=\"https://s0md3v.medium.com/exploiting-regular-expressions-2192dbbd6936\" rel=\"nofollow noreferrer\">https://s0md3v.medium.com/exploiting-regular-expressions-2192dbbd6936</a>) - although it could be simply circumvented by introducing some input length limit.</p>\n<p>Another thing how you test randomness of dices (and how it didn't catch the bug with <code>new Random(0)</code>) - notice that you have two methods for <code>result</code> in dice and only one of them is used in tests (the other seems unused but I guess that it might used somewhere else), usually this situation is a manifestation of a design flaw and it is a way for tests to tell us something valuable (pay attention to those) - here it is a way of saying that randomness seed is an external dependency and it is important enough to be identified and treated with respect.<br />\nUsually extracting seed and passing it as a dependency (in whatever way you manage them) is enough to write deterministic tests that check <em>actual results</em> in such case.\nI'll repeat it because it is so important: <strong>test for results that you care about, not what is easy to test at the moment</strong> (like testing that d4 roll can result in 1,2,3,4 values and not that result is between min and max - with the right seed you shouldn't need hundreds of attempts) and <strong>don't hesitate to change the design so that it is easy to test</strong>.</p>\n<p>These are my main points, some related ideas that sparked in my head when seeing this code:</p>\n<ul>\n<li>die vs dice looks like a nice place for <code>composite</code> pattern (I wouldn't force it, simple is better than using arbitrary pattern - but if needed it this design could be <em>leaned into</em>)</li>\n<li>if you wanted you could test <em>distribution</em> of results (a little over the top, I am aware, but if it was part of some safety critical software... then don't use dices :D)</li>\n<li>you could use <a href=\"https://github.com/VerbalExpressions/JavaVerbalExpressions\" rel=\"nofollow noreferrer\">https://github.com/VerbalExpressions/JavaVerbalExpressions</a> (I don't think any use of regex is small enough, to not use it but its only my personal opinion) but better not use it at all</li>\n<li>Seeing <a href=\"https://codereview.stackexchange.com/a/269713\">Greg Burghardt comment</a> I, personally don't fully agree with constructors doing work being a bad thing (it surely <strong>can</strong> be bad) - I think that static parsing/validation (checking invariants) can be placed in constructor as a way to strengthen compile-time(ish) type safety and (again IMO) the root problem here is (mentioned at the beginning) mixture of ideas of parsing and rollable dice</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T17:02:20.087", "Id": "532490", "Score": "0", "body": "ohhh sepertion of concerns, single responsibility... even though my code is sooo small, still something to take care of!! thank you bringing this isssue out, i didn't see this coming!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T08:20:28.113", "Id": "532537", "Score": "0", "body": "since there are so many feedbacks on my code i cannot accept one answer as the right one - as said before you helped me to improve my code strongly - and therefore i am grateful for your answer..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T12:11:48.620", "Id": "269768", "ParentId": "269687", "Score": "3" } }, { "body": "<h2>About the difference between Perl and Java</h2>\n<p>If this class will be used a lot, there are a couple other things you should probably do:</p>\n<ol>\n<li>Compile the patterns. Don't use the convenience methods in <code>String</code>. Use <code>java.util.regex.Pattern</code> explicitly and cache it in a static. Thus:\n<pre class=\"lang-java prettyprint-override\"><code>private final static Pattern INPUT_VALIDATION_PATTERN = Pattern.compile(....); \n</code></pre>\n(This was shown in @mindoverflow's answer, as it is also what is needed to use groups.)\nThe real point here is that pattern compiling is costly, so you should only do it once, if you can.\nPerl will do this automatically if the pattern is a constant, and has a flag to force it if the pattern is variable.\nIn Java, one does this oneself.</li>\n<li>Java's regular expression support is actually more complete than Perl's. It has <code>matches()</code> (and you are using it).\nThus, your pattern doesn't need a leading <code>^</code> and trailing <code>$</code>, as these are implied by the function.\nNote that <code>matches()</code> will generally be <em>faster</em> than <code>find()</code>, as the later tends to do some costly optimizations to speed up the search.</li>\n</ol>\n<p>(Other people have addressed the general pattern changes, so I won't.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T17:07:00.673", "Id": "532491", "Score": "0", "body": "there are so many aspects of Regex that someone can mess up. Your answer is very helpful, am glad that you brought it up. This is definitly a point that i have to watch out for, for my next projects. Thank you very much!!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T08:20:43.957", "Id": "532538", "Score": "0", "body": "since there are so many feedbacks on my code i cannot accept one answer as the right one - as said before you helped me to improve my code strongly - and therefore i am grateful for your answer..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T13:42:06.880", "Id": "532549", "Score": "0", "body": "@MartinFrank Agreed. Further, the use of capture groups instead of multiple tests is **more** important. I just felt the final optimizations should also be pointed out." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T13:43:07.207", "Id": "269816", "ParentId": "269687", "Score": "1" } }, { "body": "<p>I had answered the question, but my previous answer contained some factual errors. Thanks to <a href=\"https://codereview.stackexchange.com/users/22778/chepner\">chepner</a>, <a href=\"https://codereview.stackexchange.com/users/62058/eric-stein\">Eric Stein</a> and <a href=\"https://codereview.stackexchange.com/users/84364/jd%c5%82ugosz\">JDługosz</a> for the corrections, and additional info about <a href=\"https://star-wars-rpg-ffg.fandom.com/wiki/Narrative_Dice\" rel=\"nofollow noreferrer\">Narrative Dice</a> which have symbols on the die faces instead of numbers.</p>\n<hr />\n<p>You have plenty of answers about regular expressions. Instead, I will focus on the overall object oriented design.</p>\n<p>The word &quot;Die&quot; is the singular form of &quot;Dice&quot;. It was surprising to me that a &quot;Die&quot; object represented more than one item. Consider separating the concepts of a &quot;die&quot; from the algorithm used to determine a dice roll, and the result of that roll. This implies two separate classes: <code>DiceRollGenerator</code> and <code>DiceRoll</code>. For the purposes of this question I will assume all die face values are integers, but you could use Generic Types in Java on the <code>DiceRollGenerator</code> class to support additional die face types.</p>\n<p>The current Die constructor is responsible for parsing the dice roll format, which means the constructor is doing real work. <a href=\"http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/\" rel=\"nofollow noreferrer\">Constructors should not do real work</a>. Instead, the constructor should do little more than set values on fields. In the case of the DiceRollGenerator, this would be the number of dice, the number of faces for each die, and the additional amount added to each dice roll.</p>\n<pre><code>int numberOfDice = 4;\nint sides = 6;\nint amount = 2;\nDiceRollGenerator generator = new DiceRollGenerator(numberOfDice, sides, amount);\n</code></pre>\n<p>Still, it is desirable to parse a well-known dice format string. Parsing logic is error-prone. When parsing, both the parser and the caller should expect errors. This is not ideal for a constructor. Parsing logic should be moved into a static method on the class with the most knowledge about how to generate a dice roll: the <code>DiceRollGenerator</code>.</p>\n<pre><code>DiceRollGenerator generator = DiceRollGenerator.parse(&quot;4D6+2&quot;);\n</code></pre>\n<p>The <code>parse</code> method should throw exceptions given invalid input. The constructor, with its simpler input, has fewer reasons to throw an exception, making the constructor easier to call. The <code>parse</code> method is inherently harder to call due to the myriad reasons for it to fail. This allows callers to choose which technique fits best for the use case.</p>\n<p>You can eliminate the clutter of exception handling by having the <code>parse</code> method return an <code>Optional&lt;DiceRollGenerator&gt;</code> object instead of throwing exceptions when given invalid input. Just be sure to document what it means when an empty <code>Optional&lt;DiceRollGenerator&gt;</code> is returned using JavaDoc comments. An empty &quot;optional&quot; implies the dice roll format was incorrect.</p>\n<p>Creating the first dice roll would be a simple call to <code>generator.rollDice()</code>. This method would generate a random number as the seed for the dice roll. It would return a <code>DiceRoll</code> object.</p>\n<pre><code>DiceRoll roll = generator.rollDice();\n</code></pre>\n<p>The DiceRoll class should expose methods that allow you to interrogate the current state of the dice roll. This allows you to build additional game rules on top of the dice roll logic:</p>\n<pre><code>int firstDieValue = roll.getDieValue(0); // returns the value of the die object at index 0\nint total = roll.getTotal();\nboolean didDoubleSixesGetRolled = roll.hasDoubles(6);\n</code></pre>\n<p>Subsequent dice rolls also need a seed value. You can generate a new random number, or use an existing dice roll to generate the new seed:</p>\n<pre><code>roll = generator.rollDice(roll);\n</code></pre>\n<p>This could help simulate a real physical dice roll, since the player picks up the existing dice to roll them again. This, of course, is not necessary for a computer game, and simply generating a random roll each time could suffice.</p>\n<p>To summarize:</p>\n<ul>\n<li>Introduce a DiceRoll class to encapsulate the result of a dice roll.</li>\n<li>Rename the Die class to something more descriptive of what it does, like DiceRollGenerator</li>\n<li>Move parsing logic into a static method, which simplifies object construction in use cases where parsing the dice format is not necessary.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T15:34:05.397", "Id": "269851", "ParentId": "269687", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "16", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T07:54:11.037", "Id": "269687", "Score": "7", "Tags": [ "java", "object-oriented", "reinventing-the-wheel", "regex", "dice" ], "Title": "DnD Die in Java with regex" }
269687
<p>My task was to get the last 125 rows from an excel workbook.</p> <p>The rows are started from the 17th row and it goes until it can.</p> <p>Here's my code:</p> <pre><code>Sub Get_Data_From_File() Const START_ROW As Long = 17 Const NUM_ROWS As Long = 124 Dim FileToOpen As String Dim wb As Workbook, ws As Worksheet, wsDest As Worksheet Dim LastRow As Long, FirstRow As Long Dim LastRows As Range FileToOpen = Application.GetOpenFilename(&quot;Excel files (*.xls*), *.xls*&quot;, _ Title:=&quot;Válassza ki a fájlt!&quot;) If FileToOpen = &quot;False&quot; Then Exit Sub 'if a file is not selected close the window and stop the macro Set wsDest = ActiveSheet 'pasting here; or specfy some other sheet... anyway its working only with the active sheet Set wb = Workbooks.Open(FileToOpen, ReadOnly:=True) Set ws = wb.Worksheets(&quot;SMI_650_Lxy&quot;) 'or whatever sheet you need LastRow = ws.Cells(ws.Rows.Count, &quot;F&quot;).End(xlUp).Row 'find last row If LastRow &lt; START_ROW Then LastRow = START_ROW FirstRow = IIf(LastRow - NUM_ROWS &gt;= START_ROW, LastRow - NUM_ROWS, START_ROW) 'find first row Debug.Print &quot;FirstRow&quot; &amp; vbTab &amp; FirstRow 'test int the immediate windows Debug.Print &quot;LastRow&quot; &amp; vbTab &amp; LastRow Debug.Print &quot;START_ROW&quot; &amp; vbTab &amp; START_ROW 'copy ranges into the same cells ws.Range(&quot;C&quot; &amp; FirstRow &amp; &quot;:C&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;C&quot;) ws.Range(&quot;F&quot; &amp; FirstRow &amp; &quot;:F&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;F&quot;) ws.Range(&quot;M&quot; &amp; FirstRow &amp; &quot;:M&quot; &amp; LastRow).Copy 'Formula wsDest.Range(&quot;M17:M141&quot;).PasteSpecial Paste:=xlPasteValues ws.Range(&quot;P&quot; &amp; FirstRow &amp; &quot;:P&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;P&quot;) ws.Range(&quot;S&quot; &amp; FirstRow &amp; &quot;:S&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;S&quot;) ws.Range(&quot;V&quot; &amp; FirstRow &amp; &quot;:V&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;V&quot;) ws.Range(&quot;Y&quot; &amp; FirstRow &amp; &quot;:Y&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;Y&quot;) ws.Range(&quot;AF&quot; &amp; FirstRow &amp; &quot;:AF&quot; &amp; LastRow).Copy 'Formula wsDest.Range(&quot;AF17:AF141&quot;).PasteSpecial Paste:=xlPasteValues ws.Range(&quot;AM&quot; &amp; FirstRow &amp; &quot;:AM&quot; &amp; LastRow).Copy 'Formula wsDest.Range(&quot;AM17:AM141&quot;).PasteSpecial Paste:=xlPasteValues ws.Range(&quot;AP&quot; &amp; FirstRow &amp; &quot;:AP&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;AP&quot;) ws.Range(&quot;AS&quot; &amp; FirstRow &amp; &quot;:AS&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;AS&quot;) ws.Range(&quot;AV&quot; &amp; FirstRow &amp; &quot;:AV&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;AV&quot;) ws.Range(&quot;AY&quot; &amp; FirstRow &amp; &quot;:AY&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;AY&quot;) ws.Range(&quot;BB&quot; &amp; FirstRow &amp; &quot;:BB&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;BB&quot;) ws.Range(&quot;BE&quot; &amp; FirstRow &amp; &quot;:BE&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;BE&quot;) ws.Range(&quot;BL&quot; &amp; FirstRow &amp; &quot;:BL&quot; &amp; LastRow).Copy 'Formula wsDest.Range(&quot;BL17:BL141&quot;).PasteSpecial Paste:=xlPasteValues ws.Range(&quot;BS&quot; &amp; FirstRow &amp; &quot;:BS&quot; &amp; LastRow).Copy 'Formula wsDest.Range(&quot;BS17:BS141&quot;).PasteSpecial Paste:=xlPasteValues ws.Range(&quot;BV&quot; &amp; FirstRow &amp; &quot;:BV&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;BV&quot;) ws.Range(&quot;BZ&quot; &amp; FirstRow &amp; &quot;:BZ&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;BZ&quot;) ws.Range(&quot;CD&quot; &amp; FirstRow &amp; &quot;:CD&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;CD&quot;) ws.Range(&quot;CH&quot; &amp; FirstRow &amp; &quot;:CH&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;CH&quot;) ws.Range(&quot;CK&quot; &amp; FirstRow &amp; &quot;:CK&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;CK&quot;) ws.Range(&quot;CN&quot; &amp; FirstRow &amp; &quot;:CN&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;CN&quot;) ws.Range(&quot;CQ&quot; &amp; FirstRow &amp; &quot;:CQ&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;CQ&quot;) ws.Range(&quot;CT&quot; &amp; FirstRow &amp; &quot;:CT&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;CT&quot;) ws.Range(&quot;CW&quot; &amp; FirstRow &amp; &quot;:CW&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;CW&quot;) ws.Range(&quot;CZ&quot; &amp; FirstRow &amp; &quot;:CZ&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;CZ&quot;) ws.Range(&quot;DC&quot; &amp; FirstRow &amp; &quot;:DC&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;DC&quot;) ws.Range(&quot;DF&quot; &amp; FirstRow &amp; &quot;:DF&quot; &amp; LastRow).Copy wsDest.Cells(START_ROW, &quot;DF&quot;) wsDest.Range(&quot;17:141&quot;).Rows.Hidden = True 'Hide the row which is used for the data migration wb.Close False 'no save 'Add the Formulas (note you need the US-format when using .Formula ' or you can use your local format with .FormulaLocal ''insert the formula to calculate avarage Range(&quot;C5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(C17:C2025;HOL.VAN(MAX(C17:C2025);C17:C2025;1)):INDEX(C17:C2025;MAX(1;HOL.VAN(MAX(C17:C2025);C17:C2025;1)-124)))&quot; Range(&quot;F5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(F17:F2025;HOL.VAN(MAX(F17:F2025);F17:F2025;1)):INDEX(F17:F2025;MAX(1;HOL.VAN(MAX(F17:F2025);F17:F2025;1)-124)))&quot; Range(&quot;M5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(M17:M2025;HOL.VAN(MAX(M17:M2025);M17:M2025;1)):INDEX(M17:M2025;MAX(1;HOL.VAN(MAX(M17:M2025);M17:M2025;1)-124)))&quot; Range(&quot;P5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(P17:P2025;HOL.VAN(MAX(P17:P2025);P17:P2025;1)):INDEX(P17:P2025;MAX(1;HOL.VAN(MAX(P17:P2025);P17:P2025;1)-124)))&quot; Range(&quot;S5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(S17:S2025;HOL.VAN(MAX(S17:S2025);S17:S2025;1)):INDEX(S17:S2025;MAX(1;HOL.VAN(MAX(S17:S2025);S17:S2025;1)-124)))&quot; Range(&quot;V5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(V17:V2025;HOL.VAN(MAX(V17:V2025);V17:V2025;1)):INDEX(V17:V2025;MAX(1;HOL.VAN(MAX(V17:V2025);V17:V2025;1)-124)))&quot; Range(&quot;Y5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(Y17:Y2025;HOL.VAN(MAX(Y17:Y2025);Y17:Y2025;1)):INDEX(Y17:Y2025;MAX(1;HOL.VAN(MAX(Y17:Y2025);Y17:Y2025;1)-124)))&quot; Range(&quot;AF5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(AF17:AF2025;HOL.VAN(MAX(AF17:AF2025);AF17:AF2025;1)):INDEX(AF17:AF2025;MAX(1;HOL.VAN(MAX(AF17:AF2025);AF17:AF2025;1)-124)))&quot; Range(&quot;AM5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(AM17:AM2025;HOL.VAN(MAX(AM17:AM2025);AM17:AM2025;1)):INDEX(AM17:AM2025;MAX(1;HOL.VAN(MAX(AM17:AM2025);AM17:AM2025;1)-124)))&quot; Range(&quot;AP5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(AP17:AP2025;HOL.VAN(MAX(AP17:AP2025);AP17:AP2025;1)):INDEX(AP17:AP2025;MAX(1;HOL.VAN(MAX(AP17:AP2025);AP17:AP2025;1)-124)))&quot; Range(&quot;AS5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(AS17:AS2025;HOL.VAN(MAX(AS17:AS2025);AS17:AS2025;1)):INDEX(AS17:AS2025;MAX(1;HOL.VAN(MAX(AS17:AS2025);AS17:AS2025;1)-124)))&quot; Range(&quot;AV5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(AV17:AV2025;HOL.VAN(MAX(AV17:AV2025);AV17:AV2025;1)):INDEX(AV17:AV2025;MAX(1;HOL.VAN(MAX(AV17:AV2025);AV17:AV2025;1)-124)))&quot; Range(&quot;AY5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(AY17:AY2025;HOL.VAN(MAX(AY17:AY2025);AY17:AY2025;1)):INDEX(AY17:AY2025;MAX(1;HOL.VAN(MAX(AY17:AY2025);AY17:AY2025;1)-124)))&quot; Range(&quot;BB5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(BB17:BB2025;HOL.VAN(MAX(BB17:BB2025);BB17:BB2025;1)):INDEX(BB17:BB2025;MAX(1;HOL.VAN(MAX(BB17:BB2025);BB17:BB2025;1)-124)))&quot; Range(&quot;BE5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(BE17:BE2025;HOL.VAN(MAX(BE17:BE2025);BE17:BE2025;1)):INDEX(BE17:BE2025;MAX(1;HOL.VAN(MAX(BE17:BE2025);BE17:BE2025;1)-124)))&quot; Range(&quot;BL5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(BL17:BL2025;HOL.VAN(MAX(BL17:BL2025);BL17:BL2025;1)):INDEX(BL17:BL2025;MAX(1;HOL.VAN(MAX(BL17:BL2025);BL17:BL2025;1)-124)))&quot; Range(&quot;BS5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(BS17:BS2025;HOL.VAN(MAX(BS17:BS2025);BS17:BS2025;1)):INDEX(BS17:BS2025;MAX(1;HOL.VAN(MAX(BS17:BS2025);BS17:BS2025;1)-124)))&quot; Range(&quot;BV5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(BV17:BV2025;HOL.VAN(MAX(BV17:BV2025);BV17:BV2025;1)):INDEX(BV17:BV2025;MAX(1;HOL.VAN(MAX(BV17:BV2025);BV17:BV2025;1)-124)))&quot; Range(&quot;BZ5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(BZ17:BZ2025;HOL.VAN(MAX(BZ17:BZ2025);BZ17:BZ2025;1)):INDEX(BZ17:BZ2025;MAX(1;HOL.VAN(MAX(BZ17:BZ2025);BZ17:BZ2025;1)-124)))&quot; Range(&quot;CD5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(CD17:CD2025;HOL.VAN(MAX(CD17:CD2025);CD17:CD2025;1)):INDEX(CD17:CD2025;MAX(1;HOL.VAN(MAX(CD17:CD2025);CD17:CD2025;1)-124)))&quot; Range(&quot;CH5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(CH17:CH2025;HOL.VAN(MAX(CH17:CH2025);CH17:CH2025;1)):INDEX(CH17:CH2025;MAX(1;HOL.VAN(MAX(CH17:CH2025);CH17:CH2025;1)-24)))&quot; Range(&quot;CK5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(CK17:CK2025;HOL.VAN(MAX(CK17:CK2025);CK17:CK2025;1)):INDEX(CK17:CK2025;MAX(1;HOL.VAN(MAX(CK17:CK2025);CK17:CK2025;1)-24)))&quot; Range(&quot;CN5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(CN17:CN2025;HOL.VAN(MAX(CN17:CN2025);CN17:CN2025;1)):INDEX(CN17:CN2025;MAX(1;HOL.VAN(MAX(CN17:CN2025);CN17:CN2025;1)-24)))&quot; Range(&quot;CQ5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(CQ17:CQ2025;HOL.VAN(MAX(CQ17:CQ2025);CQ17:CQ2025;1)):INDEX(CQ17:CQ2025;MAX(1;HOL.VAN(MAX(CQ17:CQ2025);CQ17:CQ2025;1)-24)))&quot; Range(&quot;CT5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(CT17:CT2025;HOL.VAN(MAX(CT17:CT2025);CT17:CT2025;1)):INDEX(CT17:CT2025;MAX(1;HOL.VAN(MAX(CT17:CT2025);CT17:CT2025;1)-24)))&quot; Range(&quot;CW5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(CW17:CW2025;HOL.VAN(MAX(CW17:CW2025);CW17:CW2025;1)):INDEX(CW17:CW2025;MAX(1;HOL.VAN(MAX(CW17:CW2025);CW17:CW2025;1)-24)))&quot; Range(&quot;CZ5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(CZ17:CZ2025;HOL.VAN(MAX(CZ17:CZ2025);CZ17:CZ2025;1)):INDEX(CZ17:CZ2025;MAX(1;HOL.VAN(MAX(CZ17:CZ2025);CZ17:CZ2025;1)-24)))&quot; Range(&quot;DC5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(DC17:DC2025;HOL.VAN(MAX(DC17:DC2025);DC17:DC2025;1)):INDEX(DC17:DC2025;MAX(1;HOL.VAN(MAX(DC17:DC2025);DC17:DC2025;1)-24)))&quot; Range(&quot;DF5&quot;).FormulaLocal = &quot;=ÁTLAG(INDEX(DF17:DF2025;HOL.VAN(MAX(DF17:DF2025);DF17:DF2025;1)):INDEX(DF17:DF2025;MAX(1;HOL.VAN(MAX(DF17:DF2025);DF17:DF2025;1)-24)))&quot; 'insert the formula to calculate dispersion Range(&quot;C6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(C17:C2025;HOL.VAN(MAX(C17:C2025);C17:C2025;1)):INDEX(C17:C2025;MAX(1;HOL.VAN(MAX(C17:C2025);C17:C2025;1)-124)))&quot; Range(&quot;F6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(F17:F2025;HOL.VAN(MAX(F17:F2025);F17:F2025;1)):INDEX(F17:F2025;MAX(1;HOL.VAN(MAX(F17:F2025);F17:F2025;1)-124)))&quot; Range(&quot;M6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(M17:M2025;HOL.VAN(MAX(M17:M2025);M17:M2025;1)):INDEX(M17:M2025;MAX(1;HOL.VAN(MAX(M17:M2025);M17:M2025;1)-124)))&quot; Range(&quot;P6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(P17:P2025;HOL.VAN(MAX(P17:P2025);P17:P2025;1)):INDEX(P17:P2025;MAX(1;HOL.VAN(MAX(P17:P2025);P17:P2025;1)-124)))&quot; Range(&quot;S6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(S17:S2025;HOL.VAN(MAX(S17:S2025);S17:S2025;1)):INDEX(S17:S2025;MAX(1;HOL.VAN(MAX(S17:S2025);S17:S2025;1)-124)))&quot; Range(&quot;V6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(V17:V2025;HOL.VAN(MAX(V17:V2025);V17:V2025;1)):INDEX(V17:V2025;MAX(1;HOL.VAN(MAX(V17:V2025);V17:V2025;1)-124)))&quot; Range(&quot;Y6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(Y17:Y2025;HOL.VAN(MAX(Y17:Y2025);Y17:Y2025;1)):INDEX(Y17:Y2025;MAX(1;HOL.VAN(MAX(Y17:Y2025);Y17:Y2025;1)-124)))&quot; Range(&quot;AF6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(AF17:AF2025;HOL.VAN(MAX(AF17:AF2025);AF17:AF2025;1)):INDEX(AF17:AF2025;MAX(1;HOL.VAN(MAX(AF17:AF2025);AF17:AF2025;1)-124)))&quot; Range(&quot;AM6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(AM17:AM2025;HOL.VAN(MAX(AM17:AM2025);AM17:AM2025;1)):INDEX(AM17:AM2025;MAX(1;HOL.VAN(MAX(AM17:AM2025);AM17:AM2025;1)-124)))&quot; Range(&quot;AP6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(AP17:AP2025;HOL.VAN(MAX(AP17:AP2025);AP17:AP2025;1)):INDEX(AP17:AP2025;MAX(1;HOL.VAN(MAX(AP17:AP2025);AP17:AP2025;1)-124)))&quot; Range(&quot;AS6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(AS17:AS2025;HOL.VAN(MAX(AS17:AS2025);AS17:AS2025;1)):INDEX(AS17:AS2025;MAX(1;HOL.VAN(MAX(AS17:AS2025);AS17:AS2025;1)-124)))&quot; Range(&quot;AV6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(AV17:AV2025;HOL.VAN(MAX(AV17:AV2025);AV17:AV2025;1)):INDEX(AV17:AV2025;MAX(1;HOL.VAN(MAX(AV17:AV2025);AV17:AV2025;1)-124)))&quot; Range(&quot;AY6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(AY17:AY2025;HOL.VAN(MAX(AY17:AY2025);AY17:AY2025;1)):INDEX(AY17:AY2025;MAX(1;HOL.VAN(MAX(AY17:AY2025);AY17:AY2025;1)-124)))&quot; Range(&quot;BB6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(BB17:BB2025;HOL.VAN(MAX(BB17:BB2025);BB17:BB2025;1)):INDEX(BB17:BB2025;MAX(1;HOL.VAN(MAX(BB17:BB2025);BB17:BB2025;1)-124)))&quot; Range(&quot;BE6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(BE17:BE2025;HOL.VAN(MAX(BE17:BE2025);BE17:BE2025;1)):INDEX(BE17:BE2025;MAX(1;HOL.VAN(MAX(BE17:BE2025);BE17:BE2025;1)-124)))&quot; Range(&quot;BL6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(BL17:BL2025;HOL.VAN(MAX(BL17:BL2025);BL17:BL2025;1)):INDEX(BL17:BL2025;MAX(1;HOL.VAN(MAX(BL17:BL2025);BL17:BL2025;1)-124)))&quot; Range(&quot;BS6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(BS17:BS2025;HOL.VAN(MAX(BS17:BS2025);BS17:BS2025;1)):INDEX(BS17:BS2025;MAX(1;HOL.VAN(MAX(BS17:BS2025);BS17:BS2025;1)-124)))&quot; Range(&quot;BV6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(BV17:BV2025;HOL.VAN(MAX(BV17:BV2025);BV17:BV2025;1)):INDEX(BV17:BV2025;MAX(1;HOL.VAN(MAX(BV17:BV2025);BV17:BV2025;1)-124)))&quot; Range(&quot;BZ6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(BZ17:BZ2025;HOL.VAN(MAX(BZ17:BZ2025);BZ17:BZ2025;1)):INDEX(BZ17:BZ2025;MAX(1;HOL.VAN(MAX(BZ17:BZ2025);BZ17:BZ2025;1)-124)))&quot; Range(&quot;CD6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(CD17:CD2025;HOL.VAN(MAX(CD17:CD2025);CD17:CD2025;1)):INDEX(CD17:CD2025;MAX(1;HOL.VAN(MAX(CD17:CD2025);CD17:CD2025;1)-124)))&quot; Range(&quot;CH6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(CH17:CH2025;HOL.VAN(MAX(CH17:CH2025);CH17:CH2025;1)):INDEX(CH17:CH2025;MAX(1;HOL.VAN(MAX(CH17:CH2025);CH17:CH2025;1)-24)))&quot; Range(&quot;CK6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(CK17:CK2025;HOL.VAN(MAX(CK17:CK2025);CK17:CK2025;1)):INDEX(CK17:CK2025;MAX(1;HOL.VAN(MAX(CK17:CK2025);CK17:CK2025;1)-24)))&quot; Range(&quot;CN6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(CN17:CN2025;HOL.VAN(MAX(CN17:CN2025);CN17:CN2025;1)):INDEX(CN17:CN2025;MAX(1;HOL.VAN(MAX(CN17:CN2025);CN17:CN2025;1)-24)))&quot; Range(&quot;CQ6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(CQ17:CQ2025;HOL.VAN(MAX(CQ17:CQ2025);CQ17:CQ2025;1)):INDEX(CQ17:CQ2025;MAX(1;HOL.VAN(MAX(CQ17:CQ2025);CQ17:CQ2025;1)-24)))&quot; Range(&quot;CT6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(CT17:CT2025;HOL.VAN(MAX(CT17:CT2025);CT17:CT2025;1)):INDEX(CT17:CT2025;MAX(1;HOL.VAN(MAX(CT17:CT2025);CT17:CT2025;1)-24)))&quot; Range(&quot;CW6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(CW17:CW2025;HOL.VAN(MAX(CW17:CW2025);CW17:CW2025;1)):INDEX(CW17:CW2025;MAX(1;HOL.VAN(MAX(CW17:CW2025);CW17:CW2025;1)-24)))&quot; Range(&quot;CZ6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(CZ17:CZ2025;HOL.VAN(MAX(CZ17:CZ2025);CZ17:CZ2025;1)):INDEX(CZ17:CZ2025;MAX(1;HOL.VAN(MAX(CZ17:CZ2025);CZ17:CZ2025;1)-24)))&quot; Range(&quot;DC6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(DC17:DC2025;HOL.VAN(MAX(DC17:DC2025);DC17:DC2025;1)):INDEX(DC17:DC2025;MAX(1;HOL.VAN(MAX(DC17:DC2025);DC17:DC2025;1)-24)))&quot; Range(&quot;DF6&quot;).FormulaLocal = &quot;=SZÓRÁS(INDEX(DF17:DF2025;HOL.VAN(MAX(DF17:DF2025);DF17:DF2025;1)):INDEX(DF17:DF2025;MAX(1;HOL.VAN(MAX(DF17:DF2025);DF17:DF2025;1)-24)))&quot; 'to freeze the rows above the 17th row With ActiveWindow If .FreezePanes Then .FreezePanes = False .SplitRow = 16 .FreezePanes = True End With End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T10:37:35.390", "Id": "532145", "Score": "0", "body": "The formulas in English: \n\n\nSzórás: STDEV(INDEX(DF17:DF2025;MATCH(MAX(DF17:DF2025);DF17:DF2025;1)):INDEX(DF17:DF2025;MAX(1;MATCH(MAX(DF17:DF2025);DF17:DF2025;1)-24)))\"\n\n\nÁtlag: AVARAGE(INDEX(DF17:DF2025;MATCH(MAX(DF17:DF2025);DF17:DF2025;1)):INDEX(DF17:DF2025;MAX(1;MATCH(MAX(DF17:DF2025);DF17:DF2025;1)-24)))\"" } ]
[ { "body": "<p>I don't know if this will work for your particular project, but my first instinct would be to create some hidden rows with values like the following</p>\n<p><a href=\"https://i.stack.imgur.com/nipm9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nipm9.png\" alt=\"enter image description here\" /></a></p>\n<p>Row 1: Flags to specify if the value should be copied<br>\nRow 2: Flags to specify if the formula should be copied</p>\n<p>Rather than hardcoding which values and formulas should be copied, your script can read these rows and decide.</p>\n<p>The problem with your current solution is that if anyone adds or removes a column, then the whole script needs to be redone.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T10:04:34.533", "Id": "532243", "Score": "0", "body": "Wow, thanks that's a really good idea. I'm a beginner in vba but I try to implement it! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T12:09:40.720", "Id": "532256", "Score": "0", "body": "I stucked with it can you help me how can I make it? I needs to get the rows from the 17th rows under the formulas. I thinked about it before I started to code that to insert a statement for that I don't know how to begin. Maybe I could say that's the beta version of my code. :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T12:16:53.783", "Id": "532257", "Score": "0", "body": "No, sorry. Sometimes it’s easier to just start from scratch =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T12:17:37.150", "Id": "532258", "Score": "0", "body": "Okey, I find it out somehow than :D" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T21:57:32.743", "Id": "269717", "ParentId": "269690", "Score": "1" } }, { "body": "<p>Your question lacks clarity but going by your title the code below will transfer 125 rows from the bottom of the source sheet (less if there aren't as many rows) to a destination sheet.</p>\n<pre><code>Sub GetRows()\n ' 310\n \n Const StartRow As Long = 17\n Const NumRows As Long = 125 ' number of rows from the end\n \n Dim WbS As Workbook ' Source file\n Dim WsS As Worksheet ' Source sheet\n Dim RngS As Range ' Source range\n Dim Cs As Long ' Columns count in WsS\n Dim RsS As Long ' first source row\n Dim RlS As Long ' last source row in WsS\n Dim WbD As Workbook ' Destination file\n Dim WsD As Worksheet ' Destination sheet\n Dim Target As Range ' Destination cell\n\n Set WbS = ThisWorkbook ' use your existing code to open whatever workbook\n Set WsS = WbS.Worksheets(1) ' specify whichever in WsSsheet you want\n With WsS\n ' find the last used column in StartRow\n Cs = .Cells(StartRow, .Columns.Count).End(xlToLeft).Column\n ' find the last used row in column A\n RlS = .Cells(.Rows.Count, &quot;A&quot;).End(xlUp).Row\n RsS = WorksheetFunction.Max(RlS - NumRows + 1, StartRow)\n \n ' select the last max 125 rows starting from StartRow\n Set RngS = Range(.Cells(RsS, &quot;A&quot;), .Cells(RlS, Cs))\n Debug.Print RngS.Address(0, 0)\n End With\n \n Set WbD = ThisWorkbook ' specify whichever workbook you have open\n Set WsD = WbS.Worksheets(2) ' specify whichever sheet in WsD you want\n Set Target = WsD.Cells(1, 1) ' specify the first cell to copy the 125 rows to\n RngS.Copy Destination:=Target\nEnd Sub\n</code></pre>\n<p>In my code source workbook and target are the same. I think you can change the code using parts of what you already have. The point is that you define <strong>one</strong> range and copy/paste it.</p>\n<p>In this process formulas may change the addresses of cells they reference. That is because row numbers change. In my example the first source row is row 17 but the first target row is 1. If this is a problem for you you might first paste to the same row number and later remove rows in the destination sheet.</p>\n<p>You offer no explanation for the formulas you seem to want and writing formulas isn't the same as copying 125 rows. But basically you need one formula and a loop that copies it to 125 rows: 3 lines of code. The composition of the formula would be another question - obviously not connected to the title of this one.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T03:28:45.280", "Id": "270039", "ParentId": "269690", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T10:34:54.463", "Id": "269690", "Score": "1", "Tags": [ "vba", "excel" ], "Title": "Copy the last 125 rows from a selected excel file and paste into the used one" }
269690
<p>While setting up applications to communicate between various different trade partners and our WMS software I often have to parse very similar information from various different file formats. In this specific case i have to retrieve the tracking data from different files in csv, xml or json format. I've set up one template class for each file format to map to the respective fields. Each template derives from <code>TrackingInformationTemplate</code> class. Now I have come up with this code to select the specific template i need for the parsing.</p> <pre><code>using CommandLine; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RBHelper { [Verb(&quot;versanddatenimport&quot;)] class TrackinDataImportCommand : ICommand { [Option('i',&quot;input&quot;, Required = true)] public string FileName { get; set; } [Option('v',&quot;vorlage&quot;)] public string Template{ get; set; } private Dictionary&lt;DateiEndung, Func&lt;List&lt;TrackingInformations&gt;&gt;&gt; _convertOperations; public TrackinDataImportCommand() { _convertOperations = new Dictionary&lt;FileExtension, Func&lt;List&lt;TrackingInformations&gt;&gt;&gt;() { {FileExtension.csv, ()=&gt; FromCsv()}, {FileExtension.json, ()=&gt; FromJson()}, {FileExtension.xml, ()=&gt; FromXml()} }; } public void Execute() { // load TrackinData List&lt;TrakingInformations&gt; vis = ParseVis(); // TODO: Working with loaded data } private List&lt;TrackingInformations&gt; ParseVis() { FileExtension ext = (FileExtension)Enum.Parse(typeof(FileExtension), Path.GetExtension(FileName).Substring(1)); if(!_convertOperations.Keys.Contains(ext)) throw new NotSupportedException($&quot;{ext} not supported.&quot;); return _convertOperations[ext](); } private List&lt;TrackingInformations&gt; FromCsv() { CsvtrackingInformationTemplate template= CsvTrackingInformationTemplate.Default; if (!string.IsNullOrEmpty(Template)) template= TrackingInformationTemplate.Load&lt;CsvTrackingInformationTemplate&gt;(Template); return template.DeserializeFile(FileName); } private List&lt;TrackingInformations&gt; FromJson() { JsonTrackingInformationTemplate template = JsonTrackingInformationTemplate.Default; if (!string.IsNullOrEmpty(Template)) template = TrackingInformationTemplate.Load&lt;JsonTrackingInformatioTemplate&gt;(Template); return template.DeserializeFile(FileName); } private List&lt;TrackingInformations&gt; FromXml() { XmlTrackingInformationTemplate template = XmlTrackingInformationTemplate.Default; if (!string.IsNullOrEmpty(Temlate)) template = TrackingInformationTemplate.Load&lt;XmlTrackingInformationTemplate&gt;(Template); return template.DeserializeFile(FileName); } } } </code></pre> <p>Here is the Enum I use for file extension selection:</p> <pre><code>[JsonConverter(typeof(StringEnumConverter))] public enum FileExtension { csv, xml, json } </code></pre> <p>I am considering extracting the code related to the parsing into its own class. I just don't know how I would refactor the selection of the templates (FromCsv, FromXml, FromJson). these methods are near identical and i am certain that they can be improved.</p> <hr> <p><strong>Extra:</strong> I feel this might be outside of the scope of my question. For completion sake I'll show you the <code>VersandInformationenVorlage</code> cass and one of the dreived classes to demonstrate how those work:</p> <pre><code>using Newtonsoft.Json; using System.Collections.Generic; using System.IO; namespace RBHelper { abstract class TrackingInformationTemplate { public FileExtension FileExtension { get; private set; } public int kUser; public string CustomInfo; public string CustomRoute; public TrackingInformationTemplate(FileExtension FileExtension) =&gt; FileExtension = FileExtension; public static T Load&lt;T&gt;(string fileName) where T : TrackingInformationTemplate=&gt; JsonConvert.DeserializeObject&lt;T&gt;(File.ReadAllText(fileName)); public void Save(string fileName) =&gt; File.WriteAllText(fileName, JsonConvert.SerializeObject(this, Formatting.Indented)); public abstract List&lt;TrackingInformations&gt; DeserializeFile(string fileName); protected List&lt;TrackingInformations&gt; Deserialize(List&lt;TrackingInformations&gt; input) { List&lt;TrackingInformations&gt; output = new List&lt;TrackingInformations&gt;(); foreach (TrackingInformations v in input) if (!output.Contains(v)) output.Add(v); return output; } protected void Serialize(string serialized, string fileName) { using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) using (StreamWriter sw = new StreamWriter(fs)) { sw.Write(serialized); } } } } </code></pre> <p>And here the <code>JsonTrackingInformationTemplate</code> class</p> <pre><code>using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RBHelper { class JsonTrackingInformationTemplate: TrackingInformationTemplate { public JsonTrackingInformationTemplate() : base( DateiEndung.json) { } public string RootNode; public string TrackingDate; public string Id; public string Info; public string TrackingId; public string Route; public static JsonTrackingInformationTemplate Default =&gt; new JsonTrackingInformationTemplate() { kUser = 1, RootNode = &quot;[*]&quot;, TrackingDate = &quot;Versanddatum&quot;, Id = &quot;Id&quot;, Info = &quot;Versandinfo&quot;, TrackingId = &quot;TrackingId&quot;, Route = &quot;Route&quot; }; public override List&lt;TrackingInformations&gt; DeserializeFile(string fileName) { JToken doc = JToken.Parse(File.ReadAllText(fileName)); return doc.SelectTokens(RootNode).Select(a =&gt; DeserializeRecord(a)).ToList(); } public TrackingInformations DeserializeRecord(JToken token) { string info = string.IsNullOrEmpty(CustomInfo) ? token[Info].Value&lt;string&gt;() : CustomInfo; string route = string.IsNullOrEmpty(CustomRoute) ? token[Route].Value&lt;string&gt;() : CustomRoute; return new TrackingInformations() { TrackingDate = DateTime.Parse(token[TrackingDate].Value&lt;string&gt;()), Id = token[Id].Value&lt;string&gt;(), Info = info, TrackingId = token[TrackingId].Value&lt;string&gt;(), Route = route }; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T22:41:03.070", "Id": "532219", "Score": "2", "body": "it would be more helpful to the reviewers if the code is written in plain English." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T08:20:39.973", "Id": "532235", "Score": "1", "body": "Translated for you, @iSR5 I hope I didn't miss anything" } ]
[ { "body": "<p>For the purposes of international collaboration, for better or worse the de-facto language of software development is English, so:</p>\n<ul>\n<li>versanddaten -&gt; ShippingData</li>\n<li>vorlage -&gt; Template</li>\n<li>DateiEndung -&gt; FileExtension</li>\n</ul>\n<p>It is a great idea to localise user-facing content to German, but code should be in English.</p>\n<p>&quot;Informations&quot; should be &quot;Information&quot;.</p>\n<p>Your <code>Template</code> property suffers from an inadequate guarantee of validity - it could be null, or an empty string. Neither should be possible. If you're able, try reworking this property to be read-only, non-null and initialized on construction. Promote the use of immutable objects in your codebase, and reduce the possible number of invalid runtime states.</p>\n<p>You can rework your three methods:</p>\n<pre><code> private List&lt;TrackingInformations&gt; FromCsv()\n {\n CsvtrackingInformationTemplate template= CsvTrackingInformationTemplate.Default;\n if (!string.IsNullOrEmpty(Template)) template= TrackingInformationTemplate.Load&lt;CsvTrackingInformationTemplate&gt;(Template);\n return template.DeserializeFile(FileName);\n }\n\n private List&lt;TrackingInformations&gt; FromJson()\n {\n JsonTrackingInformationTemplate template = JsonTrackingInformationTemplate.Default;\n if (!string.IsNullOrEmpty(Template)) template = TrackingInformationTemplate.Load&lt;JsonTrackingInformatioTemplate&gt;(Template);\n return template.DeserializeFile(FileName);\n }\n\n private List&lt;TrackingInformations&gt; FromXml()\n {\n XmlTrackingInformationTemplate template = XmlTrackingInformationTemplate.Default;\n if (!string.IsNullOrEmpty(Temlate)) template = TrackingInformationTemplate.Load&lt;XmlTrackingInformationTemplate&gt;(Template);\n return template.DeserializeFile(FileName);\n }\n</code></pre>\n<p>to one method that is based on a template parameter:</p>\n<pre><code>private List&lt;TrackingInformation&gt; DeserializeFrom&lt;TemplateT&gt;()\nwhere TemplateT: TrackingInformationTemplate\n{\n TrackingInformationTemplate template = TrackingInformationTemplate.Load&lt;TemplateT&gt;(TemplateFilename);\n return template.Deserialize(FileName);\n}\n</code></pre>\n<p>This is both more extensible if other template types are added, and less code repeated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T07:49:32.003", "Id": "532329", "Score": "1", "body": "Thank you for your response. That is exactly what i was looking for. Of course you're right with the class names and I will change them to english. This mixed laguage programming is a bad habit I'm trying to get rid of" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T19:46:24.227", "Id": "269740", "ParentId": "269691", "Score": "1" } } ]
{ "AcceptedAnswerId": "269740", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T12:03:10.027", "Id": "269691", "Score": "1", "Tags": [ "c#", "parsing" ], "Title": "Parsing data from different file formats" }
269691
<blockquote> <h2>Minimal Squares in a Rectangle</h2> <p>Given a rectangle of dimensions <span class="math-container">\$a\$</span> and <span class="math-container">\$b\$</span>, we want to divide it into the <em><strong>minimal</strong></em> number of covering squares. The following rectangle has a dimensions of 5 x 3. It can be cut into 4 squares: [ 3x3, 2x2, 1x1, 1x1]</p> <p><a href="https://i.stack.imgur.com/sSgHT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sSgHT.png" alt="rectangle divided into squares" /></a></p> <p>Implement a function that will take two numbers representing the sides of the rectangle and will return an array containing the dimension of each resulting square.</p> <pre><code>var sqrs = squaresInRect(5, 3); console.log(sqrs); // [3, 2, 1, 1] sqrs = squaresInRect(3, 5); console.log(sqrs); // [3, 2, 1, 1] sqrs = squaresInRect(5, 5); console.log(sqrs); // [5] </code></pre> </blockquote> <p>I am allowed to use only: conditions (<code>if</code>), loops, <code>--</code>, <code>++</code>, <code>%</code>, <code>/</code>, <code>*</code>, <code>-</code>, <code>+</code>, <code>==</code>, <code>=!</code>, <code>=&gt;</code>, <code>&gt;</code>, <code>=&lt;</code>, <code>&lt;</code>, <code>||</code>, <code>&amp;&amp;</code>, <code>=%</code>, <code>=/</code>, <code>=*</code>, <code>+-</code>, <code>=+</code>, <code>array.length</code>, <code>array.pop()</code> and <code>concat</code>.</p> <p>I will be happy for any feedback.</p> <pre><code>function squaresInRect(a,b){ var i,ab,sofar,temp; var arryOfSquares=[]; sofar=0; ab=a*b; while(sofar !== ab &amp;&amp; a &lt;= b){ sofar=sofar + (a*a); arryOfSquares.push(a); temp=a; a=b-a; b=temp; } while(sofar !== ab &amp;&amp; a &gt;= b){ sofar=sofar + (b*b); arryOfSquares.push(b); temp=b; b=a-b; a=temp; } while(sofar !== ab){ sofar++; arryOfSquares.push(1); } return arryOfSquares; } console.log(squaresInRect(3,7)); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T18:43:22.143", "Id": "532405", "Score": "1", "body": "Instead of `=!`, `=>`, `=<`, `=%`, `=/`, `=*`, `=+`, did you really mean `!=`, `>=`, `<=`, `%=`, `/=`, `*=`, `+=`? Also, what is the `+-` operator? (if there really is such a thing) Please update your question with the correct operators." } ]
[ { "body": "<p>This problem lends itself quite well to a recursive implementation. This would be the algorithm for <code>sqaures(length,width)</code>:</p>\n<ul>\n<li><p>If <code>length</code> &lt; <code>width</code>, then we have it wrong way around, so return the value of <code>squares(width,length)</code>.</p>\n</li>\n<li><p>If <code>width</code> is zero, then we can make no squares - return empty list - this is the step that ensures that the recursion <em>terminates</em> eventually.</p>\n</li>\n<li><p>Otherwise, we can make <code>Math.floor(length / width)</code> squares of side <code>width</code>, and we have a piece left over that's <code>width</code>✕<code>length % width</code>. From that leftover piece we can make <code>squares(width, length%width)</code> smaller squares - that's the recursive call.</p>\n</li>\n</ul>\n<p>With the recursive algorithm, we don't need to write any actual loops. It's possible to pass the partial results into the recursive function to make it <em>tail recursive</em> - that can help avoid running out of stack (depending on the quality of the interpreter).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T16:03:22.390", "Id": "269778", "ParentId": "269700", "Score": "2" } }, { "body": "<h2>Style</h2>\n<ul>\n<li><p>Spaces between operators. <code>ab=a*b;</code> is better as <code>ab = a * b;</code></p>\n</li>\n<li><p>Assuming you mean <code>+=</code> rather than <code>=+</code> from the list of operators you can use. Ditto for <code>=!</code>, <code>=&gt;</code>, <code>=&lt;</code>, <code>=%</code>, <code>=/</code>, <code>=*</code>, <code>=+</code> should be <code>!=</code>, <code>&gt;=</code>, <code>&lt;=</code>, <code>%=</code>, <code>/=</code>, <code>*=</code>, <code>+=</code></p>\n</li>\n<li><p>Use addition assignment. eg <code>sofar=sofar + (a*a);</code> can be <code>sofar += a * a;</code></p>\n</li>\n<li><p>Use constants for variables that do not change. Eg the array do not change only its content changes. Thus <code>var arryOfSquares=[];</code> can be <code>const arryOfSquares=[];</code> also the name is way to long for the context. <code>const squares = [];</code> or just <code>const sqrs = [];</code> is just as clear.</p>\n</li>\n</ul>\n<h2>Too complex</h2>\n<p>Your code is way too complex for the task. The best code is always the simplest.</p>\n<p>All that needs to be done is check the for the shortest length and removing that length from the longer until you get a square (both edges are the same). Each time you remove a length push it to an array. This can be done in one loop.</p>\n<h2>Rewrite</h2>\n<p>Assuming the inputs are positive integers &gt; 0 the function can be written as...</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>function minSquares(w, h) {\n const squares = [];\n var min;\n while (w &gt; 0) {\n if (w &lt; h) {\n squares.push(w);\n h -= w;\n } else { \n squares.push(h);\n w -= h;\n }\n }\n return squares;\n}\n\nconsole.log(minSquares(5, 3).join(\",\"));\nconsole.log(minSquares(11, 3).join(\",\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Or using a ternary.</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>function minSquares(w, h) {\n const squares = [];\n var min;\n while (w &gt; 0) {\n w &lt; h ? h -= min = w : w -= min = h;\n squares.push(min);\n }\n return squares;\n}\nfunction test(...args) {\n console.log(`Squares for [${args}] is [${minSquares(...args)}]`);\n}\n\ntest(5, 3);\ntest(11, 3);\ntest(27, 19);</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-11-05T23:32:35.857", "Id": "269797", "ParentId": "269700", "Score": "2" } } ]
{ "AcceptedAnswerId": "269797", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T13:54:57.650", "Id": "269700", "Score": "1", "Tags": [ "javascript", "array" ], "Title": "Minimal Squares in a Rectangle" }
269700
<p>I'm reading &quot;Modern C++ Design&quot; (A. Alexandrescu, 2002). The author said &quot;the standard memory allocator is awful for small objects&quot;, but it has been two decades after the book has been out, glibc's malloc was really hard to beat.</p> <p>Anyway, inspired from that, I wrote a simple allocator for fixed size object, in particular, my B-Tree (<a href="https://codereview.stackexchange.com/questions/248231/c-b-tree-in-c20-iterator-support">C++ : B-Tree in C++20 (+Iterator support)</a>) node, which have <code>sizeof(Node) = 64</code> in 64-bit machine.</p> <pre><code>template &lt;typename T&gt; class FixedAllocator { struct Chunk { static constexpr std::size_t blockSize_ = sizeof(T); static constexpr unsigned char numBlocks_ = FixedAllocator::numBlocks_; Chunk() { unsigned char i = 0; for (unsigned char * p = &amp;data_[0]; i != numBlocks_; p += blockSize_) { *p = ++i; } } void* allocate() { unsigned char* result = &amp;data_[firstAvailableBlock_ * blockSize_]; firstAvailableBlock_ = *result; --blocksAvailable_; return result; } void deallocate(void* p) { assert(p &gt;= &amp;data_[0]); auto* toRelease = static_cast&lt;unsigned char*&gt;(p); assert((toRelease - &amp;data_[0]) % blockSize_ == 0); auto index = static_cast&lt;unsigned char&gt;((toRelease - &amp;data_[0]) / blockSize_); *toRelease = firstAvailableBlock_; firstAvailableBlock_ = index; ++blocksAvailable_; } bool hasBlock(void* p, std::size_t chunkLength) const { auto* pc = static_cast&lt;unsigned char*&gt;(p); return (&amp;data_[0] &lt;= pc) &amp;&amp; (pc &lt; &amp;data_[chunkLength]); } [[nodiscard]] bool hasAvailable() const { return (blocksAvailable_ == numBlocks_); } [[nodiscard]] bool isFilled() const { return !blocksAvailable_; } unsigned char data_[blockSize_ * numBlocks_]; unsigned char firstAvailableBlock_ = 0; unsigned char blocksAvailable_ = numBlocks_; }; private: static constexpr std::size_t blockSize_ = sizeof(T); static constexpr unsigned char numBlocks_ = std::numeric_limits&lt;unsigned char&gt;::max(); std::vector&lt;Chunk&gt; chunks_; Chunk* allocChunk_ = nullptr; Chunk* deallocChunk_ = nullptr; Chunk* emptyChunk_ = nullptr; public: using value_type = T; FixedAllocator() { chunks_.reserve(std::numeric_limits&lt;unsigned char&gt;::max()); } void* doAllocate() { assert(!emptyChunk_ || emptyChunk_-&gt;hasAvailable()); if (!allocChunk_ || allocChunk_-&gt;isFilled()) { if (emptyChunk_) { allocChunk_ = emptyChunk_; emptyChunk_ = nullptr; } else { auto it = chunks_.begin(); for (;; ++it) { if (it == chunks_.end()) { chunks_.emplace_back(); allocChunk_ = &amp;chunks_.back(); deallocChunk_ = &amp;chunks_.front(); break; } if (!it-&gt;isFilled()) { allocChunk_ = &amp;*it; break; } } } } else if (allocChunk_ == emptyChunk_) { emptyChunk_ = nullptr; } assert(allocChunk_ &amp;&amp; !allocChunk_-&gt;isFilled()); assert(!emptyChunk_ || emptyChunk_-&gt;hasAvailable()); return allocChunk_-&gt;allocate(); } value_type* allocate(std::size_t n) { assert(n == 1); auto* p = static_cast&lt;value_type*&gt;(doAllocate()); return p; } Chunk* findVicinity(void* p) const { assert(!chunks_.empty() &amp;&amp; deallocChunk_); const std::size_t chunkLength = numBlocks_ * blockSize_; // bidirectional search Chunk* lo = deallocChunk_; Chunk* hi = deallocChunk_ + 1; const Chunk* lbound = &amp;chunks_.front(); const Chunk* hbound = &amp;chunks_.back() + 1; if (hi == hbound) { hi = nullptr; } for (;;) { if (lo) { if (lo-&gt;hasBlock(p, chunkLength)) { return lo; } if (lo == lbound) { lo = nullptr; if (!hi) { break; } } else { --lo; } } if (hi) { if (hi-&gt;hasBlock(p, chunkLength)) { return hi; } if (++hi == hbound) { hi = nullptr; if (!lo) { break; } } } } return nullptr; } void deallocate(void* p, std::size_t n) noexcept { assert(n == 1); assert(!chunks_.empty()); assert(&amp;chunks_.front() &lt;= deallocChunk_); assert(&amp;chunks_.back() &gt;= deallocChunk_); assert(&amp;chunks_.front() &lt;= allocChunk_); assert(&amp;chunks_.back() &gt;= allocChunk_); Chunk* foundChunk = nullptr; const std::size_t chunkLength = numBlocks_ * blockSize_; if (deallocChunk_-&gt;hasBlock(p, chunkLength)) { foundChunk = deallocChunk_; } else if (allocChunk_-&gt;hasBlock(p, chunkLength)) { foundChunk = allocChunk_; } else { foundChunk = findVicinity(p); } assert(foundChunk &amp;&amp; foundChunk-&gt;hasBlock(p, chunkLength)); deallocChunk_ = foundChunk; // double free check assert(emptyChunk_ != deallocChunk_); assert(!deallocChunk_-&gt;hasAvailable()); assert(!emptyChunk_ || emptyChunk_-&gt;hasAvailable()); deallocChunk_-&gt;deallocate(p); if (deallocChunk_-&gt;hasAvailable()) { // only release chunk if there are 2 empty chunks. if (emptyChunk_) { // if last chunk is empty, just let deallocChunk_ points // to empty chunk, and release the last. // otherwise, swap two and release an empty chunk Chunk* lastChunk = &amp;chunks_.back(); if (lastChunk == deallocChunk_) { deallocChunk_ = emptyChunk_; } else if (lastChunk != emptyChunk_) { std::swap(*emptyChunk_, *lastChunk); } assert(lastChunk-&gt;hasAvailable()); chunks_.pop_back(); if ((allocChunk_ == lastChunk) || (allocChunk_-&gt;isFilled())) { allocChunk_ = deallocChunk_; } } emptyChunk_ = deallocChunk_; } } template &lt;typename... Args&gt; void construct (value_type* p, Args&amp;&amp;... args) { std::construct_at(p, std::forward&lt;Args&gt;(args)...); } void destroy(value_type* p) { std::destroy_at(p); } }; </code></pre> <p>I changed my B-Tree implementation correspondingly, ditching <code>std::unique_ptr</code> with using these functions:</p> <pre><code> FixedAllocator&lt;Node&gt; alloc; Node* make_node() { Node* ptr = alloc.allocate(1); alloc.construct(ptr); return ptr; } void erase_node(Node* ptr) { alloc.destroy(ptr); alloc.deallocate(ptr, 1); } </code></pre> <p>The benchmark gives: (inserting and removing keys from 1~10000 in totally random order, 10000 time averaged)</p> <pre><code>My allocator: Inserting: 2783us Removing: 2435us Standard allocator: Inserting: 2700us Removing: 2724us </code></pre> <p>Feel free to comment anything!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T14:44:43.193", "Id": "532164", "Score": "0", "body": "Have you looked at the newer `memory_resource` interface?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T14:46:46.803", "Id": "532165", "Score": "0", "body": "@JDlugosz Yes, I could replace ```std::vector<Chunk>``` with ```std::pmr::vector<Chunk>```, but I don't understand pmr well yet, so deferred that homework to later." } ]
[ { "body": "<h1>Missing alignment restrictions</h1>\n<p>A big issue with your allocator is that you don't ensure the storage is correctly aligned for type <code>T</code>. There are various ways to ensure storage is correctly aligned, but a simple way to do this is by using <a href=\"https://en.cppreference.com/w/cpp/types/aligned_storage\" rel=\"nofollow noreferrer\"><code>std::aligned_storage</code></a>:</p>\n<pre><code>struct Chunk {\n ...\n typename std::aligned_storage&lt;sizeof(T), alignof(T)&gt;::type data_[numBlocks_];\n ...\n};\n</code></pre>\n<p>As a bonus you no longer have to multiple things by <code>blockSize_</code> yourself.</p>\n<h1>A <code>Chunk</code> knows its own length</h1>\n<p>It's weird to see the parameter <code>chunkLength</code> for <code>hasBlock()</code>, and member functions of <code>FixedAllocator</code> calculating the size of <code>Chunk</code>'s <code>data_[]</code> and then passing it to <code>hasBlock()</code>. A <code>Chunk</code> knows exactly how large its <code>data_[]</code> is.</p>\n<p>Also, if you can make <code>hasBlock()</code> check that <code>p</code> is correctly aligned to the start of a block, you can have a single <code>assert(hasBlock(p))</code> inside <code>deallocate()</code>.</p>\n<h1>Naming things</h1>\n<p>I recommend you try following the naming conventions of the standard C++ library, so users of your library don't have to deal with multiple conventions. For example:</p>\n<ul>\n<li><code>hasBlock()</code> -&gt; <code>contains()</code></li>\n<li><code>hasAvailable()</code> -&gt; <code>empty()</code></li>\n<li><code>doAllocate()</code> -&gt; <code>allocate()</code> (it can coexist with the one that takes an argument)</li>\n</ul>\n<h1>Don't use <code>std::vector</code> to store your chunks</h1>\n<p>A <code>std::vector</code> might move its contents in memory when it needs to resize.\nYour solution to reserve the maximum size up front will potentially waste a lot of memory, and at the same time it now puts a hard limit to the number of objects an application can store using your allocator. And if you are going to give it a fixed capacity anyway, why not use a <code>std::array</code>?</p>\n<p>There are many data structures that are more suitable, the most important thing though is to think about how fast it will be to find the <code>Chunk</code> that stores an object at a given address when calling <code>FixedAllocator::deallocate()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T21:10:48.533", "Id": "269716", "ParentId": "269702", "Score": "2" } } ]
{ "AcceptedAnswerId": "269716", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T14:23:20.167", "Id": "269702", "Score": "4", "Tags": [ "c++", "memory-management" ], "Title": "C++ : Allocator for fixed size object" }
269702
<p>This is a follow-up to <a href="https://codereview.stackexchange.com/questions/269526/implementing-stdformat-part-2">this</a> question.</p> <p>Here I’m trying to do something useful with the format specifier. I guess I should have started with <code>width</code> and <code>precision</code> but foolishly decided to first try my hand at binary formatting. So here we go…</p> <pre><code>#include &lt;bitset&gt; #include &lt;charconv&gt; #include &lt;exception&gt; #include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;string_view&gt; namespace jdt { template&lt;typename T&gt; void toBinary(std::ostream&amp; oss, const T&amp; x) { oss &lt;&lt; std::bitset&lt;sizeof(T) * 8&gt;(x); } void toBinary(std::ostream&amp; oss, const double&amp; x) { union { double a; unsigned long long b; } data; data.a = x; toBinary(oss, data.b); } void toBinary(std::ostream&amp; oss, const float&amp; x) { union { float a; unsigned int b; } data; data.a = x; toBinary(oss, data.b); } void toBinary(std::ostream&amp; oss, const std::string&amp; x) { for (auto c : x) toBinary(oss, c); } void toBinary(std::ostream&amp; oss, const char* x) { for (; *x; x++) toBinary(oss, *x); } template&lt;typename T&gt; void format_helper(std::ostream&amp; oss, std::string_view fmt, const T&amp; value) { if (fmt.find('b') != std::string::npos) { toBinary(oss, value); } else { oss &lt;&lt; value; } } template&lt;typename... Targs&gt; static bool format_one(std::ostream&amp; oss, size_t i, std::string_view fmt, const Targs&amp;... args) { auto visitor = [&amp;](const auto&amp; arg) { if (!i--) { format_helper(oss, fmt, arg); return true; } else { return false; } }; return (visitor(args) || ...); } template&lt;typename... Targs&gt; std::string format(std::string_view str, const Targs&amp;... args) { std::ostringstream oss; std::size_t offset = 0; std::size_t index = str.find('{'); std::size_t argumentCounter = 0; while (index != std::string::npos) { // check for literal open-braces character if (str[index + 1] == '{') { oss.write(str.data() + offset, index - offset + 1); offset = index + 2; } else { // check if the next part is an argument index std::size_t argindex = argumentCounter++; std::size_t startOfArg = index; auto ret = std::from_chars(str.data() + index + 1, str.data() + str.size(), argindex); index = ret.ptr - str.data(); // find closing brace bool braceError = false; std::size_t closeBrace = str.find('}', index); if (closeBrace == std::string::npos) throw std::runtime_error(format(&quot;error in string: {0}, column: {1}: '{{': no matching token found &quot;, std::string(str), startOfArg).c_str()); // check for format specifier if (str[index] == ':') index++; oss.write(str.data() + offset, startOfArg - offset); if (!format_one(oss, argindex, str.substr(index, closeBrace - index), args...)) throw std::runtime_error(format(&quot;error in string: {0}, column: {1}: invalid argument index: {2}&quot;, std::string(str), startOfArg, argindex).c_str()); if (argindex &lt; 0) std::cout &lt;&lt; argindex &lt;&lt; &quot;\n&quot;; offset = closeBrace + 1; } index = str.find('{', offset); } if (offset &lt; str.size()) oss &lt;&lt; str.substr(offset); return oss.str(); } } int main() { int a = 5; double b = 3.14; std::string c(&quot;hello&quot;); char d = 'Z'; short e = 16634; float f = 123.456f; // simple arguments std::cout &lt;&lt; jdt::format(&quot;a = {}, b = {}, c = {}\n&quot;, a, b, c); // arguments with indexes std::cout &lt;&lt; jdt::format(&quot;a = {2}, b = {1}, c = {0}\n&quot;, a, b, c); // literal open-braces character std::cout &lt;&lt; jdt::format(&quot;let object = {{\&quot;a\&quot;: {0}, \&quot;b\&quot;: {1}, \&quot;c\&quot;: \&quot;{2}\&quot;};\n&quot;, a, b, c); // binary formats std::cout &lt;&lt; jdt::format(&quot;char: {0} = {0:b}\n&quot;, d); std::cout &lt;&lt; jdt::format(&quot;short: {0} = {0:b}\n&quot;, e); std::cout &lt;&lt; jdt::format(&quot;int: {0} = {0:b}\n&quot;, a); std::cout &lt;&lt; jdt::format(&quot;double: {0} = {0:b}\n&quot;, b); std::cout &lt;&lt; jdt::format(&quot;float: {0} = {0:b}\n&quot;, f); std::cout &lt;&lt; jdt::format(&quot;std::string: {0} = {0:b}\n&quot;, c); std::cout &lt;&lt; jdt::format(&quot;char*: {0} = {0:b}\n&quot;, &quot;ABCDEFG&quot;); // too few arguments std::cout &lt;&lt; jdt::format(&quot;a = {0}, b = {1}, c = {2}\n&quot;, a, b); // invalid argument indexes std::cout &lt;&lt; jdt::format(&quot;a = {0}, b = {10}, c = {2}\n&quot;, a, b, c); // too many arguments std::cout &lt;&lt; jdt::format(&quot;a = {2}, b = {1}, c = {0}\n&quot;, a, b, c, 3, 4, 5); // missing closing brace } std::cout &lt;&lt; jdt::format(&quot;a = {2}, b = {1}, c = {0\n&quot;, a, b, c); } </code></pre>
[]
[ { "body": "<p>You only need a <code>string_view</code> overload to take care of <code>string</code>, <code>const char*</code>, and <code>string_view</code> arguments.</p>\n<pre><code>data.a = x;\ntoBinary(oss, data.b);\n</code></pre>\n<p>That's <strong>undefined behavior</strong>.</p>\n<p>You ought to have a template that handles any POD type or however you decide to restrict it, that outputs the binary representation of the object's bytes. That would take care of the <code>float</code> and <code>double</code> cases you have now. Be sure to use only approved kosher methods of getting a pointer to the underlying bytes, not a 1980's trick. See <a href=\"https://en.cppreference.com/w/cpp/language/reinterpret_cast\" rel=\"nofollow noreferrer\">CppReference under <code>reinterpret_cast</code></a> where it's mentioned in a couple different places.</p>\n<p>Both cases you show here should use <code>bit_cast</code> which is for this express purpose (as of C++20).</p>\n<p>For a general object of some arbitrary size, you can use <code>reinterpret_cast</code> to inspect it as an array of bytes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T17:49:19.583", "Id": "532192", "Score": "0", "body": "Thanks for your valuable insights! I'm not sure if I'm implementing this wrong, but the `string_view` overload does not seem to handle `std::string` and `const char*`: [TIO](https://tio.run/##jY/PTsMwDIfveQprSChlGwdOqA2VNl6hdxTStFhqkypxywbi1Snpsj@VxmE@frZ/n626bq0aaepxvEOjmr7UIN6RvKacXYj6kE5ZM8wZWk9Oy3bO/D@IHJr6mrwNqD9zxhjptmskaUH7ThvZaihyNlgsgewWjXR77qlM06PuHqz3KwjXeIICdgn7ZhAqUBACDqPxAeHxS9uKFwk8wHPOd0nGftit0YfG7NQA3MlVWQdc9mRBQRobcKxzcIyKSjQErUTDTwFna0iP7kmdseuExWb7ukiyy5ayPU2Phu5jWOWTYRx/VdXI2o/rMPOilssn@Qc)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T17:52:08.443", "Id": "532195", "Score": "0", "body": "@upkajdt then there's something wrong, because we normally pass both `std::string` objects and literal lexical strings `\"like this\"` to functions declared to take `std::string_view`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T18:04:16.213", "Id": "532199", "Score": "0", "body": "This seems to work, but it is ugly [TIO](https://tio.run/##nZHNToQwFIX3fYobTGbKjOPClQEkcfx5ApYmppaCTaAl7QVnNL66WGB@iMzCsctzzz3facurasULpvK2vZCKF3UqIHqVaAXG5KjwN2a4Vs1Yk9qiEawca/aEhEaqfKq8NFK8x4SgKKuCoYhwWwnFSgFJTBotU0C9loqZLbWYBsGONgNt7SW4MhYhgY1PPgm441SIIuitQ//Iyg@hM5r4sICbmG78kHyRv0b3g1FTJ5g9K9MGKKtRA4dgGMDuHIKHqLOQ3SMvxpxJHv3dyqed/b8Xm50J69w9SiqEkklF98sHmvMOzA4Zkmmqd7e@9/xw/GfzZzU/ZR3xqffw@OT5u71@wHWN3bazXjkT7Zq17TfPCpbbduU8t3y5vGY/)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T18:17:10.637", "Id": "532201", "Score": "0", "body": "@upkajdt https://godbolt.org/z/Yj8rTWhfr You should not have to declare the other two overloads at all. I think your problem is that you are defining them to call the `string_view` version, rather than just defining the `string_view` form **only**." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T19:03:17.903", "Id": "532203", "Score": "0", "body": "This works until you have the generic function template: https://godbolt.org/z/95K35dWvq." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T19:33:41.723", "Id": "532204", "Score": "0", "body": "Something like this might work, but now I'm messing with stuff that is way beyond my skill level =) https://godbolt.org/z/T1nPKPf9z" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T21:58:29.943", "Id": "532216", "Score": "0", "body": "@upkajdt forget `enable_if` if you have a current compiler. Use `requires` which is a direct language feature for doing this, and much easier to use. Instead of the template constrained to anything that's not `std::string`, it should be anything that's trivially copyable. That still leaves `char*` and variations that you want funneled to be handled as a string... A \"better\" template match is a function that specifically takes pointers. So `foo (T*)` will match with `T` as `char` or `const char` as well as `unsigned char` etc. This pointer form can use `constexpr if` in the body..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T21:59:44.823", "Id": "532217", "Score": "0", "body": "... to decide if it's a stringline thing or some other pointer where you just print the pointer's address. Messing with stuff beyond your skill level is how you grow. \"messing around\" sure beats being beyond your skill level in assigned work with deadlines and customers!" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T16:03:47.880", "Id": "269704", "ParentId": "269703", "Score": "1" } }, { "body": "<p>This test is always false, because <code>argindex</code> is unsigned</p>\n<blockquote>\n<pre><code> if (argindex &lt; 0)\n</code></pre>\n</blockquote>\n<hr />\n<p>This variable is never used:</p>\n<blockquote>\n<pre><code> bool braceError = false;\n</code></pre>\n</blockquote>\n<hr />\n<p>There is a non-portable assumption here:</p>\n<blockquote>\n<pre><code> oss &lt;&lt; std::bitset&lt;sizeof(T) * 8&gt;(x);\n</code></pre>\n</blockquote>\n<p>You probably meant <code>CHAR_BIT</code> rather than <code>8</code>:</p>\n<blockquote>\n<pre><code> oss &lt;&lt; std::bitset&lt;sizeof x * CHAR_BIT&gt;(x);\n</code></pre>\n</blockquote>\n<hr />\n<p>Type-punning using a union is Undefined; also we cannot predict whether <code>long long</code> and <code>double</code> are the same size.</p>\n<p>I think it's safe to use <code>reinterpret_cast</code> instead, like this (I'm using <code>&lt;concepts&gt;</code> so as not to need separate versions for <code>float</code>, <code>double</code> and <code>long double</code>):</p>\n<pre><code>void toBinary(std::ostream&amp; oss, std::floating_point auto const x)\n{\n auto&amp; a = reinterpret_cast&lt;const unsigned char(&amp;)[sizeof x]&gt;(x);\n for (auto c: a) {\n toBinary(oss, c);\n }\n}\n</code></pre>\n<p>We might choose to use <code>std::bit_cast</code> from C++20:</p>\n<pre><code>void toBinary(std::ostream&amp; oss, std::floating_point auto const x)\n{\n using array = std::array&lt;unsigned char,sizeof x&gt;;\n for (auto c: std::bit_cast&lt;array&gt;(x)) {\n toBinary(oss, c);\n }\n}\n</code></pre>\n<p>On little-endian hardware, we'll want to reverse the byte order using <code>(auto c: std::views::reverse(a))</code> - I'll let you find out how to determine which order we should use.</p>\n<hr />\n<p>Finally, please give some serious consideration to using a proper unit-test framework to give more robust testing than visual inspection.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T17:58:21.213", "Id": "532197", "Score": "1", "body": "I pointed out that `reinterpret_cast` _is_ safe, if you use it to view the object as an array of bytes. It works with `char`, `unsigned char`, and `std::byte`. But `bit_cast` is better for a simple primitive type. You probably should not pass the floating_point value by reference, unless you are accepting extended-precision float class types as well. As written, I'd use that function for any POD type (if you don't mind me using an out-of-date term for that; exactly how to constrain it is subject to discussion)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T16:10:04.573", "Id": "269705", "ParentId": "269703", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T15:22:40.827", "Id": "269703", "Score": "1", "Tags": [ "c++", "c++20" ], "Title": "Implementing std::format - Part 3" }
269703
<p>I made a weather app in react and redux for an interview. The response was that I didn't use redux properly, and that it has unnecessary props. I'm not sure what they meant.</p> <p>The app is on github <a href="https://github.com/s-e1/weather-app" rel="nofollow noreferrer">https://github.com/s-e1/weather-app</a></p> <p>There are 2 pages in the App,</p> <ol> <li>Home contains SearchBar and HomeMain, HomeMain contains an array of ForecastCard.</li> <li>Favorites contains an array of CityCard.</li> </ol> <p>reducer.js</p> <pre class="lang-js prettyprint-override"><code>const initialState = { cityName: &quot;Tel Aviv&quot;, cityKey: 215854, searchResults: [], weatherResults: {} }; const reducer = (state = initialState, action) =&gt; { switch (action.type) { case 'SET NAME': return { ...state, cityName: action.payload }; case 'SET KEY': return { ...state, cityKey: action.payload }; case 'SET SEARCH': return { ...state, searchResults: action.payload }; case 'SET WEATHER': return { ...state, weatherResults: action.payload }; default: return state; } } export default reducer; </code></pre> <p>utils.js - for sending requests to the server</p> <pre class="lang-js prettyprint-override"><code>import axios from &quot;axios&quot;; const server = &quot;https://weather-app-serv.herokuapp.com/&quot; || &quot;http://localhost:8000/&quot;; export const getSearchRequest = async (cityName) =&gt; { if (!cityName) return []; let reply = await axios.get(server + &quot;search?name=&quot; + cityName); return reply.data; } export const getWeatherRequest = async (key) =&gt; { const url = `${server}weather?key=${key}`; let reply = await axios.get(url); return reply.data; } export const getFavoritesRequest = async (key) =&gt; { const url = `${server}favorites?key=${key}`; let reply = await axios.get(url); return reply.data; } </code></pre> <p>app.js</p> <pre class="lang-js prettyprint-override"><code>import { useEffect } from &quot;react&quot;; import { Switch, Route } from &quot;react-router-dom&quot;; import { useDispatch, useSelector } from 'react-redux'; import Navbar from &quot;./components/Navbar&quot;; import Home from &quot;./components/Home&quot;; import Favorites from &quot;./components/Favorites&quot;; import { getSearchRequest, getWeatherRequest } from &quot;./utils&quot;; import &quot;./App.css&quot;; function App() { const dispatch = useDispatch(); const cityName = useSelector(state =&gt; state.cityName); const cityKey = useSelector(state =&gt; state.cityKey); useEffect(() =&gt; { weatherCB(cityName, cityKey); }, []) const searchCB = (name) =&gt; { getSearchRequest(name) .then(data =&gt; { dispatch({ type: &quot;SET SEARCH&quot;, payload: data }); }) } const weatherCB = (name, key) =&gt; { dispatch({ type: &quot;SET NAME&quot;, payload: name }); dispatch({ type: &quot;SET KEY&quot;, payload: key }); getWeatherRequest(key) .then(data =&gt; { dispatch({ type: &quot;SET WEATHER&quot;, payload: data }); }) } return ( &lt;div className=&quot;appContainer&quot;&gt; &lt;Navbar /&gt; &lt;Switch&gt; &lt;Route exact path=&quot;/&quot;&gt;&lt;Home searchCB={searchCB} weatherCB={weatherCB} /&gt;&lt;/Route&gt; &lt;Route path=&quot;/favorites&quot;&gt;&lt;Favorites weatherCB={weatherCB} /&gt;&lt;/Route&gt; &lt;/Switch&gt; &lt;footer&gt; &lt;p&gt;Data provided by &lt;a href=&quot;https://developer.accuweather.com/&quot;&gt;Accuweather&lt;/a&gt;&lt;/p&gt; &lt;/footer&gt; &lt;/div&gt; ); } export default App; </code></pre> <p>Home.js - contains SearchBar and HomeMain</p> <pre class="lang-js prettyprint-override"><code>import SearchBar from &quot;./SearchBar&quot;; import HomeMain from &quot;./HomeMain&quot;; import ErrorBoundary from &quot;../ErrorBoundary&quot;; function Home({ searchCB, weatherCB }) { return ( &lt;div&gt; &lt;ErrorBoundary&gt; &lt;SearchBar searchCB={searchCB} weatherCB={weatherCB} /&gt; &lt;/ErrorBoundary&gt; &lt;ErrorBoundary&gt; &lt;HomeMain /&gt; &lt;/ErrorBoundary&gt; &lt;/div&gt; ); } export default Home; </code></pre> <p>SearchBar.js - a child of Home component</p> <pre class="lang-js prettyprint-override"><code>import { useState } from &quot;react&quot;; import { useSelector } from 'react-redux'; import &quot;./SearchBar.css&quot;; function SearchBar({ searchCB, weatherCB }) { const searchResults = useSelector(state =&gt; state.searchResults); const [text, setText] = useState(&quot;&quot;); const search = (e) =&gt; { setText(e.target.value); searchCB(e.target.value); } const sendWeather = (name, key) =&gt; { weatherCB(name, key); setText(&quot;&quot;); searchCB(&quot;&quot;); } return ( &lt;div&gt; &lt;div className=&quot;searchBar&quot;&gt;Search: &lt;input onChange={search} value={text} /&gt; &lt;/div&gt; {searchResults.length ? &lt;ul className=&quot;searchResults&quot;&gt; {searchResults.map((e, i) =&gt; { return &lt;li className=&quot;searchItem&quot; key={i} onClick={() =&gt; sendWeather(e.cityName, e.key)}&gt; {e.cityName}, {e.countryName} &lt;/li&gt; })} &lt;/ul&gt; : null} &lt;/div&gt; ); } export default SearchBar; </code></pre> <p>HomeMain.js - a child of Home component</p> <pre class="lang-js prettyprint-override"><code>import { useEffect, useState } from &quot;react&quot;; import { useSelector } from 'react-redux'; import ForecastCard from &quot;./ForecastCard&quot;; import &quot;./HomeMain.css&quot;; function HomeMain() { const cityName = useSelector(state =&gt; state.cityName); const cityKey = useSelector(state =&gt; state.cityKey); const weatherResults = useSelector(state =&gt; state.weatherResults); const [currentWeather, setCurrentWeather] = useState({}); const [forecast, setForecast] = useState([]); const [imgUrl, setImgUrl] = useState(&quot;&quot;); const [isFavorite, setIsFavorite] = useState(false); const daysOfWeek = [&quot;Sun&quot;, &quot;Mon&quot;, &quot;Tue&quot;, &quot;Wed&quot;, &quot;Thu&quot;, &quot;Fri&quot;, &quot;Sat&quot;]; const today = new Date().getDay(); const iconSite = &quot;https://developer.accuweather.com/sites/default/files/&quot;; useEffect(() =&gt; { if (weatherResults.currentWeather || weatherResults.forecast) { setCurrentWeather(weatherResults.currentWeather); setForecast(weatherResults.forecast); const url = iconSite + weatherResults.currentWeather.icon.padStart(2, '0') + &quot;-s.png&quot; setImgUrl(url); setIsFavorite(checkIfFavorite()); } }, [weatherResults.currentWeather, weatherResults.forecast]) const checkIfFavorite = () =&gt; { if (!localStorage.weatherApp) return false; const arr = JSON.parse(localStorage[&quot;weatherApp&quot;]); const found = arr.some(e =&gt; e.cityName === cityName); return found; } const addFavorite = () =&gt; { setIsFavorite(true); let arr; if (!localStorage.weatherApp) { arr = []; } else { arr = JSON.parse(localStorage[&quot;weatherApp&quot;]); const found = arr.some(e =&gt; e.cityName === cityName); if (found) return; } arr.push({ cityKey, cityName }); localStorage[&quot;weatherApp&quot;] = JSON.stringify(arr); } const removeFavorite = () =&gt; { setIsFavorite(false); const arr = JSON.parse(localStorage[&quot;weatherApp&quot;]); const filteredArr = arr.filter(e =&gt; e.cityName !== cityName); localStorage[&quot;weatherApp&quot;] = JSON.stringify(filteredArr); } return ( &lt;div className=&quot;homeMain&quot;&gt; {currentWeather.text ? &lt;div &gt; {isFavorite ? &lt;button onClick={removeFavorite}&gt;Remove From Favorites&lt;/button&gt; : &lt;button onClick={addFavorite}&gt;Add To Favorites&lt;/button&gt; } &lt;div className=&quot;currentWeather&quot;&gt; &lt;h4&gt;{cityName}&lt;/h4&gt; &lt;img src={imgUrl} alt=&quot;icon&quot; /&gt; &lt;div&gt;{currentWeather.temperature + '\u00B0'}c&lt;/div&gt; &lt;div&gt;{currentWeather.text}&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; : null} {forecast.length ? &lt;div className=&quot;forecast&quot;&gt; {forecast.map((e, i) =&gt; { return &lt;ForecastCard key={i} high={e.high} low={e.low} day={daysOfWeek[(today + i) % 7]}&gt; &lt;/ForecastCard&gt; })} &lt;/div&gt; : null} &lt;/div&gt; ); } export default HomeMain; </code></pre> <p>ForecastCard.js - a child of HomeMain</p> <pre class="lang-js prettyprint-override"><code>import &quot;./ForecastCard.css&quot;; function ForecastCard({ day, high, low }) { return ( &lt;div className=&quot;forecastCard&quot;&gt; &lt;strong&gt;{day}&lt;/strong&gt; &lt;div&gt;H: {high + '\u00B0'}c &lt;/div&gt; &lt;div&gt;L: {low + '\u00B0'}c&lt;/div&gt; &lt;/div&gt; ); } export default ForecastCard; </code></pre> <p>The 2nd page in the app for the Favorite cities weather, a child of App.</p> <pre class="lang-js prettyprint-override"><code>import { useEffect, useState } from &quot;react&quot;; import ErrorBoundary from &quot;../ErrorBoundary&quot;; import CityCard from &quot;./CityCard&quot;; import &quot;./Favorites.css&quot;; function Favorites({ weatherCB }) { const [cityArray, setCityArray] = useState([]); useEffect(() =&gt; { if (!localStorage.weatherApp) return; setCityArray(JSON.parse(localStorage[&quot;weatherApp&quot;])); }, []) return ( &lt;div&gt; &lt;ErrorBoundary&gt; &lt;div className=&quot;favorites&quot;&gt; {cityArray.length ? cityArray.map((e, i) =&gt; { return &lt;CityCard key={i} data={e} weatherCB={weatherCB} /&gt; }) : null} &lt;/div&gt; &lt;/ErrorBoundary&gt; &lt;/div&gt; ); } export default Favorites; </code></pre> <p>CityCard.js is a child of Favorites.</p> <pre class="lang-js prettyprint-override"><code>import { useEffect, useState } from &quot;react&quot;; import { useHistory } from &quot;react-router&quot;; import { getFavoritesRequest } from &quot;../utils&quot;; import &quot;./CityCard.css&quot;; function CityCard({ data, weatherCB }) { const [resData, setResData] = useState({}); let history = useHistory(); useEffect(() =&gt; { getFavoritesRequest(data.cityKey) .then(res =&gt; setResData(res)); }, [data]) const goToDetails = () =&gt; { history.push(&quot;/&quot;); weatherCB(data.cityName, data.cityKey); } return ( &lt;div onClick={goToDetails} className=&quot;cityCard&quot;&gt; {resData.text ? &lt;div&gt; &lt;h1&gt;{data.cityName}&lt;/h1&gt; &lt;div&gt;{resData.temperature + '\u00B0'}c&lt;/div&gt; &lt;div&gt;{resData.text}&lt;/div&gt; &lt;/div&gt; : null} &lt;/div&gt; ); } export default CityCard; </code></pre> <p>Any suggestions about improving the code are welcome.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T17:49:46.173", "Id": "269708", "Score": "2", "Tags": [ "interview-questions", "react.js", "jsx", "redux" ], "Title": "Proper way of using redux and props" }
269708
<p>I'm implementing a single linked list as close as it could be to <a href="//en.cppreference.com/w/cpp/container/forward_list" rel="nofollow noreferrer"><code>std::forward_list</code></a>. I would welcome a review and also more suggestions on what to test additionally.</p> <pre><code>#ifndef LINKED_LIST_HPP #define LINKED_LIST_HPP #include &lt;iostream&gt; template &lt;typename T&gt; class LinkedList { private: struct Node { Node* next; T data; Node(T data): data(data), next(nullptr){ } }; public: struct iterator { // this should probably be const or sth Node* iterNode; // Default constructor iterator(): iterNode(nullptr) { } // Constructor from a node iterator(Node* n) : iterNode(n) { } // Dereferences and gets the value of the node const T&amp; operator*() const { return iterNode-&gt;data; } // Prefix Increment points to the next element in the LinkedList iterator* operator++() { iterNode = iterNode-&gt;next; return this; } // Compares the two nodes of each iterator bool operator !=(const iterator&amp; other) const { return iterNode!= other.iterNode; } // Is the one nodes of the iterator equal to other iterator's node bool operator ==(const iterator&amp; other) const { return iterNode== other.iterNode; } // postFix increment returns an iterator to the previous node // but points to the next element in the LinkedList iterator operator++(int) { Node* previous = iterNode; iterNode = iterNode-&gt;next; return iterator(previous); } /* iterator&amp; operator--(); iterator operator--(int); value_type&amp; operator*() const; */ }; void push_back(const T&amp; value) { Node* newNode = new Node(value); if (!headNode) { std::cout &lt;&lt; &quot;!headNode&quot; &lt;&lt; std::endl; headNode = newNode; } else { auto tmp = headNode; Node* prevTmp = nullptr; std::cout &lt;&lt; &quot;tmp&quot; &lt;&lt; std::endl; while (tmp) { prevTmp = tmp; tmp = tmp-&gt;next; } prevTmp-&gt;next = newNode; } size++; } void insert(iterator it, const T&amp; value) { Node* newNode = new Node(value); auto tmp = it.iterNode-&gt;next; it.iterNode-&gt;next = newNode; newNode-&gt;next = tmp; } iterator begin() { return iterator(headNode); } iterator end() { return iterator(nullptr); } iterator erase(iterator it) { // if deleting the first node then if this is the only element // mark headNode as nullptr and delete the element else make // the headNode point to the next element and delete the previous one. if (headNode == it.iterNode) { std::cout &lt;&lt; &quot;headNode == it.iterNode&quot; &lt;&lt; std::endl; auto nodeToDelete = it; if (size == 1) { std::cout &lt;&lt; &quot;size == 1 &quot; &lt;&lt; std::endl; headNode = nullptr; } else { std::cout &lt;&lt; &quot;size != 1 &quot; &lt;&lt; std::endl; headNode = (++it)-&gt;iterNode; } std::cout &lt;&lt; &quot;deleting&quot; &lt;&lt; nodeToDelete.iterNode-&gt;data &lt;&lt; std::endl; delete nodeToDelete.iterNode; } else { auto prev = begin(); for (auto itr = begin(); itr!=end();itr++) { if (itr == it) { prev.iterNode-&gt;next = (++itr)-&gt;iterNode; delete it.iterNode; break; } prev = itr; } } } public: LinkedList() : size(0), headNode(nullptr){ } ~LinkedList() { Node* current = headNode; while (current) { Node* next = current-&gt;next; delete current; current = next; } } private: int size; Node* headNode; }; #endif //LINKED_LIST_HPP </code></pre> <p>This is testing using the g++ framework</p> <pre><code>#include &quot;linkedlist.hpp&quot; #include &lt;gtest/gtest.h&gt; TEST(LinkedListTest, PushBackTest) { LinkedList&lt;int&gt; myList; LinkedList&lt;int&gt;::iterator it; for (int i=1; i&lt;=5; ++i) myList.push_back(i); it = myList.begin(); ASSERT_EQ(*it, 1); auto counter = 1; for (auto itr = myList.begin(); itr!=myList.end();++itr) { ASSERT_EQ(*itr, counter); counter++; } } TEST(LinkedListTest, EraseTest) { LinkedList&lt;int&gt; myList; LinkedList&lt;int&gt;::iterator it; myList.push_back(1); it = myList.begin(); // Deleting when is the only node and on the first place myList.erase(it); for (int i=2; i&lt;=5; ++i) myList.push_back(i); it = myList.begin(); auto counter = 2; // Ensure values are as expected for (auto itr = myList.begin(); itr!=myList.end();++itr) { ASSERT_EQ(*itr, counter); counter++; } // Deleting when is not the only node but is on the first place it = myList.begin(); std::cout &lt;&lt; &quot;Failing case&quot; &lt;&lt; std::endl; myList.erase(it); counter = 3; // Ensure values are as expected for (auto itr = myList.begin(); itr!=myList.end();++itr) { ASSERT_EQ(*itr, counter); counter++; } it = myList.begin(); it++; // Deleting an element from the middle and ensure everything is connected correctly myList.erase(it); counter = 3; for (auto itr = myList.begin(); itr!=myList.end();++itr) { if (counter == 4) counter++; ASSERT_EQ(*itr, counter); counter++; } } </code></pre>
[]
[ { "body": "<ol>\n<li><p>Remember the rule of three. The implicitly declared copy- and move- ctor and assignment are unsuitable for <code>LinkedList</code>.</p>\n</li>\n<li><p>Two-space indentation doesn't really stand out. Consider doubling it.</p>\n</li>\n<li><p>If you add trace-output to your code, the least you can do is keeping it out of standard output. Error / Log stream is the proper destination. Also, design it for easy disabling and / or removal. Yes, that means using the preprocessor here.</p>\n</li>\n<li><p>Avoid <code>std::endl</code>. The manual flush is nearly always superfluous, just tanking performance. If you actually need it, be explicit and use <code>std::flush</code>.<br />\nSee &quot;<em><a href=\"//stackoverflow.com/questions/5492380/what-is-the-c-iostream-endl-fiasco\">What is the C++ iostream <code>endl</code> fiasco?</a></em>&quot;.</p>\n</li>\n<li><p>If you use aggregate-initialization for your nodes, you need no custom ctor. Emplacing, move-constructing and copy-constructing would otherwise already be three ctors, or a templated one.</p>\n</li>\n<li><p>Don't make data-members public without good reason. <a href=\"//en.cppreference.com/w/cpp/language/friend\" rel=\"nofollow noreferrer\"><code>friend</code></a> can be used to selectively let some other code in.</p>\n</li>\n<li><p>Use in-class-initialization for all members you can. It simplifies your ctors.<br />\nAs a bonus, you can more often define them <code>= default;</code>, making the type trivial, which has its own benefits.</p>\n</li>\n<li><p>Comments are for describing your reasoning, the overarching design, and point out subtleties.<br />\nDon't bore your readers to tears by having them read the same thing twice, once in code and once in comment.</p>\n<p>Doc-comments which are extracted to create basic documentation must stand without the code, so should be treated a bit more lenient in this regard.</p>\n</li>\n<li><p><code>// this should probably be const or sth </code> No, really not. It is exactly as it should be. Or it would be, if you returned <code>T&amp;</code> from <code>operator*</code>.</p>\n</li>\n<li><p>Currently, you are using the specific type half the time without rhyme or reason, consider leaning more on <code>auto</code>.</p>\n</li>\n<li><p>If a function cannot throw by design, mark it <code>noexcept</code>. Others can pick it up and take advantage of the guarantee.</p>\n</li>\n<li><p>Don't fear pointing at pointers.</p>\n<p>It can significantly simplify some code:</p>\n<pre><code>template &lt;class... Xs&gt;\nvoid emplace_back(Xs&amp;&amp;...xs) {\n auto p = &amp;headNode;\n while (*p)\n p = &amp;p[0]-&gt;next;\n *p = new Node{{}, T(std::forward&lt;Xs&gt;(xs)...)}; // Using modified Node\n ++size;\n}\n</code></pre>\n</li>\n<li><p>Expand the iterators, and the list-class itself. Currently, you just have the bare basics to have something move, but it is just a beginning.</p>\n</li>\n<li><p>Upgrade to C++20:</p>\n<ul>\n<li><code>!=</code> will be synthesised from <code>==</code>, so no need to define it.</li>\n<li>Most any of your members can be made <code>constexpr</code>, allowing use at compile-time.</li>\n</ul>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T21:07:34.653", "Id": "532206", "Score": "0", "body": "_Don't make data-members public without good reason. friend can be used to selectively let some other code in._\n\nSo you're suggesting to make the struct iterator a class and have a friend getter ?\nor make struct Node a class and have friend getters? Or both ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T21:37:35.937", "Id": "532214", "Score": "0", "body": "No, I mean that you can make your list a [`friend`](//en.cppreference.com/w/cpp/language/friend). `Node` should be a private member of the list, containing only data-members." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T20:09:56.110", "Id": "269714", "ParentId": "269711", "Score": "2" } }, { "body": "<p>You need to publish <em>iterator traits</em> so you can use your class with standard algorithms! Your test code did not try passing your list's iterators to <code>std::find</code> etc. Also ensure that you can use a <code>LinkedList</code> in a range-based <code>for</code> loop.</p>\n<p>Don't write unnecessary or implicit type conversions.<br />\n<code>return iterator(headNode);</code><br />\ndoes not need the explicit construction since the <code>iterator</code> constructor is not marked <code>explicit</code>. That is,<br />\n<code>return headNode;</code><br />\nmeans the same thing.</p>\n<p>Your destructor should just call <code>clear</code> and not have to do the work directly.</p>\n<p>The guard name <code>LINKED_LIST_HPP</code> is not specific enough or unique. It could easily clash if this was used in a project with many libraries and nested library usage. If you must use such guards (<code>#pragma once</code> is supported by all the major compilers) always use a UUID or the like.</p>\n<hr />\n<p>Keep up the good work!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T16:12:39.543", "Id": "532286", "Score": "0", "body": "Considering that `.clear()` is the more rarely used one, shouldn't rather `.clear()` be defined using the dtor?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T16:18:28.043", "Id": "532287", "Score": "1", "body": "See what zwol [has to say about `#pragma once`](https://stackoverflow.com/a/34884735/3204551)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T17:30:34.887", "Id": "532296", "Score": "1", "body": "How so, @deduplicator? The only way I could imagine is to invoke the destructor and then use in-place construction to reinstate the object." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T17:38:41.300", "Id": "532297", "Score": "1", "body": "@uli `*this = LinkedList();` after defining the move-ctor. But yes, manual call to dtor +in-place-new using default-ctor would also work, as no virtual bases/functions to complicate inheritance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T17:48:32.037", "Id": "532298", "Score": "0", "body": "Interesting, @Deduplicator, I hadn't thought of that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T14:24:41.290", "Id": "532367", "Score": "0", "body": "@Deduplicator you can't write `clear` in terms of the destructor. `clear` is used when the object still exists. You literally can't call the destructor from `clear`. (using explicit destructor syntax on `this` would be a horrible thing to do in cases where that actually worked)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T14:36:35.637", "Id": "532370", "Score": "0", "body": "@JDługosz Actually, using explicit-destructor-syntax on `this` is common in COM-programming. Explicit dtor + placement-new + pretending nothing important happened is fragile though, but I don't think quite forbidden, barring reference- and const-members, as well as the dangers in not being the most-derived type. Anyway, move-assignment of or swapping with a value-initialized temporary is the way to go, as it is obviously right, and even shorter." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T15:32:23.553", "Id": "269731", "ParentId": "269711", "Score": "2" } }, { "body": "<p>What happens when you copy a <code>LinkedList</code> object? GCC warns</p>\n<pre class=\"lang-none prettyprint-override\"><code>269711.cpp:6:7: warning: ‘class LinkedList&lt;int&gt;’ has pointer data members [-Weffc++]\n 6 | class LinkedList {\n | ^~~~~~~~~~\n269711.cpp:6:7: warning: but does not declare ‘LinkedList&lt;int&gt;(const LinkedList&lt;int&gt;&amp;)’ [-Weffc++]\n269711.cpp:6:7: warning: or ‘operator=(const LinkedList&lt;int&gt;&amp;)’ [-Weffc++]\n269711.cpp:165:9: note: pointer member ‘LinkedList&lt;int&gt;::headNode’ declared here\n 165 | Node* headNode;\n | ^~~~~~~~\n</code></pre>\n<p>And I don't see any tests that involve copying.</p>\n<p>Some other warnings worth fixing:</p>\n<pre class=\"lang-none prettyprint-override\"><code>269711.cpp:36:15: warning: prefix ‘LinkedList&lt;T&gt;::iterator* LinkedList&lt;T&gt;::iterator::operator++()’ should return ‘LinkedList&lt;T&gt;::iterator&amp;’ [-Weffc++]\n 36 | iterator* operator++()\n | ^~~~~~~~\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>269711.cpp: In instantiation of ‘LinkedList&lt;T&gt;::iterator LinkedList&lt;T&gt;::erase(LinkedList&lt;T&gt;::iterator) [with T = int]’:\n269711.cpp:199:15: required from here\n269711.cpp:147:3: warning: no return statement in function returning non-void [-Wreturn-type]\n 147 | }\n | ^\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>269711.cpp: In instantiation of ‘LinkedList&lt;T&gt;::Node::Node(T) [with T = int]’:\n269711.cpp:71:21: required from ‘void LinkedList&lt;T&gt;::push_back(const T&amp;) [with T = int]’\n269711.cpp:179:44: required from here\n269711.cpp:10:7: warning: ‘LinkedList&lt;int&gt;::Node::data’ will be initialized after [-Wreorder]\n 10 | T data;\n | ^~~~\n269711.cpp:9:11: warning: ‘LinkedList&lt;int&gt;::Node* LinkedList&lt;int&gt;::Node::next’ [-Wreorder]\n 9 | Node* next;\n | ^~~~\n269711.cpp:11:5: warning: when initialized here [-Wreorder]\n 11 | Node(T data): data(data), next(nullptr){\n | ^~~~\n</code></pre>\n<p>I really recommend enabling more warnings when you compile.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T17:44:36.650", "Id": "269736", "ParentId": "269711", "Score": "2" } }, { "body": "<h2>Having Tests</h2>\n<p>Big plus! I have often wished that code I worked on would have more tests or any tests at all.</p>\n<h2>Advancing to last element</h2>\n<p>This locates the last node of the list in <code>prevTmp</code> (not a speaking name, btw) and is unnecessarily complicated:</p>\n<pre><code>auto tmp = headNode;\nNode* prevTmp = nullptr;\nwhile (tmp)\n{\n prevTmp = tmp;\n tmp = tmp-&gt;next;\n}\n</code></pre>\n<p>One thing is that you already established that <code>headNode</code> is not null (in code not shown here), so the first iteration of <code>while (tmp)</code> will always execute the loop body. With that in mind, try this instead:</p>\n<pre><code>auto tmp = headNode;\nwhile (tmp-&gt;next) {\n tmp = tmp-&gt;next;\n}\n</code></pre>\n<p>After that, you have an element where <code>tmp-&gt;next</code> is null, which is almost self-documenting a free place at the end of the linked list.</p>\n<h2>Rule of Five</h2>\n<p>Your linked list has implicitly defined copy-ctor and assignment operator, which it shouldn't have. Disable them or implement them properly.</p>\n<h2><code>push_back()</code> Method</h2>\n<p>Why have this, which is the most inefficient way to use a singly-linked list? If you look at the STL (the origin of the C++ standard library), you won't find a <code>push_front()</code> method in its <code>vector</code> container either, exactly because it is inefficient! Same for your class, just don't implement it, but implement a <code>push_front()</code> and <code>pop_front()</code> instead!</p>\n<h2><code>insert()</code> Behaviour</h2>\n<p>I believe that insertion in the STL specifies the position before (!) which you insert, so you can call <code>container.insert(value, container.end())</code>. Your version does it differently.</p>\n<p>In any case, make sure to consider inserting into an empty container at positions <code>container.begin()</code> and <code>container.end()</code> in your tests!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T19:33:14.800", "Id": "532304", "Score": "1", "body": "\"insert() Behaviour: I believe that insertion in the STL specifies the position before (!) which you insert\" Which is why the forward_list instead implements [`.insert_after()`](//en.cppreference.com/w/cpp/container/forward_list/insert_after). Actually, it has *many* changes to accommodate only having forward-iterators without sacrificing efficiency." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T17:52:13.057", "Id": "269737", "ParentId": "269711", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T18:46:30.423", "Id": "269711", "Score": "2", "Tags": [ "c++", "linked-list", "reinventing-the-wheel", "template", "iterator" ], "Title": "Single-linked-list in C++ with iterators" }
269711
<p>I made a simple battleship in C# console with a little AI ( just a little ) and The goal of this practice is improving my knowledge about OOP.</p> <p>Game Rules:</p> <p>1.You Attack To The Enemy then he Attacked You.</p> <p>2.if you do not find any ships with the help of Hint, one of your own ships will sink</p> <p>3.I Write a Simple Little Small Tiny AI. If Enemy can't find your ship in his turn he can search near and find the ships for next turn (if it is near the ship).</p> <p>4.You and your enemy just have 5 ships.</p> <p>First i put all of my code then explain about it.</p> <p>My Program Class [Main Method]:</p> <pre><code> { static void Main() { GameEngine myGameEngine = new GameEngine(); while (true) { myGameEngine.Engine(); } } } </code></pre> <p>it's very simple and clean.</p> <p>Then gameEngine Class:</p> <pre><code>class GameEngine { List&lt;char&gt; _myIsland = new List&lt;char&gt;(); List&lt;char&gt; _enemyIsland = new List&lt;char&gt;(); List&lt;char&gt; _enemyIslandCover = new List&lt;char&gt;(); bool isGenerate; int hint; int cubePosition; char saveCharacter; private Ships ships; enum Direction { Up = -10, Left = -1, Right = 1, Down = 10 } public GameEngine() { ships = new Ships(this, 5); hint = 1; } public void DrawIslands() { int Counter = 0; int HowManyTime = 0; Console.Clear(); while (true) { HowManyTime += 10; while (Counter &lt; HowManyTime) { Console.Write(&quot;{0} &quot;, _myIsland[Counter]); Counter++; } Console.Write(&quot;║ &quot;); Counter -= 10; while (Counter &lt; HowManyTime) { Console.Write(&quot;{0} &quot;, _enemyIslandCover[Counter]); Counter++; } Console.WriteLine(); if (HowManyTime == 100) { break; } } } private void ShowInformation() { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(&quot;░ YOUR SHIPS: {0} \t ENEMY's SHIP: {1} \t HINT: {2}&quot;, ships.YourShip, ships.EnemyShip, hint); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(&quot;░ 1. ATTACK \t 2. HINT \t 3. EXIT&quot;); Console.ForegroundColor = ConsoleColor.White; } public void Engine() { if (!isGenerate) { FirstTimeGenerate(); } DrawIslands(); ShowInformation(); string userInput = GetString(&quot;░ Choose a number &gt; &quot;); switch (userInput) { case &quot;1&quot;: cubePosition = 0; saveCharacter = _enemyIslandCover[cubePosition]; _enemyIslandCover[cubePosition] = '■'; DrawIslands(); bool isEnter = false; while (!isEnter) { ConsoleKeyInfo readKey = Console.ReadKey(); switch (readKey.Key) { case ConsoleKey.UpArrow: Move(Direction.Up); break; case ConsoleKey.DownArrow: Move(Direction.Down); break; case ConsoleKey.RightArrow: Move(Direction.Right); break; case ConsoleKey.LeftArrow: Move(Direction.Left); break; case ConsoleKey.Enter: isEnter = true; bool result = ships.Attack(_enemyIsland, _enemyIslandCover , cubePosition); if (result) { GetSucces(&quot;You Sink One of the Enemy's Ship!! POWER&quot;); if (hint == 0) { hint++; } HasAnyoneWon(); } else { GetError(&quot;DAMN IT ADMIRAL!!!&quot;); } break; } } ships.EnemyAttack(_myIsland); HasAnyoneWon(); break; case &quot;2&quot;: if (hint == 1) { string userChoice = GetString(&quot;Are you sure for use hint [PRESS Y]? (if there is no ship in row, One of your ship will sink)&quot;); if (userChoice == &quot;y&quot;) { bool result = ships.Hint(_enemyIsland, _enemyIslandCover); hint = 0; if (!result) { for (int i = 0; i &lt; 3; i++) { int index = _myIsland.LastIndexOf('@'); _myIsland.RemoveAt(index); _myIsland.Insert(index, '░'); } DrawIslands(); HasAnyoneWon(); } } else { break; } } else { GetError(&quot;You have no any hint.&quot;); } break; case &quot;3&quot;: Console.Clear(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(&quot;Thank you for choose my game. See you later&quot;); Console.ForegroundColor = ConsoleColor.White; Environment.Exit(0); break; default: GetError(&quot;You Put Wrong Value!&quot;); break; } } private void FirstTimeGenerate() { for (int i = 0; i &lt; 100; i++) { _myIsland.Add('■'); _enemyIsland.Add('■'); _enemyIslandCover.Add('·'); } ships.GenerateShips(_myIsland); ships.GenerateShips(_enemyIsland); isGenerate = true; } private void Move(Direction dir) { _enemyIslandCover[cubePosition] = saveCharacter; cubePosition += (int)dir; if (cubePosition &gt; 0 &amp;&amp; cubePosition &lt; 100) { saveCharacter = _enemyIslandCover[cubePosition]; _enemyIslandCover[cubePosition] = '■'; DrawIslands(); } else { GetError(&quot;You Can't Move Outer the Field&quot;); cubePosition = 0; } } private void HasAnyoneWon() { if (ships.EnemyShip == 0 || ships.YourShip == 0) { int Counter = 0; int HowManyTime = 0; Console.Clear(); while (true) { HowManyTime += 10; while (Counter &lt; HowManyTime) { Console.Write(&quot;{0} &quot;, _myIsland[Counter]); Counter++; } Console.Write(&quot;║ &quot;); Counter -= 10; while (Counter &lt; HowManyTime) { Console.Write(&quot;{0} &quot;, _enemyIsland[Counter]); Counter++; } Console.WriteLine(); if (HowManyTime == 100) { break; } } if (ships.EnemyShip == 0) { GetSucces(&quot;YOU WON ADMIRAL! WE BACK TO THE COUNTRY AND TELL TO PEOPLE ABOUT YOUR BRAVE!!!! HOOOOOOOOOORAY&quot;); } else { GetError(&quot;YOU LOOSE ADMIRAL! DON'T BE UPSET. PLAY GAME AGAIN!&quot;); } Environment.Exit(0); } } // STATIC METHOD - ONCE WRITE EVERYWHERE USE public static string GetString(string message) { Console.ForegroundColor = ConsoleColor.Cyan; Console.Write(message.ToLower()); Console.ForegroundColor = ConsoleColor.White; return Console.ReadLine(); } public static void GetError(string message) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(message); Console.ForegroundColor = ConsoleColor.White; Thread.Sleep(3000); } public static void GetSucces(string message) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(message); Console.ForegroundColor = ConsoleColor.White; Thread.Sleep(2000); } } </code></pre> <p>And my last class named Ships because this class generate and create ships and all of things about ships :</p> <pre><code>class Ships { public int YourShip { get; set; } public int EnemyShip { get; set; } int indexOfAI = 0; private GameEngine gameEnigne; public Ships(GameEngine gameEngine, int howManyShip) { this.gameEnigne = gameEngine; YourShip = howManyShip; EnemyShip = howManyShip; } public void GenerateShips(List&lt;char&gt; island) { int counter = 0; Random randomGenerator = new Random(); while (true) { if (counter == YourShip) { break; } int index = randomGenerator.Next(0, island.Count); if (FindBestPlace(index, island)) { island[index] = '@'; island[index - 1] = '@'; island[index + 1] = '@'; counter++; } else { continue; } } } private bool FindBestPlace(int index, List&lt;char&gt; island) { try { int Counter = index - (index % 10); for (int i = Counter; i &lt; Counter + 10; i++) { if (island[i] != '■') { return false; } } if (index % 10 &gt; 2 &amp;&amp; index % 10 &lt; 9) { return true; } else { return false; } } catch { return false; } } public bool Hint(List&lt;char&gt; enemyIsland, List&lt;char&gt; enemyIslandCover) { Random rnd = new Random(); int index = 0; bool sunkenShip = false; bool thereIsAnyShip = false; while (!sunkenShip) { index = enemyIsland.Count / 10 * (rnd.Next(0, 10)); sunkenShip = true; thereIsAnyShip = false; for (int i = index; i &lt; index + 10; i++) { if (enemyIsland[i] == '░') { sunkenShip = false; break; } if (enemyIsland[i] == '@') { thereIsAnyShip = true; } } } for (int i = index; i &lt; index + 10; i++) { enemyIslandCover[i] = enemyIsland[i]; } gameEnigne.DrawIslands(); Thread.Sleep(1000); for (int i = index; i &lt; index + 10; i++) { enemyIslandCover[i] = '·'; } gameEnigne.DrawIslands(); if (!thereIsAnyShip) { YourShip--; } return thereIsAnyShip; } public bool Attack(List&lt;char&gt; enemyIsland, List&lt;char&gt; enemyIslandCover, int cubePosition) { if (enemyIsland[cubePosition] == '@') { int rowIndex = cubePosition - (cubePosition % 10); for (int i = rowIndex; i &lt; rowIndex + 10; i++) { if (enemyIsland[i] == '@') { enemyIsland[i] = '░'; enemyIslandCover[i] = '░'; } } gameEnigne.DrawIslands(); EnemyShip--; return true; } else { enemyIslandCover[cubePosition] = '%'; return false; } } public void EnemyAttack(List&lt;char&gt; MyIsland) { GameEngine.GetError(&quot;It's Turn of enemy | HIDE HIDE HIIIIIIIDE !!!! &quot;); int index; Random rnd = new Random(); if (indexOfAI &gt; 0) { if (indexOfAI &lt; 70) { index = rnd.Next(indexOfAI, indexOfAI + 30); } else { index = rnd.Next(indexOfAI, MyIsland.Count); } } else { index = rnd.Next(0, MyIsland.Count); } char saveChar = MyIsland[index]; MyIsland[index] = 'Ö'; gameEnigne.DrawIslands(); GameEngine.GetError(&quot;Enemy Choose His Location!! DON'T MOVE!! Sheeeeesh&quot;); MyIsland[index] = saveChar; bool isThereAnyShip = false; if (MyIsland[index] == '@') { int Counter = index - (index % 10); for (int i = Counter; i &lt; Counter + 10; i++) { if (MyIsland[i] == '@') { MyIsland[i] = '░'; isThereAnyShip = true; } } } gameEnigne.DrawIslands(); if (isThereAnyShip) { YourShip--; GameEngine.GetError(&quot;Enemy Sink One Of Your Ship Admiral, What's The Next Order ?&quot;); indexOfAI = 0; } else { GameEngine.GetSucces(&quot;The danger was eliminated. The enemy does not know the location of our ship!!&quot;); if (indexOfAI == 0) { SimpleEnemyAI(index, MyIsland); } else { indexOfAI = 0; } } } private void SimpleEnemyAI(int index , List&lt;char&gt; Island) { // it's a algorithm for Simple AI if (index &gt; 10) { index = index - (index % 10) - 10; } bool isAnyShipFind = false; if (index &lt; 70) { for (int i = index; i &lt; index + 20; i++) { if (Island[i] == '@') { indexOfAI = index; isAnyShipFind = true; break; } } } else { for (int i = index; i &lt; Island.Count; i++) { if (Island[i] == '@') { indexOfAI = index; isAnyShipFind = true; break; } } } if (isAnyShipFind) { GameEngine.GetError(&quot;But Careful! Enemy Have Radar And He Saw Vague Things In It!!&quot;); } else { indexOfAI = 0; } } } </code></pre> <p>Explain:</p> <p>first i create a class and named it GameEngine and Create a object from Ships Class and leave it NULL and create a constructor for it:</p> <pre><code> private Ships ships; public GameEngine() { ships = new Ships(this, 5); hint = 1; } </code></pre> <p>i refrenced ships to a new Ship and send to it this Class as a object (i send exactly this game engine refrence and didn't create a new GameEngine because if i create a new GameEngine object then i can't access to the filled lists)</p> <p>with this way ( thanks again from @aepot) i can access to the Ships Member And send a GameEngine object to the Ships Class and magicly i can access to the GameEngine Members in the ships class because i send a object from GameEngine to the Ships class. then i send 5 instead dynamic parameter to the Ships Constructor. That number is about the number of enemy ships and ourselves ( I could have made it dynamic, but I focused more on the game so i send a const number like 5 ) see:</p> <pre><code> public int YourShip { get; set; } public int EnemyShip { get; set; } int indexOfAI = 0; private GameEngine gameEnigne; public Ships(GameEngine gameEngine, int howManyShip) { this.gameEnigne = gameEngine; YourShip = howManyShip; EnemyShip = howManyShip; } </code></pre> <blockquote> <p>i explain about indexOfAI.</p> </blockquote> <p>i made three list. one of them is my Island or sea. One of them is enemy's Island or sea. And the last one is enemy's island but i covered it by dot because we haven't any permission to see the Enemy's island with details.</p> <pre><code> List&lt;char&gt; _myIsland = new List&lt;char&gt;(); List&lt;char&gt; _enemyIsland = new List&lt;char&gt;(); List&lt;char&gt; _enemyIslandCover = new List&lt;char&gt;(); </code></pre> <p>then i write a FirstTimeGenerate Method And Call it in to the Engine Method:</p> <pre><code>private void FirstTimeGenerate() { for (int i = 0; i &lt; 100; i++) { _myIsland.Add('■'); _enemyIsland.Add('■'); _enemyIslandCover.Add('·'); } ships.GenerateShips(_myIsland); ships.GenerateShips(_enemyIsland); isGenerate = true; } </code></pre> <p>in the FirstTimeGenerate you see GenerateShips Method.This method and FindBestPlace put ships in the island or sea:</p> <pre><code> public void GenerateShips(List&lt;char&gt; island) { int counter = 0; Random randomGenerator = new Random(); while (true) { if (counter == YourShip) { break; } int index = randomGenerator.Next(0, island.Count); if (FindBestPlace(index, island)) { island[index] = '@'; island[index - 1] = '@'; island[index + 1] = '@'; counter++; } else { continue; } } } </code></pre> <p>FindBestPlaceMethod:</p> <pre><code> private bool FindBestPlace(int index, List&lt;char&gt; island) { try { int Counter = index - (index % 10); for (int i = Counter; i &lt; Counter + 10; i++) { if (island[i] != '■') { return false; } } if (index % 10 &gt; 2 &amp;&amp; index % 10 &lt; 9) { return true; } else { return false; } } catch { return false; } } </code></pre> <p>FindBestPlace Search in the island and generate random number if the number of row is empty ( there is no ship in row) then create a ship otherwise search again and generate number again.</p> <p>after that i create method for Draw the island and show information like user Choice and Score etc.</p> <pre><code> public void DrawIslands() { int Counter = 0; int HowManyTime = 0; Console.Clear(); while (true) { HowManyTime += 10; while (Counter &lt; HowManyTime) { Console.Write(&quot;{0} &quot;, _myIsland[Counter]); Counter++; } Console.Write(&quot;║ &quot;); Counter -= 10; while (Counter &lt; HowManyTime) { Console.Write(&quot;{0} &quot;, _enemyIslandCover[Counter]); Counter++; } Console.WriteLine(); if (HowManyTime == 100) { break; } } } private void ShowInformation() { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(&quot;░ YOUR SHIPS: {0} \t ENEMY's SHIP: {1} \t HINT: {2}&quot;, ships.YourShip, ships.EnemyShip, hint); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(&quot;░ 1. ATTACK \t 2. HINT \t 3. EXIT&quot;); Console.ForegroundColor = ConsoleColor.White; } </code></pre> <p>In this algorithm, first 10 Steps from our own sea are displayed, then a distance and 10 Steps from the enemy's sea (note that in the enemy's sea we only see points because we have no right to access the location of the enemy ship)</p> <p>then i wrote Hint Method but first look at engine of hint:</p> <pre><code> case &quot;2&quot;: if (hint == 1) { string userChoice = GetString(&quot;Are you sure for use hint [PRESS Y]? (if there is no ship in row, One of your ship will sink)&quot;); if (userChoice == &quot;y&quot;) { bool result = ships.Hint(_enemyIsland, _enemyIslandCover); hint = 0; if (!result) { for (int i = 0; i &lt; 3; i++) { int index = _myIsland.LastIndexOf('@'); _myIsland.RemoveAt(index); _myIsland.Insert(index, '░'); } DrawIslands(); HasAnyoneWon(); } } else { break; } } else { GetError(&quot;You have no any hint.&quot;); } break; </code></pre> <p>Hint Method:</p> <pre><code> public bool Hint(List&lt;char&gt; enemyIsland, List&lt;char&gt; enemyIslandCover) { Random rnd = new Random(); int index = 0; bool sunkenShip = false; bool thereIsAnyShip = false; while (!sunkenShip) { index = enemyIsland.Count / 10 * (rnd.Next(0, 10)); sunkenShip = true; thereIsAnyShip = false; for (int i = index; i &lt; index + 10; i++) { if (enemyIsland[i] == '░') { sunkenShip = false; break; } if (enemyIsland[i] == '@') { thereIsAnyShip = true; } } } for (int i = index; i &lt; index + 10; i++) { enemyIslandCover[i] = enemyIsland[i]; } gameEnigne.DrawIslands(); Thread.Sleep(1000); for (int i = index; i &lt; index + 10; i++) { enemyIslandCover[i] = '·'; } gameEnigne.DrawIslands(); if (!thereIsAnyShip) { YourShip--; } return thereIsAnyShip; } </code></pre> <p>if user Choose 2 Hint Method Run But first i put some expression for user: first of all check user have hint or not. then i ask a question are you sure for use your hint, because if you use it and don't find any ship you lose your ship. then i send List of Enemy island and list of cover. in Hint method, a random number will be create and check if the row of random number have a sink ship again search for the new row and create new random number.</p> <p>then if you press 1 and if it's your turn you can attack</p> <pre><code> case &quot;1&quot;: cubePosition = 0; saveCharacter = _enemyIslandCover[cubePosition]; _enemyIslandCover[cubePosition] = '■'; DrawIslands(); bool isEnter = false; while (!isEnter) { ConsoleKeyInfo readKey = Console.ReadKey(); switch (readKey.Key) { case ConsoleKey.UpArrow: Move(Direction.Up); break; case ConsoleKey.DownArrow: Move(Direction.Down); break; case ConsoleKey.RightArrow: Move(Direction.Right); break; case ConsoleKey.LeftArrow: Move(Direction.Left); break; case ConsoleKey.Enter: isEnter = true; bool result = ships.Attack(_enemyIsland, _enemyIslandCover , cubePosition); if (result) { GetSucces(&quot;You Sink One of the Enemy's Ship!! POWER&quot;); if (hint == 0) { hint++; } HasAnyoneWon(); } else { GetError(&quot;DAMN IT ADMIRAL!!!&quot;); } break; } } ships.EnemyAttack(_myIsland); HasAnyoneWon(); break; </code></pre> <p>at the first i put the cursor or point on the first of enemy's sea ( On Zero ). then you can move the curser real time with this method and enum:</p> <p>Enum :</p> <pre><code> enum Direction { Up = -10, Left = -1, Right = 1, Down = 10 } </code></pre> <blockquote> <p>Up = -10 means if you choose up cursor move -10 step back on the list and ...</p> </blockquote> <p>Move Method:</p> <pre><code> private void Move(Direction dir) { _enemyIslandCover[cubePosition] = saveCharacter; cubePosition += (int)dir; if (cubePosition &gt; 0 &amp;&amp; cubePosition &lt; 100) { saveCharacter = _enemyIslandCover[cubePosition]; _enemyIslandCover[cubePosition] = '■'; DrawIslands(); } else { GetError(&quot;You Can't Move Outer the Field&quot;); cubePosition = 0; } } </code></pre> <p>in this method i save the next house character that the square is going to occupy in saveCharacter variable, which I previously defined outside of this method and in the same class.</p> <p>then if you press enter you can attack on the square house:</p> <pre><code> case ConsoleKey.Enter: isEnter = true; bool result = ships.Attack(_enemyIsland, _enemyIslandCover , cubePosition); if (result) { GetSucces(&quot;You Sink One of the Enemy's Ship!! POWER&quot;); if (hint == 0) { hint++; } HasAnyoneWon(); } else { GetError(&quot;DAMN IT ADMIRAL!!!&quot;); } break; </code></pre> <p>i send lists of enemy and cube position ( index of cube ). in the attack method i wrote a algorithm. if i exactly shot on the ship then ship sink and Enemy lose an score otherwise nothing happend and just a sign displayed that is '%' and it's because you remember you shot this location</p> <pre><code> public bool Attack(List&lt;char&gt; enemyIsland, List&lt;char&gt; enemyIslandCover, int cubePosition) { if (enemyIsland[cubePosition] == '@') { int rowIndex = cubePosition - (cubePosition % 10); for (int i = rowIndex; i &lt; rowIndex + 10; i++) { if (enemyIsland[i] == '@') { enemyIsland[i] = '░'; enemyIslandCover[i] = '░'; } } gameEnigne.DrawIslands(); EnemyShip--; return true; } else { enemyIslandCover[cubePosition] = '%'; return false; } } </code></pre> <p>this is exactly happend when enemy attack but with few diffrent. look:</p> <pre><code> public void EnemyAttack(List&lt;char&gt; MyIsland) { GameEngine.GetError(&quot;It's Turn of enemy | HIDE HIDE HIIIIIIIDE !!!! &quot;); int index; Random rnd = new Random(); if (indexOfAI &gt; 0) { if (indexOfAI &lt; 70) { index = rnd.Next(indexOfAI, indexOfAI + 30); } else { index = rnd.Next(indexOfAI, MyIsland.Count); } } else { index = rnd.Next(0, MyIsland.Count); } char saveChar = MyIsland[index]; MyIsland[index] = 'Ö'; gameEnigne.DrawIslands(); GameEngine.GetError(&quot;Enemy Choose His Location!! DON'T MOVE!! Sheeeeesh&quot;); MyIsland[index] = saveChar; bool isThereAnyShip = false; if (MyIsland[index] == '@') { int Counter = index - (index % 10); for (int i = Counter; i &lt; Counter + 10; i++) { if (MyIsland[i] == '@') { MyIsland[i] = '░'; isThereAnyShip = true; } } } gameEnigne.DrawIslands(); if (isThereAnyShip) { YourShip--; GameEngine.GetError(&quot;Enemy Sink One Of Your Ship Admiral, What's The Next Order ?&quot;); indexOfAI = 0; } else { GameEngine.GetSucces(&quot;The danger was eliminated. The enemy does not know the location of our ship!!&quot;); if (indexOfAI == 0) { SimpleEnemyAI(index, MyIsland); } else { indexOfAI = 0; } } } </code></pre> <p>enemy generate a random house of my island or sea and shot it if it's shot exactly on my ships then my score decreases but if he can't shot my ship then a method run named SimpleEnemyAI(). this method find near the shot and look at my ship. if there is ship in the area then set the enemy index closer.</p> <p>SimpleEnemyAI Method:</p> <pre><code> private void SimpleEnemyAI(int index , List&lt;char&gt; Island) { // it's a algorithm for Simple AI if (index &gt; 10) { index = index - (index % 10) - 10; } bool isAnyShipFind = false; if (index &lt; 70) { for (int i = index; i &lt; index + 20; i++) { if (Island[i] == '@') { indexOfAI = index; isAnyShipFind = true; break; } } } else { for (int i = index; i &lt; Island.Count; i++) { if (Island[i] == '@') { indexOfAI = index; isAnyShipFind = true; break; } } } if (isAnyShipFind) { GameEngine.GetError(&quot;But Careful! Enemy Have Radar And He Saw Vague Things In It!!&quot;); } else { indexOfAI = 0; } } </code></pre> <p>And in order for the game not to be difficult, if you pay attention to the method, you will realize that this does not happen every time.</p> <p>This was my exercise. I would be very grateful if you could please remind me of my problems and if there is anything that will improve me.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T12:27:20.503", "Id": "532259", "Score": "0", "body": "Why do you randomly switch the casing of your variable names? One minute your pascal casing (i.e. `Counter`) and the next you're camel casing (i.e. `index`, `indexOfAI`, etc). General standard is to have local variables and parameters be camelCased and have classes, member variables, etc be PascalCased." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T12:29:54.817", "Id": "532260", "Score": "0", "body": "It would be nice if you can include a section with the entire code. I like to see what the program is doing before commenting and having to copy/paste all the sections together is tedious :-)" } ]
[ { "body": "<p>Try to pay attention to how do you name things, because it's really important when other people read your code</p>\n<h4>Method names :</h4>\n<p>method names should <strong>always be a verb not a noun</strong>, because the method do things</p>\n<ul>\n<li><p><code>myGameEngine.Engine()</code> should be <code>myGameEngine.startEngine()</code> or <code>myGameEngine.runEngine()</code> or simply <code>myGameEngine.start()</code></p>\n</li>\n<li><p><code>FirstTimeGenerate()</code> should be <code>GenerateFirstTime()</code> or more clear name should be <code>GenerateFirstFram()</code></p>\n</li>\n<li><p><code>Hint()</code> should be <code>displayHint()</code> or <code>PrintHint()</code></p>\n</li>\n</ul>\n<h4>Properties names :</h4>\n<p>Field names should be a <strong>descriptive noun</strong> and doesn't use pronouns [your, my his, ...etc.]</p>\n<ul>\n<li><p><code>_myIsland</code> should be more descriptive like <code>_userIsland</code></p>\n</li>\n<li><p><code>YourShip</code> you use as a counter for user ships count, so you should name it <code>UserShipsCount</code>, similar to <code>EnemyShip</code> should be <code>EnemyShipsCount</code></p>\n</li>\n<li><p><code>hint</code> in GameEngine class should be <code>hintCounter</code> or be more descriptive <code>displayedHintCounter</code></p>\n</li>\n</ul>\n<hr />\n<p>in the following peace</p>\n<pre><code>private bool FindBestPlace(int index, List&lt;char&gt; island)\n{\n try\n {\n int Counter = index - (index % 10); // &lt;&lt; what is 10 \n for (int i = Counter; i &lt; Counter + 10; i++)\n {\n if (island[i] != '■')\n {\n return false;\n }\n }\n if (index % 10 &gt; 2 &amp;&amp; index % 10 &lt; 9)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n catch\n {\n return false;\n }\n}\n</code></pre>\n<p>I don't know what is number <strong>10</strong> represent in this context, you should not use plain number in your code, instead you can define a constant and use it</p>\n<pre><code>const int ROW_LENTH = 10; \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T16:19:11.127", "Id": "532288", "Score": "0", "body": "Thanks for your explanation. \nint Counter = index - (index % 10); in this row of code i divide the remainder of the index by 10 and subtract it from the index. Think of it as 57. 57 divided by the remaining 10 is equal to 7. 7 minus 57 is 50. This was actually a way to get a rounded number so I could check a row completely (for example from 50 to 60) to see if there was a ship in that row. But I understand what you mean by using const. Thanks for the help" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T19:13:19.553", "Id": "532302", "Score": "1", "body": "@CarlJohnson, reviewers will sometimes use a rhetorical question to guide your thinking, no explanation is really required =)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T11:42:38.943", "Id": "269727", "ParentId": "269715", "Score": "2" } }, { "body": "<h1>Use meaningful names</h1>\n<p>I have to agree with Ibram, the way you name things is a bit confusing.</p>\n<p>What is <code>GetError</code> supposed to do? A better name would have been <code>ShowError</code>.</p>\n<p>The same goes for <code>GetSucces</code>. Why not rather <code>ShowSuccessMessage</code>.</p>\n<h1>Infinite loops</h1>\n<p>In <code>HasAnyoneWon</code> you have an infinite loop but break out when <code>HowManyTime</code> reaches 100. The following would have been more readable:</p>\n<pre><code>while (HowManyTime &lt; 100)\n{\n // ...\n}\n</code></pre>\n<p>The same applies to <code>GenerateShips</code>:</p>\n<pre><code>public void GenerateShips(List&lt;char&gt; island)\n{\n int counter = 0;\n var randomGenerator = new Random();\n while (counter &lt; YourShip)\n {\n int index = randomGenerator.Next(0, island.Count);\n if (FindBestPlace(index, island))\n {\n island[index] = '@';\n island[index - 1] = '@';\n island[index + 1] = '@';\n counter++;\n }\n }\n}\n</code></pre>\n<h1>Splitting complexities into functions</h1>\n<p>You have way too much going on in <code>void Engine()</code>. I would suggest that you split it up into the following functions:</p>\n<pre><code>void Attach()\n{\n // ...\n}\n\nvoid ShowHint()\n{\n // ...\n}\n\nvoid ExitGame()\n{\n // ...\n}\n\npublic void Engine()\n{\n if (!isGenerate)\n {\n FirstTimeGenerate();\n }\n DrawIslands();\n ShowInformation();\n string userInput = GetString(&quot;░ Choose a number &gt; &quot;);\n\n switch (userInput)\n {\n case &quot;1&quot;:\n Attach();\n break;\n\n case &quot;2&quot;:\n ShowHint();\n break;\n\n case &quot;3&quot;:\n ExitGame();\n break;\n\n default:\n GetError(&quot;You Put Wrong Value!&quot;);\n break;\n }\n}\n</code></pre>\n<h1>Screen flickering</h1>\n<p>The game looks much more polished without the flickering that is caused by <code>Console.Clear()</code>. I would suggest that you rather use <code>Console.SetCursorPosition</code> and overwrite the necessary text.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T16:24:20.323", "Id": "532289", "Score": "0", "body": "thank you for the help." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T14:01:08.083", "Id": "269730", "ParentId": "269715", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T20:35:11.650", "Id": "269715", "Score": "1", "Tags": [ "c#", "game", "console" ], "Title": "I Made a Simple BattleShip Game On C# Console" }
269715
<h2>Updated previously posted string struct and utility functions</h2> <p>Previous link: <a href="https://codereview.stackexchange.com/questions/269062/user-friendly-string-struct-and-utility-functions/">User-friendly string struct and utility functions</a></p> <h4>What is updated ?</h4> <ul> <li>typedef of sstring is a major update. previously, users had to do sstring var; and then var._str = value, But now, users can do sstring var = &quot;Value&quot;;</li> <li>Buffer overflows have been fixed</li> <li>major bugs and features have been improved and fixed</li> <li>All functions now have error checking methods</li> <li>conversion from c-style array strings to sstrings and vice-versa is now easily possible through sstr2cstr() and cstr2sstr() functions!</li> <li>conversion from string to number [double/float/int] type is easily possible. It has some unique things such as it can tell if the string is a number, if an error has occured and returns the actual number!</li> <li>Sstrinputpass() introduces new type of password input method!</li> <li>All functions have slight improvements</li> </ul> <p>Any suggestions, bug-report or feedbacks are Happily Welcomed!</p> <h4>- Files -</h4> <p>sstring.h</p> <pre class="lang-c prettyprint-override"><code>#ifndef SSTRING_H_DEFINED //stdbool for sstrnum typedef #include&lt;stdbool.h&gt; #define SSTRING_H_DEFINED //define the maximum char limit here #define GLOBAL_MAX_CHAR_LIMIT 400 #define NO_ERR -1 #define GMCL_CORRUPT -10 #define INVALID_ARGS -11 #define GMCL_ERR -12 typedef struct{ double _num; bool is_num; int _err; }sstrnum; typedef char * sstring; typedef struct{ char _str[GLOBAL_MAX_CHAR_LIMIT]; int _err; }sstrfunc; typedef struct{ char _char; int _err; }charfunc; typedef sstrfunc sstrfuncerr; void nullify(char * _Buff,int _count); sstrnum sstr2num(sstring _str); sstrfunc cstr2sstr(char * _Buff); int sstr2cstr(sstring _sstr,char * _Cstr,size_t _upto); sstrfunc sstrappend(sstring _var1,sstring _var2); sstrfunc sstrinput(); ssize_t sstrfind(size_t init,sstring _str,sstring _find); size_t sstrlen(sstring _str); sstrfunc ssetchar(sstring _str,ssize_t _pos,char _ch); sstrfunc ssubstr(sstring _str,int _pos,size_t _len); charfunc sgetchar(sstring _str,ssize_t _pos); sstrfunc sstrinputpass(sstring show); void showerrs(); #endif </code></pre> <p>sstring.c</p> <pre class="lang-c prettyprint-override"><code>#include&lt;stdio.h&gt; #include&lt;string.h&gt; #include &quot;sstring.h&quot; #include&lt;stdbool.h&gt; #include&lt;conio.h&gt; #include&lt;stdlib.h&gt; #include&lt;math.h&gt; /* A Big Note To the ones saying dont return Local Variable Adresses Below functions dont return any local variable addresses to prove it, call the functions MULTIPLE times -&gt; you will see yourself They return a typedef of strfunc which contains the string in array format when the user does [functionname]([parameters])._str; the str array value is sent to the pointer so no issue will be created! :D */ size_t sstrlen(sstring _str){ //just as support for sstrings // all functions included are better! return strlen(_str); } bool isGMCLCorrupt(){ //checks if global max char limit is corrupted if(GLOBAL_MAX_CHAR_LIMIT&lt;=0){ return true; }else{ return false; } } sstrfunc cstr2sstr(char * _Buff){ sstrfunc _null; nullify(_null._str,GLOBAL_MAX_CHAR_LIMIT); _null._err = NO_ERR; if(isGMCLCorrupt()){ _null._err = GMCL_CORRUPT; return _null; } if(strlen(_Buff)&gt;=GLOBAL_MAX_CHAR_LIMIT){ _null._err = GMCL_ERR; return _null; } //blank string if(strlen(_Buff)==0){ return _null; } sstrfunc _ret; strncpy(_ret._str,_Buff,strlen(_Buff)); _ret._err = NO_ERR; return _ret; } int sstr2cstr(sstring _sstr,char * _Cstr,size_t _upto){ //first null out the _Cstr upto given length nullify(_Cstr,_upto); if(isGMCLCorrupt()){ return GMCL_CORRUPT; } if(sstrlen(_sstr)&gt;=GLOBAL_MAX_CHAR_LIMIT){ return GMCL_ERR; } //blank string if(sstrlen(_sstr)==0){ return NO_ERR; } strncpy(_Cstr,_sstr,_upto); return NO_ERR; } sstrnum sstr2num(sstring _str){ char cchar; int minus = 1; int plus=0; sstrnum _return; int pointplace=0; _return._err = NO_ERR; _return.is_num = true; if(isGMCLCorrupt()){ _return._err = GMCL_CORRUPT; _return._num = 0; _return.is_num = false; return _return; }else if(sstrlen(_str)&gt;=GLOBAL_MAX_CHAR_LIMIT){ _return._err = GMCL_ERR; _return._num = 0; _return.is_num = false; return _return; } for(int i=0;i&lt;sstrlen(_str);i++){ cchar = _str[i]; //if non integer found if(cchar&lt;'0'||cchar&gt;'9'){ if(cchar=='-'&amp;&amp;i==0){ minus = -1; }else if(cchar=='-'&amp;&amp;i&gt;0){ _return._num = 0; _return.is_num = false; _return._err = NO_ERR; return _return; }else if(cchar=='.'&amp;&amp;pointplace==0){ pointplace+=1; }else if(cchar=='.'&amp;&amp;!(pointplace==0)){ _return._num = 0; _return.is_num = false; _return._err = NO_ERR; return _return; }else if(cchar=='+'&amp;&amp;plus==0){ plus=1; }else if(cchar=='+'&amp;&amp;plus==1){ _return._num = 0; _return.is_num = false; _return._err = NO_ERR; return _return; }else{ _return._num = 0; _return.is_num = false; _return._err = NO_ERR; return _return; } }else{ if(i==0){ _return._num =cchar-'0'; }else{ if(pointplace){ _return._num+= (cchar-'0')/pow(10,pointplace); pointplace+=1; }else{ _return._num*=10; _return._num+= (cchar-'0'); } } } } _return._num*=minus; return _return; } sstrfunc ssubstr(sstring _str,int _pos,size_t _len){ //dont store anything make null return value sstrfunc _null; //is global max char limit corrupted?? //returning null means error was caught! if(isGMCLCorrupt()){ //gmcl is corrupt! errcode: #defined in sstring.h _null._err = GMCL_CORRUPT; return _null; } if(_pos&lt;0){ _null._err = INVALID_ARGS; return _null; } if(sstrlen(_str)&gt;=GLOBAL_MAX_CHAR_LIMIT||_pos&gt;=GLOBAL_MAX_CHAR_LIMIT||_len&gt;=GLOBAL_MAX_CHAR_LIMIT){ _null._err = GMCL_ERR; return _null; } if(_pos&gt;=sstrlen(_str)||_pos&lt;0||_len&gt;=sstrlen(_str)||_len&lt;0){ _null._err = INVALID_ARGS; return _null; } sstrfunc _ret; _ret._err = NO_ERR; strncpy(_ret._str,_str+_pos,_len); _ret._str[_len] = '\0'; return _ret; } sstrfunc sstrappend(sstring _var1,sstring _var2){ //dont store anything make null return value sstrfunc _null; //is global max char limit corrupted?? //returning null means error was caught! if(isGMCLCorrupt()){ //gmcl is corrupt! errcode: #defined in sstring.h _null._err = GMCL_CORRUPT; return _null; } if(sstrlen(_var1)+sstrlen(_var2)&gt;=GLOBAL_MAX_CHAR_LIMIT){ _null._err = GMCL_ERR; return _null; } //use of string.h functions -&gt; far easier than my previous headscratching! char _ret1[sstrlen(_var1)+sstrlen(_var2)]; strcpy(_ret1,_var1); strcat(_ret1,_var2); sstrfunc _ret; //no errors :D _ret._err = NO_ERR; strcpy(_ret._str,_ret1); return _ret; } void nullify(char * _Buff,int _count){ if(isGMCLCorrupt()){ exit(GMCL_CORRUPT); }else if(_count&gt;GLOBAL_MAX_CHAR_LIMIT+1){ exit(GMCL_ERR); }else{ for(int i=0;i&lt;_count+1;i++){ _Buff[i] = '\0'; } } } sstrfunc sstrinput(){ //dont store anything make null return value sstrfunc _null; //is global max char limit corrupted?? //returning null means error was caught! if(isGMCLCorrupt()){ _null._err = GMCL_CORRUPT; return _null; } char _tmp[GLOBAL_MAX_CHAR_LIMIT]; //fgets for safety :) fgets(_tmp,GLOBAL_MAX_CHAR_LIMIT,stdin); sstrfunc _ret; //ret._str is array upto GLOBAL_MAX_CHAR_LIMIT //also tmp is array upto GLOBAL_MAX_CHAR_LIMIT //so its safe :) to use strcpy same as strncpy strcpy(_ret._str,_tmp); //'\n' avoided _ret._str[strlen(_tmp)-1] = '\0'; _ret._err = NO_ERR; return _ret; } sstrfunc sstrinputpass(sstring show){ //dont store anything make null return value sstrfunc _null; //is global max char limit corrupted?? //returning null means error was caught! if(isGMCLCorrupt()){ _null._err = GMCL_CORRUPT; return _null; } char _tmp[GLOBAL_MAX_CHAR_LIMIT]; //nullify string [if i dont use this WiErD things happen] nullify(_tmp,GLOBAL_MAX_CHAR_LIMIT+1); char tmpchar; int done=0; //until a certain char has not been pressed while(1&gt;0){ //take chars only upto global max char limit if(done&gt;=GLOBAL_MAX_CHAR_LIMIT-1){ break; } tmpchar = getch(); if(tmpchar=='\r'){ break; }else if(tmpchar=='\b'){ if(strlen(_tmp)&gt;0){ _tmp[strlen(_tmp)-1] = '\0'; for(int i=0;i&lt;sstrlen(show);i++){ printf(&quot;\b&quot;); } for(int i=0;i&lt;sstrlen(show);i++){ printf(&quot; &quot;); } for(int i=0;i&lt;sstrlen(show);i++){ printf(&quot;\b&quot;); } } }else{ _tmp[strlen(_tmp)]=tmpchar; printf(show); done+=1;} } //print newline buffer printf(&quot;\n&quot;); sstrfunc _ret; //ret._str is array upto GLOBAL_MAX_CHAR_LIMIT //also tmp is array upto GLOBAL_MAX_CHAR_LIMIT //so its safe :) to use strcpy same as strncpy strcpy(_ret._str,_tmp); //no errors _ret._err = NO_ERR; return _ret; } sstrfunc ssetchar(sstring _str,ssize_t _pos,char _ch){ sstrfunc _null; //is global max char limit corrupted?? //returning null means error was caught! if(isGMCLCorrupt()){ _null._err = GMCL_CORRUPT; return _null; } sstrfunc _ret; if(sstrlen(_str)&gt;=GLOBAL_MAX_CHAR_LIMIT){ _null._err = GMCL_ERR; return _null; } if(_pos&gt;=sstrlen(_str)||_pos&lt;0){ _null._err = INVALID_ARGS; return _null; } strcpy(_ret._str,_str); _ret._str[_pos] = _ch; _ret._err = NO_ERR; return _ret; } void showerrs(){ printf(&quot;\n---- ERRORS Corresponding to their codes ----\n&quot;); printf(&quot;%d :- GMCL [global max char limit] is corrupted\n&quot;,GMCL_CORRUPT); printf(&quot;%d :- INVALID ARGS [the provided arguments are invalid]\n&quot;,INVALID_ARGS); printf(&quot;%d :- GMCL_ERR [provided variable has length greater than GMCL]\n&quot;,GMCL_ERR); printf(&quot;Other :- Unknown Error - Not Known Errors \n&quot;); printf(&quot;---------------------------------------------\n&quot;); } charfunc sgetchar(sstring _str,ssize_t _pos){ charfunc _null; //is global max char limit corrupted?? if(isGMCLCorrupt()){ _null._err = GMCL_CORRUPT; return _null; } // condition checking which are likely make error after if(sstrlen(_str)&gt;=GLOBAL_MAX_CHAR_LIMIT){ _null._err = GMCL_ERR; return _null; } if(_pos&gt;=sstrlen(_str)||_pos&lt;0||sstrlen(_str)&lt;0){ _null._err = INVALID_ARGS; return _null; } charfunc chr; chr._char = _str[_pos]; chr._err = NO_ERR; return chr; } //if the length of string is in size_t //and charachters in it can also be beyond int who knows! //used ssize_t to support returning negative numbers, i.e -&gt; -1 and errors //init is the place to start finding ssize_t sstrfind(size_t init,sstring _str,sstring _find){ size_t _len1 = sstrlen(_str); size_t _len2 = sstrlen(_find); size_t matching = 0; //is global max char limit corrupted?? if(isGMCLCorrupt()){ return GMCL_CORRUPT; } if(sstrlen(_str)&gt;=GLOBAL_MAX_CHAR_LIMIT||sstrlen(_find)&gt;=GLOBAL_MAX_CHAR_LIMIT){ return GMCL_ERR; } //some weird conditions check [user, are u fooling the function ?] if(_len2&gt;_len1||init&lt;0||init&gt;_len1-1){ return INVALID_ARGS; } //security check if(_len1&gt;=GLOBAL_MAX_CHAR_LIMIT||_len2&gt;=GLOBAL_MAX_CHAR_LIMIT){ return GMCL_ERR; } if(_len1==0||_len2==0){ //obviously it wont be found if the string itself is null or the tobefound string is null return -1; } //the main finder -by myself for(size_t i=init;i&lt;_len1+1;i++){ if(_str[i]==_find[0]){ for(int z=0;z&lt;_len2+1;z++){ if(matching==_len2){ return i; } else if(_str[i+z]==_find[z]){ matching+=1; } else{ matching=0; break; } } } } return -1; } </code></pre> <p>example-usage.c</p> <pre class="lang-c prettyprint-override"><code>#include&lt;stdio.h&gt; #include &quot;sstring.h&quot; #include&lt;string.h&gt; #include&lt;stdbool.h&gt; #include&lt;stdlib.h&gt; /* Example usage of sstring.h functions initially we dont need to include stdlib.h or string.h But are included for c-style arr conversion showcase &amp; for exit() functions inside here */ //User can handle errors in their **Own** Way void ErrCheck(sstrfuncerr _str){ if(_str._err!=NO_ERR){ printf(&quot;\n--- Error %d ---&quot;,_str._err); showerrs(); //terminate the program upon error //again user can do anything like return value and etc. exit(_str._err); } } void ErrCodeCheck(int _code){ if(_code&lt;NO_ERR){ printf(&quot;\n--- Error %d ---&quot;,_code); showerrs(); //terminate the program upon error //again user can do anything like return value and etc. exit(_code); } } void GenerateErr(int _code){ if(_code!=NO_ERR){ printf(&quot;\n--- Error %d ---&quot;,_code); showerrs(); exit(_code); } } int main(){ //---------------- Simplicity Showcase ------------------- sstring a; a = &quot;This is a sample string!&quot;; printf(&quot;Sample: %s \n\n&quot;,a); // ----------------- Functions ShowCase ------------------- //all functions of sstring have error checking methods! //create an error checking variable sstrfuncerr var; // -=-=- Sstrinput() -=-=- // No other scanf() or gets() support sstring so, specially sstrinput() for sstrings! printf(&quot;Sstrinput: &quot;); var = sstrinput(); //errcheck ErrCheck(var); a = var._str; //-=-=- Sstrlen() -=-=- // strlen() from string.h also can do this but added as a support for sstrings! printf(&quot;Length of a: %d\n\n&quot;,sstrlen(a)); // Or printf(&quot;Length of a: %d\n\n&quot;,strlen(a)); &lt;- from string.h same thing! //-=-=- Sstrfind() -=-=- //lets find space int check; check = sstrfind(0,a,&quot; &quot;); //errcheck //default err check ErrCodeCheck(check); //unknown err check if(check&gt;sstrlen(a)&amp;&amp;check!=-1){ GenerateErr(check); } if(check==-1){ printf(&quot;Space not found!\n&quot;); }else{ printf(&quot;Space found at %d charachter!\n&quot;,check); } //-=-=- Ssubstr() -=-=- var = ssubstr(a,0,sstrlen(a)-2); //errcheck ErrCheck(var); a = var._str; printf(&quot;Without having last two chars : %s\n&quot;,a); //Inputting passwords so easy! printf(&quot;\nEnter Password: &quot;); var = sstrinputpass(&quot;*&quot;); //errcheck ErrCheck(var); a = var._str; printf(&quot;Shh! Your password is : \&quot;%s\&quot;\n&quot;,a); //Converting to number printf(&quot;\nEnter a num: &quot;); var = sstrinput(); //errcheck ErrCheck(var); a = var._str; double num; sstrnum ret_num; //main conversion works on float, double or int values all negative or positive or '+' in front! //also can tell if the given string is number or not //also has error checking support! ret_num = sstr2num(a); //error check if(ret_num._err!=NO_ERR){ GenerateErr(ret_num._err); //if not a number }else if(ret_num.is_num==false){ printf(&quot;You didnt enter a number!&quot;); //if a number }else if(ret_num.is_num==true){ num = ret_num._num; printf(&quot;You entered: %f\n&quot;,num); } //-=-=- Conversion from array type to sstring and vice-versa -=-=- char arr_type_str[GLOBAL_MAX_CHAR_LIMIT]; sstring sstr_type_str; int _errcheck; //first sstring to arr type strings //fill up sstring sstr_type_str = &quot;If you see this, Sstr2Arr conversion success done!&quot;; //convert _errcheck = sstr2cstr(sstr_type_str,arr_type_str,GLOBAL_MAX_CHAR_LIMIT); //error check ErrCodeCheck(_errcheck); //display printf(&quot;\nSstr 2 Arr: %s\n&quot;,arr_type_str); //Now arr type strings to sstrings! //first lets nullify our string [previously used] nullify(arr_type_str,sstrlen(arr_type_str)); //fill up array type string strcpy(arr_type_str,&quot;If you see this, Arr2Sstr conversion success done!&quot;); //errcheck first ErrCheck(cstr2sstr(arr_type_str)); //convert sstr_type_str = cstr2sstr(arr_type_str)._str; //display printf(&quot;Arr 2 Sstr: %s\n&quot;,sstr_type_str); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T14:18:38.103", "Id": "532274", "Score": "0", "body": "Why `_` begins so many `struct` member names?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T04:37:53.677", "Id": "532439", "Score": "0", "body": "@chux its meant to be internal so `_` is used" } ]
[ { "body": "<blockquote>\n<p>conversion from c-style array strings to sstrings and vice-versa is now easily possible through sstr2cstr() and cstr2sstr() functions!</p>\n</blockquote>\n<p>Yes possible, but inefficient.</p>\n<p><code>cstr2sstr()</code> performs O(GLOBAL_MAX_CHAR_LIMIT) operations even when the C string is much shorter. This occurs in <code>return _ret;</code></p>\n<p>Within <code>cstr2sstr()</code> is the curious <code>strncpy(_ret._str,_Buff,strlen(_Buff));</code> rather than with simple <code>memcpy(_ret._str, _Buff, strlen(_Buff));</code> of which code could also use the prior <code>strlen(_Buff)</code> and save that result to avoid another expensive <code>strlen()</code> call. A good compile <em>may</em> do that for you.</p>\n<p><strong>Bug 1</strong></p>\n<p>Consider <code>nullify()</code> zeros <code>GLOBAL_MAX_CHAR_LIMIT+2</code> elements of <code>_tmp[]</code> - off by 2!</p>\n<pre><code>char _tmp[GLOBAL_MAX_CHAR_LIMIT];\nnullify(_tmp,GLOBAL_MAX_CHAR_LIMIT+1);\n\nvoid nullify(char * _Buff,int _count){\n ...\n for(int i=0;i&lt;_count+1;i++){\n _Buff[i] = '\\0';\n }\n</code></pre>\n<p><strong>Bug 2</strong></p>\n<p><code>fgets(_tmp,GLOBAL_MAX_CHAR_LIMIT,stdin);</code> does not have the return value checked, so following code lacks knowing if <code>_tmp</code> is in fact a <em>string</em>.</p>\n<p><strong>Bug 3</strong></p>\n<p>Wrong printf specifier for <code>size_t</code> --&gt; undefined behavior.</p>\n<pre><code>// printf(&quot;Length of a: %d\\n\\n&quot;,sstrlen(a));\nprintf(&quot;Length of a: %zu\\n\\n&quot;, sstrlen(a));\n</code></pre>\n<p>Also with code like <code>for(int i=0;i&lt;sstrlen(show);i++){</code>, a well enabled compiler would have warned.</p>\n<p>This, not fully using your compiler's warnings is the biggest mistake.</p>\n<p><strong>Underestimating FP</strong></p>\n<p>&quot;conversion from string to number [double/float/int] type is easily possible ...&quot;</p>\n<p>I look forward to seeing that <em>easy</em> code. I suspect it will have unexpected weaknesses.</p>\n<p><strong>Compile Error Check</strong></p>\n<p>The <code>isGMCLCorrupt()</code> test deserves to be a <code>_Static_assert()</code> compile time test.</p>\n<p><strong>Missing use of <code>const</code></strong></p>\n<p><code>const</code> allows greater optimization and wider use.</p>\n<pre><code>// sstrfunc cstr2sstr(char * _Buff);\nsstrfunc cstr2sstr(const char * _Buff);\n</code></pre>\n<p><strong>Large arrays for C strings</strong></p>\n<p><code>sstr2cstr()</code> obliges the destination C string to be sized <code>GLOBAL_MAX_CHAR_LIMIT</code>, yet a C string ends with the first <em>null character</em>. Very inefficient.</p>\n<p><strong>Namespace</strong></p>\n<p>The defines, types and functions of <code>sstring.h</code> are all over the place. Consider a common prefix to locate them lexicographically.</p>\n<p><strong>Documentation</strong></p>\n<p><code>sstring.h</code> deserves documentation to high-light overall usage and function particulars. Users should not need access to <code>sstring.c</code> to discern general function usage.</p>\n<p><strong>Design</strong></p>\n<p>I find code passing around the large <code>sstrfunc</code> objects and requiring large string arrays as wholly inefficient and recommend a new design.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T04:15:43.647", "Id": "532323", "Score": "0", "body": "Bug - 1 : every function checks if the specified strings length is [greater or equal] and if true terminates the process with returning error. so doing GLOBAL_MAX_CHAR_LIMIT + 1 in the loop wouldn't cause any bugs. Bug - 2 : Even if the user presses enter without writing any charachters no bugs are found . errors occur if you try to get substr of it because its a null string. Bug - 3: Yeah i understand that but thats located in example-usage.c not in the header files or functions. so the mistake is in example file!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T04:21:11.910", "Id": "532324", "Score": "0", "body": "Underestimating fp : The function returns a typedef of strnum. the strnum contains : bool is_num , int _err, double _num. As far as i know, converting from double type to float type or int type doesn't generate any issue. Compile error check : I am new to c and have this code as my own project. it would be thankful if you provided _how_ could i do that!. Missing use of const : Yeah but i dont think without using it would generate issue. Namespace & Design: please furthermore illustrate what are you trying to say and provide a little bit of example. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T13:21:03.703", "Id": "532359", "Score": "0", "body": "@Pear Let us review bug #1: `_tmp` is array 400. Code calls `nullify(_tmp,401);`. That function iterates 402 times with `for(int i=0;i<402;i++){ _Buff[i] = '\\0';`. This overruns `_tmp[]`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T13:26:45.293", "Id": "532360", "Score": "0", "body": "@Pear Bug 2: `fgets()` is called yet there is _no_ input - not even a `'\\n'` (I am not talking about the \"user presses enter without writing any characters\"), but end-of-of-file. `stdin` is closed. In that case, `_tmp[]` remains indefinite and `strcpy(_ret._str,_tmp);` is UB. You have not seen this bug due to not testing for immediate end-of-file (nor the rare input input error)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T13:42:09.687", "Id": "532361", "Score": "0", "body": "@Pear Did not see `sstrnum sstr2num(sstring _str)` earlier. There code compounds small (and some large) errors with each `_return._num+= (cchar-'0')/pow(10,pointplace);` and `_return._num*=10;` as the math result is not always exact. String to FP is in itself a _very_ challenging coding task to do well. This code does OK, yet has precision trouble over the `double` range and overflow trouble near `DBL_MAX, DBL_TRUE_MIN`. The usual solution is to some extended precision and range. For now, use `strtod()` if a high quality result is needed.\n `" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T13:51:43.363", "Id": "532362", "Score": "0", "body": "@Pear Namespace detail: Rather than `NO_ERR, charfunc, nullify, sgetchar` surprisingly originating in `sstring.h`, consider `SSTR_NO_ERR, sstr_charfunc, sstr_nullify, sstr_getchar` in `sstr.h`. Keep in mind `sstring.h` may be including with dozens of other `*.h` files and knowing where a generic name like `NO_ERR` originates is important." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T13:54:00.730", "Id": "532363", "Score": "0", "body": "@Pear Re `const`. Try `const char *num = \"123\"; cstr2sstr(num);`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T16:54:44.513", "Id": "532389", "Score": "0", "body": "Very very much thanx for reviewing my code and providing feedbacks! all mentioned bugs are being removed and feedbacks are being implemented! -by myself of course!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T17:37:35.317", "Id": "532399", "Score": "0", "body": "@Pear Type `sstrfunc` deserves a design review. Recommend to add a `.length` member to keep track of how much of `._str[]` is used. Yet the really question is do you want to have a fixed size (I suspect you do) or a dynamic size (more useful but many more headaches). \"Strings\" in C are tricky - no matter what you choose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T17:38:21.800", "Id": "532401", "Score": "0", "body": "@Pear Hope for a reply to [question](https://codereview.stackexchange.com/questions/269720/user-friendly-string-struct-and-utility-function-upated-version/269747?noredirect=1#comment532274_269720)/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T04:03:42.450", "Id": "532434", "Score": "0", "body": "I want the strings to be dynamic. however the functions dont handle it so well so i have set the maximum limit to a functions return of string value is GLOBAL_MAX_CHAR_LIMIT. unless you use any of the functions, the string has no limit to itself" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T04:09:00.850", "Id": "532435", "Score": "0", "body": "And hey, sstr2cstr() function doesn't oblige the destination string to be sized `GLOBAL MAX CHAR LIMIT`. it takes 3 parameters sstr2cstr(thesstring,thecstring,_upto). `_upto` is the amount upto which you have sized your variable. even if the sstring size is greater than _upto, string greater than _upto will not be entered into the thecstring making it safe as i have used strncpy()" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T04:10:55.667", "Id": "532436", "Score": "0", "body": "thanx for the feedback for sstrfunc! trying it now! also i have added replace() function also improving and fixing the bugs in the new version. [not included here]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T04:39:06.443", "Id": "532441", "Score": "0", "body": "@Pear \"making it safe as i have used strncpy()\" --> the end result in `char * _Cstr` is then certainly not always a _string_ as `strncpy()` does not always form a _string_. This reduces the safety of following code assuming a _string_ was formed. Recall, in C, a _string_ **always** contains a _null character_, else it is not a _string_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T05:03:30.467", "Id": "532444", "Score": "0", "body": "the user could check for that value in the code itself. no worries because *_Cstr is the variable which has to be assigned!" } ], "meta_data": { "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T22:36:30.737", "Id": "269747", "ParentId": "269720", "Score": "4" } }, { "body": "<p>don't use conio.h That is a microsoft invention that is not portable</p>\n<pre><code>gcc -ggdb3 -Wall -Wextra -Wconversion -pedantic -std=gnu11 -c &quot;untitled.c&quot; -o &quot;untitled.o&quot; \n\nuntitled.c:36:42: error: unknown type name ‘size_t’\n 36 | int sstr2cstr(sstring _sstr,char * _Cstr,size_t _upto);\n | ^~~~~~\nuntitled.c:4:1: note: ‘size_t’ is defined in header ‘&lt;stddef.h&gt;’; did you forget to ‘#include &lt;stddef.h&gt;’?\n 3 | #include&lt;stdbool.h&gt;\n +++ |+#include &lt;stddef.h&gt;\n 4 | #define SSTRING_H_DEFINED\nuntitled.c:39:1: error: unknown type name ‘ssize_t’\n 39 | ssize_t sstrfind(size_t init,sstring _str,sstring _find);\n | ^~~~~~~\nuntitled.c:39:18: error: unknown type name ‘size_t’\n 39 | ssize_t sstrfind(size_t init,sstring _str,sstring _find);\n | ^~~~~~\nuntitled.c:39:18: note: ‘size_t’ is defined in header ‘&lt;stddef.h&gt;’; did you forget to ‘#include &lt;stddef.h&gt;’?\nuntitled.c:40:1: error: unknown type name ‘size_t’\n 40 | size_t sstrlen(sstring _str);\n | ^~~~~~\nuntitled.c:40:1: note: ‘size_t’ is defined in header ‘&lt;stddef.h&gt;’; did you forget to ‘#include &lt;stddef.h&gt;’?\nuntitled.c:41:32: error: unknown type name ‘ssize_t’\n 41 | sstrfunc ssetchar(sstring _str,ssize_t _pos,char _ch);\n | ^~~~~~~\nuntitled.c:42:40: error: unknown type name ‘size_t’\n 42 | sstrfunc ssubstr(sstring _str,int _pos,size_t _len);\n | ^~~~~~\nuntitled.c:42:40: note: ‘size_t’ is defined in header ‘&lt;stddef.h&gt;’; did you forget to ‘#include &lt;stddef.h&gt;’?\nuntitled.c:43:32: error: unknown type name ‘ssize_t’\n 43 | charfunc sgetchar(sstring _str,ssize_t _pos);\n | ^~~~~~~\nuntitled.c:72:8: error: conflicting types for ‘sstrlen’\n 72 | size_t sstrlen(sstring _str){\n | ^~~~~~~\nuntitled.c:40:8: note: previous declaration of ‘sstrlen’ was here\n 40 | size_t sstrlen(sstring _str);\n | ^~~~~~~\nuntitled.c: In function ‘sstr2cstr’:\nuntitled.c:112:19: warning: conversion from ‘size_t’ {aka ‘long unsigned int’} to ‘int’ may change value [-Wconversion]\n 112 | nullify(_Cstr,_upto);\n | ^~~~~\nuntitled.c: In function ‘sstr2num’:\nuntitled.c:149:18: warning: comparison of integer expressions of different signedness: ‘int’ and ‘size_t’ {aka ‘long unsigned int’} [-Wsign-compare]\n 149 | for(int i=0;i&lt;sstrlen(_str);i++){\n | ^\nuntitled.c: In function ‘ssubstr’:\nuntitled.c:219:12: warning: comparison of integer expressions of different signedness: ‘int’ and ‘size_t’ {aka ‘long unsigned int’} [-Wsign-compare]\n 219 | if(_pos&gt;=sstrlen(_str)||_pos&lt;0||_len&gt;=sstrlen(_str)||_len&lt;0){\n | ^~\nuntitled.c:219:62: warning: comparison of unsigned expression &lt; 0 is always false [-Wtype-limits]\n 219 | if(_pos&gt;=sstrlen(_str)||_pos&lt;0||_len&gt;=sstrlen(_str)||_len&lt;0){\n | ^\nuntitled.c: In function ‘nullify’:\nuntitled.c:266:11: error: unknown type name ‘Compilation’\n 266 | }else{Compilation failed.\n | ^~~~~~~~~~~\nuntitled.c:266:29: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘.’ token\n 266 | }else{Compilation failed.\n | ^\nuntitled.c:267:21: error: ‘i’ undeclared (first use in this function)\n 267 | for(int i=0;i&lt;_count+1;i++){\n | ^\nuntitled.c:267:21: note: each undeclared identifier is reported only once for each function it appears in\nuntitled.c:267:35: error: expected ‘;’ before ‘)’ token\n 267 | for(int i=0;i&lt;_count+1;i++){\n | ^\n | ;\nuntitled.c:267:35: error: expected statement before ‘)’ token\nuntitled.c:261:21: warning: parameter ‘_Buff’ set but not used [-Wunused-but-set-parameter]\n 261 | void nullify(char * _Buff,int _count){\n | ~~~~~~~^~~~~\nuntitled.c: In function ‘sstrinputpass’:\nuntitled.c:316:19: warning: implicit declaration of function ‘getch’; did you mean ‘getc’? [-Wimplicit-function-declaration]\n 316 | tmpchar = getch();\n | ^~~~~\n | getc\nuntitled.c:316:19: warning: conversion from ‘int’ to ‘char’ may change value [-Wconversion]\nuntitled.c:322:30: warning: comparison of integer expressions of different signedness: ‘int’ and ‘size_t’ {aka ‘long unsigned int’} [-Wsign-compare]\n 322 | for(int i=0;i&lt;sstrlen(show);i++){\n | ^\nuntitled.c:325:30: warning: comparison of integer expressions of different signedness: ‘int’ and ‘size_t’ {aka ‘long unsigned int’} [-Wsign-compare]\n 325 | for(int i=0;i&lt;sstrlen(show);i++){\n | ^\nuntitled.c:328:30: warning: comparison of integer expressions of different signedness: ‘int’ and ‘size_t’ {aka ‘long unsigned int’} [-Wsign-compare]\n 328 | for(int i=0;i&lt;sstrlen(show);i++){\n | ^\nuntitled.c:334:13: warning: format not a string literal and no format arguments [-Wformat-security]\n 334 | printf(show);\n | ^~~~~~\nuntitled.c: In function ‘ssetchar’:\nuntitled.c:365:12: warning: comparison of integer expressions of different signedness: ‘ssize_t’ {aka ‘long int’} and ‘size_t’ {aka ‘long unsigned int’} [-Wsign-compare]\n 365 | if(_pos&gt;=sstrlen(_str)||_pos&lt;0){\n | ^~\nuntitled.c: In function ‘sgetchar’:\nuntitled.c:399:12: warning: comparison of integer expressions of different signedness: ‘ssize_t’ {aka ‘long int’} and ‘size_t’ {aka ‘long unsigned int’} [-Wsign-compare]\n 399 | if(_pos&gt;=sstrlen(_str)||_pos&lt;0||sstrlen(_str)&lt;0){\n | ^~\nuntitled.c:399:50: warning: comparison of unsigned expression &lt; 0 is always false [-Wtype-limits]\n 399 | if(_pos&gt;=sstrlen(_str)||_pos&lt;0||sstrlen(_str)&lt;0){\n | ^\nuntitled.c: In function ‘sstrfind’:\nuntitled.c:429:25: warning: comparison of unsigned expression &lt; 0 is always false [-Wtype-limits]\n 429 | if(_len2&gt;_len1||init&lt;0||init&gt;_len1-1){\n | ^\nuntitled.c:446:26: warning: comparison of integer expressions of different signedness: ‘int’ and ‘size_t’ {aka ‘long unsigned int’} [-Wsign-compare]\n 446 | for(int z=0;z&lt;_len2+1;z++){\n | ^\nuntitled.c:448:28: warning: conversion to ‘ssize_t’ {aka ‘long int’} from ‘size_t’ {aka ‘long unsigned int’} may change the sign of the result [-Wsign-conversion]\n 448 | return i;\n | ^\nuntitled.c:450:31: warning: conversion to ‘size_t’ {aka ‘long unsigned int’} from ‘int’ may change the sign of the result [-Wsign-conversion]\n 450 | else if(_str[i+z]==_find[z]){\n | ^\nuntitled.c: At top level:\nuntitled.c:464:5: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘-’ token\n 464 | gcc -ggdb3 -Wall -Wextra -Wconversion -pedantic -std=gnu11 -c &quot;untitled.c&quot; -o &quot;untitled.o&quot; (in directory: /home/richard/Documents/forum)\n | ^\nCompilation failed.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T12:43:41.200", "Id": "532355", "Score": "0", "body": "i have used conio.h for getch() function. Also did u include the header file?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T13:57:49.050", "Id": "532364", "Score": "0", "body": "user3629249, \"don't use conio.h That is a microsoft invention\" --> Sure MS invented it? I suspect they mimicked some prior art. I do agree with the idea of avoiding non-standard functions, especially when `getc()` would suffice here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T23:22:14.337", "Id": "532520", "Score": "0", "body": "I placed your header file first, The result is posted in my answer" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T11:03:48.660", "Id": "269763", "ParentId": "269720", "Score": "0" } } ]
{ "AcceptedAnswerId": "269747", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T07:11:48.577", "Id": "269720", "Score": "3", "Tags": [ "c", "strings" ], "Title": "User-friendly string struct and utility function - upated version" }
269720
<p>I'm trying to scrape arrival data from <a href="https://satudata.kemendag.go.id/balance-of-trade-with-trade-partner-country" rel="nofollow noreferrer">this website</a>. My script takes extremely long time to scrape the data. Is there any way I can speed up the scraping process?</p> <p>Here's my script:</p> <pre><code>import json import pandas as pd import copy import requests from bs4 import BeautifulSoup def getBalanceofTrade(): cookies = { '_ga': 'GA1.3.672481365.1630462756', 'sc_is_visitor_unique': 'rx12421317.1631602001.FE09E031FA464FEEAD095B438DD92829.2.2.2.2.2.2.2.2.2', '_ga_41205092': 'GS1.1.1631601995.2.0.1631602551.0', 'varient_csrf_cookie': 'c34f577f894740d92106453d293f69b4', 'ci_session': 'q9qvice0p2dgnp5f50veghgrqeveavrm', '_gid': 'GA1.3.542540031.1635307774', '_gat_gtag_UA_155890962_1': '1', 'f5avr0338662302aaaaaaaaaaaaaaaa_cspm_': 'DMPCJNDKGKPBLIDLCKDBLLDGAEPJPBKDHBPPMIDGKFDEMKGDHFNEBJBDOLAMKFJACFDCDGKEHKFEFIPPNNKAJEACAPLNMFADDKOEHBJBKJGGDMKBNHHFMJBOEGLPMEPA',} headers = { 'Connection': 'keep-alive', 'sec-ch-ua': '&quot;Chromium&quot;;v=&quot;94&quot;, &quot;Google Chrome&quot;;v=&quot;94&quot;, &quot;;Not A Brand&quot;;v=&quot;99&quot;', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest', 'sec-ch-ua-mobile': '?0', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36', 'sec-ch-ua-platform': '&quot;Windows&quot;', 'Origin': 'https://satudata.kemendag.go.id', 'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest': 'empty', 'Referer': 'https://satudata.kemendag.go.id/balance-of-trade-with-trade-partner-country', 'Accept-Language': 'en-US,en;q=0.9',} base_params = { 'varient_csrf_token': 'c34f577f894740d92106453d293f69b4', 'category': 'country'} value_id = pd.read_excel('Value ID Countries.xlsx') value_dict = dict(zip(value_id['VALUE ID'], value_id['COUNTRY'])) params_list = [] for key, value in value_dict.items(): new_params = copy.copy(base_params) new_params['region_id'] = key params_list.append(new_params) df_all = pd.DataFrame() for params in params_list: response = requests.post('https://satudata.kemendag.go.id/balance-query', headers=headers, cookies=cookies, data=params) json_data = json.loads(response.text) df1 = pd.json_normalize(json_data) #print(df1) table_list = df1['data'] for table in table_list: df = pd.DataFrame.from_records(table) df_all = df_all.append(df, ignore_index=True) country = [] for i in value_id['COUNTRY']: x = [i] * len(df) country.append(x) country_list = [item for s in country for item in s] df_all['Country'] = country_list df_new = df_all.iloc[:, 0:6] df_new1 = df_all.iloc[:, 8:9] df_new2 = df_all.iloc[:, 10:11] result = pd.concat([df_new, df_new1, df_new2], axis=1) URL = 'https://satudata.kemendag.go.id/balance-of-trade-with-trade-partner-country' page = requests.get(URL) soup = BeautifulSoup(page.content, 'html.parser') table =soup.find('table', id=&quot;table-balance&quot;) rows = table.find_all('th') cols = [item.text.strip() for item in rows] #column name uraian column_name = [cols[0]] column_name1 = cols[1:6] column_name2 = [cols[10]] tahun = column_name1 + column_name2 final_column = column_name + column_name1 + column_name2 + ['Country'] result.columns = final_column desc_1 = 3*(result['Uraian'][0],) desc_2 = 3*(result['Uraian'][3],) desc_3 = 3*(result['Uraian'][6],) desc_4 = 3*(result['Uraian'][9],) x = desc_1 + desc_2 + desc_3 + desc_4 y = list(x) z = y * len(value_id['COUNTRY']) result = result.replace(['TOTAL PERDAGANGAN', 'EKSPOR', 'IMPOR', 'NERACA PERDAGANGAN'], ['Total', 'Total', 'Total', 'Total']) df2 = pd.DataFrame(z, columns=['description']) result = result.rename(columns = {'Uraian': 'tipe'}, inplace = False) table = pd.concat ([df2, result], axis=1) df_table = table.melt(id_vars=['description', 'tipe', 'Country'], value_vars=tahun, var_name='year') return(df_table) </code></pre> <p>Excel file:</p> <pre><code>VALUE ID | COUNTRY 147 ADEN 137 AFGANISTAN 299 AFRIKA LAINNYA ... ... </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T13:44:23.663", "Id": "532267", "Score": "0", "body": "What is the reason that your output is in Pandas format?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T14:45:52.607", "Id": "532278", "Score": "0", "body": "Should we presume the Excel file has 195 countries in it? The first solution to speedup I'd try is to parallelize that `for` loop; use [threads or asyncio to request 20 at a time or so](https://stackoverflow.com/a/65996653/6243352). But without a bit more detail I can't run or mess with the code in a meaningful way to test this hypothesis." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T03:52:00.810", "Id": "532320", "Score": "1", "body": "@ggorlen it has 279 countries in it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T03:54:41.050", "Id": "532321", "Score": "1", "body": "when you click [this website](https://satudata.kemendag.go.id/balance-of-trade-with-trade-partner-country) then right-click on that page then click view-source, on that page it contains the ids and the countries @ggorlen" } ]
[ { "body": "<p>It won't be practical to speed this process up since you're scraping a third-party website. Parallelizing requests and loading the server is ethically dubious so I think you don't have many options other than to be patient.</p>\n<p><code>getBalanceofTrade</code> should be <code>get_balance_of_trade</code> by PEP8.</p>\n<p>This function mixes together far too many concerns:</p>\n<ul>\n<li>session cookie &amp; header construction (which is hard-coded when it should not be)</li>\n<li>fetching and parsing two different pages</li>\n<li>loading a country database</li>\n<li>data cleaning</li>\n<li>construction of a dataframe</li>\n</ul>\n<p>Each of these should be separate. Your requests should use an actual <code>Session</code> object. If you first run a request to <code>balance-of-trade-with-trade-partner-country</code> before the actual data fetching, it can serve two purposes: initialize a fresh (not hard-coded) CSRF token, and fetch your country database. You then won't need an Excel file at all (which should not have been an Excel file - it should have been something more machine-readable like a CSV).</p>\n<p>The country database <code>get</code> should use a strainer to only parse the portion of the HTML document containing region IDs. If you want to be fancy, you can also pre-compile your CSS selectors via <code>soupsieve</code>.</p>\n<p>You should drop nearly all of your hard-coded headers and cookies and pass only</p>\n<ul>\n<li>cookies given to you automatically via <code>Session</code>, and</li>\n<li>an <code>Accept</code> header correctly communicating what content type you're expecting (even though the server is broken and returns the wrong content type for JSON).</li>\n</ul>\n<p>You should not <code>json.loads</code>, and should instead call <code>response.json()</code>. The response should also be used in a context management <code>with</code>.</p>\n<p>An example implementation that addresses some of these concerns:</p>\n<pre><code>from pprint import pprint\nfrom typing import Iterator, Tuple, Any, Dict\nfrom urllib.parse import urljoin\n\nimport soupsieve\nfrom bs4 import SoupStrainer, BeautifulSoup, ResultSet\nfrom requests import Session\n\n\nBASE = 'https://satudata.kemendag.go.id'\n\n\nCOUNTRY_DROPDOWN = SoupStrainer(name='select', id='country')\nOPTION_SIEVE = soupsieve.compile(pattern=':root &gt; option:not([value=&quot;&quot;])')\n\n\ndef get_regions(session: Session) -&gt; Iterator[Tuple[str, int]]:\n with session.get(\n url=urljoin(BASE, 'balance-of-trade-with-trade-partner-country'),\n headers={'Accept': 'text/html'},\n ) as resp:\n resp.raise_for_status()\n doc = BeautifulSoup(\n markup=resp.text,\n features='html.parser', parse_only=COUNTRY_DROPDOWN,\n )\n\n for option in OPTION_SIEVE.select(doc):\n name = option.text.strip().title()\n value = int(option['value'])\n yield name, value\n\n\ndef query_balance(session: Session, region_id: int) -&gt; Dict[str, Any]:\n with session.post(\n urljoin(BASE, 'balance-query'),\n headers={'Accept': 'application/json'},\n data={\n 'region_id': region_id,\n 'category': 'country',\n 'varient_csrf_token': session.cookies['varient_csrf_cookie'],\n },\n ) as resp:\n resp.raise_for_status()\n return resp.json()\n\n\ndef main() -&gt; None:\n with Session() as session:\n regions = dict(get_regions(session))\n data = query_balance(session, regions['Kanada']) # 412\n pprint(data)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>For the one country queried, this prints</p>\n<pre class=\"lang-json prettyprint-override\"><code>{'country': 'KANADA',\n 'data': [{'cumulative_1': '1,597,724.5',\n 'cumulative_2': '2,049,001.3',\n 'growth': '28.24',\n 'period_1': '2,115,477.3',\n 'period_2': '2,374,859.0',\n 'period_3': '2,754,638.7',\n 'period_4': '2,696,923.0',\n 'period_5': '2,404,576.7',\n 'trend': '3.91',\n 'uraian': 'TOTAL PERDAGANGAN'},\n {'cumulative_1': '276.7',\n 'cumulative_2': '528.8',\n 'growth': '91.10',\n 'period_1': '633.8',\n 'period_2': '772.1',\n 'period_3': '1,155.0',\n 'period_4': '709.6',\n 'period_5': '407.8',\n 'trend': '-9.21',\n 'uraian': 'MIGAS'},\n {'cumulative_1': '1,597,447.8',\n 'cumulative_2': '2,048,472.5',\n 'growth': '28.23',\n 'period_1': '2,114,843.4',\n 'period_2': '2,374,086.9',\n 'period_3': '2,753,483.7',\n 'period_4': '2,696,213.4',\n 'period_5': '2,404,168.9',\n 'trend': '3.91',\n 'uraian': 'NON MIGAS'},\n {'cumulative_1': '497,670.5',\n 'cumulative_2': '675,889.8',\n 'growth': '35.81',\n 'period_1': '732,447.3',\n 'period_2': '821,233.1',\n 'period_3': '913,889.2',\n 'period_4': '858,206.0',\n 'period_5': '789,116.4',\n 'trend': '1.95',\n 'uraian': 'EKSPOR'},\n {'cumulative_1': '24.4',\n 'cumulative_2': 0,\n 'growth': '0.00',\n 'period_1': '121.4',\n 'period_2': '100.0',\n 'period_3': '123.1',\n 'period_4': '86.3',\n 'period_5': '24.4',\n 'trend': '-28.52',\n 'uraian': 'MIGAS'},\n {'cumulative_1': '497,646.1',\n 'cumulative_2': '675,889.8',\n 'growth': '35.82',\n 'period_1': '732,326.0',\n 'period_2': '821,133.1',\n 'period_3': '913,766.1',\n 'period_4': '858,119.7',\n 'period_5': '789,092.0',\n 'trend': '1.95',\n 'uraian': 'NON MIGAS'},\n {'cumulative_1': '1,100,054.0',\n 'cumulative_2': '1,373,111.5',\n 'growth': '24.82',\n 'period_1': '1,383,029.9',\n 'period_2': '1,553,625.8',\n 'period_3': '1,840,749.5',\n 'period_4': '1,838,717.0',\n 'period_5': '1,615,460.4',\n 'trend': '4.91',\n 'uraian': 'IMPOR'},\n {'cumulative_1': '252.3',\n 'cumulative_2': '528.8',\n 'growth': '109.57',\n 'period_1': '512.5',\n 'period_2': '672.1',\n 'period_3': '1,031.9',\n 'period_4': '623.3',\n 'period_5': '383.5',\n 'trend': '-6.34',\n 'uraian': 'MIGAS'},\n {'cumulative_1': '1,099,801.6',\n 'cumulative_2': '1,372,582.7',\n 'growth': '24.80',\n 'period_1': '1,382,517.4',\n 'period_2': '1,552,953.8',\n 'period_3': '1,839,717.6',\n 'period_4': '1,838,093.7',\n 'period_5': '1,615,076.9',\n 'trend': '4.91',\n 'uraian': 'NON MIGAS'},\n {'cumulative_1': '-602,383.5',\n 'cumulative_2': '-697,221.7',\n 'growth': '-15.74',\n 'period_1': '-650,582.6',\n 'period_2': '-732,392.7',\n 'period_3': '-926,860.2',\n 'period_4': '-980,511.0',\n 'period_5': '-826,344.0',\n 'trend': '-8.00',\n 'uraian': 'NERACA PERDAGANGAN'},\n {'cumulative_1': '-228.0',\n 'cumulative_2': '-528.8',\n 'growth': '-131.99',\n 'period_1': '-391.1',\n 'period_2': '-572.0',\n 'period_3': '-908.8',\n 'period_4': '-537.0',\n 'period_5': '-359.1',\n 'trend': '2.31',\n 'uraian': 'MIGAS'},\n {'cumulative_1': '-602,155.5',\n 'cumulative_2': '-696,692.8',\n 'growth': '-15.70',\n 'period_1': '-650,191.5',\n 'period_2': '-731,820.6',\n 'period_3': '-925,951.5',\n 'period_4': '-979,974.0',\n 'period_5': '-825,984.9',\n 'trend': '-8.01',\n 'uraian': 'NON MIGAS'}],\n 'period': '2016 - 2021'}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T03:59:58.733", "Id": "532322", "Score": "0", "body": "what if my expected output is dataframe of all the country data? @Reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T11:59:18.637", "Id": "532350", "Score": "0", "body": "@lockey You never answered : why a dataframe?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T12:00:22.923", "Id": "532351", "Score": "0", "body": "because it will store to postgres base on that dataframe format" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T14:00:10.047", "Id": "532365", "Score": "0", "body": "You're concerned about performance: a more performant solution will skip Pandas altogether, use a direct engine library like psycopg, and split off an asynchronous insert while the next web record is being fetched." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T14:33:21.837", "Id": "532368", "Score": "0", "body": "what do u mean with ```split off an asynchronous ```? @Reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T14:38:12.020", "Id": "532371", "Score": "0", "body": "what if scraping all countries in one time? @Reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T14:49:29.953", "Id": "532373", "Score": "3", "body": "_what if scraping all countries in one time?_ - If you don't own the website, don't do that. It's discourteous and can be construed as a DOS." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T15:48:51.327", "Id": "269733", "ParentId": "269721", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T07:19:14.983", "Id": "269721", "Score": "3", "Tags": [ "python", "performance", "python-3.x", "web-scraping", "pandas" ], "Title": "Web scraping international trade data" }
269721
<p>I have developed a web app which lets you transfer files from A device to B device, similar to airdrop's concept, working through the server and not peer-to-peer.</p> <p>I didn't go with a P2P solution because it requires a lot of time to make it work perfectly, and fallbacks in case it doesn't so I didn't really want to go in there, at least not now.</p> <p>After looking at <a href="https://www.qed42.com/insights/coe/javascript/developing-real-time-secure-chat-application-whatsapp-signal-end-end" rel="nofollow noreferrer">this tutorial</a> to see how to really use the Signal protocol for E2E in JavaScript, I successfully achieved it.</p> <p>However, I have a feeling that I implemented the handshake incorrectly and insecure.</p> <p>My main goal was making the server not know by any chance what is the data that is being transferred, which is why I used the <a href="https://signal.org/docs/specifications/doubleratchet/" rel="nofollow noreferrer">Double Ratchet algorithm by Signal</a></p> <p>There is my E2E service, which uses the signal algorithm wrapper, as shown in the tutorial above<sup><a href="https://www.qed42.com/insights/coe/javascript/developing-real-time-secure-chat-application-whatsapp-signal-end-end" rel="nofollow noreferrer">1</a></sup>, this is my front-end part:</p> <pre><code>@Injectable() export class E2eeService { private signalProtocolManagerUser: any; private store: SignalServerStore; public initializeNewSession(currentUserId: string) { return new Promise&lt;void&gt;(resolve =&gt; { const store = new SignalServerStore(); createSignalProtocolManager(currentUserId, undefined, store).then(signalProtocolManagerUser =&gt; { this.signalProtocolManagerUser = signalProtocolManagerUser; this.store = store; resolve(); }); }) } public getPreKeyBundle(clientId: string) { return this.store.getPreKeyBundle(clientId); } public encryptMessage(targetClientId: string, message: Blob) { const encryptedMessage = this.signalProtocolManagerUser.encryptMessageAsync(targetClientId, message); // todo send message to server } public decryptMessage(senderClientId: string, message: any) { return new Promise&lt;Blob&gt;(resolve =&gt; { this.signalProtocolManagerUser.decryptMessageAsync(senderClientId, message).then(message =&gt; { // TODO convert to blob, save in indexdb }); }); } } </code></pre> <p><code>signalProtocolManagerUser</code> is a wrapper for signal lib, as shown in the tutorial, <a href="https://github.com/VertikaJain/react-chat-app/blob/master/src/signal/SignalGateway.js" rel="nofollow noreferrer">same as this class</a>, maybe some names changed.</p> <p>Now this is all working and fine, but here is how my key exchange works:</p> <ol> <li>Client A initializes a prekeys bundle</li> <li>Client B initializes a prekeys bundle</li> <li>A sends B their bundle through the server through websocket, and the server passes it to client B through websocket as well without saving the bundle in the server.</li> <li>B sends A their bundle through the server through websocket, and the server passes it to client A through websocket as well without saving the bundle in the server.</li> <li>A sends an encrypted message to B, and B decrypts it.</li> <li>B sends an encrypted message to A, and A decrypts it.</li> <li>Now the connection is secure, since both of the sides have up-to-date synced ratchet.</li> </ol> <p>I would love to get a review to this flow, and if there is a way to improve it or if there is an issue with this approach.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T18:36:32.877", "Id": "532725", "Score": "3", "body": "could you please explain more in detail why do you think there may be a problem with the handshake? I don't know js nor angular, but your description of key exchange seems like a typical exchange in any public-key based algorithm: assuming that `prekeys bundle` contains only public key, not private, server has no way to decrypt the content being passed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T21:43:20.443", "Id": "532748", "Score": "0", "body": "@morgwai Think of a situation that tomorrow the server gets hacked, or I get some crazy idea and would like to see people's data. What prevents me from deploying a version of the server which also generates a prekeys bundle server-sided for itself, and passes it to the clients, and the clients will think that it's the other's side prekeys bundle, Who promises that you as a client will always get the right key bundle, server can trick both clients by syncing up the ratchet with them and passing the messages as a middle man." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T21:44:31.293", "Id": "532749", "Score": "0", "body": "Are you claiming that the code above achieves what is described in steps 1-7 for the key exchange?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T21:45:28.303", "Id": "532750", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ Nope, the code for the actual exchange wasn't posted, I don't see a reason because the flow is exactly as it is" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T21:50:14.607", "Id": "532751", "Score": "0", "body": "The reason I am asking this is that it sounds ridiculous that creating a secure communication channel between A and B through C without C knowing what's going on is possible. My intuition says that it's not possible, unless A and B meet in person and exchanged keys **directly**." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T08:14:10.737", "Id": "532782", "Score": "0", "body": "ok, now I get what you meant: yes, man in the middle is definitely possible in such scenario, but it's not related to your code: it's a property of public key protocols. There's no way to avoid it without verifying the public keys using other means (such as peers sending fingerprints to each other via a different channel or trusting some certificate authority)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T08:23:13.200", "Id": "532785", "Score": "0", "body": "...and apologies for my first comment being a bit misleading in this regard maybe: if public keys are not verified, server can replace them during initial exchange exactly the way you describe and read everything. So my first comment should be `s/assuming that prekeys bundle contains only public key/assuming that prekeys bundle contains only _verified_ public key/`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T10:19:51.817", "Id": "532794", "Score": "0", "body": "...so if you don't plan to use certificates with trusted certificate authority, then basically all you can do is to make it as clear as possible for users that they should verify their keys using another channel before transferring any sensitive data. For example displaying a popup with a message before starting a transfer. As a general note, IMO most communicators, Signal including, don't do enough to make average users aware of man in the middle threat and importance of key verifying..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T11:43:14.397", "Id": "532798", "Score": "2", "body": "I see multiple problems with your question. 1) The code isn't finished and I sincerely doubt this code accomplishes what you want it to accomplish. 2) It also seems like you've left out essential parts of the code before we can do a review. If you wanted a general review of the approach instead of the code itself, you may be in the wrong place altogether. We don't do that without seeing the code, but others might." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T12:37:34.783", "Id": "269728", "Score": "1", "Tags": [ "typescript", "angular-2+", "websocket", "encryption" ], "Title": "My implementation of the Signal protocol for end-to-end encryption in NodeJS and Angular" }
269728
<p>I had to make a single-page application that fetches some figures via an endpoint, does some calculations, and displays them to an <code>HTML</code> page. Below is my implementation. I know there is a lot of room for improvement. Looking forward to any feedback.</p> <pre><code>const getNumberOfTitles = async (title: string) =&gt; { try { const data: Response = await fetch( `https://${host}/?manga=${title}` ); const response = await data.json(); return response.number_of; } catch (error) { console.error('Error: ', error); } }; const getNumberOfMultipleTitles = async ( titleNames: Array&lt;string&gt; ) =&gt; { return Promise.all(titleNames.map(getNumberOfTitles)); }; const returnMangaData = async () =&gt; { const shounen = ['Naruto', 'Bleach']; const all_titles = [ 'AOT', 'Death Note', 'Full Metal Panic', 'Demon Slayer', ...shounen, ]; const totalShounenTitles = ( await getNumberOfMultipleTitles(shounen) ).reduce((a, b) =&gt; parseInt(a) + parseInt(b)); const totalMangaTitles = ( await getNumberOfMultipleTitles(all_titles) ).reduce((a, b) =&gt; parseInt(a) + parseInt(b)); const percentage = Math.round((totalShounenTitles / totalMangaTitles) * 100); return [totalShounenTitles, percentage]; }; const setMangaData = async () =&gt; { const [totalShounenTitles, percentage] = await returnMangaData(); const shounenNumber = document.querySelector('.manga-shounen'); if (shounenNumber) { shounenNumber.innerHTML = String(totalShounenTitles); } const shounenPercentage = document.querySelector('.shounen-percentage'); if (shounenPercentage) { shounenPercentage.innerHTML = `This is ${percentage}% of shounen titles`; } }; setMangaData(); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T13:50:33.630", "Id": "269729", "Score": "1", "Tags": [ "javascript", "typescript" ], "Title": "Implement a single page application which fetches data via an endpoint and displays to a html page" }
269729
<p>I've been adding stuff a bit &quot;blindly&quot; to my controller and currently everything is working as it should, but the controller is gotten very messy. I'm using the gem <code>rails_best_practices</code> to tidy up my code, but it's currently not giving me any other fixes than moving some of the methods to the model from the controller.</p> <p>Few questions</p> <blockquote> <p>Is there other gems like <code>rails_best_practices</code> that I could use to figure out how to tidy up the controller?</p> </blockquote> <p>and secondly</p> <blockquote> <p>Any advice on what kind of changes I should do here?</p> </blockquote> <p>I'm doing some authorisation here for which I think I should use a gem to handle, but currently not using any authorisation gems.</p> <p>Here's the mess</p> <pre class="lang-rb prettyprint-override"><code>class OffersController &lt; ApplicationController before_action :authenticate_user! before_action :offer_authorised, only: [:show] before_action :set_offer, only: [:accept, :reject, :send_signature_requests, :make_payment] before_action :is_authorised, only: [:accept, :reject] def create session[:return_to] ||= request.referer if !current_user.stripe_id? return redirect_to payment_path, alert: &quot;Connect your bank accout before payments.&quot; end rental = Rental.find(offer_params[:rental_id]) if rental &amp;&amp; rental.user_id == current_user.id redirect_to(request.referrer, alert: &quot;You cannot make an offer from your own property.&quot;) &amp;&amp; return end if current_user.offers.accepted.any? redirect_to(request.referrer, alert: &quot;You've already rented an apartment.&quot;) &amp;&amp; return end if Offer.exists?(user_id: current_user.id, rental_id: offer_params[:rental_id]) redirect_to(request.referrer, alert: &quot;You can only make one offer at a time.&quot;) &amp;&amp; return end @offer = current_user.offers.build(offer_params) @offer.landlord_id = rental.user.id if @offer.save redirect_to applications_path, notice: &quot;Offer sent.&quot; else redirect_to request.referrer, flash: {error: @offer.errors.full_messages.join(&quot;, &quot;)} end end def destroy @offer = Offer.find(params[:id]) @offer.destroy redirect_to request.referrer, notice: &quot;Offer deleted.&quot; end def accept if @offer.waiting? @offer.accepted! @offer.rental.update(active: !@offer.rental.active?) Offer.where(landlord_id: current_user.id, rental_id: @offer.rental.id).where.not(id: @offer.id).update_all(status: 2) @offer.rental.tours.destroy_all @offer.user.tours.destroy_all OfferMailer.with(offer: @offer, tenant: @offer.user_id, landlord: @offer.landlord_id).offer_accepted.deliver_now flash[:notice] = &quot;Offer accepted.&quot; end redirect_to offer_accepted_path(@offer) end def reject if @offer.waiting? @offer.rejected! flash[:notice] = &quot;Offer rejected.&quot; end redirect_to request.referrer end def update @offer = Offer.find(params[:id]) if params[:offer][:due_date] @offer.update(due_date: params[:offer][:due_date]) end if params[:offer][:rental_agreement] @offer.rental_agreement.purge @offer.rental_agreement.attach(params[:offer][:rental_agreement]) end flash[:notice] = &quot;Saved.&quot; redirect_to request.referrer end def show @offer = Offer.find(params[:id]) @rental = @offer.rental_id ? Rental.find(@offer.rental_id) : nil @comments = Comment.where(offer_id: params[:id]) @has_attachment_file_sent = Comment.where(user_id: @offer.landlord_id).any? { |obj| obj.attachment_file.attached? } respond_to do |format| format.html format.js { render layout: false } end end def pay_rent @offer = Offer.find(params[:id]) @rental = @offer.rental_id ? Rental.find(@offer.rental_id) : nil if @rental.user_referral_reward_count &gt; 0 referral_rent_payment(@rental, @offer) else make_payment(@rental, @offer) end flash[:notice] = &quot;Payment succeeded.&quot; redirect_to request.referrer end def send_signature_requests landlord_mail = User.where(id: @offer.landlord_id)[0].email tenant_mail = User.where(id: @offer.user_id)[0].email if @offer.rental_agreement.attached? attachment_file = @offer.rental_agreement blob_path = rails_blob_path(attachment_file, disposition: &quot;attachment&quot;, only_path: true) response = HTTParty.get(&quot;URL&quot;, body: { landlord_mail: landlord_mail, tenant_mail: tenant_mail, agreement_url: blob_path }.to_json, headers: {&quot;Content-Type&quot; =&gt; &quot;application/json&quot;}) @offer.update(invitation_uuid: response.parsed_response[&quot;invitation_uuid&quot;], document_uuid: response.parsed_response[&quot;document_uuid&quot;]) flash[:notice] = &quot;Signature requests sent.&quot; redirect_to request.referrer else flash[:alert] = &quot;Add aggreement.&quot; redirect_to request.referrer end rescue =&gt; e flash[:alert] = &quot;Failed to send signature requests.&quot; redirect_to request.referrer end private def make_payment(rental, offer) unless offer.user_stripe_id.blank? payment_methods = Stripe::PaymentMethod.list( customer: offer.user_stripe_id, type: &quot;sepa_debit&quot; ) payment_intent = Stripe::PaymentIntent.create({ payment_method_types: [&quot;sepa_debit&quot;], payment_method: payment_methods.data[0].id, confirm: true, off_session: true, customer: offer.user_stripe_id, amount: offer.amount * 100, currency: &quot;eur&quot;, application_fee_amount: offer.amount * 4, metadata: {&quot;name&quot; =&gt; User.where(id: offer.user_id).first.full_name, &quot;offer&quot; =&gt; offer.id}, transfer_data: { destination: rental.user_merchant_id } }) end rescue Stripe::CardError =&gt; e flash[:alert] = e.message end def referral_rent_payment(rental, offer) unless offer.user_stripe_id.blank? referrer = User.find_by(id: rental.user.id) customer = Stripe::Customer.retrieve(offer.user_stripe_id) charge = Stripe::Charge.create( customer: customer.id, amount: offer.amount * 100, description: &quot;Rent for #{rental.listing_name}&quot;, currency: &quot;eur&quot;, application_fee_amount: offer.amount * 2, metadata: {&quot;name&quot; =&gt; User.where(id: offer.user_id).first.full_name, &quot;offer&quot; =&gt; offer.id}, transfer_data: { destination: rental.user_merchant_id } ) referrer.update_attribute(:referral_reward_count, referrer.referral_reward_count -= 1) end rescue Stripe::CardError =&gt; e flash[:alert] = e.message end def offer_authorised unless Offer.exists?([&quot;id = ? AND (landlord_id = ? OR user_id = ?) AND status = ?&quot;, params[:id], current_user.id, current_user.id, 1]) redirect_to dashboard_path, alert: &quot;You're not authorized.&quot; end end def set_offer @offer = Offer.find(params[:id]) end def is_authorised redirect_to root_path, alert: &quot;You're not authorized.&quot; unless current_user.id == @offer.rental.user_id end def offer_params params.require(:offer).permit(:amount, :rental_id, :status, :priority, :rental_agreement) end end <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T20:17:00.487", "Id": "532305", "Score": "1", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), as well as [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436/120114) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T00:36:13.663", "Id": "532316", "Score": "0", "body": "Instead of moving some of that logic to the models and having a fat model for something that probably won't be necessary everywhere, I think you should consider to use [a service pattern](https://www.toptal.com/ruby-on-rails/rails-service-objects-tutorial) an move that logic there." } ]
[ { "body": "<h1>Only have CRUD actions in your controllers</h1>\n<p>Your controllers should only use the default CRUD actions index, show, new, edit, create, update, destroy.</p>\n<p>So rather than doing this</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class OffersController &lt; ApplicationController\n def accept; end\nend\n</code></pre>\n<p>you would have a dedicated controller</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class AcceptedOffersController &lt; ApplicationController\n def create; end\nend\n</code></pre>\n<p>Have a look at this article explaining this concept <a href=\"http://jeromedalbert.com/how-dhh-organizes-his-rails-controllers/\" rel=\"nofollow noreferrer\">http://jeromedalbert.com/how-dhh-organizes-his-rails-controllers/</a></p>\n<h2>Use service objects or Plain Old Ruby Objects</h2>\n<pre class=\"lang-rb prettyprint-override\"><code>class CreateOffer\n class Result\n def initialize(errors: [])\n @errors = errors\n end\n\n def valid?\n @errors.empty?\n end\n end\n\n def self.run(user:, params:)\n new(user: user, params: params).run\n end\n\n def initialize(user:, params:)\n @user = user\n @params = params\n end\n\n attr_reader :user, :params\n\n def run\n return Result.new(errors: 'Connect your bank account') unless bank_account?\n return Result.new(errors: 'You cannot make an offer from your own property.') if own_offer?\n\n # ...\n end\n\n private\n\n def bank_account?\n user.stripe_id?\n end\n\n def rental\n @rental ||= Rental.find(offer_params[:rental_id])\n end\n\n def own_offer?\n rental.user_id == user.id\n end\nend\n\nclass AcceptedOffersController &lt; ApplicationController\n def create\n result = CreateOffer.run(user: current_user, params: params)\n if result.valid?\n redirect_to applications_path, notice: &quot;Offer sent.&quot;\n else\n redirect_to(request.referrer, result.errors.join)\n end\n end\nend\n</code></pre>\n<p>Here is an example on service objects <a href=\"https://www.toptal.com/ruby-on-rails/rails-service-objects-tutorial\" rel=\"nofollow noreferrer\">https://www.toptal.com/ruby-on-rails/rails-service-objects-tutorial</a></p>\n<blockquote>\n<p>Is there other gems like rails_best_practices that I could use to figure out how to tidy up the controller?</p>\n</blockquote>\n<p>There won't be any gem which you can just pull in which will magically clean up your code for you. You should learn about Rails and clean code best practices first.</p>\n<p>A good book is <a href=\"https://www.poodr.com/\" rel=\"nofollow noreferrer\">Practical Object Oriented Design by Sandi Metz</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T23:19:55.677", "Id": "270033", "ParentId": "269738", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T18:23:25.470", "Id": "269738", "Score": "1", "Tags": [ "ruby", "ruby-on-rails", "controller", "e-commerce" ], "Title": "Rails controller to handle offers and payments for rental housing" }
269738
<p><strong>Context:</strong> I am trying to perform a <code>scan()</code> on a DynamoDB table and apply some conditional operators to a filter expression. The operators however are passed in via AWS Lambda's event field. This means the operator is determined by an external user and my code needs to handle all possible cases. <code>conditionAPIParam</code> is what contains the passed in parameter.</p> <p><strong>Current Solution:</strong> I currently use an if conditional to compare the operator to a set constant and then construct different versions of the db scan() command based on which operator is used.</p> <p><strong>Problem:</strong> This means that I have to construct a different version of the command per operator that I support. This is extremely redundant and leads to a lot of repeated code.</p> <p><strong>Question:</strong> Is there any way I could utilize the same command but just swap the operator (e.g. <code>gt()</code>, <code>begins_with()</code>, <code>lt()</code>) based on the provided conditional?</p> <p><strong>Code:</strong></p> <pre class="lang-py prettyprint-override"><code>GREATER_THAN = &quot;gt&quot; LESS_THAN = &quot;lt&quot; EQUAL = &quot;eq&quot; if conditionAPIParam == GREATER_THAN: query_response = table.scan( FilterExpression=Attr('Timestamp').gt(timestampAPIParam) &amp; Attr('Rule').contains(ruleAPIParam) # The default rule param is '' which is a part of every string ) elif conditionAPIParam == LESS_THAN: query_response = table.scan( FilterExpression=Attr('Timestamp').lt(timestampAPIParam) &amp; Attr('Rule').contains(ruleAPIParam) ) elif conditionAPIParam == EQUAL: query_response = table.scan( FilterExpression=Attr('Timestamp').begins_with(timestampAPIParam) &amp; Attr('Rule').contains(ruleAPIParam) # The default rule param is '' which is a part of every string ) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T23:58:15.277", "Id": "532315", "Score": "0", "body": "Can you indicate where `Attr` comes from? I've been unable to find documentation on it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T06:01:18.113", "Id": "532326", "Score": "0", "body": "It comes from boto3: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/customizations/dynamodb.html#boto3.dynamodb.conditions.Attr" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T08:06:45.090", "Id": "532334", "Score": "1", "body": "Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" } ]
[ { "body": "<p>Yes, you should simplify this. Make a dictionary whose key is any of the potential values for <code>conditionAPIParam</code>, and value is a non-bound class function reference.</p>\n<pre class=\"lang-py prettyprint-override\"><code>PARAMS = {\n 'gt': Attr.gt,\n 'lt': Attr.lt,\n 'eq': Attr.begins_with,\n}\nquery_response = table.scan(\n FilterExpression=PARAMS[conditionAPIParam](\n Attr('Timestamp'), # self\n timestampAPIParam,\n ) &amp; Attr('Rule').contains(ruleAPIParam)\n)\n</code></pre>\n<p>With a non-bound reference, the first parameter must be <code>self</code>, which in all cases will be <code>Attr('Timestamp')</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T06:06:42.160", "Id": "532327", "Score": "0", "body": "Interesting solution. Does this solution work because Python allows us to use functions as values to keys in a dict?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T08:59:35.267", "Id": "532336", "Score": "0", "body": "@Reinderien What would be the differences/pros/cons of using this approach vs getattr/methodcaller ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T13:02:57.267", "Id": "532356", "Score": "1", "body": "@PrithviBoinpally Python allows us to use functions as values basically anywhere (not just in a dict)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T13:06:43.143", "Id": "532357", "Score": "2", "body": "@kubatucka This approach is simple and compatible with static analysis. A `getattr` approach defeats static analysis and will not benefit from e.g. IDE autocomplete." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T00:09:33.917", "Id": "532426", "Score": "1", "body": "@Reinderien That's probably true, but OP should also be aware that they could use `getattr(Attr('Timestamp'),conditionAPIParam)(timestampAPIParam)` and not need `PARAMS`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T01:22:00.900", "Id": "532428", "Score": "2", "body": "@Teepeemm Not directly they can't. Note the difference between `eq` and `begins_with`." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T00:09:59.060", "Id": "269750", "ParentId": "269743", "Score": "5" } } ]
{ "AcceptedAnswerId": "269750", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T20:39:34.560", "Id": "269743", "Score": "3", "Tags": [ "python" ], "Title": "Scanning a DynamoDB table using a filter expression with multiple possible comparison operators" }
269743
<p>I'm writing a GUI for different VME modules (electronics). There are several of them which are used for the data acquisition. For example, an ADC produces the digitized maximum voltage on its input. So I need a way to visualize this data. Almost always this way is a <em>histogram</em>. So I've chosen the <a href="https://qwt.sourceforge.io/index.html#installonmainpage" rel="nofollow noreferrer">Qwt</a> library. The straightforward solution would be to connect the <code>QTimer</code>'s timeout signal to a slot in which the data is read and then to update a histogram. But it's bad, because no one knows in advance how long the reading and the processing would take, and most likely it would block the main loop. So, multi-threading.</p> <p>The core logic was stolen from <a href="https://doc.qt.io/qt-5/qtcore-threads-mandelbrot-example.html" rel="nofollow noreferrer">this</a> Qt's example.</p> <p>I think this code would be useful for people with the similar needs.</p> <hr /> <p>P.S. Sorry for the long post :)</p> <hr /> <p><a href="https://i.stack.imgur.com/Bzut6.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bzut6.gif" alt="enter image description here" /></a></p> <p>We have two classes in this example:</p> <ol> <li><code>DataGeneratorThread</code>: is a <code>QThread</code> and is responsible for the actual data generation (generates random numbers according to a gaussian p.d.f. )</li> <li><code>RealTimeHistogram</code>: the main widget, a user interface</li> </ol> <h1><code>DataGeneratorThread</code> class</h1> <h2><code>DataGeneratorThread.h</code></h2> <pre><code>#pragma once #include &lt;QThread&gt; #include &lt;QMutex&gt; #include &lt;QWaitCondition&gt; #include &lt;QMetaType&gt; #include &quot;qwt_samples.h&quot; Q_DECLARE_METATYPE(QVector&lt;QwtIntervalSample&gt;) class DataGeneratorThread : public QThread { Q_OBJECT public : DataGeneratorThread( QObject *parent = nullptr ); ~DataGeneratorThread() override; public slots : // These slots are the bridge between this thread // and the main one: they are to be called from the // parent thread void OnStart( size_t size ); void OnStop(); void OnPause(); void OnResume(); void Dump(); signals : // This signal is how this thread returns data // it is connected to the slot in the parent thread void DataGenerated( const QVector&lt;QwtIntervalSample&gt;&amp; data, unsigned nEvents ); protected : // The main function void run() override; private : // Flags to manipulate the control flow in // the run() function bool fAbort = false; bool fPause = false; bool fRestart = false; bool fDumpRequest = false; // Mutex to protect data access QMutex fMutex; // Condition to be able to put this thread // in the sleeping state when needed QWaitCondition fCondition; // Parameter of data generation size_t fSize; }; </code></pre> <h2><code>DataGenerator.cpp</code></h2> <pre><code>#include &lt;algorithm&gt; #include &lt;random&gt; #include &lt;QMutexLocker&gt; #include &quot;DataGenerator.h&quot; DataGeneratorThread::DataGeneratorThread( QObject* parent ) : QThread( parent ) { qRegisterMetaType&lt;QVector&lt;QwtIntervalSample&gt;&gt;(); } DataGeneratorThread::~DataGeneratorThread() { fMutex.lock(); fAbort = true;// Signal to return from run() (see below) fCondition.wakeOne();// Might be sleeping so awake fMutex.unlock(); wait();// Wait for return from run() before QThread::~QThread() } </code></pre> <p>The communication between this thread and the main one are performed through 5 public slots (they are to be called on the main thread's side) :</p> <pre><code>void DataGeneratorThread::OnStart( size_t size ) { QMutexLocker locker( &amp;fMutex ); fAbort = false; fPause = false; fSize = size; if( !isRunning() ) { start( LowPriority ); } else { fRestart = true;// Signal to restart calculation (see below) fCondition.wakeOne();//Might be sleeping so awake } } </code></pre> <p>This function is called when the main thread requests the new data to be generated.</p> <pre><code>void DataGeneratorThread::OnStop() { QMutexLocker locker( &amp;fMutex ); fAbort = true;// Signal to return from run (see below) fCondition.wakeOne(); } </code></pre> <p>This function is called when the main thread want to stop this thread.</p> <pre><code>void DataGeneratorThread::OnPause() { QMutexLocker locker( &amp;fMutex ); fPause = true;// fCondition.wakeOne(); } </code></pre> <p>This function is called when the main thread wants to <em>temporarily</em> stop data generation. This function puts this thread into sleep (not directly though, see the <code>run()</code> function).</p> <pre><code>void DataGeneratorThread::OnResume() { QMutexLocker locker( &amp;fMutex ); fPause = false; fCondition.wakeOne(); } </code></pre> <p>This function is complementary to the <code>OnPause()</code>.</p> <pre><code>void DataGeneratorThread::Dump() { QMutexLocker locker( &amp;fMutex ); fDumpRequest = true; } </code></pre> <p>This function signals that the main thread want to read the generated data.</p> <p>As you might notice, there is the <code>fCondition.wakeOne()</code> line in all but the last slots. This line wakes this thread if it's sleeping (see the <code>run()</code> function below). We don't awake the thread in the <code>Dump()</code> function intentionally, so we sure that there is no data update (no <code>DataGenerated</code> signal is emitted) when the thread is sleeping.</p> <pre><code>void DataGeneratorThread::run() { forever { fMutex.lock(); const size_t size = fSize; fMutex.unlock(); QVector&lt;QwtIntervalSample&gt; data( size ); unsigned n = 0; // Initialize histogram for( size_t i = 0; i &lt; size; ++i ) { data[i] = QwtIntervalSample( 0.0, i, i + 1 ); } std::random_device rd; std::mt19937 gen( rd() ); forever { if( fAbort )// Accessible from the OnStart() and OnStop() { return; } if( fDumpRequest )// Accessible from the Dump() { emit DataGenerated( data, n );// This signal is catched by the RealTimeHistogram fMutex.lock(); fDumpRequest = false; fMutex.unlock(); } if( fPause ) { fMutex.lock(); fCondition.wait( &amp;fMutex );// Go to sleep fMutex.unlock(); } if( fRestart ) { break; } std::normal_distribution&lt;&gt; g( size / 2., size / 20. ); size_t rand = std::round( g( gen ) ); if( rand &lt; size ) { data[ rand ].value += 1;// Fill histogram n++; } } // The only way to break from the innermost forever loop is the fRestart flag fMutex.lock(); fRestart = false; fMutex.unlock(); } } </code></pre> <p>As you can see the <code>run()</code> function consists of an infinite loop. The only way to return from it is the <code>fAbort</code> flag. The meaning of other flags is obvious: <code>fPause</code> puts this thread into sleep; <code>fRestart</code> restarts data generation; <code>fDumpRequest</code> signals that the data must be sent to the main thread.</p> <h1><code>RealTimeHistogram</code> class</h1> <p>This class contains the user interface and is supposed to be instantiated in the main thread. It is shown on the gif in the beginning of the post.</p> <h2><code>RealTimeHistogram.h</code></h2> <pre><code>#pragma once #include &lt;QWidget&gt; #include &quot;DataGenerator.h&quot; class QTimer; class QPushButton; class QwtPlot; class QwtPlotHistogram; class QwtPlotMarker; class RealTimeHistogram : public QWidget { Q_OBJECT private : static constexpr size_t N_BINS = 4096; QTimer *fTimer; QPushButton *fStartButton, *fStopButton, *fPauseButton; QwtPlot *fPlot; QwtPlotMarker *fStatistics; QwtPlotHistogram *fHisto; DataGeneratorThread fThread; private : void CreateWidgets(); void CreateTimer(); public slots : void InitHistogram(); void UpdateData( const QVector&lt;QwtIntervalSample&gt;&amp; data, unsigned nEvents ); void UpdateStat( unsigned nEvents ); void StartTimer(); void StopTimer(); void Pause(); public : RealTimeHistogram( QWidget* parent = nullptr ); ~RealTimeHistogram() override = default; }; </code></pre> <h2><code>RealTimeHistogram.cpp</code></h2> <pre><code>#include &lt;QPushButton&gt; #include &lt;QTimer&gt; #include &lt;QFrame&gt; #include &lt;QVBoxLayout&gt; #include &lt;QHBoxLayout&gt; #include &lt;qwt_plot.h&gt; #include &lt;qwt_plot_histogram.h&gt; #include &lt;qwt_plot_grid.h&gt; #include &lt;qwt_plot_layout.h&gt; #include &lt;qwt_legend.h&gt; #include &lt;qwt_plot_marker.h&gt; #include &quot;RealTimeHistogram.h&quot; RealTimeHistogram::RealTimeHistogram( QWidget* parent ) : QWidget( parent ) { CreateWidgets(); CreateTimer(); connect( &amp;fThread, &amp;DataGeneratorThread::DataGenerated, this, &amp;RealTimeHistogram::UpdateData ); } </code></pre> <p>This is how the data goes from the <code>DataGeneratorThread</code>: this class &quot;catches&quot; the signal with the data provided as arguments.</p> <pre><code>void RealTimeHistogram::CreateWidgets() { QVBoxLayout* vLayout = new QVBoxLayout(); // Buttons fStartButton = new QPushButton( &quot;START&quot; ); fStartButton-&gt;setStyleSheet( &quot;background-color: #a8ffe9&quot; ); connect( fStartButton, &amp;QPushButton::clicked, this, &amp;RealTimeHistogram::InitHistogram ); connect( fStartButton, &amp;QPushButton::clicked, this, &amp;RealTimeHistogram::StartTimer ); fPauseButton = new QPushButton( &quot;PAUSE&quot; ); fPauseButton-&gt;setStyleSheet( &quot;background-color: #b6b6b6&quot; ); connect( fPauseButton, &amp;QPushButton::clicked, this, &amp;RealTimeHistogram::Pause ); fStopButton = new QPushButton( &quot;STOP&quot; ); fStopButton-&gt;setStyleSheet( &quot;background-color: #6d6d6d; color: #ffffff&quot; ); connect( fStopButton, &amp;QPushButton::clicked, &amp;fThread, &amp;DataGeneratorThread::OnStop ); connect( fStopButton, &amp;QPushButton::clicked, this, &amp;RealTimeHistogram::StopTimer ); QFrame *buttonFrame = new QFrame(); QHBoxLayout *buttonLayout = new QHBoxLayout(); buttonLayout-&gt;addWidget( fStartButton ); buttonLayout-&gt;addWidget( fPauseButton ); buttonLayout-&gt;addWidget( fStopButton ); buttonFrame-&gt;setLayout( buttonLayout ); vLayout-&gt;addWidget( buttonFrame ); // Histogram fPlot = new QwtPlot(); fPlot-&gt;setAxisTitle( QwtPlot::yLeft, &quot;Number of events&quot; ); fPlot-&gt;setAxisTitle( QwtPlot::xBottom, &quot;Value&quot; ); fPlot-&gt;setCanvasBackground( QColor( &quot;#b6b6b6&quot; ) ); fPlot-&gt;plotLayout()-&gt;setAlignCanvasToScales( true ); fPlot-&gt;insertLegend( new QwtLegend(), QwtPlot::RightLegend ); QwtPlotGrid *grid = new QwtPlotGrid; grid-&gt;enableX( true ); grid-&gt;enableY( true ); grid-&gt;attach( fPlot ); grid-&gt;setMajorPen( QPen( QColor( &quot;#ffffff&quot; ), 0, Qt::DotLine ) ); fHisto = new QwtPlotHistogram( &quot;Data&quot; ); fHisto-&gt;setPen( QPen( QColor( &quot;#a8ffe9&quot; ) ) ); fHisto-&gt;setBrush( QBrush( QColor( &quot;#a8ffe9&quot; ) ) ); fHisto-&gt;attach( fPlot ); fStatistics = new QwtPlotMarker(); fStatistics-&gt;attach( fPlot ); fPlot-&gt;show(); fPlot-&gt;replot(); UpdateStat( 0 ); vLayout-&gt;addWidget( fPlot ); setLayout( vLayout ); } </code></pre> <p>This function creates widgets which is irrelevant to the main topic. Although it is worth to note that those slots in the <code>DataGeneratorThread</code> are connected to the <code>clicked</code> signals of the buttons.</p> <pre><code>void RealTimeHistogram::CreateTimer() { fTimer = new QTimer( this ); fTimer-&gt;setInterval( 1000 ); connect( fTimer, &amp;QTimer::timeout, &amp;fThread, &amp;DataGeneratorThread::Dump ); } </code></pre> <p>That's it : the timer just generates a dump request every second.</p> <pre><code>void RealTimeHistogram::InitHistogram() { QVector&lt;QwtIntervalSample&gt; histData; for( size_t i = 0; i &lt; N_BINS; ++i ) { histData.push_back( QwtIntervalSample( 0.0, i, i + 1 ) ); } fHisto-&gt;setSamples( histData ); fThread.OnStart( N_BINS ); } </code></pre> <p>Nothing special here (and maybe even redundant), except the last line which starts (or restarts) data generation.</p> <pre><code>void RealTimeHistogram::StartTimer() { if( not fTimer-&gt;isActive() ) { fTimer-&gt;start(); } } void RealTimeHistogram::StopTimer() { if( fTimer-&gt;isActive() ) { fTimer-&gt;stop(); } } </code></pre> <p>This is how we manage the timer.</p> <pre><code>void RealTimeHistogram::Pause() { QPushButton* button = qobject_cast&lt;QPushButton*&gt;( this-&gt;sender() ); if( button-&gt;text() == &quot;PAUSE&quot; ) { fThread.OnPause(); button-&gt;setText( &quot;RESUME&quot; ); } else if( button-&gt;text() == &quot;RESUME&quot; ) { fThread.OnResume(); button-&gt;setText( &quot;PAUSE&quot; ); } } </code></pre> <p>Depending on the name of the button this function either pauses or resumes data generation.</p> <pre><code>void RealTimeHistogram::UpdateData( const QVector&lt;QwtIntervalSample&gt;&amp; data, unsigned nEvents ) { fHisto-&gt;setSamples( data ); fPlot-&gt;replot(); UpdateStat( nEvents ); } </code></pre> <p>Here is how we use the generated data. Remember this slot is connected to the <code>DataGeneratorThread::DataGenerated()</code> signal.</p> <pre><code>void RealTimeHistogram::UpdateStat( unsigned nEvents ) { QwtScaleMap xMap = fPlot-&gt;canvasMap( QwtPlot::xBottom ); double x = (xMap.s1() + xMap.s2()) * 0.5; QwtScaleMap yMap = fPlot-&gt;canvasMap( QwtPlot::yLeft ); double y = (yMap.s1() + yMap.s2()) * 0.3; fStatistics-&gt;setValue( x, y ); fStatistics-&gt;setLabel( QwtText( QString( &quot;Number of events = %1&quot; ).arg( nEvents ) ) ); } </code></pre> <p>The function to place the label with the number of events correctly on the canvas.</p> <hr /> <h1>EDIT</h1> <p>Full code can be found at <a href="https://github.com/LRDPRDX/QwtRealTimeHistogram" rel="nofollow noreferrer">this</a> repo.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T07:05:23.897", "Id": "532328", "Score": "2", "body": "Is there any repo I could clone and play with?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T12:05:49.853", "Id": "532353", "Score": "0", "body": "@Incomputable, Added a link to the repo. And any feedback would be appreciated." } ]
[ { "body": "<h2>Build</h2>\n<p>I believe build scripts are a major part of the code. If nobody can incorporate it into their build, then the piece code is useless. Yours is good, but it seems the default distribution provides pkg-config files. I tried to use <code>pkg_check_modules</code> inside cmake, but after scratching my head for two hours I gave up on doing it by the book, for now (I will try to write a find module and link a github gist here, sometime later).</p>\n<h2>Bug</h2>\n<p>When I press start, then pause (pause button changes into resume), then start, the resume button does not change into pause as it should.</p>\n<p><s>## Memory leak?</p>\n<p>I'm not proficient in Qt's memory management style, but from what I know, all QObject instances must specify a parent if they want to be hooked into automatic memory management system. Constructor inside of the histogram does not specify parent for member objects and the destructor is trivial, which seems wrong.</s></p>\n<h2>Synchronization</h2>\n<p>The only reason the code works as is is because of X86 quirks of atomic read/write by default. On a platform where that is not the case, <code>volatile</code> is required for them to work.</p>\n<p>Instead of fine grained locking, it might be better to use atomic on the combination of state variable (combine start, pause and stop into one enum-like atomic variable). There is also potential deadlock in the destructor: if the worker thread will check abort, then user pauses and quickly exits (well, <em>human</em> probably cannot do that), it might be possible that worker thread will see false abort and go into a pause section, where it will miss the awake on condition variable, thus stuck forever. The solution is to coalesce the state variables (start, pause, stop, dump) into one variable and read under lock, or lock all of the if branches (which is bad). The easiest solution is to use a semaphore: there is no awake signal to miss. If the condition variables will be merged into one, atomic type might be useful, since worker thread only reads from them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T16:30:49.480", "Id": "532382", "Score": "0", "body": "This will be a bit of a rolling review. I'll keep adding to it when I'll have the time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T16:58:52.350", "Id": "532391", "Score": "0", "body": "Thank you for your answer. First of all, the **Bug** section. I intentionally left this behavior as I wanted to check everything worked as intended. And it did." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T17:02:18.230", "Id": "532392", "Score": "0", "body": "Now the **Memory leak** section. \"...all QObject instances must specify a parent if they want to be hooked into automatic memory management system\". No, they shouldn't --- it would be a nightmare. The layout and plot are responsible for the deletion of those objects." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T17:08:48.487", "Id": "532393", "Score": "0", "body": "The **Build**. I tried to provide a \"code only\" solution to the problem I encountered because there are not many (I didn't find any :) ) examples of this problem on the Internet. It's just source code. No more. No less." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T17:10:08.287", "Id": "532394", "Score": "0", "body": "Take your time. I appreciate your feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T17:22:38.213", "Id": "532395", "Score": "0", "body": "Oh, I didn't understand correctly your statement about parenting `QObject`s. Specifying a parent is **not** a nightmare ofc. But here is no need for that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T17:24:18.043", "Id": "532396", "Score": "0", "body": "@LRDPRDX, [this](https://doc.qt.io/qt-5/qhboxlayout.html#dtor.QHBoxLayout) says that least layout does not delete its layed out widgets. I didn't check Qwt, but my guess would be similar. If they do not manually reparent their objects, they might double delete in case when parent **is** specified." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T17:29:27.110", "Id": "532397", "Score": "0", "body": "They are reparented when `setLayout` function is called." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T17:30:36.813", "Id": "532398", "Score": "0", "body": "`QwtPlot` deletes its `attach`ed widgets." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T16:30:07.820", "Id": "269781", "ParentId": "269745", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T21:22:58.940", "Id": "269745", "Score": "3", "Tags": [ "c++", "multithreading", "gui", "qt" ], "Title": "Real time histogram using multithreading (Qt + Qwt)" }
269745
<p>I have referred to this for what constitutes as an Euler Cycle: <a href="https://xlinux.nist.gov/dads/HTML/eulercycle.html" rel="nofollow noreferrer">https://xlinux.nist.gov/dads/HTML/eulercycle.html</a></p> <p>This assignment required me to use Depth First Search and have the methods I have included. I am also required to use the Graph class provided here: <a href="https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/Graph.java.html" rel="nofollow noreferrer">https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/Graph.java.html</a></p> <p>I have tested and in my eyes, it works well. Code wise, I feel like it has a lot to improve hence I am here to ask for simple/general advice.</p> <pre><code>import edu.princeton.cs.algs4.GraphGenerator; import java.util.ArrayList; import java.util.LinkedList; public class EulerFinder { private Graph g; private boolean[] visited; private ArrayList&lt;Integer&gt; order = new ArrayList&lt;&gt;(); public EulerFinder(Graph g) { System.out.println(&quot;og graph for reference:\n&quot;); System.out.println(g); System.out.println(&quot;------------------------------&quot;); this.g = g; visited = new boolean[g.E()]; if (hasCycle(g)) { System.out.println(&quot;The cycle for the generated graph is: &quot;); for (int vertex : verticesInCycle()) { System.out.println(vertex); } } else { System.out.println(&quot;No Euler cycle could be found&quot;); } } public static void main(String[] args) { Graph graph1 = new Graph(4); graph1.addEdge(3, 1); graph1.addEdge(1, 0); graph1.addEdge(0, 2); graph1.addEdge(2, 3); //Graph graph = GraphGenerator.eulerianCycle(5, 5); EulerFinder result = new EulerFinder(graph1); } public boolean hasCycle(Graph g) { if (!evenDegree(g)) return false; return true; } private boolean evenDegree(Graph g) { for(int i = 0; i &lt; g.V(); i++) { if(g.degree(i) %2 != 0) return false; } return true; } private void DFS(int vertex) { order.add(vertex); visited[vertex] = true; Iterable&lt;Integer&gt; next = g.adj(vertex); for (int adj : next) { if(!visited[adj]) { DFS(adj); } } } public ArrayList&lt;Integer&gt; verticesInCycle() { if (g.E() &gt; 0) { DFS(g.E() - 1); } else System.out.println(&quot;\nNone! There must be more than 0 edges...&quot;); return order; } } </code></pre> <p>the output for the above example (from main) yields:</p> <pre><code>og graph for reference: 4 vertices, 4 edges 0: 2 1 1: 0 3 2: 3 0 3: 2 1 ------------------------------ The cycle for the generated graph is: 3 2 0 1 Process finished with exit code 0``` </code></pre>
[]
[ { "body": "<p>Given it seems to be <code>princeton.cs.algs4</code> course task I am not entirely sure what would be the best answer here. I'd assume you are suppose to learn and learning limited number of things at a time (here DFS and euler cycles?) is pretty good practice, so in terms of <em>what purpose does this code serve</em> if <em>you</em> wrote it, it works and you understand why - it seems already pretty good.</p>\n<p>Assuming you are asking for tips outside of the above scope that you can consider:</p>\n<ol>\n<li>writing tests - in general high quality, production-grade, code usually requires some <em>automatic correctness verification</em>, most often represented by tests (unit, integration etc... here probably unit tests are enough), you can consider writing tests for this solution - then you will not need to <em>feel</em> that it is correct - you will be able to <strong>prove</strong> it :)</li>\n<li>limiting mutability - from my experience during studies this point was not emphasized enough, generally its easier to reason about the code if fields are immutable by default - and only strictly necessary state is mutable</li>\n<li>Using IDE with some static analysis (like Intelij Idea with SonarLint plugin... and default inspections for java - you can find them in options) - it will not be perfect but should point out such classics like:</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code> public boolean hasCycle(Graph g) {\n if (!evenDegree(g))\n return false;\n return true;\n }\n</code></pre>\n<p>that could be replaced with (not to mention that inner function could be inlined):</p>\n<pre class=\"lang-java prettyprint-override\"><code> public boolean hasCycle(Graph g) {\n return evenDegree(g);\n }\n</code></pre>\n<ol start=\"4\">\n<li>Names - its not that big thing in such a project but in general abbreviations (like <code>g</code> for <code>graph</code>) are not always more readable - you can try to think on them a little</li>\n<li>Formatting - you should aim for being consistent with your braces, newlines etc (sometimes in <code>if</code>/<code>else</code> blocks you have <code>{}</code>, sometimes not, some newlines are surprising) - its a cosmetic but still, professionals are expected not to introduce such noise (good IDE can help you with it too)</li>\n</ol>\n<p>Don't stress on those too much though - its rather expected for learning programs to feel clunky (especially algorithmic ones).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T02:31:01.287", "Id": "532430", "Score": "0", "body": "Thank you for your comment. I was also curious as to a graph, i.e. 4 vertices. If 0-3 are all connected and even degree, and then vertex 3 is disconnected, is it still correct that my program outputs \"3\" instead of, say, \"1,2,0\"? My DFS will always choose the largest vertex possible..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T14:52:49.700", "Id": "269776", "ParentId": "269753", "Score": "1" } } ]
{ "AcceptedAnswerId": "269776", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T03:52:09.850", "Id": "269753", "Score": "0", "Tags": [ "java", "algorithm", "graph", "depth-first-search" ], "Title": "Recursive DFS to find Euler Cycle" }
269753
<p>I am a novice when it comes to C++ (as well as C++/CLI). I am trying to write a minimal 64-bit implementation of a List in C++ (using <code>unsigned __int64</code> as the index data type), to store <code>unsigned char</code> values (bytes), as well as a C++/CLI wrapper for it that I will use to later to talk to it in C# land.</p> <p>I may have succeeded (preliminary tests look good), so I am submitting the code for your review. Any helpful comments about changes I could make the code better would be appreciated, as well as comments about where the code might break down (this will be my first unmanaged / managed code wrapper).</p> <p>Some background: I wrote this code because I needed a larger byte list in C#. I am working on a 64-bit memory scanner, and want to eventually suspend a program, then copy it in its entirety into a giant byte list for later digestion.</p> <pre><code>//UnmanagedBigByteList.h #pragma once #include &lt;iostream&gt; class UnmanagedBigByteList { private: std::uint64_t _capacity = 4; std::uint64_t _count = 0; std::uint8_t* _items; void grow() { std::uint64_t newcapacity = _capacity * 2; std::uint8_t* newitems = new std::uint8_t[newcapacity]; for (std::uint64_t i = 0; i &lt; _capacity; i++) { newitems[i] = _items[i]; //std::cout &lt;&lt; &quot;Adding &quot; &lt;&lt; i &lt;&lt; &quot; Element to grown list.&quot; &lt;&lt; std::endl; } delete[] _items; _items = newitems; _capacity = newcapacity; } public: UnmanagedBigByteList() { _items = new std::uint8_t[_capacity]; } ~UnmanagedBigByteList() { delete[] _items; } void Add(std::uint8_t byte) { if (_capacity == _count) { grow(); } _items[_count] = byte; _count++; } void Clear() { delete[] _items; _capacity = 4; _count = 0; _items = new std::uint8_t[_capacity]; } bool Contains(std::uint8_t byte) { for (std::uint64_t i = 0; i &lt; _count; i++) { if (byte == _items[i]) { return true; } } return false; } bool IndexOf(std::uint8_t byte, std::uint64_t* index) { for (std::uint64_t i = 0; i &lt; _count; i++) { if (byte == _items[i]) { *(index) = i; return true; } } return false; } std::uint64_t Count() { return _count; } std::uint64_t Capacity() { return _capacity; } std::uint8_t&amp; operator[](std::uint64_t index) { return _items[index]; } }; //ManagedBigByteList.h #pragma once #include &quot;UnmanagedBigByteList.h&quot; using namespace System; namespace BigGenerics { public ref class ManagedBigByteList { private: UnmanagedBigByteList* _ubbl; public: ManagedBigByteList() { _ubbl = new UnmanagedBigByteList(); } ~ManagedBigByteList() { delete _ubbl; } void Add(std::uint8_t byte) { _ubbl-&gt;Add(byte); } void Clear() { _ubbl-&gt;Clear(); } bool Contains(std::uint8_t byte) { return _ubbl-&gt;Contains(byte); } bool IndexOf(std::uint8_t byte, std::uint64_t* index) { return _ubbl-&gt;IndexOf(byte, index); } property std::uint64_t Count { std::uint64_t get() { return _ubbl-&gt;Count(); } } property std::uint64_t Capacity { std::uint64_t get() { return _ubbl-&gt;Capacity(); } } property std::uint8_t&amp; default[std::uint64_t] { std::uint8_t&amp; get(std::uint64_t index) { return (*(_ubbl))[index]; } void set(std::uint64_t index, std::uint8_t&amp; value) { (*(_ubbl))[index] = value; } } }; } //BigGenericsTest.cpp #include &quot;pch.h&quot; #include &quot;ManagedBigByteList.h&quot; using namespace System; using namespace BigGenerics; int main(array&lt;System::String ^&gt; ^args) { ManagedBigByteList^ newList = gcnew ManagedBigByteList(); for (std::uint64_t i = 0; i &lt; 60; i++) { std::uint8_t newItem = i; newList-&gt;Add(newItem); } //unsigned char newItem2 = 200; //newList[59] = newItem2; //unsigned char* newItem3 = new unsigned char(150); //newList[58] = *newItem3; //newList[59] = unsigned char(2000); System::Console::WriteLine(&quot;Checking if IndexOf() works.&quot;); std::uint64_t* index; if (newList-&gt;IndexOf(std::uint8_t(30), index)) { System::Console::WriteLine(&quot;IndexOf works!&quot;); System::Console::WriteLine(&quot;Value of 30 found at: &quot; + *index); } for (std::uint64_t i = 0; i &lt; newList-&gt;Count; i++) { System::Console::WriteLine(i + &quot; Element is: &quot; + newList[i].ToString()); //unsigned char newItem = i; //newList-&gt;Add(newItem); } //System::Console::WriteLine(&quot;First Element is: &quot; + newList[0].ToString()); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T10:52:52.407", "Id": "532346", "Score": "0", "body": "Apparently there is. :-). I've updated the code. I've been using this (https://docs.microsoft.com/en-us/cpp/dotnet/managed-types-cpp-cli?view=msvc-160) as a guide to the data types (C++ vs. .Net), which is why I was using the double-underscore type. Is there a better guide, or is it just something you become familiar with as you learn the language?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T10:54:20.533", "Id": "532347", "Score": "0", "body": "No idea, I'm afraid - I only use standard C++, and very averse to using compilers' internal types. That's why I asked." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T16:15:44.900", "Id": "532380", "Score": "1", "body": "Why not just use a `std::vector<std::uint8_t>` to store the bytes?" } ]
[ { "body": "<p>I'm not sure why you don't simply use a <code>List&lt;byte&gt;</code> in C# or <code>std::vector&lt;std::uint8_t&gt;</code> in C++ as already mentioned by G.Sliepen.</p>\n<p>I'm going to ignore that for now and continue with the review.</p>\n<h1>Use the correct types.</h1>\n<p>You should use <code>std::size_t</code> instead of <code>std::uint64_t</code> for the array size and index variables. Using <code>std::uint64_t</code> in 32-bit mode will not allow your list to be any bigger than using a 32-bit type.</p>\n<h1>Shrinking the list</h1>\n<p>Consider adding a <code>ShrinkToSize</code> function. Your current implementation only allows for the list to grow.</p>\n<h1>Checking if <code>new</code> was successful</h1>\n<p>You cannot simply assume that there is enough memory available.</p>\n<h1>Optimizing <code>Grow</code></h1>\n<p>In <code>void grow()</code> you copy the existing element one by one. Modern compilers may be smart enough to automatically translate this into a call to <code>memcpy</code> or <code>memmove</code> but I would rather have used <code>std::copy</code>.</p>\n<p>For these types of lists with <b>basic</b> types, good old C's memory allocation functions have an ace up its sleeve over C++'s <code>new</code> and <code>delete</code>. You could have used <code>malloc</code> instead of <code>new</code> and <code>free</code> instead of <code>delete</code> and then <code>realloc</code> to grow or shrink the list.</p>\n<h1>Using templates</h1>\n<p>You can use templates to make your list reusable for different types:</p>\n<pre><code>template &lt;class T&gt;\nclass UnmanagedBigByteList\n{\nprivate:\n std::uint64_t _capacity = 4;\n std::uint64_t _count = 0;\n T* _items;\n // ...\n}\n</code></pre>\n<br>\n<pre><code>template &lt;class T&gt;\npublic ref class ManagedBigByteList\n{\nprivate:\n UnmanagedBigByteList&lt;T&gt;* _ubbl;\npublic:\n ManagedBigByteList()\n {\n _ubbl = new UnmanagedBigByteList&lt;T&gt;();\n }\n // ...\n}\n</code></pre>\n<br>\n<pre><code>int main(array&lt;System::String^&gt;^ args)\n{\n ManagedBigByteList&lt;std::uint8_t&gt;^ newList = gcnew ManagedBigByteList&lt;std::uint8_t&gt;();\n for (std::uint64_t i = 0; i &lt; 60; i++)\n {\n std::uint8_t newItem = i;\n newList-&gt;Add(newItem);\n }\n // ..\n}\n</code></pre>\n<h1>Final thoughts</h1>\n<p>I suspect that you may be trying to implement a 64-bit List in a 32-bit address space. This is not impossible but would be much more complicated than simply using 64-bit size and index variables.</p>\n<p>To do this you will need to split the list into blocks/pages that can either be in RAM or in a file. How to manage this optimally would make a great new question :-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T21:44:47.370", "Id": "532846", "Score": "0", "body": "Thank you so much for your review. \nWhat I've been trying to do is implement a 64-bit memory scanner in C# (in which I copy the entirety of a live, but suspended program, into a giant byte list for analysis), but ran into the problem that the largest number of elements someone can allocate (for a list) in .Net is a uint32's max value. To get around this, I am writing part of it in unmanaged C++, with a managed C++ wrapper. The machine I am developing this on is a Threadripper, with 256 GB of RAM, so there is plenty of memory for scanning and debugging 64-bit programs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T21:45:13.333", "Id": "532847", "Score": "0", "body": "Does std::vector support an unsigned int64's max value worth of elements?\n\nI tried writing this initially with templates in mind, but incompatibilities between generics and templates had me giving up in frustration. \n\nEverything else is spot on. I thank you for your time, and patience. I wish I could reward you more." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T22:05:52.773", "Id": "532849", "Score": "0", "body": "@user3799003, `std::vector` does not have this same stupid limitation as `List` so you are good to go!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T22:15:12.537", "Id": "532850", "Score": "0", "body": "@user3799003, one more thing that you should consider is that there is a cost involved every time you move between the managed and unmanaged space. It may be better to batch your calls to `BigByteList` instead of adding one element at a time. Here it would be best to experiment and see what is the most efficient =)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T13:14:12.910", "Id": "269847", "ParentId": "269755", "Score": "1" } } ]
{ "AcceptedAnswerId": "269847", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T04:21:52.063", "Id": "269755", "Score": "1", "Tags": [ "c++", ".net", "c++-cli" ], "Title": "BigByteList with a managed wrapper" }
269755
<p>This code cleans up a big dataset into a very clean and a flat file that can be further used downstream like visualization.</p> <p>I am expecting to improve the code to essentially run it faster and cleanup the code to avoid any inefficient functions that should not take further resources than it should.</p> <p>The problem is that I have written the code as and when I have experienced any functions as needed to be added on the fly and now, I am not very happy with it.</p> <p>I am seeking help from this community on the best code that can be written which performs the same work that this code does. I would also be learning on the best practices while working with pandas.</p> <p>There is so much on the internet on Pandas that every function and code seems to be a clean code but when i look at it collectively, its so bad.</p> <p>My <a href="https://gofile.io/d/ugCVSF" rel="nofollow noreferrer">dataframe</a>:</p> <pre><code>df.head() Unnamed: 0 game score home_odds draw_odds away_odds country league datetime 0 0 Sport Recife - Imperatriz 2:2 1.36 4.31 7.66 Brazil Copa do Nordeste 2020 2020-02-07 00:00:00 1 1 ABC - America RN 2:1 2.62 3.30 2.48 Brazil Copa do Nordeste 2020 2020-02-02 22:00:00 2 2 Frei Paulistano - Nautico 0:2 5.19 3.58 1.62 Brazil Copa do Nordeste 2020 2020-02-02 00:00:00 3 3 Botafogo PB - Confianca 1:1 2.06 3.16 3.5 Brazil Copa do Nordeste 2020 2020-02-02 22:00:00 4 4 Fortaleza - Ceara 1:1 2.19 2.98 3.38 Brazil Copa do Nordeste 2020 2020-02-02 22:00:00 df.describe() Unnamed: 0 count 1.115767e+06 mean 5.574871e+05 std 3.220941e+05 min 0.000000e+00 25% 2.785455e+05 50% 5.574870e+05 75% 8.364285e+05 max 1.115370e+06 </code></pre> <p>I use this code to cleanup the dataframe:</p> <pre><code>from datetime import datetime import pandas as pd import numpy as np from tabulate import tabulate start = datetime.now() df = pd.read_csv() #This part essentially splits columns and harmonises the entie dataframe # This code harmonises the game column e.g. &quot;Talleres (R.E) - Defensores Unidos&quot; should be as &quot;Talleres - &quot;Defensores Unidos&quot; removing any brackets and its values and removes any date values in the column df['game'] = df['game'].astype(str).str.replace('(\(\w+\))', '', regex=True) df['game'] = df['game'].astype(str).str.replace('(\s\d+\S\d+)$', '', regex=True) # This code removes any numerical values in the league column. Many times the league column has years concatenated which is what we don't want e.g &quot;Brazil Copa do Nordeste 2020&quot; should be &quot;Brazil Copa do Nordeste&quot; df['league'] = df['league'].astype(str).str.replace('(\s\d+\S\d+)$', '', regex=True) # This part splits the game column into two competing teams i.e. home team and away team by the delimiter &quot;-&quot; df[['home_team', 'away_team']] = df['game'].str.split(' - ', expand=True, n=1) # This part splits the score column into two competing teams i.e. home score and away score by the delimiter &quot;:&quot; df[['home_score', 'away_score']] = df['score'].str.split(':', expand=True) # This code removes any non numerical values in the home score and away score columns. e.ge scores can't have &quot;aet&quot;, &quot;canc&quot;, &quot;.&quot;, etc. We dont want anything that cannot be identified as filetype:int in pandas df['away_score'] = df['away_score'].astype(str).str.replace('[a-zA-Z\s\D]', '', regex=True) df['home_score'] = df['home_score'].astype(str).str.replace('[a-zA-Z\s\D]', '', regex=True) df = df[df.home_score != &quot;.&quot;] df = df[df.home_score != &quot;..&quot;] df = df[df.home_score != &quot;.&quot;] df = df[df.home_odds != &quot;-&quot;] df = df[df.draw_odds != &quot;-&quot;] df = df[df.away_odds != &quot;-&quot;] m = df[['home_odds', 'draw_odds', 'away_odds']].astype(str).agg(lambda x: x.str.count('/'), 1).ne(0).all(1) n = df[['home_score']].agg(lambda x: x.str.count('-'), 1).ne(0).all(1) o = df[['away_score']].agg(lambda x: x.str.count('-'), 1).ne(0).all(1) # I get UserWarning: Boolean Series key will be reindexed to match DataFrame index. at these parts df = df[~n] df = df[~m] df = df[~n] df = df[~o] df = df[df.home_score != ''] df = df[df.away_score != ''] df = df.dropna() # We now would be keeping only the columns we want df = df.loc[:, df.columns.intersection( ['datetime', 'country', 'league', 'home_team', 'away_team', 'home_odds', 'draw_odds', 'away_odds', 'home_score', 'away_score'])] #We are making sure that the columns are as per data types that we would want pandas to identify. Pandas does not seem to do a very good job identifying data types correctly. colt = { 'country': str, 'league': str, 'home_team': str, 'away_team': str, 'home_odds': float, 'draw_odds': float, 'away_odds': float, 'home_score': int, 'away_score': int } df = df.astype(colt) # This part removes any leading and trailing whitespaces in the string columns df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x) # Cleaning data where odds are greater than 100 and less than -1 and dropping duplicates df = df[df['home_odds'] &lt;= 100] df = df[df['draw_odds'] &lt;= 100] df = df[df['away_odds'] &lt;= 100] df = df.drop_duplicates(['datetime', 'home_score', 'away_score', 'country', 'league', 'home_team', 'away_team'], keep='last') df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x) df.to_csv() time_taken = end - start print('Time taken to complete: ', time_taken) df.head() home_odds draw_odds away_odds country league datetime home_team away_team home_score away_score -- ----------- ----------- ----------- --------- ---------------- ------------------- --------------- ----------- ------------ ------------ 0 1.36 4.31 7.66 Brazil Copa do Nordeste 2020-02-07 00:00:00 Sport Recife Imperatriz 2 2 1 2.62 3.3 2.48 Brazil Copa do Nordeste 2020-02-02 22:00:00 ABC America RN 2 1 2 5.19 3.58 1.62 Brazil Copa do Nordeste 2020-02-02 00:00:00 Frei Paulistano Nautico 0 2 3 2.06 3.16 3.5 Brazil Copa do Nordeste 2020-02-02 22:00:00 Botafogo PB Confianca 1 1 4 2.19 2.98 3.38 Brazil Copa do Nordeste 2020-02-02 22:00:00 Fortaleza Ceara 1 1 </code></pre> <p>It takes me 9 minutes to run this code with warnings:</p> <pre><code>sys:1: DtypeWarning: Columns (3,4,5) have mixed types.Specify dtype option on import or set low_memory=False. G:/My Drive/Odds/Code/5. Creating updated training data.py:33: UserWarning: Boolean Series key will be reindexed to match DataFrame index. df = df[~n] G:/My Drive/Odds/Code/5. Creating updated training data.py:34: UserWarning: Boolean Series key will be reindexed to match DataFrame index. df = df[~o] </code></pre> <p>How can I cleanup this code and run it faster using pandas?</p> <p>Also, I have a GPU so I can exploit <a href="https://github.com/rapidsai/cudf" rel="nofollow noreferrer">cudf</a> however I am using the python 3.7 environment and cudf does not seem to support it and am not familiar with conda yet.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T08:02:53.393", "Id": "532333", "Score": "3", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code** (and in the description, please be a bit more specific about what you mean by \"clean up\"). Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T11:57:26.213", "Id": "532349", "Score": "0", "body": "Put the part about optimizing into the body of the question. What is the game? What does the code do with the data frame?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T07:16:52.817", "Id": "532447", "Score": "0", "body": "Thank you for your feedback. I have updated the body of my question. Is there anything else I should be clarifying?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T07:01:18.347", "Id": "532773", "Score": "0", "body": "(I don't understand one example from the code: `as \"Talleres - \"Defensores Unidos\"` is not well-formed.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T07:05:20.207", "Id": "532774", "Score": "0", "body": "`problem is [I wrote] code as and when [needed]` One problem may be that you did not write and keep a specification of what to achieve." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T08:41:11.693", "Id": "532870", "Score": "0", "body": "@greybeard I have updated the code and corrected spelling mistakes. Thank you" } ]
[ { "body": "<p>Any time that you have a section labelled <code>This part</code>, that's a good indication that you should have a function. Code like this should not exist in a flat file with no structure. Among many other reasons,</p>\n<ul>\n<li>once one of your subroutines finishes, any intermediate variables that go out of scope like <code>m</code>, <code>n</code> etc. will be eligible for garbage collection</li>\n<li>performing profiling will be much more possible - please do this; otherwise you're effectively flying blind</li>\n<li>it will be more legible and self-documenting</li>\n<li>it will be possible for your IDE to perform folding, etc.</li>\n</ul>\n<p>Until you have profiling data it's effectively impossible to say what part of your code is the slowest. Some random guesses:</p>\n<ul>\n<li>where you do <code>astype(str)</code>, that's likely not necessary</li>\n<li>when you run successive predicate selection like</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>df = df[df.home_score != &quot;.&quot;]\ndf = df[df.home_score != &quot;..&quot;]\n</code></pre>\n<p>you should instead do only one <code>[]</code> indexing operation, and combine your predicates logically using <code>&amp;</code></p>\n<ul>\n<li>See if there is a performance difference if you prefer in-place operations, including dropping columns and NA, which are both possible in-place</li>\n<li>Does your <code>colt</code> actually do anything? Is there any evidence that your column types are non-uniform? Could you, instead of doing a blanket type coerce, target specific columns that need conversion?</li>\n<li>Avoid <code>applymap</code>. There is a vectorised <code>strip</code> available. You do this twice - why?</li>\n</ul>\n<p>Non-performance topics:</p>\n<ul>\n<li>Don't name variables <code>m</code>, <code>n</code>, <code>o</code> - these are opaque and non-descriptive</li>\n<li>Rather than writing &quot;this part harmonises ...&quot;, you can just write &quot;harmonise ...&quot; - i.e. use the <a href=\"https://en.wikipedia.org/wiki/Imperative_mood\" rel=\"nofollow noreferrer\">imperative mood</a> which is common in function documentation.</li>\n</ul>\n<p>A first stab, addressing some of the above, looks like</p>\n<pre class=\"lang-py prettyprint-override\"><code>import pandas as pd\nfrom datetime import datetime\n\n\ndef harmonize_game(df: pd.DataFrame) -&gt; pd.DataFrame:\n &quot;&quot;&quot;\n harmonise the game column e.g. &quot;Talleres (R.E) - Defensores Unidos&quot; should\n be split as &quot;Talleres - &quot;Defensores Unidos&quot; and removes any date values in\n the column\n &quot;&quot;&quot;\n df['game'] = df['game'].astype(str).str.replace(r'(\\(\\w+\\))', '', regex=True)\n df['game'] = df['game'].astype(str).str.replace(r'(\\s\\d+\\S\\d+)$', '', regex=True)\n\n # Remove any numerical values in the league column. Many times the league\n # column has years concatenated which is what we don't want e.g &quot;Brazil\n # Copa do Nordeste 2020&quot; should be &quot;Brazil Copa do Nordeste&quot;\n df['league'] = df['league'].astype(str).str.replace(r'(\\s\\d+\\S\\d+)$', '', regex=True)\n\n # Split the game column into tow competing teams i.e. home team and away team by the delimiter &quot;-&quot;\n df[['home_team', 'away_team']] = df['game'].str.split(' - ', expand=True, n=1)\n\n # Split the game column into tow competing teams i.e. home team and away team by the delimiter &quot;:&quot;\n df[['home_score', 'away_score']] = df['score'].str.split(':', expand=True)\n return df\n\n\ndef numerical_scores(df: pd.DataFrame) -&gt; pd.DataFrame:\n &quot;&quot;&quot;\n Remove any non numerical values in the home score and away score columns.\n e.ge scores can have &quot;aet&quot;, &quot;canc&quot;, &quot;.&quot;, etc. We don't want anything that\n cannot be identified as filetype:int in pandas\n &quot;&quot;&quot;\n df['away_score'] = df['away_score'].astype(str).str.replace(r'[a-zA-Z\\s\\D]', '', regex=True)\n df['home_score'] = df['home_score'].astype(str).str.replace(r'[a-zA-Z\\s\\D]', '', regex=True)\n df = df[df.home_score != &quot;.&quot;]\n df = df[df.home_score != &quot;..&quot;]\n df = df[df.home_score != &quot;.&quot;]\n df = df[df.home_odds != &quot;-&quot;]\n df = df[df.draw_odds != &quot;-&quot;]\n df = df[df.away_odds != &quot;-&quot;]\n m = df[['home_odds', 'draw_odds', 'away_odds']].astype(str).agg(lambda x: x.str.count('/'), 1).ne(0).all(1)\n n = df[['home_score']].agg(lambda x: x.str.count('-'), 1).ne(0).all(1)\n o = df[['away_score']].agg(lambda x: x.str.count('-'), 1).ne(0).all(1)\n df = df[~m]\n df = df[~n]\n df = df[~o]\n df = df[df.home_score != '']\n df = df[df.away_score != '']\n df = df.dropna()\n return df\n\n\ndef coerce_columns(df: pd.DataFrame) -&gt; pd.DataFrame:\n &quot;&quot;&quot;Keep only the columns we want&quot;&quot;&quot;\n df = df.loc[\n :, df.columns.intersection([\n 'datetime', 'country', 'league', 'home_team', 'away_team',\n 'home_odds', 'draw_odds', 'away_odds', 'home_score',\n 'away_score',\n ])\n ]\n\n # Make sure that the columns are as per data types that we would want pandas\n # to identify. Pandas does not seem to do a very good job identifying data\n # types correctly.\n colt = {\n 'country': str,\n 'league': str,\n 'home_team': str,\n 'away_team': str,\n 'home_odds': float,\n 'draw_odds': float,\n 'away_odds': float,\n 'home_score': int,\n 'away_score': int\n }\n df = df.astype(colt)\n return df\n\n\ndef strip_strings(df: pd.DataFrame) -&gt; pd.DataFrame:\n &quot;&quot;&quot;remove any leading and trailing whitespaces in the string columns&quot;&quot;&quot;\n return df.applymap(lambda x: x.strip() if isinstance(x, str) else x)\n\n\ndef clean_odds(df: pd.DataFrame) -&gt; pd.DataFrame:\n &quot;&quot;&quot;Cleaning data where odds are greater than 100 and less than -1 and dropping duplicates&quot;&quot;&quot;\n df = df[df['home_odds'] &lt;= 100]\n df = df[df['draw_odds'] &lt;= 100]\n df = df[df['away_odds'] &lt;= 100]\n df = df.drop_duplicates(\n ['datetime', 'home_score', 'away_score', 'country', 'league', 'home_team', 'away_team'],\n keep='last',\n )\n df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x)\n return df\n\n\ndef clean(df: pd.DataFrame) -&gt; pd.DataFrame:\n df = harmonize_game(df)\n df = numerical_scores(df)\n df = coerce_columns(df)\n df = strip_strings(df)\n df = clean_odds(df)\n return df\n\n\ndef test() -&gt; None:\n df = pd.DataFrame(\n (\n (0, 'Sport Recife - Imperatriz', '2:2', 1.36, 4.31, 7.66, 'Brazil', 'Copa do Nordeste 2020', datetime.strptime('2020-02-07 00:00:00', '%Y-%m-%d %H:%M:%S')),\n (1, 'ABC - America RN', '2:1', 2.62, 3.30, 2.48, 'Brazil', 'Copa do Nordeste 2020', datetime.strptime('2020-02-02 22:00:00', '%Y-%m-%d %H:%M:%S')),\n (2, 'Frei Paulistano - Nautico', '0:2', 5.19, 3.58, 1.62, 'Brazil', 'Copa do Nordeste 2020', datetime.strptime('2020-02-02 00:00:00', '%Y-%m-%d %H:%M:%S')),\n (3, 'Botafogo PB - Confianca', '1:1', 2.06, 3.16, 3.50, 'Brazil', 'Copa do Nordeste 2020', datetime.strptime('2020-02-02 22:00:00', '%Y-%m-%d %H:%M:%S')),\n (4, 'Fortaleza - Ceara', '1:1', 2.19, 2.98, 3.38, 'Brazil', 'Copa do Nordeste 2020', datetime.strptime('2020-02-02 22:00:00', '%Y-%m-%d %H:%M:%S')),\n ),\n columns=(\n 'Unnamed: 0', 'game',\n 'score',\n 'home_odds',\n 'draw_odds',\n 'away_odds', 'country', 'league', 'datetime',\n ),\n )\n clean(df)\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T00:39:52.257", "Id": "532521", "Score": "0", "body": "Thank you. The code is much cleaner and I get that building functions is a better way to approach this. However, I am still getting the same time as my earlier code and I still get the Boolean Reindexing warning. While I understand, the time cannot be improved however, can I resolve the reindexing warning I get at `df = df[~n]` and `df = df[~o]` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T04:06:03.540", "Id": "532523", "Score": "0", "body": "It's not strictly guaranteed that the time can't be improved. Again, you need to profile your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T09:49:24.393", "Id": "532877", "Score": "0", "body": "Can I ask for a solution for the same code but using `cudf` on this platform?\nHow can I ask it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T13:21:54.013", "Id": "532885", "Score": "0", "body": "How do I save the resulting dataframe `to_csv`?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T16:16:34.707", "Id": "269826", "ParentId": "269756", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T07:23:55.763", "Id": "269756", "Score": "0", "Tags": [ "python", "pandas" ], "Title": "Cleanup dataset for visualization" }
269756
<p>I was solving a DSA question, running median in a stream. And I decided to design my own stream class with additional features.</p> <pre><code>template&lt;typename T&gt; class ActionInterface{ public : virtual void process(const T element) = 0; }; template&lt;typename T,typename V&gt; class Action : public ActionInterface&lt;T&gt; { protected : V result; Action() : result((V)false) {}; public : virtual void process(const T element) = 0; virtual V getResult() const final{ return result; }; }; template &lt;typename T&gt; class Stream{ private : vector&lt;T&gt; buffer; unordered_map&lt;string, ActionInterface&lt;T&gt;* &gt; actions; void processActions(){ for(const auto&amp; [key, action] : actions){ action-&gt;process(buffer.back()); } } public : Stream(){}; void addAction(string actionName, ActionInterface&lt;T&gt; *action){ actions[actionName] = action; } void addElement(const T element){ buffer.push_back(element); processActions(); }; ActionInterface&lt;T&gt; *getActionObject(string actionName) const{ if(actions.find(actionName) == actions.end()) return nullptr; return actions.at(actionName); }; ~Stream(){ for(const auto&amp; [key, action] : actions){ delete action; } } }; template&lt;typename T,typename V&gt; class RunningMedian : public Action&lt;T,V&gt; { private : priority_queue&lt;T&gt; max_heap; priority_queue&lt;T,vector&lt;T&gt;,greater&lt;T&gt;&gt; min_heap; public : RunningMedian() {}; virtual void process(const T element); }; template&lt;typename T, typename V&gt; void RunningMedian&lt;T,V&gt;::process(const T element){ if(element &lt;= this-&gt;result) max_heap.push(element); else min_heap.push(element); if(abs((int)max_heap.size() - (int)min_heap.size()) &gt; 1){ if(max_heap.size() &gt; min_heap.size()){ min_heap.push(max_heap.top()); max_heap.pop(); } else{ max_heap.push(min_heap.top()); min_heap.pop(); } } if(max_heap.size() == min_heap.size()) this-&gt;result = ((V)max_heap.top() + min_heap.top())/2; else this-&gt;result = (max_heap.size() &gt; min_heap.size())? max_heap.top() : min_heap.top(); } vector&lt;double&gt; Solution::solve(vector&lt;int&gt; &amp;A) { int n = A.size(); Stream&lt;int&gt; *stream = new Stream&lt;int&gt;(); ActionInterface&lt;int&gt; *action = new RunningMedian&lt;int,double&gt;(); vector&lt;double&gt; result(n); stream-&gt;addAction(&quot;runningMedian&quot;, action); for(int i=0;i&lt;n;i++){ stream-&gt;addElement(A[i]); result[i] = ((RunningMedian&lt;int,double&gt; *)action)-&gt;getResult() } delete stream; return result; } </code></pre> <p>Any suggestion would be appreciated. Thanks in advance.</p>
[]
[ { "body": "<p>Where are the tests?</p>\n<hr />\n<p>The code doesn't compile - I needed to add a missing semicolon in <code>Solution::solve()</code> and prefix with some definitions:</p>\n<pre><code>#include &lt;vector&gt;\n#include &lt;string&gt;\n#include &lt;queue&gt;\n#include &lt;unordered_map&gt;\n#include &lt;functional&gt;\n\nusing std::vector;\nusing std::string;\nusing std::unordered_map;\nusing std::priority_queue;\nusing std::greater;\n\nnamespace Solution \n{\n std::vector&lt;double&gt; solve(std::vector&lt;int&gt;&amp;);\n}\n</code></pre>\n<p>(Though really I wouldn't have all those <code>using</code>s - just write the full names instead).</p>\n<p>Even with these fixes, I get a lot of compiler warnings:</p>\n<pre class=\"lang-none prettyprint-override\"><code>269757.cpp: In function ‘std::vector&lt;double&gt; Solution::solve(std::vector&lt;int&gt;&amp;)’:\n269757.cpp:142:19: warning: conversion from ‘std::vector&lt;int&gt;::size_type’ {aka ‘long unsigned int’} to ‘int’ may change value [-Wconversion]\n 142 | int n = A.size();\n | ~~~~~~^~\n269757.cpp: In instantiation of ‘class ActionInterface&lt;int&gt;’:\n269757.cpp:35:7: required from ‘class Action&lt;int, double&gt;’\n269757.cpp:102:7: required from ‘class RunningMedian&lt;int, double&gt;’\n269757.cpp:144:66: required from here\n269757.cpp:28:7: warning: ‘class ActionInterface&lt;int&gt;’ has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]\n 28 | class ActionInterface{\n | ^~~~~~~~~~~~~~~\n269757.cpp: In instantiation of ‘class Action&lt;int, double&gt;’:\n269757.cpp:102:7: required from ‘class RunningMedian&lt;int, double&gt;’\n269757.cpp:144:66: required from here\n269757.cpp:35:7: warning: base class ‘class ActionInterface&lt;int&gt;’ has accessible non-virtual destructor [-Wnon-virtual-dtor]\n 35 | class Action : public ActionInterface&lt;T&gt; {\n | ^~~~~~\n269757.cpp:35:7: warning: ‘class Action&lt;int, double&gt;’ has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]\n269757.cpp: In instantiation of ‘class RunningMedian&lt;int, double&gt;’:\n269757.cpp:144:66: required from here\n269757.cpp:102:7: warning: base class ‘class Action&lt;int, double&gt;’ has accessible non-virtual destructor [-Wnon-virtual-dtor]\n 102 | class RunningMedian : public Action&lt;T,V&gt;\n | ^~~~~~~~~~~~~\n269757.cpp:102:7: warning: ‘class RunningMedian&lt;int, double&gt;’ has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]\n269757.cpp: In instantiation of ‘Stream&lt;T&gt;::Stream() [with T = int]’:\n269757.cpp:143:43: required from here\n269757.cpp:70:9: warning: ‘Stream&lt;int&gt;::buffer’ should be initialized in the member initialization list [-Weffc++]\n 70 | Stream(){};\n | ^~~~~~\n269757.cpp:70:9: warning: ‘Stream&lt;int&gt;::actions’ should be initialized in the member initialization list [-Weffc++]\n269757.cpp: In instantiation of ‘RunningMedian&lt;T, V&gt;::RunningMedian() [with T = int; V = double]’:\n269757.cpp:144:66: required from here\n269757.cpp:109:9: warning: ‘RunningMedian&lt;int, double&gt;::max_heap’ should be initialized in the member initialization list [-Weffc++]\n 109 | RunningMedian() {};\n | ^~~~~~~~~~~~~\n269757.cpp:109:9: warning: ‘RunningMedian&lt;int, double&gt;::min_heap’ should be initialized in the member initialization list [-Weffc++]\n269757.cpp: In instantiation of ‘Stream&lt;T&gt;::~Stream() [with T = int]’:\n269757.cpp:154:12: required from here\n269757.cpp:95:17: warning: deleting object of abstract class type ‘ActionInterface&lt;int&gt;’ which has non-virtual destructor will cause undefined behavior [-Wdelete-non-virtual-dtor]\n 95 | delete action;\n | ^~~~~~~~~~~~~\n</code></pre>\n<p>Don't ignore warnings - your compiler is your first reviewer.</p>\n<p>For example, that last one causes a memory leak:</p>\n<pre class=\"lang-none prettyprint-override\"><code>==2921039== 32 bytes in 1 blocks are definitely lost in loss record 1 of 2\n==2921039== at 0x4839F2F: operator new(unsigned long) (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)\n==2921039== by 0x10E515: __gnu_cxx::new_allocator&lt;int&gt;::allocate(unsigned long, void const*) (new_allocator.h:127)\n==2921039== by 0x10D354: allocate (allocator.h:201)\n==2921039== by 0x10D354: std::allocator_traits&lt;std::allocator&lt;int&gt; &gt;::allocate(std::allocator&lt;int&gt;&amp;, unsigned long) (alloc_traits.h:460)\n==2921039== by 0x10C929: std::_Vector_base&lt;int, std::allocator&lt;int&gt; &gt;::_M_allocate(unsigned long) (stl_vector.h:346)\n==2921039== by 0x10C5AF: void std::vector&lt;int, std::allocator&lt;int&gt; &gt;::_M_realloc_insert&lt;int const&amp;&gt;(__gnu_cxx::__normal_iterator&lt;int*, std::vector&lt;int, std::allocator&lt;int&gt; &gt; &gt;, int const&amp;) (vector.tcc:440)\n==2921039== by 0x10BA83: std::vector&lt;int, std::allocator&lt;int&gt; &gt;::push_back(int const&amp;) (stl_vector.h:1198)\n==2921039== by 0x10F157: std::priority_queue&lt;int, std::vector&lt;int, std::allocator&lt;int&gt; &gt;, std::greater&lt;int&gt; &gt;::push(int const&amp;) (stl_queue.h:642)\n==2921039== by 0x10EF2B: RunningMedian&lt;int, double&gt;::process(int) (269757.cpp:114)\n==2921039== by 0x10BB1E: Stream&lt;int&gt;::processActions() (269757.cpp:59)\n==2921039== by 0x10B0B7: Stream&lt;int&gt;::addElement(int) (269757.cpp:75)\n==2921039== by 0x10A3F0: Solution::solve(std::vector&lt;int, std::allocator&lt;int&gt; &gt;&amp;) (269757.cpp:140)\n==2921039== by 0x10A58F: main (269757.cpp:153)\n==2921039== \n==2921039== 32 bytes in 1 blocks are definitely lost in loss record 2 of 2\n==2921039== at 0x4839F2F: operator new(unsigned long) (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)\n==2921039== by 0x10E515: __gnu_cxx::new_allocator&lt;int&gt;::allocate(unsigned long, void const*) (new_allocator.h:127)\n==2921039== by 0x10D354: allocate (allocator.h:201)\n==2921039== by 0x10D354: std::allocator_traits&lt;std::allocator&lt;int&gt; &gt;::allocate(std::allocator&lt;int&gt;&amp;, unsigned long) (alloc_traits.h:460)\n==2921039== by 0x10C929: std::_Vector_base&lt;int, std::allocator&lt;int&gt; &gt;::_M_allocate(unsigned long) (stl_vector.h:346)\n==2921039== by 0x10C5AF: void std::vector&lt;int, std::allocator&lt;int&gt; &gt;::_M_realloc_insert&lt;int const&amp;&gt;(__gnu_cxx::__normal_iterator&lt;int*, std::vector&lt;int, std::allocator&lt;int&gt; &gt; &gt;, int const&amp;) (vector.tcc:440)\n==2921039== by 0x10BA83: std::vector&lt;int, std::allocator&lt;int&gt; &gt;::push_back(int const&amp;) (stl_vector.h:1198)\n==2921039== by 0x10F105: std::priority_queue&lt;int, std::vector&lt;int, std::allocator&lt;int&gt; &gt;, std::less&lt;int&gt; &gt;::push(int const&amp;) (stl_queue.h:642)\n==2921039== by 0x10EFE3: RunningMedian&lt;int, double&gt;::process(int) (269757.cpp:121)\n==2921039== by 0x10BB1E: Stream&lt;int&gt;::processActions() (269757.cpp:59)\n==2921039== by 0x10B0B7: Stream&lt;int&gt;::addElement(int) (269757.cpp:75)\n==2921039== by 0x10A3F0: Solution::solve(std::vector&lt;int, std::allocator&lt;int&gt; &gt;&amp;) (269757.cpp:140)\n==2921039== by 0x10A58F: main (269757.cpp:153)\n</code></pre>\n<hr />\n<p>We don't need a modifiable copy of the input vector, so accept it by reference to const. Consider accepting arbitrary ranges:</p>\n<pre><code>std::vector&lt;double&gt; solve(std::ranges::forward_range auto);\n</code></pre>\n<hr />\n<p>Transferring ownership using raw pointers is error-prone and therefore dangerous. Use smart pointers instead to indicate the ownership semantics (e.g. pass a unique pointer by value when transferring ownership from one object to another).</p>\n<p>Better still, avoid pointers altogether.</p>\n<hr />\n<p>Consider</p>\n<pre><code> using Action&lt;T,V&gt;::result;\n</code></pre>\n<p>That lets us write <code>result</code> instead of the ugly <code>this-&gt;result</code> all over the place.</p>\n<hr />\n<p>Don't write empty default constructors. Just let the compiler default them naturally.</p>\n<hr />\n<p>When overriding functions, use the <code>override</code> keyword instead of <code>virtual</code>.</p>\n<hr />\n<p>Don't cast <code>std::size_t</code> to <code>int</code> like this:</p>\n<blockquote>\n<pre><code>if(abs((int)max_heap.size() - (int)min_heap.size()) &gt; 1){\n if(max_heap.size() &gt; min_heap.size()){\n</code></pre>\n</blockquote>\n<p>That's probably better split out into simpler tests anyway:</p>\n<pre><code>if (max_heap.size() &gt; min_heap.size() + 1) {\n min_heap.push(max_heap.top());\n max_heap.pop();\n}\nif (min_heap.size() &gt; max_heap.size() + 1) {\n max_heap.push(min_heap.top());\n min_heap.pop();\n}\n</code></pre>\n<hr />\n<p><code>ActionInterface</code> and <code>Action</code> look like overkill. Why not just pass a suitable invocable object? It can hold a reference to a <code>result</code> value which it updates.</p>\n<hr />\n<p>Why does <code>Stream</code> have a <code>buffer</code> member that is only written and never read?</p>\n<hr />\n<p>Why do we name actions, but never use that name for anything?</p>\n<hr />\n<p>The <code>for</code> loop in <code>solve</code> looks like it could be a <code>std::transform()</code>.</p>\n<hr />\n<h1>Simplified code</h1>\n<p>Based on the above observations, I reduced to this version, which gives me no compiler warnings and no memory issues in Valgrind:</p>\n<pre><code>#include &lt;concepts&gt;\n#include &lt;functional&gt;\n#include &lt;queue&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n\nnamespace Solution\n{\n std::vector&lt;double&gt; solve(const std::vector&lt;int&gt;&amp;);\n}\n\n\ntemplate &lt;typename T&gt;\nclass Stream\n{\n std::vector&lt;std::function&lt;void(T)&gt;&gt; actions = {};\n\npublic:\n void addAction(std::invocable&lt;T&gt; auto action)\n {\n actions.emplace_back(std::move(action));\n }\n\n void addElement(const T value)\n {\n for (const auto&amp; action: actions) {\n action(value);\n }\n }\n};\n\ntemplate&lt;typename T&gt;\nclass RunningMedian\n{\n std::priority_queue&lt;T&gt; max_heap = {};\n std::priority_queue&lt;T,std::vector&lt;T&gt;,std::greater&lt;T&gt;&gt; min_heap = {};\n T&amp; median;\n\npublic:\n RunningMedian(T&amp; median)\n : median{median}\n {}\n\n void operator()(const T element)\n {\n if (element &lt; median)\n max_heap.push(element);\n else\n min_heap.push(element);\n\n if (max_heap.size() &gt; min_heap.size() + 1) {\n min_heap.push(max_heap.top());\n max_heap.pop();\n } else if (min_heap.size() &gt; max_heap.size() + 1) {\n max_heap.push(min_heap.top());\n min_heap.pop();\n }\n\n median\n = min_heap.size() &lt; max_heap.size() ? max_heap.top()\n : max_heap.size() &lt; min_heap.size() ? min_heap.top()\n : (max_heap.top() + min_heap.top()) / 2;\n }\n};\n\nstd::vector&lt;double&gt; Solution::solve(const std::vector&lt;int&gt;&amp; input)\n{\n Stream&lt;int&gt; stream{};\n double median = 0.0;\n stream.addAction(RunningMedian&lt;double&gt;{median});\n\n std::vector&lt;double&gt; result;\n result.reserve(input.size());\n for (auto i: input) {\n stream.addElement(i);\n result.push_back(median);\n }\n\n return result;\n}\n\n// Simple test. TODO: more rigorous testing\n#include &lt;iostream&gt;\nint main()\n{\n std::vector a = { 1, 1, 1, 2, 3, 4, 5, 6, 5, 5};\n const char* sep = &quot;&quot;;\n for (auto i: Solution::solve(a)) {\n std::cout &lt;&lt; sep &lt;&lt; i;\n sep = &quot;, &quot;;\n }\n std::cout &lt;&lt; '\\n';\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T10:28:04.237", "Id": "269761", "ParentId": "269757", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T08:32:50.967", "Id": "269757", "Score": "0", "Tags": [ "c++", "algorithm", "object-oriented", "generics", "stream" ], "Title": "Stream that computes running median value" }
269757
<p>I'm learning java this week. Please reviews my code for BMI calculator using java, need some your feedback. Thanks before!</p> <p>This Assignment:</p> <p><a href="https://i.stack.imgur.com/mJ0BS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mJ0BS.png" alt="BMI Calculator and expected output" /></a></p> <p><strong>My code</strong></p> <pre><code>public class bmiCalculator extends ConsoleProgram { public void run() { println(&quot;Person 1's information: &quot;); bmiCalculation(70.0, 194.25); println(&quot;&quot;); println(&quot;Person 2's information: &quot;); bmiCalculation(62.5, 130.5); println(&quot;&quot;); print(&quot;Have a nice day!&quot;); } public void bmiCalculation(double height, double weight) { // bmi algo = BMI = weight / height ** 2 * 703 double newHeight = 1; double bmi = 0; for (int i = 0; i &lt; 2; i ++) { newHeight *= height; } bmi = weight / newHeight * 703; println(bmi); classifications(bmi); } public void classifications(double bmi) { if(bmi &lt;= 18) { println(&quot;class 1&quot;); } else if(bmi &lt;= 24.9) { println(&quot;class 2&quot;); } else if(bmi &lt;= 29.9) { println(&quot;class 3&quot;); } else { println(&quot;class 4&quot;); } } </code></pre> <p>}</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T09:46:06.827", "Id": "532341", "Score": "3", "body": "You've hard coded the people's information, rather than prompting the user for it from the console. Since it's in the problem description it's probably part of what you're being assessed on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T10:36:14.747", "Id": "532344", "Score": "1", "body": "Welcome to Code Review! Your image of text [isn't very helpful](//meta.unix.stackexchange.com/q/4086). It can't be read aloud or copied into an editor, and it doesn't index very well. Please [edit] your post to incorporate the relevant text directly (preferably using copy+paste to avoid transcription errors)." } ]
[ { "body": "<pre><code>public void bmiCalculation(double height, double weight) {\n\n // bmi algo = BMI = weight / height ** 2 * 703\n\n double newHeight = 1;\n double bmi = 0;\n for (int i = 0; i &lt; 2; i ++) {\n newHeight *= height;\n }\n bmi = weight / newHeight * 703;\n println(bmi);\n classifications(bmi);\n}\n</code></pre>\n<p>Seems overly complicated to me. You can one line it (and maybe move it to its own method):</p>\n<pre><code>bmi = (weight * 703) / (height * height);\n</code></pre>\n<p>Your output seems off with the assignments table, it mentions &lt; 18.5:</p>\n<pre><code>public void classifications(double bmi) {\n if(bmi &lt;= 18) {\n println(&quot;class 1&quot;);\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T10:35:16.817", "Id": "269762", "ParentId": "269759", "Score": "4" } }, { "body": "<p>In addition to other comments, I would suggest a change in the way you structure this program. Your functions that perform calculations and then print the output will be difficult to write automated tests for. As a first pass, I would modify your <code>classifications</code> function to return a <code>String</code>, and then perform the <code>println</code> from the calling function. You can then go one step further, and refactor to move all of the <code>println</code> calls into the <code>run</code> method, leaving you with two pure functions that take arguments and return a calculated result, without any side-effect behaviour.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T13:32:44.203", "Id": "269770", "ParentId": "269759", "Score": "0" } } ]
{ "AcceptedAnswerId": "269762", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T09:32:42.693", "Id": "269759", "Score": "2", "Tags": [ "java", "homework", "eclipse" ], "Title": "Java BMI Calculator" }
269759
<p>Okay so I built this search page that searches for posts but my current code seems so bloated and inefficient.</p> <p>My script(search page)</p> <pre><code>if(isset($_GET['title']))$title = $_GET['title'];else{ $title = ''; } if(isset($_GET['ad_brand']))$brand = $_GET['ad_brand'];else{ $brand = ''; } if(isset($_GET['min_range']))$min_range = $_GET['min_range'];else{ $min_range = ''; } if(isset($_GET['max_range']))$max_range = $_GET['max_range'];else{ $max_range = ''; } if(isset($_GET['sub_cat']))$sub_cat = $_GET['sub_cat'];else{ $sub_cat = ''; } if(isset($_GET['for_r_s']))$for_r_s = $_GET['for_r_s']; else{ $for_r_s = ''; } if(isset($_GET['main_cat']))$main_cat = $_GET['main_cat']; else{ $main_cat = ''; } if(isset($_POST['filter_button'])){ if(isset($_POST['ad_brand'])) $brand = $_POST['ad_brand']; else{$brand = '';} if(isset($_POST['main_cat'])) $main_cat = $_POST['main_cat']; else{ $main_cat = ''; } if(isset($_POST['sub_cat'])) $sub_cat = $_POST['sub_cat']; else{ $sub_cat = ''; } if($_POST['min_range'] != '') $min_range = $_POST['min_range']; else{ $min_range = ''; } if(isset($_POST['max_range'])) $max_range = $_POST['max_range']; else{ $max_range = ''; } if(isset($_POST['for_r_s'])) $for_r_s = $_POST['for_r_s']; else{ $for_r_s = ''; } header('location:search?title='. $title .'&amp;main_cat='.$main_cat.'&amp;sub_cat='. $sub_cat .'&amp;ad_brand='. $brand .'&amp;min_range='.$min_range.'&amp;max_range='.$max_range.'&amp;for_r_s='.$for_r_s.''); } if(isset($_GET['sub_cat'])){ if($_GET['sub_cat'] != ''){ if(isset($_GET['min_range'])){ if(isset($_GET['max_range']) &amp;&amp; $_GET['max_range'] != ''){ if(isset($_GET['for_r_s'])){ if($_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` &gt;= ? AND `ad_price` &lt;= ? AND `for_r_s` = ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;sssiii&quot;, $title, $sub_cat ,$brand, $min_range, $max_range, $for_r_s); }else{ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` &gt;= ? AND `ad_price` &lt;= ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;sssii&quot;, $title, $sub_cat ,$brand, $min_range, $max_range); } }else{ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` &gt;= ? AND `ad_price` &lt;= ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;sssii&quot;, $title, $sub_cat ,$brand, $min_range, $max_range); } }else{ if(isset($_GET['for_r_s'])){ if($_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` &gt;= ? AND `for_r_s` = ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;sssii&quot;, $title, $sub_cat ,$brand, $min_range, $for_r_s); }else{ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` &gt;= ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;sssi&quot;, $title, $sub_cat ,$brand, $min_range); } }else{ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` &gt;= ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;sssi&quot;, $title, $sub_cat ,$brand, $min_range); } } }else{ if(isset($_GET['max_range']) &amp;&amp; $_GET['max_range'] != ''){ if(isset($_GET['for_r_s'])){ if($_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` &lt;= ? AND `for_r_s` = ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;sssii&quot;, $title, $sub_cat ,$brand, $max_range,$for_r_s); }else{ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` &lt;= ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;sssi&quot;, $title, $sub_cat ,$brand, $max_range); } }else{ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` &lt;= ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;sssi&quot;, $title, $sub_cat ,$brand, $max_range); } }else{ if(isset($_GET['for_r_s'])){ if($_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%') AND `for_r_s` = ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;sssi&quot;, $title, $sub_cat ,$brand, $for_r_s); }else{ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%')&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;sss&quot;, $title, $sub_cat ,$brand); } }else{ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_sub_cat` = ? AND `ad_brand` LIKE CONCAT('%',?,'%')&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;sss&quot;, $title, $sub_cat ,$brand); } } } }else{ if(isset($_GET['min_range'])){ if(isset($_GET['max_range']) &amp;&amp; $_GET['max_range'] != ''){ if(isset($_GET['for_r_s'])){ if($_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` &gt;= ? AND `ad_price` &lt;= ? AND `for_r_s` = ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;ssiii&quot;, $title, $brand, $min_range, $max_range, $for_r_s); }else{ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` &gt;= ? AND `ad_price` &lt;= ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;ssii&quot;, $title, $brand, $min_range, $max_range); } }else{ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` &gt;= ? AND `ad_price` &lt;= ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;ssii&quot;, $title, $brand, $min_range, $max_range); } }else{ if(isset($_GET['for_r_s'])){ if( $_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` &gt;= ? AND `for_r_s` = ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;sssi&quot;, $title, $brand, $min_range, $for_r_s); }else{ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` &gt;= ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;ssi&quot;, $title, $brand, $min_range); } }else{ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` &gt;= ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;ssi&quot;, $title, $brand, $min_range); } } }else{ if(isset($_GET['max_range']) &amp;&amp; $_GET['max_range'] != ''){ if(isset($_GET['for_r_s'])){ if($_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` &lt;= ? AND `for_r_S` = ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;ssii&quot;, $title, $brand, $max_range, $for_r_s); }else{ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` &lt;= ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;ssi&quot;, $title, $brand, $max_range); } }else{ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `ad_price` &lt;= ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;ssi&quot;, $title, $brand, $max_range); } }else{ if(isset($_GET['for_r_s'])){ if($_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `for_r_s` = ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;ssi&quot;, $title, $brand, $for_r_s); }else{ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%')&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;ss&quot;, $title, $brand); } }else{ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%')&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;ss&quot;, $title, $brand); } } } } }else{ $sub_cat = ''; if(isset($_GET['for_r_s'])){ if($_GET['for_r_s'] == 1 || $_GET['for_r_s'] == 2){ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%') AND `for_r_s` = ?&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;ssi&quot;, $title, $brand, $for_r_s); }else{ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%')&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;ss&quot;, $title, $brand); } }else{ $query = &quot;SELECT * FROM `posts` WHERE `ad_title` LIKE CONCAT('%',?,'%') AND `ad_brand` LIKE CONCAT('%',?,'%')&quot;; $get_posts = $conn_posts-&gt;prepare($query); $get_posts-&gt;bind_param(&quot;ss&quot;, $title, $brand); } } </code></pre> <p>My Html code</p> <pre><code> &lt;form action=&quot;&quot; method=&quot;post&quot;&gt; &lt;select name=&quot;main_cat&quot; id=&quot;main_cat&quot;&gt; &lt;option value=&quot;null&quot; disabled selected&gt;Select Category&lt;/option&gt; &lt;?php $get_category = $conn_posts-&gt;prepare(&quot;SELECT * FROM `cats` WHERE `main_cat` = 0;&quot;); $get_category-&gt;execute(); $get_category_results = $get_category-&gt;get_result(); // get result while($row = $get_category_results-&gt;fetch_assoc()){ echo '&lt;option value=&quot;'.$row['ID'].'&quot;&gt;'.$row['cat_name'].'&lt;/option&gt;'; } ?&gt; &lt;/select&gt; &lt;/br&gt; &lt;select name=&quot;sub_cat&quot; id=&quot;sub-category-dropdown&quot;&gt; &lt;option value=&quot;&quot;&gt;Select SubCategory&lt;/option&gt; &lt;/select&gt; &lt;/br&gt; &lt;input type=&quot;text&quot; name=&quot;ad_brand&quot; Placeholder=&quot;Brand(Cat,Jcb,Doosan)&quot;&gt; &lt;/br&gt; &lt;label for=&quot;for_r_S&quot;&gt;Price&lt;/label&gt; &lt;div class=&quot;range_sliders&quot;&gt; &lt;input type=&quot;text&quot; name=&quot;min_range&quot; Placeholder=&quot;Min&quot;&gt; &lt;span&gt; - &lt;/span&gt; &lt;input type=&quot;text&quot; name=&quot;max_range&quot; Placeholder=&quot;Max&quot;&gt; &lt;/div&gt; &lt;/br&gt; &lt;label for=&quot;for_r_S&quot;&gt;For Rent&lt;/label&gt; &lt;input type=&quot;radio&quot; name=&quot;for_r_s&quot; id=&quot;for_r_s&quot; value=&quot;1&quot;&gt; &lt;label for=&quot;for_r_S&quot;&gt;For Sale&lt;/label&gt; &lt;input type=&quot;radio&quot; name=&quot;for_r_s&quot; id=&quot;for_r_s&quot; value=&quot;2&quot;&gt; &lt;/br&gt; &lt;div id=&quot;content&quot;&gt;&lt;/div&gt; &lt;button type=&quot;submit&quot; name=&quot;filter_button&quot; class=&quot;filter_button&quot;&gt;Search&lt;/button&gt; &lt;/form&gt; </code></pre> <p>My Database table layout</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>ad_title</th> <th>ad_sub_cat</th> <th>ad_price</th> <th>used_new</th> <th>for_r_s</th> <th>ad_brand</th> <th>ad_des</th> <th>ad_location</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>title</td> <td>12</td> <td>100</td> <td>1</td> <td>1</td> <td>loerm</td> <td>ipsum</td> <td>new york</td> </tr> </tbody> </table> </div> <p>for_r_s:: 1 = for rent, 2 = for sale</p> <p>used_new:: 1 = used, 2 = new</p> <p>Also the sub cat is gotten from ajax but i don't want to include that code here so just fill it in with any category like this <code>&lt;option value=&quot;12&quot;&gt;Select car&lt;/option&gt;</code></p> <p>The script is working how I want it to but I just want to clean this code(i don't know of any bugs and it should work just fine) and I need some help doing that my friend told me to ask here so I am still ned please tell me if this post is not good and i will put more info.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T12:04:16.193", "Id": "532352", "Score": "2", "body": "Could you elaborate a bit more on what this code does? The only thing we know, by combining two things you wrote, is: \"It searches for posts using multiple filter inputs.\". We have no idea what the data in your database represents. You also have a whole maze of `if () {...} else {...} elseif () {...}` in your code that makes little sense. What does that do, and why? Understanding code can be so much easier if the idea behind it is known. Remember, we have no data, we cannot run your code, all we have is the information you give." } ]
[ { "body": "<p>There is one thing that is not right in your application: tabs and <strong>indentation</strong>.</p>\n<p>Example:</p>\n<pre><code>if(isset($_POST['filter_button'])){\n if(isset($_POST['ad_brand']))\n $brand = $_POST['ad_brand'];\n else{$brand = '';}\n</code></pre>\n<p>So the code is hard to read and decipher because it is too compact, indentation and <strong>spacing</strong> are not consistent and the control flows are not outlined clearly enough.</p>\n<p>Something like this would be slightly more readable:</p>\n<pre><code>if(isset($_POST['filter_button'])) {\n\n if(isset($_POST['ad_brand'])) {\n $brand = $_POST['ad_brand'];\n else {\n $brand = '';\n }\n</code></pre>\n<p>Right ?</p>\n<p>But since PHP has the <a href=\"https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary\" rel=\"nofollow noreferrer\">ternary operator</a> the code could be written more concisely in a one-liner fashion like:</p>\n<pre><code>$brand = (isset($_POST['ad_brand'])) ? $_POST['ad_brand'] : '';\n</code></pre>\n<hr />\n<p>The other problem is that you have too <strong>many nested ifs</strong>. From line 38, you have 6 levels of nesting. This is too much for a program that is not even of high complexity. It is very hard to figure out if the logic is even correct, because it is difficult to tell where the ifs exactly begin end end. The likelihood of producing bugs becomes high as a result.</p>\n<p>To simplify this my advice is to check the input values <strong>early</strong>, provide default values where desired, (or abort with an error if the form is being tampered by the user). In fact you are already doing it.\nIf you consider for example lines 38-39:</p>\n<pre><code>if(isset($_GET['sub_cat'])){\n if($_GET['sub_cat'] != ''){\n</code></pre>\n<p>the form field <code>sub_cat</code> has already been assigned to variable <code>$sub_cat</code> previously. So from now on, you should be using that variable. It has been validated and has a default value too, so there is no need to make further verification. So you can already remove two levels of nesting.</p>\n<hr />\n<p>The third problem is <strong>repetition</strong>. It is understandable that you want to have different SQL statements depending on some condition, but there is no need to repeat <code>prepare</code>, <code>bind_param</code> etc. Once would be enough, at the end of the if block.</p>\n<p>But you should go further and move all the SQL statements to dedicated <strong>functions</strong>. What you need is a function with a few parameters, some of them optional, with default values for some parameters, and inside that function you can build your SQL statement.</p>\n<p>Eg:</p>\n<pre><code>function get_posts($title, $subcat, $min_price, $max_price) { ... }\n</code></pre>\n<p>The function shall return a resultset depending on the supplied parameters. All you have to do is call the function with appropriate values. Inside that function you can have ifs and build a dynamic statement according to the function arguments received.</p>\n<p>Basically all you have is a series of criteria. If for a example a minimum price is supplied to your function you can <strong>concatenate</strong> this to your SQL statement:</p>\n<pre><code>$query = &quot;SELECT * FROM `posts`&quot;;\n\nif ($min_price) {\n $query .= &quot; AND price &gt;= $min_price&quot;;\n}\n</code></pre>\n<p>and so on, as long as the resulting SQL remains correct. So what you will be doing is selective <strong>concatenation</strong>. As far as I can tell the criteria can be evaluated one by one in a sequential manner.\nAll you will need is some ifs, AND, OR. The idea is to concentrate all the logic into that function. Thus you could ditch all those if blocks.</p>\n<p>Just doing that will reduce the code size significantly and improve readability. The rule of thumb that everything that is repetitive is a candidate for a function.</p>\n<p>To sum up, all you need is:</p>\n<ul>\n<li>verify that all expected parameters are received from a POST request</li>\n<li>validate them</li>\n<li>where appropriate, you can supply default values (you are already doing that)</li>\n<li>populate your variables</li>\n<li>then you can pass those variables to a function that will build your SQL dynamically</li>\n</ul>\n<p>Result: all the nested ifs are gone.</p>\n<hr />\n<p>Something that could make the code more explanatory is to use <a href=\"https://www.php.net/manual/en/language.constants.php\" rel=\"nofollow noreferrer\">constants</a>.\neg:</p>\n<pre><code>define('FOR_SALE', '1');\ndefine('FOR_RENT', '2');\n</code></pre>\n<p>Then you can use variables like FOR_SALE or FOR_RENT in your code to make the SQL statements more descriptive.</p>\n<hr />\n<p>What is disturbing is the total lack of <strong>comments</strong>. It would be good to add some notes in plain English here and there, especially when you are checking for some condition. The idea is to better separate blocks, and that if you are looking for something, you don't have to decipher the whole code.</p>\n<hr />\n<p>The <strong>database structure</strong> is not known but judging by the present of LIKE and CONCAT I suspect that you are not taking advantage of indexes, provided they are present. You may run into performance issues as your database grows bigger.</p>\n<hr />\n<p>The HTML page on the other hand is easy. You may want to use a templating engine like twig perhaps.</p>\n<hr />\n<p>PS: maybe you need a better editor to enforce good formatting.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T18:10:40.483", "Id": "532402", "Score": "0", "body": "thanks bud i actually found a nice way of doing it and i started over as my previous code had way to many if stmts lol i don't know what I was even thinking but thanks for all the info and I will keep all of it in my mind while i code my new page :) you gave me wonderful info and this has to be the best answer by far - hope you have a great day" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T18:12:57.117", "Id": "532404", "Score": "0", "body": "if you are wondering I am thinking of using this type of code https://stackoverflow.com/a/13207064/17239314 i know its from 9yrs ago but I am updating the code so that it won't be vulnerable to sql injection" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T13:56:43.317", "Id": "532467", "Score": "0", "body": "do you think that is a valid solution?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T20:46:05.657", "Id": "532505", "Score": "0", "body": "Something along these lines, sequential concatenation, as long as you take care not introduce SQL injection vulnerabilities. Use bind_param one parameter at a time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T14:37:50.817", "Id": "532622", "Score": "0", "body": "yup will do thx bud" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T17:27:05.373", "Id": "269783", "ParentId": "269764", "Score": "1" } } ]
{ "AcceptedAnswerId": "269783", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T11:10:24.683", "Id": "269764", "Score": "0", "Tags": [ "php", "mysql" ], "Title": "PHP search multiple filter inputs" }
269764
<p>This question seems similar to this one: <a href="https://codereview.stackexchange.com/questions/241272/find-number-of-unique-paths-to-reach-opposite-grid-corner">Find number of unique paths to reach opposite grid corner</a> but is entirely not. For moving from upper-left corner to lower-right corner we are not restricted to move only rightwards and downwards otherwise this will be a simple permutation and combination question instead.</p> <p>I came up with the following very bruteforce method which works perfectly fine for a <code>boardSize</code> of <code>3</code> (meaning a (3x3) board), <code>4</code> and <code>5</code> giving <code>12</code>, <code>184</code> and <code>8512</code> successfull paths respectively for reaching <code>(boardSize, boardSize)</code> from <code>(1, 1)</code>. However the code takes forever for a board size of 6 onwards and I have to make it reach to a standard board size of 8 atleast.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; namespace ChessProblem_StackOverFlow { class Program { static void Main(string[] args) { Square currentRookPosition = new Square(1, 1); Square destinationPosition = new Square(Square.boardSize, Square.boardSize); // (3, 3) as of now List&lt;Path&gt; paths = new List&lt;Path&gt;(); List&lt;Path&gt; successfullPaths = new List&lt;Path&gt;(); // One time initialization of &quot;paths&quot; List based on rook's starting position List&lt;Square&gt; possibleMoves = currentRookPosition.GetPossibleMoves(); foreach (Square nextRookPosition in possibleMoves) { paths.Add(new Path(currentRookPosition, nextRookPosition)); } while (paths.Any()) { foreach (Path path in paths.ToList()) { Square lastSquare = path.visitedSquares[^1]; List&lt;Square&gt; nextPossibleMoves = lastSquare.GetPossibleMoves(); // For each nextPossibleMove check if it is already visited and if so remove it foreach (Square nextPossibleMove in nextPossibleMoves.ToList()) { foreach (Square visitedSquare in path.visitedSquares) { if (nextPossibleMove.Equals(visitedSquare)) { nextPossibleMoves.RemoveAt(nextPossibleMoves.IndexOf(nextPossibleMove)); break; } } } // Add path to successfullPaths if destination reached if (path.visitedSquares[^1].Equals(destinationPosition)) { successfullPaths.Add(path); paths.RemoveAt(paths.IndexOf(path)); break; } // Remove path from paths list if out of possible moves if (!nextPossibleMoves.Any()) { paths.RemoveAt(paths.IndexOf(path)); break; } else { foreach (Square nextPossibleMove in nextPossibleMoves) { // add first move in already running path if (nextPossibleMove.Equals(nextPossibleMoves[0])) path.visitedSquares.Add(new Square(nextPossibleMove.x, nextPossibleMove.y)); // create another path for other moves else paths.Add(new Path(path.visitedSquares, nextPossibleMove)); } } } } // test foreach (Path path in successfullPaths) { foreach (Square visitedSquare in path.visitedSquares) { Console.WriteLine(visitedSquare.x + &quot;, &quot; + visitedSquare.y); } Console.WriteLine(&quot;**********************************************************************&quot;); } Console.WriteLine(&quot;Number of successfull paths: &quot; + successfullPaths.Count); } } } </code></pre> <p>Here is my <code>Square</code> struct with only <code>GetPossibleMoves()</code> method which gives all possible moves irrespective of whether it is already visited or not, I am taking care of that in my <code>Main()</code> method.</p> <pre><code>struct Square { public int x, y; public static int boardSize = 3; public Square(int x, int y) { this.x = x; this.y = y; } public List&lt;Square&gt; GetPossibleMoves() { List&lt;Square&gt; possibleMoves = new List&lt;Square&gt;(); if (x &gt; 1) possibleMoves.Add(new Square(x - 1, y)); if (x &lt; boardSize) possibleMoves.Add(new Square(x + 1, y)); if (y &gt; 1) possibleMoves.Add(new Square(x, y - 1)); if (y &lt; boardSize) possibleMoves.Add(new Square(x, y + 1)); return possibleMoves; } } </code></pre> <p>And here is my <code>Path</code> class for keeping track of <code>visitedSquares</code> in any instance of this class.</p> <pre><code>class Path { Square from, to; public List&lt;Square&gt; visitedSquares = new List&lt;Square&gt;(); public Path(Square from, Square to) { this.from = from; this.to = to; visitedSquares.Add(new Square(from.x, from.y)); visitedSquares.Add(new Square(to.x, to.y)); } // another constructor public Path(List&lt;Square&gt; listToBeExtendedFrom, Square replaceLastSquareWith) { foreach(Square square in listToBeExtendedFrom) { visitedSquares.Add(new Square(square.x, square.y)); } visitedSquares.Remove(visitedSquares[visitedSquares.Count - 1]); visitedSquares.Add(new Square(replaceLastSquareWith.x, replaceLastSquareWith.y)); } } </code></pre> <p>For a <code>boardSize</code> of <code>6</code>, I let this program run for half an hour which used upto 6 GB of memory but didn't gave any output. How can I make this more efficient?</p> <p>As <a href="https://codereview.stackexchange.com/users/129343/g-sliepen">@G. Sliepen</a> and <a href="https://codereview.stackexchange.com/users/79357/pacmaninbw">@pacmaninbw</a> mentioned in this <a href="https://codereview.stackexchange.com/questions/269813/find-all-possible-ways-a-rook-can-move-c-version">follow up</a> question about <strong>Rook or king moves</strong>, the question meant to say as if we were tracing the rook's path, the rook isn't allowed to revisit an already visited square <strong>neither it is allowed to intersect it's own path</strong>. My bad I didn't already mentioned this but I pre assumed this as otherwise the question would have become really clumsy.</p>
[]
[ { "body": "<p>I would recommend that you change <code>struct Square</code> to <code>record Square</code>. This makes all the comparative stuff much easier.</p>\n<p>Then you can change your <code>Program</code> class to the following which uses recursion to find the paths. I have also added a timer to show progress.</p>\n<pre><code>class Program\n{\n static void GetPaths(List&lt;Square&gt; path, Square currentRookPosition, Square destinationPosition, int level)\n {\n path.Add(currentRookPosition);\n if (currentRookPosition == destinationPosition)\n {\n pathsFound++;\n return;\n }\n\n List&lt;Square&gt; possibleMoves = currentRookPosition.GetPossibleMoves();\n foreach (Square nextRookPosition in possibleMoves)\n {\n if (path.Contains(nextRookPosition) == false)\n {\n GetPaths(path.ToList(), nextRookPosition, destinationPosition, level + 1);\n }\n }\n }\n\n static void Main(string[] args)\n {\n sw.Start();\n using (var timer = new System.Timers.Timer(1000))\n {\n timer.Elapsed += ShowProgress;\n timer.Start();\n\n var currentRookPosition = new Square(1, 1);\n var destinationPosition = new Square(Square.boardSize, Square.boardSize); // (3, 3) as of now\n var path = new List&lt;Square&gt;();\n GetPaths(path, currentRookPosition, destinationPosition, 0);\n }\n Console.WriteLine(&quot;Paths found = &quot; + pathsFound);\n }\n\n private static void ShowProgress(object sender, System.Timers.ElapsedEventArgs e)\n {\n Console.WriteLine(String.Format(&quot;paths found = {0}, second = {1}&quot;, pathsFound, sw.ElapsedMilliseconds / 1000));\n }\n\n private static int pathsFound = 0;\n private static System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();\n}\n</code></pre>\n<p>This finds 1 262 816 paths for a 6x6 grid in about 20 seconds.</p>\n<hr>\nHere is a revised implementation that calculates a 6x6 grid in under a second using bitsets and pre-calculated moves:\n<pre><code>using System;\nusing System.Collections.Generic;\n\nnamespace ChessProblem_StackOverFlow\n{\n class Board\n {\n public Board(int cols, int rows)\n {\n this.cols = cols;\n this.rows = rows;\n this.squares = new int[cols * rows][];\n for (int y = 0; y &lt; rows; y++)\n {\n for (int x = 0; x &lt; cols; x++)\n {\n squares[x + y * cols] = calcMoves(x, y);\n }\n }\n }\n\n int[] calcMoves(int x, int y)\n {\n var moves = new List&lt;int&gt;();\n if (x &gt; 0)\n moves.Add(calcIndex(x - 1, y));\n if (x &lt; cols - 1)\n moves.Add(calcIndex(x + 1, y));\n if (y &gt; 0)\n moves.Add(calcIndex(x, y - 1));\n if (y &lt; rows - 1)\n moves.Add(calcIndex(x, y + 1));\n return moves.ToArray();\n }\n\n public int calcIndex(int x, int y)\n {\n return x + y * cols;\n }\n\n public UInt64 calcBit(int index)\n {\n UInt64 one = 1;\n return one &lt;&lt; index;\n }\n\n public int rows;\n public int cols;\n public int[][] squares;\n }\n\n class Program\n {\n static void GetPaths(UInt64 path, int currentRookPosition, int destinationPosition, int level)\n {\n path |= board.calcBit(currentRookPosition);\n if (currentRookPosition == destinationPosition)\n {\n pathsFound++;\n return;\n }\n\n foreach (int nextRookPosition in board.squares[currentRookPosition])\n {\n if ((UInt64)(path &amp; board.calcBit(nextRookPosition)) == (UInt64)0)\n {\n GetPaths(path, nextRookPosition, destinationPosition, level + 1);\n }\n }\n }\n\n static void Main(string[] args)\n {\n sw.Start();\n using (var timer = new System.Timers.Timer(1000))\n {\n timer.Elapsed += ShowProgress;\n timer.Start();\n\n int size = 6;\n board = new Board(size, size);\n var currentRookPosition = board.calcIndex(0, 0);\n var destinationPosition = board.calcIndex(board.cols - 1, board.rows - 1);\n \n UInt64 path = 0;\n GetPaths(path, currentRookPosition, destinationPosition, 0);\n }\n Console.WriteLine(&quot;Paths found = &quot; + pathsFound);\n }\n\n private static void ShowProgress(object sender, System.Timers.ElapsedEventArgs e)\n {\n Console.WriteLine(String.Format(&quot;paths found = {0}, second = {1}&quot;, pathsFound, sw.ElapsedMilliseconds / 1000));\n }\n private static int pathsFound = 0;\n private static System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();\n private static Board board;\n }\n}\n</code></pre>\n<p>It took about 2 minutes to calculate 575 780 564 paths for a 7x7 grid. I will leave the 8x8 up to you...</p>\n<p>PS. For my own amusement, I created a <a href=\"https://bit.ly/3CSwWBF\" rel=\"nofollow noreferrer\">C++ version</a> that is about 2 times faster than the C# one. Still waiting for the results for 8x8 :-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T16:36:25.667", "Id": "532384", "Score": "0", "body": "Wow, that's a HUUUUGE upgrade, but still far from achieving 8*8. Seems like the number will be really really monstrous. Will try implementing your suggestions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T08:53:07.590", "Id": "532450", "Score": "0", "body": "I changed `struct` to `record` and let the recursion version run overnight for 7x7 grid. The last line was `Paths found = 575780564, second = 23135`. 6 hours compared to 2 minutes!!! Orz I am just a beginner and this is getting overwhelmingly good." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T13:01:01.363", "Id": "532460", "Score": "1", "body": "@Prince, cool! I have posted a [follow up](https://codereview.stackexchange.com/questions/269813/find-all-possible-ways-a-rook-can-move-c-version) question that you may want to keep an eye on =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T14:35:23.447", "Id": "532474", "Score": "0", "body": "I have found that these types of programs are generally faster in C++. I answered a C# question about the Knights Tour problem then wrote a [C++ version](https://codereview.stackexchange.com/questions/132876/knights-tour-improved-refactored-recursive-breadth-first-search-for) to test my algorithm. Then I wrote a [C# version](https://codereview.stackexchange.com/questions/133674/recursive-breadth-first-search-knights-tour) that was faster than the original question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T14:42:16.417", "Id": "532477", "Score": "1", "body": "@pacmaninbw, I agree and I think that if there is any way to speed this up fundamentally, the same logic should be applicable to the C# version. I posted the C++ version to attract a different audience and see what they can come up with =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T14:48:54.513", "Id": "532478", "Score": "1", "body": "Yes, and some of the things pointed out in the answer will help this C# question as well. Especially `prune early`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T17:29:36.823", "Id": "532492", "Score": "0", "body": "@pacmaninbw Added clarification about **rook or king move** in the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T15:48:42.197", "Id": "532562", "Score": "0", "body": "@upkajdt `int[] m = calcMoves(x, y);` is not used, and it adds more time and memory for nothing. remove it to improve the performance. ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T16:24:51.880", "Id": "532570", "Score": "0", "body": "@iSR5, well spotted =)" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T14:35:06.417", "Id": "269774", "ParentId": "269767", "Score": "7" } } ]
{ "AcceptedAnswerId": "269774", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T11:55:56.870", "Id": "269767", "Score": "7", "Tags": [ "c#", "performance", "memory-optimization", "chess" ], "Title": "Find all possible ways a rook can move to a diagonally opposite corner without going back to an already visited square" }
269767
<p>Here's my attempt at leetcode's <a href="https://leetcode.com/problems/container-with-most-water/" rel="nofollow noreferrer">container with most water</a>.</p> <h3>Problem:</h3> <blockquote> <p>Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.</p> </blockquote> <h3>Solution</h3> <p>Precompute increasing left bounds dictionary <code>{height:index}</code> and increasing right bounds dictionary <code>{height:index}</code>. Then iterate through both dictionaries simultaneously until they meet in the middle.</p> <p>This solution is really fast (&gt;98%) but I really dislike the way I iterate through the dict keys. I implicitly rely on Python 3 dictionaries preserving insertion order and making an iterable of dict.keys is weird.</p> <p>Here's a previous review of the same problem more focused on performance. <a href="https://codereview.stackexchange.com/questions/256326/how-to-speed-up-the-code-for-leetcode-container-with-most-water-task">How to speed up the code for LeetCode &quot;Container with most water&quot; task?</a></p> <pre class="lang-py prettyprint-override"><code>def maxArea(self, height: List[int]) -&gt; int: if not height or len(height) &lt; 2: return 0 max_h = 0 max_h_left = {height[0]: 0} for i, h1 in enumerate(height): if h1 &gt; max_h: max_h_left[h1] = i max_h = h1 max_h2 = 0 max_h_right = {height[-1]:len(height)-1} for j in range(len(height)-1,-1, -1): # Is enumerate reversed cleaner ? h2 = height[j] if h2 &gt; max_h2: max_h_right[h2] = j max_h2 = h2 if max_h2 == max_h: break left_bounds = (k for k in max_h_left) # These feel wrong! right_bounds = (k for k in max_h_right) left = next(left_bounds) right = next(right_bounds) max_area = 0 while True: try: max_area = max( max_area, min(left, right) * abs(max_h_left[left] - max_h_right[right]) ) if left &gt; right: right = next(right_bounds) else: left = next(left_bounds) except StopIteration: return max_area </code></pre> <p>Two previous JS code reviews for reference:</p> <ul> <li><p><a href="https://codereview.stackexchange.com/questions/220314/container-with-most-water">Container with most water</a></p> </li> <li><p><a href="https://codereview.stackexchange.com/questions/232488/leetcode-container-with-most-water">Leetcode container with most water</a></p> </li> </ul>
[]
[ { "body": "<p>Two minor things:</p>\n<p>Your type hint for <code>height</code> doesn't need to be <code>List</code>; since your algorithm (correctly) does not mutate <code>height</code>, you can generalize this to <code>Sequence</code>.</p>\n<p><code>(k for k in max_h_left)</code> and similar can be simplified to <code>iter(max_h_left)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T16:19:32.200", "Id": "269780", "ParentId": "269773", "Score": "3" } }, { "body": "<h3>Iterating over height-index pairs</h3>\n<blockquote>\n<p>I implicitly rely on Python 3 dictionaries preserving insertion order and making an iterable of dict.keys is weird.</p>\n</blockquote>\n<p>This seems fine to me.\nIt's <a href=\"https://docs.python.org/3.7/library/stdtypes.html#mapping-types-dict\" rel=\"nofollow noreferrer\">well documented</a> that dictionaries preserve insertion order,\nfrom version 3.7.\nI would add a comment in the code as a reminder,\njust to help readers who may not be too familiar with Python.</p>\n<p>On the other hand,\nsince you only access the key-value pairs in insertion order,\nyou don't actually need a dictionary.\nYou just need a list of the key-value pairs, and iterate over that.</p>\n<pre><code>max_h_left = [(height[0], 0)]\nfor i, h1 in enumerate(height):\n if h1 &gt; max_h:\n max_h_left.append((h1, i))\n max_h = h1\n\n# ... similarly for max_h_right\n\nleft_it = iter(max_h_left)\nleft, left_index = next(left_it)\n\n# ... and so on\n</code></pre>\n<h3>Unnecessary <code>abs</code></h3>\n<p>On this line:</p>\n<blockquote>\n<pre><code>max_area, min(left, right) * abs(max_h_left[left] - max_h_right[right])\n</code></pre>\n</blockquote>\n<p>If you flip the left and right indexes, then you can drop the <code>abs</code> call:</p>\n<pre><code>max_area, min(left, right) * (max_h_right[right] - max_h_left[left])\n</code></pre>\n<p>By the algorithm,\nthe left and right indexes will never cross each other,\ntherefore the right index will always be higher than the left index.</p>\n<h3>No need for iterators</h3>\n<p>The purpose of the iterators in the posted code is to skip items (from left or from right) that are not in a strictly increasing sequence.\nYou can achieve this in a more straightforward way,\nwith less code,\nthat's slightly faster,\nand I think also easier to read:</p>\n<pre><code>def maxArea(self, height: List[int]) -&gt; int:\n left = 0\n right = len(height) - 1\n largest = 0\n \n while left &lt; right:\n width = right - left\n \n if height[left] &lt; height[right]:\n lower = base = height[left]\n left += 1\n while left &lt; right and height[left] &lt;= base:\n left += 1\n else:\n lower = base = height[right]\n right -= 1\n while left &lt; right and height[right] &lt;= base:\n right -= 1\n \n area = width * lower\n if largest &lt; area:\n largest = area\n \n return largest\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T18:34:09.650", "Id": "269789", "ParentId": "269773", "Score": "3" } } ]
{ "AcceptedAnswerId": "269789", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T14:26:40.403", "Id": "269773", "Score": "6", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "Container with most water, with pre-computation of possible bounds" }
269773
<p>I wrote a function saving class which basically saves data of every function that's being called</p> <pre class="lang-py prettyprint-override"><code>import inspect import typing class SaveData: def __init__(self): self.data = [] def save_data(self, func, remove_self=False): f_inspect = inspect.getfullargspec(func) assert f_inspect.varkw is None and f_inspect.varkw is None f_args = f_inspect.args.copy() if remove_self: f_args = f_args[1:] def wrap(*args, **kwargs): headers = f_args + [func.__name__ + &quot;(return)&quot;] values = list(args) if f_inspect.defaults is not None: defaults = dict(zip(f_args[::-1], f_inspect.defaults[::-1])) else: defaults = dict() for arg in f_args[len(args):]: if arg in kwargs: values.append(kwargs[arg]) else: values.append(defaults[arg]) y = func(*args, **kwargs) values += [y] self.data.append([headers, values]) return y return wrap def save(self): with open('data.pkl', 'wb') as f: pickle.dump(data,f) class Saver: _save_data_obj = SaveData() def __getattribute__(self, item): x = object.__getattribute__(self, item) if isinstance(x, typing.Callable): x = Saver._save_data_obj.save_data(x, remove_self=True) return x </code></pre> <p>Any suggestions to improve? And I wanted it to save each class that is being Inherited in a different file so I want my code to be like this:</p> <pre><code>def save(self): with open(f'{outside_class}.pkl', 'wb') as f: pickle.dump(self.data,f) </code></pre> <p>Can you help me?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T17:37:43.930", "Id": "532400", "Score": "3", "body": "This looks really generic, and - without seeing an actual use case - I can't come to any conclusion other than \"none of this should exist, and you should just use pickle directly\"." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T16:32:18.167", "Id": "269782", "Score": "0", "Tags": [ "python", "python-3.x", "serialization", "meta-programming" ], "Title": "Class to save the parameters of every function call" }
269782
<p>The following code bellow is a factory which creates two different objects for <code>marshalling</code> <code>cyphered</code> and <code>encoded</code> output or the plain text <code>default</code> output. I'm concerned with a few things:</p> <ul> <li>different switch arms may have different dependencies, e.g.<code>c.createCyphered(pgpPublicKey)</code> vs <code>c.createDefault()</code></li> <li>The <code>pgpPublicKey</code>, <code>cypher</code> and <code>enc</code> params are all available <strong>at runtime</strong> on a per request basis. The public key is retrieved from the db per user, so it cannot be retrieved at application init stage.</li> <li><code>Cypher</code> and <code>Encoder</code> at the moment are only used by <code>c.createCyphered</code>, but in not so distant future there could be new implementations added.</li> <li>at the moment the arms conditions sometimes rely on two params <code>pgpPublicKey</code> and <code>cypher</code> and sometimes on three, including two aforementioned plus <code>enc</code></li> </ul> <pre><code>// CreatorFn creates a concrete marshaller to handle the provided msg. type CreatorFn func(msg dto.Response) (json.Marshaler, error) // Creator is a factory which creates concrete marshalling strategies to handle the given msg. type Creator struct{} // New creates a new instance of Creator. func New() *Creator { return &amp;Creator{} } // Create creates a concrete marshaller.CreatorFn. // // The following rules are applied: // - No PGP Public Key given and the `cypher=openpgp` -&gt; returns vem.ErrPGPPublicKeyIsNotProvided // - PGP Public Key given and `cypher=off` -&gt; replies error vem.ErrNoCypherSpecified // - PGP Public Key given and `cypher=openpgp` -&gt; returns Cyphered vem.CreatorFn. // - No PGP Public Key given and the `cypher=off`-&gt; returns Default vem.CreatorFn. // - If the `cypher=openpg` then the enc must be `hex' // - It wraps any failures with vem.ErrCannotCreateMarshaller. func (c *Creator) Create(cypher enum.Cypher, enc enum.Enc, pgpPublicKey string) (vem.CreatorFn, error) { switch { case pgpPublicKey == &quot;&quot; &amp;&amp; cypher == enum.CypherOpenPGP: return c.errPGPPublicKeyIsNotProvided() case pgpPublicKey != &quot;&quot; &amp;&amp; cypher == enum.CypherOff: return c.errNoCypherSpecified() case pgpPublicKey != &quot;&quot;, cypher == enum.CypherOpenPGP &amp;&amp; enc == enum.EncHex: return c.createCyphered(pgpPublicKey) case pgpPublicKey == &quot;&quot; &amp;&amp; cypher == enum.CypherOff: fallthrough // fallthrough to default marshaller default: return c.createDefault() } } func (c *Creator) createCyphered(pgpPublicKey string) (vem.CreatorFn, error) { encryptor := openpgp.New(openpgp.WithPublicKey(pgpPublicKey)) encoder := hexenc.New(hexenc.WithZeroPrefix(), hexenc.WithUpperCase()) return marshaller.CreateCyphered(encryptor, encoder), nil } func (c *Creator) createDefault() (vem.CreatorFn, error) { return marshaller.CreateDefault(), nil } func (c *Creator) errPGPPublicKeyIsNotProvided() (vem.CreatorFn, error) { return nil, merry.Wrap(vem.ErrCannotCreateMarshaller, merry.WithCause(vem.ErrPGPPublicKeyIsNotProvided)) } func (c *Creator) errNoCypherSpecified() (vem.CreatorFn, error) { return nil, merry.Wrap(vem.ErrCannotCreateMarshaller, merry.WithCause(vem.ErrNoCypherSpecified)) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T07:33:17.163", "Id": "532602", "Score": "1", "body": "Are there `import` statements that are relevant to this code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T10:20:02.680", "Id": "532609", "Score": "0", "body": "No, not really. `merry` is just an error handling library. `enum` package has conventional `iota-based` enums for `Cypher` and `Encoder` types." } ]
[ { "body": "<p>After giving it another though I've refactored the code in the following fashion:</p>\n<ul>\n<li>extracted the switch branch conditions into separate functions</li>\n<li>got rid of switch by using an array of rules.</li>\n</ul>\n<p>The result is pretty similar to the following:</p>\n<pre><code>// Creator is a factory which creates concrete marshalling strategies to handle the given msg.\ntype Creator struct{}\n\n// New creates a new instance of Creator.\nfunc New() *Creator {\n return &amp;Creator{}\n}\n\ntype (\n cond func() bool\n strategy func() (vem.CreatorFn, error)\n rule struct {\n cond cond\n strategy strategy\n }\n)\n\n// Create creates a concrete marshaller.CreatorFn.\n//\n// The following rules are applied:\n// - No PGP Public Key given and the `cypher=openpgp` -&gt; returns vem.ErrPGPPublicKeyIsNotProvided\n// - PGP Public Key given and `cypher=off` -&gt; replies error vem.ErrNoCypherSpecified\n// - PGP Public Key given and `cypher=openpgp` -&gt; returns OpenPGP Cyphered and Hex Encoded vem.CreatorFn.\n// - No PGP Public Key given and the `cypher=off`-&gt; returns Default vem.CreatorFn.\n// - Unknown rules combination detected -&gt; returns vem.ErrCannotCreateMarshaller.\nfunc (c *Creator) Create(cypher enum.Cypher, enc enum.Enc, pgpPublicKey string) (vem.CreatorFn, error) {\n rules := c.registerRules(cypher, enc, pgpPublicKey)\n for _, r := range rules {\n if r.cond() {\n return r.strategy()\n }\n }\n\n return nil, merry.Wrap(vem.ErrCannotCreateMarshaller, merry.AppendMessage(&quot;marshaller not found&quot;))\n}\n\nfunc (c *Creator) registerRules(cypher enum.Cypher, enc enum.Enc, pgpPublicKey string) [4]rule {\n resolvers := [...]rule{\n {\n cond: noPGPPublicKeyGivenWithEnabledOpenPGPCypher(cypher, pgpPublicKey),\n strategy: errPGPPublicKeyIsNotProvided,\n },\n {\n cond: pgpPublicKeyGivenWithDisabledOpenPGPCypher(cypher, pgpPublicKey),\n strategy: errNoCypherSpecified,\n },\n {\n cond: pgpPublicKeyGivenWithEnabledOpenPGPCypher(cypher, enc, pgpPublicKey),\n strategy: createCyphered(pgpPublicKey),\n },\n {\n cond: noPGPPublicKeyGivenWithDisabledOpenPGPCypher(cypher, pgpPublicKey),\n strategy: createDefault,\n },\n }\n\n return resolvers\n}\n</code></pre>\n<p>I'd move it one step forward to use the <code>Command</code> &amp; <code>Command Handler</code> pattern, but for now I'll live it as it is.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T15:56:15.610", "Id": "532638", "Score": "0", "body": "Until someone else answers the question, you can actually edit the code in your question and replace it with the refactored code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T10:17:15.980", "Id": "269870", "ParentId": "269784", "Score": "0" } } ]
{ "AcceptedAnswerId": "269870", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T17:33:10.227", "Id": "269784", "Score": "1", "Tags": [ "go" ], "Title": "Factory to create default or cyphered and encoded output marshalers" }
269784
<p>Yesterday when I was showering I was thinking of branchless programming and a thought occurred to me, whether it's possible to write a branchless solution of the Fizbuzz problem. The constraints I put on myself were no if statements, no switches, no ternary operators and no loops. The code below seems to solve this problem as well as test the first 100 numbers:</p> <pre><code>#include &lt;unistd.h&gt; #include &lt;string.h&gt; #include &lt;setjmp.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; jmp_buf buf; int jump(jmp_buf buf) { longjmp(buf, 1); } int wrapexit() { exit(0); } void fizbuzz(int num) { char str[5]; sprintf(str, &quot;%d\n&quot;, num); (num % 3 &amp;&amp; num % 5) &amp;&amp; write(0, str, 5); write(0, &quot;fizbuzz\n&quot;, strlen(&quot;fizbuzz\n&quot;) * !(num % 15)) &amp;&amp; jump(buf); write(0, &quot;buzz\n&quot;, strlen(&quot;buzz\n&quot;) * !(num % 5)) &amp;&amp; jump(buf); write(0, &quot;fiz\n&quot;, strlen(&quot;fiz\n&quot;) * !(num % 3)); } int test(int num) { int throaway = (num == 101 &amp;&amp; wrapexit()); fizbuzz(num); int status = setjmp(buf); status &amp;&amp; test(num + 2); !status &amp;&amp; test(num + 1); return 0; } int main(void) { test(1); return 0; } </code></pre> <p>Also, I know I'm not doing any buffer length checks when I'm stringizing <code>num</code> at the beginning of <code>fizbuzz</code>. Anyway, code reviews most welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T18:42:57.793", "Id": "532656", "Score": "0", "body": "\"Branchless Fizbuzz\"?? `(num % 3 && num % 5) && write(0, str, 5);` looks like branching code to me with its `&&`." } ]
[ { "body": "<p>You don't use it, but your restrictions don't seem to exclude it, so if you make use of the <code>||</code> operator things can be simplified.</p>\n<pre><code>void fizbuzz(int num)\n{\n !(num % 15) &amp;&amp; printf(&quot;fizbuzz\\n&quot;) ||\n !(num % 5) &amp;&amp; printf(&quot;buzz\\n&quot;) ||\n !(num % 3) &amp;&amp; printf(&quot;fiz\\n&quot;) ||\n printf(&quot;%d\\n&quot;, num);\n}\n</code></pre>\n<p>Then you don't need to use <code>setjmp</code> and can get rid of the <code>jump</code> function.</p>\n<p><code>test</code> then becomes a smaller 4 line function:</p>\n<pre><code>int test(int num)\n{\n num == 101 &amp;&amp; wrapexit();\n fizbuzz(num);\n test(num + 1);\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T19:02:57.590", "Id": "532406", "Score": "0", "body": "Damn, this is so much better, didn't even think of logical or. And also you're using printf which is unbuffered so that's another plus." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T17:50:11.057", "Id": "532493", "Score": "0", "body": "*buffered, `printf` is buffered, `write` is unbuffered." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T19:00:38.490", "Id": "269791", "ParentId": "269785", "Score": "2" } }, { "body": "<p>Any time you do an <code>&amp;&amp; function(...)</code>, you have a conditional branch. One might even, with good reason, count function calls as branches as well. And <code>setjmp()</code> is usually implemented by changing the stack pointer and then calling a <code>ret</code> instruction or something similar, which in effect is also a branch.</p>\n<p>The closest you can come to having a &quot;branchless&quot; fizbuzz in C is by unrolling the loop and writing 15 lines at a time:</p>\n<pre><code>void fizbuzz(int num) {\n printf(&quot;%d\\n&quot;, num++);\n printf(&quot;%d\\n&quot;, num++);\n printf(&quot;fiz\\n&quot;); num++;\n printf(&quot;%d\\n&quot;, num++);\n printf(&quot;buzz\\n&quot;); num++;\n printf(&quot;fiz\\n&quot;); num++;\n printf(&quot;%d\\n&quot;, num++);\n printf(&quot;%d\\n&quot;, num++);\n printf(&quot;fiz\\n&quot;); num++;\n printf(&quot;buzz\\n&quot;); num++;\n printf(&quot;%d\\n&quot;, num++);\n printf(&quot;fiz\\n&quot;); num++;\n printf(&quot;%d\\n&quot;, num++);\n printf(&quot;%d\\n&quot;, num++);\n printf(&quot;fizbuzz\\n&quot;); num++;\n fizbuzz(num); // tail recursion\n}\n</code></pre>\n<p>It still calls functions, and at the end it will jump back to the beginning. But at least they are all <em>unconditional</em> branches.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T18:39:57.320", "Id": "532655", "Score": "1", "body": "Perhaps drop the 15x `num++`, use one long `printf()` and then `fizbuzz(num+15);`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T13:37:32.990", "Id": "532810", "Score": "0", "body": "You can also have 100 `printf` statements - no recursive loop needed. Or just hard code the results ;-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T22:27:38.387", "Id": "269795", "ParentId": "269785", "Score": "2" } } ]
{ "AcceptedAnswerId": "269795", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T17:39:57.183", "Id": "269785", "Score": "3", "Tags": [ "c", "fizzbuzz" ], "Title": "Branchless Fizbuzz in Posix C (no if-s, ternaries, switches or loops)" }
269785
<p>I was wondering what might be the best way to inject Flask routes dependencies without a DI framework.</p> <p>I came up with something like this (<code>CalculationService</code> being the dependency I want to inject):</p> <pre><code>from typing import Protocol from flask import Flask app = Flask(__name__) class CalculationService(Protocol): def calculate(self) -&gt; str: '''Returns the result of a calculation''' class CalculationServiceA: def calculate(self) -&gt; str: return 'calculation for service A' class CalculationServiceB: def calculate(self) -&gt; str: return 'calculation for service B' def calculate(calculation_service: CalculationService) -&gt; str: return calculation_service.calculate() def calculation_handler_serviceA() -&gt; str: return calculate(CalculationServiceA()) def calculation_handler_serviceB() -&gt; str: return calculate(CalculationServiceB()) class Context: def __init__(self, calculation_service: CalculationService): self.calculation_service = calculation_service def calculate(self, *args, **kwargs): return self.calculation_service.calculate(*args, **kwargs) handlers_mapping = { 'A': calculation_handler_serviceA, 'B': calculation_handler_serviceB, } chosen_service = 'A' context = Context(CalculationServiceA()) context.calculate = handlers_mapping[chosen_service] @app.route('/calculate') def calculate_route(): return context.calculate() </code></pre> <p>For brevity, it is all in one module, in real app I would split the code into different files.</p> <p>What do you think about such solution? Would it scale well in terms of readability and maintainance?</p> <p>One benefit that I see immediately is testing: I can test <code>calculate</code> directly with some fake <code>CalculationService</code> object and can also skip testing the corresponding route (sending requests with Flask client etc.) - would this be a good idea?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T21:02:29.040", "Id": "269792", "Score": "1", "Tags": [ "python", "dependency-injection", "flask", "bootstrap" ], "Title": "Injecting dependencies in Flask routes without a DI framework" }
269792
<p>I've made a little app, YouTube Downloader, which does what the name says.<br /> I have three files as I am trying to get good enough in working with multiple files in one app. So even if it is really small I will try to separate it.</p> <p>I have some questions:</p> <ul> <li>Is my style acceptable?</li> <li>Is the code clean enough(I know there is not much code in there ;))?</li> <li>Is readability ok?</li> </ul> <p>In short; if you gave me a task to create this and I give you this, would you be happy?</p> <p><a href="https://i.stack.imgur.com/u38v7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/u38v7.png" alt="enter image description here" /></a></p> <p><strong>MAIN.PY</strong></p> <pre><code>import sys, os sys.path.append(f'{os.path.dirname(__file__)}\\scripts') from scripts.app import App from scripts.downloader import Downloader def main() -&gt; None: _eng = Downloader() App(engine=_eng).mainloop() if __name__ == '__main__': main() </code></pre> <p><strong>APP.PY</strong></p> <pre><code>import tkinter as tk from tkinter import BooleanVar, PhotoImage, StringVar, ttk from functools import partial from typing import Any class App(tk.Tk): def __init__(self, engine: Any) -&gt; None: super().__init__() self._eng = engine self.title('Youtube Downloader') self.iconphoto(True, PhotoImage(file='icon.png')) self.geometry('700x300+400+300') self.resizable(False, False) self.configure(background='#333333') self.style = ttk.Style() self.style.configure('TCheckbutton', background='#333333', foreground='white') self.style.configure('TButton', font=('Tahoma', 10, 'bold'), background='#333333') self.link_var = StringVar() self.mp3_var = BooleanVar() self.file_name = StringVar() self.file_path = StringVar() # partial used for labels instead of style as it is minimazing code to variable name and text only label = partial(ttk.Label, self, font=('Tahoma', 10, 'bold'), background='#333333', foreground='white') link_label = label(text='Enter URL:') link_label.place(x=10, y=10) link_entry = ttk.Entry(self, textvariable=self.link_var) link_entry.place(x=10, y=40, width=680, height=30) label_mp3 = label(text='Download as MP3:') label_mp3.place(x=10, y=75) mp3_check = ttk.Checkbutton(self, variable=self.mp3_var, text='MP3', onvalue=True, offvalue=False, style='TCheckbutton') mp3_check.place(x=150, y=75) download_button = ttk.Button(self, text='DOWNLOAD', style='TButton', command=lambda: [self._eng.download(self.mp3_var.get(), self.link_var.get()), self.file_name.set(self._eng.download(self.mp3_var.get(), self.link_var.get())[0]), self.file_path.set((self._eng.download(self.mp3_var.get(), self.link_var.get())[1]))]) download_button.place(x=250, y=110, width=200, height=40) file_info_label = label(text='File:') file_info_label.place(x=10, y=200, height=30) file_info_label_var = label(textvariable=self.file_name) file_info_label_var.place(x=40, y=200, height=30) path_info_label = label(text='Downloaded to:') path_info_label.place(x=10, y=240, height=30) path_info_label_var = label(textvariable=self.file_path) path_info_label_var.place(x=120, y=240, height=30) self.file_path.trace_add('write', self.empty_entry_field) def empty_entry_field(self, x: Any, y: Any, z: Any) -&gt; None: self.link_var.set('') </code></pre> <p><strong>DOWNLOADER.PY</strong></p> <pre><code>from pytube import YouTube from pathlib import Path class Downloader: def __init__(self) -&gt; None: super().__init__() def download(self, MP3BoolVal: bool, url: str) -&gt; list[str]: downloads_path = str(Path.home() / 'Downloads') video = YouTube(url) name = video.title # / and \ need to be removed from the name. otherwise tkinter calls OSError as it's taking it as part of path name = name.replace('\\', '').replace('/', '') if MP3BoolVal: new_name = f'{name}.mp3' print(video.streams.get_audio_only()) video.streams.get_audio_only().download(filename=new_name, output_path=downloads_path) else: new_name = f'{name}.mp4' print(video.streams.get_highest_resolution()) video.streams.get_highest_resolution().download(filename=new_name, output_path=downloads_path) return [new_name, downloads_path] </code></pre>
[]
[ { "body": "<p>&quot;MP3 or not&quot; isn't as informative as &quot;MP3 or MP4&quot;, so you should convert your checkbox to a couple of radio buttons.</p>\n<p>This is spooky:</p>\n<pre><code>sys.path.append(f'{os.path.dirname(__file__)}\\\\scripts')\n</code></pre>\n<p>and probably means that your directory structure is misdesigned. If you want to put other scripts in a subdirectory, it should be as simple as making it a normal Python module with an <code>__init__.py</code> and importing it with a fully-qualified name.</p>\n<p>Don't hint your <code>engine</code> as an <code>Any</code>: it's a <code>Downloader</code>.</p>\n<p><code>x: Any, y: Any, z: Any</code> is not the right signature for a trace; it should be <code>name: str, index: str, mode: str</code>. If you truly don't care about the signature at all, you could just leave it as <code>*args</code>.</p>\n<p><code>list[str]</code> should actually be <code>Tuple[str, str]</code>, and your return should just be made the standard</p>\n<pre><code>return new_name, downloads_path\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T20:13:58.517", "Id": "532501", "Score": "1", "body": "Thank you very much for your review. Yes, my directory structure was a bit of a mess after the last update to Windows 11 and Python 3.10. It is sorted now and ```sys.path.append``` is removed as imports are working as they should now. ```x , y, z``` came from where I found about trace. Added ```Any``` as to type-hint it( didn't know what exactly so did Any). My bad I actually never investigated it bit more, just because it was working fine. Well reeducating myself about it right now." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T02:50:16.130", "Id": "269800", "ParentId": "269794", "Score": "4" } }, { "body": "<h3>Do not repeat potentially expensive operations</h3>\n<p>This snippet is used as a command to execute when clicking on Download:</p>\n<blockquote>\n<pre><code>... command=lambda: [self._eng.download(self.mp3_var.get(), self.link_var.get()),\n self.file_name.set(self._eng.download(self.mp3_var.get(), self.link_var.get())[0]),\n self.file_path.set((self._eng.download(self.mp3_var.get(), self.link_var.get())[1]))])\n</code></pre>\n</blockquote>\n<p>There are 3 calls to <code>self._eng.download</code>,\ntherefore the downloading will be triggered 3 times in a row.\nLuckily it seems that the YouTube library is smart enough to not re-download the same file.</p>\n<p>I also don't understand why the lambda returns a list.\nIt will never be used in this context.</p>\n<p>It would be better to define a function to handle the download action, for example:</p>\n<pre><code>def _download(self):\n url = self.link_var.get()\n as_mp3 = self.mp3_var.get()\n\n filename, path = self._eng.download(as_mp3, url)\n\n self.file_name.set(filename)\n self.file_path.set(path)\n</code></pre>\n<p>and then when creating the button use <code>command=self._download</code>.</p>\n<p>Note that it's intentional in Python that the <code>lambda</code> function can have only a single expression.\nThe idea is that for anything even a little bit complex,\nit's recommended to create a dedicated function,\nand make it easy to read,\nrather than cramming complex logic into a one-liner.</p>\n<h3>Optimize for reading top to bottom</h3>\n<p>The snippet with the complex lambda in the previous section was actually very hard to spot, because the most important piece of code was in the far right,\nand I had to scroll horizontally to see it.</p>\n<blockquote>\n<pre><code> download_button = ttk.Button(self, text='DOWNLOAD', style='TButton', command=lambda: [self._eng.download(self.mp3_var.get(), self.link_var.get()),\n self.file_name.set(self._eng.download(self.mp3_var.get(), self.link_var.get())[0]),\n self.file_path.set((self._eng.download(self.mp3_var.get(), self.link_var.get())[1]))])\n</code></pre>\n</blockquote>\n<p>At first, scrolling the code from top to bottom,\nI saw that most lines are just setting up UI stuff,\nnot very interesting to review,\nand I almost didn't notice that there is something very important to see at the far right, in the complex lambda.</p>\n<p>Make sure the most important parts of the code are easily visible,\nwithout horizontal scrolling.\nAlso note that the Python style guide (<a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>) recommends maximum line length of 79 characters.</p>\n<h3>Validate inputs</h3>\n<p>The code doesn't validate the entered URL,\nsimply passes it to <code>YouTube</code> constructor.</p>\n<p>When the user enters an invalid URL (for example &quot;foo&quot;, or blank),\nthere is no visible response on the UI,\nand on the console there is a cryptic failure message coming from the YouTube library.\nThis is not good UX.</p>\n<p>It would be better to do at least some basic sanity checks on the input,\nand signal to the user when something looks wrong,\nrather than passing unverified values to a 3rd party API.</p>\n<h3>Naming</h3>\n<p>The <code>Downloader.download</code> takes as parameter <code>MP3BoolVal</code>...\nI think a more natural name would be <code>audio_only</code>.\nThis is also consistent with the YouTube API method's naming (<code>get_audio_only</code>),\nfocusing on a general purpose without mentioning a specific format.\nI suggest to do similarly in the <code>App</code> class too,\nand also rephrase the labels in the UI.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T21:54:23.947", "Id": "532511", "Score": "0", "body": "Right now I am working on validating URL as you suggested. Comes out pytube actually does validate them. I've tried validators first and it did work for non URL, but when e.g ```google.com``` would be an input PyTube would rise an error. ```raise RegexMatchError(caller=\"regex_search\", pattern=pattern)pytube.exceptions.RegexMatchError: regex_search: could not find match for (?:v=|\\/)([0-9A-Za-z_-]{11}).*``` . Can't just do try: except as it does not catch this as an error... Think this is why I like it, will spend the next (probably) hours to find a solution and it will be something silly easy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T21:55:49.383", "Id": "532512", "Score": "0", "body": "@Jakub If you mean writing `.some_function(audio_only=audio_only)`, that's totally ok! And writing reviews is not sacrificing time, reviewer learn too in the process, it's really a win-win ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T22:00:04.697", "Id": "532514", "Score": "0", "body": "I always thought that wouldn't be okay as it is duplicated name ;D Well as I said, learning something every day ;) Anyway Thank You for your time, means a lot ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T22:01:15.133", "Id": "532515", "Score": "0", "body": "`try-except` should catch that. Are you wrapping the correct code block? This kind of error would be thrown by `YouTube(url)` (which is earlier than the actual downloading)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T22:03:28.043", "Id": "532516", "Score": "1", "body": "When an exception is thrown, the traceback is there to help you. Look for the last line that is about your code. That's the line in your code that will lead to the exception." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T22:05:35.030", "Id": "532517", "Score": "0", "body": "Yes, It is ```YouTube(url)``` error. I've actually sorted it now.. surprise. Stupid enough I've tried ```except RegexMatchError:``` don't even know why. Should of do just ```except:``` straight away. Now every time URL is not correct there is an information in ```file_info_label_var``` : ```URL IS NOT CORRECT```. I seriously need to create better names for variables." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T15:35:25.123", "Id": "269825", "ParentId": "269794", "Score": "4" } }, { "body": "<h2>UI formatting</h2>\n<p>In APP.PY there is repeated stuff: background color, font style, form size and position etc.\nYou could instead define <strong>constants</strong> for those. That makes it easier to change the running theme, something that the user could even fine-tune themselves, and even better, you could store settings to a <strong>configuration file</strong> with pickle or yaml for example.</p>\n<p>It should be possible to override the <strong>download path</strong> too. It's not something that should be hardcoded in a class. The class should be flexible and portable.\nSo the download path should be an argument to your <code>__init__</code> but it is acceptable to provide a default fallback value.</p>\n<h2>String replace (file rename)</h2>\n<p>In the download class you have this:</p>\n<pre><code>name = name.replace('\\\\', '').replace('/', '')\n</code></pre>\n<p>If you had a more complex requirement you could use a <strong>regular expression</strong> to replace a range of characters, for example:</p>\n<pre><code>import re\nname = re.sub('[\\\\\\\\|/]+', '', name)\n</code></pre>\n<p><strong>Double escaping</strong> rules apply in this case because of the significance of the backslash - <a href=\"https://stackoverflow.com/a/10585406\">Discussion</a>.</p>\n<p>But this is not enough to have safe names: depending on the OS there are more characters that should be avoided, or that are bound to cause problems. Consider the <a href=\"https://www.mtu.edu/umc/services/websites/writing/characters-avoid/\" rel=\"nofollow noreferrer\">following list</a>. Excessive length can also cause problems, depending on the OS and the underlying file system.</p>\n<p>Remember that any third-party input (in this case: the video title) is untrusted by definition. It has to be checked and validated in a way that is not going to disrupt your application, or worse induce security vulnerabilities. If you read up the literature about <strong>file uploads</strong>, the different attack techniques are explained, and some of them may apply to your situation.</p>\n<p>So if you wanted to keep it &quot;simple&quot; you could adapt the regex to replace everything that is not alphanumeric + a few allowed characters like the hyphen or underscore. But this is still too simplistic. Some videos may have titles in an alphabet other than Latin.</p>\n<p>And if you <strong>overwrite</strong> files without warning this is not good. Either show a confirmation message to the user, or add a suffix automatically eg .1 .2 etc.</p>\n<h2>Class</h2>\n<p>In the Downloader class, the sole method <code>download</code> does not even use <code>self</code>, so it could have been declared a <strong>static method</strong> right away (adding the <code>@staticmethod</code> decorator). But then the class does not achieve anything, it is merely a wrapper function around the YouTube API. It does not expose any meaningful methods otherwise.</p>\n<p>The file rename could have been a class method for example. A <em>static</em> method in fact, because that function does not need the class instance either. Even though it is one-liner at present, it should be a bit more complex than that to be effective, as we have seen previously.</p>\n<p>Likewise, handling of audio and video should be processed by distinct tasks. Thus the class would need to be broken down into smaller but specialized methods to become useful.</p>\n<p>Ideally it should be possible to get real-time statistics about the state and speed of the download. For this purpose you have thread polling techniques or callback functions. Once you get a grasp on this, you can implement <strong>parallel download</strong> of multiple files without too much difficulty, like a Torrent client.</p>\n<h2>Transient content</h2>\n<p>For such an application it is customary to use <strong>temporary files</strong>, that are renamed at the end of the process, because the download can obviously fail for many reasons, or be cancelled by the user. As a result your Downloads directory is going to be clogged with useless files over time. Until you implement some kind of resume download feature, the aborted downloads are good for the trash bin.\nHave a look at the <a href=\"https://docs.python.org/3/library/tempfile.html\" rel=\"nofollow noreferrer\">tempfile</a> library. Some methods like NamedTemporaryFile can take care of automatic disposal of the file as soon as it is closed.</p>\n<h2>Validation etc</h2>\n<p>To be a more mature product your application should have some <strong>validation of user input</strong>, basic <strong>exception handling</strong> and a UI that includes a Cancel button, which involves some form of <strong>threading</strong> for the download to do it right. In Python this is not so difficult. I have not tested your application but I am wondering how responsive the UI is while processing a large download.</p>\n<p>If you need to <strong>parse URLs</strong> Python has an interesting module: <a href=\"https://docs.python.org/3/library/urllib.parse.html\" rel=\"nofollow noreferrer\">urllib.parse</a>. Even without doing fancy stuff you can at least extract the scheme (http/https) and the domain name to ascertain that the URL looks minimally correct. Plus, it seems to handle <a href=\"https://en.wikipedia.org/wiki/Internationalized_domain_name\" rel=\"nofollow noreferrer\">IDNs</a> like <a href=\"https://xn--d1acpjx3f.xn--p1ai/\" rel=\"nofollow noreferrer\">https://яндекс.рф/</a>.\nA regex seems to be overkill.</p>\n<h2>Coding style</h2>\n<p>PEP8 one line per import, so:</p>\n<pre><code>import sys, os\n</code></pre>\n<p>becomes:</p>\n<pre><code>import sys\nimport os\n</code></pre>\n<p>What you are doing right: using the pathlib library for convenience and portability.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T20:52:32.500", "Id": "532583", "Score": "0", "body": "Thank you for your review. Validation has been already added after @janos advice. Great idea with using ```re```, going to learn a bit more about it now as it seems much cleaner than my code. Didn't think about temporary files, but that's good idea too, will need to implement that as well as cancel button. As to how responsive UI is while processing large download, on my PC with my broadband speed downloading around 300mb file takes less than me opening downloads folder but I do consider, I can't actually complain about my PC and broadband as they are both really good (at least for me)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T17:50:42.313", "Id": "269855", "ParentId": "269794", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T22:15:37.523", "Id": "269794", "Score": "7", "Tags": [ "python", "tkinter", "youtube" ], "Title": "YouTube Downloader with PyTube" }
269794
<p>I am working on an integration software. I will need to download a list of products and import it into my website. The list of products will be downloaded from <code>Constants.EndPoint</code> which contains a zipped xml document.</p> <p>I will be downloading this file periodically (once every 4 hours)</p> <p>I have written <code>UnzipClient</code> which downloads and extract the file and returns the XML document. The consumer is responsible for deserializing the XML and importing its content (I have not included the consumer code in here)</p> <h2>UnzipClient.cs</h2> <pre><code>public class UnzipClient { private static readonly HttpClient _httpClient; private static readonly Uri _endpointUri; static UnzipClient() { _httpClient = new HttpClient(); _endpointUri = new Uri(Constants.EndPoint); } public async Task&lt;(XmlDocument xmlDocument, string error)&gt; GetXml() { try { var response = await _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, _endpointUri)); error = IsValidResponse(response, &quot;Get&quot;); if (!string.IsNullOrEmpty(error)) { return (null, error); } var xml = await LoadXml(response); return (xml, &quot;&quot;); } catch (Exception ex) { string error = $&quot;Exception sending a Get request. Message: '{ex.Message}', InnerException: '{ex.InnerException}'&quot;; return (null, error); } } private string IsValidResponse(HttpResponseMessage response, string RequestType) { if (response == null) { return $&quot;{RequestType} response is null&quot;; } else if (response.StatusCode != HttpStatusCode.OK) { return $&quot;Invalid response to {RequestType} request. StatusCode: '{response.StatusCode}', Reason: '{response.ReasonPhrase}'.&quot;; } else if (response.Content == null) { return $&quot;{RequestType} request, response.Content is null&quot;; } return string.Empty; } private async Task&lt;XmlDocument&gt; LoadXml(HttpResponseMessage response) { using (var zipStream = await response.Content.ReadAsStreamAsync()) using (ZipArchive archive = new ZipArchive(zipStream)) { if (archive.Entries != null &amp;&amp; archive.Entries.Count &gt;= 1) { using (var unzipStream = archive.Entries[0].Open()) { var xml = new XmlDocument(); xml.Load(unzipStream); return xml; } } } return null; } } </code></pre> <p>The code works, but I am a little confused with the <code>using</code> blocks. <code>Stream</code> and <code>ZipArchive</code> are both <code>Disposable</code> so I would like to dispose them as soon as possible... however the consumer still needs to works with the xml document, so not sure if disposing of the <code>unzipStream</code> would have any impact on xml document?</p>
[]
[ { "body": "<p>Disposing of the unzipStream, archive and zipStream objects when exiting the using blocks, won't affect the <code>xml</code> document object.</p>\n<p>And a few notes:</p>\n<ol>\n<li><p>Constants.EndPoint - I guess it is defined somewhere in the sources. I suggest to retrieve information about the endpoint from a configuration file, so that you don't need to re-compile the sources, if the endpoint changes.</p>\n</li>\n<li><p>It's a good practice to only catch exceptions that you can handle (not Exceptions).</p>\n</li>\n<li><p>As is your UnzipClient is not thread-safe because of the static objects, so if thread-safety is a requirement, you need to revise using them.</p>\n</li>\n<li><p>(cosmetic) <code>...&amp;&amp; archive.Entries.Count &gt;= 1)</code> - use just <code>&gt; 0</code>, it's shorter and more understandble.</p>\n</li>\n<li><p>(cosmetic) from the readability perspective, I would use var for archive as we can see the type of the object and the actual type for zipStream instead of var.</p>\n<p>using (var zipStream = await response.Content.ReadAsStreamAsync())</p>\n<p>using (ZipArchive archive = new ZipArchive(zipStream))</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T10:10:09.663", "Id": "269806", "ParentId": "269796", "Score": "1" } }, { "body": "<p><strong>Current Code Notes</strong> :</p>\n<ol>\n<li><code>UnzipClient</code> is not descriptive enough. Since the actual class is projected to one purpose and provider, then it would be better if you name it after the provider name and the provider api section if any. The goal here is to let anyone know the class purpose without the need to dig inside the class code.</li>\n<li>the <code>static</code> constructor is unneeded. along with the <code>static Uri</code></li>\n<li>The <code>Task&lt;(XmlDocument xmlDocument, string error)&gt;</code> it's fine, however, I would prefer a user-defined class. It will give you more maintainability, readability, and extendibility. Or you can just return <code>Task&lt;XmlDocument&gt;</code> and throw exceptions when needed.</li>\n<li><code>XmlDocument</code> if is it self-choice, I would suggest using <code>XDocument</code> instead (AKA <code>LINQ to XML</code>). More readable, and easier to work with.</li>\n<li><code>RequestType</code> you can use <code>HttpMethod</code> instead.</li>\n<li><code>LoadXml</code> and <code>IsValidResponse</code> should be moved inside the main method, because it does not do anything outside that scope.</li>\n<li>When using <code>HttpClient</code> it is a good idea to make use of <code>BaseAddress</code> instead of passing the full path on each request. This would be useful if for some reason the <code>host</code> is changed, then you only need to update <code>BaseAddress</code></li>\n<li><code>HttpClient</code> has <code>GetAsync</code> why not use it instead of the current <code>SendAsync</code>?.</li>\n</ol>\n<p>Here is an example that demonstrates the above notes :</p>\n<pre><code>public class XmlUnzipClientResult\n{\n public int StatusCode { get; } \n public bool IsSuccess { get; } \n public XmlDocument Result { get; } \n public string Message { get; } \n public Exception ExceptionError { get; }\n \n public XmlUnzipClientResult(int statusCode, bool isSuccess, XmlDocument result, string message, Exception exception)\n {\n StatusCode = statusCode;\n IsSuccess = isSuccess; \n Result = result;\n Message = message;\n ExceptionError = exception;\n }\n \n public static XmlUnzipClientResult Success(XmlDocument result)\n {\n return new XmlUnzipClientResult(200, true, result, null, null);\n }\n \n public static XmlUnzipClientResult Failure(int statusCode, string message, Exception exception = null)\n {\n return new XmlUnzipClientResult(statusCode, false, null, message, exception);\n } \n}\n\npublic class XmlUnzipClient : IDisposable\n{\n private readonly HttpClient _httpClient = new HttpClient();\n private readonly Uri _endpointUri = new Uri(Constants.EndPoint);\n \n public async Task&lt;XmlUnzipClientResult&gt; GetRequestResult()\n {\n \n try\n {\n var response = await _httpClient.GetAsync(_endpointUri);\n \n if(response.StatusCode != HttpStatusCode.OK)\n {\n return XmlUnzipClientResult.Failure((int)response.StatusCode, $&quot;Invalid response to {HttpMethod.Get} request. StatusCode: '{response.StatusCode}', Reason: '{response.ReasonPhrase}'.&quot;); \n }\n \n using (var zipStream = await response.Content.ReadAsStreamAsync())\n using (var archive = new ZipArchive(zipStream))\n {\n var entry = archive.Entries?.FirstOrDefault();\n\n if(entry != null)\n {\n using (var unzipStream = entry.Open())\n {\n var xml = new XmlDocument();\n xml.Load(unzipStream);\n return XmlUnzipClientResult.Success(xml);\n }\n\n }\n }\n \n }\n catch (Exception ex)\n {\n return XmlUnzipClientResult.Failure(500, $&quot;'{ex.Message}'&quot;, ex);\n }\n \n return XmlUnzipClientResult.Failure(500, $&quot;Unexpected Error&quot;);\n }\n \n #region IDisposable\n\n private bool _disposed;\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n private void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n _httpClient.Dispose();\n }\n\n _disposed = true;\n }\n }\n\n #endregion \n}\n</code></pre>\n<p>the usage would be something like :</p>\n<pre><code>using(var client = new XmlUnzipClient())\n{\n var results = await client.GetRequestResult();\n \n if(results.IsSuccess)\n {\n // do something.\n }\n}\n</code></pre>\n<p>If there is multiple calls, you can declare a <code>private static XmlUnzipClient</code> in the class that will do that calls.</p>\n<p>These are just to give some insights on what you've already done. However, from the given context, I don't beleive you need a class for that, it will be better to use extension methods for the <code>ZipArchive</code> which would add more useability to your project for more wider scope.</p>\n<p>So, you need an extension method on <code>HttpResponseMessage</code> to return <code>ZipArchive</code> and another one on <code>ZipArchiveEntry</code> to return <code>XmlDocument</code></p>\n<p>Example :</p>\n<pre><code>public static class ZipArchiveExtensions\n{\n public static async Task&lt;ZipArchive&gt; ReadAsZipArchiveAsync(this HttpResponseMessage response)\n {\n if (response == null) throw new ArgumentNullException(nameof(response));\n\n try\n {\n using (var zipStream = await response.Content.ReadAsStreamAsync())\n using (ZipArchive archive = new ZipArchive(zipStream))\n {\n return archive;\n }\n }\n catch (Exception)\n {\n // handle exceptions\n }\n\n return null;\n }\n\n public static XmlDocument ToXmlDocument(this ZipArchiveEntry entry)\n {\n if(entry == null) throw new ArgumentNullException(entry);\n\n try\n {\n var xml = new XmlDocument();\n \n xml.Load(entry.Open());\n \n return xml;\n }\n catch(Exception)\n {\n // handle exceptions\n } \n\n return null;\n }\n}\n</code></pre>\n<p>with that you can do this :</p>\n<pre><code>XmlDocument xml; \nusing (var archive = await response.ReadAsZipArchiveAsync())\n{\n var entry = archive.Entries?.FirstOrDefault();\n\n if(entry != null)\n {\n xml = entry.ToXmlDocument();\n } \n}\n\nif(xml != null)\n{\n // success do something\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T01:05:41.890", "Id": "269836", "ParentId": "269796", "Score": "2" } } ]
{ "AcceptedAnswerId": "269836", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T23:32:19.367", "Id": "269796", "Score": "1", "Tags": [ "c#", "memory-management", "stream" ], "Title": "Download and unzip an XML document" }
269796
<p>I'm attempting to write an algorithm that will find the largest perfect squares of a given integer, subtracting their values from the total each time, as fast as possible. It's somewhat hard to explain, and I apologize for the somewhat ambiguous title, so I'll give some input/output examples:</p> <hr /> <ul> <li><strong>Input</strong>: 23</li> <li><strong>Output</strong>: [16, 4, 1, 1, 1]</li> <li><strong>Explanation</strong>: 25 (5x5) is too large, but 16 (4x4) fits. Add it to the array and subtract 16 from 23 (7). The next largest perfect square that fits is 4 (2x2), so add it to the array and subtract 4 from 7 (3). From here, the largest perfect square is simply 1 (1x1). So add 1 to the array until we've gotten to 0.</li> </ul> <hr /> <ul> <li><strong>Input</strong>: 13</li> <li><strong>Output</strong>: [9, 4]</li> <li><strong>Explanation</strong>: 9 (3x3) is the largest square, so add it to the array and subtract it from 13 (4). 4 is then also a perfect square, so add it and end there.</li> </ul> <hr /> <p>My solution is as follows (with variable names related to how the question was posed to me):</p> <pre><code>public static int[] solution(int startingSquareYards) { ArrayList&lt;Integer&gt; largestSquares = new ArrayList&lt;Integer&gt;(); // Cast for use with Math.xxx methods double remainingSquareYards = (double) startingSquareYards; while (remainingSquareYards &gt; 0) { double largestSquareRoot = Math.floor(Math.sqrt(remainingSquareYards)); double yardsOfMaterialUsed = largestSquareRoot * largestSquareRoot; remainingSquareYards -= yardsOfMaterialUsed; largestSquares.add((int) yardsOfMaterialUsed); } int[] solutionArray = largestSquares.stream().mapToInt(i -&gt; i).toArray(); return solutionArray; } </code></pre> <p>I'm asking for opinions on my solution and whether I could optimize it in any way for time/space complexity, simplicity (while maintaining easy readability/understanding), etc. It currently works for all of the tests I've written but I may be missing edge cases or places to improve it - I feel as though Math.sqrt() can be a bit slow. The input startingSquareYards can be between 1 and 1,000,000. Any constructive feedback is appreciated :)</p> <p>Thanks for looking!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T03:42:51.617", "Id": "532432", "Score": "0", "body": "I set up commander Lambda's panels only five days ago, did he mess them up again already? Takes at most seven squares, no need to worry about speed I'd say." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T04:39:58.467", "Id": "532442", "Score": "0", "body": "@KellyBundy Ha! LAMBCHOP's quantum antimatter reactor core is just too sensitive it seems. They ought to do a better job setting it up, or not assign such a sensitive task to grunts like me! Anything for that promotion - I've got to try to prove to Bunny HQ that I'm worthy! Who knows how far I'll make it though :)\n\nGood to hear speed isn't a big deal here. Best of luck to you, fellow double agent!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T01:58:08.530", "Id": "532522", "Score": "0", "body": "The [HotSpot JVM has intrinsics](https://gist.github.com/apangin/7a9b7062a4bd0cd41fcc) including for Math.sqrt(). Rather than being a bit slow it should be very fast." } ]
[ { "body": "<h3>A note about <code>Math.sqrt</code></h3>\n<blockquote>\n<p>I feel as though <code>Math.sqrt()</code> can be a bit slow</p>\n</blockquote>\n<p>I thought, since <code>Math.sqrt</code> computes a precise <code>double</code>, maybe if you implement a custom <code>sqrt</code> that computes just up to <code>int</code> precision, it might be an improvement. However, looking at the implementation of <code>Math.sqrt</code> in my IDE I see this comment:</p>\n<blockquote>\n<pre><code> // Note that hardware sqrt instructions\n // frequently can be directly used by JITs\n // and should be much faster than doing\n // Math.sqrt in software.\n</code></pre>\n</blockquote>\n<p>Based on this comment in the implementation,\nI doubt that the optimized less precise custom <code>sqrt</code> implementation could be faster than <code>Math.sqrt</code>.</p>\n<h3>Use interface types when possible</h3>\n<p>For the purposes of <code>largestSquares</code>,\nany <code>List&lt;Integer&gt;</code> is fine,\nthe specific implementation is not important.\nSo instead of this:</p>\n<blockquote>\n<pre><code>ArrayList&lt;Integer&gt; largestSquares = new ArrayList&lt;Integer&gt;();\n</code></pre>\n</blockquote>\n<p>Write like this:</p>\n<pre><code>List&lt;Integer&gt; largestSquares = new ArrayList&lt;&gt;();\n</code></pre>\n<p>Note that either way, the <code>&lt;Integer&gt;</code> on the right-hand side can be replaced with <code>&lt;&gt;</code>, because the type is implied.</p>\n<h3>Work with <code>int</code> instead of <code>double</code> when possible</h3>\n<p>Working with <code>double</code> can be tricky sometimes.\nWhen an <code>int</code> is enough, it's good to use that instead.</p>\n<p>Looking at the implementation, see my comments inline:</p>\n<blockquote>\n<pre><code>// flooring a double\n// -&gt; effectively making it an int\n// -&gt; this can be an int!\n// -&gt; with (int) Math.sqrt(...) instead of flooring\ndouble largestSquareRoot = Math.floor(Math.sqrt(remainingSquareYards));\n\n// the square of an int is an int -&gt; this can be an int\ndouble yardsOfMaterialUsed = largestSquareRoot * largestSquareRoot;\n\n// ... -&gt; actually we never had a good reason to make this not an int...\nremainingSquareYards -= yardsOfMaterialUsed;\n\n// ... -&gt; if everything above an int and we no longer need to cast here\nlargestSquares.add((int) yardsOfMaterialUsed);\n</code></pre>\n</blockquote>\n<p>Applying the above changes, we can largely avoid <code>double</code>,\nand the result is a bit simpler:</p>\n<pre><code>int remainingSquareYards = startingSquareYards;\n\nwhile (remainingSquareYards &gt; 0) {\n int largestSquareRoot = (int) Math.sqrt(remainingSquareYards);\n int yardsOfMaterialUsed = largestSquareRoot * largestSquareRoot;\n remainingSquareYards -= yardsOfMaterialUsed;\n largestSquares.add(yardsOfMaterialUsed);\n}\n</code></pre>\n<h3>Unnecessary explicit cast</h3>\n<p>The explicit cast here is unnecessary, you can simply omit the <code>(double)</code>:</p>\n<blockquote>\n<pre><code>double remainingSquareYards = (double) startingSquareYards;\n</code></pre>\n</blockquote>\n<h3>Unnecessary local variable</h3>\n<p>The <code>solutionArray</code> at the end is not useful,\nI suggest to return its value directly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T06:14:35.293", "Id": "269803", "ParentId": "269799", "Score": "7" } }, { "body": "<p>An approach to elimitate the Math.sqrt call (which is rather expensive) is using dynamic programming to calculate the squares up until you reach or overshoot the value. Afterwards, you'll have them readily available.</p>\n<p>A TreeMap looks like a good data structure as it is navigable:</p>\n<pre><code> // something along the lines of:\n TreeMap&lt;Integer, Integer&gt; squareToRoot = ... \n int root = 1;\n int square;\n do {\n square = root * root;\n squareToRoot.put(square, root);\n root++;\n } while (square &lt;= destinationValue);\n \n</code></pre>\n<p>Then, you just have to play around with a <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/NavigableMap.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/NavigableMap.html</a> using some lookups of floor keys and subtraction.</p>\n<hr />\n<p>Edit: seemingly Math.sqrt with its native implementation is not a problem, though it was a concern of the original poster, which I addressed in this answer.</p>\n<p>Nevertheless: the reaction I got seems to be the new way in a community that I have witnessed going south for quite some years now. Please take this edit as my apology for wasting your time over the last 8 years or so. Codereview will not see me again.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T12:56:52.567", "Id": "532457", "Score": "4", "body": "How expensive is Math.sqrt, and how much faster is your way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T07:31:15.277", "Id": "532530", "Score": "0", "body": "@KellyBundy If you are interested in benchmarking this, please go ahead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T14:51:32.337", "Id": "532557", "Score": "0", "body": "I'd be *very* happy to. I have benchmark code ready already. All I need is your complete implementation." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T07:04:16.013", "Id": "269804", "ParentId": "269799", "Score": "-1" } }, { "body": "<p>I'm no Java guy, but will comment on the &quot;algorithm&quot;. You compute and subtract squares all the way until you reach zero. You can get away with doing just one square and very modest amount of precomputation/memory.</p>\n<p>Note that squares aren't that far apart. In the allowed range 1 to a million, the largest gap is <span class=\"math-container\">\\$1000^2-999^2=1999\\$</span>. Consequently, the largest number remaining after subtracting the maximal square is <span class=\"math-container\">\\$(1000^2-1)-999^2=1998\\$</span>. So you could precompute all answers for up to area 1998 and then always just compute the maximal square and combine it with the stored answer for the remaining area.</p>\n<p>Again I'm no Java guy, but here's a Python demo (<a href=\"https://tio.run/##TY7NDoIwEITvfYo9thWNaGLEhCchHJqwSCP9YVtUnh6L9eAme5iZL7Prlzg4e756WteenAGj4gDaeEcRdJgoMtZhD8GNT@SKUIkbgzRhmpOCOkM5ASnh9E0J40wWmkwVIJUNL6Rmw/bZbFvGsptKmibJ3hFsAGgLpOwdeVlAWVXV72SmD8p7tB3/@0gw5knbyI16p/U5K/5KjlJedqUQBTxwqUe0QqzrBw\" rel=\"noreferrer\" title=\"Python 3.8 (pre-release) – Try It Online\">Try it online!</a>):</p>\n<pre><code>from math import isqrt\n\ndef solve(area):\n square = isqrt(area) ** 2\n return [square, *answer[area-square]]\n\nanswer = [[]]\nfor area in range(1, 1999):\n answer.append(solve(area))\n\nprint(max(map(solve, range(1, 10**6+1)), key=len))\n</code></pre>\n<p>The last line finds a longest answer, output is:</p>\n<pre><code>[7056, 144, 16, 4, 1, 1, 1]\n</code></pre>\n<p>So for any allowed input, you never need more than seven squares. Thus if you just want the answer for <em>one</em> input area, even this modest amount of precomputation is very wasteful. But if you want to solve <em>many</em> inputs, like I did when I solved the whole range of a million inputs, it might be worth it. That whole program above btw took about 0.66 seconds.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T14:31:19.807", "Id": "269819", "ParentId": "269799", "Score": "6" } }, { "body": "<p>Since you are subtracting squares, your loop won't have to execute very many times. Every step shrinks the number of yards.</p>\n<p>I originally thought you might want to optimize it for when there are multiple values like 1 and 4, but I just did a quick test and for 1 to 10 million you never get more than 7 elements, and 3 of those are 1s.</p>\n<p>There will never be more than 3 1s because 4 would take care of that. In fact up to 10 million the only multiples are 1s and 4s. My laptop only took about 4 seconds to calculate all the results up to 10 million in javascript, so I think it's fast enough. If you wanted to do anything you could exit the loop if the remaining is less than 9 and manually check for 4s and then 1s. Just ran a test calculating using each method 5 times for 1-10 million and it didn't help much: 21.5 seconds for the regular method and 19.3 seconds short-circuiting for numbers less than 9.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T04:12:56.353", "Id": "532524", "Score": "0", "body": "Challenge #1: Find out why \"In fact up to 10 million the only multiples are 1s and 4s\" and rewrite it accordingly. Challenge #2: What's the smallest number that needs 8 squares? Challenge #3: What's the smallest number that needs 9 squares?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T04:31:44.247", "Id": "532525", "Score": "0", "body": "Thought about that for a few minutes then gave up :). Thinking about building a square you add one for each row and column and one in the corner to get another square, so that's where you get 3 ones (1+1+1). To get to the next square you add (2+2+1). To get to the next square you add (3+3+1) so you're adding on consecutive odd numbers blocks like 3, 5, 7, 9, 11, 13. So the gaps are increasing linearly and the squares are much bigger than the gaps, but can't put into words (or mat) exactly how that ensures there won't be another duplicate..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T04:34:00.700", "Id": "532526", "Score": "0", "body": "In 3 dimensions you could get 7 1s, 3 8s, 2 27s, then never any more. In 4 dimensions you could get 15 1s, 5 16s, 3 81s, 2 256s, and 2 625s before the gap closes..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T14:49:45.547", "Id": "532555", "Score": "0", "body": "I think your *\"There will never be more than 3 1s because 4 would take care of that\"* puts it well. You can similarly say it for other numbers. Or more \"mathematically\": If you take a square \\$n^2\\$ twice, it contributes \\$2n^2=(\\sqrt{2}n)^2\\$. When that is \\$(n+1)^2\\$ or more, you'd use \\$(n+1)^2\\$ instead. Which is when \\$\\sqrt{2}n \\ge n+1\\$, i.e., when \\$n \\ge \\frac{1}{\\sqrt{2}-1}\\approx 2.41\\$. So you never take the square of \\$n\\$ more than once if n is larger than 2, meaning you'd never take a square larger than 4 more than once." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T14:50:39.917", "Id": "532556", "Score": "0", "body": "What about challenges #2 and #3? #2 you can do with running your code a little longer, #3 needs a little understanding." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T03:50:05.170", "Id": "269839", "ParentId": "269799", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T02:34:06.257", "Id": "269799", "Score": "5", "Tags": [ "java", "performance", "algorithm", "array" ], "Title": "Fastest function to find cumulative largest perfect squares of a single number?" }
269799
<p>I'm new to C and was trying to write a generic dynamic array which is type safe. I'm not sure if I pulled it off in the best way possible though.</p> <p>dynarray.h:</p> <pre class="lang-c prettyprint-override"><code>#ifndef h_DynArray #define h_DynArray #define DYNAMIC_ARR_SIZE 10 // Default size for dynamic arrays #define DYNAMIC_ARR_GROWTHRATE 2 //Growthrate for dynamic arrays #define DYNAMIC_ARR_FREE_ON_ERROR 1 #define DYNAMIC_ARR_KEEP_ON_ERROR 0 struct DynArray_Options { char freeOnError; // If set, will free the contents of the array when an error is caught, otherwise the contents remain } DynArray_Options; struct $DynArray { size_t size; // Number of elements in array size_t capacity; // Capacity of array unsigned char* data; // Pointer to data struct DynArray_Options options; // Array options size_t typeSize; // sizeof(type) }; void $DynArray_Create(struct $DynArray* arr, size_t typeSize); void $DynArray_Free(struct $DynArray* arr); void $DynArray_EmptyPush(struct $DynArray* arr); void $DynArray_Push(struct $DynArray* arr, void* value); void $DynArray_Pop(struct $DynArray* arr); void $DynArray_RemoveAt(struct $DynArray* arr, size_t index); void $DynArray_Shrink(struct $DynArray* arr); void $DynArray_Reserve(struct $DynArray* arr, size_t size); /* * Defines a DynArray of type(tag). */ #define DynArray(tag) DynArray$##tag /* * Utility macros for getting functions for type(tag). */ #define DynArray_ReinterpretCast(tag) DynArray$##tag##_ReinterpretCast #define DynArray_Create(tag) DynArray$##tag##_Create #define DynArray_Free(tag) DynArray$##tag##_Free #define DynArray_EmptyPush(tag) DynArray$##tag##_EmptyPush #define DynArray_Push(tag) DynArray$##tag##_Push #define DynArray_Pop(tag) DynArray$##tag##_Pop #define DynArray_RemoveAt(tag) DynArray$##tag##_RemoveAt #define DynArray_Shrink(tag) DynArray$##tag##_Shrink #define DynArray_Reserve(tag) DynArray$##tag##_Reserve #define DynArray_Decl(type, tag) \ $DynArray_Decl_Type(type, tag) \ static inline void DynArray$##tag##_Create(struct DynArray(tag)* arr) \ { \ $DynArray_Create(&amp;arr-&gt;$arr, sizeof(type)); \ } \ $DynArray_Decl_Func(type, tag) \ $DynArray_Decl_Func_Push(type, tag) #define $DynArray_Decl_Type(type, tag) \ struct DynArray(tag) \ { \ union \ { \ struct $DynArray $arr; \ struct \ { \ size_t size; \ size_t capacity; \ type* values; \ struct DynArray_Options options; \ }; \ }; \ }; #define $DynArray_Decl_Func(type, tag) \ static inline struct DynArray(tag) DynArray$##tag##_ReinterpretCast(void* arr) \ { \ struct DynArray(tag) dst; \ memcpy(&amp;dst, arr, sizeof dst); \ return dst; \ } \ static inline void DynArray$##tag##_Free(struct DynArray(tag)* arr) \ { \ $DynArray_Free(&amp;arr-&gt;$arr); \ } \ static inline void DynArray$##tag##_EmptyPush(struct DynArray(tag)* arr) \ { \ $DynArray_EmptyPush(&amp;arr-&gt;$arr); \ } \ static inline void DynArray$##tag##_Pop(struct DynArray(tag)* arr) \ { \ $DynArray_Pop(&amp;arr-&gt;$arr); \ } \ static inline void DynArray$##tag##_RemoveAt(struct DynArray(tag)* arr, size_t index) \ { \ $DynArray_RemoveAt(&amp;arr-&gt;$arr, index); \ } \ static inline void DynArray$##tag##_Shrink(struct DynArray(tag)* arr) \ { \ $DynArray_Shrink(&amp;arr-&gt;$arr); \ } \ static inline void DynArray$##tag##_Reserve(struct DynArray(tag)* arr, size_t size) \ { \ $DynArray_Reserve(&amp;arr-&gt;$arr, size); \ } #define $DynArray_Decl_Func_Push(type, tag) \ static inline void DynArray$##tag##_Push(struct DynArray(tag)* arr, type value) \ { \ $DynArray_Push(&amp;arr-&gt;$arr, &amp;value); \ } \ /* * The following is used to define the &quot;raw&quot; version of DynArray * which uses a custom Create function to assign sizeof(type). */ $DynArray_Decl_Type(unsigned char, raw) static inline void DynArray$raw_Create(struct DynArray(raw)* arr, size_t typeSize) { $DynArray_Create(&amp;arr-&gt;$arr, typeSize); } $DynArray_Decl_Func(unsigned char, raw) static inline void DynArray$raw_Push(struct DynArray(raw)* arr, void* value) { $DynArray_Push(&amp;arr-&gt;$arr, value); } #endif </code></pre> <p>dynarray.c:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &quot;dynarray.h&quot; void $DynArray_Create(struct $DynArray* arr, size_t typeSize) { arr-&gt;data = malloc(typeSize * DYNAMIC_ARR_SIZE); arr-&gt;size = 0; arr-&gt;capacity = DYNAMIC_ARR_SIZE; arr-&gt;typeSize = typeSize; arr-&gt;options.freeOnError = DYNAMIC_ARR_FREE_ON_ERROR; } void $DynArray_Free(struct $DynArray* arr) { free(arr-&gt;data); arr-&gt;data = NULL; } inline void $DynArray_ErrorFree(struct $DynArray* arr) { if (arr-&gt;options.freeOnError) { free(arr-&gt;data); arr-&gt;data = NULL; } } void $DynArray_EmptyPush(struct $DynArray* arr) { if (arr-&gt;data) { if (arr-&gt;size == arr-&gt;capacity) { size_t newCapacity = (size_t)(arr-&gt;capacity * DYNAMIC_ARR_GROWTHRATE); if (newCapacity == arr-&gt;capacity) ++newCapacity; void* tmp = realloc(arr-&gt;data, arr-&gt;typeSize * newCapacity); if (tmp) { arr-&gt;data = tmp; arr-&gt;capacity = newCapacity; ++arr-&gt;size; } else { $DynArray_ErrorFree(arr); } } else { ++arr-&gt;size; } } } void $DynArray_Push(struct $DynArray* arr, void* value) { $DynArray_EmptyPush(arr); if (arr-&gt;data) memcpy(arr-&gt;data + (arr-&gt;size - 1) * arr-&gt;typeSize, value, arr-&gt;typeSize); } void $DynArray_Pop(struct $DynArray* arr) { if (arr-&gt;data) { if (arr-&gt;size &gt; 0) { --arr-&gt;size; } } } void $DynArray_RemoveAt(struct $DynArray* arr, size_t index) { if (arr-&gt;data) { if (arr-&gt;size &gt; 1 &amp;&amp; index &gt; 0 &amp;&amp; index &lt; arr-&gt;size) { size_t size = arr-&gt;size - 1 - index; if (size != 0) memmove(arr-&gt;data + index * arr-&gt;typeSize, arr-&gt;data + (index + 1) * arr-&gt;typeSize, size * arr-&gt;typeSize); --arr-&gt;size; } } } void $DynArray_Shrink(struct $DynArray* arr) { if (arr-&gt;data) { size_t newCapacity = arr-&gt;size; if (newCapacity != arr-&gt;capacity) { void* tmp = realloc(arr-&gt;data, arr-&gt;typeSize * newCapacity); if (tmp) { arr-&gt;data = tmp; arr-&gt;capacity = newCapacity; ++arr-&gt;size; } else { $DynArray_ErrorFree(arr); } } } } void $DynArray_Reserve(struct $DynArray* arr, size_t size) { if (arr-&gt;data) { size_t newCapacity = arr-&gt;size + size; if (newCapacity &gt; arr-&gt;capacity) { void* tmp = realloc(arr-&gt;data, arr-&gt;typeSize * newCapacity); if (tmp) { arr-&gt;data = tmp; arr-&gt;capacity = newCapacity; arr-&gt;size = size; } else { $DynArray_ErrorFree(arr); } } else { arr-&gt;size = size; } } else { void* tmp = malloc(arr-&gt;typeSize * size); if (tmp) { arr-&gt;data = tmp; arr-&gt;capacity = size; arr-&gt;size = size; } } } </code></pre> <p>usage:</p> <pre class="lang-c prettyprint-override"><code>DynArray_Decl(int, int) // Declaration outside int main() { struct DynArray(int) intArr; DynArray_Create(int)(&amp;intArr); for (size_t i = 0; i &lt; 10; i++) { DynArray_Push(int)(&amp;intArr, i); } printf(&quot;size: %i\n&quot;, intArr.size); printf(&quot;%i\n&quot;, intArr.values[2]); } </code></pre> <p>I'm also not too sure if I utilized union properly in the declaration (<code>$DynArray_Decl_Type</code>) or if that produces undefined behaviour.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T04:45:31.447", "Id": "532443", "Score": "3", "body": "`$` is not part of the C standard's coding characters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T19:52:09.000", "Id": "532659", "Score": "0", "body": "Welcome to Code Review! I have rolled back Rev 4 → 2. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)." } ]
[ { "body": "<p><strong>Big task</strong></p>\n<p>OP's goal of &quot;trying to write a generic dynamic array which is type safe.&quot; is admirable, but not a good task for someone new to C.</p>\n<p>I recommend to start with a <em>write a generic dynamic array</em> for <code>void *</code>.</p>\n<p>Later, research <code>_Generic</code>.</p>\n<p><strong>Not so generic</strong></p>\n<p>Approach relies on types not having spaces.</p>\n<p>Try <code>struct DynArray(long long) llArr;</code></p>\n<p><strong>Stand-alone failure</strong></p>\n<p><code>#include &quot;dynarray.h&quot;</code> fails as <code>dynarray.h</code> requires prior <code>#include &lt;&gt;</code>. Put those in <code>dynarray.h</code>.</p>\n<p>Use <code>#include &quot;dynarray.h&quot;</code> first, before other includes, in <code>dynarray.c</code> to test.</p>\n<p><strong>Why 10</strong></p>\n<p>Rather than some magic number 10, Rework to start with size 0.</p>\n<pre><code>// #define DYNAMIC_ARR_SIZE 10\n</code></pre>\n<p><strong>Allow <code>$DynArray_Free(NULL)</code></strong></p>\n<p>This, like <code>free(NULL)</code>, simplifies clean-up</p>\n<pre><code>void $DynArray_Free(struct $DynArray* arr) {\n if (arr) {\n free(arr-&gt;data);\n arr-&gt;data = NULL;\n }\n}\n</code></pre>\n<p><strong>More reasonable max line length</strong></p>\n<pre><code> // if (size != 0) memmove(arr-&gt;data + index * arr-&gt;typeSize, arr-&gt;data + (index + 1) * arr-&gt;typeSize, size * arr-&gt;typeSize);\n</code></pre>\n<p>vs.</p>\n<pre><code> if (size != 0) {\n memmove(arr-&gt;data + index * arr-&gt;typeSize, \n arr-&gt;data + (index + 1) * arr-&gt;typeSize,\n size * arr-&gt;typeSize);\n } \n</code></pre>\n<p><strong>$ is not part of the standard C coding languages</strong></p>\n<p><code>$</code> not needed anyways. Consider dropping it.</p>\n<p><strong>Unneeded <code>if()</code></strong></p>\n<p>In <code>$DynArray_Reserve()</code>, code starts with unneeded <code>if (arr-&gt;data)</code> test. <code>realloc(NULL, ...)</code> is OK.</p>\n<blockquote>\n<p>If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size.</p>\n</blockquote>\n<p><strong>Uniform naming</strong></p>\n<p>Rather than <code>DYNAMIC_ARR_...</code>, match <code>DYNARRAY_...</code>.</p>\n<p>Other than that, <em>very good</em> naming scheme.</p>\n<p><strong>Allow pushing <code>const</code> data</strong></p>\n<pre><code>// void $DynArray_Push(struct $DynArray* arr, void* value)\nvoid $DynArray_Push(struct $DynArray* arr, const void* value)\n</code></pre>\n<p><strong>Not always an error</strong></p>\n<p><code>$DynArray_Shrink()</code> calls <code>$DynArray_ErrorFree(arr)</code> even if <code>arr-&gt;size == 0</code>.</p>\n<p><strong>Bug??</strong></p>\n<p>In <code>$DynArray_Shrink()</code>, code has <code>++arr-&gt;size;</code>. Maybe <code>--arr-&gt;size;</code>?</p>\n<p><strong>Pedantic: check overflow</strong></p>\n<pre><code>// Add\nif (arr-&gt;capacity &gt; SIZE_MAX/DYNAMIC_ARR_GROWTHRATE) Handle_Error();\nsize_t newCapacity = (size_t)(arr-&gt;capacity * DYNAMIC_ARR_GROWTHRATE);\n</code></pre>\n<p><strong>Use correct specifier</strong></p>\n<p>I also suspect code was not compiled with all warnings enabled. Save time, enabled them all.</p>\n<pre><code>// printf(&quot;size: %i\\n&quot;, intArr.size);\nprintf(&quot;size: %zu\\n&quot;, intArr.size);\n</code></pre>\n<p><strong><a href=\"https://en.wikipedia.org/wiki/Information_hiding\" rel=\"nofollow noreferrer\">Info hiding</a></strong></p>\n<p>Consider only <em>declaring</em> <code>struct $DynArray</code> in <code>dynarry.h</code> and putting the <em>definition</em> in <code>dynarray.c</code>. User need not see the members. Create access functions if member access needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T13:30:55.333", "Id": "532616", "Score": "0", "body": "Thanks, this was really helpful, however in the case of types having spaces such as in `long long`, is this not covered by the code using a `tag` for its types? For example: `DynArray_Decl(long long, longlong)` then when using it, use `struct DynArray(longlong)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T13:33:46.293", "Id": "532617", "Score": "0", "body": "Also yes there is a bug in the shrink function, thanks for pointing that out haha, there should be no modification to `arr->size`. Good catch!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T13:45:26.543", "Id": "532619", "Score": "0", "body": "Also, just had a very quick look at _Generic, but I'm not sure how it would work to allow for user-defined types." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T16:01:32.697", "Id": "532639", "Score": "0", "body": "@name Re: `DynArray_Decl`. The .h file provides scant info on its usage. Sample code also lacks detail with `DynArray_Decl(int, int)`. AFAIK, one should code `DynArray_Decl(long long, long long)`. Do not relay on user access to the *.c file to understand how to this function set. More documentation in the .h file is deserved." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T16:06:39.750", "Id": "532640", "Score": "0", "body": "@name Does not `main()` demo a failed _type safe_? `struct DynArray(int) intArr; ... \n DynArray_Push(int)(&intArr, i /* which is a size_t and not int */);`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T16:39:19.617", "Id": "532643", "Score": "0", "body": "You are completely right, the demo does fail type safe. I'll edit to fix it haha." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T16:41:45.067", "Id": "532644", "Score": "0", "body": "In visual studio I don't get a compiler warning / error for using `size_t` instead of `int`, I either have suppressed warnings or there is an implicit conversion I'm unaware of." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T16:44:22.873", "Id": "532645", "Score": "0", "body": "I'll keep documentation on usage in mind, would you like to add that to your answer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T21:40:55.807", "Id": "532671", "Score": "0", "body": "@name the goal \"type-safe generic dynamic array\" has 3 parts; \"type-safe\", \"generic\", \"dynamic array\". IMO start docs and code with \"dynamic array\" and then proceed to \"generic\", then \"type-safe\". You have selected a quite ambitious task here." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T12:06:41.520", "Id": "269874", "ParentId": "269801", "Score": "2" } } ]
{ "AcceptedAnswerId": "269874", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T02:56:21.853", "Id": "269801", "Score": "3", "Tags": [ "beginner", "c", "type-safety" ], "Title": "Implementation of a type-safe generic dynamic array in C" }
269801
<p>I have this code that controls the user permissions provided to a user. In my case, I constructed a simple example of CRUD. When the admin checks the boxes, it will grant the user access to perform that operation. For example, if I provide the user the ability to create, they can do so.</p> <p>The code works but I believe there is a better approach to make a simpler or more short and concise code using what I have mentioned or made in my code below.</p> <p>Is there any way to shorten and make my code more efficient, and can you provide me any ideas, advice or tips on how to create better and more efficient code?</p> <h1>Code:</h1> <hr /> <pre><code> const [permission, setPermission] = useState({ create: true, view: true, edit: true, delete: true, }); const createPerms = () =&gt; { setPermission({ ...permission, create: !permission.create }); }; const viewPerms = () =&gt; { setPermission({ ...permission, view: !permission.view }); }; const editPerms = () =&gt; { setPermission({ ...permission, edit: !permission.edit }); }; return ( &lt;&gt; &lt;h1&gt; &lt;center&gt; User Permission &lt;/center&gt; &lt;/h1&gt; &lt;table className=&quot;ui celled table&quot;&gt; &lt;thead&gt; &lt;tr&gt; {Object.keys(permission).map((key) =&gt; ( &lt;th key={key}&gt;{key}&lt;/th&gt; ))} &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; {Object.keys(permission).map((key) =&gt; ( &lt;td key={key}&gt; &lt;input type=&quot;checkbox&quot; onChange={eval(key + &quot;Perms&quot;)} /&gt; &lt;/td&gt; ))} &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; {permission.create &amp;&amp; &lt;h3&gt;Create&lt;/h3&gt;} {permission.view &amp;&amp; &lt;h3&gt;View&lt;/h3&gt;} &lt;/&gt; ); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T11:18:58.187", "Id": "532453", "Score": "1", "body": "Welcome to CR! Please choose a title that describes the application's purpose, rather than the goal for the review. Thanks." } ]
[ { "body": "<p>The main points on your code that can be improved are described in the following sections. I can't really find anything that can improve the performance of your code, so i will focus more on how you can shorten your code and make it more readable.</p>\n<h4>Checkboxes state</h4>\n<p>You chose to store all 4 permissions in an object which is just fine. The key of the object is the <code>type</code> of the permission and the value is the corresponding flag indicating if the permission is on/off (<code>enabled</code>). You haven't used the <code>enabled</code> part in your checkboxes in order to reflect the current state. That's why although you have set all permissions initially to <code>true</code>, the checkboxes are not checked.</p>\n<p>You can use <code>Object.entries(permission).map(([key, enabled])</code> instead and provide the <code>enabled</code> as the <code>checked</code> attribute of the checkbox element.</p>\n<h4>Use of <code>eval</code></h4>\n<p>In general you should <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_eval!\" rel=\"nofollow noreferrer\">avoid using eval</a>. You can see a pattern in your <code>createPerms</code>, <code>editPerms</code> etc methods. They all have the same syntax and the only thing changing is the <code>type</code> of the permission. That makes me think that you can create one method (instead of 4) and pass the type of the permission as a parameter. Your method could look like this:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code> const oneToRuleThemAll = (type) =&gt; {\n setPermission({ ...permission, [type]: !permission[type] });\n };\n</code></pre>\n<h3>Naming</h3>\n<p>Naming is really important and helps other people reading your code (or even your future self) to quickly understand what your code and variables are intended to do. Some key points that can improve readability are:</p>\n<ul>\n<li>rename <code>permission</code> state to <code>permissions</code> since it keeps all of them</li>\n<li>when iterating through the keys of your <code>permission</code> object you can use a more indicative name for each key, that states what this key represents. In your case <code>type</code> (or even <code>permissionType</code>) is much more explanatory than the generic <code>key</code> name.</li>\n<li>the method's name <code>createPerms</code>, <code>editPerms</code> etc are not really useful because they do not describe what each method does. These methods toggle the permission of the corresponding type (e.g. <code>createPerms</code> toggles the value of <code>create</code> permission). So a more valid name would be <code>toggleCreatePermission</code>.\n(But remember you don't have to do this since we will get rid of these 4 methods and just create one accepting <code>type</code> as an argument)</li>\n</ul>\n<h3>Final code</h3>\n<pre class=\"lang-javascript prettyprint-override\"><code> const [permissions, setPermissions] = useState({\n create: true,\n view: true,\n edit: true,\n delete: true\n });\n\n const togglePermission = (type) =&gt; {\n setPermissions({ ...permissions, [type]: !permissions[type] });\n };\n\n return (\n &lt;&gt;\n &lt;h1&gt;\n &lt;center&gt; User Permission &lt;/center&gt;\n &lt;/h1&gt;\n\n &lt;table className=&quot;ui celled table&quot;&gt;\n &lt;thead&gt;\n &lt;tr&gt;\n {Object.keys(permissions).map((type) =&gt; (\n &lt;th key={type}&gt;{type}&lt;/th&gt;\n ))}\n &lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n &lt;tr&gt;\n {Object.entries(permissions).map(([type, enabled]) =&gt; (\n &lt;td key={type}&gt;\n &lt;input\n type=&quot;checkbox&quot;\n onChange={() =&gt; togglePermission(type)}\n checked={enabled}\n /&gt;\n &lt;/td&gt;\n ))}\n &lt;/tr&gt;\n &lt;/tbody&gt;\n &lt;/table&gt;\n\n {permissions.create &amp;&amp; &lt;h3&gt;Create&lt;/h3&gt;}\n {permissions.view &amp;&amp; &lt;h3&gt;View&lt;/h3&gt;}\n {permissions.edit &amp;&amp; &lt;h3&gt;Edit&lt;/h3&gt;}\n {permissions.delete &amp;&amp; &lt;h3&gt;Delete&lt;/h3&gt;}\n &lt;/&gt;\n);\n</code></pre>\n<h3>Extra stuff</h3>\n<p><strong>The enhancement described here is an overkill for you component currently, but i added it to demonstrate how you can make your code even more extensible in the future and for educational purposes</strong></p>\n<p>So another improvement that can possibly make your code more easily extensible would be to store your permission types in a constant object and create them dynamically. Let me elaborate on that.</p>\n<p>Let's suppose you want to add one more permission to your component and let's name this new permission <code>authorize</code>. With the code above you need to add this new permission in your initial <code>permissions</code> state like <code>authorize: true</code> and add a new rendering section at the end to show if this is enabled or not like <code>{permissions.authorize &amp;&amp; &lt;h3&gt;Authorize&lt;/h3&gt;}</code>.</p>\n<p>You can create a static object that would look like this:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const PERMISSIONS = {\n create: { name: 'Create', initial: true },\n view: { name: 'View', initial: true },\n edit: { name: 'Edit', initial: true },\n delete: { name: 'Delete', initial: true }\n}\n</code></pre>\n<p>and then create your initial state dynamically once like below:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const INITIAL_STATE = Object.entries(PERMISSIONS).reduce((result, [type, permission]) =&gt; {\n result[type] = permission.initial;\n return result;\n}, {})\n</code></pre>\n<p>and initialize your state: <code>useState(INITIAL_STATE)</code></p>\n<p>Then you can also change the permissions rendering section to make it fully dynamic and make it like below:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code> Object.entries(permissions)\n .filter(([type, enabled]) =&gt; enabled)\n .map(([type]) =&gt; &lt;h3&gt;PERMISSIONS[type].name&lt;/h3&gt;)\n</code></pre>\n<p>Having done all that you can add/remove permissions by just adding a new entry on your static <code>PERMISSIONS</code> object. For the new <code>authorize</code> example this would be:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const PERMISSIONS = {\n create: { name: 'Create', initial: true },\n view: { name: 'View', initial: true },\n edit: { name: 'Edit', initial: true },\n delete: { name: 'Delete', initial: true },\n authorize: { name: 'Authorize', initial: false }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T05:29:02.797", "Id": "532527", "Score": "0", "body": "Thank you so much for the explanation, this is the one I needed. :))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T05:36:03.103", "Id": "532528", "Score": "0", "body": "And also for the extra info yes I'll be possibly needing it for the future purpose" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T11:42:17.463", "Id": "269809", "ParentId": "269805", "Score": "2" } } ]
{ "AcceptedAnswerId": "269809", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T09:32:15.537", "Id": "269805", "Score": "0", "Tags": [ "object-oriented", "json", "react.js", "jsx", "authorization" ], "Title": "React code that controls user permissions" }
269805
<p>I have this piece of code where it based on this condition:</p> <ol> <li>Box Color can only be in red, white and black</li> <li>If the box's type is A then any color is allowed</li> <li>Box's type C is not allowed at all</li> <li>For the gift, only green and blue color is allowed and the size cannot be small</li> <li>Box and gift color cannot be same</li> </ol> <p>views.py</p> <pre><code> boxColor = [&quot;red&quot;, &quot;white&quot;, &quot;black&quot;] giftColor = [&quot;green&quot;, &quot;blue&quot;] if box.color != gift.color: if gift.color in giftColor and gift.size != &quot;small&quot;: if (box.type == &quot;A&quot;) or (box.type != &quot;C&quot; and box.color in boxColor): return True else: return False else: return False else: return False </code></pre> <p>Is there is a way to simplify my code that I can make this more efficient ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T13:10:31.030", "Id": "532462", "Score": "0", "body": "Welcome to Code Review@SE. A `return` statement looks lacking context without a `def`, and the title doesn't follow site conventions: Please (re)visit [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask)" } ]
[ { "body": "<p>Yes, this should be simplified. Prefer sets since you're doing membership checks, and write this as a boolean expression rather than a series of <code>if</code> checks with <code>return</code>s:</p>\n<pre><code>return (\n box.type != 'C'\n and (\n box.type == 'A'\n or box.color in {'red', 'white', 'black'}\n )\n and box.color != gift.color\n and gift.size != 'small'\n and gift.color in {'green', 'blue'}\n)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T13:48:22.203", "Id": "532466", "Score": "0", "body": "Thankyou so much!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T12:52:26.303", "Id": "269812", "ParentId": "269810", "Score": "1" } } ]
{ "AcceptedAnswerId": "269812", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T12:04:25.537", "Id": "269810", "Score": "1", "Tags": [ "python" ], "Title": "Checking whether box and gift colors satisfy the given criteria" }
269810
<p>My Pagination component provides buttons:</p> <ol> <li>5 around page (i.e: if current page is 3, then it will show button page 2 3 4 5 6)</li> <li>Prev/Next page</li> <li>Button to last page</li> </ol> <p><a href="https://i.stack.imgur.com/xZygs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xZygs.png" alt="screenshot of pagination buttons" /></a></p> <pre><code>const PageButton = ({ currentPage, lastPage, handlePageClick }) =&gt; { const render = []; if (currentPage - 1 &gt;= 0) { const prevPage = currentPage - 1; render.push( &lt;IconButton icon={&lt;ChevronLeftIcon /&gt;} value={prevPage} onClick={handlePageClick} key={`prev-page-${prevPage}`} /&gt; ); } let startIdx; let endIdx; if (currentPage - 1 &gt;= 0) { startIdx = currentPage - 1; endIdx = startIdx + 5; } else { startIdx = 0; endIdx = 5; } if (currentPage + 3 &gt;= lastPage) { startIdx = lastPage - 5; endIdx = lastPage; } for (let idx = startIdx; idx &lt; endIdx; idx++) { const offset = idx + 1; render.push( &lt;Button key={`page-${offset}`} onClick={handlePageClick} value={idx}&gt; {offset} &lt;/Button&gt; ); } if (endIdx &lt; lastPage) { const offset = lastPage - 1; render.push( &lt;React.Fragment key={`last-page-${lastPage}`}&gt; &lt;FontAwesomeIcon icon={faEllipsisH} color=&quot;gray&quot; /&gt; &lt;Button onClick={handlePageClick} value={offset} &gt; {lastPage} &lt;/Button&gt; &lt;/React.Fragment&gt; ); } if (currentPage + 1 &lt; lastPage) { const nextPage = currentPage + 1; render.push( &lt;IconButton icon={&lt;ChevronRightIcon /&gt;} value={nextPage} onClick={handlePageClick} key={`next-page-${nextPage}`} /&gt; ); } return render; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T13:22:21.583", "Id": "532627", "Score": "0", "body": "So what is your question? what is the problem here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T01:24:02.293", "Id": "532679", "Score": "0", "body": "@TomvandenBogaart This site is for code review. For question, I will go to stackoverflow" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T12:16:10.000", "Id": "269811", "Score": "0", "Tags": [ "react.js", "jsx", "pagination" ], "Title": "Pagination component using React and Chakra UI" }
269811
<p>This inspired by this <a href="https://codereview.stackexchange.com/questions/269767/find-all-possible-ways-a-rook-can-move-to-a-diagonally-opposite-corner-without-g">C# question</a></p> <p>The basics is to calculate the total number of paths that a rook can take without revisiting a square to move to a diagonally opposite position.</p> <p>I tried to throw every possible tool in my rather limited toolset at this and got a pretty decent improvement.</p> <p>To calculate all the possible moves for grids &lt; 7x7 takes less than a second and a 7x7 grid takes about 45 seconds.</p> <p>I have tried to calculate the moves for an 8x8 grid but after 12 hours my office started to smell like burning plastic and I gave up.</p> <p>Is there any way to make this more efficient?</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;atomic&gt; #include &lt;chrono&gt; #include &lt;iostream&gt; #include &lt;thread&gt; #include &lt;vector&gt; typedef unsigned long long uint64; typedef unsigned int uint32; std::atomic&lt;uint64&gt; pathsFound = 0; class Board { public: Board(uint32 rows, uint32 cols) : rows{ rows }, cols{ cols } { for (uint32 y = 0; y &lt; rows; y++) { for (uint32 x = 0; x &lt; cols; x++) { squares.push_back(calcMoves(x, y)); } } } uint32 calcIndex(uint32 x, uint32 y) { return x + y * cols; } uint64 calcBit(uint32 index) { uint64 one = 1; return one &lt;&lt; index; } std::vector&lt;uint32&gt; calcMoves(uint32 x, uint32 y) { std::vector&lt;uint32&gt; moves; if (x &gt; 0) moves.push_back(calcIndex(x - 1, y)); if (x &lt; cols - 1) moves.push_back(calcIndex(x + 1, y)); if (y &gt; 0) moves.push_back(calcIndex(x, y - 1)); if (y &lt; rows - 1) moves.push_back(calcIndex(x, y + 1)); return moves; } void GetPaths(uint64 path, uint32 currentIndex, uint32 targetIndex, uint32 level) { if (currentIndex == targetIndex) { pathsFound++; return; } path |= calcBit(currentIndex); if (level &lt; 4) { #pragma omp parallel for for (int i = 0; i &lt; squares[currentIndex].size(); i++) { uint32 move = squares[currentIndex][i]; if ((uint64)(path &amp; calcBit(move)) == (uint64)0) { GetPaths(path, move, targetIndex, level + 1); } } } else { for (uint32 move : squares[currentIndex]) { if ((uint64)(path &amp; calcBit(move)) == (uint64)0) { GetPaths(path, move, targetIndex, level + 1); } } } } uint32 rows; uint32 cols; std::vector&lt;std::vector&lt;uint32&gt;&gt; squares; }; void timer(std::stop_token stoken) { using namespace std::chrono; auto begin = steady_clock::now(); while (!stoken.stop_requested()) { std::this_thread::sleep_for(seconds(1)); auto end = steady_clock::now(); std::cout &lt;&lt; &quot;found = &quot; &lt;&lt; pathsFound &lt;&lt; &quot;, ellapsed = &quot; &lt;&lt; duration_cast&lt;seconds&gt;(end - begin).count() &lt;&lt; &quot; sec.\n&quot;; } } int main() { constexpr uint32 size = 7; Board board(size, size); std::jthread tt(timer); uint32 currentIndex = board.calcIndex(0, 0); uint32 targetIndex = board.calcIndex(size - 1, size - 1); board.GetPaths(0, currentIndex, targetIndex, 0); tt.request_stop(); tt.join(); std::cout &lt;&lt; &quot;Paths = &quot; &lt;&lt; pathsFound; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T14:10:23.390", "Id": "532469", "Score": "0", "body": "Using ```std::vector<std::vector<T>>``` for 2D grid is often repeated beginner-like decision. Prefer ```std::array<T, rows * cols> ``` (then you should use rows, cols as template parameter of ```Board```), or if you want to get rows/cols dynamically, use ```std::unique_ptr<T[]>```" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T14:12:22.730", "Id": "532470", "Score": "0", "body": "@frozenca, it's is a vector that contains possible moves for each square. I agree that `std::array` might have been better but it will make zero difference to the performance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T14:16:55.390", "Id": "532471", "Score": "0", "body": "Oh, my bad. Isn't using ```uint32``` for move an overkill? How about ```uint8``` instead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T14:20:10.470", "Id": "532472", "Score": "0", "body": "@frozenca I have tried that but it does not seem to make any messurable difference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T16:44:43.357", "Id": "532574", "Score": "2", "body": "Reference: https://oeis.org/A007764" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T17:35:19.787", "Id": "532576", "Score": "2", "body": "@CarstenS, thanks, very interesting. I especially liked the [youtube](http://www.youtube.com/watch?v=Q4gTV4r0zRs) video :-)" } ]
[ { "body": "<h1>Use standard integer types</h1>\n<p>Don't use <code>typedef</code> to create your own fixed-size integer types. The standard library provides types like <a href=\"https://en.cppreference.com/w/cpp/types/integer\" rel=\"noreferrer\"><code>std::uint32_t</code> and <code>std::uint64_t</code></a> for you. Your <code>typedef</code>s might not be correct on all platforms. C only guarantees that an <code>int</code> is at least 16 bits for example, and a <code>long long</code> might actually be larger than 64 bits.</p>\n<p>If you want to save a bit of typing, then you can bring the standard types into the global namespace so you can avoid having to write <code>std::</code>, like so:</p>\n<pre><code>#include &lt;cstdint&gt;\n\nusing std::uint32_t;\nusing std::uint64_t;\n</code></pre>\n<p>But don't do this inside header files.</p>\n<h1>Make the board's dimensions template parameters</h1>\n<p>Perhaps the compiler will see that you use a constant for the size of the board and will optimize your code accordingly, but to avoid any doubt, you can use template paramaters to set the size of a <code>Board</code>:</p>\n<pre><code>template&lt;std::size_t rows, std::size_t cols&gt;\nclass Board {\npublic:\n Board() {\n for (std::size_t y = 0; y &lt; rows; y++) {\n ...\n</code></pre>\n<h1>Optimize finding valid rook moves</h1>\n<p>You are pre-computing a vector of vector for all the valid rook moves. Traversing <code>squares</code> means double pointer indirection. It is probably much faster to try all four directions inside <code>GetPaths()</code>, and check for each direction whether it is valid there. So something like:</p>\n<pre><code>#pragma omp parallel for \nfor (int dir = 0; dir &lt; 4; ++dir) {\n if (auto move = GetValidMove(currentIndex, dir)) {\n if (!(path &amp; calcBit(*move)) {\n GetPaths(path, *move, targetIndex, level + 1);\n }\n }\n}\n</code></pre>\n<p>Where <code>GetValidMove()</code> looks like this:</p>\n<pre><code>std::optional&lt;std::uint32_t&gt; GetValidMove(std::uint32_t index, int dir) {\n switch (dir) {\n case 0:\n if (index % cols) // will be efficient on an 8x8 board\n return index - 1;\n else\n return std::nullopt; // {} works as well\n case 1:\n ...\n }\n}\n</code></pre>\n<h1>Rook or king moves?</h1>\n<p>You are only checking for moves to adjacent tiles. In chess, a rook can move as much as it wants in a horizontal or vertical direction. If it moves from one side to the other, you don't count the tiles inbetween as visited.</p>\n<h1>Prune dead ends early</h1>\n<p>If you always start at the top left of the board, and after a few moves you hit another wall like so:</p>\n<pre><code> --------\n|# |\n|## |\n| #### |\n| ###X|\n| |\n --------\n</code></pre>\n<p>Then you know that you just partitioned the board into two halves, and one half is a dead zone. In the case of hitting the right wall, going up is never going to get you to the bottom right again. But your algorithm will explore every possible path within the dead zone. Adding a check for this might make each move less efficient, but pruning huge parts of the solution space this way might more than make up for it.</p>\n<h1>Make functions <code>static</code> and/or <code>const</code> where possible</h1>\n<p>Functions like <code>calcIndex()</code> and <code>calcBit()</code> neither use nor modify member variables, so they should be made <code>static</code> and <code>const</code>:</p>\n<pre><code>static std::uint32 calcIndex(std::uint32 x, std::uint32 y) const {\n ...\n}\n</code></pre>\n<p><code>GetPaths()</code> doesn't modify any member variables, so it can be made <code>const</code>. But that also brings me to:</p>\n<h1>Avoid making a <code>class</code> unnecessarily</h1>\n<p>In Java and C#, everything has to be in a <code>class</code>. However, in C++ there is no such requirement. In your code, you are only interested in calling <code>GetPaths()</code>. Consider writing it as a free function:</p>\n<pre><code>template&lt;std::size_t rows, std::size_t cols&gt;\nstatic GetPaths(std::uint32_t currentIndex = 0, std::uint32_t targetIndex = rows * cols - 1, std::uint64_t path = 0, std::uint32_t level = 0) {\n ...\n GetPaths(move, targetIndex, path, level + 1);\n ...\n}\n\nint main() {\n std::jthread tt(timer);\n GetPaths&lt;7, 7&gt;();\n std::cout &lt;&lt; &quot;Paths = &quot; &lt;&lt; pathsFound &lt;&lt; '\\n';\n}\n</code></pre>\n<h1>Make <code>GetPaths()</code> return the number of paths</h1>\n<p>I understand why you made <code>pathsFound</code> a global atomic variable, as it's the easiest way to have a separate thread show the progress. However, it has some drawbacks:</p>\n<ul>\n<li>It uses global state, so you cannot run <code>GetPaths()</code> for multiple boards a the same time.</li>\n<li>Atomics themselves are not free and might make the code less efficient.</li>\n<li>Functions should return their results via the return parameter.</li>\n</ul>\n<p>I would make it so it returns the number of paths, but you can still use a global atomic for debugging:</p>\n<pre><code>template&lt;...&gt;\nstatic std::uint64_t GetPaths(...) {\n if (currentIndex == targetIndex)\n {\n pathsFound++; // for debugging purposes\n return 1;\n }\n\n ...\n std::uint64_t num_paths{};\n ...\n num_paths += GetPaths(...);\n ...\n return num_paths;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T14:56:56.843", "Id": "532479", "Score": "0", "body": "The `King versus Rook` part bothered me about the original C# question as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T21:44:08.150", "Id": "532509", "Score": "0", "body": "Thanks for your review. I'm going to experiment with early pruning and all the other suggestions. I'm not really sure what you mean with `double pointer indirection`. I would have thought that pre-calculating the moves would be faster than messing with division and modulus operations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T22:27:31.213", "Id": "532519", "Score": "0", "body": "A `std::vector<T>` is basically a size and a pointer to an array of `T`s. A `std::vector<std::vector<T>>` is therefore a size and a pointer to an array of sizes and pointers to arrays of `T`s. Everything the CPU does costs some cycles. Following pointers has its cost. Division and modulus is expensive in general as well, but it can be very cheap if the size of your board is a power of two, as a compiler will, for example, be able to convert `% 8` into `& 7`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T14:45:50.650", "Id": "269821", "ParentId": "269813", "Score": "7" } }, { "body": "<h1>Timer logic drift</h1>\n<p>I know this will not help you speed it up, but your timer logic has some potential for drift. It could be that you see output for seconds 1, 2, 3, and 5, but not for 4, if your cpu is under heavy load.</p>\n<p>To prevent drift, instead of</p>\n<pre><code>void timer(std::stop_token stoken)\n{\n using namespace std::chrono;\n auto begin = steady_clock::now();\n while (!stoken.stop_requested())\n {\n std::this_thread::sleep_for(seconds(1));\n auto end = steady_clock::now();\n std::cout &lt;&lt; &quot;found = &quot; &lt;&lt; pathsFound &lt;&lt; &quot;, ellapsed = &quot; &lt;&lt; duration_cast&lt;seconds&gt;(end - begin).count() &lt;&lt; &quot; sec.\\n&quot;;\n }\n}\n</code></pre>\n<p>use something like</p>\n<pre><code>void timer(std::stop_token stoken)\n{\n using namespace std::chrono;\n auto begin = steady_clock::now();\n size_t secondsSinceStart = 0;\n while (!stoken.stop_requested())\n {\n std::this_thread::sleep_until(begin + seconds(++secondsSinceStart));\n std::cout &lt;&lt; &quot;found = &quot; &lt;&lt; pathsFound &lt;&lt; &quot;, ellapsed = &quot; &lt;&lt; secondsSinceStart &lt;&lt; &quot; sec.\\n&quot;;\n }\n}\n</code></pre>\n<p>This will ensure that you get output for every second, reducing potential further trouble if you'd want to parse your output.</p>\n<p>(It's not a big improvement, definitely not to performance, but a good habit to get into writing timed things this way.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T08:45:37.243", "Id": "269840", "ParentId": "269813", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T12:57:05.197", "Id": "269813", "Score": "6", "Tags": [ "c++", "performance", "c++20" ], "Title": "Find all possible ways a rook can move, C++ version" }
269813
<p>I'm building a tool that requires nested items. For that I use MySQL and Vue but that may not be important.</p> <p>Because MySQL does not really support nested data I created the nested part as JSON. To make the JSON file as small as possible I only store the IDs of the items with no additional data.</p> <h2>Nested JSON</h2> <p>It stores IDs and children with child item IDs.</p> <pre class="lang-json prettyprint-override"><code>{ &quot;id&quot;: 1, &quot;children&quot;: [ { &quot;id&quot;: 12345 }, { &quot;id&quot;: 4567, &quot;children&quot;: [ { &quot;id&quot;: 12 }, { &quot;id&quot;: 45, &quot;children&quot;: [ { &quot;id&quot;: 644 }, { &quot;id&quot;: 88 } ] } ] }, { &quot;id&quot;: 678 }, { &quot;id&quot;: 1678 } ] } </code></pre> <h2>Data from MySQL</h2> <p>I get the additonal data from MySQL which has a flat structure. It connects to the JSON with the ID numbers. This example shows the output as JSON but the info comes from a MySQL database.</p> <pre class="lang-json prettyprint-override"><code>{ &quot;1&quot;: { &quot;title&quot;: &quot;Just a dummy title&quot;, &quot;bold&quot;: true, &quot;favourite&quot;: false, &quot;description&quot;: &quot;En beskrivning&quot; }, &quot;12345&quot;: { &quot;title&quot;: &quot;Another one&quot; }, &quot;4567&quot;: { &quot;title&quot;: &quot;Cookie carrot cake chupa chups chupa chups soufflé chocolate cake liquorice. Muffin icing lollipop halvah tiramisu marshmallow tootsie roll donut. Muffin chocolate bar wafer chocolate bar chupa chups pudding cotton candy gingerbread pie.&quot;, &quot;bold&quot;: false, &quot;favourite&quot;: true, &quot;description&quot;: &quot;En till beskrivning&quot; }, &quot;12&quot;: { &quot;title&quot;: &quot;What about this one&quot; } } </code></pre> <h2>Question</h2> <p>Will this solution work well if the user add many items, or will the JSON file be too big and slow it down? I'm not sure how much but think of it as a todo list app with items and children of items.</p> <h2>Update</h2> <p>I calculated that my JSON file now is 360 characters. At most it should probably be at most 500 characters. For it to be 1MB, I should be able to store 20.000 items.</p> <p>If 1MB is much to handle, I don't know. If 20.000 todo list items is generous, I don't know.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T13:40:34.437", "Id": "532464", "Score": "0", "body": "Please share the SQL that defines your table. Also: what do the `id` and `children` fields actually represent?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T13:42:26.673", "Id": "532465", "Score": "0", "body": "And: is there some constraint keeping you on MySQL, or can you migrate to PostgreSQL (or at least MariaDB)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T19:05:41.120", "Id": "532835", "Score": "1", "body": "See; [What are the options for storing hierarchical data in a relational database?](https://stackoverflow.com/questions/4048151/what-are-the-options-for-storing-hierarchical-data-in-a-relational-database)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T13:00:18.017", "Id": "269814", "Score": "0", "Tags": [ "mysql", "json", "nested" ], "Title": "Nested data as JSON - A good idea for scale?" }
269814
<p>As a part of <a href="https://github.com/morgwai/servlet-scopes" rel="nofollow noreferrer">library implementing websocket Guice scopes</a> I need to maintain an object related to each <code>HttpSession</code> called <code>sessionContextAttributes</code>. Currently <code>sessionContextAttributes</code> is stored as an attribute of a session, which means the access and initialization needs to be synchronized:</p> <pre class="lang-java prettyprint-override"><code>ConcurrentMap&lt;Key&lt;?&gt;, Object&gt; getHttpSessionContextAttributes() { HttpSession session = getHttpSession(); try { synchronized (session) { @SuppressWarnings(&quot;unchecked&quot;) var sessionContextAttributes = (ConcurrentMap&lt;Key&lt;?&gt;, Object&gt;) session.getAttribute(SESSION_CONTEXT_ATTRIBUTE_NAME); if (sessionContextAttributes == null) { sessionContextAttributes = new ConcurrentHashMap&lt;&gt;(); session.setAttribute(SESSION_CONTEXT_ATTRIBUTE_NAME, sessionContextAttributes); } return sessionContextAttributes; } } catch (NullPointerException e) { /* ... */ } } static final String SESSION_CONTEXT_ATTRIBUTE_NAME = ContainerCallContext.class.getPackageName() + &quot;.contextAttributes&quot;; </code></pre> <p>Now I'm considering to maintain a static <code>ConcurrentMap</code> from <code>HttpSession</code> to <code>sessionContextAttributes</code> like this:</p> <pre class="lang-java prettyprint-override"><code>static final ConcurrentMap&lt;HttpSession, ConcurrentMap&lt;Key&lt;?&gt;, Object&gt;&gt; sessionCtxs = new ConcurrentHashMap&lt;&gt;(); ConcurrentMap&lt;Key&lt;?&gt;, Object&gt; getHttpSessionContextAttributes() { try { return sessionCtxs.computeIfAbsent( getHttpSession(), (ignored) -&gt; new ConcurrentHashMap&lt;&gt;()); } catch (NullPointerException e) { /* ... */ } } </code></pre> <p>This simplifies <code>getHttpSessionContextAttributes()</code> method and is probably slightly faster, <strong>BUT</strong> introduces static data <strong>AND</strong> requires manual removal to prevent leaking of <code>sessionContextAttributes</code>:</p> <pre class="lang-java prettyprint-override"><code>static class SessionContextJanitor implements HttpSessionListener { @Override public void sessionDestroyed(HttpSessionEvent event) { sessionCtxs.remove(event.getSession()); // this avoids resource leaks } } </code></pre> <p>I cannot confidently tell which approach is better: both have pros&amp;cons. Hence I'm posting it here for review: maybe someone knows some reasons that make 1 of these approaches significantly better than the other.</p>
[]
[ { "body": "<p>After some more research and thinking, it turned out that both of the above approaches are wrong ;-]<br />\nThe reason for both cases is that user <code>Filter</code>s may put <code>HttpSession</code> object into a wrapper, so neither synchronizing on it nor using it as a key in a <code>ConcurrentHashMap</code> is safe :/<br />\nFurthermore, in case of &quot;<em>maintaining a static <code>ConcurrentMap</code></em>&quot; solution, <code>sessionContextAttributes</code> would not get serialized together with its session for example when sharing between cluster nodes or temporarily storing on disk to use memory for other requests.</p>\n<p>Instead, I use <code>HttpSessionListener</code> to create and store the new context as a session attribute:</p>\n<pre class=\"lang-java prettyprint-override\"><code>ConcurrentMap&lt;Key&lt;?&gt;, Object&gt; getHttpSessionContextAttributes() {\n try {\n return (ConcurrentMap&lt;Key&lt;?&gt;, Object&gt;)\n getHttpSession().getAttribute(SESSION_CONTEXT_ATTRIBUTE_NAME);\n } catch (NullPointerException e) {\n // sessionContextAttributes!=null guaranteed, handles session==null\n }\n}\n\nstatic class SessionContextCreator implements HttpSessionListener {\n\n @Override\n public void sessionCreated(HttpSessionEvent event) {\n event.getSession().setAttribute(\n SESSION_CONTEXT_ATTRIBUTE_NAME, new ConcurrentHashMap&lt;Key&lt;?&gt;, Object&gt;());\n }\n}\n</code></pre>\n<p>While it is not explicitly stated in the spec that <code>sessionCreated(...)</code> will be called on the same thread that first created the session with <code>request.getSession()</code>, it is kinda implied and both Tomcat and Jetty do so. Last but not least, certain Spring utilities assume that this is always the case.<br />\nFurther discussions about this:\n<a href=\"https://stackoverflow.com/questions/53158685/is-httpsessionlistener-sessioncreated-guaranteed-to-complete-before-any-other\">1</a>,\n<a href=\"https://stackoverflow.com/questions/42051883/is-sessioncreated-from-a-httpsessionlistener-automatically-synchronized-with-r\">2</a>,\n<a href=\"https://stackoverflow.com/questions/9802165/is-synchronization-within-an-httpsession-feasible\">3</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T10:49:59.747", "Id": "532966", "Score": "0", "body": "Instead of `} catch (NullPointerException e) {` comment maybe just `if (getHttpSession() != null) ...`? (or some direct `session` check if it is getter's implementation dependend)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T12:40:40.810", "Id": "533043", "Score": "0", "body": "@Azahe NPE there is a result of a bug in the app that uses this library: it should be eliminated during development, so there's no point to check it every time in production where it will never happen. I catch it only to throw `RuntimeException` with [a message that explains how to fix this bug](https://github.com/morgwai/servlet-scopes/blob/v6.1-javax/src/main/java/pl/morgwai/base/servlet/scopes/ContainerCallContext.java#L49). See this article for further discussion on the topic: https://dzone.com/articles/why-i-never-null-check-parameters" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T12:47:49.423", "Id": "533045", "Score": "0", "body": "@Azahe in the post here the handling has been replaced with the comment not to bother ppl with reading code that is not related to the core of the question ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T10:37:47.297", "Id": "533252", "Score": "0", "body": "As much as I love the premise of article you mentioned (and consider it a standard approach at my workplace) I don't think that it any way justifies this way of handling programming errors. \nNote that the main idea of the article is to get rid of null checks ***by better design of the code*** - so here catching null pointer is IMO misappropriation of the idea as you are not eliminating the possibility of null pointer via redesigning library api so that making the known mistake impossible (like in the article's example with method parameters)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T11:22:36.273", "Id": "533254", "Score": "0", "body": "@Azahe you are correct, unfortunately the only way to eliminate possibility of this error would be to force session creation for every request starting a websocket connection: it is not acceptable in many cases and I didn't want to limit applicability of this lib. Reasons may be technical (cookies disabled, non-browser clients that don't even follow redirections), legal (user explicitly refusing any data storage) and probably others. Notifying developer ASAP about the issue with a clear message, was the best I could think of without compromising applicability. i's a sad trade-off basically..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T11:34:29.307", "Id": "533255", "Score": "0", "body": "@Azahe ...between API safety and lib applicability. This way developer can choose a solution that best suits him: either forcing a session creation with a filter (if it's acceptable in his case) or checking if the session exists and using app specific work-around instead of session-scoped objects (using websokcet connection scope instead will probably be acceptable in many situations).<br>\n(normal servlets are immune to this error as it's possible to create a session on demand from `HttpServletRequest`, but there's no such possibility when processing a single websocket message)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T10:02:05.650", "Id": "533314", "Score": "0", "body": "Maybe make a separate post for this trade off? :D Will probably require establishing more context but seems like nice topic." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T06:36:56.527", "Id": "269864", "ParentId": "269817", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T14:23:07.343", "Id": "269817", "Score": "2", "Tags": [ "java", "concurrency", "servlets" ], "Title": "synchronized access to HttpSession attribute vs static ConcurrentMap with HttpSessionListener" }
269817
<p>I am trying to look for a substring in a list of strings. My end result is an array that contains the presence of substring first based on <code>course.name</code> and then based on <code>course.description</code>. Is there a better way to write the following code?</p> <p>Firstly, I am looking for the substring in the <code>course.name</code> field using the <code>indexOf</code> method and adding it to the <code>foundCourseList</code> array.</p> <pre><code>let uniqueIds: string[] = []; let foundCourseList: CourseItem[] = []; this.props.courses.forEach((course: CourseItem) =&gt; { let courseNameListTobeSearchedIn = course.name.split(&quot; &quot;); courseNameListTobeSearchedIn.forEach((word: string) =&gt; { this.state.inputWord.split(&quot; &quot;).forEach((inputWord: string) =&gt; { if (word.toLowerCase().indexOf(inputWord.toLowerCase()) &gt;= 0 &amp;&amp; !uniqueIds.includes(course.id)) { foundCourseList.push(course); uniqueIds.push(course.id); }; }); }); }); </code></pre> <p>Then I am looking for the same substring in the <code>course.description</code> field using the <code>indexOf</code> method and add it to the <code>foundCourseList</code> array. In that was the search results display results based on <code>course.name</code> followed by the results based on the <code>course.description</code>.</p> <pre><code>this.props.courses.forEach((course: CourseItem) =&gt; { let courseDescriptionTobeSearchedIn: string[]; course.description &amp;&amp; (courseDescriptionTobeSearchedIn = course.description.split(&quot; &quot;)); if (courseDescriptionTobeSearchedIn) { courseDescriptionTobeSearchedIn.forEach((word: string) =&gt; { this.state.inputWord.split(&quot; &quot;).forEach((inputWord: string) =&gt; { if (word.toLowerCase().indexOf(inputWord.toLowerCase()) &gt;= 0 &amp;&amp; !uniqueIds.includes(course.id)) { foundCourseList.push(course); uniqueIds.push(course.id); }; }); }); } }); return foundCourseList; </code></pre>
[]
[ { "body": "<p>There are several inefficient elements in the implementation.</p>\n<h3>Use a <code>Set</code> instead of an array for fast lookups</h3>\n<p>The code uses <code>uniqueIds</code> to keep track of the ids seen so far.\nThe <code>uniqueIds.includes</code> does a linear scan over the items in the array.\nUsing a <code>Set</code> would make that constant time.</p>\n<h3>Avoid repeated computations</h3>\n<p>There are several repeated computations here:</p>\n<blockquote>\n<pre><code>this.props.courses.forEach((course: CourseItem) =&gt; {\n let courseNameListTobeSearchedIn = course.name.split(&quot; &quot;);\n \n courseNameListTobeSearchedIn.forEach((word: string) =&gt; {\n this.state.inputWord.split(&quot; &quot;).forEach((inputWord: string) =&gt; {\n if (word.toLowerCase().indexOf(inputWord.toLowerCase()) &gt;= 0 &amp;&amp; !uniqueIds.includes(course.id)) {\n</code></pre>\n</blockquote>\n<p>For each course, for each word in the course name, <code>this.state.inputWord</code> is repeatedly split to words, and then lowercased.\nAssuming that <code>this.state.inputWord</code> doesn't change between iterations,\nit would be better to lowercase it and split it to words once,\nbefore <code>this.props.courses.forEach</code> begins.</p>\n<p>For each input word, each <code>word</code> in the course name is repeatedly lowercased.\nIt would be better to lowercase <code>course.name</code> once before splitting it to words.</p>\n<p>The last kind of repeated computation is when there are duplicate words in the input or course names.\nIf that's unrealistic, then it might not be worth to optimize.\n(Otherwise, you could use <code>Set</code> to remove duplicates.)</p>\n<h3>Putting it together</h3>\n<p>With the above ideas applied, the code becomes:</p>\n<pre><code>const uniqueIds: Set&lt;string&gt; = new Set();\n\nconst inputWords = this.state.inputWord\n .toLowerCase()\n .split(&quot; &quot;);\n\nthis.props.courses.forEach((course: CourseItem) =&gt; {\n course.name\n .toLowerCase()\n .split(&quot; &quot;)\n .forEach((word: string) =&gt; {\n inputWords.forEach((inputWord: string) =&gt; {\n if (!uniqueIds.has(course.id) &amp;&amp; word.indexOf(inputWord) &gt;= 0) {\n foundCourseList.push(course);\n uniqueIds.add(course.id);\n };\n });\n });\n});\n</code></pre>\n<p>Notice that I switched the evaluation order in the conditions here:</p>\n<blockquote>\n<pre><code>if (!uniqueIds.has(course.id) &amp;&amp; word.indexOf(inputWord) &gt;= 0) {\n</code></pre>\n</blockquote>\n<p>The reason to order this way is because <code>!uniqueIds.has(course.id)</code> is the fast operation (thanks to making <code>uniqueIds</code> a <code>Set</code>), and <code>word.indexOf(inputWord)</code> is slower.\nThis way, if the fast condition doesn't pass,\nthe slower one can be skipped,\nso the ordering is significant.</p>\n<h3>Searching in both <code>course.name</code> and <code>course.description</code></h3>\n<p>The same points I demonstrated above on the snippet searching in <code>course.name</code> apply equally to searching in <code>course.description</code> too.</p>\n<p>Currently the search results based on <code>course.name</code> and the search results based on <code>course.description</code> both end up in the common array <code>foundCourseList</code>.\nAs such it seems to make sense to combine the words from <code>course.name</code> and <code>course.description</code> into set to make sure you don't loop over the same word twice,\nand in this case a single loop over the combined keywords will suffice:</p>\n<pre><code>courses.forEach((course: CourseItem) =&gt; {\n const keywords: Set&lt;string&gt; = new Set();\n\n course.name\n .toLowerCase()\n .split(&quot; &quot;)\n .forEach(keywords.add, keywords);\n\n course.description\n .toLowerCase()\n .split(&quot; &quot;)\n .forEach(keywords.add, keywords);\n\n keywords\n .toLowerCase()\n .split(&quot; &quot;)\n .forEach((word: string) =&gt; {\n inputWords.forEach((inputWord: string) =&gt; {\n if (!uniqueIds.has(course.id) &amp;&amp; word.indexOf(inputWord) &gt;= 0) {\n foundCourseList.push(course);\n uniqueIds.add(course.id);\n };\n });\n });\n});\n</code></pre>\n<h3>Going even further</h3>\n<p>If the frequency of search operations is significantly higher than the frequency of changes to the underlying fields (name and description),\nthen you may want to optimize further,\nto avoid recomputing the keywords over and over again to the same set of words.</p>\n<p>For example you could add a <code>keywords</code> property and recompute it every time <code>name</code> or <code>description</code> changes,\ninstead of recomputing it on every search.\nThis optimization is not free,\nbecause it requires more memory to store the keywords,\nand more computation when <code>name</code> or <code>description</code> changes.\nIt depends on your use case if this trade-off makes sense or not.</p>\n<p>Finally, you could speed up the search even further by building a <a href=\"https://en.wikipedia.org/wiki/Trie\" rel=\"nofollow noreferrer\">Trie</a> from the keywords instead of a simple <code>Set</code>.\nThis will cost even more memory, another trade-off.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T13:31:55.520", "Id": "532548", "Score": "0", "body": "Thanks for your answer. Its helpful to achieve a faster operation. However this did not address my problem where I am running the loop twice for searching for the input keyword in 2 arraylists: course.name and course.description.\nHow can I run the loop just once to look for the input word in 2 arraylists course.name and course.description and add it to the foundCourseList array?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T15:07:10.827", "Id": "532559", "Score": "0", "body": "@user2140740 I added one more section now specifically for that point. (And then one more section with further improvement ideas.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T07:48:21.427", "Id": "532605", "Score": "0", "body": "thanks for the improvement, however this code is missing sorting of the required results and I have just implemented it in the below solution" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T19:42:03.977", "Id": "269831", "ParentId": "269822", "Score": "4" } }, { "body": "<p>This is how I finally formulated the code such that it sorts the results firstly based on course.name and secondly based on course.description.</p>\n<pre><code>let foundCourseListName: CourseItem[] = [];\nlet foundCourseListDesc: CourseItem[] = [];\n const uniqueIds: Set&lt;string&gt; = new Set(); \n const inputWords = this.state.inputWord\n .toLowerCase()\n .split(&quot; &quot;);\n \n this.props.courses.forEach((course: CourseItem) =&gt; {\n course.name.toLowerCase().split(&quot; &quot;)\n .forEach((word: string) =&gt; {\n inputWords.forEach((inputWord: string) =&gt; {\n if (!uniqueIds.has(course.id) &amp;&amp; word.indexOf(inputWord) &gt;= 0) {\n foundCourseListName.push(course);\n uniqueIds.add(course.id);\n };\n });\n });\n if (course.description) {\n course.description.toLowerCase().split(&quot; &quot;)\n .forEach((word: string) =&gt; {\n inputWords.forEach((inputWord: string) =&gt; {\n if (!uniqueIds.has(course.id) &amp;&amp; word.indexOf(inputWord) &gt;= 0) {\n foundCourseListDesc.push(course);\n uniqueIds.add(course.id);\n };\n });\n });\n }\n });\n return foundCourseListName.concat(foundCourseListDesc);\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T15:53:52.467", "Id": "532637", "Score": "0", "body": "If you are looking for a review of additional code it is better to create a follow up question with a link back to the original question." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T07:45:46.133", "Id": "269866", "ParentId": "269822", "Score": "0" } } ]
{ "AcceptedAnswerId": "269831", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T14:52:43.610", "Id": "269822", "Score": "2", "Tags": [ "javascript", "strings", "sorting", "react.js", "typescript" ], "Title": "Function to find substring in a list of strings and add them to the resulting list" }
269822
<p>I came across this BMC Genomics paper: <a href="https://doi.org/10.1186/1471-2164-11-464" rel="nofollow noreferrer">Analysis of intra-genomic GC content homogeneity within prokaryotes</a></p> <p>And I implemented some Python functions to make this available as part of a personal project. The functions are these:</p> <pre><code>import numpy as np from collections import defaultdict def get_sequence_chunks(sequence, window, step, as_overlap=False): &quot;&quot;&quot;GC Content in a DNA/RNA sub-sequence length k. In overlap windows of length k, other wise non overlapping. Inputs: sequence - a string representing a DNA sequence. as_overlap - boolean that represents if overlap is needed. k - a integer representing the lengths of overlapping bases. Default is 20. Outputs: subseq - a string representing a slice of the sequence with or without overlapping characters. &quot;&quot;&quot; # make sequence upper case and getting the length of it sequence, seq_len = sequence.upper(), len(sequence) # non overlap sequence length non_overlap = range(0, seq_len - window + 1, step) # overlap sequence length overlap = range(0, seq_len - window + 1) # overlap is needed if as_overlap: # iterates to the overlap region for i in overlap: # creates the substring subseq = sequence[i:i + window] yield subseq # if non overlap is choosed else: # iterates to the non overlap region for j in non_overlap: # creates the sub-string to count the gc_content subseq = sequence[j:j + window] yield subseq def gc_content(seq, percent=True): &quot;&quot;&quot; Calculate G+C content, return percentage (as float between 0 and 100). Copes mixed case sequences, and with the ambiguous nucleotide S (G or C) when counting the G and C content. The percentage is calculated against the full length. Inputs: sequence - a string representing a sequence (DNA/RNA/Protein) Outputs: gc - a float number or a percent value representing the gc content of the sequence. &quot;&quot;&quot; seq_len = len(seq) gc = sum(seq.count(x) for x in [&quot;G&quot;, &quot;C&quot;, &quot;g&quot;, &quot;c&quot;, &quot;S&quot;, &quot;s&quot;]) if percent: try: return gc * 100.0 / seq_len except ZeroDivisionError: return 0.0 else: return gc / seq_len def get_gc_content_slide_window(sequence, window, step): &quot;&quot;&quot; Calculate teh GC (G+C) content along a sequence. Returns a dictionary -like object mapping the sequence window to the gc value (floats). Returns 0 for windows without any G/C by handling zero division errors, and does NOT look at any ambiguous nucleotides. Inputs: sequence - a string representing a sequence (DNA/RNA/Protein) window_size - a integer representing the length of sequence to be analyzed at each step in the full sequence. step - a integer representing the length of oerlapping sequence allowed. Outputs: gc- a dictionary-like object mapping the window size sequence to it gc values as floating numbers &quot;&quot;&quot; gc = defaultdict(float) for s in get_sequence_chunks(sequence, window, step, as_overlap=False): gc[s] = gc.get(s, 0.0) + gc_content(s) return gc def difference_gc(mean_gc, gc_dict): &quot;&quot;&quot; Calculates the difference between the mean GC content of window i, and the mean chromosomal GC content, as Di = GC i − GC &quot;&quot;&quot; # get the keys and default values in the dictionary d_i = defaultdict(float, [(k, 0.0) for k in gc_dict.keys()]) # iterate through all keys, gc calculated values for the # genome chunk for chunk, gc_cnt in gc_dict.items(): # get the difference between the chromosomal mean and the chunks dif = gc_cnt - mean_gc # add the difference to the appropriate chunk d_i[chunk] = dif return d_i def get_chromosomal_gc_variantion(difference_dic): &quot;&quot;&quot; Calculates the chromosomal GC variation defined as the log-transformed average of the absolute value of the difference between the mean GC content of each non-overlapping sliding window i and mean chromosomal GC content. chromosomal_gc_variantion = log(1/N*sum(|Di|), where N is the maximum number of non-overlapping window size in bp in a sliding windows. &quot;&quot;&quot; # get the number of chunks n = len(difference_dic.keys()) arr = np.array(list(difference_dic.values())) var = np.log((1/n) * sum(abs(arr))) return var </code></pre> <p>I worked with e. coli genome: <a href="https://www.ncbi.nlm.nih.gov/nuccore/NZ_CP050498.1?report=fasta" rel="nofollow noreferrer">Escherichia coli strain RM13322 chromosome, complete genome</a></p> <pre><code>gc = gc_content(ec, percent=True) = 50.76819424506625 </code></pre> <p>It is similar to found here: <a href="https://www.ncbi.nlm.nih.gov/genome/browse#!/prokaryotes/167/" rel="nofollow noreferrer">Genome Assembly and Annotation report (26286)</a> ~ 50.73.</p> <p>The slide window gave it non overlapping results like, where ec = escherichia coli genome, 100 size window, and step = 100:</p> <pre><code>get_gc_content_slide_window(ec, 100, 100) defaultdict(float, {'GTTGGCATGCCATGGTGATGTTTGTTAGGAAAGCAAAGATGGCAAAACTGCTGGGGGTTTTGTGGTTGAGTATGCCAATATAATTAATAGATTAAAGAGT': 39.0, 'TAGTTGTGAAGAAAATATGGATAAACAGGACGACGAATGCTTTCACCGATAAGGACAACTTTCCATAACTCAGTAAATATAGTGCAGAGTTCACCCTGTC': 39.0, 'AAACGGTTTCTTTTGCAGGAAAGGAATATGAGTTAAAGGTCATTGATGAAAAAACGCCTATTCTTTTTCAGTGGTTTGAACCTAATCCTGAACGATATAA': 34.0, 'GAAAGATGAGGTTCCAATAGTTAATACTAAGCAGCATCCCTATTTAGATAATGTCACAAATGCGGCAAGGATAGAGAGTGATCGTATGATAGGTATTTTT': 36.0, 'GTTGATGGCGATTTTTCAGTCAACCAAAAGACTGCTTTTTCAAAATTGGAACGAGATTTTGAAAATGTAATGATAATCTATCGGGAAGATGTTGACTTCA': 34.0, 'GTATGTATGACAGAAAACTATCAGATATTTATCATGATATTATATGTGAACAAAGGTTACGAACTGAAGACAAAAGAGATGAATACTTGTTGAATCTGTT': 29.0,...} </code></pre> <p>The difference function (slide window gc content - gc content all sequence), where ec_gc = gc content of e.coli genome and ec_non = gc content in each subsequence of size 100 non overlapped:</p> <pre><code>difference_gc(ec_gc, ec_non) defaultdict(float, {'GTTGGCATGCCATGGTGATGTTTGTTAGGAAAGCAAAGATGGCAAAACTGCTGGGGGTTTTGTGGTTGAGTATGCCAATATAATTAATAGATTAAAGAGT': -11.768194245066248, 'TAGTTGTGAAGAAAATATGGATAAACAGGACGACGAATGCTTTCACCGATAAGGACAACTTTCCATAACTCAGTAAATATAGTGCAGAGTTCACCCTGTC': -11.768194245066248, 'AAACGGTTTCTTTTGCAGGAAAGGAATATGAGTTAAAGGTCATTGATGAAAAAACGCCTATTCTTTTTCAGTGGTTTGAACCTAATCCTGAACGATATAA': -16.768194245066248, 'GAAAGATGAGGTTCCAATAGTTAATACTAAGCAGCATCCCTATTTAGATAATGTCACAAATGCGGCAAGGATAGAGAGTGATCGTATGATAGGTATTTTT': -14.768194245066248, 'GTTGATGGCGATTTTTCAGTCAACCAAAAGACTGCTTTTTCAAAATTGGAACGAGATTTTGAAAATGTAATGATAATCTATCGGGAAGATGTTGACTTCA': -16.768194245066248,...} </code></pre> <p>And the (ec_dif = difference on gc content from total sequence and from subsequences):</p> <pre><code>get_chromosomal_gc_variantion(ec_dif) 1.7809591767493207 </code></pre> <p>My principal concern It is to know if this function <strong>get_chromosomal_gc_variantion(ec_dif)</strong> was implemented as in the paper above (GCVAR):</p> <p><a href="https://i.stack.imgur.com/ifHcg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ifHcg.png" alt="journal excerpt" /></a></p> <p>As suggested, a toy example:</p> <pre><code>s=&quot;TAGTTGTGAAGAAAATATGGATAAACAGGACGACGAATGCTTTCACCGATAAGGACAACTTTCCATAACTCAGTAAATATAGTGCAGAGTTCACCCTGTC&quot; seq_gc_non_overllap = get_gc_content_slide_window(s, 20, 20) seq_gc_non_overllap defaultdict(float, {'TAGTTGTGAAGAAAATATGG': 30.0, 'ATAAACAGGACGACGAATGC': 45.0, 'TTTCACCGATAAGGACAACT': 40.0, 'TTCCATAACTCAGTAAATAT': 25.0, 'AGTGCAGAGTTCACCCTGTC': 55.0}) seq_gc_total = gc_content(s, percent=True) seq_gc_total 39.0 seq_dif_gctot_gc_slidewindow = difference_gc(seq_gc_total, seq_gc_non_overllap) defaultdict(float, {'TAGTTGTGAAGAAAATATGG': -9.0, 'ATAAACAGGACGACGAATGC': 6.0, 'TTTCACCGATAAGGACAACT': 1.0, 'TTCCATAACTCAGTAAATAT': -14.0, 'AGTGCAGAGTTCACCCTGTC': 16.0}) chromosome_gc_variation = get_chromosomal_gc_variantion(seq_dif_gctot, gc_slidewindow) chromosome_gc_variation 2.2192034840549946 </code></pre> <p>Any tip to improve the code would be very welcome, once I only have been working with python for a couple of years and I am not very skilled, and much less with numpy.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T18:02:40.703", "Id": "532494", "Score": "1", "body": "What are `ec`, `ec_gc`, `ec_non`, `ec_dif`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T19:52:41.343", "Id": "532498", "Score": "1", "body": "It's good for you to have described them, but it would be more helpful to show the code that loads them, and perhaps a reduced-size sample for your reviewers to be able to run your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T20:10:15.690", "Id": "532500", "Score": "0", "body": "@Reinderien thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T20:22:13.907", "Id": "532503", "Score": "1", "body": "@PauloSergioSchlogl Could you also link your project once you've completed/published it?" } ]
[ { "body": "<p>Quite interesting!</p>\n<p>You will benefit from introducing PEP484 type hints.</p>\n<p>Your docstring for <code>get_sequence_chunks</code> is way out of whack; you'll need to revisit your parameter names.</p>\n<p>There isn't a whole lot of benefit from tuple-combination assignment for your <code>sequence</code> and <code>seq_len</code> so I suggest just doing them separately.</p>\n<p>Your overlap logic can be greatly simplified: notice that the only difference between the two code paths is the step size.</p>\n<p>Minor spelling issues such as <code>other wise</code> that should be one word, <code>overllap</code> -&gt; <code>overlap</code>, and <code>variantion</code> -&gt; <code>variation</code>.</p>\n<p>Comments such as</p>\n<pre><code># make sequence upper case and getting the length of it\n</code></pre>\n<p>are less helpful than not having a comment at all. Note the difference between that and</p>\n<pre><code># get the difference between the chromosomal mean and the chunks\n</code></pre>\n<p>which has content that can't necessarily be inferred from the code alone (though even this will be redundant with a sufficiently descriptive variable name).</p>\n<p>This comprehension:</p>\n<pre><code>gc = sum(seq.count(x) for x in [&quot;G&quot;, &quot;C&quot;, &quot;g&quot;, &quot;c&quot;, &quot;S&quot;, &quot;s&quot;])\n</code></pre>\n<p>will iterate through the entire <code>seq</code> string for every potential character. It's likely that refactoring this to use set membership checks and one single iteration through the string will be more efficient.</p>\n<p>This code to prevent division-by-zero:</p>\n<pre><code>seq_len = len(seq) \ngc = sum(seq.count(x) for x in [&quot;G&quot;, &quot;C&quot;, &quot;g&quot;, &quot;c&quot;, &quot;S&quot;, &quot;s&quot;])\nif percent:\n try:\n return gc * 100.0 / seq_len\n except ZeroDivisionError:\n return 0.0 \nelse:\n return gc / seq_len \n</code></pre>\n<p>first of all can trivially avoid logic-by-exception by checking if the sequence length is zero; and also should extend that check to the case where a non-percent figure is returned.</p>\n<p>In <code>difference_gc</code> the initial <code>defaultdict</code> initialization is not needed, since you overwrite every single key. You can replace the whole function with one dictionary comprehension.</p>\n<p>Try to avoid abbreviating words like <code>count</code> to <code>cnt</code>.</p>\n<p>The <code>len</code> of a dict's keys is equal to the <code>len</code> of a dict itself, so you can drop the <code>.keys()</code> in <code>len(difference_dic.keys())</code>.</p>\n<p>You can avoid the construction of a list here:</p>\n<pre><code>arr = np.array(list(difference_dic.values()))\n</code></pre>\n<p>by using <code>fromiter</code> instead.</p>\n<p>Your example is kind of broken. <code>get_chromosomal_gc_variation</code> only accepts one parameter.</p>\n<p>Consider reworking your example into a basic unit test.</p>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>import math\nfrom typing import Iterator, DefaultDict, Dict\n\nimport numpy as np\nfrom collections import defaultdict\n\n\ndef get_sequence_chunks(\n sequence: str,\n window: int,\n step: int,\n as_overlap: bool = False,\n) -&gt; Iterator[str]:\n &quot;&quot;&quot;GC Content in a DNA/RNA sub-sequence length k. In\n overlap windows of length k, other wise non overlapping.\n\n Inputs:\n sequence - a string representing a DNA sequence.\n as_overlap - boolean that represents if overlap is needed.\n k - a integer representing the lengths of overlapping bases.\n Default is 20.\n\n Outputs:\n subseq - a string representing a slice of the sequence with or without\n overlapping characters.\n &quot;&quot;&quot;\n sequence = sequence.upper()\n\n if as_overlap:\n # overlap sequence length\n step = 1\n\n # iterates to the overlap region\n for i in range(0, len(sequence) - window + 1, step):\n # creates the substring\n yield sequence[i:i + window]\n\n\ndef gc_content(seq: str, percent: bool = True) -&gt; float:\n &quot;&quot;&quot;\n Calculate G+C content, return percentage (as float between 0 and 100).\n Copes mixed case sequences, and with the ambiguous nucleotide S (G or C)\n when counting the G and C content. The percentage is calculated against\n the full length.\n\n Inputs:\n sequence - a string representing a sequence (DNA/RNA/Protein)\n\n Outputs:\n gc - a float number or a percent value representing the gc content of the sequence.\n\n &quot;&quot;&quot;\n seq_len = len(seq)\n gc = sum(1 for x in seq.upper() if x in {&quot;G&quot;, &quot;C&quot;, &quot;S&quot;})\n if seq_len == 0:\n return 0\n gc /= seq_len\n if percent:\n return gc * 100\n return gc\n\n\ndef get_gc_content_slide_window(sequence: str, window: int, step: int) -&gt; DefaultDict[str, float]:\n &quot;&quot;&quot;\n Calculate the GC (G+C) content along a sequence. Returns a dictionary-like\n object mapping the sequence window to the gc value (floats).\n Returns 0 for windows without any G/C by handling zero division errors, and\n does NOT look at any ambiguous nucleotides.\n\n Inputs:\n sequence - a string representing a sequence (DNA/RNA/Protein)\n window_size - a integer representing the length of sequence to be analyzed\n at each step in the full sequence.\n step - a integer representing the length of oerlapping sequence allowed.\n\n Outputs:\n gc- a dictionary-like object mapping the window size sequence to it gc values\n as floating numbers\n &quot;&quot;&quot;\n gc = defaultdict(float)\n for s in get_sequence_chunks(sequence, window, step, as_overlap=False):\n gc[s] += gc_content(s)\n return gc\n\n\ndef difference_gc(mean_gc: float, gc_dict: Dict[str, float]) -&gt; Dict[str, float]:\n &quot;&quot;&quot;\n Calculates the difference between the mean GC content of window i, and the\n mean chromosomal GC content, as Di = GC i − GC\n &quot;&quot;&quot;\n # iterate through all keys, gc calculated values for the\n # genome chunk\n # get the difference between the chromosomal mean and the chunks\n # add the difference to the appropriate chunk\n d_i = {\n chunk: gc_cnt - mean_gc\n for chunk, gc_cnt in gc_dict.items()\n }\n return d_i\n\n\ndef get_chromosomal_gc_variation(difference_dic: Dict[str, float]) -&gt; float:\n &quot;&quot;&quot;\n Calculates the chromosomal GC variation defined as the log-transformed average\n of the absolute value of the difference between the mean GC content of each\n non-overlapping sliding window i and mean chromosomal GC content.\n chromosomal_gc_variantion = log(1/N*sum(|Di|), where N is the maximum number of\n non-overlapping window size in bp in a sliding windows.\n &quot;&quot;&quot;\n # get the number of chunks\n n = len(difference_dic)\n arr = np.fromiter(\n difference_dic.values(),\n dtype=np.float32,\n count=len(difference_dic),\n )\n var = np.log(np.sum(np.abs(arr)) / n)\n return var\n\n\ndef test() -&gt; None:\n s = (\n &quot;TAGTTGTGAAGAAAATATGGATAAACAGGACGACGAATGCTTTCACCGAT&quot;\n &quot;AAGGACAACTTTCCATAACTCAGTAAATATAGTGCAGAGTTCACCCTGTC&quot;\n )\n\n seq_gc_non_overlap = get_gc_content_slide_window(s, 20, 20)\n expected = {\n 'TAGTTGTGAAGAAAATATGG': 30,\n 'ATAAACAGGACGACGAATGC': 45,\n 'TTTCACCGATAAGGACAACT': 40,\n 'TTCCATAACTCAGTAAATAT': 25,\n 'AGTGCAGAGTTCACCCTGTC': 55,\n }\n assert expected.keys() == seq_gc_non_overlap.keys()\n for k, v in expected.items():\n assert math.isclose(seq_gc_non_overlap[k], v)\n\n seq_gc_total = gc_content(s, percent=True)\n assert math.isclose(seq_gc_total, 39)\n\n seq_dif_gctot_gc_slidewindow = difference_gc(seq_gc_total, seq_gc_non_overlap)\n expected = {\n 'TAGTTGTGAAGAAAATATGG': -9,\n 'ATAAACAGGACGACGAATGC': 6,\n 'TTTCACCGATAAGGACAACT': 1,\n 'TTCCATAACTCAGTAAATAT': -14,\n 'AGTGCAGAGTTCACCCTGTC': 16,\n }\n assert expected.keys() == seq_dif_gctot_gc_slidewindow.keys()\n for k, v in expected.items():\n assert math.isclose(seq_dif_gctot_gc_slidewindow[k], v)\n\n chromosome_gc_variation = get_chromosomal_gc_variation(seq_dif_gctot_gc_slidewindow)\n assert math.isclose(chromosome_gc_variation, 2.2192034840549946)\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T13:12:04.510", "Id": "532547", "Score": "2", "body": "thank you for your suggestions! I will check it out and sorry because English it is not my native language...some times I do a lot of mistakes. But for me it is much important to check if the statistics function chromosome_gc_variation is doing what it is need to do. But, Is always excellent to learn to write a good/efficient and beautiful code. Thank you for your time and tips. They are awesome. Paulo" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T03:39:48.930", "Id": "269838", "ParentId": "269828", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T17:20:31.717", "Id": "269828", "Score": "4", "Tags": [ "python", "python-3.x", "numpy", "statistics", "bioinformatics" ], "Title": "Function to calculate the GC content variation in a sequence" }
269828
<p>My requirement is implementing a <code>Queue&lt;T&gt;</code> (where <code>T</code> is a <code>Lexeme</code>) that is capable of insertion sort and insertion merge.</p> <p>The <code>Lexeme</code> interface:</p> <pre class="lang-kotlin prettyprint-override"><code>/** * A lexeme is the smallest piece of data it is possible to * extract during the lexing process. * For example, a lexeme could be a keyword, a comment, or an identifier. * * @author Edoardo Luppi */ interface Lexeme : Segment { /** The IntelliJ Platform type for this lexeme. */ fun getPlatformType(): IElementType /** The start offset for this lexeme inside the characters buffer. */ override fun getStartOffset(): Int /** The end offset for this lexeme inside the characters buffer. */ override fun getEndOffset(): Int /** Returns if this lexeme fully contains the inputted lexeme or not. */ fun contains(lexeme: Lexeme): Boolean /** Returns if this lexeme intersects with the inputted lexeme or not. */ fun intersects(lexeme: Lexeme): Boolean /** * Creates a copy of this lexeme, shifted right (using a positive number) * or left (using a negative number) by the given positions. */ fun shift(positions: Int): Lexeme /** Creates a copy of this lexeme with different offsets. */ fun copy(startOffset: Int, endOffset: Int): Lexeme } </code></pre> <p><strong>What do I mean by insertion merge?</strong></p> <p>During the lexing process of a document, the document is lexed with multiple passes, and each pass detects some types of tokens. A pass' token may overlap with the preceding one on the same offsets, in which case the latest token always wins.</p> <p><a href="https://i.stack.imgur.com/KItHT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KItHT.png" alt="enter image description here" /></a></p> <p>In the end I came up with something pretty straightforward using an <code>ArrayList</code> as base implementation.<br /> The following is the important part:</p> <pre class="lang-kotlin prettyprint-override"><code>/** * A queue implementation that sort lexemes on insertion and that * is capable of merging new ones with old ones in case they overlap. * * @author Edoardo Luppi */ class SortedArrayLexemeQueue(initialCapacity: Int = 32) : ArrayList&lt;Lexeme&gt;(initialCapacity), Queue&lt;Lexeme&gt; { override fun add(element: Lexeme): Boolean { if (isEmpty()) { return super.add(element) } val index = findIndex(element) if (index &lt; 0) { // The new element does not overlap with other elements, // thus we can use the index returned by 'findIndex' // to insert it on the right spot and keep the queue sorted super.add(-index - 1, element) return true } val iterator = listIterator(index) while (iterator.hasNext()) { val lexeme = iterator.next() if (!element.intersects(lexeme)) { continue } iterator.remove() if (element.contains(lexeme) &amp;&amp; iterator.hasNext()) { // The new element fully override the old one, so we simply remove it continue } if (lexeme.startOffset &lt; element.startOffset) { iterator.add(lexeme.copy(lexeme.startOffset, element.startOffset)) } iterator.add(element) if (lexeme.endOffset &gt; element.endOffset) { iterator.add(lexeme.copy(element.endOffset, lexeme.endOffset)) } } return true } /** * Returns the index where we should start processing overlaps for this element. * Otherwise, if the element does not overlap with existing ones, returns * the inverted insertion point (-insertion point - 1), defined as the index * at which the element should be inserted so that the list remains sorted. */ private fun findIndex(element: Lexeme): Int { var sortedPosition = size for ((index, lexeme) in withIndex()) { if (element.intersects(lexeme)) { return index } if (lexeme.startOffset &gt; element.startOffset) { sortedPosition = index break } } return -sortedPosition - 1 } ... </code></pre> <p>The expected queue size is around 10-60 elements, as it gets consumed often.<br /> Because of the merge feature, I could not use the standard <code>PriorityQueue</code>.</p> <p>My question is, can I do this better (considering I have a small amount of time)? If so, how?<br /> Do you spot any possible issue?</p>
[]
[ { "body": "<p>A couple improvements I've made, plus I bug I didn't notice.</p>\n<p>To ease lexeme's offsets retrieval, we provide destructuring capability:</p>\n<pre class=\"lang-kotlin prettyprint-override\"><code>interface Lexeme {\n ...\n\n // Provide destructuring capability\n operator fun component1(): Int = getStartOffset()\n operator fun component2(): Int = getEndOffset()\n}\n</code></pre>\n<p>We can optimize the insertion when the inserted lexeme's start offset is greater or equal to the last lexeme's end offset, as it means there are no overlaps and it's already sorted:</p>\n<pre class=\"lang-kotlin prettyprint-override\"><code>override fun add(element: Lexeme): Boolean {\n val (elementStart, elementEnd) = element\n\n if (isEmpty() || elementStart &gt;= last().getEndOffset()) {\n return super.add(element)\n }\n\n ...\n</code></pre>\n<p>And finally, inside the <code>ListIterator&lt;Lexeme&gt;</code> loop, we need to check if the new element has already been added, as we don't want it to be added each iteration (see the <code>elementAdded</code> boolean variable):</p>\n<pre class=\"lang-kotlin prettyprint-override\"><code>val iterator = listIterator(index)\nvar elementAdded = false\n\nwhile (iterator.hasNext()) {\n val lexeme = iterator.next()\n\n if (!element.intersects(lexeme)) {\n continue\n }\n\n iterator.remove()\n\n if (element.contains(lexeme) &amp;&amp; iterator.hasNext()) {\n // The new element fully override the old one, so we simply remove it\n continue\n }\n\n val (lexemeStart, lexemeEnd) = lexeme\n\n if (lexemeStart &lt; elementStart) {\n iterator.add(lexeme.copy(lexemeStart, elementStart))\n }\n\n if (!elementAdded) {\n iterator.add(element)\n elementAdded = true\n }\n\n if (lexemeEnd &gt; elementEnd) {\n iterator.add(lexeme.copy(elementEnd, lexemeEnd))\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T15:49:30.473", "Id": "532563", "Score": "0", "body": "Since no one else has answer the question yet, you can actually edit the original question and make improvements." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T21:36:00.703", "Id": "269832", "ParentId": "269829", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T18:00:57.813", "Id": "269829", "Score": "2", "Tags": [ "java", "queue", "kotlin" ], "Title": "Merging and sorting queue/list implementation" }
269829
<p>As part of an assignment, I need to write a program which loads a colored image to the screen, converts it to HSI and displays each component in separate grayscale image.</p> <p>My program:</p> <pre><code>#!/usr/bin/env python3 import cv2 import numpy as np import math from PIL import Image from io import BytesIO from matplotlib import pyplot as plt IMAGE_LOCATION = &quot;lena.png&quot; class RGB2HSI_Coverter: def __init__(self, img): self.img = img # Method calculates the intensity # I = (R + G + B) / 3 @staticmethod def calc_intensity(split): (R, G, B) = split return np.divide(R + G + B, 3) # Method calculates the saturation # S = 1 - (3 * min[R,G,B]) / (R + G + B) @staticmethod def calc_saturation(split): (R, G, B) = split min_value = np.minimum(np.minimum(R, G), B) return 1 - np.divide(3 * min_value, (R + G + B)) # Method calculates the hue # H = theta if B &lt;= G, otherwise 360 - theta # Where theta = arccos(( 0.5 * [(R - G) + (R - B)] ) / ([(R - G)^2 + (R - B)(G - B)]^0.5)) @staticmethod def calc_hue(split): (R, G, B) = split result_hue = np.copy(R) for i in range(0, B.shape[0]): for j in range(0, B.shape[1]): # Calculate numerator = ( 0.5 * [(R - G) + (R - B)] ) numerator = 0.5 * ((R[i][j] - G[i][j]) + (R[i][j] - B[i][j])) # Calculate denominator = ([(R - G)^2 + (R - B)(G - B)]^0.5) denominator = math.sqrt((R[i][j] - G[i][j])**2 + ((R[i][j] - B[i][j]) * (G[i][j] - B[i][j]))) # Calculate divistion = numerator / denominator divistion = np.divide(numerator, denominator) # Calculate theta = arccos(divistion) result_hue[i][j] = math.acos(divistion) # If B &gt; G then H = 360 - theta if B[i][j] &gt; G[i][j]: result_hue[i][j] = ((360 * math.pi) / 180.0) - result_hue[i][j] return result_hue def convert_R2G_to_HSI(self): with np.errstate(divide='ignore', invalid='ignore'): # Split into channels block = np.float32(self.img) / 255 split = (block[:,:,2], block[:,:,1], block[:,:,0]) # Calculate saturation saturation = self.calc_saturation(split) # Calculate intensity intensity = self.calc_intensity(split) # Calculate hue hue = self.calc_hue(split) # Merge channels into one image hsi_img = cv2.merge((hue, saturation, intensity)) return hsi_img def main(): # Load RGB image img = Image.open(IMAGE_LOCATION).convert(&quot;RGB&quot;) # Display RGB image plt.imshow(img) plt.show() # Convert RGB image to HSI converter = RGB2HSI_Coverter(img) hsi = converter.convert_R2G_to_HSI() # Display HSI image plt.imshow(hsi) plt.show() if __name__ == &quot;__main__&quot;: main() </code></pre> <p>The methods that are shown in my textbook and that I need to use to convert to HSI are:</p> <p><a href="https://i.stack.imgur.com/Fxnwx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Fxnwx.png" alt="enter image description here" /></a></p> <p>What do you think about my code? I'm more interested if my code does what expected to be done and if I handled all of the cases (less interested in code design, but still will be nice). Just looking for additional pair of eyes, to check the correctness of my code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T18:41:33.783", "Id": "532496", "Score": "0", "body": "Seems right, except that you compute H in radian instead of degrees. Usually degrees are used so that it can be stuck in an integer array. Also, you can use array operations to compute H, which will be a lot faster. Finally, you should reuse the I result to compute S, no need to repeat the same computations twice. (*Edit: Sorry, didn’t realize I was on Code Review, I shouldn’t have posted this as a comment. I don’t have time to write a full answer right now.*)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T20:27:17.133", "Id": "532504", "Score": "0", "body": "@CrisLuengo Using degrees rather than radians just because they can be represented as integers assumes that you don't care about the (big) hit to resolution. This assumption may or may not hold." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T22:08:17.167", "Id": "532518", "Score": "0", "body": "@Reinderien I didn’t say OP should round. I said that the common definition uses degrees, and I explained why this is the common definition. OpenCV even divides the degrees by two so that they fit in an 8-bit integer. It’s awful, but it’s also surprisingly hard to convince people that an image doesn’t need to be represented by 8-bit integers. I much prefer using single floats, but I’m in a minority." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T16:49:36.320", "Id": "532575", "Score": "0", "body": "Why did you put everything in the class `RGB2HSI_Coverter`? I don't think that class needs to exist. IMO, it would be cleaner if it was living directly in the module. Then `calc_hue` and the others would be pure functions, taking the image as an input." } ]
[ { "body": "<p>It would help future users to either add a hint comment that <code>cv2</code> comes from the pip package <code>opencv-contrib-python-headless</code>, or better yet write an appropriate <code>requirements.txt</code>.</p>\n<p><a href=\"https://www.thedrum.com/creative-works/project/clemenger-bbdo-losing-lena\" rel=\"nofollow noreferrer\">We need to lose Lena</a>. Particularly when there are so many other <a href=\"https://www.gannett-cdn.com/-mm-/6830b11dd7334714ee859c4104be6bcc69f3abec/c=0-323-2833-1924/local/-/media/2017/03/21/USATODAY/USATODAY/636257089475691215-USP-ENTERTAINMENT-WEIRD-AL-YANKOVIC-82386343.JPG?width=2833&amp;height=1601&amp;fit=crop&amp;format=pjpg&amp;auto=webp\" rel=\"nofollow noreferrer\">excellent test pictures around</a>.</p>\n<p>Your class structure is a little odd, betrayed partly by there being so many static methods. You can store an intermediate <code>rgb</code> array during construction, and then just list off a bunch of <code>@property</code>s, one per channel conversion you're interested in. This will convert all of your statics.</p>\n<p>In many cases, it's not actually useful to split your RGB array to three channels. Many of your expressions are not properly vectorised, and after vectorisation, the entire array can be operated on. Your hue calculation is especially amenable to vectorisation improvements, since both of the loops should go away, there should be no <code>copy</code>, and no calls to <code>math</code>.</p>\n<p><code>divistion</code> isn't a word; did you mean &quot;division&quot; or &quot;quotient&quot;?</p>\n<p>Do not call <code>show()</code> twice. The nicer display is to show the original and converted images side-by-side.</p>\n<p>Importantly,</p>\n<blockquote>\n<p>displays each component in separate grayscale image</p>\n</blockquote>\n<p>is not what your code does. Your code was interpreting the HSI space as RGB space on display. The suggested code below technically does not use grayscale, as the default viridis colour scale is better for most purposes, including IMO this one.</p>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python3\nimport numpy as np\nfrom PIL import Image\nfrom cv2.cv2 import merge # pip: opencv-contrib-python-headless\nfrom matplotlib import pyplot as plt\nimport matplotlib.image\n\n# https://www.gannett-cdn.com/-mm-/6830b11dd7334714ee859c4104be6bcc69f3abec/c=0-323-2833-1924/local/-/media/2017/03/21/USATODAY/USATODAY/636257089475691215-USP-ENTERTAINMENT-WEIRD-AL-YANKOVIC-82386343.JPG?width=2833&amp;height=1601&amp;fit=crop&amp;format=pjpg&amp;auto=webp\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom mpl_toolkits.axes_grid1.axes_divider import AxesDivider\n\nIMAGE_LOCATION = &quot;weirdal.webp&quot;\n\n\nclass RGB2HSI_Converter:\n def __init__(self, image: Image) -&gt; None:\n self.image = image\n\n # To a three-dimensional ndarray with values 0-1\n block = np.float32(self.image) / 255\n\n # From BGR to RGB, last axis to first\n self.rgb = np.moveaxis(block[:, :, ::-1], source=2, destination=0)\n\n @property\n def intensity(self) -&gt; np.ndarray:\n # I = (R + G + B) / 3\n return np.sum(self.rgb, axis=0) / 3\n\n @property\n def saturation(self) -&gt; np.ndarray:\n # S = 1 - (3 * min[R,G,B]) / (R + G + B)\n min_values = np.min(self.rgb, axis=0)\n sum_values = np.sum(self.rgb, axis=0)\n return 1 - 3 * min_values / sum_values\n\n @property\n def hue(self) -&gt; np.ndarray:\n &quot;&quot;&quot;\n H = theta if B &lt;= G, otherwise 360 - theta\n Where theta = arccos(( 0.5 * [(R - G) + (R - B)] ) / ([(R - G)^2 + (R - B)(G - B)]^0.5))\n &quot;&quot;&quot;\n R, G, B = self.rgb\n\n # Calculate numerator = ( 0.5 * [(R - G) + (R - B)] )\n numerator = 0.5 * (2*R - G - B)\n # Calculate denominator = ([(R - G)^2 + (R - B)(G - B)]^0.5)\n denominator = np.sqrt((R - G)**2 + (R - B)*(G - B))\n\n # Calculate theta = arccos(division)\n result_hue = np.arccos(numerator / denominator)\n\n # If B &gt; G then H = 360 - theta\n np.putmask(result_hue, B &gt; G, 2*np.pi - result_hue)\n\n return result_hue\n\n @property\n def hsi(self) -&gt; Image:\n with np.errstate(divide='ignore', invalid='ignore'):\n return merge((self.hue, self.saturation, self.intensity))\n\n\ndef imshow_with_bar(fig: plt.Figure, ax: plt.Axes, data: np.ndarray) -&gt; None:\n divider: AxesDivider = make_axes_locatable(ax)\n cax: plt.Axes = divider.append_axes(position='right', size='5%', pad=0.05)\n image: matplotlib.image.AxesImage = ax.imshow(data)\n fig.colorbar(mappable=image, cax=cax, orientation='vertical')\n\n\ndef main():\n img = Image.open(IMAGE_LOCATION).convert(&quot;RGB&quot;)\n converter = RGB2HSI_Converter(img)\n\n fig, (\n (top_left, top_right),\n (bottom_left, bottom_right),\n ) = plt.subplots(nrows=2, ncols=2)\n\n top_right.set_title('Hue')\n imshow_with_bar(fig, top_right, converter.hue)\n\n bottom_left.set_title('Saturation')\n imshow_with_bar(fig, bottom_left, converter.saturation)\n\n bottom_right.set_title('Intensity')\n imshow_with_bar(fig, bottom_right, converter.intensity)\n\n top_left.set_title('Original (RGB)')\n top_left.imshow(img)\n\n plt.show()\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/jXGGi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jXGGi.png\" alt=\"images by channel\" /></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T15:10:05.040", "Id": "532560", "Score": "0", "body": "Thank you! Part of my assignment, I was asked to use `grayscale`. Since I didn't use it myself, could you please explain how should it be added to your suggested code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T16:39:54.750", "Id": "532572", "Score": "0", "body": "@vesii Use [Greys](https://matplotlib.org/stable/tutorials/colors/colormaps.html)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T21:26:06.737", "Id": "532586", "Score": "0", "body": "Does it mean I need to just use `.convert('L')`?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T22:51:04.793", "Id": "269834", "ParentId": "269830", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T18:29:23.217", "Id": "269830", "Score": "2", "Tags": [ "python", "image" ], "Title": "Program which loads a colored image to the screen, converts it to HSI and displays each component in separate grayscale image" }
269830
<p>The most famous library for Support Vector Machine (SVM) algorithm is libsvm (<a href="https://github.com/cjlin1/libsvm/" rel="nofollow noreferrer">https://github.com/cjlin1/libsvm/</a>), but I felt that its code style is too old, I rewrote in newer C++ as a hobby project.</p> <p>Link : <a href="https://github.com/frozenca/ML_practice/tree/main/ML/SVM" rel="nofollow noreferrer">https://github.com/frozenca/ML_practice/tree/main/ML/SVM</a></p> <p>SVMData.h</p> <pre><code>#ifndef FROZENCA_SVMDATA_H #define FROZENCA_SVMDATA_H #include &lt;array&gt; #include &lt;charconv&gt; #include &lt;ranges&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;string_view&gt; #include &lt;variant&gt; #include &lt;vector&gt; namespace frozenca { using Samples = std::vector&lt;std::vector&lt;float&gt;&gt;; using SubSamples = std::vector&lt;std::reference_wrapper&lt;const std::vector&lt;float&gt;&gt;&gt;; class SVMTrainData { private: std::variant&lt;Samples, SubSamples&gt; X_; public: std::vector&lt;float&gt; y_; std::size_t n_; std::size_t C_; std::vector&lt;std::pair&lt;float, float&gt;&gt; feature_bounds_; friend class SVMModel; // full data construct explicit SVMTrainData(std::istream&amp; is) { std::vector&lt;std::vector&lt;float&gt;&gt; X; is.seekg(0, std::ios::end); std::streamsize len = is.tellg(); is.seekg(0, std::ios::beg); constexpr std::size_t buf_len = 1024; std::array&lt;char, buf_len&gt; buffer = {0}; float target = 0.0f; std::vector&lt;float&gt; row; std::size_t col_index = 0; while (is.getline(&amp;buffer[0], buf_len)) { auto curr = buffer.begin(); auto end = buffer.end(); while (curr != end) { float result = 0; auto delim = std::find_if(curr, end, [](int ch) { return ch == ',' || ch == '\n' || ch == '\0'; }); std::string_view sv(curr, delim); std::from_chars(sv.begin(), sv.end(), result); if (!col_index) { y_.push_back(result); } else { row.push_back(result); } curr = delim + 1; ++col_index; if (*delim == '\n') { C_ = row.size(); X.push_back(std::move(row)); row = {}; col_index = 0; target = 0.0f; } } } assert(!X.empty()); n_ = y_.size(); if (n_ != X.size() || std::ranges::any_of(X, [&amp;](const auto&amp; row) { return row.size() != C_; })) { throw std::invalid_argument(&quot;Number of features of sample does not match&quot;); } X_ = std::move(X); scale(); } SVMTrainData(Samples X, std::vector&lt;float&gt; y) : X_(std::move(X)), y_(std::move(y)), n_(y_.size()), C_(std::get&lt;Samples&gt;(X_)[0].size()) { scale(); } // constructor for subsamples SVMTrainData(SubSamples X, std::vector&lt;float&gt; y, std::vector&lt;std::pair&lt;float, float&gt;&gt; feature_bounds) : X_(std::move(X)), y_(std::move(y)), n_(y_.size()), C_(std::get&lt;SubSamples&gt;(X_)[0].get().size()), feature_bounds_(std::move(feature_bounds)) {} [[nodiscard]] Samples getX() const { if (std::holds_alternative&lt;Samples&gt;(X_)) { return std::get&lt;Samples&gt;(X_); } else { throw std::runtime_error(&quot;getX() called for subsample set&quot;); } } [[nodiscard]] SubSamples getXRef() const { if (std::holds_alternative&lt;SubSamples&gt;(X_)) { return std::get&lt;SubSamples&gt;(X_); } else { throw std::runtime_error(&quot;getXRef() called for full sample set&quot;); } } [[nodiscard]] std::vector&lt;float&gt; getX(std::size_t row_index) const { if (std::holds_alternative&lt;Samples&gt;(X_)) { return std::get&lt;Samples&gt;(X_)[row_index]; } else { return std::get&lt;SubSamples&gt;(X_)[row_index].get(); } } [[nodiscard]] std::reference_wrapper&lt;const std::vector&lt;float&gt;&gt; getXRef(std::size_t row_index) const { if (std::holds_alternative&lt;Samples&gt;(X_)) { return std::ref(std::get&lt;Samples&gt;(X_)[row_index]); } else { return std::get&lt;SubSamples&gt;(X_)[row_index]; } } private: void scale() { if (std::holds_alternative&lt;SubSamples&gt;(X_)) { return; } feature_bounds_ = std::vector&lt;std::pair&lt;float, float&gt;&gt;(C_, {std::numeric_limits&lt;float&gt;::max(), std::numeric_limits&lt;float&gt;::lowest()}); auto&amp; X = std::get&lt;Samples&gt;(X_); for (std::size_t i = 0; i &lt; n_; ++i) { for (std::size_t c = 0; c &lt; C_; ++c) { feature_bounds_[c].first = std::min(feature_bounds_[c].first, X[i][c]); feature_bounds_[c].second = std::max(feature_bounds_[c].second, X[i][c]); } } for (std::size_t c = 0; c &lt; C_; ++c) { auto [fmin, fmax] = feature_bounds_[c]; for (std::size_t i = 0; i &lt; n_; ++i) { X[i][c] = 1.0f - 2.0f * (fmax - X[i][c])/(fmax - fmin); } } } }; } // namespace frozenca #endif //FROZENCA_SVMDATA_H </code></pre> <p>SVMKernel.h</p> <pre><code>#ifndef FROZENCA_SVMKERNEL_H #define FROZENCA_SVMKERNEL_H #include &lt;algorithm&gt; #include &lt;cmath&gt; #include &lt;cstddef&gt; #include &lt;functional&gt; #include &lt;ranges&gt; #include &lt;vector&gt; namespace frozenca { static float dot(const std::vector&lt;float&gt;&amp; x, const std::vector&lt;float&gt;&amp; y) { return std::inner_product(x.begin(), x.end(), y.begin(), 0.0f); } class Kernel { public: virtual ~Kernel() = default; [[nodiscard]] virtual float operator()(const std::vector&lt;float&gt;&amp; x, const std::vector&lt;float&gt;&amp; y) const = 0; virtual void adjustParams(std::size_t f) = 0; }; class KernelLinear final : public Kernel { public: [[nodiscard]] float operator()(const std::vector&lt;float&gt;&amp; x, const std::vector&lt;float&gt;&amp; y) const { return dot(x, y); } void adjustParams(std::size_t f) final { // do nothing } }; class KernelPoly final : public Kernel { private: float gamma_ = 0.0f; float coef0_ = 0.0f; std::size_t degree_ = 3; public: [[nodiscard]] float operator()(const std::vector&lt;float&gt;&amp; x, const std::vector&lt;float&gt;&amp; y) const{ return std::pow(gamma_ * dot(x, y) + coef0_, degree_); } void adjustParams(std::size_t f) { gamma_ = 1.0f / f; } }; class KernelRBF final : public Kernel { private: float gamma_ = 0.0f; public: [[nodiscard]] float operator()(const std::vector&lt;float&gt;&amp; x, const std::vector&lt;float&gt;&amp; y) const final { std::vector&lt;float&gt; diff = x; std::ranges::transform(diff, y, diff.begin(), std::minus{}); return std::exp(-gamma_ * dot(diff, diff)); } void adjustParams(std::size_t f) final { gamma_ = 1.0f / f; } }; class KernelSigmoid final : public Kernel { private: float gamma_ = 0.0f; float coef0_ = 0.0f; public: [[nodiscard]] float operator()(const std::vector&lt;float&gt;&amp; x, const std::vector&lt;float&gt;&amp; y) const final { return std::tanh(gamma_ * dot(x, y) + coef0_); } void adjustParams(std::size_t f) final { gamma_ = 1.0f / f; } }; } // namespace frozenca #endif //FROZENCA_SVMKERNEL_H </code></pre> <p>SVMModel.h</p> <pre><code>#ifndef FROZENCA_SVMMODEL_H #define FROZENCA_SVMMODEL_H #include &quot;SVMData.h&quot; #include &quot;SVMKernel.h&quot; #include &lt;algorithm&gt; #include &lt;functional&gt; #include &lt;memory&gt; #include &lt;random&gt; #include &lt;unordered_set&gt; #include &lt;unordered_map&gt; #include &lt;utility&gt; #include &lt;vector&gt; namespace frozenca { struct SVMParams { float C = 1.0f; float nu = 0.5f; float p = 0.1f; std::vector&lt;float&gt; weight_scale; bool shrinking = true; // use the shrinking heuristics float eps = 1e-3; bool compute_probability = false; }; class SVMModel { protected: // actual model parameters // support vectors for each class (size : k) std::unordered_map&lt;std::size_t, std::vector&lt;std::vector&lt;float&gt;&gt;&gt; SV_; // coefficients for SVs in decision functions. classifier between class (i, j) =&gt; SV_coeff_[i * k + j] std::unordered_map&lt;std::size_t, std::vector&lt;float&gt;&gt; SV_coeff_; // constants in decision functions (size: k * (k - 1) / 2) std::vector&lt;float&gt; rho_; std::vector&lt;std::pair&lt;float, float&gt;&gt; feature_bounds_; std::vector&lt;float&gt; prob_A_; std::vector&lt;float&gt; prob_B_; public: std::unique_ptr&lt;Kernel&gt; kernel_ = nullptr; friend class SVMTwoClass; SVMModel(std::unique_ptr&lt;Kernel&gt; kernel) : kernel_(std::move(kernel)) {} virtual ~SVMModel() = default; virtual void fit(const SVMTrainData&amp; svm_data, const SVMParams&amp; params); virtual std::vector&lt;float&gt; crossValidate(const SVMTrainData&amp; svm_data, const SVMParams&amp; params, std::size_t count_fold) final; virtual std::vector&lt;float&gt; scaleInputs(const std::vector&lt;float&gt;&amp; sample) const final; [[nodiscard]] virtual float predict(const std::vector&lt;float&gt;&amp; sample) const = 0; [[nodiscard]] virtual std::vector&lt;float&gt; predict(const std::vector&lt;std::vector&lt;float&gt;&gt;&amp; samples) const final { std::vector&lt;float&gt; results; for (const auto&amp; sample: samples) { results.push_back(predict(sample)); } return results; } }; void SVMModel::fit(const SVMTrainData&amp; svm_data, const SVMParams&amp; params) { feature_bounds_ = svm_data.feature_bounds_; kernel_-&gt;adjustParams(svm_data.C_); } std::vector&lt;float&gt; SVMModel::scaleInputs(const std::vector&lt;float&gt;&amp; sample) const { auto sample_scaled = sample; for (std::size_t c = 0; c &lt; feature_bounds_.size(); ++c) { auto [fmin, fmax] = feature_bounds_[c]; sample_scaled[c] = 1.0f - 2.0f * (fmax - sample[c])/(fmax - fmin); } return sample_scaled; } std::vector&lt;float&gt; SVMModel::crossValidate(const SVMTrainData&amp; svm_data, const SVMParams&amp; params, std::size_t count_fold) { const std::size_t l = svm_data.n_; if (count_fold &gt; l) { count_fold = l; std::cerr &lt;&lt; &quot;WARNING: #folds &gt; #data. Will use #folds = #data (LOOCV)\n&quot;; } std::vector&lt;std::size_t&gt; fold_indices(l); for (std::size_t f = 0; f &lt; count_fold; ++f) { for (std::size_t i = f * l / count_fold; i &lt; (f + 1) * l / count_fold; ++i) { fold_indices[i] = f; } } std::mt19937 gen(std::random_device{}()); std::ranges::shuffle(fold_indices, gen); std::unordered_map&lt;std::size_t, std::unordered_set&lt;std::size_t&gt;&gt; fold_sets; for (std::size_t i = 0; i &lt; l; ++i) { fold_sets[fold_indices[i]].insert(i); } std::vector&lt;float&gt; target(l); for (std::size_t f = 0; f &lt; count_fold; ++f) { // leave f-th fold out SubSamples X_without_f; std::vector&lt;float&gt; y_without_f; for (std::size_t fd = 0; fd &lt; count_fold; ++fd) { if (fd == f) { continue; } auto&amp; fold_fd = fold_sets[fd]; for (auto fd_sample : fold_fd) { X_without_f.push_back(svm_data.getXRef(fd_sample)); y_without_f.push_back(svm_data.y_[fd_sample]); } } SVMTrainData CV_data_ffold (X_without_f, y_without_f, svm_data.feature_bounds_); fit(CV_data_ffold, params); auto&amp; fold_f = fold_sets[f]; for (auto f_sample : fold_f) { target[f_sample] = predict(svm_data.getX(f_sample)); } } return target; } } // namespace frozenca #endif //FROZENCA_SVMMODEL_H </code></pre> <p>SVMSolver.h</p> <pre><code>#ifndef FROZENCA_SVMSOLVER_H #define FROZENCA_SVMSOLVER_H #include &quot;../../Matrix/Matrix.h&quot; #include &lt;cstddef&gt; #include &lt;tuple&gt; #include &lt;unordered_set&gt; #include &lt;utility&gt; #include &lt;vector&gt; namespace frozenca { static constexpr float TAU = 1e-12; struct Solution { std::vector&lt;float&gt; alpha; float obj = 0.0f; float rho = 0.0f; float r = 0.0f; // for Solver_NU std::pair&lt;float, float&gt; upper_bound = {0.0f, 0.0f}; }; class Solver { public: enum class Alpha { Lower, Upper, Free }; Solver(std::size_t l, Mat&lt;float&gt;&amp; Q, std::vector&lt;float&gt; QD, std::vector&lt;float&gt; p, std::vector&lt;char&gt; y, std::vector&lt;float&gt; alpha, std::pair&lt;float, float&gt; C, float eps, bool shrinking); virtual ~Solver() = default; protected: const std::size_t l_; Mat&lt;float&gt;&amp; Q_; std::vector&lt;float&gt; QD_; std::vector&lt;float&gt; p_; std::vector&lt;char&gt; y_; std::vector&lt;float&gt; alpha_; std::pair&lt;float, float&gt; C_; float eps_; std::vector&lt;Alpha&gt; alpha_status_; std::vector&lt;float&gt; G_; // gradient of objective function std::vector&lt;float&gt; G_bar_; // gradient, if we treat free variable as 0 bool shrinking_; bool unshrink_ = false; std::unordered_set&lt;std::size_t&gt; active_set_; public: [[nodiscard]] float getC(std::size_t i) const { return (y_[i] &gt; 0) ? C_.first : C_.second; } [[nodiscard]] std::vector&lt;float&gt; getQ(std::size_t i) const { auto Q_i = Q_.col(i); std::vector&lt;float&gt; Qi; for (auto q : Q_i) { Qi.push_back(q); } return Qi; } void updateAlphaStatus(std::size_t i) { if (alpha_[i] &gt;= getC(i)) { alpha_status_[i] = Alpha::Upper; } else if (alpha_[i] &lt;= 0) { alpha_status_[i] = Alpha::Lower; } else { alpha_status_[i] = Alpha::Free; } } public: virtual Solution Solve() final; virtual void updateAlphaGradientValues(std::size_t i, std::size_t j) final; virtual void reconstructGradient() final; protected: virtual std::tuple&lt;bool, std::size_t, std::size_t&gt; selectWorkingSet() const = 0; virtual void calculateRho(Solution&amp; sol) const = 0; virtual void doShrinking() = 0; }; Solver::Solver(std::size_t l, Mat&lt;float&gt;&amp; Q, std::vector&lt;float&gt; QD, std::vector&lt;float&gt; p, std::vector&lt;char&gt; y, std::vector&lt;float&gt; alpha, std::pair&lt;float, float&gt; C, float eps, bool shrinking) : l_{l}, Q_(Q), QD_(std::move(QD)), p_(std::move(p)), y_(std::move(y)), alpha_(std::move(alpha)), C_(std::move(C)), eps_{eps}, shrinking_{shrinking} { alpha_status_.resize(l_); for (std::size_t i = 0; i &lt; l_; ++i) { active_set_.insert(i); updateAlphaStatus(i); } G_ = p_; G_bar_.resize(l_); for (std::size_t i = 0; i &lt; l_; ++i) { if (alpha_status_[i] != Alpha::Lower) { auto Q_i = getQ(i); for (std::size_t j = 0; j &lt; l_; ++j) { G_[j] += alpha_[i] * Q_i[j]; } if (alpha_status_[i] == Alpha::Upper) { for (std::size_t j = 0; j &lt; l_; ++j) { G_bar_[j] += getC(i) * Q_i[j]; } } } } } // Solver ordinary (non NU) class SolverOrdinary final : public Solver { public: SolverOrdinary(std::size_t l, Mat&lt;float&gt;&amp; Q, std::vector&lt;float&gt; QD, std::vector&lt;float&gt; p, std::vector&lt;char&gt; y, std::vector&lt;float&gt; alpha, std::pair&lt;float, float&gt; C, float eps, bool shrinking) : Solver(l, Q, QD, p, y, alpha, C, eps, shrinking) {} std::tuple&lt;bool, std::size_t, std::size_t&gt; selectWorkingSet() const; void calculateRho(Solution&amp; sol) const; void doShrinking() final; bool beShrunk(std::size_t i, float g_max1, float g_max2) const; }; Solution Solver::Solve() { std::size_t iter = 0; std::size_t max_iter = std::max(1'000'000lu, l_ &gt; std::numeric_limits&lt;std::size_t&gt;::max() / 100 ? std::numeric_limits&lt;std::size_t&gt;::max() : 100 * l_); std::size_t counter = std::min(l_, 1'000lu) + 1; while (iter &lt; max_iter) { if (!--counter) { counter = std::min(l_, 1'000lu); if (shrinking_) { doShrinking(); } } bool already_opt = false; std::size_t i = 0, j = 0; std::tie(already_opt, i, j) = selectWorkingSet(); if (already_opt) { // reconstruct the whole gradient reconstructGradient(); std::tie(already_opt, i, j) = selectWorkingSet(); if (already_opt) { break; } else { counter = 1; // do shrinking in next iteration } } ++iter; updateAlphaGradientValues(i, j); } if (iter &gt;= max_iter) { if (active_set_.size() &lt; l_) { reconstructGradient(); } std::cerr &lt;&lt; &quot;WARNING: reaching max number of iterations\n&quot;; } Solution s; calculateRho(s); for (std::size_t i = 0; i &lt; l_; ++i) { s.obj += alpha_[i] * (G_[i] + p_[i]); } s.obj /= 2.0f; s.alpha = alpha_; s.upper_bound = C_; std::cout &lt;&lt; &quot;Optimization finished, #iter = &quot; &lt;&lt; iter &lt;&lt; '\n'; return s; } void Solver::updateAlphaGradientValues(std::size_t i, std::size_t j) { assert(active_set_.contains(i) &amp;&amp; active_set_.contains(j)); // update alpha auto Q_i = getQ(i); auto Q_j = getQ(j); auto C_i = getC(i); auto C_j = getC(j); auto old_alpha_i = alpha_[i]; auto old_alpha_j = alpha_[j]; if (y_[i] != y_[j]) { float quad_coeff = QD_[i] + QD_[j] + 2.0f * Q_i[j]; if (quad_coeff &lt;= 0) { quad_coeff = TAU; } float delta = (-G_[i] - G_[j]) / quad_coeff; float diff = alpha_[i] - alpha_[j]; alpha_[i] += delta; alpha_[j] += delta; if (diff &gt; 0) { if (alpha_[j] &gt; 0) { alpha_[j] = 0; alpha_[i] = diff; } } else { if (alpha_[i] &lt; 0) { alpha_[i] = 0; alpha_[j] = -diff; } } if (diff &gt; C_i - C_j) { if (alpha_[i] &gt; C_i) { alpha_[i] = C_i; alpha_[j] = C_i - diff; } } else { if (alpha_[j] &gt; C_j) { alpha_[j] = C_j; alpha_[i] = C_j + diff; } } } else { float quad_coeff = QD_[i] + QD_[j] - 2.0f * Q_i[j]; if (quad_coeff &lt;= 0) { quad_coeff = TAU; } float delta = (G_[i] - G_[j]) / quad_coeff; float sum = alpha_[i] + alpha_[j]; alpha_[i] -= delta; alpha_[j] += delta; if (sum &gt; C_i) { if (alpha_[i] &gt; C_i) { alpha_[i] = C_i; alpha_[j] = sum - C_i; } } else { if (alpha_[j] &lt; 0) { alpha_[j] = 0; alpha_[i] = sum; } } if (sum &gt; C_j) { if (alpha_[i] &gt; C_j) { alpha_[i] = C_j; alpha_[j] = sum - C_j; } } else { if (alpha_[i] &lt; 0) { alpha_[i] = 0; alpha_[j] = sum; } } } // update gradient float delta_alpha_i = alpha_[i] - old_alpha_i; float delta_alpha_j = alpha_[j] - old_alpha_j; for (auto k : active_set_) { G_[k] += Q_i[k] * delta_alpha_i + Q_j[k] * delta_alpha_j; } // update alpha status and G_bar bool ui = alpha_status_[i] == Alpha::Upper; bool uj = alpha_status_[j] == Alpha::Upper; updateAlphaStatus(i); updateAlphaStatus(j); if (ui != (alpha_status_[i] == Alpha::Upper)) { Q_i = getQ(i); if (ui) { for (std::size_t k = 0; k &lt; l_; ++k) { G_bar_[k] -= C_i * Q_i[k]; } } else { for (std::size_t k = 0; k &lt; l_; ++k) { G_bar_[k] += C_i * Q_i[k]; } } } if (uj != (alpha_status_[j] == Alpha::Upper)) { Q_j = getQ(j); if (uj) { for (std::size_t k = 0; k &lt; l_; ++k) { G_bar_[k] -= C_j * Q_j[k]; } } else { for (std::size_t k = 0; k &lt; l_; ++k) { G_bar_[k] += C_j * Q_j[k]; } } } } void Solver::reconstructGradient() { if (active_set_.size() == l_) { return; } std::unordered_set&lt;std::size_t&gt; inactive_set; for (std::size_t j = 0; j &lt; l_; ++j) { if (!active_set_.contains(j)) { inactive_set.insert(j); } } std::size_t free_count = 0; for (std::size_t j = 0; j &lt; l_; ++j) { if (active_set_.contains(j)) { if (alpha_status_[j] == Alpha::Free) { ++free_count; } } else { G_[j] = G_bar_[j] + p_[j]; } } if (2 * free_count &lt; active_set_.size()) { std::cerr &lt;&lt; &quot;WARNING: deactivating shrinking may be faster\n&quot;; } if (free_count * l_ &gt; 2 * active_set_.size() * (l_ - active_set_.size())) { for (auto i : inactive_set) { auto Q_i = getQ(i); for (auto j : active_set_) { if (alpha_status_[j] == Alpha::Free) { G_[i] += alpha_[j] * Q_i[j]; } } } } else { for (auto i : active_set_) { if (alpha_status_[i] == Alpha::Free) { auto Q_i = getQ(i); for (auto j : inactive_set) { G_[j] += alpha_[i] * Q_i[j]; } } } } for (std::size_t i = 0; i &lt; l_; ++i) { active_set_.insert(i); } } // [0] : return whether if already optimal // [1], [2] : return i, j such that // i : maximizes -y_i * grad(f)_i in I_high(alpha) // j : minimizes the decreases of obj value // (if quadratic coefficient &lt;= 0, replace it with tau) // -y_j * grad(f)_j &lt; -y_i * grad(f)_i, j in I_low(alpha) std::tuple&lt;bool, std::size_t, std::size_t&gt; SolverOrdinary::selectWorkingSet() const { float g_max1 = std::numeric_limits&lt;float&gt;::lowest(); std::size_t g_max_idx = -1; for (auto i : active_set_) { if (y_[i] == +1) { if (alpha_status_[i] != Alpha::Upper) { if (g_max1 &lt;= -G_[i]) { g_max1 = -G_[i]; g_max_idx = i; } } } else { if (alpha_status_[i] != Alpha::Lower) { if (g_max1 &lt;= G_[i]) { g_max1 = G_[i]; g_max_idx = i; } } } } std::size_t i = g_max_idx; std::vector&lt;float&gt; Qi; if (i != -1) { Qi = getQ(i); } std::size_t g_min_idx = -1; float g_max2 = std::numeric_limits&lt;float&gt;::lowest(); float obj_diff_min = std::numeric_limits&lt;float&gt;::max(); for (auto j : active_set_) { if (y_[j] == +1) { if (alpha_status_[j] != Alpha::Lower) { float grad_diff = g_max1 + G_[j]; if (G_[j] &gt;= g_max2) { g_max2 = G_[j]; } if (grad_diff &gt; 0) { float obj_diff = 0.0f; float quad_coeff = QD_[i] + QD_[j] - 2.0f * y_[i] * Qi[j]; if (quad_coeff &gt; 0) { obj_diff = -std::pow(grad_diff, 2.0f) / quad_coeff; } else { obj_diff = -std::pow(grad_diff, 2.0f) / TAU; } if (obj_diff &lt;= obj_diff_min) { g_min_idx = j; obj_diff_min = obj_diff; } } } } else { if (alpha_status_[j] != Alpha::Upper) { float grad_diff = g_max1 - G_[j]; if (-G_[j] &gt;= g_max2) { g_max2 = -G_[j]; } if (grad_diff &gt; 0) { float obj_diff = 0.0f; float quad_coeff = QD_[i] + QD_[j] + 2.0f * y_[i] * Qi[j]; if (quad_coeff &gt; 0) { obj_diff = -std::pow(grad_diff, 2.0f) / quad_coeff; } else { obj_diff = -std::pow(grad_diff, 2.0f) / TAU; } if (obj_diff &lt;= obj_diff_min) { g_min_idx = j; obj_diff_min = obj_diff; } } } } } if (g_max1 + g_max2 &lt; eps_ || g_min_idx == -1) { return {true, -1, -1}; } return {false, g_max_idx, g_min_idx}; } void SolverOrdinary::calculateRho(Solution&amp; sol) const { float res = 0.0f; std::size_t count_free = 0; float ub = std::numeric_limits&lt;float&gt;::max(); float lb = std::numeric_limits&lt;float&gt;::lowest(); float sum_free = 0.0f; for (auto i : active_set_) { auto yG = y_[i] * G_[i]; if (alpha_status_[i] == Alpha::Upper) { if (y_[i] == -1) { ub = std::min(ub, yG); } else { lb = std::max(lb, yG); } } else if (alpha_status_[i] == Alpha::Lower) { if (y_[i] == +1) { ub = std::min(ub, yG); } else { lb = std::max(lb, yG); } } else { ++count_free; sum_free += yG; } } if (count_free) { res = sum_free / count_free; } else { res = (ub + lb) / 2.0f; } sol.rho = res; } void SolverOrdinary::doShrinking() { float g_max1 = std::numeric_limits&lt;float&gt;::lowest(); float g_max2 = std::numeric_limits&lt;float&gt;::lowest(); for (auto i : active_set_) { if (y_[i] == +1) { if (alpha_status_[i] != Alpha::Upper) { g_max1 = std::max(g_max1, -G_[i]); } if (alpha_status_[i] != Alpha::Lower) { g_max2 = std::max(g_max2, G_[i]); } } else { if (alpha_status_[i] != Alpha::Upper) { g_max2 = std::max(g_max2, -G_[i]); } if (alpha_status_[i] != Alpha::Lower) { g_max1 = std::max(g_max1, G_[i]); } } } if (!unshrink_ &amp;&amp; g_max1 + g_max2 &lt;= eps_ * 10) { unshrink_ = true; reconstructGradient(); } std::unordered_set&lt;std::size_t&gt; to_shrunk; for (auto i : active_set_) { if (beShrunk(i, g_max1, g_max2)) { to_shrunk.insert(i); } } for (auto i : to_shrunk) { active_set_.erase(i); } } bool SolverOrdinary::beShrunk(std::size_t i, float g_max1, float g_max2) const { assert(i &lt; l_); if (alpha_status_[i] == Alpha::Upper) { if (y_[i] == +1) { return (-G_[i] &gt; g_max1); } else { return (-G_[i] &gt; g_max2); } } else if (alpha_status_[i] == Alpha::Lower) { if (y_[i] == +1) { return (G_[i] &gt; g_max2); } else { return (G_[i] &gt; g_max1); } } return false; } // Solver NU class SolverNU final : public Solver { public: SolverNU(std::size_t l, Mat&lt;float&gt;&amp; Q, std::vector&lt;float&gt; QD, std::vector&lt;float&gt; p, std::vector&lt;char&gt; y, std::vector&lt;float&gt; alpha, std::pair&lt;float, float&gt; C, float eps, bool shrinking) : Solver(l, Q, std::move(QD), std::move(p), std::move(y), std::move(alpha), C, eps, shrinking) {} std::tuple&lt;bool, std::size_t, std::size_t&gt; selectWorkingSet() const; void calculateRho(Solution&amp; sol) const; void doShrinking(); bool beShrunk(std::size_t i, float g_max1, float g_max2, float g_max3, float g_max4) const; }; // [0] : return whether if already optimal // [1], [2] : return i, j such that // i : maximizes -y_i * grad(f)_i in I_high(alpha) // j : minimizes the decreases of obj value // (if quadratic coefficient &lt;= 0, replace it with tau) // -y_j * grad(f)_j &lt; -y_i * grad(f)_i, j in I_low(alpha) std::tuple&lt;bool, std::size_t, std::size_t&gt; SolverNU::selectWorkingSet() const { float g_maxp1 = std::numeric_limits&lt;float&gt;::lowest(); float g_maxn1 = std::numeric_limits&lt;float&gt;::lowest(); std::size_t g_maxp_idx = -1; std::size_t g_maxn_idx = -1; for (auto i : active_set_) { if (y_[i] == +1) { if (alpha_status_[i] != Alpha::Upper) { if (g_maxp1 &lt;= -G_[i]) { g_maxp1 = -G_[i]; g_maxp_idx = i; } } } else { if (alpha_status_[i] != Alpha::Lower) { if (g_maxn1 &lt;= G_[i]) { g_maxn1 = G_[i]; g_maxn_idx = i; } } } } std::size_t ip = g_maxp_idx; std::vector&lt;float&gt; Qip; if (ip != -1) { Qip = getQ(ip); } std::size_t in = g_maxn_idx; std::vector&lt;float&gt; Qin; if (in != -1) { Qin = getQ(in); } std::size_t g_min_idx = -1; float g_maxp2 = std::numeric_limits&lt;float&gt;::lowest(); float g_maxn2 = std::numeric_limits&lt;float&gt;::lowest(); float obj_diff_min = std::numeric_limits&lt;float&gt;::max(); for (auto j : active_set_) { if (y_[j] == +1) { if (alpha_status_[j] != Alpha::Lower) { float grad_diff = g_maxp1 + G_[j]; if (G_[j] &gt;= g_maxp2) { g_maxp2 = G_[j]; } if (grad_diff &gt; 0) { float obj_diff = 0.0f; float quad_coeff = QD_[ip] + QD_[j] - 2.0f * Qip[j]; if (quad_coeff &gt; 0) { obj_diff = -std::pow(grad_diff, 2.0f) / quad_coeff; } else { obj_diff = -std::pow(grad_diff, 2.0f) / TAU; } if (obj_diff &lt;= obj_diff_min) { g_min_idx = j; obj_diff_min = obj_diff; } } } } else { if (alpha_status_[j] != Alpha::Upper) { float grad_diff = g_maxn1 - G_[j]; if (-G_[j] &gt;= g_maxn2) { g_maxn2 = -G_[j]; } if (grad_diff &gt; 0) { float obj_diff = 0.0f; float quad_coeff = QD_[in] + QD_[j] - 2.0f * Qin[j]; if (quad_coeff &gt; 0) { obj_diff = -std::pow(grad_diff, 2.0f) / quad_coeff; } else { obj_diff = -std::pow(grad_diff, 2.0f) / TAU; } if (obj_diff &lt;= obj_diff_min) { g_min_idx = j; obj_diff_min = obj_diff; } } } } } if (std::max(g_maxp1 + g_maxp2, g_maxn1 + g_maxn2) &lt; eps_ || g_min_idx == -1) { return {true, -1, -1}; } return {false, (y_[g_min_idx] == +1) ? g_maxp_idx : g_maxn_idx, g_min_idx}; } void SolverNU::calculateRho(Solution&amp; sol) const { float res = 0.0f; std::size_t count_free1 = 0; std::size_t count_free2 = 0; float ub1 = std::numeric_limits&lt;float&gt;::max(); float ub2 = std::numeric_limits&lt;float&gt;::max(); float lb1 = std::numeric_limits&lt;float&gt;::lowest(); float lb2 = std::numeric_limits&lt;float&gt;::lowest(); float sum_free1 = 0.0f; float sum_free2 = 0.0f; for (auto i : active_set_) { if (y_[i] == +1) { if (alpha_status_[i] == Alpha::Upper) { lb1 = std::max(lb1, G_[i]); } else if (alpha_status_[i] == Alpha::Lower) { ub1 = std::min(ub1, G_[i]); } else { ++count_free1; sum_free1 += G_[i]; } } else { if (alpha_status_[i] == Alpha::Upper) { lb2 = std::max(lb2, G_[i]); } else if (alpha_status_[i] == Alpha::Lower) { ub2 = std::min(ub2, G_[i]); } else { ++count_free2; sum_free2 += G_[i]; } } } float r1 = 0.0f; float r2 = 0.0f; if (count_free1) { r1 = sum_free1 / count_free1; } else { r1 = (ub1 + lb1) / 2.0f; } if (count_free2) { r2 = sum_free2 / count_free2; } else { r2 = (ub2 + lb2) / 2.0f; } sol.r = (r1 + r2) / 2.0f; sol.rho = (r1 - r2) / 2.0f; } void SolverNU::doShrinking() { float g_max1 = std::numeric_limits&lt;float&gt;::lowest(); float g_max2 = std::numeric_limits&lt;float&gt;::lowest(); float g_max3 = std::numeric_limits&lt;float&gt;::lowest(); float g_max4 = std::numeric_limits&lt;float&gt;::lowest(); for (auto i : active_set_) { if (alpha_status_[i] != Alpha::Upper) { if (y_[i] == +1) { g_max1 = std::max(g_max1, -G_[i]); } else { g_max4 = std::max(g_max4, -G_[i]); } } if (alpha_status_[i] != Alpha::Lower) { if (y_[i] == +1) { g_max2 = std::max(g_max2, G_[i]); } else { g_max3 = std::max(g_max3, G_[i]); } } } if (!unshrink_ &amp;&amp; std::max(g_max1 + g_max2, g_max3 + g_max4) &lt;= eps_ * 10) { unshrink_ = true; reconstructGradient(); } std::unordered_set&lt;std::size_t&gt; to_shrunk; for (auto i : active_set_) { if (beShrunk(i, g_max1, g_max2, g_max3, g_max4)) { to_shrunk.insert(i); } } for (auto i : to_shrunk) { active_set_.erase(i); } } bool SolverNU::beShrunk(std::size_t i, float g_max1, float g_max2, float g_max3, float g_max4) const { assert(i &lt; l_); if (alpha_status_[i] == Alpha::Upper) { if (y_[i] == +1) { return (-G_[i] &gt; g_max1); } else { return (-G_[i] &gt; g_max4); } } else if (alpha_status_[i] == Alpha::Lower) { if (y_[i] == +1) { return (G_[i] &gt; g_max2); } else { return (G_[i] &gt; g_max3); } } return false; } } // namespace frozenca #endif //FROZENCA_SVMSOLVER_H </code></pre> <p>SVMClassification.h</p> <pre><code>#ifndef FROZENCA_SVMCLASSIFICATION_H #define FROZENCA_SVMCLASSIFICATION_H #include &quot;SVMModel.h&quot; #include &quot;SVMSolver.h&quot; #include &lt;algorithm&gt; #include &lt;functional&gt; #include &lt;ranges&gt; #include &lt;unordered_set&gt; #include &lt;unordered_map&gt; namespace frozenca { class SVMClassification : public SVMModel { private: std::unordered_map&lt;int, std::unordered_set&lt;std::size_t&gt;&gt; groups_; std::vector&lt;char&gt; nonzero_; std::vector&lt;int&gt; data_label_; std::vector&lt;int&gt; labels_; public: SVMClassification(std::unique_ptr&lt;Kernel&gt; kernel) : SVMModel(std::move(std::move(kernel))) {} virtual ~SVMClassification() = default; virtual void fit(const SVMTrainData&amp; svm_data, const SVMParams&amp; params) final; virtual void constructGroups(const SVMTrainData&amp; svm_data) final; virtual void constructModel(const SVMTrainData&amp; svm_data, const std::vector&lt;std::pair&lt;std::vector&lt;float&gt;, float&gt;&gt;&amp; decision_functions) final; virtual std::pair&lt;Mat&lt;float&gt;, std::vector&lt;float&gt;&gt; computeQs(std::size_t l, const SubSamples&amp; X, const std::vector&lt;char&gt;&amp; y) const final; [[nodiscard]] virtual float predict(const std::vector&lt;float&gt;&amp; sample) const final; protected: virtual std::pair&lt;std::vector&lt;float&gt;, float&gt; fitOne(const SVMTrainData&amp; svm_sub_data, const SVMParams&amp; params, float Cp, float Cn) = 0; }; void SVMClassification::fit(const SVMTrainData&amp; svm_data, const SVMParams&amp; params) { SVMModel::fit(svm_data, params); constructGroups(svm_data); const std::size_t l = svm_data.n_; const std::size_t k = groups_.size(); // train k * (k - 1) / 2 binary classifiers nonzero_.clear(); nonzero_.resize(l); std::vector&lt;SubSamples&gt; class_X (k); for (std::size_t i = 0; i &lt; k; ++i) { auto label_i = labels_[i]; auto&amp; group_i = groups_[label_i]; for (auto index_i : group_i) { class_X[i].push_back(svm_data.getXRef(index_i)); } } std::vector&lt;std::pair&lt;std::vector&lt;float&gt;, float&gt;&gt; decision_functions; for (std::size_t i = 0; i &lt; k; ++i) { auto&amp; group_i = groups_[labels_[i]]; for (std::size_t j = i + 1; j &lt; k; ++j) { auto&amp; group_j = groups_[labels_[j]]; SubSamples sample_ij; std::ranges::copy(class_X[i], std::back_inserter(sample_ij)); std::ranges::copy(class_X[j], std::back_inserter(sample_ij)); std::vector&lt;float&gt; label_ij; for (std::size_t ci = 0; ci &lt; class_X[i].size(); ++ci) { label_ij.push_back(+1); } for (std::size_t cj = 0; cj &lt; class_X[j].size(); ++cj) { label_ij.push_back(-1); } SVMTrainData sub_data(sample_ij, label_ij, svm_data.feature_bounds_); auto wi = params.weight_scale.empty() ? 1.0f : params.weight_scale[i]; auto wj = params.weight_scale.empty() ? 1.0f : params.weight_scale[j]; auto f = fitOne(sub_data, params, params.C * wi, params.C * wj); std::size_t alpha_index = 0; for (auto index_i : group_i) { if (!nonzero_[index_i] &amp;&amp; std::fabs(f.first[alpha_index]) &gt; 0) { nonzero_[index_i] = true; } alpha_index++; } for (auto index_j : group_j) { if (!nonzero_[index_j] &amp;&amp; std::fabs(f.first[alpha_index]) &gt; 0) { nonzero_[index_j] = true; } alpha_index++; } decision_functions.push_back(std::move(f)); } } constructModel(svm_data, decision_functions); } void SVMClassification::constructGroups(const SVMTrainData&amp; svm_data) { if (!groups_.empty()) { return; } const std::size_t l = svm_data.n_; data_label_.resize(l); for (std::size_t i = 0; i &lt; l; ++i) { int this_label = static_cast&lt;int&gt;(svm_data.y_[i]); groups_[this_label].insert(i); data_label_[i] = this_label; } for (const auto&amp; [label, _] : groups_) { labels_.push_back(label); } if (groups_.size() == 1) { std::cerr &lt;&lt; &quot;WARNING: training data in only one class\n&quot;; } } void SVMClassification::constructModel(const SVMTrainData&amp; svm_data, const std::vector&lt;std::pair&lt;std::vector&lt;float&gt;, float&gt;&gt;&amp; decision_functions) { const std::size_t k = groups_.size(); SV_.clear(); SV_coeff_.clear(); rho_.clear(); for (const auto&amp; [alpha, rho] : decision_functions) { rho_.push_back(rho); } for (std::size_t i = 0; i &lt; k; ++i) { for (auto idx : groups_[labels_[i]]) { if (nonzero_[idx]) { SV_[i].push_back(svm_data.getX(idx)); } } } std::size_t decision_function_index = 0; for (std::size_t i = 0; i &lt; k; ++i) { auto&amp; group_i = groups_[labels_[i]]; for (std::size_t j = i + 1; j &lt; k; ++j) { auto&amp; group_j = groups_[labels_[j]]; auto&amp; alpha = decision_functions[decision_function_index].first; std::size_t alpha_index = 0; for (auto index_i : group_i) { if (nonzero_[index_i]) { SV_coeff_[i * k + j].push_back(alpha[alpha_index]); } ++alpha_index; } for (auto index_j : group_j) { if (nonzero_[index_j]) { SV_coeff_[i * k + j].push_back(alpha[alpha_index]); } ++alpha_index; } ++decision_function_index; } } } std::pair&lt;Mat&lt;float&gt;, std::vector&lt;float&gt;&gt; SVMClassification::computeQs(std::size_t l, const SubSamples&amp; X, const std::vector&lt;char&gt;&amp; y) const { Mat&lt;float&gt; Q (l, l); std::vector&lt;float&gt; QD (l); for (std::size_t i = 0; i &lt; l; ++i) { for (std::size_t j = 0; j &lt; l; ++j) { Q[{i, j}] = y[i] * y[j] * (*kernel_)(X[i], X[j]); } QD[i] = Q[{i, i}]; } return {Q, QD}; } float SVMClassification::predict(const std::vector&lt;float&gt;&amp; sample) const { auto sample_scaled = scaleInputs(sample); const std::size_t k = groups_.size(); std::vector&lt;std::size_t&gt; vote(k); std::unordered_map&lt;std::size_t, std::vector&lt;float&gt;&gt; k_values; for (std::size_t i = 0; i &lt; k; ++i) { std::size_t SV_index = 0; for (auto idx : groups_.at(labels_[i])) { if (nonzero_[idx]) { k_values[i].push_back((*kernel_)(sample_scaled, SV_.at(i)[SV_index++])); } } } std::size_t rho_index = 0; for (std::size_t i = 0; i &lt; k; ++i) { auto&amp; group_i = groups_.at(labels_[i]); for (std::size_t j = i + 1; j &lt; k; ++j) { float sum = 0.0f; auto&amp; group_j = groups_.at(labels_[j]); auto&amp; curr_coeffs = SV_coeff_.at(i * k + j); std::size_t idx_i = 0; for (auto idx : group_i) { if (nonzero_[idx]) { sum += curr_coeffs[idx_i] * k_values[i][idx_i]; ++idx_i; } } std::size_t idx_j = 0; for (auto idx : group_j) { if (nonzero_[idx]) { sum += curr_coeffs[idx_i + idx_j] * k_values[j][idx_j]; ++idx_j; } } sum -= rho_[rho_index++]; if (sum &gt; 0.0f) { ++vote[i]; } else { ++vote[j]; } } } auto vote_max_index = std::distance(vote.begin(), std::ranges::max_element(vote)); return static_cast&lt;float&gt;(labels_[vote_max_index]); } class SVMCSVC final : public SVMClassification { public: SVMCSVC(std::unique_ptr&lt;Kernel&gt; kernel) : SVMClassification(std::move(kernel)) {} std::pair&lt;std::vector&lt;float&gt;, float&gt; fitOne(const SVMTrainData&amp; svm_data, const SVMParams&amp; params, float Cp, float Cn); }; std::pair&lt;std::vector&lt;float&gt;, float&gt; SVMCSVC::fitOne(const SVMTrainData&amp; svm_data, const SVMParams&amp; params, float Cp, float Cn) { const std::size_t l = svm_data.n_; std::vector&lt;float&gt; minus_ones (l, -1.0f); std::vector&lt;char&gt; y (l); std::vector&lt;float&gt; alpha (l); for (std::size_t i = 0; i &lt; l; ++i) { if (svm_data.y_[i] &gt; 0) { y[i] = +1; } else { y[i] = -1; } } auto [Q, QD] = computeQs(l, svm_data.getXRef(), y); SolverOrdinary s(l, Q, QD, minus_ones, y, alpha, {Cp, Cn}, params.eps, params.shrinking); auto solution = s.Solve(); if (Cp == Cn) { float sum_alpha = std::accumulate(solution.alpha.begin(), solution.alpha.end(), 0.0f); std::cout &lt;&lt; &quot;nu = &quot; &lt;&lt; sum_alpha / (Cp * l) &lt;&lt; '\n'; } std::ranges::transform(solution.alpha, y, solution.alpha.begin(), std::multiplies{}); return {solution.alpha, solution.rho}; } class SVMNuSVC final : public SVMClassification { public: SVMNuSVC(std::unique_ptr&lt;Kernel&gt; kernel, const SVMParams&amp; params) : SVMClassification(std::move(kernel)) {} std::pair&lt;std::vector&lt;float&gt;, float&gt; fitOne(const SVMTrainData&amp; svm_data, const SVMParams&amp; params, float Cp, float Cn); }; std::pair&lt;std::vector&lt;float&gt;, float&gt; SVMNuSVC::fitOne(const SVMTrainData&amp; svm_data, const SVMParams&amp; params, float Cp, float Cn) { const std::size_t l = svm_data.n_; std::vector&lt;float&gt; alpha (l); std::vector&lt;char&gt; y (l); auto sum_pos = params.nu * l / 2.0f; auto sum_neg = params.nu * l / 2.0f; for (std::size_t i = 0; i &lt; l; ++i) { if (svm_data.y_[i] &gt; 0) { y[i] = +1; alpha[i] = std::min(1.0f, sum_pos); sum_pos -= alpha[i]; } else { y[i] = -1; alpha[i] = std::min(1.0f, sum_neg); sum_neg -= alpha[i]; } } std::vector&lt;float&gt; zeros(l); auto [Q, QD] = computeQs(l, svm_data.getXRef(), y); SolverOrdinary s(l, Q, QD, zeros, y, alpha, {1.0f, 1.0f}, params.eps, params.shrinking); auto solution = s.Solve(); auto r = solution.r; std::cout &lt;&lt; &quot;C = &quot; &lt;&lt; 1.0f / r &lt;&lt; '\n'; std::ranges::transform(solution.alpha, y, solution.alpha.begin(), [&amp;r](auto a, auto y) { return a * y / r; }); solution.rho /= r; solution.obj /= std::pow(r, 2.0f); solution.upper_bound = {1.0f / r, 1.0f / r}; return {solution.alpha, solution.rho}; } } // namespace frozenca </code></pre> <p>Test code: Generated male/female height, weights and trained. Predicted newly generated male/female heights and weights, and it predicts correctly.</p> <pre><code>#include &quot;Matrix/Matrix.h&quot; #include &quot;ML/SVM/SupportVectorMachine.h&quot; #include &lt;iostream&gt; #include &lt;memory&gt; #include &lt;random&gt; namespace fc = frozenca; int main() { std::unique_ptr&lt;fc::SVMModel&gt; sm = std::make_unique&lt;fc::SVMCSVC&gt;(std::make_unique&lt;fc::KernelRBF&gt;()); std::mt19937 gen(std::random_device{}()); constexpr std::size_t num_samples = 200; std::normal_distribution&lt;float&gt; male_height (177.0f, 8.0f); std::normal_distribution&lt;float&gt; male_weight (70.0f, 6.0f); std::normal_distribution&lt;float&gt; female_height (162.0f, 7.0f); std::normal_distribution&lt;float&gt; female_weight (53.0f, 5.5f); std::vector&lt;std::vector&lt;float&gt;&gt; X; std::vector&lt;float&gt; y; for (std::size_t i = 0; i &lt; num_samples; ++i) { auto height = male_height(gen); auto weight = male_weight(gen); X.push_back(std::vector&lt;float&gt;{height, weight}); y.push_back(+1); } for (std::size_t i = 0; i &lt; num_samples; ++i) { auto height = female_height(gen); auto weight = female_weight(gen); X.push_back(std::vector&lt;float&gt;{height, weight}); y.push_back(-1); } fc::SVMTrainData data(X, y); fc::SVMParams params; params.shrinking = false; sm-&gt;fit(data, params); std::vector&lt;std::vector&lt;float&gt;&gt; X1; for (std::size_t i = 0; i &lt; 10; ++i) { auto height = male_height(gen); auto weight = male_weight(gen); X1.push_back({height, weight}); } auto y1 = sm-&gt;predict(X1); for (auto y_pred : y1) { std::cout &lt;&lt; y_pred &lt;&lt; ' '; } std::cout &lt;&lt; '\n'; std::vector&lt;std::vector&lt;float&gt;&gt; X2; for (std::size_t i = 0; i &lt; 10; ++i) { auto height = female_height(gen); auto weight = female_weight(gen); X2.push_back({height, weight}); } auto y2 = sm-&gt;predict(X2); for (auto y_pred : y2) { std::cout &lt;&lt; y_pred &lt;&lt; ' '; } std::cout &lt;&lt; '\n'; } </code></pre> <p>Test Output</p> <pre><code>Optimization finished, #iter = 39 nu = 0.18 1 1 1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 </code></pre> <p>Pretty good!</p> <p>Feel free to comment anything!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T12:28:53.650", "Id": "532546", "Score": "0", "body": "I would suggest the you use templates so that the same code can be used for `float` and `double`." } ]
[ { "body": "<h1>Split <code>SVMTrainData</code> instead of using a variant</h1>\n<p>I think you can avoid the variant by splitting <code>SVMTrainData</code> into a class that holds the full training data, and one that holds a subset of the data using references, perhaps named <code>SVMTrainSet</code>. Have an easy way to generate the latter from the first (like how a <code>std::string_view</code> or a <code>std::span</code> works), and use the latter exclusively in the rest of the code.</p>\n<h1>Missing error checking</h1>\n<p>Errors seeking or reading from the input stream are ignored by your code. There's a only a check for <code>X</code> being empty and rows not all having the same length. The seeking is unnecessary since you don't seem to be using the variable <code>len</code> at all (ensure you enable compiler warnings, which should have caught this). After the <code>while</code>-loop, check if <code>is.eof()</code> is <code>true</code>, if not there was an error while reading.</p>\n<h1>Be consistent reporting errors</h1>\n<p>I see both <code>assert()</code> and <code>throw</code> being using in the constructor that reads from a <code>std::istream</code>. Be consistent, and use <code>throw</code> for any recoverable error.</p>\n<p>I also would use <a href=\"https://en.cppreference.com/w/cpp/error/runtime_error\" rel=\"nofollow noreferrer\"><code>std::runtime_error</code></a> instead of <code>std::invalid_argument</code>, the latter is normally meant when you pass an invalid argument to a function, not for I/O errors.</p>\n<h1>Avoid unnecessary moving</h1>\n<p>You don't need to create <code>X</code> first and then move it into <code>X_</code>.\nIn the constructor that scales existing samples, just take <code>X</code> by <code>const</code> reference, and have the constructor make the copy:</p>\n<pre><code>SVMTrainData(const Samples &amp;X, const std::vector&lt;float&gt; &amp;y) :\n X_(X), y_(y), n_(y_.size()), C_(X[0].size()) {\n scale();\n}\n</code></pre>\n<p>In the constructor that reads from the input stream, you can initialize <code>X_</code> to the right type and then use it directly inside the constructor body:</p>\n<pre><code>explicit SVMTrainData(std::istream&amp; is): X_(Samples{}) {\n ...\n X_.push_back(std::move(row));\n ...\n}\n</code></pre>\n<p>Similarly, you can avoid moving the <code>row</code> by adding an entry to <code>X_</code> and getting a reference to it:</p>\n<pre><code>auto &amp;row = X_.emplace_back();\n</code></pre>\n<p>However, that needs some other change to your code to make it possible:</p>\n<h1>Read lines using <code>std::getline()</code></h1>\n<p>The member function <code>getline()</code> of <code>std::istream</code> is a bit unfortunate; it requires you to provide a buffer long enough to hold the line, and then there are all sorts of issues to deal with, like what to do if the line is actually longer than the buffer. A simpler way to read lines is to use <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/getline\" rel=\"nofollow noreferrer\"><code>std::getline()</code></a> to read a whole line into a <code>std::string</code>:</p>\n<pre><code>std::string buffer;\n\nwhile (std::getline(is, buffer)) {\n // We now know we have read a full line\n auto &amp;row = X_.emplace_back();\n std::size_t curr{};\n while (...) {\n auto delim = buffer.find(',', curr);\n ...\n row.push_back(result);\n }\n}\n</code></pre>\n<h1>Don't unnecessarily store duplicate information</h1>\n<p>There is no need for <code>n_</code> and <code>C_</code> in <code>SVMTrainData</code>, just use <code>X_.size()</code> and <code>X_[0].size()</code> directly, create member functions that return <code>X_.size()</code> and <code>X_[0].size()</code>, or use range-<code>for</code> loops to avoid needing to use the sizes explicitly.</p>\n<p>Duplicating information always has the issue that you have to keep it in sync, otherwise bad things can happen.</p>\n<h1>Use range-<code>for</code> loops where appropriate</h1>\n<p>You can avoid a lot of manual iteration by using range-<code>for</code> loops. This simplifies code and reduces the chance of mistakes, like accidentily swapping <code>n_</code> and <code>C_</code>. For example, you can rewrite <code>scale()</code> like so:</p>\n<pre><code>void scale() {\n feature_bounds_ = ...;\n\n for (auto &amp;row: X_) {\n for (std::size_t c = 0; c &lt; row.size(); ++c) {\n feature_bounds[c] = {\n std::min(feature_bounds_[c].first, row[c]),\n std::max(feature_bounds_[c].second, row[c])\n };\n }\n }\n\n ...\n}\n</code></pre>\n<p>If you wait for C++23 or can use the <a href=\"https://ericniebler.github.io/range-v3/\" rel=\"nofollow noreferrer\">range-v3 library</a>, then you can use <code>zip()</code> for the inner loop:</p>\n<pre><code>using ranges::views::zip;\n\nfor (auto &amp;row: X_) {\n for (auto [value, bounds]: zip(row, feature_bounds_) {\n bounds = {\n std::min(bounds.first, value),\n std::max(bounds.second, value)\n };\n }\n}\n</code></pre>\n<h1>Use of virtual classes</h1>\n<p>I think most of the use of <code>virtual</code> in your code does not make sense. For the <code>Kernel</code>, I think it would be better to store it as a <code>std::function</code> inside <code>SVMModel</code>:</p>\n<pre><code>class SVMModel {\n ...\n std::function&lt;float(const std::vector&lt;float&gt;&amp;, const std::vector&lt;float&gt;&amp;)&gt; kernel_;\n ...\n};\n</code></pre>\n<p>The only issue is how to handle <code>adjustParams</code>. Perhaps you can just pass <code>f</code> as a third argument to the kernel function.</p>\n<p>For the <code>SVMModel</code>, there are lots of <code>virtual final</code> functions in the base class. That doesn't make sense, why not make those regular functions? As for <code>fit()</code>, this also doesn't need to be <code>virtual</code>, as the only users of the base class's <code>fit()</code> are the derived classes themselves.</p>\n<p>Another option is to use template parameters instead of virtual classes. Consider being able to write this in <code>main()</code>:</p>\n<pre><code>SVMCSVC&lt;KernelRBF&gt; sm;\n...\nsm.fit(data, params);\n...\nfor (auto y_pred: sm.predict(X1)) {\n std::cout &lt;&lt; y_pred &lt;&lt; ' ';\n}\nstd::cout &lt;&lt; '\\n';\n</code></pre>\n<h1>Use your own type aliases consistently</h1>\n<p>You define the type alias <code>Samples</code>, but in most of the code you are writing <code>std::vector&lt;std::vector&lt;float&gt;&gt;</code> explicitly. If you do define a type alias, use it consistently.</p>\n<h1>Consider going for a more functional style</h1>\n<p>Your classes are written such that you have an object, and then you call <code>fit()</code> on that object, and now the object is modified to hold the result of the fit. A more functional approach would be to have <code>fit()</code> not modify its own object, but rather <code>return</code> the result of the fit. In fact, <code>fit()</code> could just be a free function, so you can write:</p>\n<pre><code>fc::SVMTrainData data(X, y);\nfc::SVMParams params;\nparams.shrinking = false;\nparams.kernel = KernelRBF;\n\nauto sm = fc::SVMFit(data, params);\n</code></pre>\n<p>The same goes for the <code>Solver</code> class. Instead of first constructing the class with all the parameters, and then calling <code>solver.Solve()</code>, it would be much more natural to write:</p>\n<pre><code>auto solution = SolveOrdinary(l, Q, QD, ...);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T13:11:25.697", "Id": "269846", "ParentId": "269837", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T01:34:57.550", "Id": "269837", "Score": "3", "Tags": [ "c++", "machine-learning", "numerical-methods", "c++20" ], "Title": "libsvm++ : Rewritten libsvm in newer C++" }
269837
<p>I would like to code review of my program. I would very much like to request a code review. I would like the directory.getfiles statement to retrieve only files with the specified name.</p> <p>Regards</p> <pre><code>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace FontAwesomeIconGenerator { class Program { static async Task Main(string[] args) { Console.WriteLine(&quot;Start generate icon&quot;); //Database data string database = &quot;USE [database-test]&quot;; string schema = &quot;[dbo]&quot;; string tableName = &quot;[icon]&quot;; StringBuilder query = new StringBuilder(); query.Append(database); query.AppendLine(); query.Append(&quot;DELETE FROM &quot; + schema + &quot;.&quot; + tableName + &quot; WHERE PRX='ICO'&quot;); query.AppendLine(); query.Append(&quot;GO&quot;); query.AppendLine(); //Get all icon name var allIcon = GetAllFontawesomeIconName(&quot;fontawesome&quot;); foreach (var icon in allIcon) { query.Append(&quot;INSERT INTO &quot; + schema + &quot;.&quot; + tableName + &quot; ([PRX],[KEY_CODE],[VALUE_CODE]) VALUES('ICO', '&quot; + icon + &quot;', NULL)&quot;); query.AppendLine(); } var test = query.ToString(); await File.WriteAllTextAsync(&quot;Update_FontAwesomeIcon.sql&quot;, test); Console.WriteLine(&quot;Completed generating file&quot;); } public static List&lt;string&gt; GetAllFontawesomeIconName(string pathToFile) { List&lt;string&gt; result = new List&lt;string&gt;(); var filesContent = new Dictionary&lt;string, string&gt;(); string[] files = Directory.GetFiles(pathToFile); foreach (var file in files) { filesContent.Add(Path.GetFileName(file), File.ReadAllText(file)); } var filteredData = Regex.Matches(filesContent[&quot;all.css&quot;], @&quot;^\.fa\-(.*):&quot;, RegexOptions.Multiline).Cast&lt;Match&gt;().Select(m =&gt; m.Value).ToList(); foreach (var el in filteredData) { string iconName = el.Remove(el.Length - 1).Remove(0, 4); string iconNameWithQuotes = &quot;\&quot;&quot; + iconName + &quot;\&quot;&quot;; AddPrefixToIconName(filesContent, result, iconName, iconNameWithQuotes); } return result; } public static List&lt;string&gt; AddPrefixToIconName(Dictionary&lt;string, string&gt; filesContent, List&lt;string&gt; result, string iconName, string customizedIconName) { if (filesContent[&quot;solid.js&quot;].Contains(customizedIconName)) { result.Add(&quot;fas fa-&quot; + iconName); } if (filesContent[&quot;regular.js&quot;].Contains(customizedIconName)) { result.Add(&quot;far fa-&quot; + iconName); } if (filesContent[&quot;light.js&quot;].Contains(customizedIconName)) { result.Add(&quot;fal fa-&quot; + iconName); } if (filesContent[&quot;duotone.js&quot;].Contains(customizedIconName)) { result.Add(&quot;fad fa-&quot; + iconName); } if (filesContent[&quot;brands.js&quot;].Contains(customizedIconName)) { result.Add(&quot;fab fa-&quot; + iconName); } return result; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T10:01:10.047", "Id": "532543", "Score": "5", "body": "\"I would like the directory.getfiles statement to retrieve only files with the specified name.\" What does it currently do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T15:55:59.417", "Id": "532565", "Score": "4", "body": "Is the code currently working as you expect it to? You should read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T09:03:43.963", "Id": "269842", "Score": "0", "Tags": [ "c#" ], "Title": "Program that retrieves icon name and create sql file" }
269842
<p>The mission:</p> <p>Zero Trim</p> <p>Write a function which trims multiple zero's sequences to a single zero digit. The return value is the updated array. You are not allowed to use another array, and you need to implement it with one pass over the array. In other words, each element in the array should change its index only once during the program.</p> <p>var w = [1,2,0,0,0,0,5,7,-6,0,0,0,8,0,0];</p> <p>var n = zeroTrim(w);</p> <p>console.log(n); //print [1,2,0,5,7,-6,0,8,0]</p> <p>Best implementation should be in complexity of O(n), i.e., with one pass over the array.</p> <p>I am allowed to use only: function,conditions (if), loops, --, ++, %, /, *, -, +, ==, !=, &gt;=, &gt;, &lt;=, &lt;, ||, &amp;&amp;, %=, /=, *=, +=, array.length, array.pop() and concat.</p> <p>My code:</p> <pre><code>function zeroTrim(a){ var i,j,l,last,count,count1; count=0; count1=0; for( i = 0 ;i &lt; a.length ;i++){ if(a[i] + a[i+1] === 0){ count++; j=i; while(a[j] === 0){ last=j; j++; count1++; } for(l=i ; l &lt; a.length ;l++){ a[l] = a[last]; last++; } } } for(i = 0 ;i &lt; count1-count ;i++ ){ a.pop(); } return a; } var a=[1,2,0,0,0,0,5,7,-6,0,0,0,8,0,0]; console.log(zeroTrim(a)); </code></pre> <p>Any feedback would be appreciated, if you have other options please share it.</p> <p>Thank you guys!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T09:13:32.063", "Id": "532606", "Score": "0", "body": "You didn't listed `===` in your allowed list but you are using it?" } ]
[ { "body": "<p>To make sure I understood the problem, I scribbled a simple solution.</p>\n<pre><code>// Trim multiple zero's sequences to a single zero digit. \n// The return value is the updated array. \nfunction zeroTrim(a){\n let j = 0;\n for (let i = 0; i &lt; a.length; i++) {\n if (a[i] !== 0 || (i == 0 || a[i-1] !== 0)) {\n a[j++] = a[i];\n }\n }\n a.length = j;\n return a;\n}\n\nvar w = [1,2,0,0,0,0,5,7,-6,0,0,0,8,0,0];\nvar n = zeroTrim(w);\nconsole.log(n); //print [1,2,0,5,7,-6,0,8,0]\n</code></pre>\n<p>I then read your code. You have a lot of complicated, difficult-to-read code with a lot of loops.</p>\n<p>Since one of your conditions is <code>(a[i] + a[i+1] === 0)</code>, I ran a simple test.</p>\n<pre><code>var a=[42,-42];\nconsole.log(zeroTrim(a)); //print [undefined, undefined]\n</code></pre>\n<p>That doesn't look right.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T21:14:23.220", "Id": "532585", "Score": "2", "body": "This is a very clever and compact solution, but the access to `a[-1]` on the first iteration is a bit ugly. (I'd also point out that the correctness of the in-place modification is non-trivial, in the sense that even small and seemingly innocuous changes to the task and/or to the algorithm could easily break it. But since the OP's exercise requires it, I can't really criticize it as a design choice. If I saw this in code review at work, I *would* request a rationale for those choices and an outline of a correctness proof, though. And thorough unit tests, of course.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T22:34:06.580", "Id": "533018", "Score": "0", "body": "@IlmariKaronen: I added an explicit check instead of a[-1] as undefined. It goes without saying that there would be tests and proof of correctness." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T14:26:38.997", "Id": "269849", "ParentId": "269845", "Score": "5" } }, { "body": "<p>Like peterSO said in his answer your code appears complicated and it is not so easy to understand without an explanation of the task, moreover the <code>(a[i] + a[i+1] === 0)</code> condition brings with itself not conform outputs to what you expect.\nAn approach to simplify your code is to use the fact that <code>0</code> is a <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Falsy\" rel=\"noreferrer\"><code>falsy</code></a> value and combine this with a variable storing the number of the ints you are saving in 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>function zeroTrim(arr){\n let count = 0;\n let foundZero = false;\n\n for (const elem of arr) {\n if (elem || !foundZero) {\n arr[count++] = elem;\n foundZero = !elem;\n } \n }\n\n arr.length = count;\n return arr;\n}\n\nconsole.log(zeroTrim([]));\nconsole.log(zeroTrim([0]));\nconsole.log(zeroTrim([0, 0]));\nconsole.log(zeroTrim([1,2,0,0,0,0,5,7,-6,0,0,0,8,0,0]));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>I used <code>let</code>, <code>const</code> instead of <code>var</code> like in your code because for me they help to read the code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T17:09:29.027", "Id": "269853", "ParentId": "269845", "Score": "7" } }, { "body": "<p>Your code is really hard to understand. You'll notice that the other answers found it so hard to understand that they basically ignored what you wrote and instead gave their own attempt. I think I've managed to get through what you intended.</p>\n<ul>\n<li>You should prefer <code>const</code> if possible (not the case here), <code>let</code> if not <code>const</code>, and <code>var</code> if you have no other option.</li>\n<li>As has been pointed out, it appears you're thinking that <code>a[i] + a[i+1] === 0</code> is a shortcut for <code>(a[i]===0)&amp;&amp;(a[i+1]===0)</code>. It's not, so I'll assume you have that instead.</li>\n<li>Your variable names aren't great, and are the main source of confusion about what your code is doing. <code>i</code>, <code>j</code>, and <code>l</code> would possibly work for an index, but since you use all three in the same array, it's not clear what you mean by them. <code>count</code> would make sense if it's counting something, but since you also have <code>count1</code>, it's not at all clear what you're counting. I don't know what you mean by <code>last</code>, and the only reason that I know <code>a</code> is because of the problem description. My best guess at better variable names:\n<ul>\n<li><code>count1</code> -&gt; <code>zerosInBlocks</code></li>\n<li><code>j</code> -&gt; <code>zerosEndAt</code></li>\n<li><code>count</code> -&gt; <code>zeroBlocks</code></li>\n<li><code>a</code> -&gt; <code>array</code></li>\n</ul>\n</li>\n<li>Move the declarations to the tightest scope you can: <code>j</code>, <code>l</code>, and <code>last</code> are all within the <code>if</code> block. I'm also going to move <code>let l</code> and <code>let i</code> into the initializations of the for loops, although I've seen others complain about that.</li>\n<li><code>last=j</code> occurs in the <code>while</code> block, but doesn't do anything. Just move it after the block and say <code>last=j-1</code>.</li>\n<li><code>last++</code> is at the end of the for loop, but <code>l++</code> is the increment. They're doing the same thing, so lets put them in the increment area.</li>\n<li>Now that we've gotten this far, I finally understand that the point of the <code>l</code>/<code>last</code> for loop is to move the rest of the array downward and overwrite the zeros. This needs a comment. This also means that you're making multiple passes over the array, and your algorithm is O(n^2). The better approaches in the other answers have two indices running through the array: <code>i</code>/<code>elem</code> is where the variables start and <code>j</code>/<code>count</code> is where they end up.\n<ul>\n<li><code>last</code> -&gt; <code>moveFrom</code></li>\n</ul>\n</li>\n<li>Instead of popping individual items off the end of the array, we'll just redefine the length to be what we want.</li>\n<li>I'm not seeing why <code>j</code> (now <code>zerosEndAt</code>) doesn't go past the end of the array in the while loop. I added that check.\nYour code has now become:</li>\n</ul>\n<pre class=\"lang-javascript prettyprint-override\"><code>function zeroTrim(array){\n let zeroBlocks = 0,\n zerosInBlocks = 0;\n for ( let i = 0 ; i &lt; array.length ; i++ ) {\n if ( array[i]===0 &amp;&amp; array[i+1] === 0 ) {\n zeroBlocks++;\n let zerosEndAt = i;\n while ( zerosEndAt &lt; array.length &amp;&amp; array[zerosEndAt] === 0 ) {\n zerosEndAt++;\n zerosInBlocks++;\n }\n // move the rest of the array downward\n let moveFrom = zerosEndAt-1;\n for ( let l=i ; l &lt; array.length ; l++, moveFrom++ ) {\n array[l] = array[moveFrom];\n }\n }\n }\n array.length -= zerosInBlocks-zeroBlocks;\n return array;\n}\n\nvar array = [1,2,0,0,0,0,5,7,-6,0,0,0,8,0,0];\nconsole.log(zeroTrim(array));\n</code></pre>\n<ul>\n<li>&quot;Remove a bunch of stuff from the array&quot; is basically the description of one use of the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice\" rel=\"nofollow noreferrer\"><code>Array.splice</code></a> function, although it appears you're not allowed to use that. But I'll continue. &quot;Move the rest downward&quot; becomes <code>a.splice(i,zerosEndAt-i-1);</code> (This is still probably O(n^2).)</li>\n<li>Since the point of <code>zerosEndAt</code> is to count how many we're going to need to delete, let's do that. Instead of <code>zerosEndAt</code>, we'll use <code>zerosInThisBlock</code>. This also lets us move the <code>zerosInBlocks</code> increment out of the loop, and just update it after the loop.\nYour code has now become:</li>\n</ul>\n<pre class=\"lang-javascript prettyprint-override\"><code>function zeroTrim(array){\n let zeroBlocks = 0,\n zerosInBlocks = 0;\n for ( let i = 0 ; i &lt; array.length ; i++ ) {\n if ( array[i]===0 &amp;&amp; array[i+1] === 0 ) {\n zeroBlocks++;\n let zerosInThisBlock = 0;\n while ( i+zerosInThisBlock &lt; array.length &amp;&amp; array[i+zerosInThisBlock] === 0 ) {\n zerosInThisBlock++;\n }\n zerosInBlocks += zerosInThisBlock;\n array.splice(i,zerosInThisBlock-1);\n }\n }\n array.length -= zerosInBlocks-zeroBlocks;\n return array;\n}\n\nvar array = [1,2,0,0,0,0,5,7,-6,0,0,0,8,0,0];\nconsole.log(zeroTrim(array));\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T23:30:54.537", "Id": "270055", "ParentId": "269845", "Score": "2" } } ]
{ "AcceptedAnswerId": "269849", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T12:15:37.583", "Id": "269845", "Score": "2", "Tags": [ "javascript", "algorithm", "array" ], "Title": "Zero Trim from array- JavaScript" }
269845
<p>There are already many Tic Tac Toe posts. But as far as I can tell, none of the ones in Haskell are complete with a GUI</p> <p>Here is my implementation with Gloss. <a href="https://gist.github.com/Agnishom/4f2bdcbedbb3714e847ee2d17810ccf6" rel="nofollow noreferrer">Gist Link for convenience</a></p> <pre class="lang-hs prettyprint-override"><code>module Board where import Data.Map (Map, (!)) import qualified Data.Map as Map import Data.List (intercalate) data Player = X | O deriving (Eq, Ord, Show) newtype Board = Board (Map (Int, Int) (Maybe Player)) deriving (Eq, Ord) initBoard :: Board initBoard = Board $ Map.fromList [((x, y), Nothing) | x &lt;- [0..2], y &lt;- [0..2]] getMark :: Board -&gt; (Int, Int) -&gt; Maybe Player getMark (Board board) (x, y) | x &lt; 0 || x &gt; 2 || y &lt; 0 || y &gt; 2 = error &quot;Invalid coordinates&quot; | otherwise = board ! (x, y) putMark :: Board -&gt; Player -&gt; (Int, Int) -&gt; Maybe Board putMark (Board board) player (x, y) | x &lt; 0 || x &gt; 2 || y &lt; 0 || y &gt; 2 = error $ &quot;Invalid coordinates&quot; ++ show (x, y) | board ! (x, y) /= Nothing = Nothing | otherwise = Just $ Board $ Map.insert (x, y) (Just player) board emptySquares :: Board -&gt; [(Int, Int)] emptySquares (Board board) = [(x, y) | x &lt;- [0..2], y &lt;- [0..2], board ! (x, y) == Nothing] instance Show Board where show (Board board) = intercalate &quot;\n- - - \n&quot; [ ( intercalate &quot;|&quot; [prettyShow $ board ! (x, y) | y &lt;- [0..2]] ) | x &lt;- [0..2]] where prettyShow Nothing = &quot; &quot; prettyShow (Just X) = &quot;X&quot; prettyShow (Just O) = &quot;O&quot; allX :: Board allX = Board $ Map.fromList [((x, y), Just X) | x &lt;- [0..2], y &lt;- [0..2]] allO :: Board allO = Board $ Map.fromList [((x, y), Just O) | x &lt;- [0..2], y &lt;- [0..2]] </code></pre> <pre class="lang-hs prettyprint-override"><code>module Position where import Control.Applicative import Control.Monad.State import Data.Maybe import Data.Map (Map) import Data.List (minimumBy) import qualified Data.Map as Map import Board data Position = Position { curBoard :: Board, curPlayer :: Player } deriving (Eq, Ord, Show) type Line = [(Int, Int)] winningLines :: [Line] winningLines = [ [(x, y) | x &lt;- [0..2]] | y &lt;- [0..2]] ++ -- vertical lines [ [(x, y) | y &lt;- [0..2]] | x &lt;- [0..2]] ++ -- horizontal lines [[(0, 0), (1, 1), (2, 2)], -- main diagonal [(0, 2), (1, 1), (2, 0)]] -- off diagonal lineWinner :: Board -&gt; Line -&gt; Maybe Player lineWinner b l | all (== Just X) marks = Just X | all (== Just O) marks = Just O | otherwise = Nothing where marks = map (getMark b) l boardWinner :: Board -&gt; Maybe Player boardWinner b = foldr (&lt;|&gt;) Nothing $ map (lineWinner b) winningLines nextPlayer :: Player -&gt; Player nextPlayer X = O nextPlayer O = X succPositions :: Position -&gt; [Position] succPositions (Position b p) = newPosition . fromJust . markSquare &lt;$&gt; (emptySquares b) where newPosition b' = Position { curBoard = b', curPlayer = nextPlayer p } markSquare = putMark b p isDraw :: Board -&gt; Bool isDraw b = null (emptySquares b) &amp;&amp; isNothing (boardWinner b) data Label = Win | Lose | Draw deriving (Show, Eq) data Score = Score { label :: Label, height :: Int } deriving (Show, Eq) instance Ord Score where (Score Win i) &lt;= (Score Win j) = i &gt;= j (Score Win _) &lt;= _ = False (Score Lose i) &lt;= (Score Lose j) = i &lt;= j (Score Lose _) &lt;= _ = True (Score Draw i) &lt;= (Score Draw j) = i &gt;= j (Score Draw _) &lt;= (Score Win _) = True (Score Draw _) &lt;= (Score Lose _) = False type KnowledgeBase = Map Position Score scorePosition :: Position -&gt; State KnowledgeBase Score scorePosition pos@(Position b p) | isDraw b = pure $ Score { label = Draw, height = 0 } | (boardWinner b) == Just p = pure $ Score { label = Win, height = 0 } | Just _ &lt;- (boardWinner b) = pure $ Score { label = Lose, height = 0 } scorePosition pos@(Position b p) = do knowledge &lt;- gets (Map.lookup pos) case knowledge of Just s -&gt; return s Nothing -&gt; do let nextPositions = succPositions pos nextScores &lt;- mapM scorePosition nextPositions let bestSuccScore = minimum nextScores let score = curScore bestSuccScore modify (Map.insert pos score) return score bestResponse :: Position -&gt; State KnowledgeBase Position bestResponse pos@(Position b p) = do let nextPositions = succPositions pos nextScores &lt;- mapM scorePosition nextPositions let bestSucc = snd $ minimumBy (\(s1, p1) (s2, p2) -&gt; compare s1 s2) $ zip nextScores nextPositions return bestSucc -- given the minimum score among the successors, -- compute the current score curScore :: Score -&gt; Score curScore (Score Win i) = Score Lose (i + 1) curScore (Score Lose i) = Score Win (i + 1) curScore (Score Draw i) = Score Draw (i + 1) </code></pre> <pre class="lang-hs prettyprint-override"><code>module GlossUI where import Data.Map (Map) import qualified Data.Map as Map import Control.Monad import Control.Monad.State import Control.Applicative import Graphics.Gloss import Graphics.Gloss.Interface.Pure.Game import Debug.Trace import Board import Position -- copying some code from https://gist.github.com/gallais/0d61677fe97aa01a12d5 data GameState = GameState { pos :: Position , kb :: KnowledgeBase , playersTurn :: Bool , needToEval :: Bool } deriving Show type Size = Float resize :: Size -&gt; Path -&gt; Path resize k = fmap (\ (x, y) -&gt; (x * k, y * k)) drawO :: Size -&gt; (Int, Int) -&gt; Picture drawO k (i, j) = let x' = k * (fromIntegral j - 1) y' = k * (1 - fromIntegral i) in color (greyN 0.8) $ translate x' y' $ thickCircle (0.1 * k) (0.3 * k) drawX :: Size -&gt; (Int, Int) -&gt; Picture drawX k (i, j) = let x' = k * (fromIntegral j - 1) y' = k * (1 - fromIntegral i) in color black $ translate x' y' $ Pictures $ fmap (polygon . resize k) [ [ (-0.35, -0.25), (-0.25, -0.35), (0.35,0.25), (0.25, 0.35) ] , [ (0.35, -0.25), (0.25, -0.35), (-0.35,0.25), (-0.25, 0.35) ] ] drawBoard :: Size -&gt; Board -&gt; Picture drawBoard k b = Pictures $ grid : markPics where markPics = [drawAt (i, j) (getMark b (i, j)) | i &lt;- [0..2], j &lt;- [0..2]] drawAt :: (Int, Int) -&gt; (Maybe Player) -&gt; Picture drawAt (_, _) Nothing = Blank drawAt (i, j) (Just X) = drawX k (i, j) drawAt (i, j) (Just O) = drawO k (i, j) grid :: Picture grid = color black $ Pictures $ fmap (line . resize k) [ [(-1.5, -0.5), (1.5 , -0.5)] , [(-1.5, 0.5) , (1.5 , 0.5)] , [(-0.5, -1.5), (-0.5, 1.5)] , [(0.5 , -1.5), (0.5 , 1.5)] ] checkCoordinateY :: Size -&gt; Float -&gt; Maybe Int checkCoordinateY k f' = let f = f' / k in 2 &lt;$ guard (-1.5 &lt; f &amp;&amp; f &lt; -0.5) &lt;|&gt; 1 &lt;$ guard (-0.5 &lt; f &amp;&amp; f &lt; 0.5) &lt;|&gt; 0 &lt;$ guard (0.5 &lt; f &amp;&amp; f &lt; 1.5) checkCoordinateX :: Size -&gt; Float -&gt; Maybe Int checkCoordinateX k f' = let f = f' / k in 0 &lt;$ guard (-1.5 &lt; f &amp;&amp; f &lt; -0.5) &lt;|&gt; 1 &lt;$ guard (-0.5 &lt; f &amp;&amp; f &lt; 0.5) &lt;|&gt; 2 &lt;$ guard (0.5 &lt; f &amp;&amp; f &lt; 1.5) getCoordinates :: Size -&gt; (Float, Float) -&gt; Maybe (Int, Int) getCoordinates k (x, y) = (,) &lt;$&gt; checkCoordinateY k y &lt;*&gt; checkCoordinateX k x gameUpdate' :: Size -&gt; Event -&gt; GameState -&gt; GameState gameUpdate' _ e gs | playersTurn gs == False || needToEval gs = gs gameUpdate' k (EventKey (MouseButton LeftButton) Down _ (x', y')) gs = let newBoard = do (i, j) &lt;- getCoordinates k (x', y') putMark (curBoard $ pos gs) (curPlayer $ pos gs) (i, j) in case newBoard of Nothing -&gt; gs Just b' -&gt; gs { pos = Position { curBoard = b' , curPlayer = nextPlayer (curPlayer $ pos gs) } , playersTurn = False , needToEval = True } gameUpdate' _ _ gs = gs gameTime :: Float -&gt; GameState -&gt; GameState -- let the player move gameTime _ gs | playersTurn gs &amp;&amp; not (needToEval gs) = gs -- check if player has won gameTime t gs | (needToEval gs) = case (boardWinner $ curBoard $ pos gs) of Just X -&gt; gs { pos = (pos gs) { curBoard = allX } } Just O -&gt; gs { pos = (pos gs) { curBoard = allO } } Nothing -&gt; gs { needToEval = False } -- make computers move gameTime _ gs = let (pos', kb') = runState (bestResponse $ pos gs) (kb gs) in GameState {pos = pos', kb = kb', playersTurn = True, needToEval = True} initGameState :: GameState initGameState = GameState { pos = Position { curBoard = initBoard , curPlayer = X } , kb = Map.empty , playersTurn = True , needToEval = False } main :: IO () main = let window = InWindow &quot;Tic Tac Toe&quot; (300, 300) (10, 10) size = 100.0 in play window white 1 initGameState (\ gs -&gt; drawBoard size $ curBoard $ pos gs) (gameUpdate' size) gameTime </code></pre> <p>I would like some feedback on the following:</p> <ul> <li>Is the best way to implement the <code>scorePosition</code> using the state monad? See [Line 63 in <code>Position.hs</code>]</li> <li>In general, is there a better way to implement the mechanism to pick the next move?</li> <li>Is there a better way to implement the main UI loop in <code>GlossUI.hs</code>? Or is the way of marking explicit points in the state space the best way?</li> <li>Is it a better idea to define the board in some other way in <code>Board.hs</code>?</li> <li>Anything else that is worth changing?</li> </ul> <hr /> <p>later edit: I made certain changes to my code. If you are curious, see <a href="https://javaplt.github.io/haskell-course/" rel="nofollow noreferrer">Link</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T01:15:24.507", "Id": "533601", "Score": "1", "body": "two small tips: gloss has scale, you can use it instead of resize; don't do two options guards, specially if you need to re-evaluate a expression, that's what ifs are meant for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T02:10:30.813", "Id": "533602", "Score": "0", "body": "@pedrofuria what are options guards?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T15:18:05.570", "Id": "533614", "Score": "0", "body": "guards with two branchs" } ]
[ { "body": "<p>For tic-tac-toe the efficiency of the scoring function doesn't matter much; you can do exhaustive search (as in your <code>scorePosition</code>) because the search space is very small.</p>\n<p>Perhaps you could encode the positions as a product-of-sum type rather than a tuple of integers, which would eliminate a bunch of error checking:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>data Coord = C1 | C2 | C3 deriving (Eq, Ord, Show, Enum, Bounded)\ntype Pos = (Coord, Coord)\n</code></pre>\n<p>Re. code review : your Position and Board modules are very readable.</p>\n<p>However for larger games (like chess) you need to prioritize the search schedule.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T11:19:02.353", "Id": "270266", "ParentId": "269850", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T14:30:35.180", "Id": "269850", "Score": "8", "Tags": [ "haskell", "tic-tac-toe", "gui", "state-machine", "state" ], "Title": "Haskell Tic-Tac-Toe (with automation and GUI)" }
269850
<p>I am trying to learn rust and as such have been redoing some of the challenges on project Rosalind. This one relates to the challenge <a href="http://rosalind.info/problems/perm/" rel="nofollow noreferrer">Enumerating Gene Orders</a>.</p> <pre><code>fn all_combinations(mut combinations: Vec&lt;Vec&lt;usize&gt;&gt;, chain: Vec&lt;usize&gt;, mut choices: Vec&lt;usize&gt;, max: usize) -&gt; Vec&lt;Vec&lt;usize&gt;&gt;{ // filling options if choices.len() == 0 { choices = (1..max+1).collect(); } // loop over all potential numbers and appending the chain for (i, numb) in choices.iter().enumerate(){ let mut local_chain: Vec&lt;usize&gt; = chain.clone(); local_chain.push(*numb); // remove used number by its index let reduced_choices: Vec&lt;usize&gt; = [&amp;choices[..i], &amp;choices[i+1..]].concat(); // nothing more to add if reduced_choices.len() == 0 { combinations.push(local_chain); return combinations; } // depth still left else{ combinations = all_combinations(combinations.clone(), local_chain, reduced_choices, max); } } combinations } </code></pre> <p>Above is called as such:</p> <pre><code>let combinations: Vec&lt;Vec&lt;usize&gt;&gt; = Vec::new(); let chain: Vec&lt;usize&gt; = Vec::new(); let choices: Vec&lt;usize&gt; = Vec::new(); let all_combinations = all_combinations(combinations, chain, choices, 5); </code></pre> <p>I know that for n &gt; 8 with this algorithm it going to take an infinite amount of time to finish, but I'm really interested in how incorrect my code snippet is in terms of Rust guidelines and good practices since many things are still quite alien to me.</p> <p>Thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T19:46:38.337", "Id": "532581", "Score": "0", "body": "before any Rust comment, you don't need any vec to do that, first find a better algo" } ]
[ { "body": "<p>As already stated, not sure why you're returning vectors; the linked question asks for a number. And with that, you can use big-integers with simple calculations; some already do num-combin and num-perm efficiently behind the scenes.</p>\n<p>Ignoring the algorithm though (since that seems to be your intent), you're passing ownership of values that you're not modifying. In most cases you should accept a reference. Specifically &quot;<code>chain: &amp;Vec&lt;u8&gt;</code>&quot;</p>\n<p>It's debatable whether accepting a mutable vector (the combinations) as owned, then returning it when you're done is a good practice. It's technically fine. But more generally that's a mutable borrow &quot;<code>combinations: &amp;mut Vec&lt;Vec&lt;u8&gt;&gt;</code>&quot; with no return value then.</p>\n<p>Instead of declaring a mutable input parameter just to affect the default, you should accept it as immutable and conditinoally initialize a local. Change '<code>mut choices: Vec&lt;usize&gt;</code>' to '<code>_choices: &amp;Vec&lt;u8&gt;</code>' then in the code use '<code>let choices = if _choices.len() &gt; 0 { _choices } else { ... };</code> . It avoids losing ownership by the caller (in general you shouldn't take ownership unless you need it)</p>\n<p>Notice also, the usize is 4 or 8 bytes; usize is meant for vector-lengths and pointers (e.g. machine pointer sizes). Whereas u8,u16,u32,u64,u128 are meant for math. So if your max is bounded (since you'd run out of memory), you might as well use capped types; rust will assert that you do not exceed the max value. u8 would work in your example, but for this class of problem, u32 might be decent.. The main point is usize is unknown/platform specific, so not appropriate here.</p>\n<p>Next <code>Vec&lt;Vec&lt;u8&gt;&gt;</code> feels akward to me you're returning a fixed length tuplet; rather all second dimension fields are the same length. Let There is a 24 byte overhead in each of the second dimension fields.. You have a pointer-struct to-a pointer-struct. It's less efficient than a C double array.</p>\n<pre><code>fn all_combinations&lt;N:usize&gt;(..) -&gt; Vec&lt;[u8 ; N]&gt; {}\n</code></pre>\n<p>would be slightly better, as the inner array is a fixed-length struct. Though it means N is no longer a variable; it's not a compile-time constant.</p>\n<p>Not sure the best way to do a 2D array in rust actually; I typically do 1D arrays with manual offset calculations (in other languages like java, where 2D is more expensive, just like here). So replacing <code>combinations:Vec&lt;Vec&lt;u8&gt;&gt;</code> with <code>combinations:Vec&lt;u8&gt;</code> but using slices of size N.</p>\n<p>The concatenated arrays also irks me the wrong way.. It's certainly functional, so Lisp would love it. But that's pretty damn expensive here. Would be better to have a temp Vector, clear it between each iteration, then copy slices onto it. You could then copy the final slices into a fixed range offset of the 1D output array (from previous section).</p>\n<p>Not crazy about iterating over the choices vector. The consequence here is that you have an if-return in the middle of your loop.. Ideally you have a single return point. If you just did a <code>let mut i = 0; while !reduced_choices.is_empty() { let numb=choices[i]; ... i += 1; }</code> that would be slightly cleaner to my eye. Would also happen to get rid of the ugly '<code>*numb</code>'</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T18:55:17.577", "Id": "270365", "ParentId": "269856", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T18:28:25.610", "Id": "269856", "Score": "2", "Tags": [ "recursion", "rust", "combinatorics" ], "Title": "Finding possible combinations for n<7 with rust" }
269856
<p>I'm a back-end developer (in PHP and Python) and I use JavaScript mostly for DOM manipulation.</p> <p>Now I'm writing a chat app in Node.js and I'm not sure if my code is the cleanest.</p> <p>Here is how it works:</p> <ul> <li>Users open the chat page;</li> <li>We will match them randomly to another user;</li> <li>They will chat p2p.</li> </ul> <p>Here is what I have:</p> <p>When the user opens the page and sends the <code>ready signal</code> to the server, it will add the user information to the <code>USERS</code> stack and add the user socket id (which I basically use as its id ) to the <code>QUEUE</code> object.</p> <pre><code>const USERS = {}; const QUEUE = {}; const MATCH = []; const CHATS = {}; app.io.route('ready' , function (req){ USERS[req.socket.id] = { username : req.data.username , socket : req.socket.id , req : req , }; QUEUE[req.socket.id] = req.socket.id ; }) </code></pre> <p>Next there is a function to process the users in the queue and match them together. This function will grab the first user in the <code>QUEUE</code> (we call it primary user) and loop through the other users in the queue and when it finds another user (secondary user). It will add them to the <code>MATCH</code> array and remove them from the <code>QUEUE</code> and at the end calls the next function <code>match_making</code>.</p> <pre><code>var QUEUE_INPROG = false ; function process_queue(){ if(QUEUE_INPROG) return ; QUEUE_INPROG = true ; if( Object.keys(QUEUE).length &lt; 2 ) { QUEUE_INPROG = false ; return ; } let primary_user = QUEUE[ Object.keys(QUEUE)[0] ]; for (let secondary_user in QUEUE) { if ( secondary_user != primary_user) { MATCH.push({ primary : primary_user , secondary : secondary_user, }); delete QUEUE[secondary_user]; delete QUEUE[primary_user]; break ; } } QUEUE_INPROG = false ; match_making(); } setInterval(()=&gt;{ process_queue(); } , 5000 ); </code></pre> <p>The last function is pretty simple basically grabbing both users and sending their info to each other:</p> <pre><code>function match_making(){ if(MATCH.length &lt; 1 ) return ; var match = MATCH.shift(); let primary = USERS[match.primary]; let secondary = USERS[match.secondary]; console.log('sending match data to users '); primary.req.io.emit('incoming_chat', { user : secondary.username }) secondary.req.io.emit('incoming_chat', {user : primary.username }) let chat_key = match.primary+match.secondary; CHATS[chat_key] = { primary : primary , secondary : secondary , guest : null }; } </code></pre> <p>I'm not happy about how I call functions and not sure if using an interval for calling <code>process_queue</code> is the best way to go. Also, I had to use a flag <code>(QUEUE_INPROG)</code> to avoid function being called again before the last call is done.</p> <p>And how I have to use objects instead of array because I find it hard to search in an array and remove values.</p> <p>I would love for someone with JS experience to take a look at this code and give me some feedback.</p>
[]
[ { "body": "<p>In the ready function, don't add to queue, call queue-handler with id.\npop your queue-<strong>list</strong> and if not undefined you've got a match.\nelse add the user to the queue.</p>\n<p>Don't know if you need a <code>MATCH</code>-object at all. You're using it as temporary storage between functions instead of just passing parameters. Maybe you need it later?</p>\n<p>You shouldn't need <code>setInterval</code> when every new, ready user triggers the process. And that might remove the need for <code>QUEUE_INPROG</code> variable.</p>\n<p>You uppercase variables makes me as a javascript developer uncomfortable but that's ok :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T02:11:38.407", "Id": "532859", "Score": "0", "body": "thanx , the thing is i might have multiple users online and ready at the same time , thats why i've put them in an queue object/array and have another function process them to avoid some sort of race condition bug that might happen if i call the queue-handler directly in the ready event" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T02:13:42.180", "Id": "532860", "Score": "0", "body": "but it's a good idea to call the queue handler when user is ready and pass the id to handler , pop the queue object in the handler function for match and if not found just add the new id to queue object ... this way i dont need to use interval" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T07:16:02.177", "Id": "269900", "ParentId": "269860", "Score": "2" } }, { "body": "<p>The first thing that stands out is the casing on variables that are declared like globals. Syntactically there is nothing wrong with it but a common convention in many style guides is to only use all caps for (<a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Immutable\" rel=\"nofollow noreferrer\">immutable</a>) constants. This is recommended in many widely accepted style guides, not just for JavaScript (e.g. <a href=\"https://eslint.org/docs/rules/camelcase\" rel=\"nofollow noreferrer\">ESLint</a>, <a href=\"https://github.com/airbnb/javascript#naming--uppercase\" rel=\"nofollow noreferrer\">AirBnB</a>, <a href=\"https://google.github.io/styleguide/jsguide.html#naming-constant-names\" rel=\"nofollow noreferrer\">Google</a>) but also for Python (<a href=\"https://www.python.org/dev/peps/pep-0008/#constants\" rel=\"nofollow noreferrer\">PEP-8</a>) and other C-based languages like PHP (<a href=\"https://www.php-fig.org/psr/psr-1/\" rel=\"nofollow noreferrer\">PSR-1</a>).</p>\n<p>The scope of variables can be reduced dramatically. Prefer using <code>const</code> over <code>let</code> and <code>var</code>. This helps anyone reading the code, including your future self, know what can be reassigned and what can’t. Refer to answers to <a href=\"https://softwareengineering.stackexchange.com/q/278652/244085\">this post</a> for more details.</p>\n<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Property_definitions\" rel=\"nofollow noreferrer\">shorthand property definition notation</a> can be used to simplify the lines like these where the key is the same as the name of the variable being referenced:</p>\n<blockquote>\n<pre><code>CHATS[chat_key] = {\n\n primary : primary ,\n secondary : secondary ,\n guest : null\n\n};\n</code></pre>\n</blockquote>\n<p>Can be simplified to:</p>\n<pre><code>CHATS[chat_key] = {\n\n primary,\n secondary,\n guest : null\n\n};\n</code></pre>\n<p>Also, the call to setup the interval can be simplified from wrapping the call in an anonymous function/closure:</p>\n<blockquote>\n<pre><code>setInterval(()=&gt;{\n process_queue();\n} , 5000 );\n</code></pre>\n</blockquote>\n<p>To just referencing the function name:</p>\n<pre><code>setInterval(process_queue, 5000 );\n</code></pre>\n<blockquote>\n<p><em>…not sure if using an interval for calling <code>process_queue</code> is the best way to go. Also, I had to use a flag (<code>QUEUE_INPROG</code>) to avoid function being called again before the last call is done.</em></p>\n</blockquote>\n<p>Instead of an interval being set, <code>setTimeout()</code> could be used at the end of the function. That may eliminate the need for setting and checking the flag.</p>\n<blockquote>\n<p><em>how I have to use objects instead of array because I find it hard to search in an array and remove values.</em></p>\n</blockquote>\n<p>A <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\">Map</a> could be used. A <code>Map</code> object iterates its elements in insertion order — a <code>for...of</code> loop returns an array of <code>[key, value]</code> for each iteration. <sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#description\" rel=\"nofollow noreferrer\">1</a></sup>.</p>\n<p>A <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap\" rel=\"nofollow noreferrer\"><code>WeakMap</code></a> may also be useful. It may be able to help <a href=\"https://stackoverflow.com/a/29416340/1575353\">eliminate memory leaks</a>.</p>\n<hr />\n<p>There is a loop in <code>process_queue()</code>:</p>\n<blockquote>\n<pre><code>for (let secondary_user in QUEUE) {\n</code></pre>\n</blockquote>\n<p>From the MDN documentation for <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#deleted_added_or_modified_properties\" rel=\"nofollow noreferrer\"><code>for…in</code></a>:</p>\n<blockquote>\n<p>A <code>for...in</code> loop iterates over the properties of an object in an arbitrary order (see the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete\" rel=\"nofollow noreferrer\"><code>delete</code></a> operator for more on why one cannot depend on the seeming orderliness of iteration, at least in a cross-browser setting). <sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#deleted_added_or_modified_properties\" rel=\"nofollow noreferrer\">2</a></sup></p>\n</blockquote>\n<p>If the code was run on the client-side and IE was supported then it would be possible that insertion order wouldn’t be guaranteed<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#cross-browser_notes\" rel=\"nofollow noreferrer\">3</a></sup> . However this code is run on the node server, but in general it would be better to use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for…of</code></a> loop to iterate over the keys.</p>\n<pre><code>for (const secondary_user of Object.keys(QUEUE)) {\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T18:32:24.953", "Id": "270051", "ParentId": "269860", "Score": "3" } }, { "body": "<p>A longer review;</p>\n<ul>\n<li>Keep full uppercase names only for constant values like numbers</li>\n<li>In the <code>ready</code> function you access <code>req.socket.id</code> enough that you could store it locally</li>\n<li>To me, it is a code smell that you have the socket id in the key and in the value of USERS</li>\n<li>You mix <code>var</code> with <code>const</code> and <code>let</code>, I would stick with <code>const</code> and <code>let</code></li>\n<li>JavaScript variables should be in lowerCamelCase so <code>primary_user</code> -&gt; <code>primaryUser</code></li>\n<li><code>delete</code> was at some point considered obsolete, I try to avoid its use</li>\n<li>For a queue, I would use a list, not an object, I think the code could be so much simpler</li>\n<li>Magic numbers (like 5000) should be in a nicely named constant</li>\n<li>A match is just 2 objects, that seems unlikely to change, I would use an array instead of an object</li>\n<li>You should have a logging framework with log levels</li>\n<li>Actually, <a href=\"https://softwareengineering.stackexchange.com/a/148109/7614\">globals are evil</a>, you should really look into that</li>\n<li>I prefer function names to follow <code>&lt;verb&gt;&lt;thing&gt;</code> so <code>match_making</code> -&gt; <code>makeMatches</code></li>\n<li>YOu should realize that <code>()=&gt;processQueue();</code> and <code>processQueue</code> are functionally equivalent, but the 2nd approach is cleaner and more readable</li>\n<li>You should read about the <code>async</code> keyword, I am fairly certain that you don't need <code>QUEUE_INPROG</code>. I left it in the rewrite, because I cant test the code</li>\n</ul>\n<p>Taking that into account;</p>\n<p>Part 1;</p>\n<pre><code>const socketUsers = {};\nconst queue = {};\nconst matches = [];\nconst chats = {};\n\napp.io.route('ready' , function (request){\n\n id = request.socket.id;\n socketUsers[id] = {\n username : request.data.username,\n socket : id ,\n req : request,\n };\n //Drawback of a list, it does not natively weed out dupes\n if(!queue.includes(id)){\n queue.push(id);\n }\n })\n</code></pre>\n<p>Part 2;</p>\n<pre><code>let queueLocked = false ;\nconst queueProcessInterval = 5000;\nfunction processQueue(){\n\n if(queueLocked || queue.length &lt; 2){\n return;\n }\n queueLocked = true;\n\n matches.push([queue.pop(), queue.pop()]);\n\n queueLocked = false ;\n makeMatches();\n}\n\n\nsetInterval(processQueue, queueProcessInterval);\n</code></pre>\n<p>Part 3;</p>\n<pre><code>function makeMatches(){\n\n while(matches.length){\n const match = matches.pop();\n const primary = users[match.pop()];\n const secondary = users[match.pop()];\n\n //You should have a logging framework with log levels\n //console.log('sending match data to users ');\n\n primary.req.io.emit('incoming_chat', { user : secondary.username })\n secondary.req.io.emit('incoming_chat', {user : primary.username })\n\n const chatKey = primary.socket + secondary.socket;\n //This will make guest `undefined`, not null, I am not a fan of null\n chats[chatKey] = {primary, secondary, guest};\n\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T12:56:34.940", "Id": "534213", "Score": "0", "body": "about the function names `<verb><thing>` like ` match_making -> makeMatches` i think starting with `thing` kinda works like namespace , makes it easier to find/group the functions about that `thing`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T16:14:26.977", "Id": "270166", "ParentId": "269860", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T02:21:22.253", "Id": "269860", "Score": "4", "Tags": [ "javascript", "node.js" ], "Title": "Random matchmaking for a p2p chat application" }
269860
<p>I have a PHP API which echoes some data depending on the parameters in the URL:</p> <blockquote> <p>URL = &quot;MyWebsite.com/MyAPI.php/username/password&quot;</p> </blockquote> <p>When I try to access this API with Postman, I get the result within 5 seconds, however, using any Android device, I get the result at least 15 seconds later, under same network.</p> <p>Now I suspect there might be a delay in the way I'm processing the data, but I'm also doubting that it's taking +10 seconds.</p> <p>Here's the result from the API call:</p> <pre><code>{'Data1': Value1, 'Data2': 'Value2', 'Data3': 'Value3', 'Data4': 'Value4', 'Data5': 'Value5', 'Data6': 'Value6', 'Data7': 'Value7'} </code></pre> <p>Only the first value is integer, the rest are all string.</p> <p>API Call code:</p> <pre><code> apiTEST = view.findViewById(R.id.apiTEST);//Text View Button getUserData = view.findViewById(R.id.getUserData); String apiURL = &quot;https://MyWebsite.com/MyAPI.php/username/password&quot;; new Handler().postDelayed(() -&gt; { getUserData.performClick(); apiTEST.setText(getResources().getString(R.string.please_wait));//Show please wait line }, 1000);//Automatically press the invisible button a second after loading the activity getUserData.setOnClickListener(v -&gt; { StringRequest stringRequest = new StringRequest(apiURL, response -&gt; showJSONS(view, response), error -&gt; { apiTEST.setText(error.getMessage()); getUserData.performClick(); //Sometimes an error occurs (null), so this line will just click the button automatically to make the request again }); RequestQueue requestQueue = Volley.newRequestQueue(getActivity()); requestQueue.add(stringRequest); }); </code></pre> <p>Data processing/showing:</p> <pre><code> private void showJSONS(View view, String response) { response = response.replace(&quot;'&quot;, &quot;&quot;).replace(&quot;\&quot;&quot;, &quot;&quot;).replace(&quot;{&quot;, &quot;&quot;).replace(&quot;}&quot;,&quot;&quot;); String[] theValues = response.split(&quot;,&quot;); apiTEST = view.findViewById(R.id.apiTEST); for (String theValue : theValues) { if (theValue.contains(&quot;Data1&quot;)){ String[] data1Line = theValue.split(&quot;:&quot;); String Data1 = data1Line[1]; Data1 = Data1.replace(&quot;'&quot;, &quot;&quot;); data1_field.setText(Data1); } else if (theValue.contains(&quot;Data2&quot;)){ String[] data2Line = theValue.split(&quot;:&quot;); String data2 = data2Line[1]; data2 = data2.replace(&quot;'&quot;, &quot;&quot;); data2_field.setText(data2); data2ProgressBar[0] = data2; } else if (theValue.contains(&quot;Data3&quot;)){ String[] data3Line = theValue.split(&quot;:&quot;); String data3 = data3Line[1]; data3 = data3.replace(&quot;\&quot;&quot;, &quot;&quot;); data3_field.setText(data3); data3ProgressBar[0] = data3; } else if (theValue.contains(&quot;Data4&quot;)){ String[] data4Line = theValue.split(&quot;:&quot;); String data4Value = data4Line[1]; data4Value = data4Value.replace(&quot;\&quot;&quot;, &quot;&quot;); data4Value = data4Value.replace(&quot;}]}&quot;, &quot;&quot;); data4_field.setText(data4Value); data4ProgressBar[0] = data4Value; } ... same for data5, data6 &amp; data7 } setButtonsVisibility(view, true);//Show buttons to interact with the values apiTest.setText(&quot;&quot;);//Remove the &quot;Please Wait&quot; line } </code></pre> <p>Although I have set the buttons visibility before removing the &quot;Please wait&quot; line, what actually happens in the app is that the &quot;Please wait&quot; line gets removed, then about 7 seconds later the buttons appear!</p> <p>Is there a better approach to retrieving the data from the API? Or to process the data more effectively?</p> <p>About the auto clicking the button automatically when an error occurs: If I try to use Postman, I get the result 10/10, never failed or showed any error, but through the app, sometimes I just get &quot;null&quot; so I can only get the result after retrying few times. Thanks.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T09:30:51.897", "Id": "532607", "Score": "0", "body": "Welcome to Stack Review, from your code you know you are receiving a json object , there is a specific reason why you chose to see it as a string and not a json object ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T09:45:46.537", "Id": "532608", "Score": "0", "body": "Thank you, the only reason is that this will be the first version for the app, and I found it a little bit difficult for me to deal with JSON in Java, so I decided to deal with it as String, then on the next version I'll have more time to learn how to use it as JSON." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T11:04:16.200", "Id": "532613", "Score": "1", "body": "You are welcome, but with string you are inspecting the message several times while with json the inspection process (deserialization) is done just one time , so it is more convenient and almost surely explains the slowness. Not related to the question,if you want to be sure users receive your reply you have to write *@* before the username, there is also the username autocomplete option." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T16:22:26.413", "Id": "532641", "Score": "0", "body": "Also retreiving 6 values of data should never take more then 5 seconds... I would expect something like maximum of 100ms" } ]
[ { "body": "<p>When approaching optimization problems (and it kinda is one as you want to make a call faster) its generally best to first make sure that <strong>you understand exactly what is happening</strong> so when in doubt - <strong>measure</strong> and <strong>debug</strong>.</p>\n<p>Before doing any changes in the code I'd first set up debugger and probably some logs with timestamps (assuming you are testing on separate physical device - maybe emulator would be more useful?).</p>\n<p>After you have tools that allow you to measure the code runtime - <strong>don't guess, locate the hotspot</strong>. When hotspot is known usually the solution becomes obvious (if its not then its a good moment to ask further questions).</p>\n<p>Sorry if this is not the answer you were counting for but I believe that giving advice on code performance without specific measurement is exactly wrong - and amount of data you have provided is insufficient (mainly because there is too much difference between using postman from your development machine and app working on a android device - does it have enough ram? what exactly spans those 15 seconds - changes in the UI or it is time between http request and response? what does it mean they are on the same network? etc...).</p>\n<p>BTW &quot;https://MyWebsite.com/MyAPI.php/username/password&quot; - passing username and password like this makes me uneasy in terms of security see: <a href=\"https://owasp.org/www-community/vulnerabilities/Information_exposure_through_query_strings_in_url#\" rel=\"noreferrer\">https://owasp.org/www-community/vulnerabilities/Information_exposure_through_query_strings_in_url#</a></p>\n<p>Also, I'd <strong>strongly recommend</strong> using json parsing library instead of current solution like jackson object mapper (simple tutorial: <a href=\"https://www.baeldung.com/jackson-object-mapper-tutorial\" rel=\"noreferrer\">https://www.baeldung.com/jackson-object-mapper-tutorial</a>)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T12:34:36.497", "Id": "533331", "Score": "0", "body": "it might have been some time, but I took your advice and went through everything you suggested, I was able to figure out the delay problem, no longer passing the username & password through the URL (using headers with Base64 encryption) and learned how to use JSON to extract the data. Thank you very much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T13:13:02.650", "Id": "533335", "Score": "0", "body": "Love to hear that first part, keep up the good work - but please note that ***Base64 is not an encryption - anyone having access can decode it***, if you are communicating over ***https*** (and making sure of it) keeping secrets in headers is probably enough, no need to additionally encrypt them. In case of doubt refer to https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html and https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html and in general to OWASP materials." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T11:36:45.360", "Id": "269872", "ParentId": "269867", "Score": "5" } } ]
{ "AcceptedAnswerId": "269872", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T09:02:41.347", "Id": "269867", "Score": "1", "Tags": [ "java", "android" ], "Title": "My Android app is really slow when getting simple data from PHP" }
269867
<p>I was on Hacker Rank for the first time and there was <a href="https://www.hackerrank.com/challenges/py-collections-namedtuple/problem" rel="nofollow noreferrer">a question</a> that required to get the inputs from STDIN and use <code>collections.namedtuple()</code>. It was my first time working with getting inputs from STDIN so the way I acquired the inputs and used them to calculate the data might not be efficient.</p> <p>The question was to calculate the average mark of the students and was given a multiple line string input with specific data about the student (like: NAME, CLASS, ID) in which one of them is MARKS (I have added an image of a sample STDIN input data below to explain better). But the layout of the input data could change so the code must be able to figure out where the MARKS are in the data and also get the number of students in order to calculate the average of their marks.</p> <p>I came up with a quick way to solve this but was wondering how to appropriately and efficiently acquire the input data and perform the calculation.</p> <p>Briefly, what is a better (pythony, efficient, shorter) way to write my code?</p> <pre><code># Enter your code here. Read input from STDIN. Print output to STDOUT from collections import namedtuple import sys data = [line.rstrip().split() for line in sys.stdin.readlines()] sOMCache = []; n = 0 dataLength = len(data) if 'MARKS' in data[1] : marksIndex = data[1].index('MARKS') for i in range(dataLength) : if n &gt; 1 : sOMCache.append(data[n][marksIndex]) n += 1 sOM = sum([int(x) for x in sOMCache]) Point = namedtuple('Point','x,y') pt1 = Point(int(sOM), int((data[0][0]))) dot_product = ( pt1.x / pt1.y ) print (dot_product) </code></pre> <h2>Samples</h2> <p>Testcase 01:</p> <pre><code>5 ID MARKS NAME CLASS 1 97 Raymond 7 2 50 Steven 4 3 91 Adrian 9 4 72 Stewart 5 5 80 Peter 6 </code></pre> <p>Expected output: <code>78.00</code></p> <hr /> <p>Testcase 02:</p> <pre><code>5 MARKS CLASS NAME ID 92 2 Calum 1 82 5 Scott 2 94 2 Jason 3 55 8 Glenn 4 82 2 Fergus 5 </code></pre> <p>Expected output: <code>81.00</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T22:24:03.117", "Id": "532672", "Score": "0", "body": "@200_success oh so thats what they meant by change the img to text data. Thanks for the edit." } ]
[ { "body": "<blockquote>\n<p>there was a question that required to get the inputs from STDIN and use <code>collections.namedtuple()</code></p>\n</blockquote>\n<p>Really? I don't think that HackerRank would enforce using a named tuple, and using a named tuple isn't hugely helpful here. Plus, if you <em>were</em> to use a named tuple, I would sooner expect that it capture the four fields in every line rather than one point at the end.</p>\n<p>Python doesn't need semicolons <code>;</code> at the end of statements so you can delete that.</p>\n<p>The first line doesn't need to be split at all. The second line does need a full split, but every line after that only needs <code>marksIndex + 1</code> splits which you can specify via the <code>maxsplit</code> parameter.</p>\n<p>Your <code>if 'MARKS' in</code> check is a little odd. Hacker Rank hasn't asked for validation, and if they did, they are many more things you'd want to add to your validation than just this.</p>\n<p>Keeping <code>data</code> in one big list of lists will occupy much more memory than just keeping a running total.</p>\n<p>When you say dot product... what you have isn't really a dot product. Or as a stretch, maybe it's the dot product of two length-one vectors where the first value is 1/n and the second is the total. This doesn't make a whole lot of sense. If the dot product did appear in this question, I would expect two vectors, one full of 1/n and the other with the student marks; then the dot product would find the sum of the products of each element. But this is not an efficient way to implement this question. Just have a running total.</p>\n<p>I usually provide a suggested implementation at the end of review, but here I think there's more value for you to work on the above and come up with it on your own.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T18:48:21.840", "Id": "532657", "Score": "1", "body": "[probable context](https://www.hackerrank.com/challenges/py-collections-namedtuple/problem)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T02:17:58.340", "Id": "532681", "Score": "0", "body": "I think you can see from @200_success's [answer](https://codereview.stackexchange.com/a/269888/21582) how it's possible to get some mileage out of using `namedtuple` to handle things." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T03:27:54.380", "Id": "532682", "Score": "0", "body": "@martineau I understand how it can be used, but in this case the question is only looking for one field - and an aggregate of one field, at that. So a simple solution doesn't really need full records." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T07:02:23.353", "Id": "532684", "Score": "0", "body": "It's not *that* inefficient to `yield` full records from the generator function. As long as the caller never stores the full records in a list, it can extract the `MARKS` field and discard the rest of the record as it streams through each row." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T14:21:11.960", "Id": "269878", "ParentId": "269868", "Score": "4" } }, { "body": "<h2>namedtuple implementation</h2>\n<p>It's possible that I misunderstand the purpose of the exercise but since you are processing a list of <strong>students</strong>, I would expect that the namedtuple would represent a student object with properties like name, class, marks etc. You are still dealing with list indexes, and your present implementation of namedtuple does not really provide the flexibility you could have achieved.</p>\n<p>Below is a proposed snippet.\nTo simplify a bit, I would first process the input of stdin <strong>line by line</strong>, and then split each line in a loop. We first need to find the column headers so we discard the previous line(s). As soon as we know the column headers (student properties) we can create the namedtuple dynamically (its properties are not determined in advance and could change), and we can start processing the data.</p>\n<p>What we are effectively doing is this:</p>\n<pre><code>Student = namedtuple('Student', ['ID', 'MARKS', 'NAME', 'CLASS'])\n</code></pre>\n<p>There is one thing you should do: verify that after splitting the line contains the number of elements you expect, that is 4. Then we add a Student instance (the namedtuple) to a list for later tallying.</p>\n<p>To add a new Student instance we should normally do something like this:</p>\n<pre><code>student = Student('1', '97', 'Raymond', '7')\n</code></pre>\n<p>but instead we want to pass a <strong>list</strong> of values (that is, the line split). So the trick is to pass the arguments with a single *.</p>\n<p>In this example student.NAME would return Raymond and student.MARKS would return 97.</p>\n<p>Accordingly, the proposed code would be something along these lines:</p>\n<pre><code>import statistics\nfrom collections import namedtuple\n\nlines = [line.rstrip() for line in sys.stdin.readlines()]\n\nstudents = []\nstudent_fields = None\n\nfor i, line in enumerate(lines, start=1):\n elements = line.split()\n # this line contains column headers\n if 'MARKS' in elements:\n print(f&quot;Column headers found on line {i}: {elements}&quot;)\n student_fields = elements\n Student = namedtuple('Student', student_fields)\n else:\n if student_fields:\n student = Student(*elements)\n students.append(student)\n\n# compute average of all students\naverage_marks = statistics.mean([int(student.MARKS) for student in students])\nprint(f&quot;Average marks: {average_marks}&quot;)\n</code></pre>\n<p>Calculating the average is easy but in this case I have used statistics.mean for a more straightforward approach. It is a simple list comprehension. NB: check that the list is not empty before computing average.</p>\n<p>This is a rough approach that assumes that the data is well-formed, that the number of elements is always correct, and that the marks can be cast as integer.</p>\n<p>Without the requirement to use a namedtuple the Python <a href=\"https://docs.python.org/3/library/csv.html\" rel=\"nofollow noreferrer\">csv module</a> could have done the trick perhaps, with a Dictreader.</p>\n<h2>Coding style</h2>\n<p>Suggested reading is PEP8 for recommended Python coding style. Variable names should be lowercase, underscore can be used to separate keywords.</p>\n<pre><code>dot_product = ( pt1.x / pt1.y )\n</code></pre>\n<p>should be written:</p>\n<pre><code>dot_product = (pt1.x / pt1.y)\n</code></pre>\n<p>And</p>\n<pre><code>for i in range(dataLength) :\n</code></pre>\n<p>becomes:</p>\n<pre><code>for i in range(dataLength):\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T14:47:13.120", "Id": "532623", "Score": "0", "body": "Ish. In your proposed code: I would drop the `enumerate`; you shouldn't construct a list for `mean` and should just pass the generator; the fields of your `Student` should be lowercase; and it doesn't make much sense to search every single line for the header. The header is defined to appear on the second line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T14:52:23.893", "Id": "532624", "Score": "0", "body": "I am not certain that the headers will always be found on the second line actually. Hence this naive implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T14:53:55.247", "Id": "532626", "Score": "1", "body": "OK, but... your implementation will now break for a file that contains a student named MARKS. The best information that we have is that the headers appear on the second line and nowhere else." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T14:32:42.397", "Id": "269879", "ParentId": "269868", "Score": "2" } }, { "body": "<p>I liked the fact that you used the <code>sum()</code> builtin function, but I have no idea what <code>sOM</code> or <code>sOMCache</code> mean in <code>sOM = sum([int(x) for x in sOMCache])</code> — &quot;Sum of marks&quot;, maybe? But the capitalization is weird by <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Python standards</a>, and this isn't a cache — you wouldn't just eject data from this &quot;cache&quot;, would you?</p>\n<p>I think, as you probably suspected, that you missed the mark for this exercise. The main issues with your solution are:</p>\n<ul>\n<li>Misunderstanding the <code>Point</code>. What you're computing here is an average, not a dot product. The dot product in the tutorial was just to illustrate how you can access member fields within a <code>namedtuple</code> using <code>.x</code> or <code>.y</code>.</li>\n<li>Failure to take advantage of <code>namedtuple</code>. If you do things right, you should be able to write something like <code>row.MARKS</code> to get the value of the <code>MARKS</code> column for a particular <code>row</code>.</li>\n<li>Lack of expressiveness, such that it's not obvious what the code intends to do at a glance.</li>\n</ul>\n<h2>Suggested solution</h2>\n<pre><code>from collections import namedtuple\nfrom statistics import mean\nimport sys\n\ndef records(line_iter):\n &quot;&quot;&quot;\n Read records, one per line, space-separated, following a header.\n \n The header consists of two lines: the first line contains an integer\n specifying the number of records, and the second line specifies the\n column names. Records are yielded as namedtuples, where the fields\n have names specified by the second header row.\n &quot;&quot;&quot;\n n = int(next(line_iter))\n Record = namedtuple('Record', next(line_iter))\n for _ in range(n):\n yield Record(*next(line_iter).split())\n\nprint(mean(float(rec.MARKS) for rec in records(sys.stdin)))\n</code></pre>\n<p>Explanation:</p>\n<p>The final line of code drives all the work: read records from STDIN, and print the mean of the <code>MARKS</code> column. I've chosen to interpret the marks as <code>float</code>s for versatility, but if you're sure that the data are all integers then you could call <code>int(rec.MARKS)</code> instead.</p>\n<p>All of the work to read the input is handled by a generator function. The <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstring</a> describes what it does. As you can see, it takes advantage of the <code>namedtuple</code> to let you refer to the column of interest later.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T21:01:59.617", "Id": "269888", "ParentId": "269868", "Score": "5" } } ]
{ "AcceptedAnswerId": "269888", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T09:12:25.020", "Id": "269868", "Score": "3", "Tags": [ "python", "python-3.x", "programming-challenge", "parsing" ], "Title": "Find the average score, given data in a table with labeled columns not in a fixed order" }
269868
<p>I have created the below script in which I'm trying to set up a class for handling a config file, but also defining some functions that I call from the class methods. Not sure if I'm following the best practices when creating a class.</p> <pre><code># Python3 program to show that we can create # instance variables inside methods import pandas as pd from datetime import datetime as dt, timedelta as td import jtp_aux as aux def import_config_df(): &quot;&quot;&quot; Imports config dataframe with the values enabled being equal to 'YES' Returns: dataframe &quot;&quot;&quot; df_ = pd.read_excel( r'\\path\file.xlsx' ) cond_ = conditions_df(df_, 'ENABLED', 'YES').fillna(False) return df_[cond_] def conditions_df(df_, col_check_, col_value_, match_type_='MATCH'): &quot;&quot;&quot; Args: df_ (): config dataframe col_check_ (): column to check col_value_ (): value to check match_type_ (): match type being 'MATCH' for full match or 'CONTAINS' for partial match Returns: Dataframe with the True/False for the rows based on conditions met or not. &quot;&quot;&quot; if match_type_ == 'MATCH': return df_[col_check_].str.match(col_value_).fillna(False) elif match_type_ == 'CONTAINS': return df_[col_check_].str.contains(col_value_).fillna(False) else: return None def return_config(df_, process_, procedure_, sub_procedure_, type_return_): &quot;&quot;&quot; Based on the three first column of the config dataframe, it returns the value enabled for it. Args: df_ (dataframe): process_ (string): first config parameter from config file procedure_ (string): second config parameter from config file sub_procedure_ (string): third config parameter from config file type_return_ (string): 'LIST' (2+ value enabled to concatenate) or 'STRING' (1 value enabled). Returns: String or list resulting from the configuration inputted. &quot;&quot;&quot; cond1 = conditions_df(df_, 'PROCESS', process_) cond2 = conditions_df(df_, 'PROCEDURE', procedure_) cond3 = conditions_df(df_, 'SUB_PROCEDURE', sub_procedure_) if type_return_ == 'LIST': return df_[cond1 &amp; cond2 &amp; cond3]['VALUE_ENABLED'].to_list() elif type_return_ == 'STRING': return df_[cond1 &amp; cond2 &amp; cond3]['VALUE_ENABLED'].astype('str').to_string(index=False) else: return None def config_reports(df_, process_, report_day_, auto_manual_): &quot;&quot;&quot; Args: df_ (): config dataframe process_ (): 'REPORTS', 'VALIDATIONS'... report_day_ (): for the auto-schedule. auto_manual_ (): auto or manual schedule Returns: dictionary &quot;&quot;&quot; dict_return = {} cond1 = conditions_df(df_, 'PROCESS', process_) # If auto-scheduled or manually scheduled. if auto_manual_ == 'AUTO': cond2a = conditions_df(df_, 'SUB_PROCEDURE', 'AUTO_SCHEDULE') cond2b = conditions_df(df_, 'VALUE_ENABLED', report_day_, 'CONTAINS') else: cond2a = conditions_df(df_, 'SUB_PROCEDURE', 'MANUAL_SCHEDULE') cond2b = conditions_df(df_, 'VALUE_ENABLED', 'YES') # And/or logic cond2 = cond2a &amp; cond2b procedures_ = df_[cond1 &amp; cond2]['PROCEDURE'].unique() for procedure_ in procedures_: # Base df for operations cond3 = conditions_df(df_, 'PROCEDURE', procedure_) df_aux = df_[cond1 &amp; cond3] # Fetch config for the PLSQL Code to execute cond4 = conditions_df(df_, 'SUB_PROCEDURE', 'PLSQL') plsql_ = df_aux[cond4]['VALUE_ENABLED'].astype('str').to_string(index=False) plsql_ = '\n'.join(['BEGIN', plsql_, 'END;']) # Fetch config for the Cathnas01 path cond5 = conditions_df(df_, 'SUB_PROCEDURE', 'PATH_CATHNAS01') path_ = df_aux[cond5]['VALUE_ENABLED'].astype('str').to_string(index=False) # Fetch config for the name of the file cond6 = conditions_df(df_, 'SUB_PROCEDURE', 'FILENAME') filename_ = df_aux[cond6]['VALUE_ENABLED'].astype('str').to_string(index=False) # Fetch config for the data in the tabs cond7 = conditions_df(df_, 'SUB_PROCEDURE', 'EXCEL_CONTENT') tabs_data_ = df_aux[cond7][['FIELD2', 'VALUE_ENABLED']].set_index('FIELD2')['VALUE_ENABLED'].to_dict() dict_return[procedure_] = (plsql_, path_, filename_, tabs_data_) return dict_return class MyConfigFile: def __init__(self, process_): self.df = import_config_df() self.process = process_ # Manual or auto-schedule self.auto_manual = return_config(self.df, self.process, 'GLOBAL', 'AUTO_MANUAL', 'STRING') def getdictreports(self, delta_): # Dictionary to iterate for reports return config_reports( self.df, self.process, (dt.today() + td(days=delta_)).strftime('%a').upper(), self.auto_manual ) def send_errors_mail(self, body_): &quot;&quot;&quot; Sends an error mail. Args: body_ (): mail body Returns: None &quot;&quot;&quot; aux.send_email( strfrom=return_config(self.df, self.process, 'ERRORS', 'FROM', 'STRING'), vpara=return_config(self.df, self.process, 'ERRORS', 'TO', 'LIST'), vcc=return_config(self.df, self.process, 'ERRORS', 'CC', 'LIST'), vasunto=return_config(self.df, self.process, 'ERRORS', 'SUBJECT', 'STRING'), test_body=body_, attachments=r'', vprioridad=return_config(self.df, self.process, 'ERRORS', 'PRIORITY', 'STRING'), image=None ) def send_confirmation_mail(self, body_): &quot;&quot;&quot; Send a confirmation mail if everything successful. Args: body_ (): Returns: &quot;&quot;&quot; aux.send_email( strfrom=return_config(self.df, self.process, 'CONFIRMATION', 'FROM', 'STRING'), vpara=return_config(self.df, self.process, 'CONFIRMATION', 'TO', 'LIST'), vcc=return_config(self.df, self.process, 'CONFIRMATION', 'CC', 'LIST'), vasunto=return_config(self.df, self.process, 'CONFIRMATION', 'SUBJECT', 'STRING'), test_body=body_, attachments=r'', vprioridad=return_config(self.df, self.process, 'CONFIRMATION', 'PRIORITY', 'STRING'), image=None ) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T10:39:06.340", "Id": "532610", "Score": "0", "body": "Hey! Is this a copy paste error: `r'\\\\path\\file.xlsx'` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T10:57:13.237", "Id": "532611", "Score": "0", "body": "@kubatucka no, I had there my actual path, but I anonymized it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T22:58:43.620", "Id": "532674", "Score": "0", "body": "Please include an example or specification of the config file format." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T10:21:06.953", "Id": "269871", "Score": "0", "Tags": [ "python", "python-3.x" ], "Title": "Python Class for config file parameters" }
269871
<p>In my .net core console application, I am reading multiple excel files and bulk copy data into a database table. It is working as it is expected, I wonder if there are any improvements to make it better. So I would be glad if you can share your comments.</p> <p>Thanks in advance.</p> <pre><code>class Program { static async Task Main(string[] args) { try { string s = null; var d = new DirectoryInfo(@&quot;C:\Test&quot;); var files = d.GetFiles(&quot;*.xlsx&quot;); var usersList = new List&lt;User&gt;(); foreach (var file in files) { var fileName = file.FullName; using var package = new ExcelPackage(file); ExcelPackage.LicenseContext = LicenseContext.NonCommercial; var currentSheet = package.Workbook.Worksheets; var workSheet = currentSheet.First(); var noOfCol = workSheet.Dimension.End.Column; var noOfRow = workSheet.Dimension.End.Row; for (int rowIterator = 2; rowIterator &lt;= noOfRow; rowIterator++) { var user = new User { GameCode = workSheet.Cells[rowIterator, 1].Value?.ToString(), Count = Convert.ToInt32(workSheet.Cells[rowIterator, 2].Value), Email = workSheet.Cells[rowIterator, 3].Value?.ToString(), Status = Convert.ToInt32(workSheet.Cells[rowIterator, 4].Value) }; usersList.Add(user); } } var conn = ConfigurationManager.ConnectionStrings[&quot;Development&quot;].ConnectionString; await using var connString = new SqlConnection(conn); connString.Open(); await BulkWriter.InsertAsync(usersList, &quot;[Orders]&quot;, connString, CancellationToken.None); } catch (Exception e) { Console.WriteLine(e); throw; } } private class BulkWriter { private static readonly ConcurrentDictionary&lt;Type, SqlBulkCopyColumnMapping[]&gt; ColumnMapping = new ConcurrentDictionary&lt;Type, SqlBulkCopyColumnMapping[]&gt;(); public static async Task InsertAsync&lt;T&gt;(IEnumerable&lt;T&gt; items, string tableName, SqlConnection connection, CancellationToken cancellationToken) { using var bulk = new SqlBulkCopy(connection); await using var reader = ObjectReader.Create(items); bulk.DestinationTableName = tableName; foreach (var colMap in GetColumnMappings&lt;T&gt;()) bulk.ColumnMappings.Add(colMap); await bulk.WriteToServerAsync(reader, cancellationToken); } private static IEnumerable&lt;SqlBulkCopyColumnMapping&gt; GetColumnMappings&lt;T&gt;() =&gt; ColumnMapping.GetOrAdd(typeof(T), type =&gt; type.GetProperties() .Select(p =&gt; new SqlBulkCopyColumnMapping(p.Name, p.Name)).ToArray()); } } </code></pre> <h1>Updated version:</h1> <p>I also added excel extension change and moving excel into another folder. Any comments?</p> <pre><code>public static class Program { private static async Task ReadAllExcelFilesInDirectory(string path, List&lt;User&gt; usersList) { var dirInfo = new DirectoryInfo(path); var files = dirInfo.GetFiles(&quot;*.xlsx&quot;); foreach (var file in files) await ReadExcelFile(file, usersList); } private static async Task ReadExcelFile(FileInfo fileName, List&lt;User&gt; usersList) { const string destinationFile = @&quot;T:\Test&quot;; if (fileName == null) throw new ArgumentNullException(nameof(fileName)); if (usersList == null) throw new ArgumentNullException(nameof(usersList)); using var package = new ExcelPackage(fileName); ExcelPackage.LicenseContext = LicenseContext.NonCommercial; var currentSheet = package.Workbook.Worksheets; var workSheet = currentSheet.First(); var noOfCol = workSheet.Dimension.End.Column; var noOfRow = workSheet.Dimension.End.Row; for (var rowIterator = 2; rowIterator &lt;= noOfRow; rowIterator++) { var user = new User { GameCode = workSheet.Cells[rowIterator, 1].Value?.ToString(), Count = Convert.ToInt32(workSheet.Cells[rowIterator, 2].Value), Email = workSheet.Cells[rowIterator, 3].Value?.ToString(), Status = Convert.ToInt32(workSheet.Cells[rowIterator, 4].Value) }; usersList.Add(user); } //Change extension await using var newfile = File.OpenWrite(fileName.FullName + &quot;.old&quot;); await package.SaveAsAsync(newfile); // To move a file or folder to a new location File.Move(fileName.FullName, destinationFile + &quot;\\&quot; + fileName.Name); } private static async Task InsertUsersIntoDatabase(List&lt;User&gt; usersList) { var conn = ConfigurationManager.ConnectionStrings[&quot;Development&quot;].ConnectionString; await using var connString = new SqlConnection(conn); connString.Open(); await InsertAsync(usersList, &quot;[GameAPI].[dbo].[A101Orders]&quot;, connString, CancellationToken.None); } private static async Task Main(string[] args) { try { var usersList = new List&lt;User&gt;(); await ReadAllExcelFilesInDirectory( @&quot;C:\Test&quot;, usersList); await InsertUsersIntoDatabase(usersList); } catch (Exception e) { Console.WriteLine(e); throw; } } private static async Task InsertAsync&lt;T&gt;(IEnumerable&lt;T&gt; items, string tableName, SqlConnection connection, CancellationToken cancellationToken) { using var bulk = new SqlBulkCopy(connection); await using var reader = ObjectReader.Create(items); bulk.DestinationTableName = tableName; var properties = typeof(T).GetProperties(); foreach (var prop in properties) bulk.ColumnMappings.Add(new SqlBulkCopyColumnMapping(prop.Name, prop.Name)); await bulk.WriteToServerAsync(reader, cancellationToken); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T15:05:03.873", "Id": "533207", "Score": "2", "body": "Rather than extending the code in a question that has been answered, it might be better to ask a `follow on question` with a link to this question." } ]
[ { "body": "<h1>Missing classes</h1>\n<p>You have failed to include your definition of the <code>User</code> class in the code snippet so I had to create my own.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>class User\n{\n public string GameCode { get; set; }\n public int Count { get; set; }\n public string Email { get; set; }\n public int Status { get; set; }\n}\n</code></pre>\n<p>For <code>ConfigurationManager</code> there are 3 different packages that I could install.</p>\n<ul>\n<li>Microsoft.IdentityModel.Protocols</li>\n<li>System.Configuration.ConfigurationManager</li>\n<li>NLog</li>\n</ul>\n<p>After consulting my magic 8-ball, I decided to go for <code>System.Configuration.ConfigurationManager</code>.</p>\n<h1>Incorrect usage of try...catch</h1>\n<p>Placing your entire program into one <code>try</code>...<code>catch</code> block serves no purpose and makes debugging much harder.</p>\n<h1>Splitting concerns into functions</h1>\n<p>Currently, your main program does it all. Consider splitting it out into the following functions:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>class Program\n{\n static void ReadExcelFile(string fileName, List&lt;User&gt; usersList)\n {\n // ...\n }\n\n static void ReadAllExcelFilesInDirectory(string path, List&lt;User&gt; usersList)\n {\n var dirInfo = new DirectoryInfo(path);\n var files = dirInfo.GetFiles(&quot;*.xlsx&quot;);\n foreach (var file in files)\n ReadExcelFile(file.FullName, usersList);\n }\n\n static async void InsertUsersIntoDatabase(List&lt;User&gt; usersList)\n {\n // ...\n }\n\n static async Task Main(string[] args)\n {\n var usersList = new List&lt;User&gt;();\n ReadAllExcelFilesInDirectory(@&quot;C:\\Test&quot;, usersList);\n InsertUsersIntoDatabase(usersList);\n }\n}\n</code></pre>\n<h1>Opening the database connection</h1>\n<p>Here you have mixed up <code>conn</code> and <code>connString</code>.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var conn = ConfigurationManager.ConnectionStrings[&quot;Development&quot;].ConnectionString;\nawait using var connString = new SqlConnection(conn);\nconnString.Open();\n</code></pre>\n<p>The following would have made much more sense:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var connString = ConfigurationManager.ConnectionStrings[&quot;Development&quot;].ConnectionString;\nusing var conn = new SqlConnection(connString);\nawait conn.OpenAsync();\n</code></pre>\n<h1>BulkWriter</h1>\n<p>I think you are overcomplicating things here. The following is much simpler and easier to read:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>class BulkWriter\n{\n public static async Task InsertAsync&lt;T&gt;(IEnumerable&lt;T&gt; items, string tableName, SqlConnection connection,\n CancellationToken cancellationToken)\n {\n using var bulk = new SqlBulkCopy(connection);\n await using var reader = ObjectReader.Create(items);\n bulk.DestinationTableName = tableName;\n var properties = typeof(T).GetProperties();\n foreach (var prop in properties)\n bulk.ColumnMappings.Add(new SqlBulkCopyColumnMapping(prop.Name, prop.Name));\n await bulk.WriteToServerAsync(reader, cancellationToken);\n }\n}\n</code></pre>\n<p>You can actually remove the whole <code>BulkWriter</code> class and simply make <code>InsertAsync</code> a method of <code>Program</code></p>\n<h1>Unused variables</h1>\n<p>Right at the top on <code>Main</code>, you have this line that does not do anything:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>string s = null;\n</code></pre>\n<h1>Final thoughts</h1>\n<p>Every time you make an asynchronous call, you immediately use <code>await</code> to block execution until it is done. Is it really worth it?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T16:31:43.487", "Id": "532905", "Score": "0", "body": "Thank you for your thoughts, I will try **splitting concerns into functions** and **bulkwriter** simplification." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T14:31:33.290", "Id": "269979", "ParentId": "269875", "Score": "3" } } ]
{ "AcceptedAnswerId": "269979", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T12:56:42.207", "Id": "269875", "Score": "2", "Tags": [ "c#", "excel", ".net-core" ], "Title": "Reading excel files and save data into database" }
269875
<p>my models</p> <pre><code>class AssessmentTest(BasicModel): title = models.CharField(max_length=120, unique=True) class UserTestResult(BasicModel): assessment_test = models.ForeignKey(AssessmentTest, on_delete=models.CASCADE, related_name='users_passed') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='test_results') points = models.PositiveIntegerField(default=0) </code></pre> <p>my views</p> <pre><code>class AssessmentTestView(ReadOnlyModelViewSet): serializer_class = AssessmentTestSerializer queryset = AssessmentTest.objects.all() </code></pre> <p>my serializers</p> <pre><code>class AssessmentTestListSerializer(serializers.ModelSerializer): class Meta: model = AssessmentTest fields = [ 'id', 'title', 'user_results', ] user_results = serializers.SerializerMethodField() def get_user_results(self, obj: AssessmentTest): user = self.context['request'].user if not user.is_anonymous: test_result = UserTestResult.objects.filter(assessment_test=obj, user=user) if test_result: return UserTestResultSerializer(instance=test_result.last()).data return None </code></pre> <p>When I try to get all tests, in <code>get_user_results</code> I face n+1 problem (for every test there is extra query to UserTestResult)</p> <p>Can I somehow avoid this? Maybe it's possible to use prefetch_related on reverse foreign_key in queryset? Or not? Can someone help?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T14:32:10.863", "Id": "532621", "Score": "0", "body": "Looks like that should be a nested serialiser to me - you're embedding the results for `UserTest` in `AssessmentTest`. Take a look at the [docs](https://www.django-rest-framework.org/api-guide/relations/#nested-relationships) on the subject if you wish." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T23:49:20.660", "Id": "532676", "Score": "0", "body": "Is this piece of code working as intended to the best of your knowledge ? If not, it is [off-topic](https://codereview.stackexchange.com/tour) here and Stackoverflow would be the place to post this. Then some more context would be welcome ie showing a data sample that illustrates the problem, and the expect result." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T13:46:33.527", "Id": "269877", "Score": "1", "Tags": [ "python", "django" ], "Title": "Reduce db queries" }
269877
<p>I am writing my own parser for fasta format. I can't use Biopython or anything else, because it's a part of an assigment and our teacher wants us to try to do it manually. For now, I have done this:</p> <pre><code>def read_file(fasta_file): &quot;Parse fasta file&quot; count = 0 headers = [] sequences = [] aux = [] with open(&quot;yeast.fna&quot;, 'r') as infile: for line in infile: record = line.rstrip() if record and record[0] == '&gt;': headers.append(record[1:]) if count &gt; 0: sequences.append(''.join(aux)) aux = [] else: aux.append(record) count += 1 sequences.append(''.join(aux)) return headers, sequences headers, sequences = read_file(&quot;yeast.fna&quot;) lengths = 0 countN = 0 acum = 0 lengths = [] n = 0 lengths = [len(entry) for entry in sequences] count = sum(lengths) seqlengths = [entry for entry in sequences] countN = [entry.count(&quot;N&quot;) + entry.count(&quot;n&quot;) for entry in sequences] print(&quot;\nTotal length of the assembly : &quot;, count) print(&quot;\n Total number of unsequenced nucleotides (Ns) in the assembly : &quot;, countN) #arrange the secq sizes in decrossing order all_len = sorted(lengths, reverse=True) print(all_len) #Search for size accumulation until the size is &lt;= half the size for y in range (len(lengths)): if acum &lt;= count/2: acum = all_len[y] + acum n = y #L50 n = n + 1 # because the vector begin by a 0 print(&quot;The L50 is&quot;, n) print(&quot;The N50 is&quot;, all_len[n-1]) #Seq is n-1 because vector begin in 0 </code></pre> <p>As you can see this parser does some basic stats like calculating L50, ... But the problem with this parser is that it is not very universal since I designed it for the assembled genome of S. Cerivisae which has 17 chromosomes. I know that the best way to do a universal effective parser is to use a dictionary (and make 2 dictionaries).</p> <p>Can you help me with that?</p> <hr /> <p>Here is a sample of input file <code>yeast.fna</code>. It is basically a txt file with headers which begin by a <code>&gt;</code> followed by the dna sequences. I just copy part of it because it's a very big txt file with 17 chromosomes sequences (each one has it own header).</p> <pre><code>&gt;NC_001133.9 Saccharomyces cerevisiae S288C chromosome I, complete sequence ccacaccacacccacacacccacacaccacaccacacaccacaccacacccacacacacacatCCTAACACTACCCTAAC ACAGCCCTAATCTAACCCTGGCCAACCTGTCTCTCAACTTACCCTCCATTACCCTGCCTCCACTCGTTACCCTGTCCCAT TCAACCATACCACTCCGAACCACCATCCATCCCTCTACTTACTACCACTCACCCACCGTTACCCTCCAATTACCCATATC &gt;NC_001134.8 Saccharomyces cerevisiae S288C chromosome II, complete sequence AAATAGCCCTCATGTACGTCTCCTCCAAGCCCTGTTGTCTCTTACCCGGATGTTCAACCAAAAGCTACTTACtaccttta ttttatgtttactttttatagGTTGTCTTTTTATCCCACTTCTTCGCACTTGTCTCTCGCTACTGCCGTGCAACAAACAC TAAATcaaaacaatgaaataCTACTACATCAAAACGCATTTTccctagaaaaaaaattttcttacAATATACTATACTAC ACAATACATAATCACTGACTTTCgtaacaacaatttccttcacTCTCCAACTTCTCTGCTCGAATCTCTACatagtaata &gt;NC_001148.4 Saccharomyces cerevisiae S288C chromosome XVI, complete sequence AAATAGCCCTCATGTACGTCTCCTCCAAGCCCTGTTGTCTCTTACCCGGATGTTCAACCAAAAGCTACTTACtaccttta ttttatgtttactttttatagaTTGTCTTTTTATCCTACTCTTTCCCACTTGTCTCTCGCTACTGCCGTGCAACAAACAC TAAATCAAAACAGTGAAATACTACTACATCAAAACGCATATTccctagaaaaaaaaatttcttacaATATACTATACTAC </code></pre> <p>Here is my output when I run my code :</p> <pre><code>Total length of the assembly : 12157105 Total number of unsequenced nucleotides (Ns) in the assembly : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1531933, 1091291, 1090940, 1078177, 948066, 924431, 813184, 784333, 745751, 666816, 576874, 562643, 439888, 316620, 270161, 230218, 85779] The L50 is 6 The N50 is 924431 </code></pre> <p>Everything is okay but I need to make a more universal fasta parser which doesn't work only for my specific input file with 17 chromosome. In order to do that I have to use dictionary but I really don't know how to do that. You can also download the <a href="https://www.ncbi.nlm.nih.gov/genome/15?genome_assembly_id=22535" rel="nofollow noreferrer">full input file</a>. At the top of the page in line &quot;Download sequences in FASTA format for genome, transcript, protein&quot; you click on &quot;genome&quot; and you will download the file which is zipped.</p>
[]
[ { "body": "<p>Your <code>read_file</code> returns headers and sequences implicitly correlated by their order. A model that is easier to work with is to make sequence class instances that each have their own header and sequence string.</p>\n<p>If you accept <code>fasta_file</code>, then why do you hard-code <code>yeast.fna</code>?</p>\n<p><code>yeast.fna</code>'s original name is <code>GCF_000146045.2_R64_genomic.fna</code>. It seems unwise to discard this information, unless perhaps <code>yeast.fna</code> is a symlink.</p>\n<p>This code is not just a parser - it does a little bit of analysis. Ensure that your parsing code and analysis code are separated, and that neither leaks into the global namespace.</p>\n<p>Separate your summary calculation from your summary printing.</p>\n<p>As to your concern that</p>\n<blockquote>\n<p>it is not very universal since I designed it for the assembled genome of S. Cerivisae which has 17 chromosomes.</p>\n</blockquote>\n<p>I don't see where you've hard-coded 17 chromosomes, so (apart from other design concerns) this doesn't seem like a problem.</p>\n<blockquote>\n<p>I know that the best way to do a universal effective parser is to use a dictionary (and make 2 dictionaries).</p>\n</blockquote>\n<p>I don't think so. Prefer class instances rather than dictionaries for internal data.</p>\n<p>Consider making two lightweight classes - one for each sequence, and one for the assembly overall.</p>\n<p>You should do some basic parsing of your header - the first field is the ID, and the rest of the string is the description.</p>\n<p>I have validity concerns about the way that you measure unsequenced data. Part of the problem seems to be with the format itself, but part of the problem looks to be with your parser, because it doesn't pay attention to <code>X</code> or <code>-</code>.</p>\n<p>Consider using Python's built-in <code>gzip</code> support and operating on that archive directly rather than decompressing it on the file system.</p>\n<p>Introduce PEP484 type hinting to your code.</p>\n<p>You have descriptive headings for almost all of your summary fields - good! Add one for your <code>all_len</code>.</p>\n<h2>Suggested</h2>\n<p>This suggested code exclusively uses modules that are built into Python 3.9.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import gzip\nfrom io import StringIO\nfrom itertools import accumulate\nfrom typing import Iterator, NamedTuple, Optional, Tuple\n\n\nclass FastaSequence(NamedTuple):\n identifier: str\n description: str\n sequence: str\n\n @staticmethod\n def parse_lines(lines: Iterator[str]) -&gt; Tuple[\n str, # sequence\n Optional[str], # next header\n ]:\n next_header: Optional[str] = None\n\n def iterate():\n nonlocal next_header\n for line in lines:\n line = line.rstrip()\n if line.startswith('&gt;'):\n next_header = line\n break\n yield line\n\n return ''.join(iterate()), next_header\n\n @classmethod\n def from_file(cls, in_file: Iterator[str]) -&gt; Iterator['FastaSequence']:\n header = next(in_file).rstrip()\n while True:\n identifier, description = header[1:].split(maxsplit=1)\n sequence, next_header = cls.parse_lines(in_file)\n yield cls(identifier, description, sequence)\n if next_header is None:\n break\n header = next_header\n\n @property\n def n_unsequenced(self) -&gt; int:\n # This is problematic and probably wrong, because documentation like\n # http://genetics.bwh.harvard.edu/pph/FASTA.html\n # says that X or - could also indicate unsequenced data, and N might\n # also just mean 'asparagine'.\n # - in particular indicates that this count is only a lower bound as the\n # gap is of indeterminate length.\n return sum(\n 1 for x in self.sequence\n if x.lower() in {'n', 'x', '-'}\n )\n\n\nclass FastaAssembly:\n def __init__(self, sequences: Tuple[FastaSequence]) -&gt; None:\n self.sequences = sequences\n \n self.sequence_lengths = sorted(\n (len(seq.sequence) for seq in self.sequences),\n reverse=True,\n )\n self.length = sum(self.sequence_lengths)\n index_50 = self.half_length\n self.l50 = index_50 + 1\n self.n50 = self.sequence_lengths[index_50]\n\n @property\n def half_length(self) -&gt; int:\n for i, total in enumerate(accumulate(self.sequence_lengths)):\n if total &gt; self.length/2:\n return i\n raise IndexError() # This will never happen\n\n @classmethod\n def from_file(cls, in_file: Iterator[str]) -&gt; 'FastaAssembly':\n return cls(tuple(FastaSequence.from_file(in_file)))\n\n @property\n def summary(self) -&gt; str:\n unsequenced = [seq.n_unsequenced for seq in self.sequences]\n return (\n f'Total length of the assembly: {self.length}'\n f'\\nTotal number of unsequenced nucleotides (Ns) in the assembly: {unsequenced}'\n f'\\nAll sequence lengths: {self.sequence_lengths}'\n f'\\nThe L50 is {self.l50}'\n f'\\nThe N50 is {self.n50}'\n )\n\n\nEXAMPLE = \\\n'''&gt;NC_001133.9 Saccharomyces cerevisiae S288C chromosome I, complete sequence\nccacaccacacccacacacccacacaccacaccacacaccacaccacacccacacacacacatCCTAACACTACCCTAAC\nACAGCCCTAATCTAACCCTGGCCAACCTGTCTCTCAACTTACCCTCCATTACCCTGCCTCCACTCGTTACCCTGTCCCAT\nTCAACCATACCACTCCGAACCACCATCCATCCCTCTACTTACTACCACTCACCCACCGTTACCCTCCAATTACCCATATC\n&gt;NC_001134.8 Saccharomyces cerevisiae S288C chromosome II, complete sequence\nAAATAGCCCTCATGTACGTCTCCTCCAAGCCCTGTTGTCTCTTACCCGGATGTTCAACCAAAAGCTACTTACtaccttta\nttttatgtttactttttatagGTTGTCTTTTTATCCCACTTCTTCGCACTTGTCTCTCGCTACTGCCGTGCAACAAACAC\nTAAATcaaaacaatgaaataCTACTACATCAAAACGCATTTTccctagaaaaaaaattttcttacAATATACTATACTAC\nACAATACATAATCACTGACTTTCgtaacaacaatttccttcacTCTCCAACTTCTCTGCTCGAATCTCTACatagtaata\n&gt;NC_001148.4 Saccharomyces cerevisiae S288C chromosome XVI, complete sequence\nAAATAGCCCTCATGTACGTCTCCTCCAAGCCCTGTTGTCTCTTACCCGGATGTTCAACCAAAAGCTACTTACtaccttta\nttttatgtttactttttatagaTTGTCTTTTTATCCTACTCTTTCCCACTTGTCTCTCGCTACTGCCGTGCAACAAACAC\nTAAATCAAAACAGTGAAATACTACTACATCAAAACGCATATTccctagaaaaaaaaatttcttacaATATACTATACTAC\n'''\n\n\ndef test() -&gt; None:\n with StringIO(EXAMPLE) as f:\n assembly = FastaAssembly.from_file(f)\n print(assembly.summary)\n print()\n\n with gzip.open('GCF_000146045.2_R64_genomic.fna.gz', 'rt') as f:\n assembly = FastaAssembly.from_file(f)\n print(assembly.summary)\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n<h2>Output</h2>\n<pre class=\"lang-none prettyprint-override\"><code>Total length of the assembly: 800\nTotal number of unsequenced nucleotides (Ns) in the assembly: [0, 0, 0]\nAll sequence lengths: [320, 240, 240]\nThe L50 is 2\nThe N50 is 240\n\nTotal length of the assembly: 12157105\nTotal number of unsequenced nucleotides (Ns) in the assembly: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\nAll sequence lengths: [1531933, 1091291, 1090940, 1078177, 948066, 924431, 813184, 784333, 745751, 666816, 576874, 562643, 439888, 316620, 270161, 230218, 85779]\nThe L50 is 6\nThe N50 is 924431\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T02:25:35.490", "Id": "532760", "Score": "0", "body": "may i ask why you used `NamedTuple` instead of dataclasses ? Is it just for unpacking namedtuples or it has more advantages in this case? Thanks!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T02:29:49.217", "Id": "532761", "Score": "1", "body": "@AlexDotis Named tuples are naturally immutable and have a simpler API than dataclasses." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T17:26:46.500", "Id": "269927", "ParentId": "269880", "Score": "2" } } ]
{ "AcceptedAnswerId": "269927", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T15:11:55.457", "Id": "269880", "Score": "1", "Tags": [ "python", "parsing", "homework", "bioinformatics" ], "Title": "Python Fasta Parser using dictionaries without using BioPython or other external libraries" }
269880