body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I'm writing a ReST API Client Tester using VueJS.</p> <p>I'm trying to have a really clean code, But I feel like it's too much,</p> <p>Here is my <code>store.js</code> file, which I use it for Vuex and the application state management, all there variables I use to send a request are store here</p> <pre><code>import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { globals: { methods: ['GET', 'POST', 'PUT', 'DELETE'], }, request: { method: 'GET', url: 'http://example.com', body: {}, headers: {}, }, }, mutations: { // Change Methods changeMethod(state, method) { state.request.method = method; }, changeURL(state, url) { state.request.url = url; }, changeBody(state, body) { state.request.body = body; }, changeHeaders(state, headers) { state.request.headers = headers; }, // Add to Data Methods addToHeaders(state, payload) { state.request.headers[payload.key] = payload.value; }, addToBody(state, payload) { state.request.body[payload.key] = payload.value; }, // Delete from Data Methods deleteFromHeaders(state, key) { delete state.request.headers[key]; }, deleteFromBody(state, key) { delete state.request.body[key]; }, // Reset Methods resetMethod(state) { state.request.method = 'GET'; }, resetURL(state) { state.request.url = ''; }, resetBody(state) { state.request.body = {}; }, resetHeaders(state) { state.request.headers = {}; }, // Reset request Method resetRequest(state) { state.request = { method: 'GET', url: '', body: {}, headers: {}, }; }, }, actions: { }, }); </code></pre> <p>As you can see, I'm sticking to a rule which says, each function should only do one thing and nothing more, I'm not sure if I'm using it right or now, But with this amount of code, It seems a little ridiculous to me...</p> <p>Let me know what you think? How can I improve this to have more readability and less LoC?</p> <p>Am I doing it right or not?</p>
[]
[ { "body": "<p>Overall, your code seems okay if you have UI elements setting each of these attributes. If you are solely setting these requests in one go with code, having separate mutations is overkill and probably unnecessary.</p>\n\n<p>I think there are some things you can improve though.</p>\n\n<h2>Reactivity</h2>\n\n<p>The new key-value pairs you add to <code>headers</code> and <code>body</code> are not reactive, because it is not possible to detect addition of new keys in Objects via native methods. I strongly recommend to use <code>Vue.set(..)</code> and <code>Vue.delete(..)</code> when dealing with objects.</p>\n\n<h2>Default</h2>\n\n<p>You have a reset function that has the same payload as found under the default state. Consider factoring out this part and copying it everytime you need a new state. You need to keep in mind that you require a deep copy to get this to work.</p>\n\n<h2>LoC</h2>\n\n<p>You can potentially decrease the number of lines of code by creating a generator function that generates your mutations. The thing with a generator function is that it adds an extra layer of abstraction, and will likely make your code less readable than it is now. I don't think factoring out the mutations you have here into a generator function is very helpful either.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T22:44:15.913", "Id": "208576", "ParentId": "208112", "Score": "2" } } ]
{ "AcceptedAnswerId": "208576", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T08:41:37.063", "Id": "208112", "Score": "2", "Tags": [ "javascript", "vue.js" ], "Title": "VueJS ReST Client: Vuex Store Methods" }
208112
<p>Here is a type trait which - I feel - could fit in <code>std</code> next to <a href="https://en.cppreference.com/w/cpp/types/add_cv" rel="nofollow noreferrer"><code>std::add_const</code></a> and <a href="https://en.cppreference.com/w/cpp/types/remove_cv" rel="nofollow noreferrer"><code>std::remove_const</code></a>:</p> <pre><code>#include &lt;type_traits&gt; template &lt;typename T&gt; struct set_constness_of { template &lt;typename U&gt; struct by { using type = typename std::conditional&lt; std::is_const&lt;U&gt;::value, typename std::add_const&lt;T&gt;::type, typename std::remove_const&lt;T&gt;::type &gt;::type; }; }; </code></pre> <p>Note this is intentionally C++11 to minimize requirements for using it. One can obviously define <code>set_constness_of_t</code> in which <code>by</code> is a type rather than a struct with a type.</p> <p>I've also written a tiny <a href="http://coliru.stacked-crooked.com/a/264f7c3ecf3aabee" rel="nofollow noreferrer">sample program</a> (coliru.com) to ensure it runs, at least for some cases. </p> <pre><code>/* the above definition of set_constness_of goes here (paste it) */ #inlcude &lt;iostream&gt; struct foo { void m() { std::cout &lt;&lt; "Non-const\n"; } void m() const { std::cout &lt;&lt; "Const\n"; } }; template &lt;class T&gt; void call_m() { T().m(); } int main() { call_m&lt;foo&gt;(); using bar = const int; call_m&lt; set_constness_of&lt;foo&gt;::by&lt;bar&gt;::type &gt;(); } </code></pre> <p>Questions:</p> <ul> <li>Is this correctly defined for all cases?</li> <li>What do you think about placing the second template parameter as an inner struct's template param, rather than having two template parameters on the outer struct?</li> <li>What do you think about the choice of naming?</li> </ul> <p>Other comments are welcome.</p>
[]
[ { "body": "<p>I don't see any obvious omissions or bugs.</p>\n\n<p>The naming and inner struct are neatly expressive (and remind me of some testing frameworks' precondition/assertion chaining). It's not something that's done by the standard library, but I don't think it should be hugely controversial.</p>\n\n<p>I might go with a naming like <code>copy_const&lt;foo&gt;::from&lt;bar&gt;</code> - or perhaps even the other way around: <code>copy_const&lt;bar&gt;::to&lt;foo&gt;</code>. Or even both! (Actually, I now wish <code>std::is_assignable</code> worked like that - it would be easier to remember which parameter is which!)</p>\n\n<p>None of the above is a concrete suggestion - intended merely as food for thought!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T19:23:22.083", "Id": "402052", "Score": "0", "body": "If find the second version very fluent! Or maybe something like `constness_from<foo>::to<bar>`. There's a lot of valid option. A strawpoll might be nice :p" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T21:58:57.870", "Id": "402083", "Score": "0", "body": "`copy_const` sounds like \"copy constructor\"..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T22:13:01.743", "Id": "402086", "Score": "0", "body": "@Calak: See my answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T19:00:36.907", "Id": "208176", "ParentId": "208121", "Score": "3" } }, { "body": "<p>Following @Calak's comment, I'm now thinking of the following change of order of the template parameters:</p>\n\n<pre><code>#include &lt;type_traits&gt;\n\ntemplate &lt;typename U&gt;\nstruct constness_of { \n enum { value = std::is_const&lt;U&gt;::value };\n template &lt;typename T&gt;\n struct applied_to {\n using type = typename std::conditional&lt;\n value,\n typename std::add_const&lt;T&gt;::type,\n typename std::remove_const&lt;T&gt;::type\n &gt;::type;\n };\n#if __cplusplus &gt;= 201402L\n template &lt;typename U&gt;\n using applied_to_t = typename applied_to&lt;U&gt;::type;\n#endif\n};\n</code></pre>\n\n<p>Which would be used as follows:</p>\n\n<pre><code>if (constness_of&lt;bar&gt;::value) { std::cout &lt;&lt; \"bar is const!\\n\"; }\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>using altered_foo = constness_of&lt;bar&gt;::applied_to&lt;foo&gt;::type;\nusing altered_foo_2 = constness_of&lt;bar&gt;::applied_to_t&lt;foo&gt;;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T22:12:47.383", "Id": "208195", "ParentId": "208121", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T10:10:41.330", "Id": "208121", "Score": "5", "Tags": [ "c++", "template", "type-safety", "casting", "constants" ], "Title": "add_const or remove_const based on another type" }
208121
<p>I have a table with courses. The user that is currently logged in can mark these courses as <em>attended</em> and <em>unattended</em>. There can be multiple rows selected. </p> <blockquote> <p>The logic for this row selecting looks like this:</p> <ul> <li>It's not possible to select courses which you have <em>attended</em> when there are <em>unattended</em> courses selected. This works vica versa.</li> <li>When a unattended course is selected, a button for attending this course will be enabled.</li> <li>When a attended course is selected, a button for unattending this course will be enabled.</li> <li>For every row, the checkbox which is inside the table will be checked.</li> </ul> </blockquote> <p>What I currently ended up with is this:</p> <pre><code>/** * The form for handling requests * * @type {jQuery|HTMLElement} */ const form = $('#attendCourseForm'); /** * The buttons for attending a course * * @type {jQuery|HTMLElement} */ const courseFollowButton = $('#courseFollowButton'), courseUnFollowButton = $('#courseUnfollowButton'); /** * Selecting rows */ form.on('click', 'tbody tr', select); /** * Select the course rows */ function select() { const $this = $(this), attended = $this.hasClass('attendedCourse'), siblings = $this.siblings(); let toggle = 'table-active', button = courseFollowButton; // Prevent selecting more types if (attended) { if (siblings.hasClass('table-active')) { return; } toggle = 'table-secondary'; button = courseUnFollowButton; } else if (!attended &amp;&amp; siblings.hasClass('table-secondary')) { return; } $this.toggleClass(toggle); // Toggle the checkbox let checkbox = $this.children().last().find('input[type=checkbox]'); checkbox.prop('checked', $this.hasClass(toggle)); // Turn buttons on and off let hasToggleClass = $this.hasClass(toggle) || siblings.hasClass(toggle); button.prop('disabled', !hasToggleClass); } </code></pre> <p>This looks like a mess to me. Can this be done any better?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T10:52:16.583", "Id": "208124", "Score": "1", "Tags": [ "javascript", "jquery", "ecmascript-6" ], "Title": "Selecting rows on condition in a table" }
208124
<p>I am beginning to learn Python on my own through edX and I was given this basic problem: "Given a list of cities, separate the list into two lists, namely one with cities containing the letter 'a' in their name and one with cities not containing the letter 'a'."</p> <p>This is my approach. It works, but I can't help but feel like there is a much more concise way to get this result. If anybody could offer some other methods I would be interested:</p> <pre><code>cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paulo", "Hyderabad"] a_city, no_a_city = [],[] for city in cities: for x in range(0, len(city)): if city[x] == "a": a_city.append(city) break else: if x == len(city) - 1: no_a_city.append(city) print("a_city:", a_city) print("no_a_city:", no_a_city) </code></pre> <p>I am also interested in learning more about the interaction between nested loops/conditionals and complexity if anybody has some resources.</p>
[]
[ { "body": "<p>This usecase is actually covered by one of the <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"noreferrer\"><code>itertools</code> recipes</a>. <code>itertools</code> is a package in the Python standard library that supplies fast and efficient tools for iterating over things or creating certain iterable things (like the combination of all pairs and such). It is an often used library and well worth it to get acquainted with.</p>\n\n<p>The recipe is as follows:</p>\n\n<blockquote>\n<pre><code>from itertools import filterfalse, tee\n\ndef partition(pred, iterable):\n 'Use a predicate to partition entries into false entries and true entries'\n # partition(is_odd, range(10)) --&gt; 0 2 4 6 8 and 1 3 5 7 9\n t1, t2 = tee(iterable)\n return filterfalse(pred, t1), filter(pred, t2)\n</code></pre>\n</blockquote>\n\n<p>In your specific case you would use it like this:</p>\n\n<pre><code>if __name__ == \"__main__\": \n cities = [\"New York\", \"Shanghai\", \"Munich\", \"Tokyo\", \"Dubai\", \"Mexico City\", \"São Paulo\", \"Hyderabad\"]\n no_a_city, a_city = map(list, partition(lambda city: \"a\" in city, cities))\n print(\"a_city:\", a_city)\n print(\"no_a_city:\", no_a_city)\n</code></pre>\n\n<p>The <code>map(list, ...)</code> part is needed because what the <code>partition</code> function returns are <a href=\"https://wiki.python.org/moin/Generators\" rel=\"noreferrer\">generators</a> that generate values on the fly. They can be consumed into a <code>list</code>.</p>\n\n<p>The predicate used is a <a href=\"https://www.w3schools.com/python/python_lambda.asp\" rel=\"noreferrer\"><code>lambda</code> function</a>, an anonymous function which in this case returns truthy or falsy values. It is used to test each element of the iterable.</p>\n\n<p>Instead of manually iterating over each name (even worse, over each index of each name, have a look at <a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"noreferrer\">Loop Like A Native</a>), I used the fact that strings support the <code>in</code> operator.</p>\n\n<p>I also added a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script from another script.</p>\n\n<hr>\n\n<p>One thing you could have used in your code is the fact that <a href=\"http://book.pythontips.com/en/latest/for_-_else.html\" rel=\"noreferrer\"><code>for</code> loops have an optional <code>else</code> clause</a> which is run if no <code>break</code> statement interrupted the loop:</p>\n\n<pre><code>a_city, no_a_city = [],[]\nfor city in cities:\n for char in city:\n if char == \"a\":\n a_city.append(city)\n break\n else:\n no_a_city.append(city)\n</code></pre>\n\n<hr>\n\n<p>As for complexity, this has the same complexity as your code. You have two nested <code>for</code> loops, making this on average <span class=\"math-container\">\\$\\mathcal{O}(nk)\\$</span> with <span class=\"math-container\">\\$n\\$</span> being the number of cities and <span class=\"math-container\">\\$k\\$</span> being the average length of the city names.</p>\n\n<p>The <code>in</code> operator for strings is <span class=\"math-container\">\\$\\mathcal{O}(k)\\$</span> (it is just the same loop you wrote, but probably written in C) and it is used once per city. However, due to the <code>tee</code> my code iterates twice over the cities, so would be <span class=\"math-container\">\\$\\mathcal{O}(2nk)\\$</span>, which in terms of algorithmic complexity is also <span class=\"math-container\">\\$\\mathcal{O}(nk)\\$</span>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T13:07:38.390", "Id": "401916", "Score": "1", "body": "Thank you Graipher,\n\nThat is a lot to take in for a beginner, but I will work on dissecting some of it to improve my coding. I briefly checked out that link that you provided and already see some issues with what I am doing (as you pointed out, iterating over each name AND each index of each name) so thanks for that. You've given me a lot to look into. \n\nOn complexity: using the link that you provided, I can see a way to write this same code using only one for loop. Does this imply that it is less complex than your code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T13:24:40.513", "Id": "401920", "Score": "1", "body": "@JacobCheverie: Yes, there is still some road left ahead of you, but don't despair. And no, just because there is only one visible `for` loop does not make it linear in time (my solution has no visible `for` loop and yet it is not). I cannot think of a way that does not have to look at each character of each city name, but maybe you are more clever than I." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T18:51:04.630", "Id": "402186", "Score": "0", "body": "I'm not convinced that this approach makes sense; the main benefit of working with generators is a small memory footprint which is completely comprised by the use of `tee`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T12:42:35.967", "Id": "208134", "ParentId": "208130", "Score": "15" } }, { "body": "<p>This is not a complete review, but rather two simpler alternatives that illustrate how you can cut the some of the inner control flow using the <code>in</code> keyword. This keyword tests for membership of an object in an iterable. In this case, you want to test for membership of <code>'a'</code> in the name of each element of <code>cities</code>.</p>\n\n<p>The first takes the same approach as your code</p>\n\n<pre><code>cities = [\"New York\", \"Shanghai\", \"Munich\", \"Tokyo\", \"Dubai\", \"Mexico City\", \"São Paulo\", \"Hyderabad\"]\n\na_city, no_a_city = [],[]\nfor city in cities:\n if 'a' in city:\n a_city.append(city)\n else:\n no_a_city.append(city)\n\nprint(\"a_city:\", a_city)\nprint(\"no_a_city:\", no_a_city)\n</code></pre>\n\n<p>The membership test using <code>in</code> is a drop-in replacement for the harder-to-read and more error-prone explicit loop over the characters.</p>\n\n<p>An even cleaner solution makes use of the built-in <code>set</code> data type. In simplistic terms, a <code>set</code> is like a <code>list</code>, except that it is not ordered and does not contain duplicates. </p>\n\n<pre><code># a set is constructed with {}, unlike the the [] used for lists\ncities = {\"New York\", \"Shanghai\", \"Munich\", \"Tokyo\", \"Dubai\", \"Mexico City\", \"São Paulo\", \"Hyderabad\"}\n\n# we can also construct one using the `set` builtin function (analogous to `list`)\na_city = set(city for city in cities if 'a' in city)\n\n# subtracting one set from another is well-defined and does the obvious thing\nno_a_city = cities - a_city\n\n\nprint(\"a_city:\", a_city)\nprint(\"no_a_city:\", no_a_city)\n</code></pre>\n\n<p>Check out <a href=\"https://docs.python.org/3/tutorial/datastructures.html#sets\" rel=\"noreferrer\">the docs</a> for a flavor of the kinds of rich membership and comparison that sets allow. These operations can typically be expected to be more efficient than equivalent algorithms on lists, mainly due to the fact that sets are guaranteed not to have duplicate elements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T18:09:18.250", "Id": "402031", "Score": "0", "body": "Thanks @Endulum, I like the set approach. I can see where I would have to be careful using this, however. If I was not guaranteed to have distinct members then I assume that the set approach would discard some information and thus not be appropriate. When you define a_city, do I read this as I would read a mathematical set (set of all 'city' such that for 'city' in 'cities' if 'a' in 'city')? Without reading as so, it appears to me as a typo." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T18:19:33.840", "Id": "402033", "Score": "1", "body": "Regarding the appropriateness of sets versus dictionaries: yes, if is desirable that you retain duplicates, then a set is likely not the right collection to choose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T18:26:32.800", "Id": "402034", "Score": "1", "body": "Regarding the relationship to mathematical set notation, it should be read like (the set of all 'city' in 'cities' such that 'a' in 'city'). It is an alternative syntax for consisely building lists, sets, or other collections without an explicit loop. It is called a \"comprehension\", in this case a \"set comprehension\". If you have not learned about these yet, I expect you will before long. They are very popular among Python programmers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T19:06:10.260", "Id": "402046", "Score": "0", "body": "I had touched on list comprehensions briefly last night while reading but I didn't recognize the form. I only asked about the relationship to mathematics because city is written twice at the start of the set definition which seems a bit hard to remember, but I think that this is just Python syntax I must get used to. Thanks again!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T16:29:22.300", "Id": "208167", "ParentId": "208130", "Score": "9" } }, { "body": "<p>The task here is to <em>collate</em> the list of cities according to a <em>key</em>. In this case the key can be <code>'a' in city</code>, which is <code>True</code> if the city contains <code>'a'</code> and <code>False</code> otherwise.</p>\n\n<p>It's common to encounter processing tasks which require collation, for example to <a href=\"https://codereview.stackexchange.com/a/187465/11728\">find words that are anagrams of each other</a> we could collate the words in a dictionary according to their sorted letters.</p>\n\n<p>There is a standard pattern for collation in Python, which is to use <a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"noreferrer\"><code>collections.defaultdict</code></a> and a loop. In the cities case, it goes like this:</p>\n\n<pre><code>from collections import defaultdict\nwith_a = defaultdict(list)\nfor city in cities:\n with_a['a' in city].append(city)\n</code></pre>\n\n<p>After running this loop, <code>with_a[True]</code> is the list of cities with <code>'a'</code> and <code>with_a[False]</code> is the list of cities without.</p>\n\n<p>I prefer this approach to <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"noreferrer\"><code>itertools.partition</code></a> because it iterates over the input just once (whereas <code>partition</code> iterates over the input twice), and it's clear how to generalize it to other kinds of key.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T18:15:18.650", "Id": "402032", "Score": "0", "body": "This is seemingly high-powered. I will look into defaultdict some more to gain a better understanding of the code. When you mention your preference of this over partition, does that imply that this would be a more efficient/less complex approach?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T18:47:34.523", "Id": "402185", "Score": "1", "body": "+1 Imo, this approach is easier to digest, and has better space and time complexity than the `itertools.partition` approach." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T16:54:39.960", "Id": "208169", "ParentId": "208130", "Score": "12" } }, { "body": "<p><a href=\"https://www.pythonforbeginners.com/basics/list-comprehensions-in-python\" rel=\"nofollow noreferrer\">List comprehensions</a> are very well-suited for this task. The basic syntax is the following:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>new_list = [ expression(x) for x in old_list if condition(x) ]\n</code></pre>\n\n<p>In this case we don't want to change the list elements, simply select them according to a condition. What should be this condition? Well, Python also provides a simple syntax to check if a string (or a list) contains an element, with the keyword <code>in</code>,or <code>not in</code> for the negation (this is the same keyword used for iterationg through a list, so be careful to not get confused).</p>\n\n<p>With these tools, your code can fit on two lines, with no import required:</p>\n\n<pre><code>a_city = [ city for city in cities if \"a\" in city ]\nno_a_city = [ city for city in cities if \"a\" not in city ]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T10:22:10.877", "Id": "208222", "ParentId": "208130", "Score": "4" } } ]
{ "AcceptedAnswerId": "208134", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T12:19:32.137", "Id": "208130", "Score": "7", "Tags": [ "python", "python-3.x" ], "Title": "Divide a set of strings into those which contain \"a\" and those which don't" }
208130
<p>I have a function in a project that I feel could be written better. The purpose of the function is to return the direction of an arrow based on two parameters.</p> <ul> <li><strong><code>positiveDirection</code></strong>: The direction for a positive result. The values could be <code>increasing</code> or <code>decreasing</code>.</li> <li><strong><code>changeType</code></strong>: Whether the result was <code>positive</code>, <code>negative</code> or <code>no-change</code>.</li> </ul> <p>I guess it's the <code>if</code> statement that is bothering me the most; it looks like it could be reduced based on some logic gate that I don't know of.</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> getArrowDirection = (positiveDirection, changeType) =&gt; { let direction = null if(changeType === 'no-change') { return direction } if( (changeType === 'positive' &amp;&amp; positiveDirection === 'increasing') || (changeType === 'negative' &amp;&amp; positiveDirection === 'decreasing') ) { direction = 'up-arrow' } else if( (changeType === 'positive' &amp;&amp; positiveDirection === 'decreasing') || (changeType === 'negative' &amp;&amp; positiveDirection === 'increasing') ) { direction = 'down-arrow' } return direction }</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:16:27.790", "Id": "401940", "Score": "0", "body": "What's possible values for `changeValue` and `positiveDirection`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T15:23:45.573", "Id": "401978", "Score": "0", "body": "We might be able to improve the code further if we knew the context. Who calls this code, and where do the parameter values come from?" } ]
[ { "body": "<p>You could could extract your conditions into functions with very clear condition description names. Would cut down the code because many of those conditions are repeated.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T13:09:12.387", "Id": "208139", "ParentId": "208133", "Score": "0" } }, { "body": "<p>The test for <code>if(changeType === 'no-change') {</code> is redundant and not needed as it will fall through if the other tests fail and return <code>null</code> anyways.</p>\n\n<p>You could also break the statement up returning the result as needed and falling through if they fail for <code>null</code>.</p>\n\n<pre><code>const getArrowDirection = (dir, type) =&gt; {\n if (type === \"positive\") {\n if (dir === \"increasing\") { return \"up-arrow\" }\n if (dir === \"decreasing\") { return \"down-arrow\" }\n }else if (type === \"negative\") {\n if (dir === \"increasing\") { return \"down-arrow\" }\n if (dir === \"decreasing\") { return \"up-arrow\" }\n }\n return null;\n}\n</code></pre>\n\n<p>Assuming that you have given all possible values you can make assumptions and reduce the code further </p>\n\n<pre><code>const getArrowDirection = (dir, type) =&gt; {\n if (type !== 'no-change') {\n if (type === \"positive\") { return dir === \"increasing\" ? \"up-arrow\" : \"down-arrow\" }\n return dir === \"increasing\" ? \"down-arrow\" : \"up-arrow\";\n }\n return null; // returning null is not the best. Returning undefined would\n // be better and would not need this line\n}\n</code></pre>\n\n<p>You can use an object as a lookup using the combined strings.</p>\n\n<pre><code>const getArrowDirection = (() =&gt; {\n const directions = {\n positiveincreasing: \"up-arrow\",\n negativedecreasing: \"up-arrow\",\n positivedecreasing: \"down-arrow\",\n negativeincreasing: \"down-arrow\",\n };\n return (dir, type) =&gt; directions[type + dir] ? directions[type + dir] : null;\n})();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T13:11:31.110", "Id": "208142", "ParentId": "208133", "Score": "4" } }, { "body": "<p>We don't need the <code>direction</code> variable - we can simply return at the appropriate point.</p>\n\n<p>Once you know that <code>changeType</code> is one of <code>'positive'</code> or <code>'negative'</code> and that <code>positiveDirection</code> is either <code>'increasing'</code> or <code>'decreasing'</code>, you can test whether the two equality tests match:</p>\n\n<pre><code>// Winging it, because this isn't my language!\ngetArrowDirection = (positiveDirection, changeType) =&gt; {\n\n if (changeType != 'positive' &amp;&amp; changeType != 'negative') {\n return null;\n }\n if (positiveDirection != 'increasing' &amp;&amp; positiveDirection != 'decreasing')\n return null;\n }\n\n if ((changeType === 'positive') == (positiveDirection === 'increasing')) {\n return 'up-arrow';\n else\n return 'down-arrow';\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:17:36.730", "Id": "208150", "ParentId": "208133", "Score": "2" } }, { "body": "<p>If <code>changeValue</code> can only be (after your early check for '<code>no-change</code>') equal to 'positive' or 'negative' and <code>positiveDirection</code> can only be equal to 'increasing' or 'decreasing, your <code>if</code> should cover all possible ways.</p>\n\n<p>But you can simplify it a lot making use of the xor operator:</p>\n\n<pre><code> direction = (changeType === 'positive' ^ positiveDirection === 'decreasing')\n ? 'up-arrow'\n : 'down-arrow';\n</code></pre>\n\n<p>Or make the whole function a one-liner:</p>\n\n<pre><code>return (changeType !== 'no-change')\n ? ((changeType === 'positive' ^ positiveDirection === 'decreasing') ? 'up-arrow' : 'down-arrow')\n : null;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T15:21:51.707", "Id": "401977", "Score": "0", "body": "This is slick. Definitely a better solution than my original code. The ^ syntax was something I didn't know about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T15:32:35.170", "Id": "401982", "Score": "0", "body": "Given `A^B`, if `A` and `B` are either both `true` or `false`, returns `false`. Otherwise, returns `true`. If fact, you can also replace it with `!=` but I found the logic xor prettier/smarter :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:43:49.343", "Id": "208156", "ParentId": "208133", "Score": "3" } } ]
{ "AcceptedAnswerId": "208156", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T12:40:38.570", "Id": "208133", "Score": "1", "Tags": [ "javascript", "ecmascript-6" ], "Title": "Function to determine the direction of an arrow" }
208133
<p>This is my solution to <a href="https://leetcode.com/problems/valid-sudoku/" rel="nofollow noreferrer">LeetCode – Valid Sudoku</a> in Swift.</p> <p><a href="https://i.stack.imgur.com/AfNGL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AfNGL.png" alt="img"></a></p> <pre><code>class Solution { func isValidSudoku(_ board: [[Character]]) -&gt; Bool { let count = board.count var set = Set&lt;Character&gt;() for i in 0..&lt;count{ // firstly set = Set(board[i]) var num = board[i].reduce(0 , {(result : Int, char : Character) in var cent = 0 if String(char) == "."{ cent = 1 } return result + cent }) if num &gt; 0 , count - num != set.count - 1{ return false } else if num == 0, set.count != count{ return false } // secondly set = Set(board.reduce([Character]() , { resultArray, chars in return resultArray + [chars[i]] })) num = board.reduce(0 , {(result : Int, chars : [Character]) in var cent = 0 if String(chars[i]) == "."{ cent = 1 } return result + cent }) if num &gt; 0 , count - num != set.count - 1{ return false } else if num == 0, set.count != count{ return false } // thirdly let characters = board.flatMap{ return $0 } let fisrtMiddle = ( i/3 ) * 27 + ( i % 3 ) * 3 + 1 let secondMiddle = fisrtMiddle + 9 let thirdMiddle = fisrtMiddle + 18 let arrayThree = [characters[fisrtMiddle - 1], characters[fisrtMiddle], characters[fisrtMiddle + 1], characters[secondMiddle - 1], characters[secondMiddle], characters[secondMiddle + 1], characters[thirdMiddle - 1], characters[thirdMiddle], characters[thirdMiddle + 1]] set = Set(arrayThree) num = arrayThree.reduce(0 , {(result : Int, char : Character) in var cent = 0 if String(char) == "."{ cent = 1 } return result + cent }) if num &gt; 0 , count - num != set.count - 1{ return false } else if num == 0, set.count != count{ return false } } return true } } </code></pre> <p>How can I make it shorter in syntax and keep intuitive, like the following Python code?</p> <pre><code>def isValidSudoku(self, board): seen = sum(([(c, i), (j, c), (i/3, j/3, c)] for i, row in enumerate(board) for j, c in enumerate(row) if c != '.'), []) return len(seen) == len(set(seen)) </code></pre> <p>The Python code is very Pythonic and short.</p> <p>How to use Swift syntax power to make my code shorter?</p> <p>I think Functional is a good choice. RxSwift is welcomed.</p>
[]
[ { "body": "<h3>Naming</h3>\n\n<p>Some variable names should be more descriptive: </p>\n\n<ul>\n<li>What does <code>set</code> contain?</li>\n<li>What does <code>num</code> count?</li>\n<li>What is <code>cent</code> or <code>arrayThree</code>?</li>\n</ul>\n\n<h3>Simplifications</h3>\n\n<p><code>if String(char) == \".\"</code> can be shorted to <code>if char == \".\"</code>, the conversion to\na string is not needed because <code>\".\"</code> can be both a string literal and a\ncharacter literal.</p>\n\n<p>In </p>\n\n<pre><code>var num = board[i].reduce(0 , {(result : Int, char : Character)\n in\n var cent = 0\n if String(char) == \".\"{\n cent = 1\n }\n return result + cent\n})\n</code></pre>\n\n<p>the closure can be shortened to</p>\n\n<pre><code>var num = board[i].reduce(0 , {(result, char) in\n char == \".\" ? result + 1 : result\n})\n</code></pre>\n\n<p>without the need for a temporary variable.</p>\n\n<p>In</p>\n\n<pre><code>set = Set(board.reduce([Character]() , { resultArray, chars in\n return resultArray + [chars[i]]\n}))\n</code></pre>\n\n<p>an array is created with the elements in column #i, and put into a set. That can be simplified to</p>\n\n<pre><code>let column = board.map { $0[i]} // Column #i\nset = Set(column)\n</code></pre>\n\n<p>and <code>column</code> can then also be used in the following count of empty fields.</p>\n\n<p>The creation of an array of all entries of a block can be simplified using\narray slices:</p>\n\n<pre><code>let firstRow = 3 * (i / 3)\nlet firstCol = 3 * (i % 3)\nlet block = board[firstRow..&lt;firstRow+3].flatMap { $0[firstCol..&lt;firstCol+3]}\n</code></pre>\n\n<p>Generally, the check for duplicate digits in a row/column/block can\nbe simplified if you filter out empty fields <em>before</em> creating the set,\nthat makes counting the empty fields obsolete.</p>\n\n<h3>Comments</h3>\n\n<p>The comments</p>\n\n<pre><code>// firstly\n// secondly\n// thirdly\n</code></pre>\n\n<p>are not really helpful. </p>\n\n<h3>Putting it together</h3>\n\n<p>Summarizing the above suggestions so far, the code could look like this:</p>\n\n<pre><code>class Solution {\n func isValidSudoku(_ board: [[Character]]) -&gt; Bool {\n\n for i in 0..&lt;9 {\n // Check digits in row #i:\n let rowDigits = board[i].filter { $0 != \".\" }\n if rowDigits.count != Set(rowDigits).count {\n return false\n }\n\n // Check digits in column #i:\n let colDigits = board.map { $0[i] }.filter { $0 != \".\" }\n if colDigits.count != Set(colDigits).count {\n return false\n }\n\n // Check digits in block #i:\n let firstRow = 3 * (i / 3)\n let firstCol = 3 * (i % 3)\n let blockDigits = board[firstRow..&lt;firstRow+3].flatMap { $0[firstCol..&lt;firstCol+3]}\n .filter { $0 != \".\" }\n if blockDigits.count != Set(blockDigits).count {\n return false\n } \n }\n\n return true\n }\n}\n</code></pre>\n\n<h3>An alternative approach</h3>\n\n<p>The Python solution can not be translated directly to Swift, one reason is\nthat tuples are not <code>Hashable</code> and therefore cannot be put into a set.\nAlso inhomogeneous collections are better avoided in Swift.</p>\n\n<p>But we <em>can</em> enumerate the board in a similar fashion, and put each element\ninto a set corresponding to its row, column, and block. The return value\nfrom the <code>insert</code> statement already indicates if an identical element was\nalready present.</p>\n\n<p>That leads to the following implementation:</p>\n\n<pre><code>class Solution {\n func isValidSudoku(_ board: [[Character]]) -&gt; Bool {\n var rowSets = Array(repeating: Set&lt;Character&gt;(), count: 9)\n var colSets = Array(repeating: Set&lt;Character&gt;(), count: 9)\n var blockSets = Array(repeating: Set&lt;Character&gt;(), count: 9)\n\n for (i, row) in board.enumerated() {\n for (j, char) in row.enumerated() where char != \".\" {\n if !rowSets[i].insert(char).inserted {\n return false\n }\n if !colSets[j].insert(char).inserted {\n return false\n }\n let block = (i / 3) + 3 * (j / 3)\n if !blockSets[block].insert(char).inserted {\n return false\n }\n }\n }\n\n return true\n }\n}\n</code></pre>\n\n<p>I haven't checked which one is more efficient, I leave that task to you :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T01:43:20.513", "Id": "402100", "Score": "0", "body": "The latter one gets better performance. It takes 316 ms to pass 504 test case in Leetcode. And the prior one takes 356 ms. It is heard that `functional languages are a bad fit for high performance computing: they’re high-level, rely on garbage collection, are pretty inflexible about memory layouts and don’t permit all the low-level optimizations you need to maximize performance.`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T01:50:59.517", "Id": "402101", "Score": "0", "body": "Wondering where to find the syntax ‘set.inserted’ . I did not googled it yet. And not see it in [doc](https://developer.apple.com/documentation/swift/set). And it works" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T06:21:35.013", "Id": "402113", "Score": "1", "body": "@dengApro: That overview page does not show the return values of the methods. If you go to [`Set.insert(_:)`](https://developer.apple.com/documentation/swift/set/1541375-insert) then you see that the method returns a tuple whose first member `.inserted` indicates if the member was already present or not." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T21:28:08.603", "Id": "208191", "ParentId": "208136", "Score": "1" } }, { "body": "<h2>Alternative solution</h2>\n\n<p>Here is the (current) fastest solution. It is pretty straightforward :</p>\n\n<p><strong>1-</strong> First off, let's model the Sudoku grid :\nA row is a set of unique digits from 0 to 9, represented by characters. The rows all together, will be represented by an array of those sets :</p>\n\n<pre><code>var rows = Array(repeating: Set&lt;Character&gt;(), count: 9)\n</code></pre>\n\n<p><code>rows</code> is mutable since we'll be filling those initially empty sets.</p>\n\n<p><strong>2-</strong> The same goes for the columns :</p>\n\n<pre><code>var columns = Array(repeating: Set&lt;Character&gt;(), count: 9)\n</code></pre>\n\n<p><strong>3-</strong> A 3x3 box will be modeled by a set of characters. Three boxes on the same horizontal line will be represented by an array of 3 boxes (3 sets of characters). 3 of those arrays make a whole Sudoku grid :</p>\n\n<pre><code>var boxes = Array(repeating: Array(repeating: Set&lt;Character&gt;(), count: 3), count: 3)\n</code></pre>\n\n<p><strong>4-</strong> Then, we loop through all the \"rows\" and \"columns\" inside of <code>board</code> :</p>\n\n<pre><code>for row in 0..&lt;9 {\n for column in 0..&lt;9 {\n let value = board[row][column]\n ...\n }\n}\n</code></pre>\n\n<p><strong>5-</strong> If a cell is not empty :</p>\n\n<pre><code>let value = board[row][column]\n\nif value != \".\" {\n ...\n}\n</code></pre>\n\n<p><strong>6-</strong> ... we try to insert it into a cell. A cell belongs to a row, a column, and a box. Three checks have to be made: If either the row, or the column, or the box already contains that character, return <code>false</code>. </p>\n\n<p>To do this we use the pretty handy <code>inserted</code> element from the tuple returned by the <a href=\"https://developer.apple.com/documentation/swift/set/1541375-insert\" rel=\"nofollow noreferrer\"><code>insert(_:)</code></a> method :</p>\n\n<pre><code>if !rows[row].insert(value).inserted\n || !columns[column].insert(value).inserted\n || !boxes[row/3][column/3].insert(value).inserted {\n return false\n}\n</code></pre>\n\n<hr>\n\n<p>Here is the complete solution :</p>\n\n<pre><code>class Solution {\n func isValidSudoku(_ board: [[Character]]) -&gt; Bool {\n var rows = Array(repeating: Set&lt;Character&gt;(), count: 9)\n var columns = Array(repeating: Set&lt;Character&gt;(), count: 9)\n var boxes = Array(repeating: Array(repeating: Set&lt;Character&gt;(), count: 3), count: 3)\n\n for row in 0..&lt;9 {\n for column in 0..&lt;9 {\n let value = board[row][column]\n\n if value != \".\" {\n if !rows[row].insert(value).inserted\n || !columns[column].insert(value).inserted\n || !boxes[row/3][column/3].insert(value).inserted {\n return false\n }\n }\n }\n }\n\n return true\n }\n}\n</code></pre>\n\n<p>It's execution time is <code>204 ms</code> on LeetCode :</p>\n\n<p><a href=\"https://i.stack.imgur.com/pFpWh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pFpWh.png\" alt=\"100%\"></a></p>\n\n<p>Compared to <code>212 ms</code> for the alternative approach given in the accepted answer (which is faster than 70.73%)</p>\n\n<hr>\n\n<h2>Playing golf</h2>\n\n<p>If you're looking for a short, <em>Pythony</em>, solution, (not necessarily the fastest), then here is a solution :</p>\n\n<pre><code>class Solution {\n func isValidSudoku(_ board: [[Character]]) -&gt; Bool {\n var seen: [String] = []\n for (i, row) in board.enumerated() {\n for case let (j, c) in row.enumerated() where c != \".\" {\n seen.append(contentsOf: [\"r\\(i)\\(c)\", \"c\\(j)\\(c)\", \"b\\(i/3)\\(j/3)\\(c)\"])\n }\n }\n return seen.count == Set(seen).count\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T23:22:51.790", "Id": "210774", "ParentId": "208136", "Score": "0" } } ]
{ "AcceptedAnswerId": "208191", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T12:55:13.583", "Id": "208136", "Score": "2", "Tags": [ "programming-challenge", "swift", "sudoku" ], "Title": "Valid Sudoku in Swift" }
208136
<p>I have this following code which find every possible pair of numbers that sum up to n number</p> <pre><code>lst = [int(input()) for i in range(int(input()))] num = int(input()) #Amount to be matched cnt = 0 lst = list(filter(lambda i: i &lt;= num, lst)) #Remove number that more than `num` for i in lst: for j in lst: if i+j == num: cnt += 1 print(int(cnt/2)) </code></pre> <p>For example, if I enter</p> <pre><code>5 #How many numbers 1 &lt; #Start of number input 4 &lt; 5 7 1 &lt; #End of number input 5 #Amount to be matched </code></pre> <p>It will return 2 because there is two pair that their sum is equal to 5 (1,4) and (4,1) (The number I marked with &lt; ).</p> <p>The problem is the complexity is O(n<sup>2</sup>) which will run slow on large input. I wanted to know if that is there a way to make this run faster?</p> <p>Another example:</p> <pre><code>10 #How many numbers 46 #Start of number input 35 27 45 16 0 &lt; 30 &lt; 30 &lt; 45 37 #End of number input 30 #Amount to be matched </code></pre> <p>The pair will be (0, 30) and (0, 30) which will return 2.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T13:37:05.847", "Id": "401923", "Score": "3", "body": "If you store them in a `set` you can, for each number entered, find if `amount - number` is in the set. If you ask user to enter `amount` BEFORE entering all the numbers, you can do it in realtime so that by the moment user enters the last number you'll already know all the appropriate pairs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T16:28:14.397", "Id": "402001", "Score": "1", "body": "@phwt - that's true only if no numbers appear more than once. There's a bit more work involved in the general case - see my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T20:01:14.927", "Id": "402061", "Score": "0", "body": "Are the numbers in the list all *non-negative integers*? Do you know anything about the maximum value of those integers?" } ]
[ { "body": "<p>Removing numbers greater than the target affects the correctness of this program - they could be added to negative numbers to reach the target.</p>\n\n<p>You could get a performance improvement by finding the difference between each element and the target, then looking to see if that difference is in the list. This doesn't in itself reduce the computational complexity (it's still <strong>O(<em>n</em>²)</strong>), but we can build on that: if the list is first sorted, and we then use a binary search to test membership we get to <strong>O(<em>n</em> log <em>n</em>)</strong>; if we convert to a structure with fast lookup (such as a <code>collections.​Counter</code>, which has amortized O(1) insertion and lookup), then we come down to <strong>O(<em>n</em>)</strong>.</p>\n\n<p>If we have a <code>Counter</code>, then we can account for all combinations of that pair by multiplying one count by the other (but we'll need to consider the special case that the number is exactly half the target).</p>\n\n<p>We could do with some auto tests. Consider importing the <code>doctest</code> module and using it. Some good test cases to include:</p>\n\n<pre><code>1, [] → 0\n1, [1] → 0\n1, [0, 1] → 1\n0, [-1, 1] → 1\n0, [0, 1] → 0\n4, [1, 4, 3, 0] → 2\n4, [1, 1, 3, 3] → 4\n4, [2, 2, 2, 2] → 6\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T13:25:13.257", "Id": "208143", "ParentId": "208138", "Score": "10" } }, { "body": "<p>Other minor suggestions:</p>\n\n<ul>\n<li>Don't leave your <code>input()</code>s blank. Pass a prompt so that the user knows what they're entering.</li>\n<li>The first time you initialize <code>lst</code>, it doesn't need to be memory; it can be left as a generator (parens instead of brackets).</li>\n<li>The second time you initialize <code>lst</code>, it does not need to be mutable, so make it a <code>tuple</code> instead of a <code>list</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:17:07.103", "Id": "208149", "ParentId": "208138", "Score": "2" } }, { "body": "<p>You can use a sorting algorithm to first sort the list, this can be done (in many ways) with a complexity of O(nlog(n)).\nOnce the list is sorted (small to large for example), the problem can be solved with complexity O(n) as followed:</p>\n\n<pre><code>head = 0\ntail = len(list) - 1\nwhile (head &lt; tail):\n sum = list[head] + list[tail]\n if sum == num:\n cnt += 1\n head += 1\n tail -= 1\n elif sum &gt; num:\n tail -= 1\n else:\n head += 1\n</code></pre>\n\n<p>This results in an overall complexity of O(nlog(n))</p>\n\n<p>Note : This runs under the assumption that all elements are unique. This can be easily fixed depending on how you want to handle cases with duplicate elements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T20:17:23.387", "Id": "402062", "Score": "1", "body": "Since the sample given by the original poster indicates that the elements are not unique, you do need to handle duplicates." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T20:17:51.097", "Id": "402063", "Score": "0", "body": "There is a linear time solution, which I've given in my answer. See if you can find it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T10:03:35.080", "Id": "402249", "Score": "0", "body": "@EricLippert With an ideal map implementation there is a linear time solution. Unfortunately python's map does not guarantee constant time reads or writes, the worst case time for reads and writes are linear with respect to the size of the map which makes the worst case total time for an algorithm using maps to be O(n^2)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T16:16:05.143", "Id": "208166", "ParentId": "208138", "Score": "2" } }, { "body": "<p>So far every solution given has been O(n<sup>2</sup>) or O(n log n), but there is an O(n) solution, which is sketched as follows:</p>\n\n<ul>\n<li>Get your input into a list, as you have done so. Obviously this is O(n)</li>\n<li>Create an empty map from integers to integers. The map must have an O(1) insertion operation and an O(1) contains-key operation and an O(1) lookup operation and an O(n) \"enumerate all the keys\" operation. Commonly-used map types in modern programming languages typically have these characteristics.</li>\n<li>Build a count of all the items in the input. That is, for each input item, check to see if it is in the map. If it is not, add the pair (item, 1) to the map. If it is already in the map, look up the associated value and change the map so that it has the pair (item, value + 1). All those operations are O(1) and we do them n times, so this step is O(n).</li>\n<li>Now we take our target, call it <code>sum</code> and we wish to enumerate the pairs which add to that target. Enumerate the keys of the map. Suppose the key is <code>k</code>. We compute <code>sum-k</code>. Now there are two cases. \n\n<ul>\n<li>Case 1: if <code>sum-k == k</code> then check the map to see if the value associated with <code>k</code> is 2 or greater. If it is, then we have a pair <code>(k, k)</code>. Output it.</li>\n<li>Case 2: if <code>sum-k</code> is not <code>k</code> then check the map to see if <code>sum-k</code> is in the map. If it is, then we have a pair <code>(k, sum-k)</code>.</li>\n</ul></li>\n<li>The enumeration enumerates at most <code>n</code> keys, and each step is O(1), so this step is also O(n)</li>\n<li>And we're done, with total cost O(n).</li>\n</ul>\n\n<p>Now, <strong>can you implement this solution?</strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T20:48:17.503", "Id": "402068", "Score": "0", "body": "I don't think that \"most\" map types have all the O(1) operations that you mention. They do have an *amortized* cost of O(1), though. Worst case scenario, they'll still be O(n)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T20:54:48.870", "Id": "402071", "Score": "1", "body": "@ChatterOne: \"Most\" was not intended to imply that I had done a survey and that 50%+1 or more met the criterion; I was speaking informally. But I am curious: can you give an example of a popular language with a popular mutable dictionary type where typical worst-case performance with *non-hostile* input is O(n)? Particularly if the keys are small integers, as is the case here. The C#, Java, Python, JavaScript dictionaries all have O(1) insertion and lookup when given realistic, non-hostile inputs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T20:58:50.137", "Id": "402073", "Score": "0", "body": "@ChatterOne: I note that the *sorted key* dictionary types and *immutable* dictionary types are typically balanced binaries trees behind the scenes, and so are O(lg n) on those operations, but here I am specifically interested in mutable unsorted dictionaries." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T21:26:32.757", "Id": "402076", "Score": "0", "body": "@EricLippert: Absent some other work-around, the O(n) insertion cost will be paid on each resize operation. Hence, ChatterOne is making the point that calling insertion an O(1) operation (i.e., without stating that this cost is amortized) is inaccurate even for non-hostile inputs. Per the last paragraph of [Dictionary.Add remarks](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.add?view=netframework-4.7.2#remarks), C# has the same cost. However, C# can avoid this cost by setting the initial capacity, a feature Python lacks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T21:29:56.943", "Id": "402077", "Score": "1", "body": "@Brian: Ah, I understand the point now, but I'm not sure why it is germane. First, because the algorithm I propose is O(n) whether or not the cost of a dictionary insertion is O(1) strictly, or O(1) amortized. And second, because as you note, *we know ahead of time a bound on the dictionary size*. And third, because we are cheerfully ignoring superlinearities in all manner of infrastructure, like the superlinear cost of garbage collections as data structures grow in an environment with collection pressure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T22:21:27.490", "Id": "402087", "Score": "0", "body": "That sounds exactly as I've described in my answer (except I took a more conservative estimate for inserting into a `collections.Counter`, based on C++ `std::map` performance - I've since been corrected, as I should have been thinking of `std::unordered_map`). You seem to have assumed we only need to count distinct pairs, but the last example in the question suggests otherwise (so when `sum-k == k`, we need to count `n*(n-1)/2` pairs, and otherwise `n*m` pairs, where `n` is `count[k]` and `m` is `count[sum-k]`)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T20:14:29.177", "Id": "208184", "ParentId": "208138", "Score": "6" } } ]
{ "AcceptedAnswerId": "208143", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T13:05:32.133", "Id": "208138", "Score": "8", "Tags": [ "python", "algorithm", "k-sum" ], "Title": "Find every possible pair of numbers that sum up to n number" }
208138
<p>This is my solution to <a href="https://leetcode.com/problems/minimum-area-rectangle/" rel="nofollow noreferrer">LeetCode – Minimum Area Rectangle</a> in Swift</p> <blockquote> <p><strong>939. Minimum Area Rectangle</strong></p> <p>Given a set of points in the xy-plane, determine the minimum area of a rectangle formed from these points, with sides parallel to the x and y axes.<br /> If there isn't any rectangle, return 0.</p> <ul> <li><strong>Example 1:</strong></li> </ul> <p>Input: <code>[[1,1],[1,3],[3,1],[3,3],[2,2]]</code></p> <p>Output: <code>4</code></p> <ul> <li><strong>Example 2:</strong></li> </ul> <p>Input: <code>[[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]</code></p> <p>Output: <code>2</code></p> </blockquote> <pre><code>class Solution { struct Point_Dng: Hashable{ var x: Int var y: Int init(_ x: Int, _ y: Int) { self.x = x self.y = y } var hashValue: Int{ return x * 100000 + y } static func == (_ lhs: Point_Dng, _ rhs: Point_Dng) -&gt; Bool{ return lhs.x == rhs.x &amp;&amp; lhs.y == rhs.y } } func minAreaRect(_ points: [[Int]]) -&gt; Int { let points_new = points.map({ (point: [Int]) -&gt; Point_Dng in return Point_Dng(point[0], point[1]) }) let set = Set(points_new) var ans = Int.max for point in points{ for point_piece in points{ if point[0] != point_piece[0] , point[1] != point_piece[1] , set.contains(Point_Dng(point[0], point_piece[1])) ,set.contains(Point_Dng(point_piece[0], point[1])) { ans = min(ans, abs((point_piece[1] - point[1] ) * (point_piece[0] - point[0]))) } } } if ans == Int.max { return 0 } else{ return ans } } } </code></pre> <blockquote> <p>Note:</p> <ol> <li><p><code>1 &lt;= points.length &lt;= 500</code></p> </li> <li><p><code>0 &lt;= points[i][0] &lt;= 40000</code></p> </li> <li><p><code>0 &lt;= points[i][1] &lt;= 40000</code></p> </li> <li><p>All points are distinct.</p> </li> </ol> </blockquote> <p>According to LeetCode's note, I improved the hash performance. I turned</p> <pre><code>var hashValue: Int{ return &quot;\(x)\(y)&quot;.hashValue } </code></pre> <p>into</p> <pre><code>var hashValue: Int{ return x * 100000 + y } </code></pre> <p>because Swift's tuple is not hashable. The prior one will lead to “Time Limit Exceeded”</p> <p>How can I improve it further?<br /> In fact I want to know is there something I missed in Swift.<br /> Something out of my knowledge.<br /> Because I did it simple.</p>
[]
[ { "body": "<h3>Naming</h3>\n\n<p>The meaning of some identifier names is hard to grasp:</p>\n\n<ul>\n<li>What does <code>Point_Dng</code> stand for? Why not simply <code>Point</code>?</li>\n<li>What is <code>point_piece</code> in the inner loop, and how is it different from \n<code>piece</code> from the outer loop?</li>\n<li><code>set</code> is too generic, what does it contain?</li>\n<li><code>ans</code> stands for “answer,” but actually contains the “minimal area” found so far.</li>\n</ul>\n\n<h3>Simplifications</h3>\n\n<p>As of Swift 4.2, the compiler automatically creates the required methods\nfor <code>Equatable</code> and <code>Hashable</code> conformance for a <code>struct</code> if all its member\nare <code>Equatable</code>/<code>Hashable</code>.</p>\n\n<p>A <code>struct</code> also has a default memberwise initializer if you don't define your\nown.</p>\n\n<p>The properties of a point are never mutated, so they can be declared as constants (with <code>let</code>). </p>\n\n<p>This makes the <code>struct Point</code> as simple as</p>\n\n<pre><code>struct Point: Hashable {\n let x: Int\n let y: Int\n}\n</code></pre>\n\n<p>The closure in</p>\n\n<pre><code>let points_new = points.map({ (point: [Int]) -&gt; Point_Dng in\n return Point_Dng(point[0], point[1])\n})\n</code></pre>\n\n<p>can be simplified because the compiler can infer the argument type and the\nreturn type automatically. Since the array is only needed for creating the\nset, the assignments can be combined into one:</p>\n\n<pre><code>let pointSet = Set(points.map { point in Point(x: point[0], y: point[1]) })\n</code></pre>\n\n<h3>Performance improvements</h3>\n\n<p>In the nested loop it suffices to consider only those pairs where one point\nis the “lower left” and the other the “upper right” corner of a potential\nrectangle. That reduces the number of tests, and makes the <code>abs()</code> call\nredundant.</p>\n\n<h3>Putting it together</h3>\n\n<p>The following version was roughly twice as fast in my tests with \nrandom arrays of 500 points (on a 3.5 GHz Intel Core i5 iMac, compiled\nin Release mode, i.e. with optimizations):</p>\n\n<pre><code>class Solution {\n struct Point: Hashable {\n let x: Int\n let y: Int\n }\n\n func minAreaRect(_ points: [[Int]]) -&gt; Int {\n let pointSet = Set(points.map { point in Point(x: point[0], y: point[1]) })\n\n var minArea = Int.max\n for lowerLeft in points {\n for upperRight in points {\n if upperRight[0] &gt; lowerLeft[0]\n &amp;&amp; upperRight[1] &gt; lowerLeft[1]\n &amp;&amp; pointSet.contains(Point(x: lowerLeft[0], y: upperRight[1]))\n &amp;&amp; pointSet.contains(Point(x: upperRight[0], y: lowerLeft[1])) {\n\n let area = (upperRight[0] - lowerLeft[0]) * (upperRight[1] - lowerLeft[1])\n minArea = min(minArea, area)\n }\n }\n }\n\n return minArea == Int.max ? 0 : minArea\n }\n}\n</code></pre>\n\n<h3>Further suggestions</h3>\n\n<p>Sorting the point array in increasing order of x-coordinates would allow to\nfind “lower left/upper right” pairs faster, potentially increasing the \nperformance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T10:29:35.197", "Id": "402383", "Score": "1", "body": "Design: Should `minAreaRect(_:)` be a class/static function? Would a struct `Solution ` be preferable to a class?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T10:50:35.270", "Id": "402385", "Score": "0", "body": "@Carpsen90: Generally yes, but the class and the instance method is *given* on the LeetCode problem page https://leetcode.com/problems/minimum-area-rectangle/ when you submit a solution in Swift." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T19:55:10.307", "Id": "208181", "ParentId": "208141", "Score": "2" } }, { "body": "<h2>Alternative Approach</h2>\n\n<p>Here is an alternative implementation that is currently the fastest on LeetCode:</p>\n\n<p><strong>1-</strong> First, let's create two dictionaries, one all for the abscissae (x-axis) and the other for the ordinates (y-axis) :</p>\n\n<pre><code>var xAxisDictionary: [Int:Set&lt;Int&gt;] = [:]\nvar yAxisDictionary: [Int:Set&lt;Int&gt;] = [:]\n</code></pre>\n\n<p>Each dictionary will store the indices of the elements of <code>points</code> that have a certain coordinate. Abscissae are the keys of <code>xAxisDictionary</code>. Ordinates are the keys of <code>yAxisDictionary</code>.</p>\n\n<p><strong>2-</strong> <code>pointsCoordinates</code> will store unique strings that would represent points, this is faster than creating a struct and relying on the automatic hashing system:</p>\n\n<pre><code>var pointsCoordinates: Set&lt;String&gt; = []\n</code></pre>\n\n<p>Using a set rather than an array gives better execution time. In fact, if an array is used, the time limit would be exceeded. As shown by the following graph, <code>Array.contains</code> is faster for less than 16 elements. <code>SortedArray.contains</code> would be the fastest from approximately 16 up to 256 elements. <code>Set.contains</code> is the fastest from 256 up to 500 points : </p>\n\n<p><a href=\"https://i.stack.imgur.com/unKRm.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/unKRm.jpg\" alt=\"Contains\"></a></p>\n\n<p><strong>3-</strong> <code>indicesToConsider</code> is a set of indices of points that may be part of a rectangle :</p>\n\n<pre><code>var indicesToConsider: Set&lt;Int&gt; = []\n</code></pre>\n\n<p><strong>4-</strong> Let's fill the dictionaries:</p>\n\n<pre><code>for (index, point) in points.enumerated() {\n if var set = xAxisDictionary[point[0]] {\n set.insert(index)\n xAxisDictionary[point[0]] = set\n } else {\n xAxisDictionary[point[0]] = Set([index])\n }\n\n if var set = yAxisDictionary[point[1]] {\n set.insert(index)\n yAxisDictionary[point[1]] = set\n } else {\n yAxisDictionary[point[1]] = Set([index])\n }\n}\n</code></pre>\n\n<p>Notice that optional binding is done using <code>if var</code> for <code>set</code> to be mutable.</p>\n\n<p><strong>5-</strong> Then, we only keep points that may be part of a rectangle :</p>\n\n<pre><code>for (_, indicesSet) in xAxisDictionary {\n // A vertical side of a rectangle, as described in this problem, has to have two points with the same x coordinate\n if indicesSet.count &lt; 2 {\n continue\n }\n\n // Likewise, a horizontal side of a rectangle, as described in this problem, has to have two points with the same y coordinate\n for pointIndex in indicesSet {\n if yAxisDictionary[points[pointIndex][1]]!.count &gt; 1 {\n indicesToConsider.insert(pointIndex)\n pointsCoordinates.insert(\"\\(points[pointIndex][0])_\\(points[pointIndex][1])\")\n }\n }\n}\n</code></pre>\n\n<p>Force-unwrapping is safe here, it serves also for brevity.</p>\n\n<p><strong>6-</strong> Let's traverse the considered indices from smallest to largest :</p>\n\n<pre><code>let indicesToConsiderArray = indicesToConsider.sorted()\n</code></pre>\n\n<p>Using a sorted array makes a 500ms difference on LeetCode. </p>\n\n<p><strong>7-</strong> Initially, we'll consider that the minimum area is as big as possible :</p>\n\n<pre><code>var result = Int.max\n</code></pre>\n\n<p>The maximum value of <code>result</code> is <code>40_000 * 40_000</code> since all the coordinates belong to the interval [0, 40000]. </p>\n\n<p>On LeetCode, defining <code>result</code> as an integer, initially equal to <code>Int.max</code>, was little bit faster than: defining <code>result</code> as an optional integer initially equal to <code>nil</code>, updating it using <code>result = min(abs((x2 - x1) * (y2 - y1)), result ?? Int.max)</code>, and returning <code>result ?? 0</code>.</p>\n\n<p><strong>8-</strong> Now, traverse the <code>indicesToConsiderArray</code>, and calculate the area of the rectangle which is confined between a bottom left corner, and a top right corner :</p>\n\n<pre><code>for pointIndex in indicesToConsiderArray {\n let x1 = points[pointIndex][0]\n let y1 = points[pointIndex][1]\n let xPeers = xAxisDictionary[x1]!\n let yPeers = yAxisDictionary[y1]!\n\n for xPeer in xPeers {\n if xPeer &lt;= pointIndex {\n continue\n }\n let y2 = points[xPeer][1]\n for yPeer in yPeers {\n if yPeer &lt;= pointIndex {\n continue\n }\n let x2 = points[yPeer][0]\n if pointsCoordinates.contains(\"\\(x2)_\\(y2)\") {\n result = min(abs((x2 - x1) * (y2 - y1)), result)\n }\n }\n }\n}\n</code></pre>\n\n<p>Looping through <code>xPeers</code> (or <code>yPeers</code>) could also be written this way : </p>\n\n<pre><code>for case let xPeer in xPeers where xPeer &gt; pointIndex { ... }\n</code></pre>\n\n<p>Meanwhile, we update <code>result</code> if a smaller area is found.</p>\n\n<p><strong>9-</strong> At the end of our function, if the value of <code>result</code> isn't changed, then we'll return <code>0</code>, meaning that no rectangle can be formed using <code>points</code> : </p>\n\n<pre><code>return result &lt; Int.max ? result : 0\n</code></pre>\n\n<hr>\n\n<p>For convenience, here is the whole solution :</p>\n\n<pre><code>class Solution {\n func minAreaRect(_ points: [[Int]]) -&gt; Int {\n var xAxisDictionary: [Int:Set&lt;Int&gt;] = [:]\n var yAxisDictionary: [Int:Set&lt;Int&gt;] = [:]\n var pointsCoordinates: Set&lt;String&gt; = []\n var indicesToConsider: Set&lt;Int&gt; = []\n\n for (index, point) in points.enumerated() {\n if var set = xAxisDictionary[point[0]] {\n set.insert(index)\n xAxisDictionary[point[0]] = set\n } else {\n xAxisDictionary[point[0]] = Set([index])\n }\n\n if var set = yAxisDictionary[point[1]] {\n set.insert(index)\n yAxisDictionary[point[1]] = set\n } else {\n yAxisDictionary[point[1]] = Set([index])\n }\n }\n\n for (_, indicesSet) in xAxisDictionary {\n if indicesSet.count &lt; 2 {\n continue\n }\n\n for pointIndex in indicesSet {\n if yAxisDictionary[points[pointIndex][1]]!.count &gt; 1 {\n indicesToConsider.insert(pointIndex)\n pointsCoordinates.insert(\"\\(points[pointIndex][0])_\\(points[pointIndex][1])\")\n }\n }\n }\n\n let indicesToConsiderArray = indicesToConsider.sorted()\n\n var result = Int.max\n\n for pointIndex in indicesToConsiderArray {\n let x1 = points[pointIndex][0]\n let y1 = points[pointIndex][1]\n let xPeers = xAxisDictionary[x1]! //Force unwrapping is safe here\n let yPeers = yAxisDictionary[y1]! //and here\n\n for xPeer in xPeers {\n if xPeer &lt;= pointIndex {\n continue\n }\n let y2 = points[xPeer][1]\n for yPeer in yPeers {\n if yPeer &lt;= pointIndex {\n continue\n }\n let x2 = points[yPeer][0]\n if pointsCoordinates.contains(\"\\(x2)_\\(y2)\") {\n result = min(abs((x2 - x1) * (y2 - y1)), result)\n }\n }\n }\n }\n\n return result &lt; Int.max ? result : 0\n }\n}\n</code></pre>\n\n<p>The execution time on LeetCode is <code>1472 ms</code> :</p>\n\n<p><a href=\"https://i.stack.imgur.com/szZYD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/szZYD.png\" alt=\"100%\"></a></p>\n\n<p>Compared to <code>3404 ms</code> for the accepted answer (which is faster than 0.00%)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-02T23:07:29.730", "Id": "210772", "ParentId": "208141", "Score": "1" } } ]
{ "AcceptedAnswerId": "208181", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T13:10:17.630", "Id": "208141", "Score": "1", "Tags": [ "programming-challenge", "swift" ], "Title": "Minimum Area Rectangle in Swift" }
208141
<p>This question has a second part here:</p> <p><a href="https://codereview.stackexchange.com/questions/208220/comparing-columns-from-two-csv-files-2">Comparing columns from two CSV files - follow-up</a></p> <p>I'm currently trying to compare two CSV files column by column but only when their indexes match.</p> <p>Here is what I've done:</p> <pre><code>import sys def get_column(columns, name): count = 0 columns = columns.split(';') for column in columns: array = list(column) if(array[0] == '"'): array[0] = '' if(array[len(column) - 1] == '"'): array[len(column) - 1] = '' column = ''.join(array) if column != name: count += 1 else: return(count) def set_up_file(file, variable): columns = next(file) siren_pos = get_column(columns, 'INDEX1') nic_pos = get_column(columns, 'INDEX2') variable_pos = get_column(columns, variable) return(siren_pos, nic_pos, variable_pos) def test_variable(variable): with open('source.csv', 'r') as source: sir_s, nic_s, comp_s = set_up_file(source, variable) with open('tested.csv', 'r') as tested: sir_t, nic_t, comp_t = set_up_file(tested, variable) correct = 0 memory = 0 for row_s in source: row_s = row_s.split(';') tested.seek(0, 0) count = 0 for row_t in tested: count += 1 if(count &gt;= memory): row_t = row_t.split(';') if(row_s[sir_s] == row_t[sir_t] and row_s[nic_s] == row_t[nic_t]): if(row_s[comp_s] == row_t[comp_t]): correct += 1 memory = count break tested.seek(0, 0) print(correct / sum(1 for line in tested) * 100) def main(): test_variable('VARIABLE_TO_COMPARE') if(__name__ == "__main__"): main() </code></pre> <p>This script is running into some performance issue and I would like to know how to make it run faster / make it more readable.</p>
[]
[ { "body": "<p>First I'd like to call out the good things that you've done:</p>\n\n<ul>\n<li>Writing functions, including a standard <code>main()</code>.</li>\n<li>Having more or less sensible function and variable names.</li>\n<li>Proper use of <code>with</code>.</li>\n</ul>\n\n<p>An improvement here is to stop parsing the file yourself, and to start parsing it with Python's native <code>csv</code> library. Even though your format is <em>not</em> technically CSV (it's separated by semicolon), you can still configure <code>csv</code> to use a different delimiter.</p>\n\n<p><s>I recommend the use of the <code>DictReader</code> class.</s> Given that you only pay attention to one variable, just use <code>csv.reader</code>. During initialization, get the index of the column you want, and then use that on every record that the reader gives back.</p>\n\n<p>The critical performance issue here is that you have nested loops for row comparison. Given that you are comparing two series expected to be in the same order, but with edits (insertions and deletions), effectively you're doing a diff. Read this for a nice walkthrough.</p>\n\n<p><a href=\"http://www.xmailserver.org/diff2.pdf\" rel=\"nofollow noreferrer\">http://www.xmailserver.org/diff2.pdf</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:38:57.157", "Id": "401956", "Score": "0", "body": "Indeed, changing the separator allowed me to use the `csv` module. However I can't use `zip` because the files are not containing exactly the same lines so it won't line up correctly" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:41:13.540", "Id": "401958", "Score": "0", "body": "@Comte_Zero Are both in the same order, with some random insertions and deletions? Or are the files the same size, but out of order with respect to each other?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:44:05.340", "Id": "401959", "Score": "0", "body": "Same order, random insertions and deletions" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:45:35.970", "Id": "401962", "Score": "0", "body": "And are you checking all of the columns in both files, or only some of the columns?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:47:20.720", "Id": "401965", "Score": "0", "body": "This may vary, that is why the main function contains only one, potentially copiable line" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:07:12.900", "Id": "208148", "ParentId": "208144", "Score": "2" } } ]
{ "AcceptedAnswerId": "208148", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T13:48:03.670", "Id": "208144", "Score": "1", "Tags": [ "python", "csv" ], "Title": "Comparing columns from two CSV files" }
208144
<p>I have a windows form in C# project that keeps some information. I created a bunch of textbox and combobox dynamically, depend upon user input.</p> <p>Consider, I have a list of 10 combobox whose values will be selected by user.</p> <p>The combobox values are:</p> <ol> <li>Finding</li> <li>No Finding</li> <li>Incomplete</li> <li>Skipped.</li> </ol> <p>Now I have a single final combobox which contains the following values.</p> <ol> <li>Finding</li> <li>No Finding</li> <li>Incomplete</li> <li>Skipped Reviewed</li> <li>Skipped Not reviewed</li> </ol> <p>The final combobox should be populated depend upon the following logic</p> <ol> <li>If all values are "<code>Finding</code>", then the the final combobox should be "<code>Finding</code>"</li> <li>If all values are "<code>No_Finding</code>", then the the final combobox should be "<code>No_Finding</code>"</li> <li>If all values are "<code>InComplete</code>", then the the final combobox should be "<code>InComplete</code>"</li> <li><p>If all values are "<code>Skipped</code>", then the the final combobox should be "<code>Skipped Not Reviewed</code>".</p></li> <li><p>If any value is "<code>Finding</code>", then the final combobox should be "<code>Finding</code>".</p></li> <li>If any value is "<code>Incomplete</code>", then the final combobox should be "<code>Incomplete</code>".</li> <li>If any value is "<code>Skipped</code>", then the final combobox should be "<code>Skipped Reviewed</code>".</li> </ol> <p>With respect to the above logic conditions I have written the following that works fine. </p> <p>After writing the code I feel it's not cleaner and not an easily understandable solution.</p> <p><strong>What I need now whether there is any way to refactor the following lines of code.</strong> </p> <pre><code> public void selectfinalComboxValue() { List&lt;string&gt; list_of_combobox = new List&lt;string&gt;(); //txtBoxValLines is an user input for (int i = 0; i &lt; int.Parse(txtboxvalLines.Text); i++) { string cmbboxValue = ((ComboBox)panel1.Controls["Add_combobox" + (i).ToString()]).Text; list_of_combobox.Add(cmbboxValue); } List&lt;string&gt; distinct = list_of_combobox.Distinct().ToList(); if (distinct.Any(str =&gt; str.Contains("InComplete"))) { cmbFinalStatus.SelectedIndex = 2; cmbFinalStatus.Enabled = false; } else if (distinct.Any(str =&gt; str.Equals("Finding"))) { cmbFinalStatus.SelectedIndex = 0; cmbFinalStatus.Enabled = false; } else { cmbFinalStatus.SelectedIndex = -1; cmbFinalStatus.Enabled = true; } if (distinct.Count().ToString() == "1") { if (distinct.Any(str =&gt; str.Equals("Skipped"))) { cmbFinalStatus.SelectedIndex = 4; cmbFinalStatus.Enabled = false; } else if (distinct.Any(str =&gt; str.Equals("No Finding"))) { cmbFinalStatus.SelectedIndex = 1; cmbFinalStatus.Enabled = false; } } else { if (distinct.Any(str =&gt; str.Contains("Skipped"))) { cmbFinalStatus.SelectedIndex = 3; cmbFinalStatus.Enabled = false; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T17:29:54.227", "Id": "402024", "Score": "0", "body": "What happens if `list_of_combobox` have 5 `Finding` and 5 `Incomplete` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T17:37:28.870", "Id": "402026", "Score": "0", "body": "@Calak In that case it is Incomplete." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T15:36:54.730", "Id": "402295", "Score": "0", "body": "edited my code below, too show you more :)" } ]
[ { "body": "<p>I think you might be able to eliminate creating the distinct list and the nested ifs by first checking for the All() condtions, then later check for Any()</p>\n\n<pre><code> var items = list_of_combobox.ToList();\n\n if (items.All(str =&gt; str.Equals(\"Finding\")))\n {\n // assign final comboxbox \n }\n else if (items.Any(str =&gt; str.Equals(\"Finding\")))\n</code></pre>\n\n<p>Also, you might want to try creating an enum of the possible values, adding these values to the ComboBox, then getting/setting the SelectedItem property rather than dealing with indexes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T16:12:51.300", "Id": "208165", "ParentId": "208151", "Score": "1" } }, { "body": "<p>I won't give you the full response, because your code lack of context (we didn't know nothing about <code>cmbFinalStatus...</code>).</p>\n\n<h3>Without using distinct</h3>\n\n<p><code>result</code> value is set if case case 1,2,3,4 match.</p>\n\n<pre><code>List&lt;string&gt; all_of = new List&lt;string&gt;(){\"Skipped\", \"Incomplete\", \"No_Finding\", \"Finding\"};\nvar result = all_of.FirstOrDefault(lhs =&gt; list_of_combobox.All(rhs =&gt; rhs.Equals(lhs)));\nif (\n</code></pre>\n\n<p><code>result</code> value is set if case 5,6,7 match.</p>\n\n<pre><code>List&lt;string&gt; first_of = new List&lt;string&gt;(){\"Skipped\", \"Incomplete\", \"Finding\"};\nvar result = first_of.FirstOrDefault(lhs =&gt; list_of_combobox.Any(rhs =&gt; rhs.Equals(lhs)));\n</code></pre>\n\n<p><strong>Edit</strong>: Putting all together, we got:</p>\n\n<pre><code> // for... populating list_of_combobox\n // ...\n\n var str = new List&lt;string&gt;(){\"Finding\", \"No Finding\", \"InComplete\", \"Skipped\"}\n .Where(lhs =&gt; list_of_combobox.All(rhs =&gt; lhs.Equals(rhs)))\n .FirstOrDefault() ?? string.Empty;\n\n if (str.Length != 0)\n {\n if (str.Equals(\"Skipped\")) str = \"Skipped Not Reviewed\";\n }\n else\n {\n str = new List&lt;string&gt;(){\"Finding\", \"InComplete\", \"Skipped\"}\n .Where(lhs =&gt; list_of_combobox.Any(rhs =&gt; lhs.Equals(rhs)))\n .FirstOrDefault() ?? string.Empty; \n\n if (str.Equals(\"Skipped\")) str = \"Skipped Reviewed\";\n }\n\n cmbFinalStatus.SelectedIndex = new List&lt;string&gt;(){\"Finding\", \"No Finding\", \"InComplete\", \"Skipped Reviewed\", \"Skipped Not Reviewed\"}\n .IndexOf(str);\n\n cmbFinalStatus.Enabled = (cmbFinalStatus.SelectedIndex &lt; 0);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T18:58:58.807", "Id": "208175", "ParentId": "208151", "Score": "1" } } ]
{ "AcceptedAnswerId": "208175", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:20:01.370", "Id": "208151", "Score": "3", "Tags": [ "c#", "winforms" ], "Title": "Assign a value to combobox depend upon other combobox value" }
208151
<p>Based on my <a href="https://stackoverflow.com/a/53170526/5481787">answer</a> I have my implementation of linq Zip operator which operates on different length lists, and loops shortest list. </p> <p>My implementation:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; namespace SO { internal class Program { public static void Main(string[] args) { List&lt;String&gt; listA = new List&lt;string&gt; {"a", "b", "c", "d", "e", "f", "g"}; List&lt;String&gt; listB = new List&lt;string&gt; {"1", "2", "3"}; var mix = listA.ZipNew(listB, (l1, l2) =&gt; new[] {l1, l2}).SelectMany(x =&gt; x); foreach (var m in mix) { Console.WriteLine(m); } } } public static class Impl { public static IEnumerable&lt;TResult&gt; ZipNew&lt;TFirst, TSecond, TResult&gt;( this IEnumerable&lt;TFirst&gt; first, IEnumerable&lt;TSecond&gt; second, Func&lt;TFirst, TSecond, TResult&gt; resultSelector) { using (IEnumerator&lt;TFirst&gt; iterator1 = first.GetEnumerator()) using (IEnumerator&lt;TSecond&gt; iterator2 = second.GetEnumerator()) { var i1 = true; var i2 = true; var i1Shorter = false; var i2Shorter = false; var firstRun = true; while(true) { i1 = iterator1.MoveNext(); i2 = iterator2.MoveNext(); if (!i1 &amp;&amp; (i1Shorter || firstRun)) { iterator1.Reset(); i1 = iterator1.MoveNext(); i1Shorter = true; firstRun = false; } if (!i2 &amp;&amp; (i2Shorter || firstRun)) { iterator2.Reset(); i2 = iterator2.MoveNext(); i2Shorter = true; firstRun = false; } if (!(i1 &amp;&amp; i2)) { break; } yield return resultSelector(iterator1.Current, iterator2.Current); } } } } } </code></pre> <p>And I wonder if this implementation could be improved somehow, what could be improved, for better readability or speed. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:33:13.057", "Id": "401952", "Score": "2", "body": "Your question would benefit from some example usage within the question itself, so that we can see how you intend the method to be consumed, and quickly verify that it is working as intended." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:35:14.473", "Id": "401953", "Score": "0", "body": "@VisualMelon improved, full working code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T19:45:38.233", "Id": "402056", "Score": "5", "body": "Never `Reset` an enumerator. Just get a new enumerator. `Reset` was a misfeature intended for COM interop scenarios." } ]
[ { "body": "<blockquote>\n<pre><code> public static class Impl\n {\n public static IEnumerable&lt;TResult&gt; ZipNew&lt;TFirst, TSecond, TResult&gt;(\n</code></pre>\n</blockquote>\n\n<p>Names? The class would be more descriptive as something like <code>LinqExtensions</code>; the method something like <code>ZipLooped</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> using (IEnumerator&lt;TFirst&gt; iterator1 = first.GetEnumerator()) \n using (IEnumerator&lt;TSecond&gt; iterator2 = second.GetEnumerator())\n {\n var i1 = true;\n var i2 = true;\n var i1Shorter = false;\n var i2Shorter = false;\n var firstRun = true;\n</code></pre>\n</blockquote>\n\n<p>The iterators have useful names, but what does <code>i1</code> mean? And why five variables to track the state of two iterators? IMO it would be simpler as</p>\n\n<pre><code> var firstEnded = false;\n var secondEnded = false;\n\n while (true) \n {\n if (!iterator1.MoveNext())\n {\n if (secondEnded) yield break;\n firstEnded = true;\n iterator1.Reset();\n if (!iterator1.MoveNext()) yield break;\n }\n if (!iterator2.MoveNext())\n {\n if (firstEnded) yield break;\n secondEnded = true;\n iterator2.Reset();\n if (!iterator2.MoveNext()) yield break;\n }\n\n yield return resultSelector(iterator1.Current, iterator2.Current); \n }\n</code></pre>\n\n<p>and the almost repeated code <em>might</em> be worth pulling out as an inner method:</p>\n\n<pre><code> var firstEnded = false;\n var secondEnded = false;\n\n bool advance&lt;T&gt;(IEnumerator&lt;T&gt; it, ref bool thisEnded, bool otherEnded)\n {\n if (it.MoveNext()) return true;\n // `it` has done a full cycle; if the other one has too, we've finished\n if (otherEnded) return false;\n thisEnded = true;\n // Start again, although if `it` is empty we need to abort\n it.Reset();\n return it.MoveNext();\n }\n\n while (true)\n {\n if (!advance(iterator1, ref firstEnded, secondEnded)) yield break;\n if (!advance(iterator2, ref secondEnded, firstEnded)) yield break;\n yield return resultSelector(iterator1.Current, iterator2.Current); \n }\n</code></pre>\n\n<hr>\n\n<p>I notice that you've decided to <code>yield break</code> if either of the enumerables is empty. Would an exception be a better choice?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T16:44:40.037", "Id": "402007", "Score": "0", "body": "I'd rename `advance` in `TryMoveNextOrLoop`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T16:51:12.110", "Id": "402008", "Score": "0", "body": "_I notice that you've decided to yield break if either of the enumerables is empty._ - This is the expected behaviour. I'd be surprised if it was something else and this makes linq so reliable - nothing there so nothing happens - otherwise you would need to check everything for emptyness, not pretty ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T17:10:42.667", "Id": "402014", "Score": "0", "body": "@t3chb0t only most LINQ methods don't explicitly loop over one of the inputs as it consumes the other. I would probably expect an exception here if only one of them was empty, and an empty enumerable (`yield break`) if both are empty." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T17:13:29.170", "Id": "402017", "Score": "0", "body": "@VisualMelon no way :-P this is not how it should work. No collection returning LINQ extensions throw exceptions if the source is empty. Compare this `new[] { 1 }.Zip(Enumerable.Empty<int>(), (x, y) => (x, y)).Dump();` The result is an empty collection." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T17:19:24.800", "Id": "402018", "Score": "0", "body": "@t3chb0t indeed, but that's because it's defined as zipping as far as the shortest. I'd argue that extracting values repeatedly from an empty collection is meaningless, and so it should throw (as per `Average`). Anyhow, I can see your argument, so I think we'll have to agree to disagree :P" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T17:22:31.353", "Id": "402019", "Score": "0", "body": "@t3chb0t, `advance` here is an inner method, so it feels strange to me to give it a name with a leading capital letter. The reason that an exception makes sense to me is that the behaviour here should be that if the longer enumerable has length \\$n\\$ and the shorter has length \\$m\\$ the shorter should be repeated \\$n/m\\$ times, which gives a division by zero." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T17:24:17.797", "Id": "402021", "Score": "0", "body": "@VisualMelon I disagree to agree to disagree ;-] `Avarage`, `Min` or `Max` are scalars, that's why I said _collection returning LINQ extensions_ - I'm ok with them to throw but not when it's a non-scalar. This would make concatenating them very unpredictable... although I have to admit I already created `AverageOrDefault` etc because those scalars a real traps." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T17:26:13.560", "Id": "402022", "Score": "0", "body": "I've posted [my](https://stackoverflow.com/a/53417215/235671) version under the original question - which is basically the same as yours. Maybe I'll get some internet points too ;-]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T17:29:06.427", "Id": "402023", "Score": "0", "body": "Mhmm... could you explain what you mean with the division by zero in other words? I'm not sure why this is relevant... especially that you are not dividing anything." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T17:35:28.203", "Id": "402025", "Score": "0", "body": "@t3chb0t, in the example the longer list has 7 elements and the shorter list has 3 elements, so the shorter list is repeated 7/3 times. If the shorter list had 0 elements, it should be repeated 7/0 times. From a different perspective, I understand the requirement to be that `a.ZipNew(b, _).Count() == Math.Max(a.Count(), b.Count())`, so if one of them is empty the method cannot fulfil its contract (unless both of them are empty - VisualMelon made a good point there)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T17:48:29.833", "Id": "402029", "Score": "0", "body": "I see your point now, thanks for reframing it... however, one could say the same about the original `Zip` - your example would apply there too and yet they've decided to no throw when one collection is empty and I think it was a good decision. Not throwing is always better then throwing. `7/0` would be acceptable for something like `ZipLoopedOrEmpty` or `ZipLoopedOrDefault` but not for this one. I have large system build on top of this behaviour and I would be very unhappy if I had to check each collection for emptyness first. This would kill the 30+ calls spread over multiple methods chain;-]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T18:00:39.083", "Id": "402030", "Score": "0", "body": "@t3chb0t, no. If you could say the same about `Zip` then this method would be unnecessary. `a.Zip(b, _).Count() == Math.Min(a.Count(), b.Count())` and the difference between `Min` and `Max` in the presence of `0` is the crucial point." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:54:59.290", "Id": "208157", "ParentId": "208152", "Score": "10" } }, { "body": "<p>I noticed a few things that can be improved:</p>\n\n<ul>\n<li>Not all enumerators support <code>Reset</code>. Generator methods don't, for example, so calling <code>ZipNew</code> on the result of a <code>ZipNew</code> call will fail with a <code>NotSupportedException</code>. Obtaining a new enumerator should work, at the cost of having to replace the convenient <code>using</code> statements with <code>try/finally</code> constructions. <strong><em>Edit</strong>: As Eric pointed out, <code>Reset</code> should not be used at all. It's been abandoned.</em></li>\n<li>There's no need to call <code>Reset</code> <em>(or rather, to get a new enumerator)</em> when a collection is empty. I'd probably add a special case for that.</li>\n<li>Passing <code>null</code> causes either an unspecific <code>NullReferenceException</code> or an <code>ArgumentNullException</code> with parameter name <code>source</code> to be thrown. Throwing <code>ArgumentNullException</code>s with accurate parameter names would be more helpful. <strong><em>Edit:</strong> As JAD pointed out, this is trickier than it looks. You'll have to split the method into an eager non-yielding method and a lazy yielding method. A local function should be useful here.</em></li>\n<li><code>i1</code> and <code>i2</code> can be declared inside the while loop.</li>\n</ul>\n\n<hr>\n\n<p><strong>Addendum:</strong></p>\n\n<p>As Henrik's answer shows, a helper class can be useful for properly repeating enumerators without having to give up on <code>using</code>. I would take a slightly different approach by creating a repeatable enumerator class:</p>\n\n<pre><code>class RepeatableEnumerator&lt;T&gt; : IDisposable\n{\n private IEnumerable&lt;T&gt; _enumerable;\n private IEnumerator&lt;T&gt; _enumerator;\n\n\n public bool IsRepeating { get; private set; }\n public T Current =&gt; _enumerator.Current;\n\n\n public RepeatableEnumerator(IEnumerable&lt;T&gt; enumerable)\n {\n _enumerable = enumerable;\n _enumerator = enumerable.GetEnumerator();\n }\n\n public void Dispose()\n {\n _enumerator.Dispose();\n _enumerator = null;\n }\n\n public bool MoveNext() =&gt; _enumerator.MoveNext();\n\n public bool Repeat()\n {\n IsRepeating = true;\n _enumerator.Dispose();\n _enumerator = _enumerable.GetEnumerator();\n return _enumerator.MoveNext();\n }\n}\n</code></pre>\n\n<p>Which can then be used for both enumerables (and possibly in other extension methods as well):</p>\n\n<pre><code>public static IEnumerable&lt;TResult&gt; ZipLongest&lt;TFirst, TSecond, TResult&gt;(\n this IEnumerable&lt;TFirst&gt; first,\n IEnumerable&lt;TSecond&gt; second,\n Func&lt;TFirst, TSecond, TResult&gt; resultSelector)\n{\n // Eager parameter validation:\n if (first == null) throw new ArgumentNullException(nameof(first));\n if (second == null) throw new ArgumentNullException(nameof(second));\n if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector));\n\n // Local function for lazy zipping:\n IEnumerable&lt;TResult&gt; ZipLongestImpl()\n {\n using (var enum1 = new RepeatableEnumerator&lt;TFirst&gt;(first))\n using (var enum2 = new RepeatableEnumerator&lt;TSecond&gt;(second))\n {\n // Up-front check for empty collections:\n if (!enum1.MoveNext() || !enum2.MoveNext())\n yield break;\n\n while (true)\n {\n yield return resultSelector(enum1.Current, enum2.Current);\n\n var is1Empty = !enum1.MoveNext();\n var is2Empty = !enum2.MoveNext();\n if (is1Empty)\n {\n if (enum2.IsRepeating || is2Empty || !enum1.Repeat())\n yield break;\n }\n else if (is2Empty)\n {\n if (enum1.IsRepeating || !enum2.Repeat())\n yield break;\n }\n }\n }\n }\n return ZipLongestImpl();\n}\n</code></pre>\n\n<p>At this point it would be a good idea to add some documentation...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T07:52:26.080", "Id": "402123", "Score": "1", "body": "Worth adding that if you're going to throw `ArgumentNullExceptions`, make sure they're thrown eagerly, not only when iteration has started." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T08:25:40.997", "Id": "402129", "Score": "0", "body": "That's a good point! Much trickier than you'd expect it to be... looks like a good place to use a local function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T07:41:43.843", "Id": "402230", "Score": "0", "body": "Ah, so that's what you meant with a local function. If you look at what [`System.Linq`](https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,24) does, they put the lazy part in a separate private method. But I don't think there's much difference between those two." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T07:50:07.973", "Id": "402232", "Score": "0", "body": "Also, maybe it's worth adding a repetition counter to the repeater class. I can imagine some instances where it's worth knowing howmany time it has looped." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T08:31:11.697", "Id": "402235", "Score": "0", "body": "Local functions get turned into private static methods, so it's basically the same thing. I think they would've been used in Linq if they had been available at that time. I'll update the example to use capturing though - contrary to what I expected, in this case it's actually slightly faster, and it simplifies the code a little." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T08:32:16.997", "Id": "402236", "Score": "0", "body": "Ah, good to know. Never used local functions before." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T15:12:29.053", "Id": "208161", "ParentId": "208152", "Score": "10" } }, { "body": "<p>If you should respect that not all <code>Enumerators</code> implement <code>Reset()</code> then it is not possible to use <code>using</code> statements for the two <code>IEnumerators</code>. But you could introduce an <code>IEnumerator&lt;TResult&gt;</code> for the zipped result and use it like this:</p>\n\n<pre><code>public static IEnumerable&lt;TResult&gt; ZipNew&lt;TFirst, TSecond, TResult&gt;(\nthis IEnumerable&lt;TFirst&gt; first,\nIEnumerable&lt;TSecond&gt; second,\nFunc&lt;TFirst, TSecond, TResult&gt; resultSelector)\n{\n if (first == null) throw new ArgumentNullException(nameof(first));\n if (second == null) throw new ArgumentNullException(nameof(second));\n if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector));\n\n return InnerZipNew(first, second, resultSelector);\n}\n\nprivate static IEnumerable&lt;TResult&gt; InnerZipNew&lt;TFirst, TSecond, TResult&gt;(\nthis IEnumerable&lt;TFirst&gt; first,\nIEnumerable&lt;TSecond&gt; second,\nFunc&lt;TFirst, TSecond, TResult&gt; resultSelector)\n{\n using (ZipEnumerator&lt;TFirst, TSecond, TResult&gt; zipEnumerator = new ZipEnumerator&lt;TFirst, TSecond, TResult&gt;(first, second, resultSelector))\n {\n while (zipEnumerator.MoveNext())\n {\n yield return zipEnumerator.Current;\n }\n }\n}\n</code></pre>\n\n<p>As JAD writes in his comment it is necessary to catch possible invalid input as the first thing and then call a private shadow method to do the actual iteration in order to make the exceptions be thrown when the extension is called rather than when the enumeration is performed.</p>\n\n<p>In this way you're back on the using track.</p>\n\n<p>The <code>ZipEnumerator</code> it self could be something like:</p>\n\n<pre><code> public class ZipEnumerator&lt;T, S, TResult&gt; : IEnumerator&lt;TResult&gt;\n {\n IEnumerable&lt;T&gt; m_dataT;\n IEnumerable&lt;S&gt; m_dataS;\n IEnumerator&lt;T&gt; m_enumerT;\n IEnumerator&lt;S&gt; m_enumerS;\n List&lt;IDisposable&gt; m_disposables = new List&lt;IDisposable&gt;();\n Func&lt;T, S, TResult&gt; m_selector;\n bool m_secondReloaded = false;\n bool m_first = true;\n\n public ZipEnumerator(IEnumerable&lt;T&gt; dataT, IEnumerable&lt;S&gt; dataS, Func&lt;T, S, TResult&gt; selector)\n {\n m_dataT = dataT ?? throw new ArgumentNullException(nameof(dataT));\n m_dataS = dataS ?? throw new ArgumentNullException(nameof(dataS));\n m_selector = selector ?? throw new ArgumentNullException(nameof(selector));\n\n }\n\n public TResult Current =&gt; m_selector(m_enumerT.Current, m_enumerS.Current);\n\n object IEnumerator.Current =&gt; Current;\n\n public void Dispose()\n {\n foreach (IDisposable disposable in m_disposables)\n {\n disposable.Dispose();\n }\n m_disposables.Clear();\n }\n\n private IEnumerator&lt;T&gt; GetTEnumerator()\n {\n var enumerator = m_dataT.GetEnumerator();\n m_disposables.Add(enumerator);\n return enumerator;\n }\n\n private IEnumerator&lt;S&gt; GetSEnumerator()\n {\n var enumerator = m_dataS.GetEnumerator();\n m_disposables.Add(enumerator);\n return enumerator;\n }\n\n public bool MoveNext()\n {\n m_enumerT = m_enumerT ?? GetTEnumerator();\n m_enumerS = m_enumerS ?? GetSEnumerator();\n\n if (m_first)\n {\n if (m_enumerT.MoveNext())\n {\n if (!m_enumerS.MoveNext())\n {\n m_enumerS = GetSEnumerator();\n m_secondReloaded = true;\n if (!m_enumerS.MoveNext())\n return false;\n }\n return true;\n }\n else\n {\n m_first = false;\n }\n }\n\n if (!m_first &amp;&amp; !m_secondReloaded)\n {\n if (m_enumerS.MoveNext())\n {\n if (!m_enumerT.MoveNext())\n {\n m_enumerT = GetTEnumerator();\n if (!m_enumerT.MoveNext())\n return false;\n }\n\n return true;\n }\n }\n\n return false;\n }\n\n public void Reset()\n {\n m_secondReloaded = false;\n m_first = true;\n m_enumerT = null;\n m_enumerS = null;\n Dispose();\n }\n }\n</code></pre>\n\n<p>It's a little more code than other suggestions, but it encapsulates the problems with the disposal of intermediate enumerators without the necessity of a try-catch-statement. You could discuss if the disposal should be immediately when the enumerator is done or as I do collect them for disposal when the <code>ZipEnumerator</code> itself is disposed off?</p>\n\n<p>The <code>MoveNext()</code> method went a little more complicated than I like, so feel free to edit or suggest improvements.</p>\n\n<hr>\n\n<p><strong>Edit</strong></p>\n\n<p>A refactored version of <code>ZipEnumerator</code>:</p>\n\n<pre><code> public class ZipEnumerator&lt;T, S, TResult&gt; : IEnumerator&lt;TResult&gt;\n {\n IEnumerable&lt;T&gt; m_dataT;\n IEnumerable&lt;S&gt; m_dataS;\n IEnumerator&lt;T&gt; m_enumeratorT;\n IEnumerator&lt;S&gt; m_enumeratorS;\n List&lt;IDisposable&gt; m_disposables = new List&lt;IDisposable&gt;();\n Func&lt;T, S, TResult&gt; m_selector;\n bool m_secondReloaded = false;\n bool m_isInitilized = false;\n\n public ZipEnumerator(IEnumerable&lt;T&gt; dataT, IEnumerable&lt;S&gt; dataS, Func&lt;T, S, TResult&gt; selector)\n {\n m_dataT = dataT ?? throw new ArgumentNullException(nameof(dataT));\n m_dataS = dataS ?? throw new ArgumentNullException(nameof(dataS));\n m_selector = selector ?? throw new ArgumentNullException(nameof(selector));\n }\n\n public TResult Current =&gt; m_selector(m_enumeratorT.Current, m_enumeratorS.Current);\n object IEnumerator.Current =&gt; Current;\n\n public void Dispose()\n {\n DoDispose();\n }\n\n private void RegisterDisposable(IDisposable disposable)\n {\n m_disposables.Add(disposable);\n if (m_disposables.Count &gt; 10)\n {\n DoDispose();\n }\n }\n\n private void DoDispose()\n {\n foreach (IDisposable disposable in m_disposables)\n {\n disposable.Dispose();\n }\n m_disposables.Clear();\n }\n\n private IEnumerator&lt;T&gt; GetTEnumerator()\n {\n var enumerator = m_dataT.GetEnumerator();\n RegisterDisposable(enumerator);\n return enumerator;\n }\n\n private IEnumerator&lt;S&gt; GetSEnumerator()\n {\n var enumerator = m_dataS.GetEnumerator();\n RegisterDisposable(enumerator);\n return enumerator;\n }\n\n private Func&lt;bool&gt; CurrentMover = null;\n\n private bool FirstMover()\n {\n if (m_enumeratorT.MoveNext())\n {\n if (!m_enumeratorS.MoveNext())\n {\n m_enumeratorS = GetSEnumerator();\n m_secondReloaded = true;\n if (!m_enumeratorS.MoveNext())\n return false;\n }\n return true;\n }\n else if (!m_secondReloaded)\n {\n CurrentMover = SecondMover;\n return CurrentMover();\n }\n\n return false;\n }\n\n private bool SecondMover()\n {\n if (m_enumeratorS.MoveNext())\n {\n if (!m_enumeratorT.MoveNext())\n {\n m_enumeratorT = GetTEnumerator();\n if (!m_enumeratorT.MoveNext())\n return false;\n }\n\n return true;\n }\n\n return false;\n }\n\n private void Initialize()\n {\n m_enumeratorT = GetTEnumerator();\n m_enumeratorS = GetSEnumerator();\n CurrentMover = FirstMover;\n m_isInitilized = true;\n }\n\n public bool MoveNext()\n {\n if (!m_isInitilized)\n {\n Initialize();\n }\n return CurrentMover();\n }\n\n public void Reset()\n {\n m_isInitilized = false;\n m_secondReloaded = false;\n CurrentMover = null;\n m_enumeratorT = null;\n m_enumeratorS = null;\n DoDispose();\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T19:22:09.173", "Id": "402051", "Score": "0", "body": "I'd like to click +1 but when I see the variable names it says -1 so at the and it's a 0 ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T19:34:55.323", "Id": "402055", "Score": "0", "body": "I think the word _unconventional_ describes them pretty good... although `ts` and `ss` were below that level ;-]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T19:56:36.197", "Id": "402059", "Score": "0", "body": "I can explain that ;-P It's local and in a very small scope, this is allowed in my world, `tt` and `ss` on the other hand were `public`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T07:50:05.310", "Id": "402121", "Score": "0", "body": "You might want to refactor this so that the null-checks are eagerly performed instead of when iteration start. Doing so would be in line with other Linq implementations. Calling any Linq method on a null enumerable will throw immediately, not when iterating starts. To do this, have the public extension methods check for nulls, then from that call a private method that's using the `yield return` lazy evaluation. [Example](https://gist.github.com/JarkoDubbeldam/57430846438be59f15f68a8d6ddeeea4)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T08:06:52.843", "Id": "402127", "Score": "0", "body": "@JAD: I maybe misunderstand you, but the null-checks are performed in the constructor of the ZipEnumerator - not in the MoveNext(). I leave it to the Enumerator to handle invalid input, which I find appropriate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T08:09:53.610", "Id": "402128", "Score": "1", "body": "@HenrikHansen I saw that. The problem is that if a method is using the `yield` method of returning a `IEnumerable`, the entire method is treated as lazy. So nothing in the method starts executing before the first element in the result sequence is accessed. This means that only at that point the `ZipEnumerator` is constructed, and only then nullchecks are performed. Take a look at [this blog by Jon Skeet](https://codeblog.jonskeet.uk/2010/09/03/reimplementing-linq-to-objects-part-2-quot-where-quot/) for another (probably better) explanation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T08:32:11.357", "Id": "402133", "Score": "0", "body": "@JAD: OK, I've found the case. You got a point here. I'll update." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T19:15:45.503", "Id": "208178", "ParentId": "208152", "Score": "7" } }, { "body": "<p>It can be achieved with less noise in the code. So we can have the guarding logic in the main call as follows:</p>\n\n<pre><code> public static IEnumerable&lt;IEnumerable&lt;TResult&gt;&gt; ZipManyWithDifferentLengths&lt;TIn, TResult&gt;(\n this IEnumerable&lt;IEnumerable&lt;TIn&gt;&gt; sequences,\n Func&lt;TIn, TResult&gt; resultSelector)\n {\n if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector));\n\n var sequenceCollection = sequences as IEnumerable&lt;TIn&gt;[] ?? sequences.ToArray();\n if (sequenceCollection.Any(_ =&gt; _ == null)) throw new ArgumentException(nameof(sequences));\n\n return ZipIterator(sequenceCollection, resultSelector);\n }\n</code></pre>\n\n<p>We can get all the enumerators in input sequences, then, iterate through them in a way which increments a counter when MoveNext fails to do so for an enumerator. If not, we Concat results of the selector function applied to each element in that certain position in each sequence. Once the counter is equal to the number of sequences, we break the loop as there is nothing more to iterate over. Below is the code doing that all:</p>\n\n<pre><code> private static IEnumerable&lt;IEnumerable&lt;TResult&gt;&gt; ZipIterator&lt;TIn, TResult&gt;(\n this IEnumerable&lt;IEnumerable&lt;TIn&gt;&gt; sequences,\n Func&lt;TIn, TResult&gt; resultSelector)\n {\n var enumerators = sequences.Select(_ =&gt; _.GetEnumerator()).ToArray();\n var length = enumerators.Length;\n var counter = 0;\n while (counter &lt; length)\n {\n var result = Enumerable.Empty&lt;TResult&gt;();\n foreach (var i in Enumerable.Range(0, length))\n {\n if (!enumerators[i].MoveNext()) counter++;\n else\n {\n result = resultSelector(enumerators[i].Current).Yield().Concat(result);\n }\n }\n\n yield return result;\n }\n }\n</code></pre>\n\n<p>where Yield implementation is as follows:</p>\n\n<pre><code> public static IEnumerable&lt;T&gt; Yield&lt;T&gt;(this T item)\n {\n yield return item;\n }\n</code></pre>\n\n<p>Note that we need to make sure the extention method name is not misleading considering default Zip operation semantics.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Fixing obvious issues caused by wrong choice of test data which made it look like it was working - I used 3 lists of 1, 2 and 3 elements which was hiding the <code>counter</code> issue. Also adding the dispose call for each enumerator.</p>\n\n<pre><code>private static IEnumerable&lt;IEnumerable&lt;TResult&gt;&gt; ZipIteratorExtended&lt;TIn, TResult&gt;(\n IEnumerable&lt;IEnumerable&lt;TIn&gt;&gt; sequences,\n Func&lt;TIn, TResult&gt; resultSelector)\n {\n var enumerators = sequences.Select(_ =&gt; _.GetEnumerator()).ToList();\n var length = enumerators.Count;\n var breakEnumerators = new bool[length];\n while (breakEnumerators.Any(_ =&gt; !_))\n {\n var result = Enumerable.Empty&lt;TResult&gt;();\n foreach (var i in Enumerable.Range(0, length))\n {\n if (!enumerators[i].MoveNext()) breakEnumerators[i] = true;\n else\n {\n result = resultSelector(enumerators[i].Current).Yield().Concat(result);\n }\n }\n\n yield return result;\n }\n\n enumerators.ForEach(_ =&gt; _.Dispose());\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-25T14:40:33.250", "Id": "446807", "Score": "2", "body": "Unfortunately, there are a few problems with this approach: it's not how `Zip` and `ZipNew`'s `resultSelector` works, it's not repeating shorter sequences, there's a bug where `counter` gets incremented too often when one sequence is shorter, and the enumerators are not being disposed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-25T15:11:43.807", "Id": "446817", "Score": "0", "body": "Another point: it only makes sense to make `result` an enumerable if you want to lazily call `resultSelector`. That's not the case here, so you might as well use a list or array - less overhead and less code. As for `Yield` (which I think is an interesting approach - in the past I would just wrap the item in an array), nowadays Linq offers `Prepend` and `Append` methods." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-26T13:19:07.603", "Id": "446998", "Score": "0", "body": "@PieterWitvoet - Thanks for the feedback. Just shared the refactored version." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-25T09:24:52.587", "Id": "229621", "ParentId": "208152", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:24:35.677", "Id": "208152", "Score": "8", "Tags": [ "c#", "linq", "extension-methods" ], "Title": "Custom implementation of the linq Zip operator for different length lists" }
208152
<p><strong>What does it do ?</strong></p> <p>Looks in big XML files <strong>(1-3 GB)</strong> for given parameters that I need in my project, appends them to lists and finally exports both of them to the CSV files.</p> <p><strong>My XML scheme</strong></p> <p>I need to get child named <strong>'v'</strong>, which is value of specific child <strong>'k'</strong> nested in tag named <strong>'tag'</strong> which is nested within parent <strong>'way'</strong>.</p> <p><a href="https://i.stack.imgur.com/AMY0F.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AMY0F.png" alt="enter image description here"></a></p> <p><strong>What I tried</strong></p> <p><a href="https://www.ibm.com/developerworks/xml/library/x-hiperfparse/" rel="noreferrer">IBM's take on big xml files</a></p> <p>Plus various scripts from StackExchange.</p> <p><strong>Performance</strong></p> <p>My function needs 50% less time to parse XML than above method, any other I tried or I was able to try, because with some I was unable to figure things out and given up on them.</p> <p><strong>My goal</strong></p> <p>To get some tips on my code, hopefully find way to speed it up. I need to parse about 20 - 30 GB of XML files (as mentioned before single file is 1-3 GB), whole procedure is really time consuming - It takes about 12 hours up to 2 days of non stop parsing.</p> <p><strong>Variables description:</strong></p> <ul> <li><strong>xml</strong> - path to xml file</li> <li><strong>list_agis</strong> - list of IDs, list which length is number between 5k - 1 kk</li> <li><strong>parent</strong> - way</li> <li><strong>child</strong> - tag</li> <li><strong>child_atribitute</strong> - k</li> <li><strong>child_value_1</strong> - highway</li> <li><strong>child_value_2</strong> - track</li> <li><strong>name_id, name_atribute, name_file, path_csv, part_name</strong> - variables needed to create csv file name</li> </ul> <p><strong>My code</strong></p> <pre><code>def save_to_csv( list_1, list_2, name_1, name_2, csv_name, catalogue, part_name): """ Saves to CSV, based on 2 lists. """ raw_data = {name_1: list_1, name_2: list_2} df = pd.DataFrame(raw_data, columns=[name_1, name_2]) df.to_csv( '{0}\{1}_{2}.csv'.format(catalogue, part_name, csv_name), index=False, header=True, encoding = 'CP1250') def xml_parser( xml, lista_agis, parent, atribiute_parent, child, child_atribiute, child_value_1, child_value_2, name_file, sciezka_csv, name_id, name_atribiute, part_name): """ Function to pick from xml files tag values. Firstly it creates tree of xml file and then goes each level town and when final condtion is fullfiled id and value from xml file is appended to list in the end of xml file list is saved to CSV. """ rootElement = ET.parse(xml).getroot() list_id = [] list_value = [] for subelement in rootElement: if subelement.tag == parent: if subelement.get(atribiute_parent) in lista_agis: for sselement in subelement: if sselement.tag == child: if sselement.attrib[child_atribiute] == child_value_1: list_id.append( subelement.get(atribiute_parent)) list_value.append( sselement.get(child_value_2)) save_to_csv( list_id, list_value, name_id, name_atribiute, name_file, sciezka_csv, part_name) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T15:06:10.173", "Id": "401972", "Score": "1", "body": "Welcome on code review. When you ask to be reviewed from international people, try to give english code. You have more chance to get useful response if code have meaning for reviewers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T15:28:03.833", "Id": "401980", "Score": "0", "body": "Is that OSM XML? Can you avoid the overhead of XML by using a PBF version of your OSM dump instead? (C++ certainly has good libraries for reading OSM PBF; I'd be very surprised if Python doesn't)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T15:31:39.923", "Id": "401981", "Score": "2", "body": "Yes that is OSM XML. Im gonna dive into that pbf files then. Thanks! edit: I think this is my solution. https://imposm.org/docs/imposm.parser/latest/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T15:50:40.257", "Id": "401986", "Score": "2", "body": "You probably want to use a stream parser, instead of loading the entire document into memory and then parsing it. See [this answer](https://stackoverflow.com/a/22504625/3690024) on Stack Overflow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T16:55:35.523", "Id": "402009", "Score": "1", "body": "`k` and `v` are \"attributes\", not \"children\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T08:25:49.850", "Id": "402234", "Score": "0", "body": "Ok, above link is for Python 2. My project requires Python 3. Gonna dive deep into Google again." } ]
[ { "body": "<p><strong>Introduction</strong></p>\n\n<p>Unfortunately <a href=\"https://imposm.org/docs/imposm.parser/latest/\" rel=\"nofollow noreferrer\">imposm</a> is just for Python 2, my project is in Python 3. I think lxml library looks promising. I wrote simple code to test it, right now it is based on just 2 nodes. </p>\n\n<p><strong>Picture of nodes</strong></p>\n\n<p>I attach picture from XML file so one can see what I am dealing with.</p>\n\n<p><a href=\"https://i.stack.imgur.com/cmhgW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cmhgW.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>How it works</strong></p>\n\n<p>It is iterating over <strong>l_id</strong> (which is list of ids) using etree.parse and findall.</p>\n\n<p>First inner loop gathers dictionary where given <strong>id</strong> is.</p>\n\n<p>Second inner loop gathers dictionary where chosen <strong>value</strong> is.</p>\n\n<p>Loop for <strong>dict_ids_all</strong> appends to new list only ids from dictionary.</p>\n\n<p>Loop for <strong>dict_ids_all</strong> appends to new list only value from dictionary.</p>\n\n<p><strong>My code</strong></p>\n\n<pre><code>tree = lxml.etree.parse(r'path to xml')\nl_dict_ids_all = []\nl_dict_values_all= []\nl_only_id =[]\nl_only_values = []\nl_id = ['\"35121262\"', '\"35121263\"']\nname = '\"name\"'\n\nfor id in l_id:\n for tag in tree.findall('//node[@id={0}]'.format(id)):\n l_dict_ids_all.append(tag.attrib)\n\n for tag in tree.findall('//node[@id={0}]//tag[@k={1}]'.format(id,name)):\n l_dict_values_all.append(tag.attrib)\n\n\n#printing is only for review purpose\n\nprint('Full id dict') \nprint(l_dict_ids_all)\n\nprint('Full Value dict')\nprint(l_dict_values_all)\n\nprint('Only ID list')\nfor element in l_dict_ids_all:\n l_only_id.append(element['id'])\nprint(l_only_id)\n\nprint('Only Value list')\nfor element in l_dict_values_all:\n l_only_values.append(element['k'])\nprint(l_only_values)\n</code></pre>\n\n<p><strong>Output</strong></p>\n\n<blockquote>\n <p><strong>Full id dict</strong></p>\n \n <p>[{'id': '35121262', 'visible': 'true', 'version': '17',\n 'changeset': '41419943', 'timestamp': '2016-08-12T22:24:23Z', 'user':\n 'kocio', 'uid': '52087', 'lat': '52.1560439', 'lon': '21.0346808'},\n {'id': '35121263', 'visible': 'true', 'version': '16', 'changeset':\n '41419943', 'timestamp': '2016-08-12T22:24:20Z', 'user': 'kocio',\n 'uid': '52087', 'lat': '52.1492285', 'lon': '21.0461042'}]</p>\n \n <p><strong>Full Value dict</strong> [{'k': 'name', 'v': 'Stokłosy'}, {'k': 'name', 'v': 'Imielin'}]</p>\n \n <p><strong>Only ID list</strong> ['35121262', '35121263']</p>\n \n <p><strong>Only Value list</strong> ['name', 'name']</p>\n</blockquote>\n\n<p><strong>What I tried</strong></p>\n\n<p>I am aware that creating list and using it to append items to new list is wrong, but whenever I tried something like this:</p>\n\n<pre><code>l_dict_ids_all.append(tag.attrib[0]['id'])\n</code></pre>\n\n<p><strong>Received an error :</strong></p>\n\n<blockquote>\n <p>TypeError Traceback (most recent call)</p>\n \n <p>ipython-input-91-8b0a49bc5f35 in ()\n 7 for id in l_id:\n 8 for tag in tree.findall('//node[@id={0}]'.format(id)):\n ----> 9 l_dict_ids_all.append(tag.attrib[0]['id'])\n 10\n src/lxml/etree.pyx in lxml.etree._Attrib.<strong>getitem</strong>()</p>\n \n <p>src/lxml/apihelpers.pxi in lxml.etree._getAttributeValue()</p>\n \n <p>src/lxml/apihelpers.pxi in lxml.etree._getNodeAttributeValue()</p>\n \n <p>src/lxml/apihelpers.pxi in lxml.etree._getNsTag()</p>\n \n <p>src/lxml/apihelpers.pxi in lxml.etree.__getNsTag()</p>\n \n <p>src/lxml/apihelpers.pxi in lxml.etree._utf8()</p>\n \n <p>TypeError: Argument must be bytes or unicode, got 'int'</p>\n</blockquote>\n\n<p><strong>My goal/problem</strong></p>\n\n<p>Code is working, but I want to make it better.\nI need to get rid of 2 out 4 lists which I create at the begging.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T11:56:12.183", "Id": "208280", "ParentId": "208158", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:59:20.747", "Id": "208158", "Score": "5", "Tags": [ "python", "parsing", "xml" ], "Title": "Search for ways in OpenStreetMap extract" }
208158
<p>I wanted to try C# network programming and wrote this simple client/server application. The idea is - many clients can connect to server and request some data. As an example they request a set of points on sine-wave (required number of points and time span is up to each user).<br> The server then calculates required points and sends them to each user. </p> <p>As this is my first program of that kind (and because I <em>frankensteined</em> it from 2 different examples) I guess there are definitely errors/smell here and I would be really grateful to hear them.</p> <p>First - server setup:</p> <pre><code>class Program { static void Main(string[] args) { IPHostEntry iph = Dns.GetHostEntry(Dns.GetHostName()); IPAddress serverAddress = iph.AddressList[1]; int server_Port = 1337; int maxConnections = 10; Listener listener = new Listener(serverAddress, server_Port); // Setup server listener.StartListening(maxConnections); // Start server Console.Read(); } } // Here we accept new connections class Listener { //This is the socket that will listen to any incoming connections public Socket _serverSocket { get; private set; } public int Port { get; private set; } public int maxConnections { get; private set; } public IPAddress ipAddress { get; private set; } public Listener(IPAddress ServerIp, int ServerPort) { ipAddress = ServerIp; Port = ServerPort; _serverSocket = new Socket(ServerIp.AddressFamily, SocketType.Stream, ProtocolType.Tcp); } // Here we start waiting for new client public void StartListening(int MaxConnections) { maxConnections = MaxConnections; try { Console.WriteLine("Server started at IP:" + ipAddress.ToString() + "; port:" + Port.ToString() + ";\n"); _serverSocket.Bind(new IPEndPoint(ipAddress, Port)); // Setup server at selected endpoint _serverSocket.Listen(MaxConnections); // Limit maximum number of clients _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), _serverSocket); // Actual waiting } catch (Exception ex) { throw new Exception("Server starting error" + ex); } } // Here we go after receiving connection request private void AcceptCallback(IAsyncResult ar) { try { Socket temp = (Socket)ar.AsyncState; // ?? Socket acceptedSocket = temp.EndAccept(ar); // Get socket of new client ClientController.AddNewClient(acceptedSocket); // Handle new client IPEndPoint REP = (IPEndPoint)acceptedSocket.RemoteEndPoint; Console.WriteLine("Received request from IP:" + REP.Address.ToString() + "; port:" + REP.Port.ToString() + ";"); Console.WriteLine(ClientController.AllClients.Count() + " clients connected now"); Console.WriteLine(); // Resume waiting for new clients _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), _serverSocket); } catch (Exception ex) { throw new Exception("Server listening error" + ex); } } } </code></pre> <p>Client class and Client collection:</p> <pre><code>// Client class class Client { public int Id { get; private set; } public Socket _clientSocket { get; private set; } public ClientSender Sender { get; private set; } public ClientReceiver Receive { get; private set; } public Client(Socket socket, int id) { Sender = new ClientSender(socket, id); Receive = new ClientReceiver(socket, id); Receive.StartReceiving(); _clientSocket = socket; Id = id; } // Handling client's request public void HandleRequest(string request) { string[] cmd = request.Split('_'); // Here as an example I return points on sine wave based on user's request double tSpan; double.TryParse(cmd[1], out tSpan); int nPoints; int.TryParse(cmd[3], out nPoints); double tStep = tSpan / nPoints; for (int i = 0; i &lt; nPoints; i++) { double ti = 0 + i * tStep; double val = 10 * Math.Sin(2 * Math.PI * ti); string DataToSend = "Точка (_" + ti.ToString() + "_,_" + val.ToString() + "_)"; Sender.AnswerRequest(DataToSend); Thread.Sleep((int)(1000.0 * tStep)); } } } // Class, which controlls all connected clients static class ClientController { // All connected clients in a list public static List&lt;Client&gt; AllClients = new List&lt;Client&gt;(); // Handling new client (accepting/denying connection) public static void AddNewClient(Socket socket) { Client newClient = new Client(socket, AllClients.Count); AllClients.Add(newClient); } // Removing client public static void RemoveClient(int id) { int TargetClientIndex = AllClients.FindIndex(x =&gt; x.Id == id); AllClients.RemoveAt(TargetClientIndex); } // Serving client request (accepting/denying it) public static void AddClientRequest(int id, string data) { int TargetClientIndex = AllClients.FindIndex(x =&gt; x.Id == id); AllClients.ElementAt(TargetClientIndex).HandleRequest(data); } } </code></pre> <p>And communications with clients:</p> <pre><code>// Class for receiving messages from client public class ClientReceiver { private byte[] _buffer; private Socket _receiveSocket; private int _clientId; public ClientReceiver(Socket receiveSocket, int Id) { _receiveSocket = receiveSocket; _clientId = Id; } // Start waiting for message from client public void StartReceiving() { try { _buffer = new byte[4]; _receiveSocket.BeginReceive(_buffer, 0, _buffer.Length, 0, ReceiveCallback, null); } catch (Exception ex) { throw new Exception("Receiving start error" + ex); } } // Receiving message private void ReceiveCallback(IAsyncResult AR) { try { if (_receiveSocket.EndReceive(AR) &gt; 1) { // First 4 bytes store the size of incoming messages - read them int MessageLength = BitConverter.ToInt32(_buffer, 0); // Knowing the full size of incoming message - prepare for receiving _buffer = new byte[MessageLength]; // Receive _receiveSocket.Receive(_buffer, MessageLength, SocketFlags.None); string data = Encoding.Unicode.GetString(_buffer); Console.WriteLine("User " + _clientId.ToString() + " sent following request: " + data); // Send received message for handling ClientController.AddClientRequest(_clientId, data); // Resume waiting for new message StartReceiving(); } // if we didn't receive anything - disconnect client else { Disconnect(); } } catch { if (!_receiveSocket.Connected) { Disconnect(); } else { Console.WriteLine("Data receive error"); StartReceiving(); } } } // Disconnecting client private void Disconnect() { // Close connection _receiveSocket.Disconnect(true); ClientController.RemoveClient(_clientId); } } // Class, used to send messages back to selected client class ClientSender { private Socket _senderSocket; private int _clientId; public ClientSender(Socket receiveSocket, int Id) { _senderSocket = receiveSocket; _clientId = Id; } // Sending message to client public void AnswerRequest(string data) { try { byte[] DataPart = Encoding.Unicode.GetBytes(data); int SendMsgLength = DataPart.Length; byte[] InfoPart = BitConverter.GetBytes(SendMsgLength); var fullPacket = new List&lt;byte&gt;(); fullPacket.AddRange(InfoPart); fullPacket.AddRange(DataPart); _senderSocket.Send(fullPacket.ToArray()); } catch (Exception ex) { throw new Exception("Data sending error" + ex); } } // Disconnecting client private void Disconnect() { // Close connection _senderSocket.Disconnect(true); ClientController.RemoveClient(_clientId); } } </code></pre> <p>On the client side: GUI part:</p> <pre><code>public delegate void UpdateCallback(string message); public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void ConnectClick(object sender, EventArgs e) { IPHostEntry iph = Dns.GetHostEntry(Dns.GetHostName()); IPAddress serverAddress = iph.AddressList[1]; int server_Port = 1337; Connection.TryToConnect(serverAddress, server_Port); Connection.NewDataReceived += Foo_Changed; data_outp.Items.Add("Connection Succesfull"); } private void SendClick(object sender, EventArgs e) { double tSpan; double.TryParse(tSpan_input.Text, out tSpan); int nPoints; int.TryParse(nPoints_input.Text, out nPoints); string DataToSend = "PLS GIMME THIS tSpan=_" + tSpan.ToString() + "_ nPoints=_" + nPoints.ToString(); Connection.SendRequest(DataToSend); } private void Update(string message) { data_outp.Items.Add(message); } public void Foo_Changed(object sender, MyEventArgs args) // the Handler (reacts) { data_outp.Dispatcher.Invoke(new UpdateCallback(Update), new object[] { args.Message }); } } </code></pre> <p>Interaction with server:</p> <pre><code>static class Connection { public static Socket _connectingSocket { get; private set; } public static IPAddress ipAddress { get; private set; } public static int Port { get; private set; } public static string ReceivedData { get; private set; } private static byte[] _buffer; public static event EventHandler&lt;MyEventArgs&gt; NewDataReceived; // Trying connecting to selected server public static void TryToConnect(IPAddress ServerIp, int ServerPort) { ipAddress = ServerIp; Port = ServerPort; _connectingSocket = new Socket(ServerIp.AddressFamily, SocketType.Stream, ProtocolType.Tcp); while (!_connectingSocket.Connected) { Thread.Sleep(100); try { _connectingSocket.Connect(new IPEndPoint(ipAddress, Port)); StartReceiving(); } catch (Exception ex) { throw new Exception("Connection error" + ex); } } } // Start waiting for message from client public static void StartReceiving() { try { _buffer = new byte[4]; _connectingSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, ReceiveCallback, null); } catch (Exception ex) { throw new Exception("Receiving start error" + ex); } } // Receiving message private static void ReceiveCallback(IAsyncResult AR) { try { if (_connectingSocket.EndReceive(AR) &gt; 1) { // First 4 bytes store the size of incoming messages - read them int MessageLength = BitConverter.ToInt32(_buffer, 0); // Knowing the full size of incoming message - prepare for receiving _buffer = new byte[MessageLength]; // Receive _connectingSocket.Receive(_buffer, _buffer.Length, SocketFlags.None); // Handle ReceivedData = Encoding.Unicode.GetString(_buffer, 0, MessageLength); if (ReceivedData.Length != 0) NewDataReceived?.Invoke(null, new MyEventArgs(null, ReceivedData)); // Resume waiting for new message StartReceiving(); } else { // Received nothing } } catch (Exception ex) { throw new Exception("Data receive error" + ex); } } // Send message to server public static void SendRequest(string DataToSend) { try { byte[] DataPart = Encoding.Unicode.GetBytes(DataToSend); int SendMsgLength = DataPart.Length; byte[] InfoPart = BitConverter.GetBytes(SendMsgLength); var fullPacket = new List&lt;byte&gt;(); fullPacket.AddRange(InfoPart); fullPacket.AddRange(DataPart); _connectingSocket.Send(fullPacket.ToArray()); Console.WriteLine("Sending request: " + DataToSend); Console.WriteLine("Infobytes length=" + InfoPart.Length + " bytes ; Total message length=" + SendMsgLength.ToString() + " bytes;"); } catch (Exception ex) { throw new Exception("Data send error" + ex); } } } </code></pre> <p>And an event to pass received data back to main GUI thread:</p> <pre><code>// My event to pass received message public class MyEventArgs : EventArgs { public MyEventArgs(Exception ex, string msg) { Error = ex; Message = msg; } public Exception Error { get; } public string Message { get; } } </code></pre> <p>It does everything I need as of now (I can plot/save data and all that) but i guess there's room for improvement. Especially on the client side - I don't really like that event driven part, but couldn't make true async data pass.</p>
[]
[ { "body": "<h3>ClientController</h3>\n\n<ul>\n<li>I don't see a purpose for this class. I would move <code>AllClients</code>, <code>AddNewClient</code>, <code>RemoveClient</code> to <code>Listener</code> and <code>AddClientRequest</code> to <code>Client</code>.</li>\n<li>These operations should be made thread-safe.</li>\n</ul>\n\n<h3>Client</h3>\n\n<ul>\n<li>Don't start an async operation int the constructor. Create a method <code>Initialise()</code> and let this method call <code>Receive.StartReceiving()</code>.</li>\n</ul>\n\n<h3>ClientReceiver</h3>\n\n<ul>\n<li><p><code>ReceiveCallback</code> expects <code>_receiveSocket.Receive</code> to contain one message only and the full message. This should not be asserted. The underying socket is optimized to use a buffer for sending data. You should be able to deal with parts of messages and multiple messages. Accomodating this adds some complexity though, you should:</p>\n\n<ul>\n<li>Use a raw buffer queue per client</li>\n<li>Create a lexer/parser per client to determine when a full message is available in the queue</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<h3>Common Guidelines</h3>\n\n<ul>\n<li><p>Use camelCase for arguments</p>\n\n<blockquote>\n <p><code>public Listener(IPAddress ServerIp, int ServerPort)</code></p>\n</blockquote>\n\n<p><code>public Listener(IPAddress serverIp, int serverPort)</code></p></li>\n<li><p>Guard arguments</p>\n\n<blockquote>\n<pre><code> public Listener(IPAddress serverIp, int serverPort)\n {\n // ..\n }\n</code></pre>\n</blockquote>\n\n<p><code>public Listener(IPAddress serverIp, int serverPort)\n {\n if (serverIp == null) throw new ArgumentNullException(nameof(serverIp));\n // ..\n }</code></p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T05:13:58.320", "Id": "222059", "ParentId": "208160", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T15:11:10.143", "Id": "208160", "Score": "5", "Tags": [ "c#", "beginner", "socket", "server", "client" ], "Title": "Socket client-server app for exchanging sine-wave points" }
208160
<p>I want to call a series of functions to build up an array, like so:</p> <pre><code>$array['conditions'][] = $this-&gt;function1($input1); $array['conditions'][] = $this-&gt;function2($input2); $array['conditions'][] = $this-&gt;function3($input3); </code></pre> <p>However, each function may return either an array with values or an empty array (depending on input). In the case of a returned empty array, <code>$array['conditions']</code> is polluted with a bunch of empty entries, which is a problem when it comes to unit test maintenance - if I add additional functions I have to go back and update the expected value for all of my tests.</p> <p>I could do something like:</p> <pre><code>$function1_return = $this-&gt;function1($input1); if(!empty($function1_return) { $array['conditions'][] = $function1_return; } </code></pre> <p>but I'm hoping there is a cleaner way? I also tried to remove any empty values after the fact, but to no avail (<code>array_filter</code>, for example, retains any array keys).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T15:39:31.800", "Id": "401984", "Score": "2", "body": "would `array_values(array_filter($conditions))` help? I don't really get why array keys are that important for you though" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T16:08:03.510", "Id": "401990", "Score": "0", "body": "@YourCommonSense I don't see how your proposed code solution will help, because as mentioned `array_filter` retains keys. The reason it's a problem is for the maintenance of tests - I have to keep adding extra empty keys to the expected array for each test as I add functions in the future. I will update my question to reflect this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T16:19:28.087", "Id": "401995", "Score": "0", "body": "You want to keep empty keys and in same time drop them? That's totally unclear." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T16:31:03.903", "Id": "402003", "Score": "0", "body": "@YourCommonSense jumped to a bad conclusion, apologies. Your code does indeed work perfectly! Please submit it as an answer and I will mark it as so." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T16:31:05.503", "Id": "402004", "Score": "0", "body": "@Erebus 1) It's unclear what you asked, 2) The code you presented in its current form is not meaningfully reviewable. We only review real, working code. If you edit your question to contain your actual code we can review it for improvements. See [What topics can I ask about?](https://codereview.stackexchange.com/help/on-topic) for reference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T16:32:59.563", "Id": "402005", "Score": "0", "body": "@Calak yes I wasn't very clear on explaining _why_ it was a problem - but I did get a great answer in the first comment, just didn't work through it properly to see if it actually helped. Thanks." } ]
[ { "body": "<p>The cleanest way is how you do and then filter:</p>\n\n<pre><code>$array['conditions'] = array_filter ($array['conditions']);\n</code></pre>\n\n<p>Or more explicitly (depend of your values):</p>\n\n<pre><code>$array['conditions'] = array_filter ($array['conditions'], function ($v){return !empty($v);});\n</code></pre>\n\n<p>And for normalizing indexes:</p>\n\n<pre><code>$array['conditions'] = array_values(array_filter($array['conditions']));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T16:12:38.477", "Id": "401992", "Score": "0", "body": "Thanks, but as I mentioned in the question, `array_filter` doesn't work as it retains keys." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T16:17:24.603", "Id": "401994", "Score": "0", "body": "Just use `array_values` as @YourCommonSense stated" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T16:07:22.640", "Id": "208164", "ParentId": "208162", "Score": "1" } } ]
{ "AcceptedAnswerId": "208164", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T15:31:34.253", "Id": "208162", "Score": "-2", "Tags": [ "php", "array" ], "Title": "Append to array if not empty" }
208162
<p>For an interview, I was tasked with writing a program that consumes a list of strings, and produces a mapping between every character in the list, and the characters found most frequently with it (let's call them Companion Characters). </p> <p>For example, if it was given <code>["aabc", "bcdddd", "cde"]</code>, it would return <code>{a=[b, c], b=[c], c=[b, d], d=[c], e=[c, d]}</code>. <code>a</code> maps to <code>b, c</code> because they were together in the first word, <code>b</code> maps to <code>c</code> because they were together in two words (<code>"aabc"</code> and <code>"bcddd"</code>), while <code>a</code> and <code>d</code> were only with it for one word, etc. </p> <p>To solve it, I used two HashMaps – One which mapped every character to a map of companion characters, to integers (the number of times found), and another which mapped character to the list of companion characters found most frequently with it. My code (which compiles and works) is below. </p> <pre><code>import java.util.*; public class MaxMap { private Map&lt;Character, Map&lt;Character, Integer&gt;&gt; charMap; private Map&lt;Character, List&lt;Character&gt;&gt; maxMap; public MaxMap() { charMap = new HashMap&lt;&gt;(); maxMap = new HashMap&lt;&gt;(); } public void computeMap(List&lt;String&gt; strs) { for(String str: strs) { //Will contain all of the starting letters encountered in the string Set&lt;Character&gt; seenOriginal = new HashSet&lt;&gt;(); for(int i = 0; i &lt; str.length(); i++) { char original = str.charAt(i); if(!charMap.containsKey(original)) { charMap.put(original, new HashMap&lt;&gt;()); } //Haven't yet calculated the mappings for this character - and dups don't matter if(!seenOriginal.contains(original)) { seenOriginal.add(str.charAt(i)); Set&lt;Character&gt; seenMapping = new HashSet&lt;&gt;(); for(int j = 0; j &lt; str.length(); j++) { //This is the same character, or a character previously encountered. if(i == j || str.charAt(i) == str.charAt(j) || seenMapping.contains(str.charAt(j))) continue; char added = str.charAt(j); seenMapping.add(added); int num = charMap.get(original).getOrDefault(added, 0); num++; charMap.get(original).put(added, num); setMaxMapping(original, added); } } } } } public void setMaxMapping(char original, char added) { List&lt;Character&gt; current = maxMap.getOrDefault(original, new ArrayList&lt;&gt;()); int oldCount = 0; if(current.size() &gt; 0) { oldCount = charMap.get(original).get(current.get(0)); //Special case, in case the first char in list was the one adjusted if(current.get(0) == added) { oldCount--; } } int addedCount = charMap.get(original).get(added); if(addedCount &gt; oldCount) { current = new ArrayList&lt;&gt;(Arrays.asList(added)); } else if (addedCount == oldCount) { current.add(added); } maxMap.put(original, current); } public Map&lt;Character, List&lt;Character&gt;&gt; getMaxMap() { return this.maxMap; } } </code></pre> <p>The main class which constructed and called it is</p> <pre><code>import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; public class Main { public static void main(String[] args) { List&lt;String&gt; strings = new ArrayList&lt;&gt;(Arrays.asList("aabc", "bcdddd", "cde")); MaxMap mm = new MaxMap(); mm.computeMap(strings); System.out.println(mm.getMaxMap()); } } </code></pre> <p>I didn't get the job, because my code wasn't optimal enough. How should I improve it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T19:10:15.753", "Id": "402047", "Score": "1", "body": "Shouldn't `a` map to `a` as well?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T20:46:08.927", "Id": "402067", "Score": "0", "body": "For each character, keep count of companions. When you finish looking at all strings, sort the counts and get the most frequent for each character. You can do the first part in O(chars * 26) assuming all characters go from a-z" } ]
[ { "body": "<p>Here are some tips to keep in mind when writing code that needs to be optimal:</p>\n\n<ol>\n<li><strong>The single biggest thing is: reduce the time complexity!</strong> This is by far the most significant improvement you can possibly make. Avoid iterations over the data as much as possible. For instance, every time you check if the char was added to <code>charMap</code>, the <code>containsKey()</code> function iterates over data in the <code>Map</code>. There aren't many letters so you can have a small data structure where the position of the data (index) indicates what character it relates to, this will remove the need to iterate to search for a specific character. In other cases you may reduce the number of iterations by sorting your data and using an efficient search algorithm such as binary search.</li>\n<li>Arrays are the fastest data structure, use them instead of more complex data structures wherever it makes sense to do so.</li>\n<li>Minimize the amount of data to be stored/manipulated - this can too be achieved by position-coding the data in your data structure, the position where the numbers are saved tells you what character these numbers relate to, so there are no actual <code>Character</code> variables being created until you need to create them, and then you can write code that will create only the chars you need to use/output.</li>\n</ol>\n\n<p>Here is my implementation of the function you were tasked to write, I also avoided some of the logic checks you did, but getting rid of a few <code>if</code> statements is not a significant optimization so don't worry about it, focus on the main points I explained and see how they are implemented.</p>\n\n<p>(notice the difference caused by improving the time complexity: according to my benchmarking, my implementation works about as fast as yours (1.1 times faster) with an input of 3 strings in the list, but it works ~5.4 times faster than yours when given an input list of 30 strings, the speed gap grows the bigger the input gets)</p>\n\n<pre><code>public static Map&lt;Character, List&lt;Character&gt;&gt; companionChars(List&lt;String&gt; strings){\n Map&lt;Character, List&lt;Character&gt;&gt; result = new HashMap&lt;&gt;(27, 1);\n int[] lengths = {26, 26};\n int[][] companionCounts = (int[][]) Array.newInstance(int.class, lengths);\n\n for(String str : strings){\n int[] charsFound = new int[26];\n for(int x = 0; x &lt; str.length(); x++)\n charsFound[str.charAt(x) - 'a'] = 1;\n for(int x = 0; x &lt; 26; x++)\n if(charsFound[x] == 1){\n for(int y = 0; y &lt; 26; y++)\n companionCounts[x][y] += charsFound[y];\n companionCounts[x][x]--;\n }\n }\n\n for(int x = 0; x &lt; 26; x++){\n ArrayList&lt;Character&gt; chars = new ArrayList&lt;Character&gt;();\n int max = 1;\n for(int y = 0; y &lt; 26; y++){\n if(companionCounts[x][y] &gt; max){\n max = companionCounts[x][y];\n chars.clear();\n chars.add((char)('a' + y));\n }\n else if(companionCounts[x][y] == max)\n chars.add((char)('a' + y));\n }\n if(!chars.isEmpty())\n result.put(new Character((char)('a' + x)), chars);\n }\n return result;\n}\n</code></pre>\n\n<p>Main function:</p>\n\n<pre><code>public static void main(String args[]) {\n List&lt;String&gt; strings = Arrays.asList(\"aabc\", \"bcdddd\", \"cde\");\n System.out.println(companionChars(strings));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T13:32:42.067", "Id": "208376", "ParentId": "208174", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T18:58:37.990", "Id": "208174", "Score": "3", "Tags": [ "java", "performance", "algorithm", "strings", "interview-questions" ], "Title": "Map Character to Characters Most Frequently Found With it (in list of strings)" }
208174
<p>Giving a review to <a href="https://codereview.stackexchange.com/questions/207494/threadsafe-oneshot-event-which-fires-on-subscription-if-the-event-was-fired-in-t">Oachkatzl</a> and recently about some other synchronization problems (Lazy with invalidate and some node-locking list), I wanted to test my skills and redesign it in most light-weight way I can muster.</p> <p>I am especially concerned about thread-safety here, because there is NO LOCK statement, only <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.interlocked.compareexchange#System_Threading_Interlocked_CompareExchange__1___0____0___0_" rel="nofollow noreferrer"><code>Interlocked.CompareExchange</code></a> in a loop, that is used for <a href="https://stackoverflow.com/a/22534723/1722660">event fields</a> anyway. There is only one field - <code>object _state</code> to prevent torn-down reads (e.g. by overwriting sender+args without proper lock and knowing for sure we won to do the invoke).</p> <p>Having single field also makes me consider changing this all to <code>struct</code>, because it will be used as private field for public event anyway.</p> <p>Last thing I was thinking about was to maybe remove the runtime-typechecks (<code>state is Invoked</code>), but do not think it is worth it (would probably need wrapping the delegates in another class and using interface or common base class).</p> <pre><code>/// &lt;summary&gt; /// Thread-safe event manager that ensures that subscribers get notified once after the event happens, /// even if the event already happened. /// &lt;/summary&gt; /// &lt;typeparam name="Sender"&gt;Sender of the event&lt;/typeparam&gt; /// &lt;typeparam name="Args"&gt;Additional arguments passed to subscribers&lt;/typeparam&gt; public class OneShotEvent&lt;Sender, Args&gt; { public delegate void Handler(Sender sender, Args args); // helper class to store sender and args when invoked private class Invoked { public Sender sender; public Args args; public Invoked(Sender sender, Args args) { this.sender = sender; this.args = args; } } // Delegate (subscribers) or Invoked (sender and args) private object _state; /// &lt;summary&gt; /// Subscribers will be notified once after the event happens, /// can be notified immediately if the event already happened. /// &lt;/summary&gt; public event Handler Event { add { var state = _state; object prev; do { if (state is Invoked invoked) { value(invoked.sender, invoked.args); return; } prev = state; state = Interlocked.CompareExchange(ref _state, Delegate.Combine((Delegate)state, value), prev); } while (prev != state); } remove { var state = _state; object prev; do { if (state is Invoked) return; prev = state; state = Interlocked.CompareExchange(ref _state, Delegate.Remove((Delegate)state, value), prev); } while (prev != state); } } /// &lt;summary&gt; /// Notify subscribers if not already done. /// &lt;/summary&gt; /// &lt;param name="sender"&gt;Sender of the notification&lt;/param&gt; /// &lt;param name="args"&gt;Arguments of the notification&lt;/param&gt; /// &lt;returns&gt;true if no invoke was called before, false if already invoked&lt;/returns&gt; public bool TryInvoke(Sender sender, Args args) { var state = _state; if (state is Invoked) return false; var invoked = new Invoked(sender, args); object prev; do { prev = state; state = Interlocked.CompareExchange(ref _state, invoked, prev); if (state is Invoked) return false; } while (prev != state); ((Handler)state)?.Invoke(sender, args); return true; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T10:42:42.033", "Id": "402151", "Score": "0", "body": "Additional info can be found [in this chat](https://chat.stackexchange.com/rooms/86095/discussion-between-firda-and-oachkatzl) (me and oachkatzl talking about the fragility of these lock-less solutions, how seemingly innocent modification involving double-read can destroy the correctnes of the code)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T09:31:33.770", "Id": "402245", "Score": "0", "body": "**USAGE:** This is primarily designed for events like **connection closed** or **object removed/disposed**. You can get such object from e.g. concurrent collection and it could already be closed/removed/disposed at the time you wish to subscribe to the event. This ensures correctnes (and saves you some checks) in these scenairos." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T19:03:47.083", "Id": "208177", "Score": "4", "Tags": [ "c#", "thread-safety", "event-handling" ], "Title": "\"Lock-free\" one-shot event manager" }
208177
<p>I wrote a Perl 6 grammar to parse a C++ function. My final goal would be to parse an entire header. The aim is not to correct C++ syntax errors, but to parse valid C++.</p> <p>Do you have some advice or improvements?</p> <pre><code>#!/usr/bin/env perl6 grammar FUNCTION { token TOP { [ &lt;attr&gt; \s+ ]? &lt;type&gt; [ \s* &lt;type_mod&gt; ]? (\s+) &lt;fname&gt; (\s*) "(" (\s*) [&lt;parameter&gt; [ "," (\s*) &lt;parameter&gt; ]* ]? (\s*) ')'(\s*) ';' } token name { \w+ } token namespace { [ "::" ]? [ &lt;name&gt; "::" ]* } token attr { &lt;name&gt; } token type { &lt;namespace&gt;? &lt;name&gt; } token type_mod { [ \*|\&amp; ]+ } token fname { &lt;name&gt; } token variable { &lt;name&gt; } token parameter { &lt;type&gt; [\s* &lt;type_mod&gt; ]? \s+ &lt;variable&gt; } } my $str = "const ::one::std::string ** ma1n( int&amp;&amp; i, two::std::string va1e_ );"; my $parsed = FUNCTION.parse($str); say $parsed; </code></pre>
[]
[ { "body": "<p>I'd expect to see many more tests of any program that addresses a problem as gnarly as parsing a C++ declaration.</p>\n\n<p>Choosing a couple I've recently had cause to write (on Stack Overflow), I would immediately add</p>\n\n\n\n<ul>\n<li><pre class=\"lang-c++ prettyprint-override\"><code>void (SENDER::*get_func())(double, double);\n</code></pre>\n\n(from <a href=\"//stackoverflow.com/a/53390003\"><em>Passing pointers to member function as returned values to <code>QObject::connect()</code></em></a>)</li>\n<li><pre class=\"lang-c++ prettyprint-override\"><code>constexpr std::size_t len(const T(&amp;)[length]);\n</code></pre>\n\n(from <a href=\"//stackoverflow.com/a/53409160\"><em>Differentiate between array and pointer as function parameter</em></a>)</li>\n</ul>\n\n<p>Neither of these succeeded when I tried them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T14:28:04.890", "Id": "402170", "Score": "1", "body": "I've no way to test it right there but I believe it also lacks `noexcept` support" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T22:58:48.960", "Id": "208200", "ParentId": "208179", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T19:22:53.777", "Id": "208179", "Score": "3", "Tags": [ "parsing", "grammar", "lexer", "raku" ], "Title": "Parsing a C++ function declaration with Perl 6 grammar" }
208179
<p>I am really new to Python and programming in general and I am trying to improve doing some projects like this one. I would like to know how I can improve this the right way.</p> <pre><code> """A simple calculator """ def additions(): print("ADDITION:") num1 = input("Give me your first number: ") num2 = input("Give me a second number: ") try: result = float(num1) + float(num2) print(result) except ValueError: print("INVALID") def subtractions(): print("SUBTRACTION:") num1 = input("Give me your first number: ") num2 = input("Give me a second number: ") try: result = float(num1) + float(num2) print(result) except ValueError: print("INVALID") def divisions(): print("DIVISION:") num1 = input("Give me your first number: ") num2 = input("Give me a second number: ") try: result = float(num1) + float(num2) print(result) except ValueError: print("INVALID") def multiplications(): print("MULTIPLICATION:") num1 = input("Give me your first number: ") num2 = input("Give me a second number: ") try: result = float(num1) + float(num2) print(result) except ValueError: print("INVALID") print("Hello to Simple Calculator ver.0.0003.") print("Type:\n 1. for Addition.\n 2. for Subtraction .\n 3. for Multiplication.\n 4. for Division. \n 0. to EXIT.") while True: try: user_input = int(input("What operation do you need? ")) except ValueError: print("INVALID!!!") continue if user_input == 1: additions() elif user_input == 2: subtractions() elif user_input == 3: multiplications() elif user_input == 4: divisions() elif user_input == 0: break </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T00:54:09.020", "Id": "402098", "Score": "1", "body": "Double check your operations. Currently they're all addition." } ]
[ { "body": "<p>For a beginner this is not bad at all. Consider factoring out repeated code into its own function, particularly the code that reads two input numbers and converts them to floats. In that function you could also include the printing of the operation title. Finally, consider putting your globally scoped code into a main function.</p>\n\n<p>The application can be even more abbreviated if you use the <code>operator</code> library and some simple tuple lookups:</p>\n\n<pre><code>#!/usr/bin/env python3\n\nfrom operator import add, sub, mul, truediv\n\n'''A simple calculator '''\n\n\ndef main():\n ops = (('Addition', add),\n ('Subtraction', sub),\n ('Multiplication', mul),\n ('Division', truediv))\n print('Hello to Simple Calculator ver.0.0003.')\n print('Type:')\n print('\\n'.join(' %d. for %s' % (i+1, name)\n for i, (name, op) in enumerate(ops)))\n print(' 0. to exit')\n\n while True:\n try:\n user_input = int(input('What operation do you need? '))\n except ValueError:\n print('Invalid input.')\n continue\n if user_input == 0:\n break\n elif 1 &lt;= user_input &lt;= 4:\n title, op = ops[user_input - 1]\n print('%s:' % title)\n try:\n num1 = float(input('Give me your first number: '))\n num2 = float(input('Give me a second number: '))\n print(op(num1, num2))\n except ValueError:\n print('Invalid input.')\n else:\n print('Invalid input.')\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>You don't even need your operations to be separated into functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T11:57:00.733", "Id": "402160", "Score": "0", "body": "This was really helpful thank you very much ." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T00:52:32.393", "Id": "208202", "ParentId": "208182", "Score": "1" } } ]
{ "AcceptedAnswerId": "208202", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T20:00:41.593", "Id": "208182", "Score": "-1", "Tags": [ "python", "beginner", "python-3.x", "calculator" ], "Title": "Simple Python calculator 5" }
208182
<p>I recently started delving into Vue.js, and decided to try my hand at some custom class/style bindings, so I made a small app that's supposed to cycle through each "light" of a stoplight (red, yellow, green, red, etc.).</p> <p>My Vue instance has a data property <code>count</code>, which is initially set to <code>0</code>, and I also have a <code>setInterval</code> callout that is to increments the <code>count</code> every one second.</p> <p>Each "light" in the stoplight has a Bootstrap button class associated with it (<code>btn-danger</code> for red, <code>btn-warning</code> for yellow, and <code>btn-success</code> for green), and each class becomes "active" based on some modulus arithmetic against my Vue instance's <code>count</code>.</p> <p>I'm wondering if perhaps I could be handling the change in these classes more efficiently, but am not sure what could be done.</p> <p>Here is my current code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var app = new Vue({ el: '#app', data: { count: 0, styleObject: { display: 'block', width: '30px', margin: '0', borderRadius: '50px', border: '1px solid black' } } }); setInterval(function() { app.count = app.count + 1; }, 1000);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#light { background-color: yellow; display: inline-block; border: 2px solid black; margin: 10px; padding: 5px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" /&gt; &lt;script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"&gt;&lt;/script&gt; &lt;div id="app"&gt; &lt;div id='light'&gt; &lt;input type='button' id='red' :class='["btn", (count % 3 === 0) &amp;&amp; "btn-danger"]' :style='styleObject' /&gt; &lt;br /&gt; &lt;input type='button' id='yellow' :class='["btn", (count % 3 === 1) &amp;&amp; "btn-warning"]' :style='styleObject' /&gt; &lt;br /&gt; &lt;input type='button' id='green' :class='["btn", (count % 3 === 2) &amp;&amp; "btn-success"]' :style='styleObject' /&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>You could use the <a href=\"https://vuejs.org/v2/guide/class-and-style.html#Object-Syntax\" rel=\"nofollow noreferrer\">Object Syntax</a> to specify the class bindings instead of the <a href=\"https://vuejs.org/v2/guide/class-and-style.html#Array-Syntax\" rel=\"nofollow noreferrer\">Array Syntax</a>:</p>\n\n<pre><code>&lt;input type='button' id='red' :class='{\"btn\": true, \"btn-danger\": (count % 3 === 0)}' /&gt;\n</code></pre>\n\n<p>That <code>\"btn\": true</code> is okay but a little annoying. Luckily \"<em>it’s also possible to use the object syntax inside array syntax</em>\"<sup><a href=\"https://vuejs.org/v2/guide/class-and-style.html#Array-Syntax\" rel=\"nofollow noreferrer\">1</a></sup></p>\n\n<pre><code>&lt;input type='button' id='red' :class='[\"btn\", {\"btn-danger\": (count % 3 === 0)}]' /&gt;\n</code></pre>\n\n<p>The documentation uses double quotes and I attempted to use those but it didn't appear to work - perhaps because <code>btn-danger</code> needs to be surrounded by quotes.</p>\n\n<pre><code>&lt;input type='button' id='red' :class=\"[btn, {'btn-danger': (count % 3 === 0)}]\" /&gt;\n</code></pre>\n\n<hr>\n\n<p>There doesn't appear to be anything dynamic about the styles in <code>styleObject</code>, so those can be moved out of the business logic and maintained with the other styles in the CSS section. </p>\n\n<hr>\n\n<p>The interval function could be simplified using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_()\" rel=\"nofollow noreferrer\">increment operator</a>:</p>\n\n<pre><code>setInterval(function() {\n app.count++;\n}, 1000);\n</code></pre>\n\n<hr>\n\n<p>See the rewritten code that utilizes the advice above. </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var app = new Vue({\n el: '#app',\n data: {\n count: 0 \n }\n});\n\nsetInterval(function() {\n app.count++;\n}, 1000);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#light {\n background-color: yellow;\n display: inline-block;\n border: 2px solid black;\n margin: 10px;\n padding: 5px;\n}\n\n#light .btn {\n display: block;\n width: 30px;\n margin: 0;\n border-radius: 50px;\n border: 1px solid black;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;link href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" rel=\"stylesheet\" /&gt;\n&lt;script src=\"https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js\"&gt;&lt;/script&gt;\n&lt;div id=\"app\"&gt;\n &lt;div id='light'&gt;\n &lt;input type='button' id='red' :class='[\"btn\", {\"btn-danger\": (count % 3 === 0)}]' /&gt;\n &lt;br /&gt;\n &lt;input type='button' id='yellow' :class='[\"btn\", {\"btn-warning\": (count % 3 === 1)}]' /&gt;\n &lt;br /&gt;\n &lt;input type='button' id='green' :class='[\"btn\", {\"btn-success\": (count % 3 === 2)}]' /&gt;\n &lt;/div&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><sup>1</sup><sub><a href=\"https://vuejs.org/v2/guide/class-and-style.html#Array-Syntax\" rel=\"nofollow noreferrer\">https://vuejs.org/v2/guide/class-and-style.html#Array-Syntax</a></sub></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T22:17:06.040", "Id": "208197", "ParentId": "208183", "Score": "1" } } ]
{ "AcceptedAnswerId": "208197", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T20:07:07.417", "Id": "208183", "Score": "1", "Tags": [ "javascript", "html", "css", "twitter-bootstrap", "vue.js" ], "Title": "Vue.js Stoplight app - Dynamically changing classes on elements" }
208183
<p>I am quite new to C++ and would like some feedback on my implementation of a dictionary data structure. The code is below.</p> <pre><code>#ifndef DICTIONARY_H_INCLUDED #define DICTIONARY_H_INCLUDED #include &lt;initializer_list&gt; #include &lt;algorithm&gt; #include &lt;vector&gt; template &lt;typename T, typename U&gt; class Dictionary{ private: std::vector&lt;T&gt; keys; std::vector&lt;U&gt; values; public: Dictionary(); Dictionary(std::initializer_list&lt;std::pair&lt;T,U&gt;&gt;); bool has(T) const; void add(T,U); T* begin(); T* end(); U operator[](T); }; template &lt;typename T, typename U&gt; T* Dictionary&lt;T,U&gt;::begin(){ return &amp;(keys[0]); } template &lt;typename T, typename U&gt; T* Dictionary&lt;T,U&gt;::end(){ return &amp;(keys[keys.size()-1])+1; } template &lt;typename T, typename U&gt; Dictionary&lt;T,U&gt;::Dictionary (std::initializer_list&lt;std::pair&lt;T,U&gt;&gt; store){ for (std::pair&lt;T,U&gt; object : store){ keys.push_back(object.first); values.push_back(object.second); } } template &lt;typename T, typename U&gt; bool Dictionary&lt;T,U&gt;::has(T targetKey) const{ for (T currentKey : keys){ if (currentKey == targetKey){ return true; } } return false; } template &lt;typename T, typename U&gt; void Dictionary&lt;T,U&gt;::add (T key, U value){ keys.push_back(key); values.push_back(value); } template &lt;typename T, typename U&gt; U Dictionary&lt;T,U&gt;::operator[] (T key){ unsigned int pos = std::find(keys.begin(), keys.end(), key) - keys.begin(); return values[pos]; } #endif // DICTIONARY_H_INCLUDED </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T21:32:12.127", "Id": "402078", "Score": "3", "body": "Do you have any tests, or sample code that shows how it's used? That would help people to review this." } ]
[ { "body": "<p>The representation (as a parallel pair of vectors) isn't as good as the alternative (a single vector of pairs), because:</p>\n\n<ol>\n<li>any time the vectors have to grow, there's two separate allocations rather than just one, and</li>\n<li>whenever they are used, the data may be in different regions of memory (the code has poorer <em>spatial locality</em>).</li>\n</ol>\n\n<p>Consider instead writing</p>\n\n<pre><code>using value_type = std::pair&lt;T, U&gt;;\nstd::vector&lt;value_type&gt; entries;\n</code></pre>\n\n<p>This will change the interface a little - in particular, <code>begin()</code> and <code>end()</code> will now give iterators that access these pairs. That's more consistent with <code>std::map</code> interface, so I recommend that.</p>\n\n<hr>\n\n<p>We can reduce duplication a little: in the initializer-list constructor, we can simply call <code>add()</code> for each element rather than re-writing its body:</p>\n\n<pre><code>template &lt;typename T, typename U&gt;\nDictionary&lt;T,U&gt;::Dictionary (std::initializer_list&lt;std::pair&lt;T,U&gt;&gt; store)\n{\n for (std::pair&lt;T,U&gt; object : store) {\n add(object.first, object.second);\n }\n}\n</code></pre>\n\n<p>On the other hand, if we've changed our representation as above, we simply have</p>\n\n<pre><code>template &lt;typename T, typename U&gt;\nDictionary&lt;T,U&gt;::Dictionary (std::initializer_list&lt;std::pair&lt;T,U&gt;&gt; store)\n{\n for (std::pair&lt;T,U&gt; object : store) {\n entries.push_back(object);\n }\n}\n</code></pre>\n\n<hr>\n\n<p>The indexing operator is surprising. If <code>key</code> doesn't exist in the dictionary, then we have undefined behaviour (accessing <code>values</code> out of range). That's a valid choice, but worthy of a comment (particularly as it diverges from the Standard Library interface). Since it doesn't create as necessary, and only ever returns a <em>copy</em> of the value (rather than a reference) it probably ought to be declared <code>const</code>.</p>\n\n<hr>\n\n<p>We should probably check whether <code>key</code> already exists in <code>add()</code>. We can then either ignore it, or update the existing value. What we have at the moment is the worst possible choice - we add data that can never be used, which only serves to slow future operations.</p>\n\n<hr>\n\n<p>Some other useful accessors are missing - constant and/or reverse iterators spring to mind as an obvious example, as do methods of removing values. A <code>swap()</code> member would also be very useful.</p>\n\n<hr>\n\n<p>The <code>has</code> function can be simplified a bit with the use of a standard algorithm: <code>std::any_of()</code> can replace the loop.</p>\n\n<hr>\n\n<h1>Algorithmic complexity</h1>\n\n<p>Our <code>operator[]</code> uses linear search with <code>std::find()</code>. Whilst this works, it will get slower in proportion to the number of elements contained - in \"big O\" notation, we say that it <em>scales as O(n)</em>. Once we have the interface as we we want, we'll then want to look at changing the data structure to improve look-up times (and we might need to trade against insertion speed). The good news is that storing items as pairs will work well with whatever storage we choose, and it will be much easier to change the implementation than with separate storage of keys and values.</p>\n\n<p>It may well be worth moving to pair-based storage, and implementing the other review items, and then returning for a performance review of the new code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T09:49:33.993", "Id": "402147", "Score": "0", "body": "Shouldn't you have tackled performance issues also? `O(n)` look-up isn't acceptable in a map-like container, because it wouldn't add anything to a simple `std::vector` + `std::find`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T10:13:19.080", "Id": "402148", "Score": "0", "body": "Yes, you're right - I wrote this in a rush and didn't get to that part. I believe it's important to get the interface right first, and there were sufficient changes there that changing the algorithm was going to be too much in one go." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T10:21:40.660", "Id": "402149", "Score": "0", "body": "@papagaga - I've edited to recommend returning for a performance review after first round of fixes." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T21:51:27.240", "Id": "208192", "ParentId": "208188", "Score": "7" } }, { "body": "<p>Definition for default constructor is missing.</p>\n\n<hr>\n\n<p>Begin() and end() cause UB when dictionary is empty because you performed out of bound access on the keys vector. Begin and end should return iterator that allow access of both key and value. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T08:37:37.277", "Id": "402134", "Score": "0", "body": "Good observations - I missed both of these in my review." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T07:24:52.117", "Id": "208215", "ParentId": "208188", "Score": "5" } } ]
{ "AcceptedAnswerId": "208192", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T20:59:41.767", "Id": "208188", "Score": "5", "Tags": [ "c++", "hash-map" ], "Title": "C++ Implementation of a dictionary data structure" }
208188
<p>I have a class that makes API requests for a mobile app. The code can be making multiple API requests at the same time. But, if the request is unauthorized, I want to refresh the access token. While the refresh is occurring, I do not want another process to try to refresh the token.</p> <p>I think there should be a better way to keep other processes from refreshing the token while another process is refreshing the token.</p> <p>The <code>TTSecureStorage</code> class is a wrapper around the Xamarin Essentials Secure Storage where I can store values using the devices Secure Storage.</p> <pre><code>namespace TTAzureClient { public class AuthenticationDelegator : DelegatingHandler { public static string Token; private static readonly SemaphoreSlim semaphore = new SemaphoreSlim(1); private static bool isReauthenticating = false; public object UserUtilities { get; private set; } protected override async Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // Clone the request, in case we need to re-issue it var clone = await CloneHttpRequestMessageAsync(request); try { string authToken = await TTSecureStorage.TokenStorage.GetAccessToken(); clone.Headers.Remove("X-ZUMO-AUTH"); clone.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authToken); var response = await base.SendAsync(clone, cancellationToken); if (response.StatusCode == HttpStatusCode.Unauthorized) { TTSecureStorage.TokenStorage.RemoveAll(); TTSecureStorage.UserDetailStorage.RemoveAll(); var refreshToken = await TTSecureStorage.TokenStorage.GetRefreshToken(); if (!String.IsNullOrEmpty(refreshToken)) { await semaphore.WaitAsync(); string newToken = await TTSecureStorage.TokenStorage.GetAccessToken(); if (String.IsNullOrEmpty(newToken)) { await RefreshToken(); } authToken = await TTSecureStorage.TokenStorage.GetAccessToken(); semaphore.Release(); clone.Headers.Remove("Authorization"); clone.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authToken); response = await base.SendAsync(clone, cancellationToken); } } return response; } catch (Exception ex) { throw ex; } finally { semaphore.Release(); } } /// &lt;summary&gt; /// Clone a HttpRequestMessage /// Credit: http://stackoverflow.com/questions/25044166/how-to-clone-a-httprequestmessage-when-the-original-request-has-content /// &lt;/summary&gt; /// &lt;param name="req"&gt;The request&lt;/param&gt; /// &lt;returns&gt;A copy of the request&lt;/returns&gt; public static async Task&lt;HttpRequestMessage&gt; CloneHttpRequestMessageAsync(HttpRequestMessage req) { HttpRequestMessage clone = new HttpRequestMessage(req.Method, req.RequestUri); // Copy the request's content (via a MemoryStream) into the cloned object var ms = new MemoryStream(); if (req.Content != null) { await req.Content.CopyToAsync(ms).ConfigureAwait(false); ms.Position = 0; clone.Content = new StreamContent(ms); // Copy the content headers if (req.Content.Headers != null) foreach (var h in req.Content.Headers) clone.Content.Headers.Add(h.Key, h.Value); } clone.Version = req.Version; foreach (KeyValuePair&lt;string, object&gt; prop in req.Properties) clone.Properties.Add(prop); foreach (KeyValuePair&lt;string, IEnumerable&lt;string&gt;&gt; header in req.Headers) clone.Headers.TryAddWithoutValidation(header.Key, header.Value); return clone; } private async Task&lt;bool&gt; RefreshToken() { try { string refresh_token = await TTSecureStorage.TokenStorage.GetRefreshToken(); HttpClient client = new HttpClient(); client.BaseAddress = new Uri("https://login.microsoftonline.com/&lt;tenant&gt;/oauth2/v2.0/token?p=b2c_1_b2c_tt_ropc"); var request = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress); request.Headers.Add("Accept", "application/json"); var dict = new Dictionary&lt;string, string&gt;(); dict.Add("grant_type", "refresh_token"); dict.Add("resource", "&lt;resource id&gt;"); dict.Add("client_id", "&lt;client id&gt;"); dict.Add("response_type", "id_token"); dict.Add("refresh_token", refresh_token); request.Content = new FormUrlEncodedContent(dict); var result = await client.SendAsync(request); JsonSerializer json = new JsonSerializer(); if (result.StatusCode != System.Net.HttpStatusCode.OK) { var exMsg = await result.Content.ReadAsStringAsync(); try { dynamic e = JsonConvert.DeserializeObject(exMsg); //throw new MsalException(e.error, e.error_description); } catch (Exception exi) { //throw new Exception(exMsg); return false; } } var msg = await result.Content.ReadAsStringAsync(); dynamic ar = JsonConvert.DeserializeObject(msg); //UserUtilities.token = ar.access_token; //UserUtilities.userAzureId = ar.id_token; Utils.Settings.Current.AuthToken = ar.access_token; Utils.Settings.Current.AzureMobileUserId = ar.id_token; Utils.Settings.Current.RefreshToken = ar.refresh_token; try { TokenStorage.RemoveAll(); await TokenStorage.SetAccessToken(Convert.ToString(ar.access_token)); await TokenStorage.SetIdToken(Convert.ToString(ar.id_token)); await TokenStorage.SetRefreshToken(Convert.ToString(ar.refresh_token)); } catch (Exception ex) { // Possible that device doesn't support secure storage on device. } return true; } catch (System.Exception e) { } return false; } } </code></pre> <p>}</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T21:03:17.957", "Id": "208189", "Score": "1", "Tags": [ "c#", "authentication", "xamarin" ], "Title": "Make API request with Access Token and Refresh" }
208189
<p>I have just begun learning Julia. Here is an implementation of experience replay memory for use in a reinforcement learning algorithm. It is pretty simple, essentially a ring buffer with the following requirements:</p> <ul> <li>Used to store 1D arrays of numbers, typically Float32 or Float64. All the stored arrays are the same size.</li> <li>Has a maximum capacity, after which new entries overwrite old ones</li> <li>Has a sample function for retrieving a given number of entries</li> </ul> <p></p> <pre><code>import Base.length struct Memory{T &lt;: Real} max_size::UInt32 experiences::Vector{Vector{T}} end Memory{T}(max_size) where {T &lt;: Real} = Memory{T}(max_size, Vector{Vector{T}}()) length(memory::Memory) = length(memory.experiences) function remember!(memory::Memory, experience) size = length(memory) if size == memory.max_size memory.experiences[1 + size % memory.max_size] = experience else push!(memory.experiences, experience) end end function sample(memory::Memory{T}, count::Integer) where {T &lt;: Real} size = length(memory) @assert count &lt;= size return [memory.experiences[1 + rand(UInt32) % size] for i in 1:count] end </code></pre>
[]
[ { "body": "<ul>\n<li>There's a <a href=\"https://github.com/JuliaCollections/DataStructures.jl/blob/master/src/circular_buffer.jl\" rel=\"nofollow noreferrer\"><code>CircularBuffer</code></a> type in <code>DataStructures</code>, which does pretty much the same. Have a look at its code for some inspiration. Or reuse it, if it fits your needs and you don't hesitate to add that dependency.</li>\n<li>Regarding the point before, I'd especially recommend to implement the common interfaces, and probably <code>iterate</code> as well. <code>remember!</code> makes sense semantically, but <code>push!</code> is the standard name for this functionality. You could implement <code>remember!</code> in terms of <code>push!</code> and export both, or just use <code>push!</code> and mention it in the docs.</li>\n<li><p>There isn't really a need to be so specific about types. I'd just use</p>\n\n<pre><code>struct Memory{T}\n max_size::UInt32\n experiences::Vector{T}\nend\n</code></pre>\n\n<p>Nothing is lost by generalizing in this way, since you never use information about the content. But who knows, maybe you later want switch to different types for experiences, eg. <code>StaticVector</code>s.</p></li>\n<li><p>I would doubt whether using <code>UInt32</code> saves more than it complicates. <code>Int</code> is pretty much standard for everything of this kind: lengths, indices, offsets, etc.</p></li>\n<li>Depending on the sizes of your use case, it might be better to preallocate <code>experiences</code> as <code>Vector{T}(undef, max_size)</code> and use just indexing (and keeping track of the actual length), instead of <code>push!</code>ing until full -- see the <code>DataStructures</code> implementation. If not, calling <code>sizehint!(experiences, max_size)</code> might be good, if you expect to always exhaust the full capacity.</li>\n<li><p>Instead of providing <code>sample</code>, I'd recommend <a href=\"https://docs.julialang.org/en/v1.0/stdlib/Random/#Hooking-into-the-Random-API-1\" rel=\"nofollow noreferrer\">hooking into <code>rand</code></a>, thereby getting more methods for free. In the simplest case, this just consists of defining </p>\n\n<pre><code>Random.rand(rng::Random.AbstractRNG, s::Random.SamplerTrivial{Memory{T}}) where {T} = rand(rng, s[].experiences)\n</code></pre>\n\n<p>which gives you all variations: <code>rand(m)</code>, <code>rand(m, N)</code> (corresponging to your <code>sample</code>), <code>rand(rng, m)</code>, etc. Especially the form with a provided RNG is relevant if you want to write reproducible experiments. The <code>rand!</code> methods seem not to work by default, but can be added easily if you need them. (If you switch to a preallocation + indexing solution, you need to make sure to sample only from <code>@view experiences[1:length]</code>.)</p>\n\n<p>And note that you can directly sample from an array <code>a</code> using <code>rand(a)</code>.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-09T15:39:29.197", "Id": "209317", "ParentId": "208190", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T21:03:23.413", "Id": "208190", "Score": "1", "Tags": [ "julia" ], "Title": "Experience replay memory" }
208190
<p>I'm trying to tackle a <a href="https://www.hackerrank.com/challenges/circular-palindromes/problem" rel="nofollow noreferrer">programming challenge</a> to determine how many palindromes exist in a given string that is being rotated character by character. My solution works, but it's too slow, and I'm struggling on where to optimize it.</p> <p>For example, the string "cacbbba" would rotate 6 times, and would have 3 palindromes in each string.</p> <ol> <li>cacbbba (3 palindromes)</li> <li>acbbba<strong>c</strong> (3 palindromes)</li> <li>cbbba<strong>ca</strong> (3 palindromes)</li> <li>bbba<strong>cac</strong> (3 palindromes)</li> <li>bba<strong>cacb</strong> (3 palindromes)</li> <li>ba<strong>cacbb</strong> (3 palindromes)</li> <li>a<strong>cacbbb</strong> (3 palindromes)</li> </ol> <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 circularPalindromes(s) { const k = s.length; const result = []; const isPalindrome = (str) =&gt; { const len = str.length; for (let i = 0; i &lt; len / 2; i++) { if (str[i] !== str[len - 1 - i]) { return false; } } return true; }; const subs = (s) =&gt; { let max = 0; for (let i = 0; i &lt; s.length; i++) { for (let j = 1; j &lt;= s.length - i; j++) { const sub = s.substring(i, i + j); if (sub.length &lt; 2) continue; if (isPalindrome(sub) &amp;&amp; sub.length &gt; max) { max = sub.length; } } } return max; }; for (let i = 0; i &lt; k; i++) { result.push(subs(s.substring(i, k) + s.substring(0, i))); } return result; } console.log(circularPalindromes('cacbbba'));</code></pre> </div> </div> </p>
[]
[ { "body": "<p>After trying to optimize my current solution and getting nowhere fast, I went back to the drawing board and came up with this solution. The performance gains are outstanding: <code>543,334 ops per/sec</code> vs. <code>275 ops per/sec</code></p>\n\n<h1>Performance Test</h1>\n\n<p><a href=\"https://jsperf.com/largest-vs-subs\" rel=\"nofollow noreferrer\">https://jsperf.com/largest-vs-subs</a></p>\n\n<h1>Solution</h1>\n\n<pre><code>function circularPalindromes(s) {\n s = s.split('');\n\n let currentLength, equalsLength, j1, j2;\n const length = s.length;\n const length2 = s.length - 1;\n const largest = new Array(s.length).fill(0);\n\n for (let i = 0; i &lt; s.length; i++) {\n currentLength = 1;\n j1 = (i &lt; 1) ? length2 : i - 1;\n j2 = (i &gt;= length2) ? 0 : i + 1;\n\n while (s[i] === s[j2] &amp;&amp; currentLength &lt; length) {\n currentLength++;\n if (++j2 &gt;= length) j2 = 0;\n }\n equalsLength = currentLength;\n\n if (currentLength &gt; 1) {\n checkEqual(largest, i, currentLength);\n i += currentLength - 1;\n }\n\n while (s[j1] === s[j2] &amp;&amp; currentLength &lt; length &amp;&amp; j1 !== j2) {\n currentLength += 2;\n if (--j1 &lt; 0) j1 = length2;\n if (++j2 &gt;= length) j2 = 0;\n }\n\n if (currentLength &gt; equalsLength) {\n if(++j1 &gt;= length) j1 = 0;\n checkLargest(largest, j1, currentLength, equalsLength);\n }\n }\n\n return largest;\n}\n\nfunction checkEqual(largest, position, length) {\n const limit = position + length;\n const middle = position + (length &gt;&gt; 1);\n const even = (length &amp; 1) === 0;\n\n for (let i = (position - largest.length + length &lt; 0 ? 0 : position - largest.length + length); i &lt; position; i++) {\n if (largest[i] &lt; length) largest[i] = length;\n }\n\n for (let i = position + length; i &lt; largest.length; i++) {\n if (largest[i] &lt; length) largest[i] = length;\n }\n\n for (let i = position, j = position; i &lt; limit; i++, j++) {\n if (j &gt;= largest.length) j = i % largest.length;\n if (largest[j] &lt; length) largest[j] = length;\n if (i &lt; middle){\n length--;\n } else if (i &gt; middle) {\n length++;\n } else if (even) {\n length++;\n }\n }\n}\n\nfunction checkLargest(largest, position, length, equalsLength) {\n const limit1 = position + (length &gt;&gt; 1) - (equalsLength &gt;&gt; 1);\n const limit2 = position + length;\n\n for (let i = (position - largest.length + length &lt; 0 ? 0 : position - largest.length + length); i &lt; position; i++) {\n if (largest[i] &lt; length) largest[i] = length;\n }\n\n for (let i = position + length; i &lt; largest.length; i++) {\n if (largest[i] &lt; length) largest[i] = length;\n }\n\n for (let i = position, j = position; i &lt; limit1; i++, j++) {\n if (j &gt;= largest.length) j = i % largest.length;\n if (largest[j] &lt; length) largest[j] = length;\n length -= 2;\n }\n\n for (let i = limit1 + equalsLength, j = limit1 + equalsLength; i &lt; limit2; i++, j++) {\n if (j &gt;= largest.length) j = i % largest.length;\n if (largest[j] &lt; length) largest[j] = length;\n length += 2;\n }\n}\n\nconsole.log(circularPalindromes('cacbbba'));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T12:28:57.643", "Id": "402162", "Score": "0", "body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T20:56:28.587", "Id": "402197", "Score": "0", "body": "I'll go back and add some explanation; however, I did explain why it's better than the original, and even attached a performance test. Also, I am the author :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T04:32:48.347", "Id": "208208", "ParentId": "208203", "Score": "1" } } ]
{ "AcceptedAnswerId": "208208", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T01:06:58.693", "Id": "208203", "Score": "2", "Tags": [ "javascript", "algorithm", "programming-challenge", "palindrome", "circular-list" ], "Title": "Find palindromes in circular rotated string" }
208203
<p>A friend of mines needed some help. He wanted to build up two linked list and then compared them to see if they had the same data values. Finally a 3rd link list would contain the nodes with duplicated data. The linked list holds int data btw. I redid his code and I was aiming to be as simple and clean as possible but I have a shaky feeling. Below is my code and his code together. I feel there is something to learn from both of us so I posted both of our codes although my solution is fully finished. Is my code simple and clean? Is my friend's code formatted in such a way that my code is missing it? Does my look good on the eyes. Critique on both solution would help me grow a bit. </p> <p>Laurent's code</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; using namespace std; struct Node{ Node* next; int data; }; class LinkedList{ private: int length; Node* head; public: LinkedList(); ~LinkedList(); Node* getHead(); void appendToTail(int data); void appendExistingNodesToTail(Node* newtail, int data); //Takes a collection of node pointers. This is used to append existing nodes from other lists to it own list. void insertToHead(int data); void print(); }; LinkedList::LinkedList(){ this-&gt;length = 0; this-&gt;head = NULL; } LinkedList::~LinkedList(){ //avoid memory leaks.... give back what you take Node* next = head; Node* cur = NULL; while (next != NULL) { cur = next; next = next-&gt;next; delete cur; } cout &lt;&lt; "LIST DELETED"&lt;&lt; endl; } Node* LinkedList::getHead(){ return head; } void LinkedList::appendToTail(int data){ Node *newtail = new Node; newtail-&gt;data = data; newtail-&gt;next = nullptr; if (this-&gt;head == nullptr) { head = newtail; } else { Node *temp = head; while (temp-&gt;next != nullptr) { temp = temp-&gt;next; } temp-&gt;next = newtail; this-&gt;length++; } } void LinkedList::appendExistingNodesToTail(Node* newtail, int data){ newtail = new Node; newtail-&gt;data = data; newtail-&gt;next = nullptr; if (this-&gt;head == nullptr) { head = newtail; } else { Node *temp = head; while (temp-&gt;next != nullptr) { temp = temp-&gt;next; } temp-&gt;next = newtail; this-&gt;length++; } } void LinkedList::insertToHead(int data){ Node* newhead = new Node; newhead-&gt;data = data; newhead-&gt;next = this-&gt;head; this-&gt;head = newhead; this-&gt;length++; } void LinkedList::print(){ Node* head = this-&gt;head; int i = 1; while(head){ std::cout &lt;&lt; i &lt;&lt; ": " &lt;&lt; head-&gt;data &lt;&lt; std::endl; head = head-&gt;next; i++; } cout &lt;&lt; endl; } //-------------------------------------GENERAL PURPOSE FUNCTIONS------------------------------------------// void generateDuplicateNodeDataFound(LinkedList* list_a, LinkedList* list_b, LinkedList* list_c){ //Find the duplicate values to build up list c from existing nodes from list a&amp;b. Need two list to compare, one list to build Node* head1 = list_a-&gt;getHead(); Node* head2 = list_b-&gt;getHead(); while(head1){ while(head2){ if (head1-&gt;data == head2-&gt;data){ list_c-&gt;appendExistingNodesToTail(head1, head1-&gt;data); break; } head2 = head2-&gt;next; } head1 = head1-&gt;next; head2 = list_b-&gt;getHead(); // Reset } } int main(int argc, char const *argv[]){ LinkedList* list1 = new LinkedList(); LinkedList* list2 = new LinkedList(); LinkedList* list_found_duplicates = new LinkedList(); int arr1[] = {2,5,7,9,0,2}; int arr2[] = {9,78,3,2,5,9}; //https://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c int lenght = sizeof(arr1) / sizeof(arr1[0]); for(int i=0; i&lt;lenght; i++){ list1-&gt;appendToTail(arr1[i]); } lenght = sizeof(arr2) / sizeof(arr2[0]); for(int i=0; i&lt;lenght; i++){ list2-&gt;appendToTail(arr2[i]); } list1-&gt;print(); list2-&gt;print(); generateDuplicateNodeDataFound(list1, list2, list_found_duplicates); list_found_duplicates-&gt;print(); delete list1; delete list2; delete list_found_duplicates; cin&gt;&gt; arr1[0]; return 0; } </code></pre> <p>Laurent's Friend code</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; using namespace std; class Node{ public: Node(int value= 0, Node* nextNode= nullptr); void insertAfter(Node* newPtr); Node* getNext(); int getValue(); private: int val; Node* nextNodePtr; }; Node::Node(int value, Node* nextNode){ this-&gt;val= value; this-&gt;nextNodePtr= nextNode; } void Node::insertAfter(Node* newPtr){ Node* tempPtr = nullptr; tempPtr= this-&gt;nextNodePtr; this-&gt;nextNodePtr = newPtr; newPtr-&gt;nextNodePtr =tempPtr; } Node* Node::getNext(){ return nextNodePtr; } int Node::getValue(){ return this-&gt;val; } bool search(int Key, Node* temp){ bool found= false; if(temp!= nullptr){ while(Key != temp-&gt;getValue()){ temp= temp-&gt;getNext(); cout&lt;&lt;Key&lt;&lt;" , "&lt;&lt;temp-&gt;getValue()&lt;&lt;endl; if(temp-&gt;getNext() == 0){ found= false; break; } } if(Key==temp-&gt;getValue()){ found=true; } } return found; } //tries to intersect void intersect(Node* start1, Node* start2,Node* node){ Node* node1 = start1; Node* node2 = start2; Node* temp= nullptr; cout&lt;&lt;"\n!i am here!\n"; while(node1!=nullptr){ cout&lt;&lt;"\n"&lt;&lt;node1-&gt;getValue()&lt;&lt;"\n"; cout&lt;&lt;"\n!i am here now!\n"; if (search(node1-&gt;getValue(), node2)){ node-&gt;insertAfter(node1); node=node-&gt;getNext(); } node1= node1-&gt;getNext(); } } // prints liked list void printList(Node* start){ while(start-&gt;getNext()!= nullptr){ cout&lt;&lt;start-&gt;getValue()&lt;&lt;" "; start= start-&gt;getNext(); } cout&lt;&lt;start-&gt;getValue(); cout&lt;&lt;endl&lt;&lt;endl; } //merging algorithm void merge(Node* start,Node* end, Node* node){ cout&lt;&lt;start-&gt;getValue()&lt;&lt;" "; while(start-&gt;getNext()!= nullptr){ cout&lt;&lt;start-&gt;getValue()&lt;&lt;" "; node-&gt;insertAfter(start); node= node-&gt;getNext(); start= start-&gt;getNext(); } while(end-&gt;getNext()!=nullptr){ cout&lt;&lt;start-&gt;getValue()&lt;&lt;" "; node-&gt;insertAfter(end); end= end-&gt;getNext(); } } int main() { Node* new1= nullptr; Node* new2= nullptr; Node* new3= nullptr; int arr[]={2,5,7,9,0,2}; new1 = new Node(arr[0]); new3= new1; for(int i=1; i&lt;6;i++){ new2 = new Node(arr[i]); new3-&gt;insertAfter(new2); new3=new2; } printList(new1); cout&lt;&lt;endl; Node* newst = nullptr; new2= nullptr; new3= nullptr; int arr1[]={9,78,3,2,5,9}; newst = new Node(arr1[0]); new3= newst; for(int i=1; i&lt;6;i++){ new2 = new Node(arr1[i]); new3-&gt;insertAfter(new2); new3=new2; } cout&lt;&lt;endl; printList(newst); if(search(1,new1)){ cout&lt;&lt;"ll\n"; } cout&lt;&lt;"\nll\n"; if(search(7,newst)){ cout&lt;&lt;"lol\n"; } Node* inter = new Node(0); intersect(new1, newst, inter); printList(inter); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T03:43:28.723", "Id": "402102", "Score": "1", "body": "Is your friend aware that you posted their code and allowed you to post it under [CC-BY-SA](https://stackoverflow.blog/2009/06/25/attribution-required/)? By the way, you likely want to add the [tag:comparative-review] tag." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T04:06:28.197", "Id": "402103", "Score": "0", "body": "No, I didn't think it was a big deal because it was for an up coming school assignment. I will ask them and keep and remove the code by their wishes. [EDIT] They don't care." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T05:03:59.113", "Id": "402106", "Score": "0", "body": "Which version of C++ is this targeting? Any? C++98? Or a more modern version, like C++11/14/17? // If this was a solution to an exercise question, it might be helpful to include that question in its original wording. Small details matter!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T05:57:49.943", "Id": "402111", "Score": "1", "body": "Friend's code has two (identical?) `main`s. You may want to remove one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T08:40:53.157", "Id": "402135", "Score": "5", "body": "The output of those 2 \"solutions\" are very different. Even if one ignores the rest, the output of the intersection is `{2, 5, 9, 2}` in your code and `{0, 2}` in your friends' code. // Is the repetition of `2` in the result set intended? Why do those two implementation give different results? To me, it seems like the code either isn't working as intended, or there is some context missing why both answers would be correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T09:42:25.487", "Id": "402145", "Score": "0", "body": "The most interesting part is handling of duplicates; assuming we have `n` occurences of the same value in first list and `m` in second one: Do you want to have `min(n, m)` occurences in result or just one single?" } ]
[ { "body": "<ul>\n<li><p>Avoid <code>using namespace std;</code>. This can easily lead to name clashes. While a recommendation in source files, absolutely no-go in header files(!).</p></li>\n<li><p>It's a good idea to encapsulate the linked list into its own class. However, still anybody could modify the nodes in the list unsupervised, in worst case destroing the list or creating memory leaks. So nobody should be able to change the <code>next</code> pointer apart from <code>LinkedList</code> class. Solution: Make the pointer private and <code>LinkedList</code> a friend of <code>Node</code>; as then <code>Node</code> gets closely coupled to <code>LinkedList</code>, it would be more apprpriate to make the former a nested class of the latter.</p></li>\n<li><p>Give <code>Node</code> class a constructor accepting the value and setting its successor node to nullptr - as your friend did. You don't need accessor functions, remember, you made LinkedList friend (see above). In contrast to your friend, use the constructors initialiser list, though: <pre>\nNode::Node(int data, Node* next)\n: data(data), next(next)\n{ }</pre></p></li>\n<li><p>What did you intend with <code>appendExistingNodesToTail</code>? It does exactly the same as <code>appendToTail</code>, the first parameter is unused and gets overwritten immediately. If you <em>intended</em> to append multiple nodes (then second parameter is not needed): Better accept another <code>LinkedList</code> as const reference and copy the internal data from.</p></li>\n<li><p>In both forementioned functions you forgot to set length to one if the list was empty before. Easiest fix: move <code>length++</code> out of the else clause to the very end of the function.</p></li>\n<li><p>You have <code>appendToTail</code> - for symmetry, I'd name the other function <code>prependToHead</code>.</p></li>\n<li><p>You did not provide search/find function as your friend did; albeit it was just a helper function for your friend, it still would nicely fit into your linked list's interface.</p></li>\n<li><p>You are re-inventing the wheel! While it might be a good <em>exercise</em>, once you're done with, switch over to <code>std::list&lt;int&gt;</code> (doubly linked) or <code>std::forward_list&lt;int&gt;</code> (singly linked).</p></li>\n<li><p>Your friend's merge algorithm is broken: </p></li>\n</ul>\n\n<p>So far for the linked list...</p>\n\n<ul>\n<li><p><code>intersect</code> is the better name (describing the same, but much shorter).</p></li>\n<li><p>Intersection: Assuming you have lists <code>{ 7 }</code> and <code>{ 7, 7 }</code>, then your friend's algorithm will output <code>{ 7 }</code> while yours will: <code>{ 7, 7 }</code>. If you swap arguments, both algorithms will output <code>{ 7, 7 }</code>, i. e. your friend's variant is <em>not</em> symmetric. Your variant, though, with <code>{ 7, 7 }</code> and <code>{ 7, 7 }</code> as arguments, will yield <code>{ 7, 7, 7, 7 }</code>! To avoid, you'd have to check if the current <code>head1</code> element has occured in the list before. But if you do so in the native approach, you'd get an O(n³) algorithm from one that already now is O(n²). So we should really look for better alternatives. If it is fine to modify the lists, you could sort both of them in advance, then finding duplicates is straight forward and O(n). If want to retain original order, you might operate on duplicates instead (possibly copy the data into arrays for faster access and saving memory).</p></li>\n<li><p>... in theory at least. Actually, your friend's <code>intersect</code> algorithm is broken: after <code>node-&gt;insertAfter(node1);</code>, <code>node1</code>'s successor is whatever <code>node</code>s was before, and the rest of the linked list gets lost (leaking). From a point of view of design, it's not a good idea to change the input lists anyway. Your friend would need to create new nodes as you did.</p></li>\n<li><p>Your friend's merge algorithm is broken as well, suffers from same bad usage of <code>insertAfter</code> as <code>intersect</code> does already. Additionally: Why do we need three pointers? We'd pass two lists, merge them into one single list, and best: return pointer to new head. Your friend's algorithm seemd to try to merge as <code>x[0], y[0], x[1], y[1], ...</code>. One could. But what's the benefit from? The lists are not sorted anyway, so one could just as well only <em>append</em> one to the other.</p></li>\n</ul>\n\n<p>My personal assessment: Albeit there are yet a few issues left open, you already did quite a good job on improving the original interface of your friend...</p>\n\n<p>One final issue about your main:</p>\n\n<pre><code>LinkedList* list1 = new LinkedList();\n// ...\ndelete list1;\n</code></pre>\n\n<p>It is good that you <code>delete</code> what you <code>new</code>ed. You can avoid explicit deletion by usage of a smart pointer:</p>\n\n<pre><code>std::unique_ptr&lt;LinkedList&gt; list1(new LinkedList());\n</code></pre>\n\n<p>but why <code>new</code> at all? Your class is not that big that you might risk to consume up too much of the stack, so just do:</p>\n\n<pre><code>LinkedList list1;\n// ^ no pointer!\n</code></pre>\n\n<p>This will create a variable with scope local to main function and as soon as the scope is left, the object is destroyed automatically (just as with the smart pointer; actually, the smart pointer works exactly the same, <code>delete</code>ing the object it points to in its destructor).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T07:47:02.530", "Id": "402119", "Score": "0", "body": "Re \"To avoid, you'd advance `head1` as long as it is equal to its predecessor.\": IIUC, that still wouldn't prevent `{7, 2, 7}` and `{7}` returning `{7, 7}`. A better way would be to check whether the current value is already in the result list." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T07:49:35.160", "Id": "402120", "Score": "0", "body": "@hoffmale Oh, you're absolutely right... Too much used to *sorted* input! Thanks for the hint!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T08:05:05.083", "Id": "402126", "Score": "0", "body": "@ *'is already in the result list'* - one option. `{ 7, 7 }` and `{ 7, 7 }` would yield { 7 } then, though. Possibly valid, unsuitable, if we *wanted* to get `{ 7, 7 }` instead... Did not thing thoroughly enough about to be 100% sure, but I think this would give an O(n³) algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T08:31:58.820", "Id": "402132", "Score": "0", "body": "Well, that's why I asked for clarification in my comments on the question. Too much hinges on what the expected output should be. // **Making some assumptions:** If the output order isn't important, one could just sort the input lists in \\$\\mathcal{O}(n \\log n)\\$ and then implement your original suggestion for a total complexity of \\$\\mathcal{O}(n \\log n)\\$. Still, in that case, there is a better linear algorithm: Insert all items from `list1` into an `std::unordered_set`. Then do a pass over `list2`: For each item, if it is in the set, remove it from the set and add it to the output list." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T09:41:07.503", "Id": "402144", "Score": "0", "body": "@hoffmale The hashing approach is nice (`std::unordered_multiset` would allow for multiple values...). Initial try was to avoid additonal memory usage, so sorting the lists *in place*, but with proposition of the duplicates left that territory anyway. Finally, you are right, we are already too deep in the field of assumptions. Let's see what OP answers..." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T07:13:26.183", "Id": "208214", "ParentId": "208205", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T03:38:59.917", "Id": "208205", "Score": "-2", "Tags": [ "c++", "linked-list", "comparative-review" ], "Title": "Build up two linked list, then build up a 3rd link list with nodes of duplicate data from both" }
208205
<p>This function is part of a python board game program. The game is a board game with chests and bandits hidden throughout the board. The function is dedicated to the "easy" section of the game (where it is a 8x8 grid).</p> <pre><code>def easy_level(Coins): #This function is for the movement of the game in easy difficulty while True: oldcurrent=current boardeasy[oldcurrent[0]][oldcurrent[1]]='*' table_game_easy() boardeasy[oldcurrent[0]][oldcurrent[1]]=' ' n = input('Enter the direction followed by the number Ex:Up 5 , Number should be &lt; 8 \n') n=n.split() if n[0].lower() not in ['up','left','down','right']:#Validates input print('Wrong command, please input again') continue elif n[0].lower()=='up': up(int(n[1].lower()),8)#Boundary is set to 8 as the 'easy' grid is a 8^8 elif n[0].lower()=='down': down(int(n[1].lower()),8) elif n[0].lower()=='left': left(int(n[1].lower()),8) elif n[0].lower()=='right': right(int(n[1].lower()),8) print("5 chests left") print("8 bandits left") print("Coins:",Coins)#Acts as a counter, displays the number of coins that the player has if current[0] == Treasure1_Row and current[1] == Treasure1_Col\ or current[0] == Treasure2_Row and current[1] == Treasure2_Col\ or current[0] == Treasure3_Row and current[1] == Treasure3_Col\ or current[0] == Treasure4_Row and current[1] == Treasure4_Col\ or current[0] == Treasure5_Row and current[1] == Treasure5_Col\ or current[0] == Treasure6_Row and current[1] == Treasure6_Col\ or current[0] == Treasure7_Row and current[1] == Treasure7_Col\ or current[0] == Treasure8_Row and current[1] == Treasure8_Col\ or current[0] == Treasure9_Row and current[1] == Treasure9_Col\ or current[0] == Treasure10_Row and current[1] == Treasure10_Col: print("Hooray! You have found booty! +10 gold") Coins = Coins+10 #Adds an additional 10 points print("Coins:",Coins) if current[0] == Bandit1_Row and current[1] == Bandit1_Col\ or current[0] == Bandit2_Row and current[1] == Bandit2_Col\ or current[0] == Bandit3_Row and current[1] == Bandit3_Col\ or current[0] == Bandit4_Row and current[1] == Bandit4_Col\ or current[0] == Bandit5_Row and current[1] == Bandit5_Col: print("Oh no! You have landed on a bandit...they steal all your coins!") Coins = Coins-Coins #Removes all coins print("Coins:",Coins) boardeasy[current[0]][current[1]]='*'#sets value to players position </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-14T00:00:13.187", "Id": "402104", "Score": "2", "body": "what do you mean more efficient?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-14T00:01:41.877", "Id": "402105", "Score": "1", "body": "Reduce the amount of code needed perhaps?" } ]
[ { "body": "<p>We're definitely missing some context here to run your code or understand what it is supposed to do, but there is enough to detect a few things that could be easily improved.</p>\n\n<hr>\n\n<pre><code> Coins = Coins-Coins #Removes all coins\n</code></pre>\n\n<p>This should be:</p>\n\n<pre><code> Coins = 0 #Removes all coins\n</code></pre>\n\n<p>Also</p>\n\n<pre><code> Coins = Coins+10 #Adds an additional 10 points\n</code></pre>\n\n<p>can be written</p>\n\n<pre><code> Coins += 10 #Adds an additional 10 points\n</code></pre>\n\n<hr>\n\n<p>Don't perform the same operations more than needed. In particular when handling the user input, you can limit the number of index accesses, to call to <code>lower</code> function, to call to <code>int</code> function:</p>\n\n<pre><code> user_input = input('Enter the direction followed by the number Ex:Up 5 , Number should be &lt; 8 \\n').split()\n if len(user_input) != 2:\n print('Wrong command, please input again')\n continue\n direct, number = user_input\n direct = direct.lower()\n number = int(number.lower())\n if direct not in ['up','left','down','right']:#Validates input\n print('Wrong command, please input again')\n continue\n elif direct == 'up':\n up(number, 8) #Boundary is set to 8 as the 'easy' grid is a 8^8\n elif direct == 'down':\n down(number, 8)\n elif direct == 'left':\n left(number, 8)\n elif direct == 'right':\n right(number, 8)\n</code></pre>\n\n<p>Then, you can actually change the condition order so that you don't need to list twice the valid directions:</p>\n\n<pre><code> if direct == 'up':\n up(number, 8) #Boundary is set to 8 as the 'easy' grid is a 8^8\n elif direct == 'down':\n down(number, 8)\n elif direct == 'left':\n left(number, 8)\n elif direct == 'right':\n right(number, 8)\n else:\n print('Wrong command, please input again')\n continue\n</code></pre>\n\n<hr>\n\n<p>You could probably rewrite the comparisons to have something like:</p>\n\n<pre><code> if current == Treasure1_Pos\\\n or current == Treasure2_Pos\\\n or current == Treasure3_Pos\\\n or current == Treasure4_Pos\\\n or current == Treasure5_Pos\\\n or current == Treasure6_Pos\\\n or current == Treasure7_Pos\\\n or current == Treasure8_Pos\\\n or current == Treasure9_Pos\\\n or current == Treasure10_Pos:\n print(\"Hooray! You have found booty! +10 gold\")\n Coins += 10 #Adds an additional 10 points\n print(\"Coins:\",Coins)\n\n if current == Bandit1_Pos\\\n or current == Bandit2_Pos\\\n or current == Bandit3_Pos\\\n or current == Bandit4_Pos\\\n or current == Bandit5_Pos:\n print(\"Oh no! You have landed on a bandit...they steal all your coins!\")\n Coins = 0 #Removes all coins\n print(\"Coins:\",Coins)\n</code></pre>\n\n<p>And you could even define a data structure (list, set) to hold all the relevant positions and write something like:</p>\n\n<pre><code> if current in Treasure_Positions:\n print(\"Hooray! You have found booty! +10 gold\")\n Coins += 10 #Adds an additional 10 points\n print(\"Coins:\",Coins)\n\n if current in Bandit_Positions:\n print(\"Oh no! You have landed on a bandit...they steal all your coins!\")\n Coins = 0 #Removes all coins\n print(\"Coins:\",Coins)\n</code></pre>\n\n<hr>\n\n<p>Then more things look wrong/improvable about <code>boardeasy</code> but we'd need to see what it does.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T08:44:03.697", "Id": "208217", "ParentId": "208206", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-13T23:52:51.903", "Id": "208206", "Score": "0", "Tags": [ "python", "game" ], "Title": "Function in a board game with chests and bandits" }
208206
<p>Tired of thinking up random names when following tutorials involving people? So was I.</p> <p>The code below is the first project I've written in Python. Put simply, it grabs a list of forenames and last-names from an online database, saves them into a dictionary, then writes it to a JSON file. After that, the rest of the code reads the JSON file, chooses a first and last name based on any regex strings passed into the function, then returns the first and last name as a single string, separated by a space.</p> <p>I've noticed however, this baby is <strong>sloooooow</strong>. I'm talking 150 - 200ms to generate a name. That's 20 seconds to generate a list of 100 names. I know there's huge room for improvement here, but I'm not well versed enough in the standard libraries yet.</p> <p>Here it is:</p> <pre><code>from codecs import decode from json import dump, loads from pathlib import Path from random import randrange from re import compile, findall, IGNORECASE from timeit import default_timer as timer from urllib import request DB_FORE = 'https://raw.githubusercontent.com/smashew/NameDatabases/master/NamesDatabases/first%20names/us.txt' DB_LAST = 'https://raw.githubusercontent.com/smashew/NameDatabases/master/NamesDatabases/surnames/us.txt' def write_names(dest, url_forename = DB_FORE, url_surname = DB_LAST): """ Writes the names from the database to the given destination. :param dest: the name of the destination file. Blank if you want the string returned :param url_forename: url containing plain text first names, entries separated by \r\n :param url_surname: url containing plain text last names, entries separated by \n """ names = { # Last values tend to be buggy, so get rid of them 'forenames': _get_names(url_forename).split("\r\n")[:-1], 'surnames': _get_names(url_surname).split("\n")[:-1], } with open(dest, 'w') as json_file: dump(names, json_file, indent = 4, separators = (',', ': ')) def random_name(fmatches = '', smatches = ''): """ Gets a random name in the form "Forename Lastname". :param fmatches: a regex string to try to match to a forename :param smatches: a regex string to try to match to a surname :return: a random name based on the regex inputs, or None if no names were found """ file_name = 'names.json' names_file = Path(file_name) if not Path(names_file).is_file(): print(f'{file_name} not found, writing from default database') write_names(file_name) print('Done!') with names_file.open('r') as json_file: names = loads(json_file.read()) first = _choose_name(fmatches, names['forenames']) last = _choose_name(smatches, names['surnames']) if first is None or last is None: return None else: return first + " " + last def _get_names(url): with request.urlopen(url) as site: return str(decode(site.read(), 'utf-8')) def _choose_name(expr, data): if expr is None: return data[randrange(0, len(data))] else: return _random_match(compile(expr, flags = IGNORECASE), data) def _match_names(expr, data): return [name for name in data if findall(expr, name)] def _random_match(expr, data): matches = _match_names(expr, data) return matches[randrange(0, len(matches))] if len(matches) &gt; 0 else None if __name__ == '__main__': start = timer() print(random_name('rose', 'an')) end = timer() print(end - start, '\n') start = timer() print(random_name(fmatches = '^jo')) end = timer() print(end - start, '\n') start = timer() print(random_name(smatches = 'en$')) end = timer() print(end - start, '\n') start = timer() print(random_name(fmatches = 'grf')) end = timer() print(end - start, '\n') start = timer() print([random_name() for _ in range(10)]) end = timer() print(end - start, '\n') </code></pre> <p>The JSON file (named 'names.json') is in the following format:</p> <pre><code>{ "forenames": [ "Aaron", "Abbey", "Abdul", ... ], "surnames": [ "Aaberg", "Aaby", "Aadland", ... ] } </code></pre> <p>For reference, there's about 5,000 forenames, and 90,000 surnames... yeah, I'm thinking that has something to do with how slow it is (go figure). Obviously I could speed up the execution significantly by removing a lot of uncommon names, but I want to know if there is any way I can improve the current implementation with the current list of names.</p> <p>The name generator supports entering regex strings, but I haven't seen any notable performance difference between generating a name with or without regex.</p> <p>Here's a sample output from running the module:</p> <pre><code>Roseanna Sodeman 0.1488200619749599 Joette Knorr 0.21161438351850587 Birdie Tohen 0.15252753028006855 None 0.21214806850333456 ['Mohammed Koelzer', 'Luvenia Kovalcin', 'Danica Lehnen', 'Chad Mannan', 'Naomi Kilborne', 'Cami Lydecker', 'Amie Dearson', 'Seema Reiche', 'Ai Bruhn', 'Laureen Gitthens'] 2.1672272217311948 </code></pre> <p>Because I'm a beginner, I would appreciate reviews on both improving the performance of the code, and also my code style (i.e. any standard libraries I could be utilising, any shortcuts such as List Comprehension that I'm missing).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T05:29:47.333", "Id": "402108", "Score": "2", "body": "partly because of [greedy expressions search in regex is slow](https://stackoverflow.com/questions/26214328/why-python-regex-is-so-slow)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T06:00:01.447", "Id": "402112", "Score": "3", "body": "Partly because you are re-reading the JSON file of names every time you generate a name." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T04:26:31.423", "Id": "208207", "Score": "3", "Tags": [ "python", "performance", "python-3.x" ], "Title": "Random name generator from JSON file" }
208207
<p>I have server-client communication architecture where there is <strong>one</strong> server and <strong>150</strong> clients.</p> <p>The server-client communication happens via Java NIO where all the clients send some or the other data every 10 seconds. Previously we used to queue all the process messages and process all those in a single thread, as the number of clients are more so as the messages, server is not able to process all the messages instantly and there is a delay in processing in turn data loss. So I have thought of implementing <code>CachecThreadPool</code> to process the tasks simultaneously as soon as they come, picked <code>CachedThreadPool</code> over <code>FixedThreadPool</code> because the tasks are short lived and many in number, below is the code for that. The thread which receives messages from client calls <code>ProcessorClass.processData(message)</code> as soon as it receives the message.</p> <pre><code>public class ProcessorClass{ private static final Logger LOGGER = Logger.getLogger(ProcessorClass.class); static ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); public static void processData(StringBuffer message) { Runnable task = new Runnable() { @Override public void run() { try { LOGGER.info("Queue size:"+executor.getQueue().size()); if (message != null){ processMessage(message); } } catch(Exception e) { LOGGER.error("Error happened in run() method" + e.getMessage()); } } }; executor.execute(task); } public static void processMessage(StringBuffer message){ // all the processing of message such as DB operations goes here. } } </code></pre> <p>Doubts:</p> <ol> <li>How CachedThreadPool stores the message in the queue because i haven't defined any explicitly.</li> <li>Should i chose FixedThreadPool over this?</li> <li>Should i make my <code>processMessage()</code> method <strong>synchronized</strong>?</li> </ol> <p>All the suggestions and review comments are welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T14:31:57.423", "Id": "402172", "Score": "0", "body": "Your code is missing something. What's inside `processMessage`? Is it thread-safe? More context usually leads to a better question and better answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T14:44:19.517", "Id": "402177", "Score": "0", "body": "inside processMessage i am performing database operations by parsing the message received,as far as i know i am not doing any operations which deals with shared objects inside that method." } ]
[ { "body": "<ol>\n<li><p>The thread pool is not storing messages on a queue; it is storing <code>Runnable</code> tasks. However, each <code>Runnable</code> task has access to the effectively final <code>StringBuffer message</code> variable from the calling context.</p></li>\n<li><p>See <a href=\"https://stackoverflow.com/questions/17957382/fixedthreadpool-vs-cachedthreadpool-the-lesser-of-two-evils\">this StackOverflow question</a>. Each is a <code>ThreadPoolExecutor</code>, just with different parameters to control how many threads are created and the type of queue. I would lean in favour of the <code>FixedThreadPool</code> with 1 thread for each CPU core, but many other factors can and will impact that; profile to be sure.</p></li>\n<li><p><strong>No</strong>. Making <code>processMessage()</code> synchronized will mean you are single threaded ... worse, because the overhead of multiple threads being scheduled to process the task queue in a single threaded fashion. At 150 messages/10 seconds, with one thread the function would need to complete in 66ms. If you have 8 cores, with 1 thread per core, each thread could take a leisurely 500ms to process the message, as long as they can run independently. You may have parts of <code>processMessage</code> that you may need to make synchronized, but you’ll want to make those regions as small and fast as possible.</p></li>\n</ol>\n\n<p>Other comments:</p>\n\n<p>A <code>StringBuffer</code> is a mutable object; since <code>message</code> is being passed to another thread, for safety, I’d want the message to be transformed into a immutable <code>String</code> so the caller doesn’t clear the message buffer while the executor thread is processing it.</p>\n\n<p><code>processMessage()</code> does not need to be <code>public</code>; <code>private</code> would be more appropriate. </p>\n\n<p>It looks like <code>executor</code> should be <code>private</code> and <code>final</code> as well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T06:48:03.933", "Id": "208212", "ParentId": "208210", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T05:51:26.537", "Id": "208210", "Score": "0", "Tags": [ "java", "multithreading" ], "Title": "Multi threading with CachedThreadPool" }
208210
<p>this is the original question</p> <p><a href="https://www.geeksforgeeks.org/find-the-smallest-positive-number-missing-from-an-unsorted-array/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/find-the-smallest-positive-number-missing-from-an-unsorted-array/</a></p> <p>You are given an unsorted array with both positive and negative elements. You have to find the smallest positive number missing from the array in O(n) time using constant extra space. You can modify the original array.</p> <blockquote> <p>Input: <kbd>{2, 3, 7, 6, 8, -1, -10, 15}</kbd>   Output: <kbd>1</kbd></p> <p>Input: <kbd>{ 2, 3, -7, 6, 8, 1, -10, 15 }</kbd>  Output: <kbd>4</kbd></p> <p>Input: <kbd>{1, 1, 0, -1, -2}</kbd>                Output: <kbd>2</kbd></p> </blockquote> <pre><code>using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ArrayQuestions { [TestClass] public class FindTheSmallestNonnegativeNumberNoyInArray { [TestMethod] public void FindTheSmallestNonnegativeNumberNoyInArrayTest() { int[] array = {2, 3, 7, 6, 8, -1, -10, 15}; int result = FindSmallestPositiveHash(array); int expected = 1; Assert.AreEqual(expected, result); } [TestMethod] public void FindTheSmallestNonnegativeNumberNoyInArrayTest2() { int[] array = { 2, 3, -7, 6, 8, 1, -10, 15 }; int result = FindSmallestPositiveHash(array); int expected = 4; Assert.AreEqual(expected, result); } private int FindSmallestPositiveHash(int[] array) { HashSet&lt;int&gt; set = new HashSet&lt;int&gt;(); int maxPositive = 0; for (int i = 0; i &lt; array.Length; i++) { if (!set.Contains(array[i])) { maxPositive = Math.Max(maxPositive, array[i]); set.Add(array[i]); } } for (int i = 1; i &lt; maxPositive; i++) { if (!set.Contains(i)) { return i; } } return maxPositive + 1; } } } </code></pre> <p>I know there is a better solution, I tried to implement the hash based solution please comment or runtime and performance. Thanks</p>
[]
[ { "body": "<p>There are a few things you can do to simplify your code:</p>\n\n<ul>\n<li>There's no need to keep track of the maximum positive integer if you remove the condition from the second <code>for</code> loop: <code>for (int i = 1; ; i++)</code>.</li>\n<li>That means you don't need to check whether the hash already contains the given number: just add it right away.</li>\n<li>If you don't mind a small performance hit you can use Linq's <code>ToHashSet</code> instead: <code>var set = array.ToHashSet();</code> (<strong>Edit:</strong> or <code>new HashSet&lt;int&gt;(array);</code> if you're not using .NET Framework 4.7.2).</li>\n<li><strong>Edit:</strong> Alternately, if you expect a lot of negative values in your inputs, not adding those to the set can result in a fair speed improvement - I'm seeing a 30% improvement for inputs with 50% negative values.</li>\n</ul>\n\n<p>The first three changes don't really speed things up, and the last one is fairly input-specific. For a significant and more reliable performance improvement, replace the hash with an array of booleans:</p>\n\n<pre><code>var presence = new bool[array.Length + 1];\nforeach (var value in array)\n{\n if (value &gt; 0 &amp;&amp; value &lt; presence.Length)\n {\n presence[value] = true;\n }\n}\n\nfor (int i = 1; i &lt; presence.Length; i++)\n{\n if (!presence[i])\n {\n return i;\n }\n}\nreturn presence.Length;\n</code></pre>\n\n<p>The maximum possible return value is <code>array.Length + 1</code>, so values larger than that can safely be ignored (just like negative values) because they won't affect the result. The input <code>[1, 2, 3]</code> produces <code>4</code>. Replacing any of these numbers with a larger one will create a gap: <code>[1, 99, 3]</code> produces <code>2</code>. Whether or not <code>99</code> is present is irrelevant: what matters is that <code>2</code> is not present.</p>\n\n<p>For large inputs this is about twice as fast, for small inputs it can be more than 10x faster. Hash set lookups are fast, but there is some overhead involved, so they won't beat array lookups.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> The proposed solution on their website is (re)using the input array as a lookup table. It's moving all positive numbers to the front and then marking the presence of numbers by making the value at that index negative - somewhat similar to the above approach. I guess the first step allows them to simplify the rest of the algorithm, but it does make things slower. That first step can be removed with careful swapping and negating, making it run faster, but it's still a bit slower as the array of boolean approach - and more difficult to understand.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T15:49:06.137", "Id": "402179", "Score": "1", "body": "`.NET Framework 4.7.2` - that's why I've never seen `ToHashSet` before :-o I was wondering what you are talking about ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T09:39:03.927", "Id": "402448", "Score": "0", "body": "@pieter, what is the space complexity of your solution? Can you please explain? I think it is O(n). Is it right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T14:14:14.343", "Id": "402467", "Score": "0", "body": "@Emdad: it takes O(n) space, yes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T16:12:17.680", "Id": "402477", "Score": "0", "body": "@PieterWitvoet, thanks for your clarification. I am looking for O(1) space complexity for this problem. Can you please help me?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T19:32:02.667", "Id": "402496", "Score": "1", "body": "@Emdad: the last part of my post contains some notes about the O(1) solution that is shown on the website Gilad linked to. It's more complicated, slower and requires modifications to the input, so I don't see much practical use for it." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T11:02:47.643", "Id": "208226", "ParentId": "208218", "Score": "8" } } ]
{ "AcceptedAnswerId": "208226", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T09:22:03.977", "Id": "208218", "Score": "5", "Tags": [ "c#", "programming-challenge", "interview-questions" ], "Title": "Find the smallest positive number missing from an unsorted array" }
208218
<p>A Helper class for Fragment Management.<br/> The <strong>FragmentsManager</strong> class has methods to add and replace fragments.<br/> The replace method checks if the given fragment is present in backstack or not and if the fragment is present it brings back the old fragment. Need review for the following:</p> <ul> <li>Code optimized.</li> <li>Memory Efficiency</li> <li>Overall code review</li> <li>Can the replace method be improved in any way so as to avoid creation of additional fragments?</li> <li>I've tried to use popbackstack() but couldn't how to use it. Can you help with that?</li> </ul> <p>Thanks</p> <pre><code>import android.app.Activity; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; class FragmentsManager { private static final String TAG = "FragmentsManager"; private static FragmentTransaction transaction; // Return Fragment Transaction private static FragmentTransaction getTransaction(Activity activity){ // if (transaction == null) { // return transaction; // } return getFragmentManager(activity).beginTransaction(); } // Return Fragment Manager private static FragmentManager getFragmentManager(Activity activity){ return ((AppCompatActivity)activity).getSupportFragmentManager(); } /** * Add Fragment to the given ID * @param activity * @param fragment * @param id * @param add_to_backstack */ static void addFragment(Activity activity, Fragment fragment, int id, boolean add_to_backstack){ transaction = getTransaction(activity); transaction.add(id,fragment,fragment.getClass().getName()); if (add_to_backstack) transaction.addToBackStack(fragment.getClass().getName()); transaction.commit(); } static void replaceFragment(Activity activity, Fragment fragment, int id, boolean add_to_backstack) { Fragment check_Fragment = getFragmentManager(activity).findFragmentByTag(fragment.getClass().getName()); if (check_Fragment == null) { transaction = getTransaction(activity) .replace(id,fragment,fragment.getClass().getName()); if (add_to_backstack) transaction.addToBackStack(fragment.getClass().getName()); transaction.commit(); } else{ transaction = getTransaction(activity); transaction.replace(id,check_Fragment,check_Fragment.getClass().getName()) .addToBackStack(null) .commit(); } } } </code></pre>
[]
[ { "body": "<p>your code looks <strong>very good</strong>, there are only <strong>minor issues</strong>:</p>\n\n<h1>1) naming</h1>\n\n<p>since you don't create any instances of <code>FragmentsManager</code> you should consider to rename it to <code>FragmentsUtility</code>. An Utility class provides <strong>methods</strong> to help you with your code while a Manager is an <strong>instance</strong> that does the work for you.</p>\n\n<p>boolean should beginn with prefix <em>is</em> (or rarely as an alternative <em>has/can/should</em>) (in Java it's convention to use camelCase)\nso rename your <code>boolean add_to_backstack</code> into <code>boolean isAddedToBackstack</code> rather (btw. in java it's convention to use camelCase)</p>\n\n<h1>2) comments</h1>\n\n<p>remove commented code!</p>\n\n<h1>3) javadoc</h1>\n\n<p>you provide some javadoc on the <code>addFragment</code> methode which is very crude - get things done and finish it!</p>\n\n<p>the same applies to <code>replaceFragment</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T06:07:26.013", "Id": "402358", "Score": "0", "body": "Thank you for your review. I thought JavaDocs should be provided for all the methods defined for description purposes. So I added them. Guess I was wrong. Thanks again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T05:40:10.827", "Id": "208264", "ParentId": "208219", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T09:54:46.413", "Id": "208219", "Score": "3", "Tags": [ "java", "android" ], "Title": "Helper class for Fragments management" }
208219
<p>This is the second part of a question, you can find the first part here:</p> <p><a href="https://codereview.stackexchange.com/questions/208144/comparing-columns-from-two-csv-files?noredirect=1#comment401973_208144">Comparing columns from two CSV files</a></p> <p>I've made some changes to the script and here is what it looks like now:</p> <pre><code>import csv, sys def get_column(columns, name): count = 0 for column in columns: if column != name: count += 1 else: return(count) def set_up_file(file, variable): columns = next(file) siren_pos = get_column(columns, 'SIREN') nic_pos = get_column(columns, 'NIC') variable_pos = get_column(columns, variable) return(siren_pos, nic_pos, variable_pos) def test_variable(variable): with open('source.csv', 'r') as source: source_r = csv.reader(source, delimiter=';') sir_s, nic_s, comp_s = set_up_file(source_r, variable) line_s = next(source_r) with open('tested.csv', 'r') as tested: tested_r = csv.reader(tested, delimiter=';') sir_t, nic_t, comp_t = set_up_file(tested_r, variable) size = sum(1 for line in tested_r) tested.seek(0, 0) line_t = next(tested_r) line_t = next(tested_r) correct = 0 try: while True: if(line_s[sir_s] == line_t[sir_t] and line_s[nic_s] == line_t[nic_t]): if(line_s[comp_s] == line_t[comp_t]): correct += 1 line_t = next(tested_r) line_s = next(source_r) elif(int(line_s[sir_s]) &gt; int(line_t[sir_t])): line_t = next(tested_r) elif(int(line_s[sir_s]) &lt; int(line_t[sir_t])): line_s = next(source_r) else: if(int(line_s[nic_s]) &gt; int(line_t[nic_t])): line_t = next(tested_r) else: line_s = next(source_r) except StopIteration: return(correct / size * 100) def main(): with open('tested.csv', 'r') as file: file_r = csv.reader(file, delimiter=';') columns = next(file_r) found = test_variable('SIREN') for column in columns: print(column, '%.2f' % (test_variable(column) / found * 100)) if(__name__ == "__main__"): main() </code></pre> <p>There are no real performance issue in the new version but I feel like it could still be improved greatly.</p> <p>Also, would it be possible to reduce the size of the <code>test_variable</code> function? I thought about cutting it right before the <code>try</code> statement but I'll end up passing about 7 parameters which is not really a clean solution in my opinion.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T16:23:44.503", "Id": "402180", "Score": "1", "body": "You're missing the `get_column` function. This cannot be properly reviewed until you provide all of your code." } ]
[ { "body": "<p>On this line:</p>\n\n<pre><code>return(siren_pos, nic_pos, variable_pos)\n</code></pre>\n\n<p>you do not need to surround the return values in parens. They will be returned as a tuple anyway.</p>\n\n<p>It seems ill-advised to iterate through the entire file just to count the number of lines. I advise incrementing <code>size</code> as you go along, so that you only have to iterate once.</p>\n\n<p>You have a bunch of common code that applies to both files. I recommend writing function that does the <code>open()</code>, the <code>csv.reader()</code>, and the <code>set_up_file()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T08:35:29.297", "Id": "402237", "Score": "0", "body": "I'd prefer keeping the parens around the return value for clarity, size has to be counted outside of the loop because said loop depend on two iterator and is not consistant but what you said on duplicate code is true, that has been changed, thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T16:33:03.290", "Id": "208240", "ParentId": "208220", "Score": "1" } }, { "body": "<ul>\n<li>There is some duplication of code because you are handling two files.</li>\n<li>When you need some data converted to <code>int</code> it would be best to do soon as you've read it to avoid sprinkling other logic with <code>int()</code> calls.</li>\n<li>The two columns SIREN and NIC combined seem to form a sorting key to the file. You could simplify the <code>if elif...</code> part by performing the comparisons on <code>(SIREN, NIC)</code> tuples.</li>\n</ul>\n\n<p>To address the above, I propose to organize the code like this:</p>\n\n<pre><code>def parse_file(file, variable):\n reader = csv.reader(file, delimiter=';')\n sir_s, nic_s, comp_s = set_up_file(reader, variable)\n for line in reader:\n key = int(line[sir_s]), int(line[nic_s])\n yield key, line[comp_s]\n\ndef test_variable(variable):\n with open('source.csv', 'r') as source, open('tested.csv', 'r') as tested:\n source_r = parse_file(source, variable)\n tested_r = parse_file(tested, variable)\n\n correct = 0\n try:\n line_s = next(source_r)\n line_t = next(tested_r)\n while True:\n key_s, comp_s = line_s\n key_t, comp_t = line_t\n if line_s == line_t:\n correct += 1\n if key_s &gt;= key_t:\n line_t = next(tested_r)\n if key_s &lt;= key_t:\n line_s = next(source_r)\n\n except StopIteration:\n return correct\n</code></pre>\n\n<p>Note however that I've omitted the computation of <code>size</code>. This could be done by incrementing a variable after reading each line, but since lines are read at multiple places, and some may be left in the end if the other file ends first, it may be best to count the lines separately like you have done.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T09:22:05.973", "Id": "402244", "Score": "0", "body": "I would need some details on how `key_s, comp_s = line_s` works because `comp_s` is not re-used in the code after that yet it seems to manage the calculations" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T10:02:53.053", "Id": "402248", "Score": "0", "body": "@Comte_Zero Well actually `comp_s` is a redundant variable, you could also use `key_s = line_s[0]`. Because `line_s == line_t` compares all three columns at once, a separate variable is not needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T10:11:09.730", "Id": "402252", "Score": "0", "body": "The problem had to do with my non-understanding of yield, I've done some research and it is fine now, thanks for your answer it is really helpful but how about removing `key_s, comp_s = line_s` and using `line_s[0]` instead of `key_s` in the rest of the file, wouldn't it save some memory space / performances ?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T17:22:53.547", "Id": "208241", "ParentId": "208220", "Score": "2" } } ]
{ "AcceptedAnswerId": "208241", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T10:09:48.617", "Id": "208220", "Score": "2", "Tags": [ "python", "csv" ], "Title": "Comparing columns from two CSV files - follow-up" }
208220
<p>I am trying to build a REST API with express router, which contains of nested sub routes. I have mounted these sub routes in my <code>index.js</code> file.</p> <p>I have defined it as follows:</p> <pre><code>// Mounted routes app.use('/api/v1/Project', new ProjectRouter().routes); app.use('/api/v1/Project/:projectId/Context', new ContextRouter().routes); app.use('/api/v1/Project/:projectId/Context/:contextId/Question', new QuestionRouter().routes); app.use('/api/v1/Project/:projectId/Context/:contextId/Question/:questionId/Answer', new AnswerRouter().routes); </code></pre> <p>I want to arrange my routes revolved around the functionality and being more complaint towards REST standards.</p> <p><strong>In the case the route prefix <code>/api/v1/Project/</code> is being repeated over and over again.</strong></p> <p>Is there some best practice to minimize the redundant routes by prefixing?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T22:44:18.393", "Id": "402662", "Score": "1", "body": "This may be a little ancillary to what you are saying, but it is a common practice to limit the depth of your routes. https://restful-api-design.readthedocs.io/en/latest/urls.html For instance, you most likely dont need project and context in the url to modify a question's anwser." } ]
[ { "body": "<p>The main idea is you can define routes in each controller (no matter how). For hide the base route, you can use a base class with a method addRoute and a property baseRoute or just use a simple variable for base route.</p>\n\n<p>With Ecma6 will look something like this:</p>\n\n<p>in projects.controller.js</p>\n\n<pre><code>require('base.controller.js')\nclass ProjectsController extends BaseController {\n constructor(app){\n super(app, \"/api/v1/Project\");\n this.addRoute(\"/\", \"get\", this.getAll);\n this.addRoute(\"/:id\", \"get\", this.getOne)\n }\n getAll(){}\n getOne(){}\n}\nmodule.exports = ProjectsController;\n</code></pre>\n\n<p>in 'base.controller.js':</p>\n\n<pre><code>class BaseController {\n constructor(app, baseRoute){\n this.baseRoute = baseRoute;\n this.app = app\n }\n addRoute(route, method, callback){\n const url = this.baseRoute + route;\n console.log('controllerRoute', url, method);\n this.app[method](url, callback.bind(this));\n }\n}\nmodule.exports=BaseController;\n</code></pre>\n\n<p>and in index.js (or app/server.js), for each controller:</p>\n\n<pre><code>require(\"./projects.controller.\")(app);\n</code></pre>\n\n<p>The simplest way:</p>\n\n<pre><code>let baseRoute = \"/api/v1/Project\";\napp.use(baseRoute + \"/\", new ProjectRouter().routes);\napp.use(baseRoute + '/:projectId/Context', new ContextRouter().routes);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-03T04:47:51.013", "Id": "403580", "Score": "1", "body": "Kunal isn't using TypeScript, and this setup has multiple issues. 1. Method isn't passed to `addRoute`. 2. No `super()` call. 3. No nice way to specify another controller is under `/api/v1/Project`. 4. Routes are currently looking like `/api/api/...`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-03T05:03:06.280", "Id": "403581", "Score": "0", "body": "Yes you are right. I corrected the mistakes. What do you mean by 3. ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-03T05:11:31.030", "Id": "403583", "Score": "0", "body": "You mean is not ok to define a base class for controller?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-03T05:15:37.503", "Id": "403584", "Score": "0", "body": "About typescript: Ecma6 is very similar with Typescript (except types), so why is this a problem?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-02T12:02:03.037", "Id": "208872", "ParentId": "208224", "Score": "-1" } }, { "body": "<p>This is where the Express Router class comes in. You could define a router for ‘api/v1/Project’, mount that router to you main app, and then add the individual routes to the router.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T02:43:02.950", "Id": "212437", "ParentId": "208224", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T10:58:05.773", "Id": "208224", "Score": "2", "Tags": [ "javascript", "node.js", "express.js", "url-routing" ], "Title": "Minimizing duplicate routes index.js" }
208224
<p>Need to perform such actions:</p> <ul> <li>receive JSON from REST</li> <li>extract nexted JSON document</li> <li>calculate hash of the nested document</li> <li>add some fields to extracted document and save it in database</li> <li>return response CONTAINING some fields of the source DOCUMENT</li> </ul> <p>I wrote this service:</p> <pre><code>@Service public class InvoiceService { private static final Logger logger = LoggerFactory.getLogger(InvoiceService.class); @Autowired private InvoiceRepository repository; public Object processInvoice(InvoiceRequest invoice) { if (!validateInvoice(invoice)) { logger.error("Error: empty object UID. JSON dumped:"); logger.error(invoice.toString()); return new ResponseError(invoice.getRequestUID(), invoice.getObjectUID(), invoice.getSenderDateTime(), "Empty object UID"); } return saveInvoice(invoice); } private boolean validateInvoice(InvoiceRequest invoice) { return (invoice.getObjectUID() != null) &amp;&amp; (!invoice.getObjectUID().equals("")); } private Object saveInvoice(InvoiceRequest invoice) { FlatInvoice flat = convertToFlat(invoice); if (repository.existsByUID(invoice.getObjectUID())) { if (tryToUpdate(invoice)) { ResponseSuccess success = new ResponseSuccess(invoice.getRequestUID(), invoice.getObjectUID(), Time.now()); return new ResponseEntity&lt;&gt;(success, HttpStatus.OK); } else { // return status OK return new ResponseEntity&lt;&gt;("", HttpStatus.OK); } } if (!repository.insert(flat)) { respondWithError(invoice, "DB insertion failed", HttpStatus.INTERNAL_SERVER_ERROR); } return respondWithSuccess(invoice); } private ResponseEntity&lt;?&gt; respondWithError(InvoiceRequest invoice, String msg, HttpStatus status) { ResponseError ret = new ResponseError(invoice.getRequestUID(), invoice.getObjectUID(), Time.now(), msg); return new ResponseEntity&lt;&gt;(ret, status); } private ResponseEntity&lt;?&gt; respondWithSuccess(InvoiceRequest invoice) { ResponseSuccess ret = new ResponseSuccess(invoice.getRequestUID(), invoice.getObjectUID(), Time.now()); return new ResponseEntity&lt;&gt;(ret, HttpStatus.OK); } private FlatInvoice convertToFlat(InvoiceRequest invoice) { FlatInvoice flat = InvoiceFlattener.flatten(invoice); flat.setSenderDateTime(invoice.getSenderDateTime()); flat.setCreateDateTime(Time.now()); flat.setHash(Crypto.sha256(invoice.getInvoice().toString().getBytes())); return flat; } public Object findByUID(String uid) { return repository.findByObjectUID(uid); } public boolean tryToUpdate(InvoiceRequest invoice) { Object object = repository.findByObjectUID(invoice.getObjectUID()); HashMap map = (HashMap) object; String hashStored = (String)map.get("hash"); String hashActual = Crypto.sha256(invoice.getInvoice().toString().getBytes()); if (compareSenderDates(invoice, map)) { if (!hashActual.equals(hashStored)) { return repository.update(invoice.getObjectUID(), convertToFlat(invoice)); } } else { System.out.println("ignore doc, reason: actual senderDateTime is less or equal"); } return false; } public boolean compareSenderDates(InvoiceRequest invoice, HashMap storedDoc) { long timestampReceived = Time.timestamp(invoice.getSenderDateTime()); long timestampStored = Time.timestamp((String)storedDoc.get("senderDateTime")); return timestampReceived &gt; timestampStored; } } </code></pre> <p>It is overcomplicated because of a huge amount of nested logic and if statements. All methods do more than one logical action. Constructing of error response is mixed with business logic. How to refactor all of this?</p> <pre><code>public class ResponseError { private String requestUID; private String objectUID; private String receivedDateTime; private String errorMessage; public ResponseError(String requestUID, String objectUID, String receivedDateTime, String errorMessage) { this.requestUID = requestUID; this.objectUID = objectUID; this.receivedDateTime = receivedDateTime; this.errorMessage = errorMessage; } public String getRequestUID() { return requestUID; } public void setRequestUID(String requestUID) { this.requestUID = requestUID; } public String getObjectUID() { return objectUID; } public void setObjectUID(String objectUID) { this.objectUID = objectUID; } public String getReceivedDateTime() { return receivedDateTime; } public void setReceivedDateTime(String receivedDateTime) { this.receivedDateTime = receivedDateTime; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } } public class ResponseSuccess { private String requestUID; private String objectUID; private String receivedDateTime; public ResponseSuccess(String requestUID, String objectUID, String receivedDateTime) { this.requestUID = requestUID; this.objectUID = objectUID; this.receivedDateTime = receivedDateTime; } public String getRequestUID() { return requestUID; } public void setRequestUID(String requestUID) { this.requestUID = requestUID; } public String getObjectUID() { return objectUID; } public void setObjectUID(String objectUID) { this.objectUID = objectUID; } public String getReceivedDateTime() { return receivedDateTime; } public void setReceivedDateTime(String receivedDateTime) { this.receivedDateTime = receivedDateTime; } } public class ResponseBuilder { public static ResponseError error(HashMap request, String msg) { return new ResponseError(FieldExtractor.requestUID(request), FieldExtractor.objectUID(request), Time.now(), msg); } public static ResponseSuccess success(HashMap request) { return new ResponseSuccess(FieldExtractor.requestUID(request), FieldExtractor.objectUID(request), Time.now()); } private static class FieldExtractor { public static String requestUID(HashMap request) { return (String) getBusData(request).get("requestUID"); } public static String objectUID(HashMap request) { return (String) getBusData(request).get("objectUID"); } private static HashMap getBusData(HashMap request) { HashMap receiveData = (HashMap)request.get("receiveData"); return (HashMap)receiveData.get("iBusData"); } } } public class InvoiceRequest { private ReceiveData receiveData; public ReceiveData getReceiveData() { return receiveData; } public void setReceiveData(ReceiveData receiveData) { this.receiveData = receiveData; } public String getRequestUID() { return getReceiveData().getiBusData().getRequestUID(); } public String getObjectUID() { return getReceiveData().getiBusData().getObjectUID(); } public String getSenderDateTime() { return getReceiveData() .getiBusData() .getSenderDateTime(); } public Invoice getInvoice() { return getReceiveData() .getiBusData() .getData() .getInvoice(); } public String getUID() { return getInvoice().getUid(); } public String getDate() { return getInvoice().getDate(); } public String getNumber() { return getInvoice().getNumber(); } public Boolean getMarked() { return getInvoice().getMarked(); } public Boolean getPosted() { return getInvoice().getPosted(); } public String getSenderCityUID() { return getInvoice().getSenderCityUID(); } public String getReceiverTerminalUID() { return getInvoice().getReceiverTerminalUID(); } public String getReceiverCityUID() { return getInvoice().getReceiverCityUID(); } public String getCargoUID() { return getInvoice().getCargoUID(); } public Double getAmount() { return getInvoice().getAmount(); } public Double getAmountExtraLarge() { return getInvoice().getAmountExtraLarge(); } public Double getNetWeight() { return getInvoice().getNetWeight(); } public Double getNetWeightExtraLarge() { return getInvoice().getNetWeightExtraLarge(); } public Double getGrossWeight() { return getInvoice().getGrossWeight(); } public Double getNetVolume() { return getInvoice().getNetVolume(); } public Double getNetVolumeExtraLarge() { return getInvoice().getNetVolumeExtraLarge(); } public Double getGrossVolume() { return getInvoice().getGrossVolume(); } public Double getDeclaredValue() { return getInvoice().getDeclaredValue(); } public String getContractorSenderUID() { return getInvoice().getContractorSenderUID(); } public String getContractorReceiverUID() { return getInvoice().getContractorReceiverUID(); } public String getContractorPayerUID() { return getInvoice().getContractorPayerUID(); } public String getContractorSenderIssueUID() { return getInvoice().getContractorSenderIssueUID(); } public String getContractorReceiverIssueUID() { return getInvoice().getContractorReceiverIssueUID(); } public String getActualReceiver() { return getInvoice().getActualReceiver(); } public Double getFreightInKops() { return getInvoice().getFreightInKops(); } public Double getDeliveryTimeInsuranceSum() { return getInvoice().getDeliveryTimeInsuranceSum(); } public String getTerminalUID() { return getInvoice().getTerminalUID(); } public Double getCargoInsuranceSum() { return getInvoice().getCargoInsuranceSum(); } public String getSenderCityName() { return getInvoice().getSenderCityName(); } public String getSenderCityKLADR() { return getInvoice().getSenderCityKLADR(); } public String getReceiverCityName() { return getInvoice().getReceiverCityName(); } public String getReceiverCityKLADR() { return getInvoice().getReceiverCityKLADR(); } public Double getTransportationCostOnReceiving() { return getInvoice().getTransportationCostOnReceiving(); } public Double getTransportationCostOnIssuing() { return getInvoice().getTransportationCostOnIssuing(); } public String getBaseDocumentUID() { return getInvoice().getInvoiceUID(); } public String getPackagingStateFlags() { return getInvoice().getPackagingStateFlags(); } public String getCargoName() { return getInvoice().getCargoName(); } public String getOperation() { return getInvoice().getOperation(); } public Person getActualReceiverPersonalID() { return getInvoice().getActualReceiverPersonalID(); } @Override public String toString() { return "InvoiceRequest{" + "receiveData=" + receiveData + '}'; } } @Service public class InvoiceFlattener { public static FlatInvoice flatten(InvoiceRequest invoice) { FlatInvoice result = new FlatInvoice( invoice.getUID(), invoice.getDate(), invoice.getNumber(), invoice.getMarked(), invoice.getPosted(), invoice.getSenderCityUID(), invoice.getReceiverTerminalUID(), invoice.getReceiverCityUID(), invoice.getCargoUID(), invoice.getAmount(), invoice.getAmountExtraLarge(), invoice.getNetWeight(), invoice.getNetWeightExtraLarge(), invoice.getGrossWeight(), invoice.getNetVolume(), invoice.getNetVolumeExtraLarge(), invoice.getGrossVolume(), invoice.getDeclaredValue(), invoice.getContractorSenderUID(), invoice.getContractorReceiverUID(), invoice.getContractorPayerUID(), invoice.getContractorSenderIssueUID(), invoice.getContractorReceiverIssueUID(), invoice.getActualReceiver(), invoice.getFreightInKops(), invoice.getDeliveryTimeInsuranceSum(), invoice.getTerminalUID(), invoice.getCargoInsuranceSum(), invoice.getSenderCityName(), invoice.getSenderCityKLADR(), invoice.getReceiverCityName(), invoice.getReceiverCityKLADR(), invoice.getTransportationCostOnReceiving(), invoice.getTransportationCostOnIssuing(), invoice.getBaseDocumentUID(), invoice.getPackagingStateFlags(), invoice.getCargoName(), invoice.getOperation(), invoice.getActualReceiverPersonalID()); return result; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T10:25:49.130", "Id": "402253", "Score": "0", "body": "Could you also provide your `InvoiceRequest`, `ResponseError`, `FlatInvoice` and `InvoiceFlattener` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T10:33:12.127", "Id": "402254", "Score": "0", "body": "@gervais.b, InvoiceRequest is a hierarchy of objects representing JSON structure." } ]
[ { "body": "<p>Thanks for the classes. However I did not wait for them and just created some \"stubs\". Here is my answer:</p>\n\n<p>When you have <em>\"a huge amount of nested logic\"</em> you should try to extract and distribute it somewhere else. I like to do DDD and place the business logic in my domain objects.</p>\n\n<h3>Validation</h3>\n\n<p>Let's start from the first lines of code: <code>if ( !validateInvoice(invoice) )</code>:</p>\n\n<p>You can easily extract the validation to a dedicated class. Spring provide \na good support for validation. You can also annotate your methods parameters \nwith <code>@Valid</code> to have them validated automatically by the framework.</p>\n\n<p>To separate the construction of the error from your business logic you can return a structure of errors instead of a <code>boolean</code>. Then you verify if thie structure \nhas errors and construct the error response or let it continue. This structure already exists into the spring framework. </p>\n\n<p>You can also hide the construction of the <code>ErrorResponse</code> in the class itself \nor into a factory method.</p>\n\n<pre><code>Map&lt;String, Set&lt;String&gt;&gt; errors = validator.validate(invoice);\nif ( errors.isEmpty() ) {\n return saveInvoice(invoice);\n} else {\n logger.error(\"Invalid request : {}. Json: {}.\", errors, invoice);\n return new ResponseEntity&lt;&gt;(ResponseError.of(invoice, errors), HttpStatus.BAD_REQUEST);\n}\n</code></pre>\n\n<p>Note that I have replaced the two calls to <code>logger.error</code> with one. Nothing guarantee that the two messages will be next to each other so it is better to log everything in one statement.\nIf you are using Slf4j you can also use the templates expansion to format your\nmessage. And, please, do not use <code>toString</code> to have a JSON representation of \nyour object.</p>\n\n<h3>Transformation</h3>\n\n<p>Many use a mapping framework. But you can also create your own mapper like \nyou did with the <code>InvoiceFlattener</code>. However, it is sad that you still have to \nset some properties to the result object. Ideally the result will be \"complete\".</p>\n\n<pre><code>FlatInvoice flat = InvoiceFlattener.flatten(invoice);\n// Nothing more\n</code></pre>\n\n<h3>Persistence</h3>\n\n<p>It seems that <code>saveInvoice</code> methods contains your business logic but also a \ncouple of <code>ifs</code>.</p>\n\n<p>You can already remove the <code>if</code> around <code>repository.insert(flat)</code> because usually\na repository trows an exception when he cannot persist the entity. You can use a \nSpring exception handler to convert the exception to a <code>ResponseError</code>. Apply \nthis to all the methods in your repository.</p>\n\n<p>The <code>tryToUpdate</code> method is confusing because it start with <em>try</em> and thus \nwe expect an exception. It is also annoying to have the effective update as a side\neffect of this test. You should better keep the test in a method but update in the \nbody of your<code>if</code>. </p>\n\n<pre><code>if ( repository.exists(invoice) ) {\n if ( isChanged(invoice) ) {\n repository.update(invoice.getObjectUID(), InvoiceFlattener.flatten(invoice));\n ResponseSuccess body = new ResponseSuccess(invoice.getRequestUID(), invoice.getObjectUID(),\n LocalTime.now());\n return new ResponseEntity&lt;&gt;(body, HttpStatus.OK);\n } else {\n logger.debug(\"Ignoring unchanged invoice {}.\", invoice);\n return new ResponseEntity&lt;&gt;(\"\", HttpStatus.OK);\n }\n} else {\n repository.insert(flat);\n ResponseSuccess ret = new ResponseSuccess(invoice.getRequestUID(), invoice.getObjectUID(), LocalTime.now());\n return new ResponseEntity&lt;&gt;(ret, HttpStatus.OK);\n}\n</code></pre>\n\n<h3>Domain logic</h3>\n\n<p>Another improvement that you can do is to replace the <code>Map</code> that you receive from your repository by a class. So that you should be able to move the <code>isChanged</code> logic into this class. You can also map the <code>InvoiceRequest</code> to that new class so that you don't have to deal with <code>InvoiceRequest</code>, <code>FlatInvoice</code> and <code>Map&lt;String, ?&gt;</code> that are all representing the same model (from what I understand). If you do that you have something that looks like a domain object. </p>\n\n<p>You can also continue the separation between the domain logic and the protocol by introducing a controller aside of your service. The controller will map the <code>InvoiceRequest</code> to your <code>Invoice</code> entity and convert the result and exceptions to <code>HttpEntity</code>.</p>\n\n<p>You should end up with something like:</p>\n\n<pre><code>@Service\npublic class InvoiceService {\n private static final Logger LOG = LoggerFactory.getLogger(InvoiceService.class);\n\n private final InvoiceRepository repository;\n\n public InvoiceService(InvoiceRepository repository) {\n this.repository = repository;\n }\n\n public Invoice process(Invoice invoice) throws PersistenceException {\n return repository.find(invoice.getUuid())\n .map(existing -&gt; updateOrIgnore(existing, invoice))\n .orElseGet(() -&gt; repository.insert(invoice));\n }\n\n private Invoice updateOrIgnore(Invoice existing, Invoice updated) {\n if (existing.isAfter(updated) &amp;&amp; existing.isDifferent(updated)) {\n return repository.update(existing.getUuid(), updated);\n } else {\n LOG.debug(\"Ignoring unchanged invoice {}.\", updated);\n return existing;\n }\n }\n\n}\n\n\n// ~ ----------------------------------------------------------------------\n\n@RestController\npublic class InvoiceController {\n\n private final InvoiceRequestValidator validator = new InvoiceRequestValidator();\n private final InvoiceRequestMapper mapper = new InvoiceRequestMapper();\n private final InvoiceService service;\n\n public InvoiceController(InvoiceService service) {\n this.service = service;\n }\n\n @PostMapping(\"/invoices\")\n public ResponseEntity&lt;?&gt; receive(@Valid InvoiceRequest request) throws\n PersistenceException, ValidationException {\n Map&lt;String, Set&lt;String&gt;&gt; errors = validator.validate(request);\n if ( errors.isEmpty() ) {\n Invoice invoice = mapper.map(request);\n Invoice result = service.process(invoice);\n return new ResponseEntity&lt;&gt;(\n ResponseSuccess.of(request, result),\n HttpStatus.OK);\n } else {\n return new ResponseEntity&lt;&gt;(\n ResponseError.of(request, errors),\n HttpStatus.BAD_REQUEST);\n }\n }\n\n @ExceptionHandler(PersistenceException.class)\n ResponseEntity&lt;ResponseError&gt; on(PersistenceException pe) {\n ResponseError body = new ResponseError(pe.getRequestUID(), pe.getObjectUID(),\n pe.getSenderDateTime(), pe.getMessage());\n return new ResponseEntity&lt;&gt;(body, HttpStatus.INTERNAL_SERVER_ERROR);\n }\n\n}\n</code></pre>\n\n<p>I hope that you can find some inspiration in this answer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T20:21:48.797", "Id": "208306", "ParentId": "208229", "Score": "1" } } ]
{ "AcceptedAnswerId": "208306", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T12:22:30.383", "Id": "208229", "Score": "0", "Tags": [ "java", "rest", "spring", "spring-mvc" ], "Title": "Refactor REST service with overcomplicated logic" }
208229
<p>I implemented a simple queuing system for my Node.JS app and wanted a critique on it's structure.</p> <pre><code>const TPS = 20; const Queue = { counter: 1, items: {}, /** * Add an item to the queue, with the given func to call * @param {Function} func * @param {Boolean} repeating * @return {Number} */ add(func, repeating = false) { const id = this.counter++; this.items[id] = {func, repeating, id}; return id; }, /** * Remove an item from the queue with the given id * @param {Number} id */ remove(id) { if (this.items.hasOwnProperty(id)) { delete this.items[id]; } }, /** * Process items in the queue */ process() { for (let id in this.items) { // Prevent this item from being processed again if (!this.items.hasOwnProperty(id) || this.items[id].processing) { continue; } // Delete this item when it's scheduled for deletion if (this.items[id].scheduledForDeletion) { delete this.items[id]; continue; } // Let the queue know this item is being processed and // it's scheduled deletion status this.items[id].processing = true; this.items[id].scheduledForDeletion = !this.items[id].repeating; // Don't wait for item's promise to resolve, since this // will create a backlog on the queue (async () =&gt; { try { await this.items[id].func.call(null); } catch (err) { // TODO: Handle errors. console.error(err); } this.items[id].processing = false; })(); } } }; (function tick() { setTimeout(tick, 1000 / TPS); Queue.process(); })(); </code></pre> <p>This is an example of how it's implemented.</p> <pre><code>// Add three items to the queue: 1 normal, 1 async and 1 repeating Queue.add(() =&gt; console.info(`[tick] -&gt; ${Date.now()}`)); Queue.add(async () =&gt; setTimeout(() =&gt; console.info(`[async] -&gt; ${Date.now()}`), 100)); const timeLoop = Queue.add(() =&gt; console.info(`[loop] time (loop) -&gt; ${Date.now()}`), true); // Remove the looping item from the queue setTimeout(() =&gt; Queue.remove(timeLoop), 500); </code></pre> <p>The idea is to have this run when the server starts and continually process the queue items. Queue is in it's own file and exported. I import this file into my controllers and call (for example) <code>Queue.add('function to add user to DB and send out email')</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T18:05:13.813", "Id": "402955", "Score": "1", "body": "There's certainly some critiques that could be made about your code, but I'm having difficulty understanding why it is needed. Is there some reason you don't just fire and forget your async functions where you need to instead of introducing more complexity with a \"Queue\" (which I'd claim really isn't a queue)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-29T18:02:53.970", "Id": "403158", "Score": "0", "body": "You are right, for the one-time executions, you could argue that it's unnecessary to add them to this queue. However for the repeating (long running) processes, it is unnecessary to add them to this queue. Mostly this queue is used in a game that I'm building, where a lot of things happen that need to be processed per-tick." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-01T01:33:29.127", "Id": "403377", "Score": "0", "body": "What are you trying to determine? What is the purpose of the immediately invoked async arrow function within `process`; and `async` at `Queue.add(async () => setTimeout(() => console.info(\\`[async] -> ${Date.now()}\\`), 100))` where no `Promise` is included within or returned from the function passed to `Queue.add()`? Is `Queue.add()` and `process` expected to handle both asynchronous and synchronous functions as parameters?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-01T16:05:32.587", "Id": "403438", "Score": "0", "body": "I invoke the arrow function inside the process method since the `await` keyword needs to be inside an `async` body, but I think it might be better to move it to the process function definition like `async process()`. The `Queue.add` calls at the end of my code are just examples to show you that you can add async items to the queue. And actually `async` returns a promise by default so technically they are returning promises. Finally, yes, the process method handles both sync and async items." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-01T19:52:52.253", "Id": "403458", "Score": "0", "body": "@Enijar Where does `async () => setTimeout(() => console.info(\\`[async] -> ${Date.now()}\\`), 100)` return any value? [See Why is value undefined at .then() chained to Promise?](https://stackoverflow.com/q/44439596/)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-02T16:00:51.680", "Id": "403533", "Score": "0", "body": "@guest271314 `async` returns a promise by default" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-02T16:26:21.203", "Id": "403541", "Score": "0", "body": "@Enijar Yes, the `Promise` will be returned from the `async` function with the value set at `undefined` before the function passed to `setTimeout()` is executed. Is that the expected result?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-02T17:09:42.857", "Id": "403546", "Score": "0", "body": "@Enijar http://plnkr.co/edit/cNmKdpXJO5bq7OKj0vD2?p=preview" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-03T08:42:20.210", "Id": "403600", "Score": "0", "body": "@guest271314 It's irrelevant for my use-case, since I never use the return value of `Queue.add`. I just use the arrow functions to keep my code smaller." } ]
[ { "body": "<p>The structure looks fine. It is quite succinct and makes good use of <code>const</code> and <code>let</code> where appropriate. </p>\n\n<p>To adhere to the D.R.Y. principle, <code>process()</code> can and should utilize <code>remove()</code> to remove items from the queue.</p>\n\n<hr>\n\n<p>I considered suggesting that arguments be accepted with each function but that can be achieved with partially bound functions. </p>\n\n<p>I also considered suggesting you consider using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\" rel=\"nofollow noreferrer\">a class</a>, since ES-6 featured can be utilized, but then you would either need to instantiate a queue once or else make all methods static. </p>\n\n<hr>\n\n<p>I would suggest you consider accepting an error handler callback for each function. That way, instead of writing all errors to the console, the caller could add an appropriate handler. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-03T03:33:18.563", "Id": "208906", "ParentId": "208231", "Score": "1" } } ]
{ "AcceptedAnswerId": "208906", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T12:49:02.247", "Id": "208231", "Score": "4", "Tags": [ "javascript", "node.js", "ecmascript-6", "queue" ], "Title": "Node.JS Server Queue Processor" }
208231
<p>Here is a C++ implementation of a bounding volume hierarchy, aimed for fast collision detection (view frustum, rays, other bounding volumes). It is based on the ideas from the book "Real-Time Rendering, Third Edition". Would like to hear some thoughts:</p> <pre class="lang-cpp prettyprint-override"><code>#ifndef BOUNDINGVOLUMEHIERARCHY_H #define BOUNDINGVOLUMEHIERARCHY_H #include &lt;Camera.h&gt; #include &lt;vector&gt; #include &lt;IntersectionTests.h&gt; #include &lt;CullResult.h&gt; #include &lt;Ray.h&gt; #include &lt;boost/pool/object_pool.hpp&gt; namespace Log2 { template&lt;typename T, typename BV, typename Proxy, typename TNested&gt; class BoundingVolumeHierarchy { public: class NodePool; static const auto Dim = BV::getDim(); using Type = typename BV::Type; using Ray = Ray&lt;Dim, Type&gt;; using Vector = Vector&lt;Dim, Type&gt;; using Matrix = Matrix&lt;Dim + 1, Dim + 1, Type&gt;; struct PrimitiveInfo { T* _primitive; BV _bv; Type _bvSize; }; private: auto getBV(const T&amp; primitive) { return Proxy::GetBoundingVolume()(primitive); } auto getSize(const T&amp; primitive) { return Proxy::GetLargestBVSize()(primitive); } PrimitiveInfo createInfo(T* primitive) { return { primitive, getBV(*primitive), getSize(*primitive) }; } public: class Node { public: Node() = default; virtual ~Node() = default; virtual void cullVisiblePrimitives(const Camera::CullingParams&amp; cp, CullResult&lt;T&gt;&amp; cull_result) const = 0; virtual void cullVisiblePrimitives(const Camera::CullingParams&amp; cp, const IntersectedPlanes&amp; in, CullResult&lt;T&gt;&amp; cull_result) const = 0; virtual void cullAllPrimitives(const Camera::CullingParams&amp; cp, std::vector&lt;T&gt;&amp; primitives) const = 0; virtual size_t getSizeInBytes() const = 0; virtual void intersectPrimitives(const BV&amp; bv, std::vector&lt;T&gt;&amp; intersected_primitives) const = 0; virtual void intersectPrimitives(const BV&amp; bv, const Matrix&amp; transform, std::vector&lt;T&gt;&amp; intersected_primitives) const = 0; virtual void intersectPrimitives(const BV&amp; bv, std::vector&lt;T const *&gt;&amp; intersected_primitives) const = 0; virtual void intersectPrimitives(const BV&amp; bv, const Matrix&amp; transform, std::vector&lt;T const *&gt;&amp; intersected_primitives) const = 0; virtual void intersectFirst(const BV&amp; bv, T const *&amp; first) const = 0; virtual void intersectFirst(const BV&amp; bv, const Matrix&amp; transform, T const *&amp; first) const = 0; virtual void cullVisibleNodes(const Camera::CullingParams&amp; cp, std::vector&lt;Node const *&gt;&amp; nodes) const = 0; virtual void cullAllNodes(const Camera::CullingParams&amp; cp, std::vector&lt;Node const *&gt;&amp; nodes) const = 0; virtual void countNodes(unsigned&amp; internal_nodes, unsigned&amp; leaf_nodes) const = 0; virtual void getAllBVs(std::vector&lt;BV&gt;&amp; bvs) const = 0; virtual void cullBVs(const Camera::CullingParams&amp; cp, const Matrix&amp; transform, std::vector&lt;BV&gt;&amp; result) const = 0; virtual void intersectPrimitives(const Ray&amp; ray, std::vector&lt;T&gt;&amp; intersected_primitives) const = 0; virtual void intersectPrimitives(const Ray&amp; ray, const Matrix&amp; transform, std::vector&lt;T&gt;&amp; intersected_primitives) const = 0; virtual void intersectPrimitives(const Ray&amp; ray, std::vector&lt;T&gt;&amp; intersected_primitives, std::vector&lt;BV&gt;&amp; bvs) const = 0; virtual void intersectPrimitives(const Ray&amp; ray, const Matrix&amp; transform, std::vector&lt;T&gt;&amp; intersected_primitives, std::vector&lt;BV&gt;&amp; bvs) const = 0; virtual void findNearest(const Ray&amp; ray, const Matrix&amp; transform, T const *&amp; nearest, Type&amp; nearest_t, Matrix&amp; nearest_transform) const = 0; virtual void findNearest(const Ray&amp; ray, const Matrix&amp; transform, T const *&amp; nearest, Type&amp; nearest_t, Matrix&amp; nearest_transform, std::vector&lt;BV&gt;&amp; bvs) const = 0; virtual void findNearestPrecise(const Ray&amp; ray, const Matrix&amp; transform, T const *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform) const = 0; virtual void findNearestPrecise(const Ray&amp; ray, const Matrix&amp; transform, T *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform) = 0; virtual void findNearestPrecise(const Ray&amp; ray, const Matrix&amp; transform, T const *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform, std::vector&lt;BV&gt;&amp; bvs) const = 0; virtual void findNearestNested(const Ray&amp; ray, TNested const *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform) const = 0; virtual void findNearestNested(const Ray&amp; ray, TNested *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform) = 0; virtual void queryRange(const BV&amp; bv, std::vector&lt;T&gt;&amp; intersected_primitives) const = 0; virtual void queryAll(std::vector&lt;T&gt;&amp; intersected_primitives) const = 0; virtual void queryRange(const BV&amp; bv, const Camera::CullingParams&amp; cp, std::vector&lt;T&gt;&amp; intersected_primitives) const = 0; virtual void queryAll(const Camera::CullingParams&amp; cp, std::vector&lt;T&gt;&amp; intersected_primitives) const = 0; virtual bool isLeaf() const = 0; virtual Node* getLeft() const = 0; virtual Node* getRight() const = 0; virtual Node*&amp; getLeft() = 0; virtual Node*&amp; getRight() = 0; virtual T * getPrimitivePtr() = 0; virtual BV getBV() const = 0; virtual BV const * getBVPtr() const = 0; virtual BV * getBVPtr() = 0; virtual Type distToPoint2(const Vector&amp; point) const = 0; virtual void destroy(NodePool&amp; pool) = 0; virtual Type* getLargestBVSize() = 0; virtual Type cost(const BV&amp; bv) const = 0; }; class LeafNode : public Node { public: explicit LeafNode(T primitive) : Node(), _primitive(primitive) { } virtual ~LeafNode() = default; virtual void cullVisiblePrimitives(const Camera::CullingParams&amp; cp, CullResult&lt;T&gt;&amp; cull_result) const override { cull_result._probablyVisiblePrimitives.push_back(_primitive); } virtual void cullVisiblePrimitives(const Camera::CullingParams&amp; cp, const IntersectedPlanes&amp; in, CullResult&lt;T&gt;&amp; cull_result) const override { cull_result._probablyVisiblePrimitives.push_back(_primitive); } virtual void cullAllPrimitives(const Camera::CullingParams&amp; cp, std::vector&lt;T&gt;&amp; primitives) const override { primitives.push_back(_primitive); } virtual size_t getSizeInBytes() const override { return sizeof *this; } virtual void intersectPrimitives(const BV&amp; bv, std::vector&lt;T&gt;&amp; intersected_primitives) const override { if (bv.intersects(getBV())) { intersected_primitives.push_back(_primitive); } } virtual void intersectPrimitives(const BV&amp; bv, const Matrix&amp; transform, std::vector&lt;T&gt;&amp; intersected_primitives) const override { if (bv.intersects(BV(getBV(), transform))) { intersected_primitives.push_back(_primitive); } } virtual void intersectPrimitives(const BV&amp; bv, std::vector&lt;T const *&gt;&amp; intersected_primitives) const override { if (bv.intersects(getBV())) { intersected_primitives.push_back(&amp;_primitive); } } virtual void intersectPrimitives(const BV&amp; bv, const Matrix&amp; transform, std::vector&lt;T const *&gt;&amp; intersected_primitives) const override { if (bv.intersects(BV(getBV(), transform))) { intersected_primitives.push_back(&amp;_primitive); } } virtual void intersectFirst(const BV&amp; bv, T const *&amp; first) const override { if (!first &amp;&amp; bv.intersects(getBV())) { first = &amp;_primitive; } } virtual void intersectFirst(const BV&amp; bv, const Matrix&amp; transform, T const *&amp; first) const override { if (!first &amp;&amp; bv.intersects(BV(getBV(), transform))) { first = &amp;_primitive; } } virtual void cullVisibleNodes(const Camera::CullingParams&amp; cp, std::vector&lt;Node const *&gt;&amp; nodes) const override { if (contributes(cp) &amp;&amp; intersectFrustum(cp) != IntersectionResult::OUTSIDE) { nodes.push_back(this); } } virtual void cullAllNodes(const Camera::CullingParams&amp; cp, std::vector&lt;Node const *&gt;&amp; nodes) const override { if (contributes(cp)) { nodes.push_back(this); } } virtual void countNodes(unsigned&amp; internal_nodes, unsigned&amp; leaf_nodes) const override { leaf_nodes++; } virtual void getAllBVs(std::vector&lt;BV&gt;&amp; bvs) const override { bvs.push_back(getBV()); } virtual void cullBVs(const Camera::CullingParams&amp; cp, const Matrix&amp; transform, std::vector&lt;BV&gt;&amp; result) const override { BV bv(getBV(), transform); if (bv.contributes(cp._camPos, cp._thresh)) { result.push_back(bv); } } virtual void intersectPrimitives(const Ray&amp; ray, std::vector&lt;T&gt;&amp; intersected_primitives) const override { if (std::get&lt;0&gt;(IntersectionTests::rayIntersectsBoundingVolume(getBV(), ray))) { intersected_primitives.push_back(_primitive); } } virtual void intersectPrimitives(const Ray&amp; ray, const Matrix&amp; transform, std::vector&lt;T&gt;&amp; intersected_primitives) const override { if (std::get&lt;0&gt;(IntersectionTests::rayIntersectsBoundingVolume(BV(getBV(), transform), ray))) { intersected_primitives.push_back(_primitive); } } virtual void intersectPrimitives(const Ray&amp; ray, std::vector&lt;T&gt;&amp; intersected_primitives, std::vector&lt;BV&gt;&amp; bvs) const override { if (std::get&lt;0&gt;(IntersectionTests::rayIntersectsBoundingVolume(getBV(), ray))) { intersected_primitives.push_back(_primitive); bvs.push_back(getBV()); } } virtual void intersectPrimitives(const Ray&amp; ray, const Matrix&amp; transform, std::vector&lt;T&gt;&amp; intersected_primitives, std::vector&lt;BV&gt;&amp; bvs) const override { if (std::get&lt;0&gt;(IntersectionTests::rayIntersectsBoundingVolume(BV(getBV(), transform), ray))) { intersected_primitives.push_back(_primitive); bvs.push_back(BV(getBV(), transform)); } } virtual void findNearest(const Ray&amp; ray, const Matrix&amp; transform, T const *&amp; nearest, Type&amp; nearest_t, Matrix&amp; nearest_transform) const override { auto result = IntersectionTests::rayIntersectsBoundingVolume(BV(getBV(), transform), ray); if (std::get&lt;0&gt;(result) &amp;&amp; std::get&lt;1&gt;(result) &lt; nearest_t) { nearest = &amp;_primitive; nearest_t = std::get&lt;1&gt;(result); nearest_transform = transform; } } virtual void findNearest(const Ray&amp; ray, const Matrix&amp; transform, T const *&amp; nearest, Type&amp; nearest_t, Matrix&amp; nearest_transform, std::vector&lt;BV&gt;&amp; bvs) const override { auto result = IntersectionTests::rayIntersectsBoundingVolume(BV(getBV(), transform), ray); if (std::get&lt;0&gt;(result) &amp;&amp; std::get&lt;1&gt;(result) &lt; nearest_t) { nearest = &amp;_primitive; nearest_t = std::get&lt;1&gt;(result); nearest_transform = transform; bvs.push_back(BV(getBV(), transform)); } } virtual void findNearestPrecise(const Ray&amp; ray, const Matrix&amp; transform, T const *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform) const override { if (std::get&lt;0&gt;(IntersectionTests::rayIntersectsBoundingVolume(BV(getBV(), transform), ray))) { auto result = Proxy::IntersectRay()(_primitive, ray, transform); if (std::get&lt;0&gt;(result) &amp;&amp; std::get&lt;3&gt;(result) &lt; t) { nearest = &amp;_primitive; nearest_transform = transform; u = std::get&lt;1&gt;(result); v = std::get&lt;2&gt;(result); t = std::get&lt;3&gt;(result); } } } virtual void findNearestPrecise(const Ray&amp; ray, const Matrix&amp; transform, T *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform) override { if (std::get&lt;0&gt;(IntersectionTests::rayIntersectsBoundingVolume(BV(getBV(), transform), ray))) { auto result = Proxy::IntersectRay()(_primitive, ray, transform); if (std::get&lt;0&gt;(result) &amp;&amp; std::get&lt;3&gt;(result) &lt; t) { nearest = &amp;_primitive; nearest_transform = transform; u = std::get&lt;1&gt;(result); v = std::get&lt;2&gt;(result); t = std::get&lt;3&gt;(result); } } } virtual void findNearestPrecise(const Ray&amp; ray, const Matrix&amp; transform, T const *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform, std::vector&lt;BV&gt;&amp; bvs) const override { if (std::get&lt;0&gt;(IntersectionTests::rayIntersectsBoundingVolume(BV(getBV(), transform), ray))) { auto result = Proxy::IntersectRay()(_primitive, ray, transform); if (std::get&lt;0&gt;(result) &amp;&amp; std::get&lt;3&gt;(result) &lt; t) { nearest = &amp;_primitive; nearest_transform = transform; u = std::get&lt;1&gt;(result); v = std::get&lt;2&gt;(result); t = std::get&lt;3&gt;(result); bvs.push_back(BV(getBV(), transform)); } } } virtual void findNearestNested(const Ray&amp; ray, TNested const *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform) const override { Proxy::FindNearestNestedConst()(_primitive, ray, nearest, u, v, t, nearest_transform); } virtual void findNearestNested(const Ray&amp; ray, TNested *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform) override { Proxy::FindNearestNested()(_primitive, ray, nearest, u, v, t, nearest_transform); } virtual void queryRange(const BV&amp; bv, std::vector&lt;T&gt;&amp; intersected_primitives) const override { if (bv.intersects(getBV())) { intersected_primitives.push_back(_primitive); } } virtual void queryAll(std::vector&lt;T&gt;&amp; intersected_primitives) const override { intersected_primitives.push_back(_primitive); } virtual void queryRange(const BV&amp; bv, const Camera::CullingParams&amp; cp, std::vector&lt;T&gt;&amp; intersected_primitives) const override { if (contributes(cp) &amp;&amp; bv.intersects(getBV())) { intersected_primitives.push_back(_primitive); } } virtual void queryAll(const Camera::CullingParams&amp; cp, std::vector&lt;T&gt;&amp; intersected_primitives) const override { if (contributes(cp)) { intersected_primitives.push_back(_primitive); } } virtual bool isLeaf() const override { return true; } virtual Node* getLeft() const override { throw std::exception("Don't call this method"); return nullptr; } virtual Node* getRight() const override { throw std::exception("Don't call this method"); return nullptr; } virtual Node*&amp; getLeft() override { throw std::exception("Don't call this method"); } virtual Node*&amp; getRight() override { throw std::exception("Don't call this method"); } virtual T * getPrimitivePtr() override { return &amp;_primitive; } virtual BV getBV() const override { return Proxy::GetBoundingVolume()(_primitive); } virtual BV const * getBVPtr() const override { throw std::exception("Don't call this method"); return nullptr; } virtual BV * getBVPtr() override { throw std::exception("Don't call this method"); return nullptr; } virtual Type distToPoint2(const Vector&amp; point) const override { return Proxy::GetBoundingVolume()(_primitive).distToPoint2(point); } virtual void destroy(NodePool&amp; pool) override { pool.destroy(this); } virtual Type* getLargestBVSize() override { throw std::exception("Don't call this method"); return nullptr; } virtual Type cost(const BV&amp; bv) const override { return bv.getUnion(getBV()).size2(); } private: T _primitive; auto contributes(const Camera::CullingParams&amp; cp) const { return getBV().contributes(cp._camPos, cp._thresh, Proxy::GetLargestBVSize()(_primitive)); } auto intersectFrustum(const Camera::CullingParams&amp; cp) const { return IntersectionTests::frustumIntersectsBoundingVolume(getBV(), cp._frustumPlanes); } }; using NodePtr = Node * ; class InternalNode : public Node { public: InternalNode(PrimitiveInfo* begin, PrimitiveInfo* end, BoundingVolumeHierarchy&amp; bvh) : Node(), _bv(begin-&gt;_bv), _largestBVSize(begin-&gt;_bvSize) { for (auto const* ptr = begin + 1; ptr &lt; end; ptr++) { _bv.unify(ptr-&gt;_bv); maximize(ptr-&gt;_bvSize, _largestBVSize); } auto axis = _bv.longestAxis(); auto bv_center = _bv.center(axis); auto mid = std::partition(begin, end, [&amp;axis, &amp;bv_center](const PrimitiveInfo&amp; p) { return p._bv.center(axis) &lt; bv_center; }); if (mid == begin || mid == end) { mid = begin + (end - begin) / 2u; } _left = bvh.createNode(begin, mid); _right = bvh.createNode(mid, end); } virtual ~InternalNode() = default; virtual void cullVisiblePrimitives(const Camera::CullingParams&amp; cp, CullResult&lt;T&gt;&amp; cull_result) const override { if (contributes(cp)) { auto result = intersectFrustum(cp); if (result == IntersectionResult::INTERSECTING) { _left-&gt;cullVisiblePrimitives(cp, cull_result); _right-&gt;cullVisiblePrimitives(cp, cull_result); } else if (result == IntersectionResult::INSIDE) { _left-&gt;cullAllPrimitives(cp, cull_result._fullyVisiblePrimitives); _right-&gt;cullAllPrimitives(cp, cull_result._fullyVisiblePrimitives); } } } virtual void cullVisiblePrimitives(const Camera::CullingParams&amp; cp, const IntersectedPlanes&amp; in, CullResult&lt;T&gt;&amp; cull_result) const override { if (contributes(cp)) { IntersectedPlanes out; auto result = intersectFrustum(cp, in, out); if (result == IntersectionResult::INTERSECTING) { _left-&gt;cullVisiblePrimitives(cp, out, cull_result); _right-&gt;cullVisiblePrimitives(cp, out, cull_result); } else if (result == IntersectionResult::INSIDE) { _left-&gt;cullAllPrimitives(cp, cull_result._fullyVisiblePrimitives); _right-&gt;cullAllPrimitives(cp, cull_result._fullyVisiblePrimitives); } } } virtual void cullAllPrimitives(const Camera::CullingParams&amp; cp, std::vector&lt;T&gt;&amp; primitives) const override { if (contributes(cp)) { _left-&gt;cullAllPrimitives(cp, primitives); _right-&gt;cullAllPrimitives(cp, primitives); } } virtual size_t getSizeInBytes() const override { return sizeof *this + _left-&gt;getSizeInBytes() + _right-&gt;getSizeInBytes(); } virtual void intersectPrimitives(const BV&amp; bv, std::vector&lt;T&gt;&amp; intersected_primitives) const override { if (bv.intersects(_bv)) { _left-&gt;intersectPrimitives(bv, intersected_primitives); _right-&gt;intersectPrimitives(bv, intersected_primitives); } } virtual void intersectPrimitives(const BV&amp; bv, const Matrix&amp; transform, std::vector&lt;T&gt;&amp; intersected_primitives) const override { if (bv.intersects(BV(_bv, transform))) { _left-&gt;intersectPrimitives(bv, transform, intersected_primitives); _right-&gt;intersectPrimitives(bv, transform, intersected_primitives); } } virtual void intersectPrimitives(const BV&amp; bv, std::vector&lt;T const *&gt;&amp; intersected_primitives) const override { if (bv.intersects(_bv)) { _left-&gt;intersectPrimitives(bv, intersected_primitives); _right-&gt;intersectPrimitives(bv, intersected_primitives); } } virtual void intersectPrimitives(const BV&amp; bv, const Matrix&amp; transform, std::vector&lt;T const *&gt;&amp; intersected_primitives) const override { if (bv.intersects(BV(_bv, transform))) { _left-&gt;intersectPrimitives(bv, transform, intersected_primitives); _right-&gt;intersectPrimitives(bv, transform, intersected_primitives); } } virtual void intersectFirst(const BV&amp; bv, T const *&amp; first) const override { if (!first &amp;&amp; bv.intersects(_bv)) { _left-&gt;intersectFirst(bv, first); _right-&gt;intersectFirst(bv, first); } } virtual void intersectFirst(const BV&amp; bv, const Matrix&amp; transform, T const *&amp; first) const override { if (!first &amp;&amp; bv.intersects(BV(_bv, transform))) { _left-&gt;intersectFirst(bv, transform, first); _right-&gt;intersectFirst(bv, transform, first); } } virtual void cullVisibleNodes(const Camera::CullingParams&amp; cp, std::vector&lt;Node const *&gt;&amp; nodes) const override { if (contributes(cp)) { auto result = intersectFrustum(cp); if (result == IntersectionResult::INSIDE) { nodes.push_back(this); _left-&gt;cullAllNodes(cp, nodes); _right-&gt;cullAllNodes(cp, nodes); } else if (result == IntersectionResult::INTERSECTING) { nodes.push_back(this); _left-&gt;cullVisibleNodes(cp, nodes); _right-&gt;cullVisibleNodes(cp, nodes); } } } virtual void cullAllNodes(const Camera::CullingParams&amp; cp, std::vector&lt;Node const *&gt;&amp; nodes) const override { if (contributes(cp)) { nodes.push_back(this); _left-&gt;cullAllNodes(cp, nodes); _right-&gt;cullAllNodes(cp, nodes); } } virtual void countNodes(unsigned&amp; internal_nodes, unsigned&amp; leaf_nodes) const override { internal_nodes++; _left-&gt;countNodes(internal_nodes, leaf_nodes); _right-&gt;countNodes(internal_nodes, leaf_nodes); } virtual void getAllBVs(std::vector&lt;BV&gt;&amp; bvs) const override { bvs.push_back(_bv); _left-&gt;getAllBVs(bvs); _right-&gt;getAllBVs(bvs); } virtual void cullBVs(const Camera::CullingParams&amp; cp, const Matrix&amp; transform, std::vector&lt;BV&gt;&amp; result) const override { BV bv(_bv, transform); if (bv.contributes(cp._camPos, cp._thresh)) { result.push_back(bv); _left-&gt;cullBVs(cp, transform, result); _right-&gt;cullBVs(cp, transform, result); } } virtual void intersectPrimitives(const Ray&amp; ray, std::vector&lt;T&gt;&amp; intersected_primitives) const override { if (std::get&lt;0&gt;(IntersectionTests::rayIntersectsBoundingVolume(_bv, ray))) { _left-&gt;intersectPrimitives(ray, intersected_primitives); _right-&gt;intersectPrimitives(ray, intersected_primitives); } } virtual void intersectPrimitives(const Ray&amp; ray, const Matrix&amp; transform, std::vector&lt;T&gt;&amp; intersected_primitives) const override { if (std::get&lt;0&gt;(IntersectionTests::rayIntersectsBoundingVolume(BV(_bv, transform), ray))) { _left-&gt;intersectPrimitives(ray, transform, intersected_primitives); _right-&gt;intersectPrimitives(ray, transform, intersected_primitives); } } virtual void intersectPrimitives(const Ray&amp; ray, std::vector&lt;T&gt;&amp; intersected_primitives, std::vector&lt;BV&gt;&amp; bvs) const override { if (std::get&lt;0&gt;(IntersectionTests::rayIntersectsBoundingVolume(_bv, ray))) { _left-&gt;intersectPrimitives(ray, intersected_primitives, bvs); _right-&gt;intersectPrimitives(ray, intersected_primitives, bvs); bvs.push_back(_bv); } } virtual void intersectPrimitives(const Ray&amp; ray, const Matrix&amp; transform, std::vector&lt;T&gt;&amp; intersected_primitives, std::vector&lt;BV&gt;&amp; bvs) const override { if (std::get&lt;0&gt;(IntersectionTests::rayIntersectsBoundingVolume(BV(_bv, transform), ray))) { _left-&gt;intersectPrimitives(ray, transform, intersected_primitives, bvs); _right-&gt;intersectPrimitives(ray, transform, intersected_primitives, bvs); bvs.push_back(BV(_bv, transform)); } } virtual void findNearest(const Ray&amp; ray, const Matrix&amp; transform, T const *&amp; nearest, Type&amp; nearest_t, Matrix&amp; nearest_transform) const override { auto result = IntersectionTests::rayIntersectsBoundingVolume(BV(_bv, transform), ray); if (std::get&lt;0&gt;(result) &amp;&amp; std::get&lt;1&gt;(result) &lt; nearest_t) { _left-&gt;findNearest(ray, transform, nearest, nearest_t, nearest_transform); _right-&gt;findNearest(ray, transform, nearest, nearest_t, nearest_transform); } } virtual void findNearest(const Ray&amp; ray, const Matrix&amp; transform, T const *&amp; nearest, Type&amp; nearest_t, Matrix&amp; nearest_transform, std::vector&lt;BV&gt;&amp; bvs) const override { auto result = IntersectionTests::rayIntersectsBoundingVolume(BV(_bv, transform), ray); if (std::get&lt;0&gt;(result) &amp;&amp; std::get&lt;1&gt;(result) &lt; nearest_t) { bvs.push_back(BV(_bv, transform)); _left-&gt;findNearest(ray, transform, nearest, nearest_t, nearest_transform, bvs); _right-&gt;findNearest(ray, transform, nearest, nearest_t, nearest_transform, bvs); } } virtual void findNearestPrecise(const Ray&amp; ray, const Matrix&amp; transform, T const *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform) const override { auto result = IntersectionTests::rayIntersectsBoundingVolume(BV(_bv, transform), ray); if (std::get&lt;0&gt;(result) &amp;&amp; std::get&lt;1&gt;(result) &lt; t) { _left-&gt;findNearestPrecise(ray, transform, nearest, u, v, t, nearest_transform); _right-&gt;findNearestPrecise(ray, transform, nearest, u, v, t, nearest_transform); } } virtual void findNearestPrecise(const Ray&amp; ray, const Matrix&amp; transform, T *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform) override { auto result = IntersectionTests::rayIntersectsBoundingVolume(BV(_bv, transform), ray); if (std::get&lt;0&gt;(result) &amp;&amp; std::get&lt;1&gt;(result) &lt; t) { _left-&gt;findNearestPrecise(ray, transform, nearest, u, v, t, nearest_transform); _right-&gt;findNearestPrecise(ray, transform, nearest, u, v, t, nearest_transform); } } virtual void findNearestPrecise(const Ray&amp; ray, const Matrix&amp; transform, T const *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform, std::vector&lt;BV&gt;&amp; bvs) const override { auto result = IntersectionTests::rayIntersectsBoundingVolume(BV(_bv, transform), ray); if (std::get&lt;0&gt;(result) &amp;&amp; std::get&lt;1&gt;(result) &lt; t) { bvs.push_back(BV(_bv, transform)); _left-&gt;findNearestPrecise(ray, transform, nearest, u, v, t, nearest_transform, bvs); _right-&gt;findNearestPrecise(ray, transform, nearest, u, v, t, nearest_transform, bvs); } } virtual void findNearestNested(const Ray&amp; ray, TNested const *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform) const override { auto result = IntersectionTests::rayIntersectsBoundingVolume(_bv, ray); if (std::get&lt;0&gt;(result) &amp;&amp; std::get&lt;1&gt;(result) &lt; t) { Node* nodes[2] = { _left, _right }; auto result = _left-&gt;distToPoint2(ray.getOrigin()) &lt; _right-&gt;distToPoint2(ray.getOrigin()); nodes[!result]-&gt;findNearestNested(ray, nearest, u, v, t, nearest_transform); nodes[result]-&gt;findNearestNested(ray, nearest, u, v, t, nearest_transform); } } virtual void findNearestNested(const Ray&amp; ray, TNested *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform) override { auto result = IntersectionTests::rayIntersectsBoundingVolume(_bv, ray); if (std::get&lt;0&gt;(result) &amp;&amp; std::get&lt;1&gt;(result) &lt; t) { Node* nodes[2] = { _left, _right }; auto result = _left-&gt;distToPoint2(ray.getOrigin()) &lt; _right-&gt;distToPoint2(ray.getOrigin()); nodes[!result]-&gt;findNearestNested(ray, nearest, u, v, t, nearest_transform); nodes[result]-&gt;findNearestNested(ray, nearest, u, v, t, nearest_transform); } } virtual void queryRange(const BV&amp; bv, std::vector&lt;T&gt;&amp; intersected_primitives) const override { if (bv.contains(_bv)) { _left-&gt;queryAll(intersected_primitives); _right-&gt;queryAll(intersected_primitives); } else if (bv.intersects(_bv)) { _left-&gt;queryRange(bv, intersected_primitives); _right-&gt;queryRange(bv, intersected_primitives); } } virtual void queryAll(std::vector&lt;T&gt;&amp; intersected_primitives) const override { _left-&gt;queryAll(intersected_primitives); _right-&gt;queryAll(intersected_primitives); } virtual void queryRange(const BV&amp; bv, const Camera::CullingParams&amp; cp, std::vector&lt;T&gt;&amp; intersected_primitives) const override { if (contributes(cp)) { if (bv.contains(_bv)) { _left-&gt;queryAll(cp, intersected_primitives); _right-&gt;queryAll(cp, intersected_primitives); } else if (bv.intersects(_bv)) { _left-&gt;queryRange(bv, cp, intersected_primitives); _right-&gt;queryRange(bv, cp, intersected_primitives); } } } virtual void queryAll(const Camera::CullingParams&amp; cp, std::vector&lt;T&gt;&amp; intersected_primitives) const override { if (contributes(cp)) { _left-&gt;queryAll(cp, intersected_primitives); _right-&gt;queryAll(cp, intersected_primitives); } } virtual bool isLeaf() const override { return false; } virtual Node* getLeft() const override { return _left; } virtual Node* getRight() const override { return _right; } virtual Node*&amp; getLeft() override { return _left; } virtual Node*&amp; getRight() override { return _right; } virtual T * getPrimitivePtr() override { throw std::exception("Don't call this method"); return nullptr; } virtual BV getBV() const override { return _bv; } virtual BV const * getBVPtr() const override { return &amp;_bv; } virtual BV * getBVPtr() override { return &amp;_bv; } virtual Type distToPoint2(const Vector&amp; point) const override { return _bv.distToPoint2(point); } virtual void destroy(NodePool&amp; pool) override { pool.destroy(this); } virtual Type* getLargestBVSize() override { return &amp;_largestBVSize; } virtual Type cost(const BV&amp; bv) const override { return bv.getUnion(_bv).size2(); } private: NodePtr _left, _right; BV _bv; Type _largestBVSize; auto contributes(const Camera::CullingParams&amp; cp) const { return _bv.contributes(cp._camPos, cp._thresh, _largestBVSize); } auto intersectFrustum(const Camera::CullingParams&amp; cp) const { return IntersectionTests::frustumIntersectsBoundingVolume(_bv, cp._frustumPlanes); } auto intersectFrustum(const Camera::CullingParams&amp; cp, const IntersectedPlanes&amp; in, IntersectedPlanes&amp; out) const { return IntersectionTests::frustumIntersectsBoundingVolume(_bv, cp._frustumPlanes, in, out); } }; BoundingVolumeHierarchy() = delete; BoundingVolumeHierarchy(T* primitives, unsigned count) : _nodePool(count) { std::vector&lt;PrimitiveInfo&gt; infos; infos.reserve(count); for (unsigned i = 0; i &lt; count; i++) { infos.push_back(createInfo(primitives + i)); } _root = createNode(infos.data(), infos.data() + count); } BoundingVolumeHierarchy(const BoundingVolumeHierarchy&amp; other) = delete; BoundingVolumeHierarchy&amp; operator=(const BoundingVolumeHierarchy&amp; other) = delete; BoundingVolumeHierarchy(BoundingVolumeHierarchy&amp;&amp; other) = default; BoundingVolumeHierarchy&amp; operator=(BoundingVolumeHierarchy&amp;&amp; other) = default; auto cullVisiblePrimitives(const Camera::CullingParams&amp; cp, CullResult&lt;T&gt;&amp; cull_result) const { _root-&gt;cullVisiblePrimitives(cp, cull_result); } auto cullVisiblePrimitivesWithPlaneMasking(const Camera::CullingParams&amp; cp, CullResult&lt;T&gt;&amp; cull_result) const { IntersectedPlanes out = { { 0, 1, 2, 3, 4, 5 }, 6 }; _root-&gt;cullVisiblePrimitives(cp, out, cull_result); } auto intersectPrimitives(const BV&amp; bv, std::vector&lt;T&gt;&amp; intersected_primitives) const { _root-&gt;intersectPrimitives(bv, intersected_primitives); } auto intersectPrimitives(const BV&amp; bv, const Matrix&amp; transform, std::vector&lt;T&gt;&amp; intersected_primitives) const { _root-&gt;intersectPrimitives(bv, transform, intersected_primitives); } auto intersectPrimitives(const BV&amp; bv, std::vector&lt;T const *&gt;&amp; intersected_primitives) const { _root-&gt;intersectPrimitives(bv, intersected_primitives); } auto intersectPrimitives(const BV&amp; bv, const Matrix&amp; transform, std::vector&lt;T const *&gt;&amp; intersected_primitives) const { _root-&gt;intersectPrimitives(bv, transform, intersected_primitives); } auto intersectFirst(const BV&amp; bv, T const *&amp; first) const { _root-&gt;intersectFirst(bv, first); } auto intersectFirst(const BV&amp; bv, const Matrix&amp; transform, T const *&amp; first) const { _root-&gt;intersectFirst(bv, transform, first); } auto intersectPrimitives(const Ray&amp; ray, std::vector&lt;T&gt;&amp; intersected_primitives) const { _root-&gt;intersectPrimitives(ray, intersected_primitives); } auto intersectPrimitives(const Ray&amp; ray, const Matrix&amp; transform, std::vector&lt;T&gt;&amp; intersected_primitives) const { _root-&gt;intersectPrimitives(ray, transform, intersected_primitives); } auto intersectPrimitives(const Ray&amp; ray, std::vector&lt;T&gt;&amp; intersected_primitives, std::vector&lt;BV&gt;&amp; intersected_bvs) const { _root-&gt;intersectPrimitives(ray, intersected_primitives, intersected_bvs); } auto intersectPrimitives(const Ray&amp; ray, const Matrix&amp; transform, std::vector&lt;T&gt;&amp; intersected_primitives, std::vector&lt;BV&gt;&amp; intersected_bvs) const { _root-&gt;intersectPrimitives(ray, transform, intersected_primitives, intersected_bvs); } auto findNearest(const Ray&amp; ray, const Matrix&amp; transform, T*&amp; nearest, Type&amp; nearest_t, Matrix&amp; nearest_transform) const { _root-&gt;findNearest(ray, transform, nearest, nearest_t, nearest_transform); } auto findNearest(const Ray&amp; ray, const Matrix&amp; transform, T*&amp; nearest, Type&amp; nearest_t, Matrix&amp; nearest_transform, std::vector&lt;BV&gt;&amp; bvs) const { _root-&gt;findNearest(ray, transform, nearest, nearest_t, nearest_transform, bvs); } auto findNearestPrecise(const Ray&amp; ray, const Matrix&amp; transform, T const *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform) const { _root-&gt;findNearestPrecise(ray, transform, nearest, u, v, t, nearest_transform); } auto findNearestPrecise(const Ray&amp; ray, const Matrix&amp; transform, T *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform) const { _root-&gt;findNearestPrecise(ray, transform, nearest, u, v, t, nearest_transform); } auto findNearestPrecise(const Ray&amp; ray, const Matrix&amp; transform, T const *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform, std::vector&lt;BV&gt;&amp; bvs) const { _root-&gt;findNearestPrecise(ray, transform, nearest, u, v, t, nearest_transform, bvs); } auto cullVisibleNodes(const Camera::CullingParams&amp; cp, std::vector&lt;Node const *&gt;&amp; nodes) const { _root-&gt;cullVisibleNodes(cp, nodes); } auto findNearestNested(const Ray&amp; ray, TNested const *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform) const { _root-&gt;findNearestNested(ray, nearest, u, v, t, nearest_transform); } auto findNearestNested(const Ray&amp; ray, TNested *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform) const { _root-&gt;findNearestNested(ray, nearest, u, v, t, nearest_transform); } auto queryRange(const BV&amp; bv, std::vector&lt;T&gt;&amp; intersected_primitives) const { _root-&gt;queryRange(bv, intersected_primitives); } auto queryRange(const BV&amp; bv, const Camera::CullingParams&amp; cp, std::vector&lt;T&gt;&amp; intersected_primitives) const { _root-&gt;queryRange(bv, cp, intersected_primitives); } template&lt;typename OtherNodePtr, typename OtherT, typename OtherProxy&gt; void findOverlappingPairs(NodePtr a, OtherNodePtr b, const Matrix&amp; a_transform, std::vector&lt;std::tuple&lt;T*, OtherT*&gt;&gt;&amp; overlapping_pairs) const { if (!a-&gt;isLeaf() &amp;&amp; !b-&gt;isLeaf()) { auto a_bv = BV(*a-&gt;getBVPtr(), a_transform); if (a_bv.intersects(*b-&gt;getBVPtr())) { if (a_bv.size2() &gt; b-&gt;getBVPtr()-&gt;size2()) { findOverlappingPairs&lt;OtherNodePtr, OtherT, OtherProxy&gt;(a-&gt;getLeft(), b, a_transform, overlapping_pairs); findOverlappingPairs&lt;OtherNodePtr, OtherT, OtherProxy&gt;(a-&gt;getRight(), b, a_transform, overlapping_pairs); } else { findOverlappingPairs&lt;OtherNodePtr, OtherT, OtherProxy&gt;(a, b-&gt;getLeft(), a_transform, overlapping_pairs); findOverlappingPairs&lt;OtherNodePtr, OtherT, OtherProxy&gt;(a, b-&gt;getRight(), a_transform, overlapping_pairs); } } } else if (a-&gt;isLeaf() &amp;&amp; b-&gt;isLeaf()) { auto a_bv = BV(Proxy::GetBoundingVolume()(*a-&gt;getPrimitivePtr()), a_transform); auto b_bv = OtherProxy::GetBoundingVolume()(*b-&gt;getPrimitivePtr()); if (a_bv.intersects(b_bv)) { overlapping_pairs.push_back(std::tuple&lt;T*, OtherT*&gt;(a-&gt;getPrimitivePtr(), b-&gt;getPrimitivePtr())); } } else if (a-&gt;isLeaf() &amp;&amp; !b-&gt;isLeaf()) { if (BV(a-&gt;getBV(), a_transform).intersects(*b-&gt;getBVPtr())) { findOverlappingPairs&lt;OtherNodePtr, OtherT, OtherProxy&gt;(a, b-&gt;getLeft(), a_transform, overlapping_pairs); findOverlappingPairs&lt;OtherNodePtr, OtherT, OtherProxy&gt;(a, b-&gt;getRight(), a_transform, overlapping_pairs); } } else { // a is internal and b is leaf node if (BV(*a-&gt;getBVPtr(), a_transform).intersects(b-&gt;getBV())) { findOverlappingPairs&lt;OtherNodePtr, OtherT, OtherProxy&gt;(a-&gt;getLeft(), b, a_transform, overlapping_pairs); findOverlappingPairs&lt;OtherNodePtr, OtherT, OtherProxy&gt;(a-&gt;getRight(), b, a_transform, overlapping_pairs); } } } auto insert(T primitive) { insert(primitive, _root); } auto getSizeInBytes() const { return _root-&gt;getSizeInBytes(); } const auto&amp; getBV() const { return _root-&gt;getBV(); } const auto&amp; getRoot() const { return _root; } auto getAllBVs() const { std::vector&lt;BV&gt; bvs; _root-&gt;getAllBVs(bvs); return bvs; } auto cullBVs(const Camera::CullingParams&amp; cp, const Matrix&amp; transform, std::vector&lt;BV&gt;&amp; bvs) const { _root-&gt;cullBVs(cp, transform, bvs); } auto countNodes(unsigned&amp; internal_nodes, unsigned&amp; leaf_nodes) const { internal_nodes = 0; leaf_nodes = 0; _root-&gt;countNodes(internal_nodes, leaf_nodes); } private: auto insert(T primitive, Node*&amp; node) { if (!node-&gt;isLeaf()) { node-&gt;getBVPtr()-&gt;unify(getBV(primitive)); maximize(getSize(primitive), *node-&gt;getLargestBVSize()); insert(primitive, node-&gt;getLeft()-&gt;cost(getBV(primitive)) &lt; node-&gt;getRight()-&gt;cost(getBV(primitive)) ? node-&gt;getLeft() : node-&gt;getRight()); } else { PrimitiveInfo primitives[2] = { createInfo(&amp;primitive), createInfo(node-&gt;getPrimitivePtr()) }; node-&gt;destroy(_nodePool); node = createNode(primitives, primitives + 2); } } class NodePool { public: NodePool(unsigned num_primitives) { auto height = static_cast&lt;unsigned&gt;(std::floor(log2(static_cast&lt;double&gt;(num_primitives)))); auto num_nodes = static_cast&lt;unsigned&gt;(std::pow(2.0, static_cast&lt;double&gt;(height) + 1.0) - 1.0); auto num_leaf_nodes = static_cast&lt;unsigned&gt;(std::pow(2.0, static_cast&lt;double&gt;(height))); auto num_internal_nodes = num_nodes - num_leaf_nodes; maximize(32u, num_leaf_nodes); maximize(32u, num_internal_nodes); _internalNodePool.set_next_size(num_internal_nodes); _leafNodePool.set_next_size(num_leaf_nodes); } NodePool(const NodePool&amp; other) = delete; NodePool&amp; operator=(const NodePool&amp; other) = delete; NodePool(NodePool&amp;&amp; other) = delete; NodePool&amp; operator=(NodePool&amp;&amp; other) = delete; Node* createNode(PrimitiveInfo* begin, PrimitiveInfo* end, BoundingVolumeHierarchy&amp; bvh) { if (end - begin &gt; 1) { return new (_internalNodePool.malloc()) InternalNode(begin, end, bvh); } return new (_leafNodePool.malloc()) LeafNode(*begin-&gt;_primitive); } auto destroy(LeafNode* node) { _leafNodePool.destroy(node); } auto destroy(InternalNode* node) { _internalNodePool.destroy(node); } private: boost::object_pool&lt;InternalNode&gt; _internalNodePool; boost::object_pool&lt;LeafNode&gt; _leafNodePool; }; NodePool _nodePool; auto* createNode(PrimitiveInfo* begin, PrimitiveInfo* end) { return _nodePool.createNode(begin, end, *this); } Node* _root; }; } #endif </code></pre> <p><strong>Edit:</strong> Here is a sample use, in my Renderer class, I have this:</p> <pre><code> struct Proxy { struct GetBoundingVolume { const BV&amp; operator()(const MeshRenderablePtr&amp; ptr) const { return ptr-&gt;getBV(); } }; struct GetLargestBVSize { auto operator()(const MeshRenderablePtr&amp; ptr) const { return ptr-&gt;getLargestObjectBVSize(); } }; struct IntersectRay { auto operator()(const MeshRenderablePtr&amp; ptr, const Ray&amp; ray, const Matrix&amp; transform) const { throw std::exception("Don't call this method"); return std::tuple&lt;bool, float, float, float&gt;(); } }; struct FindNearestNestedConst { auto operator()(const MeshRenderablePtr&amp; ptr, const Ray&amp; ray, Triangle const *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform) const { ptr-&gt;getGPUMeshData()-&gt;getMesh().getBVH().findNearestPrecise(ray, *ptr-&gt;getModelMatrix(), nearest, u, v, t, nearest_transform); } }; struct FindNearestNested { auto operator()(const MeshRenderablePtr&amp; ptr, const Ray&amp; ray, Triangle *&amp; nearest, Type&amp; u, Type&amp; v, Type&amp; t, Matrix&amp; nearest_transform) { ptr-&gt;getGPUMeshData()-&gt;getMesh().getBVH().findNearestPrecise(ray, *ptr-&gt;getModelMatrix(), nearest, u, v, t, nearest_transform); } }; }; using BVH = BoundingVolumeHierarchy&lt;MeshRenderable*, BV, Proxy, Triangle&gt;; </code></pre> <p>Usage:</p> <pre><code>auto ray = _renderer.getRay(_mousePos); Triangle const * nearest = nullptr; Mat4f nearest_transform; float u, v; float nearest_t = std::numeric_limits&lt;float&gt;::max(); _renderer.getStaticBVH()-&gt;findNearestNested(ray, nearest, u, v, nearest_t, nearest_transform); if (nearest) { // Do something } </code></pre>
[]
[ { "body": "<ul>\n<li>Quite a lot of context is missing, so I'm guessing some things. e.g.:\n\n<ul>\n<li>What's <code>BV</code>?</li>\n<li>What's <code>BV::Type</code>? (apparently it's a size, but for some reason it's stored outside the <code>BV</code> itself? Seems a bit odd if we have our own copy of the BV.)</li>\n<li>What is <code>maximize</code>? (I'd guess <code>a = std::max(a, b)</code>, but that can't be right because <code>maximize(getSize(primitive), *node-&gt;getLargestBVSize());</code> wouldn't work).</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<ul>\n<li>The constructor should take a <code>T const*</code>.</li>\n<li>Various functions (e.g. <code>createNode</code>) taking <code>PrimitiveInfo*</code> can be <code>PrimitiveInfo const*</code>.</li>\n<li><code>createInfo</code> could take a <code>T const*</code>, be made static, and then simply deleted.</li>\n<li><code>getBV</code> and <code>getSize</code> can be static.</li>\n</ul>\n\n<hr>\n\n<ul>\n<li>The <code>Proxy</code> class is confusing.\n\n<ul>\n<li>Why use nested structs with <code>operator()</code>, instead of simple static functions?</li>\n<li>It injects a whole lot of unnecessary complexity into the <code>BVH</code> class. There's no reason for the <code>BVH</code> class to handle searches in a nested <code>BVH</code> that may or may not exist.</li>\n<li>Enforcing an interface on the primitive type would be neater. (Why put a primitive with no <code>getBV()</code> in a bounding volume hierarchy?)</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<ul>\n<li><p>Prefer returning a struct over a tuple, because you can name the members. It's hard to remember what each element of the tuple is for, the code isn't self-documenting, and it's easier to make mistakes with magic numbers than actual names.</p></li>\n<li><p>There's a lot of code duplication:</p>\n\n<ul>\n<li><code>intersectPrimitives(BV, vector)</code> and <code>queryRange(BV, vector)</code> are identical.</li>\n<li><code>findNearestPrecise</code> functions are nearly identical (factor out common functionality).</li>\n<li><code>intersectPrimitives</code> functions are nearly identical (factor out common functionality).</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<ul>\n<li>I doubt the <code>BVH</code> class needs to know anything about culling or the camera. Can this be implemented as a simple <code>intersectsFrustum</code> function, and all of the rendering specific stuff done outside the class?</li>\n</ul>\n\n<hr>\n\n<p>Design questions:</p>\n\n<ul>\n<li><p>Is inheritance really the best option for the nodes? Leaf nodes don't have left / right children, and internal nodes don't have a primitive, so some of the virtual functions don't really make sense either way. Perhaps a variant would be better, and all the search functions can then be implemented in the main class.</p></li>\n<li><p>Perhaps node creation should be done in the main class, instead of in InternalNode?</p></li>\n<li><p>Can traversal and action on the node be abstracted out? Most of the query / intersection functions seem to end up doing the following (pseudocode):</p>\n\n<pre><code>do_thingy(traversal_condition, action):\n if is_leaf:\n if traversal_condition(node.bv)\n left.do_thingy()\n right.do_thingy()\n else\n return\n else\n action(node.primitive)\n</code></pre></li>\n</ul>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-08T15:35:07.660", "Id": "404470", "Score": "0", "body": "BV is some bounding volume, usually a box (AABB, OBB) or a sphere. Type is the underlying primitive data type like double, float, int etc. maximize() is actually defined by : template<typename T>\n static auto maximize(const T& other, T& out)\n {\n out = std::max(out, other);\n }\n\"Various functions (e.g. createNode) taking PrimitiveInfo* can be PrimitiveInfo const*.\" No, they can't, because I cannot call partition() then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-08T17:40:10.227", "Id": "404493", "Score": "1", "body": "Good point. I'd missed the `partition`. However, I'd then suggest there's no reason to modify external data like that. If we need to modify it, we should take the data by value in the constructor." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-02T20:06:25.303", "Id": "208891", "ParentId": "208236", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T14:39:06.807", "Id": "208236", "Score": "4", "Tags": [ "c++", "collision" ], "Title": "Bounding volume hierarchy C++" }
208236
<p>I want to find all shortest paths between a pair of vertices in a unweighted graph i.e all paths that have the same length as the shortest. The edges of the graph are stored in a SQL database. The graph has about 460,000,000 edges and 5,600,000 nodes. My approach is to use a bidirectional BFS to find all the shortest paths.</p> <p>I implemented the algorithm as follows: A search is started from the source node outwards to the target node and one is started on the target node and searches in the direction of the source. If there is a intersection between the nodes visited by the BFS from the source to the target and the BFS from target to source a path has been found. Since I wish to find all the paths the current distance from the source is saved and the current distance from the target is saved. The search then continues as long as there are more nodes with the same distance from the source or same distance from the target. Now all paths have been found but not just the shortes but also longer once. The last step is therefore to remove the paths that are not the shortest.</p> <p>The SQL database looks like this:</p> <pre><code>CREATE TABLE edges ( edge_from UNSIGNED int(10) NOT NULL, edge_target UNSIGNED int(10) NOT NULL ); CREATE INDEX edges_from_index ON edges (edge_from); CREATE INDEX edges_target_index ON edges (edge_target); </code></pre> <p>Running the function on my computer takes a few seconds even if the path is pretty short. A quick look at the time spent in each function with <code>cProfile</code> reveals that what takes the longest are the SQL-lookup. Is there anything I can do to improve the time complexity and thereby decrease the lookups or can I improve my SQL-database/SQL-query to make it any faster? I also appreciate any comments on my code in general. Here is my code:</p> <pre><code>import sqlite3 import collections import itertools def bidirectional_BFS(connection, source, target): """ Returns all the shortest paths between 'source' and 'target'. """ source_queue = collections.deque((source,)) target_queue = collections.deque((target,)) source_visited = {source: 0} # Maps a node to it's distance from the source target_visited = {target: 0} # Maps a node to it's distance from the target # Keeps track all the ways to get to a given node source_parent = collections.defaultdict(set) target_parent = collections.defaultdict(set) source_parent[source].add(None) target_parent[target].add(None) found_path = False source_deapth = 0 target_deapth = 0 # The set of all intersections between the two searches intersections = set() while source_queue and target_queue: if found_path and (source_visited[source_queue[0]] &gt; source_deapth and target_visited[target_queue[0]] &gt; target_deapth): # We are done. All nodes at the current deapth has been explored intersections = filter_intersections(source_visited, target_visited, intersections) return construct_path(source_parent, target_parent, source, target, intersections) if found_path and source_visited[source_queue[0]] &gt; source_deapth: # Found a path but the BFS from the target still has more nodes to explore target_added, t_deapth = BFS_target(target_queue, target_visited, target_parent, connection) intersections |= target_added &amp; source_visited.keys() elif found_path and target_visited[target_queue[0]] &gt; target_deapth: # Found a path but the BFS from the source still has more nodes to explore source_added, s_deapth = BFS_source(source_queue, source_visited, source_parent, connection) intersections |= source_added &amp; target_visited.keys() else: source_added, s_deapth = BFS_source(source_queue, source_visited, source_parent, connection) target_added, t_deapth = BFS_target(target_queue, target_visited, target_parent, connection) intersections |= source_added &amp; target_visited.keys() intersections |= target_added &amp; source_visited.keys() if not found_path and intersections: # We found a path so we look the search deapth to the current deapth found_path = True source_deapth = s_deapth target_deapth = t_deapth if found_path: return construct_path(source_parent, target_parent, source, target, intersections) else: return None def filter_intersections(source_visited, target_visited, intersections): """ Returns only the intersections where the combined distance from source to the intersection and from target to the intersect are the smallest """ filterd = set() shortest = float('inf') for intersection in intersections: if source_visited[intersection] + target_visited[intersection] &lt; shortest: shortest = source_visited[intersection] + target_visited[intersection] filterd = {intersection} elif source_visited[intersection] + target_visited[intersection] == shortest: filterd.add(intersection) return filterd def construct_path(source_parent, target_parent, source, target, intersections): """ Constructs all paths and returns a list of list where each list is one path """ paths = set() for intersection in intersections: from_source_to_inter = construct_path_from_to(source_parent, source, intersection) from_inter_to_target = construct_path_from_to(target_parent, target, intersection, reverse=True) for path in itertools.product(from_source_to_inter, from_inter_to_target): paths.add(tuple(path[0] + path[1][1:])) return paths def construct_path_from_to(source_parent, target, start, reverse=False): """ Constructs all paths between start and target recursivly. If reverse is true then all the paths are reversed. """ if start == target: return [[target]] paths = [] for parent in source_parent[start]: for path in construct_path_from_to(source_parent, target, parent, reverse): if reverse: path.insert(0, start) else: path.append(start) paths.append(path) return paths def BFS_source(queue, visited, parent, connection): """ Runs one iteration of the BFS from source to the target and then returns the edges explored during the iteration and the current deapth of the search """ current = queue.popleft() added = set() for (neighbor,) in connection.execute('SELECT edge_target FROM edges WHERE edge_from= ?;', (current,)): if neighbor not in visited: parent[neighbor].add(current) visited[neighbor] = visited[current] + 1 queue.append(neighbor) added.add(neighbor) elif visited[current] + 1 == visited[neighbor]: parent[neighbor].add(current) return added, visited[current] def BFS_target(queue, visited, parent, connection): """ Runs one iteration of the BFS from target to source and then returns the edges explored during the iteration and the current deapth of the search """ current = queue.popleft() added = set() for (neighbor,) in connection.execute('SELECT edge_from FROM edges WHERE edge_target = ?;', (current,)): if neighbor not in visited: parent[neighbor].add(current) visited[neighbor] = visited[current] + 1 queue.append(neighbor) added.add(neighbor) elif visited[current] + 1 == visited[neighbor]: parent[neighbor].add(current) return added, visited[current] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T18:33:50.980", "Id": "402184", "Score": "0", "body": "I'm not sure I understand your problem definition. Is your ention to find the [`k-Shortest (simple?) paths`](https://en.wikipedia.org/wiki/K_shortest_path_routing), or does your bi-direction (graph) search definitely provide the behaviour that you want? (I do not believe it is providing the shortest paths). (I've made an adjustment to your title, as there are a few ways to misinterpret it otherwise)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T18:56:38.527", "Id": "402188", "Score": "0", "body": "@VisualMelon No I'm not looking for the k-Shortest paths. In my case there may exist multiple paths between to vertices with the same length. I simply what to find all paths that share length with the shortest. But if you believe that my search does't work then please explain your concerns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T19:05:33.067", "Id": "402191", "Score": "0", "body": "OK, that's not how I'd understood it. I'm not a Python person, but I may put an answer together later today/tomorrow if you don't get a decent one first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T12:13:35.683", "Id": "402275", "Score": "1", "body": "Is `if neighbornot in visited:` a bug/typo in the code, or did it creep in when it came to code-review?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T12:38:09.673", "Id": "402278", "Score": "0", "body": "@VisualMelon it's not a bug in my code but thanks anyway. I do however think that I've founde one fault in my line of thinking" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T17:27:06.200", "Id": "402306", "Score": "0", "body": "how short is the path? is every node reachable from any node?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T17:33:21.843", "Id": "402308", "Score": "0", "body": "To do less queries, you might want to retrieve all edges from all neighbours instead of 1 at a time at the expense of more memory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T17:33:24.430", "Id": "402309", "Score": "0", "body": "@juvian Every node does not have too be reachable. The path length may vary but it's probably not usually more than maybe 6 steps. (That is however only my assumption. I infact intend to examine exactly that, how long we can expect a path to be)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T17:44:50.700", "Id": "402313", "Score": "0", "body": "do you know the largest distance between 2 nodes? How many edges does a node usually have?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T18:04:48.320", "Id": "402321", "Score": "0", "body": "I think the best you can do is do 1 query for each level (all edges from nodes with distance 1, all with distance 2, all with 3...) instead of doing 1 query per node as you have currently" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T20:17:01.240", "Id": "402343", "Score": "0", "body": "@juvian I do not know the largest distance between to nodes. There are on average about 70-80 edges per vertex but it may vary. I don't know that much SQL so could you please show how to do the query you speak of and how to retrieve all items as you mention" } ]
[ { "body": "<p>Pseudocode of source to target bfs using 1 query for each level. This meand that if the distance is 6, you only need 6 queries:</p>\n\n<pre><code>queue.add(source)\nwhile queue is not empty:\n nodesOnThisLevel = []\n edges = {}\n while queue is not empty:\n nodesOnThisLevel.append(queue.pop())\n for (edge_from, edge_target) in connection.execute('SELECT edge_from, edge_target FROM edges WHERE edge_from in {}'.format(tuple(nodesOnThisLevel))):\n edges[edge_from].append(edge_target)\n\n for node in nodesOnThisLevel:\n for neighbor in edges[node]:\n if edge_target not in visited:\n queue.add(edge_target)\n visited[edge_target] = true \n update distance\n if edge_target == target:\n finish\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T20:28:28.383", "Id": "208308", "ParentId": "208237", "Score": "1" } }, { "body": "<p>SQL is a set-oriented language. I think to obtain good performance you need to use it in that way. I suggest two temporary tables with the points reachable in one step, then two steps, then three steps etc from the two given points. At each step a new set of points will be inserted into the temporary tables. Something like this:</p>\n\n<pre><code>create table #t1 ( pt unsigned (10 ) )\ninsert into #t1 (pt) @p1 -- The first given point\n\ncreate table #t2 ( pt unsigned (10 ) )\ninsert into #t2 (pt) @p2 -- The second given point\n\nwhile not exists ( select 1 from #t1 as A inner join #t2 as B where A.pt = B.pt )\nbegin\n insert into #t1 ( pt ) \n select edge_target from edges as E inner join #t1 as X on E.edge_from = X.pt\n\n insert into #t2 ( pt ) \n select edge_target from edges as E inner join #t2 as X on E.edge_from = X.pt\nend\n</code></pre>\n\n<p>This simply finds the distance between the two points (or loops indefinitely if there is no path!), it shouldn't be too hard to modify it to recover the paths.</p>\n\n<p>Just a suggestion, I haven't programmed this myself. The temporary tables should be indexed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-01T20:14:47.507", "Id": "210710", "ParentId": "208237", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T15:01:27.633", "Id": "208237", "Score": "2", "Tags": [ "python", "algorithm", "python-3.x", "sql", "graph" ], "Title": "Find all shortest paths between 2 nodes in a directed, unweighted, SQL graph" }
208237
<p>After reading <a href="https://wrosinski.github.io/deep-learning-frameworks/" rel="nofollow noreferrer">this</a>, I decided to transition my DQN code from the keras library to tf.keras library (code is located in <a href="https://github.com/Neves4/SnakeAI" rel="nofollow noreferrer">this repo</a>) and my original code used NCHW format, as it was faster with GPUs. As I need to run in CPUs also, I found out that it ran only with NHWC format on my tf version (1.12 with python 3.7, compiled with AVX2 flags).</p> <p>I redesigned my code and it's working, but I stack in the NCHW format and then I have to transpose it every function call, which is costly.</p> <h2>My code</h2> <p>There is a 'frames' list sized 'self.nb_frames', which will hold the (10, 10) states. Then I expand_dims and transpose, returning the list in NHWC format.</p> <h3>example.py</h3> <pre><code>#!/usr/bin/env python import numpy as np class Agent(): def __init__(self): """Initialize the agent with given attributes.""" self.frames = None self.nb_frames = 4 def get_game_data(self, state): """Create a list with 4 frames and append/pop them each frame.""" frame = state if self.frames is None: self.frames = [frame] * self.nb_frames else: self.frames.append(frame) self.frames.pop(0) # from (4, 10, 10) to (1, 4, 10, 10) expanded_frames = np.expand_dims(self.frames, 0) # From (1, 4, 10, 10) to (1, 10, 10, 4) | NCHW -&gt; NHWC expanded_frames = np.transpose(expanded_frames, [0, 3, 2, 1]) return expanded_frames board_size = 10 state = np.zeros((board_size, board_size)) agent = Agent() stacked_state = agent.get_game_data(state) </code></pre> <p>In order to verify how costly is to transpose, I've executed the code below for two conditions:</p> <ol> <li>Without transposing (NCHW) = <strong>5.775287926 s</strong>;</li> <li><p>Transposing (NHWC) = <strong>7.381751397 s</strong>.</p> <pre><code>from timeit import Timer t = Timer(lambda: agent.get_game_data(state)) print (t.timeit(number = 1000000)) </code></pre></li> </ol> <p>So transposing is responsible for 27% of the running time of the function get_game_data.</p> <p>Is there a better option to create the list directly in the (10, 10, 4) format? Does my code follow best practices?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T17:39:32.737", "Id": "208242", "Score": "1", "Tags": [ "python", "algorithm", "object-oriented", "numpy", "machine-learning" ], "Title": "Get stacked game state in NHWC format" }
208242
<p>I'm trying to get better at javascript and have built a simple function that returns 1 if the mode is equal to the mean, and 0 if not. You can enter an array of numbers into the function:</p> <pre><code>// tests meanMode([1,2,3]); - returns 0 meanMode([4,4,4,6,2]); - returns 1 meanMode([4,4,4,6,6,6,2]); - returns 0 </code></pre> <p>To clarify, the mean is the middle number in the array, and mode most occurring number.</p> <p>When I was writing this, I wondered whether I create too many variables and overcomplicate things. The problems I thought I might be making are:</p> <ol> <li>There are too many variables</li> <li>It's confusing and over complex</li> <li>It can be hard to retrace my logic and know what the code does and why it's there</li> </ol> <p>I have a few questions that I hope better coders than myself can answer, as I'm relatively new to javascript:</p> <ol> <li>Was using a counts variable necessary?</li> <li>Are all variable keywords (const &amp; let) optimal?</li> <li>Is it wise to include comments to describe what the code does?</li> <li>Was declaring the mode variable before assigning its value the best way? Its value depends on a condition</li> </ol> <p>Before writing this I wrote a brief logic plan as follows:</p> <p>Mode:</p> <ol> <li>var uniqueVals with unique vals (set)</li> <li>for each unique value (uniqueVals.map), count no of occurrences in arr (filter.length) &amp; store as an array</li> <li>if all values are identical, return 0, otherwise get the most frequent &amp; store in variable (there may be cases with no mode)</li> </ol> <p>Mean:</p> <ol> <li>sum all numbers</li> <li>divide by no of numbers</li> </ol> <p>And:</p> <ul> <li>if unique values length is same as arr length, return 0</li> <li>if mean = mode, return 1</li> </ul> <p>When people write programming, is it usually best to have a detailed plan to follow? I wonder whether there are any best practices that I could follow to improve my coding ability.</p> <pre><code>function meanMode(arr) { let uniqueVals = Array.from(new Set(arr)); let counts = uniqueVals.map(function (c, i, a) { return arr.filter(function (c2) { return c2 == c }).length }); // [3,1,1] if (arr.every(sameValues)) { return 0; } else { var mode; // if highest number in counts appears just once, then there is a mode if ((counts.filter(function (x) { return x == (Math.max(...counts)) }).length) == 1) { mode = uniqueVals[counts.indexOf(Math.max(...counts))]; // scope issue? } else { return 0; } const mean = (arr.reduce(function (a, c) { return a + c })) / (arr.length); if (mode == mean) { return 1; } else { return 0; } } function sameValues(c, i, a) { return c == a[0]; } } </code></pre>
[]
[ { "body": "<p>First of all, I don’t think this is reasonable:</p>\n\n<blockquote>\n <p>if unique values length is same as arr length, return 0</p>\n</blockquote>\n\n<p>If your array consists of unique values only (e.g. <code>[1, 2, 3, 4]</code>), its mode is not unique, rather there is multiple modes (in this case <code>[1, 2, 3, 4]</code>). How you define what <em>mode</em> exactly means depends on your application so I’m going to ignore this for now.</p>\n\n<hr>\n\n<p>Let’s look at your code. I’ll list some observations:</p>\n\n<ul>\n<li><strong>Function name</strong>. A name like <code>meanEqualsMode</code> would more clearly describe what the function does</li>\n<li><strong>Unused variables</strong>. There are a few unused variables. Line 3 uses three arguments for the <code>map</code> function’s callback, but the callback is only ever called with one argument: The current array element. You also never use <code>i</code> and <code>a</code>.</li>\n<li><strong>Single-letter variable names</strong>. This style of naming problematic for a variety of reasons. Most importantly, it’s harder to reason about your own code. For example, in line 21, the <code>reduce</code> function has <code>a</code> and <code>c</code> as callback arguments. <code>sum</code> and <code>count</code> would be better names.</li>\n<li><strong>Separation of concerns</strong>. Your <code>meanMode</code> function does multiple things. It calculates the mode <em>and</em> the mean. Instead, use separate functions to calculate the mode and mean separately. If your applications uses the check for equality of mode and mean a lot, this would be a third function calling the other two. I’ve done that in the updated code below.</li>\n<li><strong>Predictable results</strong>. You state that <code>meanMode</code> should return whether the mode and the mean are equal; however, it actually returns a <code>Number</code> (<code>1</code> or <code>0</code>). A comparison function (e.g. a function containing the words <em>is</em>, <em>equal</em>, or similar) should always return a boolean value (<code>true</code> or <code>false</code>). This again makes it easier to reason about your code. Just reading <code>meanEqualsMode([2, 3, 5])</code> should tell you what the result of that function will be without the need to look at the actual implementation.</li>\n</ul>\n\n\n\n<pre><code>function meanEqualsMode(array) {\n const mode = arrayMode(array);\n const mean = arrayMean(array);\n\n return mode === mean;\n}\n\nfunction arrayMode(array) {\n const frequencies = new Map();\n\n for (const value of array) {\n const currentCount = frequencies.has(value) ? frequencies.get(value) : 0;\n frequencies.set(value, currentCount + 1);\n }\n\n let highestCount = 0;\n let mostOccurringValue;\n\n for (const [value, count] of frequencies) {\n if (count &gt;= highestCount) {\n highestCount = count;\n mostOccurringValue = value;\n }\n }\n\n return mostOccurringValue;\n}\n\nfunction arrayMean(array) {\n return array.reduce((sum, value) =&gt; sum + value) / array.length;\n}\n</code></pre>\n\n<p>Now, answering some of your questions:</p>\n\n<blockquote>\n <p>Was using a counts variable necessary?</p>\n</blockquote>\n\n<p>Yes and no. In order to calculate the mode of a list of numbers, you need to know the number of occurrences for each number. However, it is possible to determine the mode <em>while</em> counting the occurences; thus, allowing you to calculate the mode without explicitly storing the occurences. To keep the code simple, I opted for not combining these steps.</p>\n\n<blockquote>\n <p>Are all variable keywords (const &amp; let) optimal?</p>\n</blockquote>\n\n<p>Probably not. You are using <code>const</code> and <code>let</code>. There is very, very little reason to also still use <code>var</code> at all. Most variables are assigned only once and can be defined using <code>const</code>. Some variables have to be declared using <code>let</code> because they’re (re-)assigned later.</p>\n\n<blockquote>\n <p>Is it wise to include comments to describe what the code does?</p>\n</blockquote>\n\n<p>Yes. Take my code for example. Is there something you don’t understand? Then it could’ve maybe explained with a comment. You used a <code>reduce</code> function in your code which I often find hard to read. You need to ask yourself: Is my code dealing with a complex problem that needs explaining or is it just written in a hardly readable fashion? A complex problem is best explained with comments. Code which is hard to read and thus hard to reason about is better fixed by making it more readable and obvious.</p>\n\n<blockquote>\n <p>Was declaring the mode variable before assigning its value the best way? Its value depends on a condition</p>\n</blockquote>\n\n<p>No, it wasn’t. The mode of a list of numbers always exists although it might not be unique. Therefor its value does not logically depend on a condition.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T11:12:07.513", "Id": "402450", "Score": "0", "body": "VERY helpful, thank you. I'll note all of these useful points down. Also I like how you used a for of loop and a new Map to count the number of instances in each array - I'll definitely be copying this trick!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T12:39:52.787", "Id": "208334", "ParentId": "208244", "Score": "3" } }, { "body": "<h2>Too complex</h2>\n<p>As the issue of complexity has not come up and as the functions complexity is O(n<sup>2</sup>) for a problem that can be solved in O(n) where n is length of <code>arr</code>, I must point out some of the flaws.</p>\n<p>The code comments show all the iterations for a worst case argument <code>[2,4,6,8,12,14,16,18,10,10]</code> the return will be <code>1</code>. (<code>**</code> is exponential operator)</p>\n<pre><code>function meanMode(arr) {\n let uniqueVals = Array.from(new Set(arr)); // &lt;&lt; array iteration * 2\n let counts = uniqueVals.map(function (c, i, a) { // &lt;&lt; outer iteration\n return arr.filter(function (c2) { // &lt;&lt; inner iteration **2\n return c2 == c\n }).length\n });\n if (arr.every(sameValues)) { // &lt;&lt; array iteration\n return 0;\n } else {\n var mode;\n if ((counts.filter(function (x) { // &lt;&lt; outer iteration\n return x == (Math.max(...counts)) // &lt;&lt; inner iteration **2 to get max\n }).length) == 1) {\n\n // Next line has nested iteration **2 to get max again\n mode = uniqueVals[counts.indexOf(Math.max(...counts))]; \n } else {\n return 0;\n }\n const mean = (arr.reduce(function (a, c) { // &lt;&lt; array iteration\n return a + c\n })) / (arr.length);\n\n if (mode == mean) {\n return 1;\n } else {\n return 0;\n }\n }\n function sameValues(c, i, a) {\n return c == a[0];\n }\n}\n</code></pre>\n<p>Not only are the 3 instances of iteration at O(n<sup>2</sup>) unneeded, you use <code>Array.filter</code> to count!! :( ... Use <code>Array.reduce</code> to count so you don't need to allocate memory each time you add 1.</p>\n<p>There are also repeated iterations that compute the same value. <code>Math.max(...counts)</code> requires one full iteration of <code>counts</code> each time it is called and you call it in the worst case 2n times.</p>\n<p>Even when you add these optimisations (<code>Array.reduce</code> rather than <code>Array.filter</code> and calculate max once) and gain about 50% performance you are still at O(n<sup>2</sup>).</p>\n<h2>In a single pass O(n)</h2>\n<p>Using a <code>counts = new Map();</code> and a single iteration you can compute the <code>sum</code> to get the mean (after iteration), count each items frequency (via the map), and as you count the frequency you can keep a record of the top two max counts and the current max <code>mode</code>.</p>\n<p>After the iteration compute the <code>mean</code> from the <code>sum</code> divide the <code>arr.length</code>, check if <code>mode</code> is equal to <code>mean</code> and if it is check that the top two frequencies are not equal to return 1 (or true).</p>\n<p>An example of O(n) solution tuned for performance. (has optimisation that give an advantage if there are many sequences of the same value)</p>\n<pre><code>function isMeanMode(arr) {\n const counts = new Map();\n var i, prevMaxVal, item, maxA = -1, maxB = -1, index = 0, max = 1, sum = 0;\n for (i = 0; i &lt; arr.length; i ++) { // Only one iteration O(n)\n const val = arr[i];\n const item = counts.get(val);\n sum += val;\n if (item) { \n item.count++;\n while (val === arr[i + 1]) { // for quick count of sequences\n i++; \n item.count++;\n sum += val;\n }\n if (max &lt;= item.count) {\n max = item.count;\n if (prevMaxVal !== val) { // tracks the top two counts\n maxB = maxA; // if maxA and maxB are the same\n maxA = max; // after iteration then 2 or more mode vals\n } else { maxA = max }\n index = i;\n prevMaxVal = val;\n }\n\n } else { counts.set(val, {count : 1}) }\n }\n if (counts.size === arr.length || maxB !== -1 &amp;&amp; maxA === maxB) { return 0 }\n return arr[index] === sum / arr.length ? 1 : 0;\n}\n</code></pre>\n<p>The above solution has a performance increase from 2 orders of magnitude + faster for large random arrays, to 3-4 times faster for very small arrays.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T16:20:01.183", "Id": "208337", "ParentId": "208244", "Score": "1" } } ]
{ "AcceptedAnswerId": "208334", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T19:11:02.000", "Id": "208244", "Score": "5", "Tags": [ "javascript", "beginner", "statistics" ], "Title": "Simple function returning 1 if the Mean = Mode, or 0 if not" }
208244
<p>I'm new to Python and I came to the following excercise:</p> <blockquote> <p>Write a function named printTable() that takes a list of lists of strings and displays it in a well-organized table with each column right-justified. Assume that all the inner lists will contain the same number of strings. For example, the value could look like this:</p> <pre><code>tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] </code></pre> <p>Your printTable() function would print the following:</p> <pre><code> apples Alice dogs oranges Bob cats cherries Carol moose banana David goose </code></pre> </blockquote> <p>My solution is this:</p> <p><strong>table_printer.py</strong></p> <pre><code>tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] def printTable(tableData): """ Print table neatly formatted: e.g: [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] becomes: apples Alice dogs oranges Bob cats cherries Carol moose banana David goose """ # make list of ints to store later max len element of each list colWidths = [0] * len(tableData) # Store maxlen of each list i = 0 while i &lt; len(tableData): colWidths[i] = len(max(tableData[i], key=len)) i = i + 1 # Print formatted for x in range(len(tableData[0])): for y in range(len(colWidths)): print(tableData[y][x].rjust(colWidths[y]), end=' ') print(end='\n') printTable(tableData) </code></pre> <p>I wonder if this is a good solution or if there is an easier/better way. It took me quite some time to come up with a solution. Still I feel its probaly not very elegant. Maybe I'm overcomplicating it because I came from C/C++ where you oftenly have to do stuff by hand.</p> <p>I read that it's often not a good idea in python to write loops like in other languages with explicit indices (what I basically did here). Are there any alternatives?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T02:11:14.437", "Id": "402218", "Score": "0", "body": "You can compute the maximal length on each row by `np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData])` which returns `[8 5 5]`. These numbers will be used to format the strings." } ]
[ { "body": "<p>Here is my proposal. It is shorter than OP's solution, specially to compute the length of each word to be used in the format procedure while printing.</p>\n\n<p>In a single line, we obtain a 1D array with maximal lengths.</p>\n\n<pre><code>import numpy as np\n\ntableData = [['apples', 'oranges', 'cherries', 'banana'],\n ['Alice', 'Bob', 'Carol', 'David'],\n ['dogs', 'cats', 'moose', 'goose']]\n\nmax_len = np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData])\n\nfor col in range(len(tableData[0])):\n for i in range(len(tableData)):\n print (\"{:&gt;%d}\" % max_len[i]).format(tableData[i][col]),\n print \"\"\n</code></pre>\n\n<p><strong>Output</strong></p>\n\n<pre><code> apples Alice dogs \n oranges Bob cats \ncherries Carol moose \n banana David goose\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T12:48:01.307", "Id": "402399", "Score": "0", "body": "Hello. While the solution is a nice one, your answer just provides and alternative to OP's code which is not what this site is about. Please expand your answer and explain how you're improving OP's solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T13:37:28.020", "Id": "402401", "Score": "0", "body": "@яүυк, hello. Since my knowledge is not big, I tried to improve it. To be true, my code is shorter but I am not sure if it is more efficient. What do you think?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T02:12:53.810", "Id": "208258", "ParentId": "208246", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T19:59:05.343", "Id": "208246", "Score": "3", "Tags": [ "python", "beginner", "strings", "formatting" ], "Title": "Table Printer excercise" }
208246
<p>I wrote the Python class below, which does what I want it to do, but the data structure is a mess. Was wondering if there was a better structure I could use to get the same results but with better readable code.</p> <p>Idea here is we retrieve a dataset from SQL(constructor), cluster the dataset into distinct keys(constructor), iterate through the keys and isolate the matching criteria in the dataset(organizer), pass those data chunks to map_loc_to_lat_long which will find all possible combinations of rows in the chunk and find the straight line distance between all the combination Lat Longs.</p> <pre><code>class OrderProximityModel: def __init__(self, date): self.date = str(date) self.order_data = OrderProxDao().Load_Order_Lat_Long_Date_Zone_Data(self.date) self.distinct = set([str(row.Requirements) + ' ' + str(row.Route_Date) for row in self.order_data]) def organizer(self): container = [] for date_zone in self.distinct: latlng = list(filter(lambda x: str(x.Requirements) + ' ' + str(x.Route_Date) == date_zone, self.order_data)) for i in self.map_loc_to_lat_long(latlng): container.append((i[0][0][0], i[0][0][1], i[0][0][2], i[0][0][4], i[0][0][5], i[0][0][6])) InsertHelpers(container).chunk_maker(100) return True def map_loc_to_lat_long(self, grouped_zone): converted = {} for row in grouped_zone: converted[row.LocationKey] = [row.Latitude, row.Longitude, row.DA, row.Route_Date, row.Requirements, row.DA] grouped_combos = self.combo_creator(converted.keys()) return map(lambda combo: ([converted[combo[0]][2:] + [combo[0]] + [combo[1]] + [StraightLineDistance().dist_cal(converted[combo[0]][0], converted[combo[0]][1], converted[combo[1]][0], converted[combo[1]][1])]], ), grouped_combos) @staticmethod def combo_creator(inputs): out = [] for index, value in enumerate(inputs): for nex_value in inputs[index + 1:]: out.append((value, nex_value)) return out </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T10:41:43.783", "Id": "402384", "Score": "0", "body": "What are `OrderProxDao`, `InsertHelpers`, `StraightLineDistance`?" } ]
[ { "body": "<pre><code>self.date = str(date)\n</code></pre>\n\n<p>This is a pet peeve of mine. Stringly-typed variables are usually a bad idea. If you receive a datetime object, you should usually keep it as datetime until you actually need it to be a string.</p>\n\n<pre><code>Load_Order_Lat_Long_Date_Zone_Data\n</code></pre>\n\n<p>If at all possible, shorten this method name. Also, methods are lowercase by convention.</p>\n\n<pre><code>self.distinct = set([str(row.Requirements) + ' ' + str(row.Route_Date) for row in self.order_data])\n</code></pre>\n\n<p>Here you make a generator, construct a list and then convert it to a set. Skip the list - the <code>set</code> constructor can accept generators directly. Better yet, if you're in a sane version of Python, just use a set literal (and use a format string):</p>\n\n<pre><code>self.distinct = {'%s %s' % (row.Requirements, row.Route_Date) for row in self.order_data}\n</code></pre>\n\n<p>Your <code>container = []</code> / <code>container.append()</code> loop can be replaced by proper use of a generator. Same with <code>out</code>.</p>\n\n<p><code>latlng</code> does not (and should not) be materialized to a list. It should be left as a generator, since you only iterate over it once.</p>\n\n<p>This:</p>\n\n<pre><code>container.append((i[0][0][0], i[0][0][1], i[0][0][2], i[0][0][4], i[0][0][5], i[0][0][6]))\n</code></pre>\n\n<p>can be:</p>\n\n<pre><code>container.append(tuple(i[0][0][j] for j in (0, 1, 2, 4, 5, 6)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T05:19:50.607", "Id": "208263", "ParentId": "208247", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T20:10:42.043", "Id": "208247", "Score": "0", "Tags": [ "python", "python-2.x", "clustering", "geospatial" ], "Title": "Analyzing distances between clusters of orders" }
208247
<p>I've been using this <code>wgs84togrid</code> program for a few years. It converts in both directions between National Grid coordinates for GB or Ireland (beginning with a letter or letter-pair identifying the 100km square) and latitude/longitude positions (in decimal degrees, decimal minutes or decimal seconds) on a WGS84 ellipsoid.</p> <p>It acts as a filter, expecting one point per line, copying unchanged any unrecognised parts of the line.</p> <p>Program options (all may be shortened, provided that's unambiguous):</p> <ul> <li><code>-grid</code>: choose a grid: GB (default) or IE</li> <li><code>-reverse</code>: reverse direction - convert National Grid positions to WGS84</li> <li><code>-lonlat</code>: geodesic positions are longitude first</li> <li><code>-datum</code>: use alternative datum instead of WGS84 (National Grid coordinates are always on the appropriate fixed datum)</li> <li><code>-precision</code>: how many digits to include in northings and eastings (default: 5, which gives 1-metre resolution)</li> <li><code>-verbose</code>: extra output (to confirm that lat/lon are parsed as you expect).</li> </ul> <p>Example use (in Bash):</p> <pre class="lang-none prettyprint-override"><code>$ wgs84togrid -p 3 &lt;&lt;&lt;"55°56′55\″N 3°12′03\″W" NT251734 $ wgs84togrid -r &lt;&lt;&lt;NT251734 55.9482278708547 -3.20011121889597 </code></pre> <p>The heavy work of coordinate transformation is performed by the PROJ.4 library; all I do is manage the grid letters and I/O formats.</p> <p>I assume the presence of <code>scotland.gsb</code> and <code>england-wales.gsb</code> grid corrections files, but that option may be removed if you don't have them, at the cost of a few metres of accuracy (&lt; 10m, I'm sure).</p> <p>Specifically out of scope:</p> <ul> <li>I don't check that the point is within the valid area of the chosen grid (and certainly don't think of auto-selecting the correct grid).</li> <li>No plans to support any other grids elsewhere in the world.</li> </ul> <hr> <pre><code>#!/usr/bin/perl -w use strict; use Getopt::Long; use Geo::Proj4; my %squares = (A=&gt;'04', B=&gt;'14', C=&gt;'24', D=&gt;'34', E=&gt;'44', F=&gt;'03', G=&gt;'13', H=&gt;'23', J=&gt;'33', K=&gt;'43', L=&gt;'02', M=&gt;'12', N=&gt;'22', O=&gt;'32', P=&gt;'42', Q=&gt;'01', R=&gt;'11', S=&gt;'21', T=&gt;'31', U=&gt;'41', V=&gt;'00', W=&gt;'10', X=&gt;'20', Y=&gt;'30', Z=&gt;'40'); my %tosquare = map { ($squares{$_}, $_) } keys %squares; my $grid = 'GB'; my $lonlat; my $datum = 'WGS84'; my $precision = 5; my $reverse; my $verbose; GetOptions('grid=s' =&gt; <span class="math-container">\$grid, 'reverse!' =&gt; \$</span>reverse, 'lonlat!' =&gt; <span class="math-container">\$lonlat, 'datum=s' =&gt; \$</span>datum, 'precision=i' =&gt; <span class="math-container">\$precision, 'verbose!' =&gt; \$</span>verbose) or die "Option parsing failure\n"; sub any2xy($$$) { my ($x, $y, $numbers) = @_; my $len = length $numbers; die "Odd gridref length - '$_' ($len)\n" if $len % 2; $len /= 2; $x = 100000 * ("$x.".substr($numbers, 0, $len).'5'); $y = 100000 * ("$y.".substr($numbers, $len).'5'); return [$x, $y]; } sub osgb2xy($) { local $_ = shift; my ($letters, $numbers) = m/^(\D{2})(\d+)$/ or die "Malformed OSGB ref '$_'\n"; my $x = 0; my $y = 0; foreach (split '', $letters) { my @sq = split '', $squares{$_} or die "Non-grid square '$_'\n"; $x = 5 * $x + $sq[0]; $y = 5 * $y + $sq[1]; } $x -= 10; $y -= 5; return any2xy($x, $y, $numbers); } sub osi2xy($) { $_ = shift; my ($letters, $numbers) = m/^(\D)(\d+)$/ or die "Malformed OSI ref '$_'\n"; my ($x, $y) = split '', $squares{$letters} or die "Non-grid square '$_'\n"; return any2xy($x, $y, $numbers); } sub togrid(<span class="math-container">$$$$</span>) { my ($sq, $x, $y, $prec) = @_; return sprintf('%s%s%s', $sq, map { substr(100000 + $_%100000, 1, $prec) } ($x, $y)); } sub xy2osi($$$) { my ($x, $y, $prec) = @_; my $sq = $tosquare{int($x/100000) . int($y/100000)} or die "No square for $x,$y\n"; return togrid($sq, $x, $y, $prec); } sub xy2osgb($$$) { my ($x, $y, $prec) = @_; $x += 1000000; $y += 500000; my $sq = $tosquare{int($x/500000) . int($y/500000)} . $tosquare{int($x/100000)%5 . int($y/100000)%5} or die "No square for $x,$y\n"; return togrid($sq, $x, $y, $prec); } my $inputs; sub getnext(); sub getnext() { if ($inputs) { $_ = &lt;$inputs&gt;; return $_ if $_; $inputs = undef; } if (@ARGV) { $_ = shift @ARGV; if ($_ eq '-') { $inputs = \*STDIN; return getnext(); } return $_; } return undef; } my $wgs84 = Geo::Proj4-&gt;new(proj =&gt; 'latlon', datum =&gt; $datum) or die Geo::Proj4-&gt;error; my ($proj, $xy2grid, $grid2xy); if (uc $grid eq 'GB') { $proj = Geo::Proj4-&gt;new(init =&gt; 'epsg:27700 +nadgrids=scotland.gsb,england-wales.gsb') or die Geo::Proj4-&gt;error; $xy2grid = \&amp;xy2osgb; $grid2xy = \&amp;osgb2xy; } elsif (uc $grid eq 'IE') { $proj = Geo::Proj4-&gt;new(init =&gt; 'epsg:29901') or die Geo::Proj4-&gt;error; $xy2grid = \&amp;xy2osi; $grid2xy = \&amp;osi2xy; } else { die "Unknown grid '$grid'\n"; } my $numpat = '[+-]?\d+(?:\.\d+)?\s*'; @ARGV=('-') unless @ARGV; while ($_ = getnext()) { chomp; if ($reverse) { my $point = $grid2xy-&gt;($_); my ($lon, $lat) = @{$proj-&gt;transform($wgs84, $point)}; print $lonlat ? "$lon $lat\n" : "$lat $lon\n"; } else { tr/,'"/ ms/; # ' # for prettify s/°/d/g; # UTF-8 multibyte chars don't work with 'tr' s/′/m/g; s/″/s/g; s/($numpat)m\s*($numpat)s?/($1 + $2\/60.0) . "m"/oeg; s/($numpat)d(?:eg)?\s*($numpat)(?:m\s*)?/($1 + $2\/60.0)/oeg; tr/d//d; s/\s*\b([nsew])\b\s*/$1/i; tr!/,! !; s/($numpat[ew ])\s*($numpat[ns]?)/$2 $1/oi; s/($numpat)\s+($numpat[ns]|[ns]$numpat)/$2 $1/oi; my ($lat, $ns, $lon, $ew) = m/^\s*($numpat)([ns ]?)\s*($numpat)([ew]?)\s*$/i or die "Malformed input: $_\n"; $lat *= -1 if lc $ns eq 's'; $lon *= -1 if lc $ew eq 'w'; print STDERR "$lat, $lon\n" if $verbose; my $point = ($ns || $ew || $lonlat) ? [$lon, $lat] : [$lat, $lon]; my ($x, $y) = @{$wgs84-&gt;transform($proj, $point)}; print $xy2grid-&gt;($x, $y, $precision), "\n"; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T21:32:14.893", "Id": "402201", "Score": "1", "body": "You can probably tell that I learnt Perl 4 a couple of decades ago and haven't kept up. Perl 5 suggestions are of course welcome, though you might need to assume much lower understanding from me if that's what you choose to contribute. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T21:35:15.067", "Id": "402202", "Score": "0", "body": "Something seems to have got mangled in the `GetOptions()` call when I pasted this (as if tabs had been crushed to 4 spaces - but I didn't use tabs for indentation!). For the record, the options *do* all line up, and it's just a SE display bug there (assuming I'm not the only one seeing that!)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T09:44:13.723", "Id": "402246", "Score": "0", "body": "I see the wrong indentation as well. However, in edit mode, the lines line up correctly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T09:56:14.887", "Id": "402247", "Score": "0", "body": "Thanks @Martin - I've tried everything I can think of, but no difference. The really annoying thing is that it looks fine in preview. If I can be bothered, perhaps I might ask about it on Meta.SE." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-10T13:03:47.930", "Id": "416005", "Score": "0", "body": "Have you considered turning those long numbers into constants?" } ]
[ { "body": "<p><em>NB: This review assumes Perl5, specifically the Unicode features in 5.12 (released 2010) and later.</em></p>\n<hr />\n<h3>1. the parsing could be simpler and more featureful</h3>\n<p>Much code is devoted to handling delimiters that we're only going to throw away.</p>\n<p>Explicit N/S/E/W should override <code>-lonlat</code> but don't.</p>\n<p>The sole error message (&quot;malformed input&quot;) is vague and happens at the very end, after a series of transformations on the input. The mangled string—which may not resemble original input much anymore—is included in the error message and only adds to the confusion.</p>\n<p>In general: modifying an input string to impart meaning is usually a mistake. Modify to remove noise, extract the meaningful parts as structured data, and deal with them there.</p>\n<h3>2. there is a fair amount of duplicated or nearly-duplicated code</h3>\n<p>A dispatch table is the standard way to choose code based on data. Your &quot;a2b&quot; functions have a lot of common code, and can be merged once the unique parts are moved into a data structure.</p>\n<h3>3. the data representations could be more suitable</h3>\n<p><code>squares</code> and <code>tosquare</code> use 2-digit values, but you never need values in that format. You always need a pair of single digits, and this complicates the conversion functions. Restructure to suit the need, such that <code>$squares{A} == [ 0, 4 ]</code> (hash of arrays) and <code>$tosquare[0][4] == 'A'</code> (array of arrays).</p>\n<p><code>100000</code> is better written as <code>100_000</code> or <code>1e5</code>.</p>\n<p><code>$numpat</code> can be simplified to <code>qr/[+-]? \\d+ \\.?\\d* \\s* /x</code>. Write regular expression pieces with the <code>qr/REGEXP/</code> quoting construct, so that they are only compiled once; you then won't need <code>/o</code> modifiers when you reference them. The <code>/x</code> modifier allows the use of whitespace in regular expressions, and makes long expressions more readable. Space within <code>[ ]</code> is still recognized; other whitespace is ignored.</p>\n<h3>4. Unicode handling is haphazard</h3>\n<p>This is an artifact of writing in Perl4, which had no Unicode facilities. In Perl5, UTF-8 source code (<code>s/°/d/g;</code> etc.) should inform Perl of the source encoding via <code>use utf8;</code>.</p>\n<p>To accept UTF-8 input, <code>STDIN</code> should be placed in <code>:utf8</code> mode, via <code>binmode STDIN, &quot;:utf8&quot;</code>. As you're including user input in <code>die</code> messages, <code>STDERR</code> should get the same treatment.</p>\n<h3>5. tricks and minor stuff</h3>\n<p><code>getnext()</code> is about three times longer and more confusing than it ought to be; see below for a revised version.</p>\n<p>Every output ends in a newline; use the <code>-l</code> switch instead.</p>\n<p><code>%tosquare = reverse %squares</code> is the idiomatic version of <code>%tosquare = map { ($squares{$_}, $_) } keys %squares</code>.</p>\n<p><code>local $_ = shift;</code> is usually what you want when assigning to <code>$_</code> in a sub, else it will be clobbered in the calling scope. (The rewrite contravenes this advice and clobbers <code>$_</code> on purpose.)</p>\n<p><code>nadgrids=</code> can be adjusted at setup time to ignore missing files. Calls to <code>-&gt;transform()</code> should print error on failure (due to, say, a missing nadgrids file :)</p>\n<p>A long series of synonym-to-canonical-value substitutions, as you're doing with <code>s/°/d/g</code>, etc., can be replaced by a hash table where the keys combine into a regex, as in:</p>\n<pre><code> my %decoratives=(qw( ' m &quot; s ° d ′ m ″ s ), (&quot;,&quot; =&gt; &quot; &quot;) );\n s/([@{[ join '', keys %decoratives ]}])/$decoratives{$1}/g; \n</code></pre>\n<h3>revision</h3>\n<p>Here's my response to my own criticisms. It's not much shorter—about 75% of the original's size—but does improve the error messages and is (perhaps) more clear in its intent.</p>\n<pre class=\"lang-perl prettyprint-override\"><code>#!/usr/bin/perl -wl\nuse strict;\nuse Getopt::Long;\nuse Geo::Proj4;\nuse utf8;\nbinmode STDIN, &quot;:utf8&quot;;\nbinmode STDERR, &quot;:utf8&quot;;\nsub grid2xy(_);\nsub xy2grid($$$);\nsub getnext();\n\nmy %squares = qw( \n A 04 B 14 C 24 D 34 E 44 F 03 G 13 H 23 J 33 K 43 L 02 M 12 N 22 \n O 32 P 42 Q 01 R 11 S 21 T 31 U 41 V 00 W 10 X 20 Y 30 Z 40 \n);\nmy @tosquare;\n$tosquare[ int $squares{$_}/10 ][ $squares{$_}%10 ] = $_ for keys %squares;\n$_ = [ split '' ] for values %squares; \n\nmy %howto=(\n GB =&gt; {\n setup =&gt; 'epsg:27700 +nadgrids=' . join(',' =&gt; grep { -f } qw( scotland.gsb england-wales.gsb )),\n parse =&gt; qr/^(\\D\\D)(\\d+)$/,\n xy2os =&gt; sub { [ map { int($_[$_]/5e5) + 2 - $_ } 0..1 ], [ map { ($_[$_]/1e5) % 5 } 0..1 ] },\n os2xy =&gt; sub { map { 5*$_[0][$_] + $_[1][$_] - 10 + 5*$_ } 0..1 }\n },\n IE =&gt; {\n setup =&gt; 'epsg:29901',\n parse =&gt; qr/^(\\D)(\\d+)$/,\n xy2os =&gt; sub { [ map int($_/1e5) =&gt; @_ ] },\n os2xy =&gt; sub { @{ $_[0] } }\n }\n);\n\nmy ($grid, $datum, $precision,$lonlat,$reverse,$verbose) = ('GB', 'WGS84', 5);\nGetOptions(\n 'grid=s' =&gt; <span class=\"math-container\">\\$grid,\n 'reverse!' =&gt; \\$</span>reverse,\n 'lonlat!' =&gt; <span class=\"math-container\">\\$lonlat,\n 'datum=s' =&gt; \\$</span>datum,\n 'precision=i' =&gt; <span class=\"math-container\">\\$precision,\n 'verbose!' =&gt; \\$</span>verbose\n) or die &quot;Option parsing failure\\n&quot;;\n\nour %do=%{ $howto{$grid} or die &quot;Unknown grid $grid\\n&quot; };\n\nmy $wgs84 = Geo::Proj4-&gt;new(proj =&gt; 'latlon', datum =&gt; $datum) or die Geo::Proj4-&gt;error;\nmy $proj = Geo::Proj4-&gt;new(init =&gt; $do{setup}) or die Geo::Proj4-&gt;error;\n\n@ARGV=('-') unless @ARGV;\nwhile (getnext) { \n if ($reverse) {\n my @lola = @{ $proj-&gt;transform($wgs84, grid2xy) or die $proj-&gt;error };\n local $,=&quot; &quot;;\n print $lonlat ? @lola : reverse @lola;\n } else {\n my @tokens= map {uc} /( [+-]? \\d+ \\.?\\d* | [NSEW] )/gix;\n print &quot;tokens: @tokens&quot; if $verbose;\n my @lalo=(0,0);\n my @dms=( 1, 60, 3600 );\n my ($unit,$ll,$seenNS, $seenEW)=(0,0,0,0);\n my %seen=( N =&gt; <span class=\"math-container\">\\$seenNS, S =&gt; \\$</span>seenNS, E =&gt; <span class=\"math-container\">\\$seenEW, W =&gt; \\$</span>seenEW );\n my %sign=( N =&gt; 1, S =&gt; -1, E =&gt; 1, W =&gt; -1 );\n while (@tokens) { \n my $tok=shift @tokens;\n if ($sign{$tok}) { \n die &quot;Repeated or conflicting direction '$tok'\\n&quot; if ${ $seen{$tok} };\n die &quot;Directions come after the coordinates\\n&quot; unless $unit;\n $lalo[$ll++] *= $sign{$tok};\n ${ $seen{$tok} } = $ll; # after the increment so that it's nonzero.\n $unit=0;\n } else {\n if ($unit&gt;$#dms) { $ll++; $unit=0; }\n die &quot;Too many coordinates in '$_'\\n&quot; if $ll&gt;1;\n $lalo[$ll] += $tok / $dms[$unit++];\n }\n }\n @lalo=reverse @lalo if (!$seenNS &amp;&amp; !$seenEW &amp;&amp; $lonlat or $seenNS==1 or $seenEW==2);\n print STDERR &quot;lat/lon @lalo&quot; if $verbose;\n my ($x, $y) = @{ $wgs84-&gt;transform($proj, [ @lalo ]) or die $wgs84-&gt;error };\n print xy2grid($x, $y, $precision);\n }\n}\nexit 0;\n\nsub grid2xy(_) {\n local $_=shift;\n my ($letters, $numbers) = /$do{parse}/ or die &quot;Malformed ref '$_'\\n&quot;;\n my $len = length $numbers;\n die &quot;Odd gridref length - '$_' ($len)\\n&quot; if $len % 2;\n $len /= 2;\n my @sq = map { $squares{$_} or die &quot;Non-grid square '$_'\\n&quot; } split '', $letters;\n my ($x,$y) = $do{os2xy}(@sq);\n $x = 100000 * (&quot;$x.&quot;.substr($numbers, 0, $len).'5');\n $y = 100000 * (&quot;$y.&quot;.substr($numbers, $len).'5');\n return [$x, $y];\n}\n\nsub xy2grid($$$) { \n my ($x, $y, $prec) = @_;\n local $,=&quot;,&quot;; # for the die()\n my $sq = join '', map { $tosquare[ $_-&gt;[0] ][ $_-&gt;[1] ] or die &quot;No square for @$_\\n&quot; } $do{xy2os}($x,$y); \n return sprintf('%s%s%s', $sq, map { substr(100000 + $_%100000, 1, $prec) } ($x, $y));\n}\n\nsub getnext() {\n if (@ARGV and $ARGV[0] eq '-') {\n if ($_ = &lt;STDIN&gt;) { chomp; return $_ }\n else { shift @ARGV }\n }\n return $_=shift @ARGV;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T08:47:07.813", "Id": "416086", "Score": "1", "body": "Excellent review; I've learnt a lot from this. Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T12:31:07.603", "Id": "416118", "Score": "1", "body": "I will be keeping a 5-line version of `%squares` - the newlines there do actually show the 5x5 structure embodied in the coordinates." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T08:18:34.313", "Id": "416420", "Score": "0", "body": "I think I remember why the error message includes the part-processed (aka *mangled*) input: I thought it would be useful to see what had been matched. Of course, that makes sense only to the author (I probably added that when debugging) and not to other users, and I need to learn to improve my users-eye-view of what I write!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T10:28:52.527", "Id": "416446", "Score": "0", "body": "yes, that kind of telemetry comes with the territory of parse-by-`s///`, which is a trap we've all fallen into, because it's seductively immediate and concise. That sentence in my review that begins \"In general: …\" was multiple, rambling paragraphs on this topic; they didn't make the final draft." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-11T01:51:38.150", "Id": "215162", "ParentId": "208248", "Score": "5" } } ]
{ "AcceptedAnswerId": "215162", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T20:35:37.527", "Id": "208248", "Score": "11", "Tags": [ "perl", "geospatial" ], "Title": "Convert British and Irish National Grid references to or from WGS84 geodetic coordinates" }
208248
<p>Python allows logging to be used in several ways. Can you review the relative merits of these two approaches to Logging when Unit Testing with Python? Is one approach appropriate to specific circumstances? What are those circumstances and how might each approach be improved?</p> <p><strong>Directly addressing the logger</strong>.</p> <pre><code>#!/usr/bin/env python import logging import unittest class LoggingTest(unittest.TestCase): logging.basicConfig(level=logging.INFO) def test_logger(self): logging.info("logging.info test_logger") pass </code></pre> <p><strong>Getting a logger by name</strong></p> <pre><code>#!/usr/bin/env python import logging import unittest class GetLoggerTest(unittest.TestCase): logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) def test_logger(self): self.logger.info("self.logger.info test_logger") pass </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T07:02:08.510", "Id": "402229", "Score": "2", "body": "It's not clear what you are testing. Is your goal to test if correct output appears in the log?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T18:46:54.157", "Id": "402329", "Score": "1", "body": "This comment seems immaterial to the code to be reviewed. I am asking for a review of the two different approaches to logging shown. This review is about the logging not testing." } ]
[ { "body": "<p>According to the <a href=\"https://docs.python.org/3/library/logging.html\" rel=\"nofollow noreferrer\">logging docs</a>:</p>\n\n<blockquote>\n <p>The logger name hierarchy is analogous to the Python package hierarchy, and identical to it if you organise your loggers on a per-module basis using the recommended construction <code>logging.getLogger(__name__)</code>. That’s because in a module, <code>__name__</code> is the module’s name in the Python package namespace.</p>\n</blockquote>\n\n<p>Based on my experience, I would say that you should always use <code>logging.getLogger(__name__)</code> for bigger projects, as it'll make logging modularization easier.</p>\n\n<p>As your question is broad, I recommend you to read the Logging Cookbook, <a href=\"https://docs.python.org/3/howto/logging-cookbook.html\" rel=\"nofollow noreferrer\">in this link</a>, as it holds many important use cases in which you could optimize the way you use logging.</p>\n\n<p>It's also possible to mix both cases in order to add a timestamp, in example, which is an improved way of using this module:</p>\n\n<pre><code>#!/usr/bin/env python\nimport logging\nimport unittest\n\nclass GetLoggerTest(unittest.TestCase):\n logger = logging.getLogger(__name__)\n logging.basicConfig(format = '%(asctime)s %(module)s %(levelname)s: %(message)s',\n datefmt = '%m/%d/%Y %I:%M:%S %p', level = logging.INFO)\n\n def test_logger(self):\n self.logger.info(\"self.logger.info test_logger\")\n pass\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T00:42:42.673", "Id": "208256", "ParentId": "208251", "Score": "2" } } ]
{ "AcceptedAnswerId": "208256", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T21:32:22.453", "Id": "208251", "Score": "2", "Tags": [ "python", "unit-testing", "logging" ], "Title": "Two approaches to Logging when Unit Testing with Python" }
208251
<p>Not satisfied with the Brute Force Solver that I wrote for <a href="https://stackoverflow.com/a/53330707/9912714">All possible combinations of 1 to 9 in the same cells without repetition</a>, I created an OOP Cross Sum Solver. </p> <p>As expected my OOP Solver crushes the Brute Force Solver performace, 0.03-0.12 seconds compared to 109 - 400 seconds respectively.</p> <p>I probably should post the Brute Force Solver instead but I found it boring.</p> <p><a href="https://i.stack.imgur.com/DCO4W.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DCO4W.jpg" alt="Cross Sum Examples"></a></p> <p><a href="http://www.contestcen.com/cross.htm" rel="nofollow noreferrer">The Contest Center:CROSS SUMS Rules</a></p> <blockquote> <p>"Your job is to fill the numbers from 1 to 9 into the 9 empty boxes so that the arithmetic in each row is correct. The math operations are performed from left to right. So to evaluate 1+2×5 you first add 1+2 to get 3, and then multiply that by 5 to get 15. When performing the operations you may never go below zero, and each division must be even. Thus you could not have 5-7+4 because 5-7 goes below 0, and you could not have 7÷2+6 because 7÷2 is not an even division, it has a remainder."</p> </blockquote> <h2>Class Overview</h2> <ul> <li>Node: Basically a list of numbers. Each Node is linked to 2</li> <li>Equations Equation: Processes a set of 3 Nodes, 2 operators, and an Answer</li> <li>Solver: Links 9 Nodes to 6 Equations</li> </ul> <h2>Calculate</h2> <p>Initially the Solver will trigger each Equation to Calculate. As an Equation is calculated, each of its Nodes numbers lists are optimised by removing numbers that can not be used to solve the Equation. If a Node's list is reduced to 1 then the Nodes value is removed from all other Node's number lists. If an Equation causes a Node to change than all Equations are recalculated. This is necessary because each Node is linked to 2 Equations. At this point if an Equation is not solved then the <code>ApplyBruteForce</code> method of each Equation can be used to solve the Puzzle. </p> <h2>ApplyBruteForce</h2> <p>This method first saves each nodes state and then attempts to solve each Equation but testing all combinations of its Nodes number lists. If an answer can not be determined after an Equation is tested than the Nodes state are restored and the next Equation is evaluated. </p> <p>Note: All problems were solved on or before the 3rd Equation was tested. It is possible that an this method will not solve all problems. If this is the case than a true Brute Force method will need to be added.</p> <h2>Class: Node</h2> <pre><code>Attribute VB_Name = "Node" Option Explicit Private passed() As Boolean Private numbers() As Long Private saved() As Long Private Index As Long Public Dirty As Boolean Private Sub Class_Initialize() ReDim passed(8) ReDim numbers(8) Dim n As Long For n = 0 To 8 numbers(n) = n + 1 Next End Sub Public Function Count() As Long Count = UBound(numbers) + 1 End Function Public Function Current() As Long Current = numbers(Index) End Function Public Sub DeleteElementAt(ByVal Index As Integer, ByRef prLst As Variant) Dim i As Integer ' Move all element back one position For i = Index + 1 To UBound(prLst) prLst(i - 1) = prLst(i) Next ' Shrink the array by one, removing the last one ReDim Preserve prLst(Len(prLst) - 1) End Sub Public Function EOF() As Boolean EOF = Index &lt;= UBound(numbers) End Function Public Sub MoveFirst() Index = 0 End Sub Public Sub MoveNext() Index = Index + 1 End Sub Public Sub Remove(Value As Long) Dim n1 As Long, n2 As Long If UBound(numbers) = 0 Then 'Stop Exit Sub End If For n1 = UBound(numbers) To 0 Step -1 If numbers(n1) = Value Then For n2 = n1 To UBound(numbers) - 1 numbers(n2) = numbers(n2 + 1) Next ReDim Preserve numbers(UBound(numbers) - 1) ReDim passed(UBound(numbers)) Exit Sub End If Next End Sub Public Sub RemoveBadNumbers() Dim oldCount As Long, n As Long, pIndex As Long oldCount = Count pIndex = -1 For n = 0 To UBound(numbers) If passed(n) Then pIndex = pIndex + 1 If pIndex &lt; n Then numbers(pIndex) = numbers(n) End If Next If pIndex &lt; UBound(numbers) And pIndex &gt; -1 Then ReDim Preserve numbers(pIndex) ReDim passed(UBound(numbers)) Dirty = oldCount &lt;&gt; Count End Sub Public Sub Restore() ReDim numbers(UBound(saved)) ReDim passed(UBound(numbers)) Dim n As Long For n = 0 To UBound(numbers) numbers(n) = saved(n) Next End Sub Public Sub Save() ReDim saved(UBound(numbers)) Dim n As Long For n = 0 To UBound(numbers) saved(n) = numbers(n) Next End Sub Public Sub setValue(n As Long) ReDim passed(0) ReDim numbers(0) numbers(0) = n End Sub Public Function ToString() As String Dim n As Long ReDim results(UBound(numbers)) For n = 0 To UBound(numbers) results(n) = numbers(n) Next ToString = "{" &amp; Join(results, ",") &amp; "}" End Function Public Sub ValidateCurrent() passed(Index) = True End Sub Public Function Value(ByVal Index As Long) As Long Index = Index - 1 Value = numbers(Index) End Function </code></pre> <h2>Class: Equation</h2> <pre><code>Attribute VB_Name = "Equation" Option Explicit Private Type Members answer As Long operator(1 To 2) As String End Type Private this As Members Public Node1 As Node Public Node2 As Node Public Node3 As Node Public Dirty As Boolean Public Sub Init(operator1 As String, operator2 As String, answer As Long) this.operator(1) = operator1 this.operator(2) = operator2 this.answer = answer End Sub Public Function Solved() As Boolean Solved = Count = 3 End Function Public Sub Calculate() Node1.MoveFirst While Node1.EOF Node2.MoveFirst While Node2.EOF Node3.MoveFirst While Node3.EOF If Node1.Current &lt;&gt; Node2.Current And Node1.Current &lt;&gt; Node3.Current And Node2.Current &lt;&gt; Node3.Current Then Dim part1 As Long Dim n1 As Long, n2 As Long, n3 As Long n1 = Node1.Current n2 = Node2.Current n3 = Node3.Current part1 = ev(Node1.Current, Node2.Current, this.operator(1)) If part1 &gt;= 0 Then If ev(part1, Node3.Current, this.operator(2)) = this.answer Then 'Debug.Print Node1.Current, Node2.Current, Node3.Current, ev(ev(Node1.Current, Node2.Current, this.operator(1)), Node3.Current, this.operator(2)) Node1.ValidateCurrent Node2.ValidateCurrent Node3.ValidateCurrent End If End If End If Node3.MoveNext Wend Node2.MoveNext Wend Node1.MoveNext Wend Dim oldCount As Long oldCount = Count RemoveBadNumbers Dirty = oldCount &lt;&gt; Count End Sub Public Function Count() As Long Count = Node1.Count + Node2.Count + Node3.Count End Function Private Sub RemoveBadNumbers() Node1.RemoveBadNumbers Node2.RemoveBadNumbers Node3.RemoveBadNumbers End Sub Private Function ev(v1 As Long, v2 As Long, operator As String) As Long Select Case operator Case "+" ev = v1 + v2 Case "-" ev = v1 - v2 Case "/", "÷" ev = v1 / v2 Case "*", "×", "x", "X" ev = v1 * v2 Case Else Debug.Print operator End Select End Function Public Function ToString() As String ToString = this.operator(1) &amp; " " &amp; this.operator(2) &amp; " " &amp; this.answer &amp; ": " &amp; Node1.ToString &amp; "," &amp; Node2.ToString &amp; "," &amp; Node3.ToString End Function Private Sub Class_Initialize() Set Node1 = New Node Set Node2 = New Node Set Node3 = New Node End Sub </code></pre> <h2>Class: Solver</h2> <pre><code>Attribute VB_Name = "Solver" Private Type Members answer As Long Data As Variant operator(1 To 2) As String Solved As Boolean End Type Private this As Members Private Equations(1 To 6) As Equation Private Test(1 To 2) As Node Private Nodes(1 To 9) As New Node Public Sub ApplyBruteForce() Save Dim n As Long For n = 1 To 6 With Equations(n) If Not .Solved Then Dim n1 As Long, n2 As Long, n3 As Long For n1 = 1 To .Node1.Count For n2 = 1 To .Node2.Count For n3 = 1 To .Node3.Count If .Node1.Value(n1) &lt;&gt; .Node2.Value(n2) And _ .Node1.Value(n1) &lt;&gt; .Node3.Value(n3) And _ .Node2.Value(n2) &lt;&gt; .Node3.Value(n3) Then .Node1.setValue .Node1.Value(n1) .Node2.setValue .Node2.Value(n2) .Node3.setValue .Node3.Value(n3) RemoveCompletedNumbers Me.Calculate If Solved Then Exit Sub Restore End If Next Next Next End If End With If Solved Then Exit Sub Restore Next End Sub Private Sub ForceNodeValues() Save Dim n As Long For n = 1 To 9 If TestNode(Nodes(n)) Then Exit Sub Next End Sub Private Function TestNode(Node As Node) As Boolean Dim n As Long For n = 1 To Node.Count Node.setValue Node.Value(n) RemoveCompletedNumbers Me.Calculate If Solved Then TestNode = True Exit Function End If Restore Next End Function Public Sub Calculate() Dim n As Long For n = 1 To 6 Equations(n).Calculate If Equations(n).Dirty Then RemoveCompletedNumbers n = 0 End If Next End Sub Public Function getData() As Variant Dim results As Variant results = this.Data If Solved Then results(1, 1) = Nodes(1).Value(1) results(1, 3) = Nodes(2).Value(1) results(1, 5) = Nodes(3).Value(1) results(3, 1) = Nodes(4).Value(1) results(3, 3) = Nodes(5).Value(1) results(3, 5) = Nodes(6).Value(1) results(5, 1) = Nodes(7).Value(1) results(5, 3) = Nodes(8).Value(1) results(5, 5) = Nodes(9).Value(1) End If getData = results End Function Public Sub Init(Data As Variant) this.Data = Data this.Solved = False InitEquations Equations(1).Init CStr(Data(1, 2)), CStr(Data(1, 4)), CLng(Data(1, 7)) Equations(2).Init CStr(Data(3, 2)), CStr(Data(3, 4)), CLng(Data(3, 7)) Equations(3).Init CStr(Data(5, 2)), CStr(Data(5, 4)), CLng(Data(5, 7)) Equations(4).Init CStr(Data(2, 1)), CStr(Data(4, 1)), CLng(Data(7, 1)) Equations(5).Init CStr(Data(2, 3)), CStr(Data(4, 3)), CLng(Data(7, 3)) Equations(6).Init CStr(Data(2, 5)), CStr(Data(4, 5)), CLng(Data(7, 5)) With Equations(1) Set .Node1 = Nodes(1) Set .Node2 = Nodes(2) Set .Node3 = Nodes(3) End With With Equations(2) Set .Node1 = Nodes(4) Set .Node2 = Nodes(5) Set .Node3 = Nodes(6) End With With Equations(3) Set .Node1 = Nodes(7) Set .Node2 = Nodes(8) Set .Node3 = Nodes(9) End With With Equations(4) Set .Node1 = Nodes(1) Set .Node2 = Nodes(4) Set .Node3 = Nodes(7) End With With Equations(5) Set .Node1 = Nodes(2) Set .Node2 = Nodes(5) Set .Node3 = Nodes(8) End With With Equations(6) Set .Node1 = Nodes(3) Set .Node2 = Nodes(6) Set .Node3 = Nodes(9) End With End Sub Private Sub InitEquations() Dim n As Long For n = 1 To 6 Set Equations(n) = New Equation Next End Sub Private Sub RemoveCompletedNumbers() Dim item1 As Variant, item2 As Variant For Each item1 In Nodes If item1.Count = 1 And item1.Dirty Then item1.Dirty = False For Each item2 In Nodes If Not item1 Is item2 Then item2.Remove item1.Value(1) End If Next End If Next End Sub Public Sub Restore() Dim n As Long For n = 1 To 9 Nodes(n).Restore Next End Sub Public Sub Save() Dim n As Long For n = 1 To 9 Nodes(n).Save Next End Sub Public Function Solved() As Boolean Dim n As Long Dim dups As New Collection For n = 1 To 9 If Nodes(n).Count &gt; 1 Then Exit Function On Error Resume Next dups.Add 0, CStr(Nodes(n).Value(1)) If Err.Number &lt;&gt; 0 Then Exit Function End If On Error GoTo 0 Next Solved = True End Function Public Function ToString() As String Dim results(1 To 6) As String For n = 1 To 6 results(n) = Equations(n).ToString Next ToString = Join(results, vbNewLine) End Function </code></pre> <p>Module: TestMod</p> <pre><code>Attribute VB_Name = "TestMod" Option Explicit Const BaseRange As String = "A1:G7", ValueRange As String = "A1,C1,E1,A3,C3,E3,A5,C5,E5" Sub TestCrossSum() ' C2, L2, U2, AD2, AM2, AV2, C11, L11, U11, AD11, AM11, AV11 Dim t As Double: t = Timer TestSolver Range("C2") 'TestSolver Range("U11") Debug.Print Round(Timer - t, 2) End Sub Sub TestAll() Application.ScreenUpdating = False Dim t As Double: t = Timer With ThisWorkbook.Worksheets("Cross Sums") Dim r As Long, c As Long For r = 1 To 2 For c = 1 To 6 TestSolver .Cells(r * 9 - 7, c * 9 - 6) Next Next End With Debug.Print Round(Timer - t, 2) End Sub Sub TestSolver(TopLeftCell As Range) Dim Solver As New Solver, Header As Range, Target As Range Set Target = TopLeftCell.Range(BaseRange) Set Header = Target.Offset(-1).Resize(1, 1) Target.Range(ValueRange).ClearContents Header.Value = "" Solver.Init Target.Value Solver.Calculate If Solver.Solved Then Header.Value = "Normal" Else Solver.ApplyBruteForce If Solver.Solved Then Header.Value = "Hard" End If If Solver.Solved Then Target.Value = Solver.getData Else Debug.Print Target.Address Debug.Print Solver.ToString End If End Sub </code></pre> <hr> <p>I'm interested in any problem that might stump the Solver, a Cross Sum Generator if anyone cares to write one, any ideas on how to write a better Solver, and as always any tips on how to improve my code.</p> <p><a href="https://www.dropbox.com/s/y3dexnaahclg261/cross%20sum%20solver.xlsm?dl=0" rel="nofollow noreferrer">Cross Sum Solver.xlsm Download</a></p>
[]
[ { "body": "<p>Some quick comments. This reminds me of over 10 years ago when I was thinking of a solver for Soduku in VB6 (which I never finished writing because I always have trouble with interfaces/user forms)</p>\n\n<h2>Class Node</h2>\n\n<p>Why not use a <code>Collection</code> instead of arrays for <code>numbers</code> and <code>passed</code>. This will clean up (i.e. remove) the <code>ReDim</code> work. I think the refactoring that you would end up doing by this approach will make the <code>Node</code> class simpler and cleaner. Oh, and you can then use `For Each'.</p>\n\n<p>You could also have property for <code>Solved</code> so that you return a single value instead of doing collection processing when you have actually solved this node.</p>\n\n<h2>Class Equation</h2>\n\n<p>You use <code>Public</code> Members instead of <code>Properties Set</code> and <code>Get</code>. I remember somewhere in all my OOP reading that this is a bad thing (tm) to do. Probably because if you want to tweak or do some data validation you can't. </p>\n\n<p>You could check to see if a <code>Node</code> has been solved. This will enable shortcutting to solving the second <code>Node</code>. This means that you can start using Boolean logic instead of counting each time you want to check something. Probably not much difference in performance, but the programming logic is a lot clearer. Which, in turn means this would be easier to maintain. </p>\n\n<p>Why not pass the nodes in with the initial <code>Init</code>? Then nodes are not going to change address or location. This, coupled with a <code>Property Get</code> means that you are less likely to overwrite a <code>Node</code> with a new location.</p>\n\n<p>Make your life a little easier and add a public <code>Evaluate</code> function that takes three parameters. It can return a Boolean, either the inputs evaluate to the answer, or they don't. This would be used primarily by the Brute Force solver.</p>\n\n<p>Under the subroutine <code>Calculate</code> to declare <code>n1</code>, <code>n2</code> and <code>n3</code>. You even assign them a value. But then don't use that value.</p>\n\n<h2>Class Solver</h2>\n\n<p>As noted under <code>Equation</code>, passing the relevant nodes in as part of the <code>Equation.Init</code> would be cleaner.</p>\n\n<p>Using <code>Collection</code>s under the <code>Nodes</code> would make the brute force approach cleaner. </p>\n\n<p>Brute force could be made a little easier by have the other <code>Evaluate</code> function in the <code>Equation</code> class.</p>\n\n<p>I am not sure of your logic here. While a selection of 3 numbers may solve the equation, there may be multiple triplets. I haven't walked myself through the logic in detail here (I did say quick comments) but intuitively, I think this may shortcut the checking and may produce some wrong results. I don't see a way to walk back a series of calculations if there is found to be a conflicting set.</p>\n\n<h2>General</h2>\n\n<p>I don't see any validation of inputs - what if a range of 8 cells are passed?\nI have already mentioned the use of <code>Public</code> members instead of <code>Property</code>s\nSome of your <code>Sub</code>s can be <code>Function</code>s and form a double duty. For example, the subroutine <code>Calculate</code> could return a Boolean that represents <code>Dirty</code>. This approach will allow you to get rid of a \"global\" variable. Thinking this way allows you to chain your code logic into a logical process. A good and visible process should help with code readability.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T06:20:51.143", "Id": "402224", "Score": "0", "body": "I don't think that I have ever had a better review of my code. Your check is in the mail overnight express...lol." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T06:38:57.283", "Id": "402225", "Score": "0", "body": "Just a couple of thoughts. I intentionally used arrays because I use Dictionaries in some much of my code. I was regretting it towards the end. I thought about using `Properties`. I noticed that Matt used them often in Batteship. I didn't link the Nodes in `Equation.Init` because of time restraints. I felt that the current setup would allow me to make all the correct links without mistakes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T06:45:16.407", "Id": "402226", "Score": "0", "body": "I think that shortcutting when a single Node is solved is counter-productive because the number lists of the other 2 Nodes in the equations will still need to be solved. Solving node1 might cause nodes 2 and 3 to solved. In this case, 3 numbers can be excluded from all the other nodes at once. This will greatly reduce the number of operations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T06:50:50.497", "Id": "402227", "Score": "0", "body": "Adding Solved to the Nodes and having brute force methods for each Equation is very interesting. I would like to roll-up Solved, Calculate and ApplyBruteForce into a single method. I didn't do it because I wasn't sure how long that it would take to apply brute force." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T06:57:03.193", "Id": "402228", "Score": "0", "body": "Sorry if my random thought comments are annoying. I will definitely apply most of your tips to my rewrite. I'm thinking about writing a really solid Solver and than rewriting it in a different programming language each week as a challenge. If nothing out it would keep me from spewing code all over the VBA tag. Thanks again for your time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T19:21:17.403", "Id": "402334", "Score": "0", "body": "Np with the random thoughts - \"talking to the bear\" or \"rubber ducking\"! Glad I could help." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T05:44:25.173", "Id": "208265", "ParentId": "208254", "Score": "2" } } ]
{ "AcceptedAnswerId": "208265", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T22:48:16.103", "Id": "208254", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "OOP Cross Sum Solver" }
208254
<p>I am currently coding a PHP script that connects to a database and inserts a phone number and IP address if either item is not present in the table. I believe I have completed it and it is working but I want to make sure that I have used best practices in regards to security. I have read <a href="https://www.w3schools.com/php/php_mysql_prepared_statements.asp" rel="nofollow noreferrer">here</a> about how to connect to MySQL and query it using a PDO and a prepared statement. I also read on Stack Overflow that had a fantastic explanation on how to do this. However, this is now a few years old.</p> <p>I would like to know if my code follows current best practices and that it is secure against SQL injection.</p> <pre><code>if( isset($_POST['submit'])) { //user data $name = $_REQUEST['fullname']; $numbers = $_REQUEST['number']; $bedrooms = $_REQUEST['bedrooms']; $date = $_REQUEST['date']; $movingFrom = $_REQUEST['from-postcode']; $movingTo = $_REQUEST['to-postcode']; $typeOfJob = $_REQUEST['typeOfJob']; $additionalInfo= $_REQUEST['message']; $ip = $_SERVER['REMOTE_ADDR']; $id= NULL; //connection variables $host='localhost'; $user='root'; $pass=''; $db='lookup'; $chset='utf8mb4'; $dns = "mysql:dbname=$db;host=$host;charset=$chset"; $options = [ PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE =&gt; PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES =&gt; false, ]; try { //Try to create a new PDO object and pass the vars $connection = new PDO($dns, $user, $pass, $options); //prepare the database for data and exectue $stmt = $connection-&gt;prepare("SELECT id, numbers, ip FROM numbers"); $stmt-&gt;execute(); //Loop through table and check for numbers and ips //If present set var to true and break from loop $present = false; foreach ($stmt-&gt;fetchAll() as $k=&gt;$v) { if($v['ip'] == $ip or $v['numbers'] == $numbers) $present = true; break; } //If data present I will be redirecting and informing user if($present) { //TODO: send to different pages echo "present"; } //Else insert the data into the table else { $sql = "INSERT INTO numbers (id, numbers, ip) VALUES (NULL, '$numbers', '$ip')" ; $stmt = $connection-&gt;prepare($sql); $stmt-&gt;bindParam(':id', $id); $stmt-&gt;bindParam(':numbers', $numbers); $stmt-&gt;bindParam(':ip', $ip); $stmt-&gt;execute(); echo "Woohoo"; } } catch (PDOException $e) { echo 'Caught exception: ', $e-&gt;getMessage(), "\n"; } </code></pre> <p>There is more code in the <code>if</code> statement but it is irrelevant here as it is for the HTML.</p>
[]
[ { "body": "<ul>\n<li><p>Obey PSR coding standards.  As a starting point, use proper indentation and spacing.  Here's a place to begin your research: <a href=\"https://www.php-fig.org/psr/psr-2/\" rel=\"nofollow noreferrer\">https://www.php-fig.org/psr/psr-2/</a></p></li>\n<li><p>If you haven't already, narrow how your incoming submitted data is delivered to your script.  If you expect your user's data to be coming from a form with  <code>method=POST</code>, then use <code>$_POST</code> instead of <code>$_REQUEST</code>.  This will reduce the points of data entry and make your coding intention clearer to future human readers of your script.</p></li>\n<li><p>Variable naming is important! If you have incoming data that holds a \"phone number\", use a variable name that will never lead to confusion.  <code>phone_number</code>, <code>phone</code>, or <code>mobile_phone</code>, etc might be better choices than <code>$numbers</code> which comes from <code>$_REQUEST[\"number\"]</code>. Truth be told, I don't know if the incoming data is a phone numbet, a serial number, or a chemical that makes things <em>numb</em>. What probably concerns me more than the term is the sudden change from singular to plural.  Is this data an array of numbers? I have to assume not based on the script to follow, but then why use a plural variable name.</p></li>\n<li><p>I wanted to recommend some investigation into the possibility of using an autoincremented primary id with two unique columns, <a href=\"https://stackoverflow.com/q/5416548/2943403\">https://stackoverflow.com/q/5416548/2943403</a> but there seems to be some debate about stability and suitable environments.  Furthermore, I don't want to make any incorrect assumptions about your coding logic.  Ultimately, I always encourage developers to seek solutions that execute the least number of calls to the database.  If this script can be done by sending one INSERT query and processing the response, that would get a nod from me.</p></li>\n<li><p>Because you are hunting for a specific <code>id</code> value and a specific <code>numbers</code> value, write those conditions directly into your SELECT query's WHERE clause.  This with speed up your processing, eliminate your <code>break</code> requirement, and simply make your code more direct / intuitive.</p></li>\n<li><p>Since the purpose of your SELECT query is to determine if an id or number exists, you can write your SELECT clause depending on the response quality that you intend to deliver to the end user. 1. If you don't intend to inform the user about which value already exists in the database table, use <code>COUNT(*)</code>. 2. If you are going to explain which value already exists, <code>SELECT id, numbers</code> with a LIMIT of 1.</p></li>\n<li><p>Rather than extracting the full result set then feeding it to the <code>foreach()</code>, I recommend fetching as you iterate.  <a href=\"https://stackoverflow.com/a/12970800/2943403\">https://stackoverflow.com/a/12970800/2943403</a> That said, I think your code should only be processing a single row of data at most.</p></li>\n<li><p>You could improve your variable naming in your loop.  <code>$k</code> actually represents the \"index\" of the current row in the result set, so <code>$i</code> would be meaningful, <code>$index</code> would be more so, but best would be to omit the declaration entirely because you never use it in your script.  <code>$v</code> is the current row's data.  I recommend <code>$row</code>.</p></li>\n<li><p>Try to avoid using boolean flags like <code>$present</code>.  In most cases, after a bit of careful thought, you can redesign your script to <code>break</code> or <code>continue</code> or conditionally call a custom function as a means to avoid this extra declaration.</p></li>\n<li><p>Your INSERT query is not using the prepared statement / named placeholders / binding properly.  <a href=\"http://php.net/manual/en/pdo.prepare.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/pdo.prepare.php</a>  First, I would the <code>id</code> column is to receive a static <code>NULL</code> value -- you don't need a variable for this, just hardcode it directly into the query.  Second, never write variable values into your prepared statement -- see my link to the pdo manual regarding the proper syntax.</p></li>\n<li><p>Finally, never present the raw <code>$e-&gt;getMessage()</code> details to the public.  You may wish to offer generalized feedback but don't give the specifics as a matter of good security practices.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-04T09:54:57.827", "Id": "407642", "Score": "0", "body": "Thank you very much for the time you took to answer my question Mick I will go back through my code and and implement your suggestions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-03T14:20:58.440", "Id": "210817", "ParentId": "208255", "Score": "2" } } ]
{ "AcceptedAnswerId": "210817", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-22T23:33:10.280", "Id": "208255", "Score": "3", "Tags": [ "php", "mysql", "pdo", "sql-injection" ], "Title": "PHP code to insert phone number and IP address into a table if not already present" }
208255
<p>This code seems to work correctly. I would appreciate any comments on how to improve the code, e.g. readability, algorithms, const-correctness, memory, anything else I am forgetting? Also, for the function <code>swap_values</code>, would it make more sense to swap two nodes instead of just values of the nodes and why?</p> <p><strong>SinglyLinkedList.hpp</strong></p> <pre><code>#pragma once #include &lt;iostream&gt; class SinglyLinkedList { private: struct ListNode { int value; std::shared_ptr&lt;ListNode&gt; next; ListNode(int val) : value(val), next(nullptr) {} }; std::shared_ptr&lt;ListNode&gt; head; std::shared_ptr&lt;ListNode&gt; tail; std::shared_ptr&lt;ListNode&gt; find (int val) const; public: SinglyLinkedList(); void print_list () const; void push_back (int val); void pop_back (); void push_front (int val); void pop_front (); size_t get_size () const; bool search (int val) const; void swap_values (int val1, int val2); void remove_nodes (int val); void reverse (); ~SinglyLinkedList(); }; </code></pre> <p><strong>SinglyLinkedList.cpp</strong></p> <pre><code>#include "SinglyLinkedList.hpp" SinglyLinkedList::SinglyLinkedList () : head (nullptr), tail (nullptr) { } void SinglyLinkedList::print_list () const { // O(n) if (head) { std::shared_ptr&lt;ListNode&gt; tempNode = head; while (tempNode) { std::cout &lt;&lt; tempNode-&gt;value &lt;&lt; " "; tempNode = tempNode-&gt;next; } std::cout &lt;&lt; "\n"; } else { std::cout &lt;&lt; "List is empty.\n"; } } void SinglyLinkedList::push_back(int val) { // O(n) std::shared_ptr&lt;ListNode&gt; currNode = std::make_shared&lt;ListNode&gt;(val); if (head) { std::shared_ptr&lt;ListNode&gt; tempNode = head; while (tempNode != tail) { tempNode = tempNode-&gt;next; } tempNode-&gt;next = currNode; tail = currNode; } else { head = currNode; tail = currNode; } } void SinglyLinkedList::pop_back () { // O(n) if (!head) { std::cout &lt;&lt; "List is empty.\n"; return; } if (head == tail) { head = nullptr; tail = nullptr; return; } std::shared_ptr&lt;ListNode&gt; currNode = head; while (currNode-&gt;next != tail) { currNode = currNode-&gt;next; } tail = currNode; currNode-&gt;next = nullptr; } void SinglyLinkedList::push_front (int val) { // O(1) std::shared_ptr&lt;ListNode&gt; currNode = std::make_shared&lt;ListNode&gt;(val); currNode-&gt;next = head; head = currNode; } void SinglyLinkedList::pop_front () { // O(1) if (!head) { std::cout &lt;&lt; "List is empty.\n"; return; } std::shared_ptr&lt;ListNode&gt; currNode = head; head = head-&gt;next; currNode-&gt;next = nullptr; } size_t SinglyLinkedList::get_size () const { // O(n) size_t listSize = 0; std::shared_ptr&lt;ListNode&gt; currNode = head; while (currNode) { ++listSize; currNode = currNode-&gt;next; } return listSize; } bool SinglyLinkedList::search (int val) const { // O(n) if (!head) { std::cout &lt;&lt; "List is empty.\n"; return false; } std::shared_ptr&lt;ListNode&gt; currNode = head; while (currNode) { if (currNode-&gt;value == val) { //std::cout &lt;&lt; "Value " &lt;&lt; val &lt;&lt; " is in the list\n"; return true; } currNode = currNode-&gt;next; } //std::cout &lt;&lt; "Value " &lt;&lt; val &lt;&lt; " is not in the list.\n"; return false; } std::shared_ptr&lt;SinglyLinkedList::ListNode&gt; SinglyLinkedList::find (int val) const { // O(n) if (!head) { return nullptr; } std::shared_ptr&lt;ListNode&gt; currNode = head; while (currNode) { if (currNode-&gt;value == val) { return currNode; } currNode = currNode-&gt;next; } return nullptr; } void SinglyLinkedList::swap_values (int val1, int val2) { // swap is O(1), find is O(n) // Should I be swapping nodes instead of values? std::shared_ptr&lt;ListNode&gt; val1Node = find (val1); std::shared_ptr&lt;ListNode&gt; val2Node = find (val2); if (!val1Node) { std::cout &lt;&lt; "Value " &lt;&lt; val1 &lt;&lt; " is not in the list.\n"; return; } if (!val2Node) { std::cout &lt;&lt; "Value " &lt;&lt; val2 &lt;&lt; " is not in the list.\n"; return; } int tempNodeVal = val1Node-&gt;value; val1Node-&gt;value = val2Node-&gt;value; val2Node-&gt;value = tempNodeVal; } void SinglyLinkedList::remove_nodes (int val) { if (!head) { std::cout &lt;&lt; "List is empty.\n"; return; } std::shared_ptr&lt;ListNode&gt; prevNode = nullptr; std::shared_ptr&lt;ListNode&gt; currNode = head; while (currNode) { if (currNode-&gt;value == val) { // val found - remove if (!prevNode) { // delete head node if (head == tail) { head = nullptr; tail = nullptr; return; } head = head-&gt;next; prevNode = currNode; currNode = currNode-&gt;next; prevNode-&gt;next = nullptr; prevNode = nullptr; } else if (currNode == tail) { // delete tail node tail = prevNode; prevNode-&gt;next = nullptr; currNode-&gt;next = nullptr; } else { prevNode-&gt;next = currNode-&gt;next; currNode-&gt;next = nullptr; currNode = prevNode-&gt;next; } } else { // val not found prevNode = currNode; currNode = currNode-&gt;next; } } } void SinglyLinkedList::reverse () { // O(n) if (!head || head == tail) { return; } std::shared_ptr&lt;ListNode&gt; currNode = head; std::shared_ptr&lt;ListNode&gt; prevNode = nullptr; std::shared_ptr&lt;ListNode&gt; nextNode = nullptr; head = nullptr; tail = head; while (currNode) { nextNode = currNode-&gt;next; currNode-&gt;next = prevNode; prevNode = currNode; currNode = nextNode; } head = prevNode; } SinglyLinkedList::~SinglyLinkedList () { } </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include "SinglyLinkedList.hpp" int main() { // List init SinglyLinkedList myList; std::cout &lt;&lt; "Print list: \n"; myList.print_list(); std::cout &lt;&lt; "List size: " &lt;&lt; myList.get_size() &lt;&lt; "\n"; // Add nodes to the back of the list myList.push_back(2); myList.push_back(4); myList.push_back(3); myList.push_back(1); std::cout &lt;&lt; "Print list: \n"; myList.print_list(); std::cout &lt;&lt; "List size: " &lt;&lt; myList.get_size() &lt;&lt; "\n"; // Add nodes to the front of the list myList.push_front(5); myList.push_front(7); myList.push_front(6); std::cout &lt;&lt; "Print list: \n"; myList.print_list(); std::cout &lt;&lt; "List size: " &lt;&lt; myList.get_size() &lt;&lt; "\n"; // Pop nodes from the front of the list myList.pop_front(); myList.pop_front(); std::cout &lt;&lt; "Print list: \n"; myList.print_list(); std::cout &lt;&lt; "List size: " &lt;&lt; myList.get_size() &lt;&lt; "\n"; // Pop nodes from the back of the list myList.pop_back(); myList.pop_back(); std::cout &lt;&lt; "Print list: \n"; myList.print_list(); std::cout &lt;&lt; "List size: " &lt;&lt; myList.get_size() &lt;&lt; "\n"; // Check if node with specific velue is in the list int valToSearch = 3; bool foundVal = myList.search(valToSearch); if (foundVal) { std::cout &lt;&lt; valToSearch &lt;&lt; " is in the list.\n"; } else { std::cout &lt;&lt; valToSearch &lt;&lt; " is not in the list.\n"; } // Swap the values of two nodes myList.push_back(7); myList.push_back(8); myList.push_back(9); myList.print_list(); myList.swap_values(9, 2); std::cout &lt;&lt; "Print list: \n"; myList.print_list(); // Remove nodes from the list myList.push_back(9); myList.push_back(3); myList.push_back(9); myList.print_list(); myList.remove_nodes(5); myList.remove_nodes(9); myList.remove_nodes(4); std::cout &lt;&lt; "Print list: \n"; myList.print_list(); // Reverse the list myList.push_back(9); myList.push_back(3); myList.push_back(9); myList.print_list(); myList.reverse(); std::cout &lt;&lt; "Print list: \n"; myList.print_list(); } </code></pre>
[]
[ { "body": "<h1>About the interface</h1>\n<pre><code>#pragma once\n</code></pre>\n<p><code>#pragma once</code> isn't standard, prefer include guards if you want to maximize portability</p>\n<pre><code>#include &lt;iostream&gt;\n\nclass SinglyLinkedList {\n \nprivate:\n struct ListNode {\n int value;\n std::shared_ptr&lt;ListNode&gt; next;\n \n</code></pre>\n<p>Why a <code>shared_ptr</code>? You don't expose the nodes. I don't see why each node wouldn't be the only\none responsible for its <code>next</code> node.</p>\n<pre><code> ListNode(int val) : value(val), next(nullptr) {}\n</code></pre>\n<p>Are you certain that automatically generated copy operator, assignment operator, destructor are fine?\nBecause I don't: at least the destructor will cause issues if the list is too long, because it will trigger\nrecursively until stack-overflow</p>\n<pre><code>};\n\nstd::shared_ptr&lt;ListNode&gt; head;\nstd::shared_ptr&lt;ListNode&gt; tail;\nstd::shared_ptr&lt;ListNode&gt; find (int val) const;\n\npublic:\n SinglyLinkedList();\n\n void print_list () const;\n</code></pre>\n<p>print shouldn't be a member function. There's too many ways to print a list:\n<code>[1, 2, 3, 4]</code>, <code>(1 2 3 4)</code>, <code>[1 2 3 4]</code> which are equally fine.\nThat's why you should rather provide a way to access members, and let the user choose the format</p>\n<pre><code>void push_back (int val);\nvoid pop_back ();\nvoid push_front (int val);\nvoid pop_front ();\n</code></pre>\n<p>Strangely you don't allow access to the values in the list. I would expect a <code>int back()</code>\nand <code>int front()</code> at the very least</p>\n<pre><code>size_t get_size () const;\n</code></pre>\n<p>Same here for those functions, which are mostly orthogonal to the list class: you could search, swap, reverse, the list\nif you had access to its elements. <code>remove_nodes</code> indeed needs to rely on a primitive in the class interface, but can't replace\nit: what if I only want to remove the first / last / duplicated nodes with that value?</p>\n<pre><code>bool search (int val) const;\nvoid swap_values (int val1, int val2);\nvoid remove_nodes (int val);\nvoid reverse ();\n\n~SinglyLinkedList();\n</code></pre>\n<p>};</p>\n<h1>About the implementation:</h1>\n<pre><code>#include &quot;SinglyLinkedList.hpp&quot;\n\n\nSinglyLinkedList::SinglyLinkedList () : head (nullptr), tail (nullptr) {\n}\n</code></pre>\n<p>You could have inlined this constructor in the header file, your class'd be easier to read</p>\n<pre><code>void SinglyLinkedList::print_list () const {\n // O(n)\n if (head) {\n std::shared_ptr&lt;ListNode&gt; tempNode = head;\n \n</code></pre>\n<p><code>std::shared_ptr</code> should be used when something is co-owned by two objects whose life-times aren't correlated.\nIt is impossible here that tempNode would outlive head. I really believe a <code>unique_ptr</code> for ownership, and a raw pointer\nobtained by <code>get()</code> for traversal is the way to go</p>\n<pre><code> while (tempNode) {\n std::cout &lt;&lt; tempNode-&gt;value &lt;&lt; &quot; &quot;;\n tempNode = tempNode-&gt;next;\n }\n std::cout &lt;&lt; &quot;\\n&quot;;\n} else {\n std::cout &lt;&lt; &quot;List is empty.\\n&quot;;\n}\n</code></pre>\n<p>This is very rigid. There are a lot of contexts where I don't want a new line, or, worse, a &quot;empty list message&quot;!</p>\n<p>}</p>\n<pre><code>void SinglyLinkedList::push_back(int val) {\n // O(n)\n \n</code></pre>\n<p>since you maintain a <code>head</code> pointer in your class, you should make use of it to <code>push_back</code> (with O(1) complexity), or dispense with it altogether.</p>\n<pre><code> std::shared_ptr&lt;ListNode&gt; currNode = std::make_shared&lt;ListNode&gt;(val);\n if (head) {\n std::shared_ptr&lt;ListNode&gt; tempNode = head;\n while (tempNode != tail) {\n tempNode = tempNode-&gt;next;\n }\n tempNode-&gt;next = currNode;\n tail = currNode;\n } else {\n head = currNode;\n tail = currNode;\n }\n}\n\nvoid SinglyLinkedList::pop_back () {\n // O(n)\n if (!head) {\n std::cout &lt;&lt; &quot;List is empty.\\n&quot;;\n \n</code></pre>\n<p>There are many ways to deal with incorrect manipulations, but writing to <code>std::cout</code>\nisn't one of them. Writing to <code>std::clog</code> or <code>std::cerr</code> would be a beginning, but you primarily need to\nprovide a feed-back mechanism: either an exception, or a return value indicating success / failure</p>\n<pre><code> return;\n}\nif (head == tail) {\n head = nullptr;\n tail = nullptr;\n return;\n}\nstd::shared_ptr&lt;ListNode&gt; currNode = head;\nwhile (currNode-&gt;next != tail) {\n currNode = currNode-&gt;next;\n}\ntail = currNode;\n</code></pre>\n<p>This traversal already appeared twice in your code. It should be encapsulated in its own function</p>\n<pre><code> currNode-&gt;next = nullptr;\n}\n\nvoid SinglyLinkedList::push_front (int val) {\n // O(1)\n std::shared_ptr&lt;ListNode&gt; currNode = std::make_shared&lt;ListNode&gt;(val);\n currNode-&gt;next = head;\n head = currNode;\n</code></pre>\n<p>There is an <code>std::exchange</code> function in the stl which makes it a one-liner:\n<code>currNode-&gt;next = std::exchange(head, currNode)</code>;</p>\n<pre><code>}\n\nvoid SinglyLinkedList::pop_front () {\n // O(1)\n if (!head) {\n std::cout &lt;&lt; &quot;List is empty.\\n&quot;;\n return;\n }\n std::shared_ptr&lt;ListNode&gt; currNode = head;\n head = head-&gt;next;\n currNode-&gt;next = nullptr;\n}\n\nsize_t SinglyLinkedList::get_size () const {\n // O(n)\n \n</code></pre>\n<p>You should consider maintaining a size counter to make it <code>O(1)</code>, because it's tipically how it's done\nand clients wouldn't expect <code>O(n)</code> complexity</p>\n<pre><code> size_t listSize = 0;\n std::shared_ptr&lt;ListNode&gt; currNode = head;\n while (currNode) {\n ++listSize;\n currNode = currNode-&gt;next;\n }\n\n return listSize;\n}\n\nbool SinglyLinkedList::search (int val) const {\n // O(n)\n if (!head) {\n std::cout &lt;&lt; &quot;List is empty.\\n&quot;;\n \n</code></pre>\n<p>Why print anything? It isn't like it's an error to search an empty list. Simply return false</p>\n<pre><code> return false;\n}\nstd::shared_ptr&lt;ListNode&gt; currNode = head;\nwhile (currNode) {\n if (currNode-&gt;value == val) {\n //std::cout &lt;&lt; &quot;Value &quot; &lt;&lt; val &lt;&lt; &quot; is in the list\\n&quot;;\n</code></pre>\n<p>It's best to eliminate remnants of debugging altogether.</p>\n<pre><code> return true;\n }\n currNode = currNode-&gt;next;\n }\n //std::cout &lt;&lt; &quot;Value &quot; &lt;&lt; val &lt;&lt; &quot; is not in the list.\\n&quot;;\n return false;\n}\n\nstd::shared_ptr&lt;SinglyLinkedList::ListNode&gt; SinglyLinkedList::find (int val) const {\n // O(n)\n if (!head) {\n return nullptr;\n }\n std::shared_ptr&lt;ListNode&gt; currNode = head;\n while (currNode) {\n if (currNode-&gt;value == val) {\n return currNode;\n }\n currNode = currNode-&gt;next;\n } \n return nullptr;\n}\n\nvoid SinglyLinkedList::swap_values (int val1, int val2) {\n // swap is O(1), find is O(n)\n // Should I be swapping nodes instead of values?\n</code></pre>\n<p>Indeed you should. That's an example of disputable design: you now have the burden of error management (checks + reports)\nIt would have been better to make find public, with a slightly different interface (an iterator, eg: a non-owning pointer)\nand then let the user invoke <code>std::iter_swap</code></p>\n<pre><code> std::shared_ptr&lt;ListNode&gt; val1Node = find (val1);\n std::shared_ptr&lt;ListNode&gt; val2Node = find (val2);\n\n if (!val1Node) {\n std::cout &lt;&lt; &quot;Value &quot; &lt;&lt; val1 &lt;&lt; &quot; is not in the list.\\n&quot;;\n return;\n }\n if (!val2Node) {\n std::cout &lt;&lt; &quot;Value &quot; &lt;&lt; val2 &lt;&lt; &quot; is not in the list.\\n&quot;;\n return;\n }\n\n int tempNodeVal = val1Node-&gt;value;\n val1Node-&gt;value = val2Node-&gt;value;\n val2Node-&gt;value = tempNodeVal;\n}\n\nvoid SinglyLinkedList::remove_nodes (int val) {\n if (!head) {\n std::cout &lt;&lt; &quot;List is empty.\\n&quot;;\n \nSo what? That's not an error. \n \n return;\n }\n std::shared_ptr&lt;ListNode&gt; prevNode = nullptr;\n std::shared_ptr&lt;ListNode&gt; currNode = head;\n while (currNode) {\n if (currNode-&gt;value == val) {\n \n</code></pre>\n<p>I thought your <code>find</code> member function was written precisely to find a node with the given value, why don't you use it?</p>\n<pre><code> // val found - remove\n if (!prevNode) {\n // delete head node\n if (head == tail) {\n head = nullptr;\n tail = nullptr;\n return;\n }\n head = head-&gt;next;\n prevNode = currNode;\n currNode = currNode-&gt;next;\n prevNode-&gt;next = nullptr;\n prevNode = nullptr;\n } else if (currNode == tail) {\n // delete tail node\n tail = prevNode;\n prevNode-&gt;next = nullptr;\n currNode-&gt;next = nullptr;\n } else {\n prevNode-&gt;next = currNode-&gt;next;\n currNode-&gt;next = nullptr;\n currNode = prevNode-&gt;next;\n }\n \n</code></pre>\n<p>That seems very complicated. I'm almost certain that you can find a more concise way to express it</p>\n<pre><code> } else {\n // val not found\n prevNode = currNode;\n currNode = currNode-&gt;next;\n }\n }\n }\n\nvoid SinglyLinkedList::reverse () {\n // O(n)\n if (!head || head == tail) {\n return;\n }\n std::shared_ptr&lt;ListNode&gt; currNode = head;\n std::shared_ptr&lt;ListNode&gt; prevNode = nullptr;\n std::shared_ptr&lt;ListNode&gt; nextNode = nullptr;\n head = nullptr;\n tail = head;\n while (currNode) {\n nextNode = currNode-&gt;next;\n currNode-&gt;next = prevNode;\n prevNode = currNode;\n currNode = nextNode;\n }\n head = prevNode;\n}\n\nSinglyLinkedList::~SinglyLinkedList () {\n</code></pre>\n<p>If you leave it empty, consider to declare it <code>=default</code> in your interface. But here you need to define your implementation,\nsince default behavior will result in a stack overflow for large lists</p>\n<pre><code>}\n</code></pre>\n<h1>Conclusion:</h1>\n<p>You're on the right track to write good code. But you should study the standard library to get a better idea of how to design a C++ container: container/algorithm orthogonality, iterators, etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T02:26:54.433", "Id": "402352", "Score": "0", "body": "Thank you, this is very helpful, I've been implementing your suggestions today. One thing I don't quite get is this:\n\"I really believe a unique_ptr for ownership, and a raw pointer obtained by get() for traversal is the way to go\"\nCould you suggest some example code where this is done?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T04:11:14.107", "Id": "402353", "Score": "0", "body": "Ok, I think I got it. So, I declare `std::unique_ptr<ListNode> head;` and then for traversal I use `ListNode* tempNode = head.get();` and `tempNode = tempNode->next.get();`. Is this correct? Do I need to `delete tempNode;` in the end of the function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T15:45:30.513", "Id": "402407", "Score": "1", "body": "@user_185051: no need to delete a raw pointer!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T10:19:14.327", "Id": "208274", "ParentId": "208260", "Score": "6" } }, { "body": "<p>Expanding on papagaga's answer</p>\n\n<hr>\n\n<pre><code>#include &lt;iostream&gt;\n</code></pre>\n\n<p>Be aware that many of the C++ implementations currently transparently inject a static constructor into ever translation unit that includes <code>&lt;iostream&gt;</code>. My advice, drop any support for <code>&lt;iostream&gt;</code> or split it into its own IO utility class.</p>\n\n<hr>\n\n<pre><code> struct ListNode {\n int value;\n std::shared_ptr&lt;ListNode&gt; next;\n ListNode(int val) : value(val), next(nullptr) {}\n };\n</code></pre>\n\n<p>Why name this <code>ListNode</code>? It's already (privately) encapsulated by <code>SinglyLinkedList</code>. Perhaps just call it <code>Node</code>?</p>\n\n<p>When you have constants, you can use in-class member initialization.</p>\n\n<pre><code> std::shared_ptr&lt;ListNode&gt; next = nullptr;\n ListNode(int val) : value(val) {}\n</code></pre>\n\n<p>Why <code>std::shared_ptr</code>? Take some time and watch <a href=\"https://www.youtube.com/watch?v=JfmTagWcqoE\" rel=\"nofollow noreferrer\">Herb Sutter's talk from CppCon 2016: Leak-Freedom in C++... By Default</a>.</p>\n\n<p>Papagaga touched on this, but it really needs emphasis. Anytime you are dealing with ownership, you need to keep in mind how the default-generated special member functions operate in that context. The <a href=\"https://cpppatterns.com/patterns/rule-of-five.html\" rel=\"nofollow noreferrer\">rule of three/five</a> is very important. See <a href=\"https://www.youtube.com/watch?v=IzQk6IM74JE\" rel=\"nofollow noreferrer\">Quuxplusone's talk from CppNow 2016: The Rule of Seven (Plus or Minus Two)</a>.</p>\n\n<p>You should include <code>&lt;memory&gt;</code> for <code>std::shared_ptr&lt;&gt;</code>.</p>\n\n<hr>\n\n<pre><code> std::shared_ptr&lt;ListNode&gt; head;\n std::shared_ptr&lt;ListNode&gt; tail;\n\n SinglyLinkedList();\n\nSinglyLinkedList::SinglyLinkedList () : head (nullptr), tail (nullptr) {\n}\n</code></pre>\n\n<p>If you can avoid using defining the special member functions, then do so. Use in-class member initializers here.</p>\n\n<pre><code> std::shared_ptr&lt;ListNode&gt; head = nullptr;\n std::shared_ptr&lt;ListNode&gt; tail = nullptr;\n\n SinglyLinkedList();\n\nSinglyLinkedList::SinglyLinkedList () {\n}\n</code></pre>\n\n<p>As long as you never declare any kind of constructor for your class type, the compiler will implicitly declare one for you.</p>\n\n<pre><code> std::shared_ptr&lt;ListNode&gt; head = nullptr;\n std::shared_ptr&lt;ListNode&gt; tail = nullptr;\n\n // Don't need this\n // SinglyLinkedList();\n\n// Or this\n// SinglyLinkedList::SinglyLinkedList () {\n// }\n</code></pre>\n\n<p>If you declare/define any another constructor, the compiler will not implicitly generate the default constructor for you. To unsuppress the implicitly-generated default constructor, you can declare the default constructor with the keyword <code>default</code>.</p>\n\n<pre><code> std::shared_ptr&lt;ListNode&gt; head = nullptr;\n std::shared_ptr&lt;ListNode&gt; tail = nullptr;\n\n SinglyLinkedList() = default;\n\n// Still don't need this...\n// SinglyLinkedList::SinglyLinkedList () {\n// }\n</code></pre>\n\n<p>The same can be done with the destructor...</p>\n\n<pre><code> ~SinglyLinkedList() = default;\n</code></pre>\n\n<p>However, the semantics of the implicitly generated functions are meant to be used with values, not ownership references/pointers. So you will need to provide a definition or hope your list never gets big enough to blow the stack.</p>\n\n<hr>\n\n<pre><code> SinglyLinkedList();\n void print_list () const;\n</code></pre>\n\n<p>Try to be consistent with your spacing. Spaces are great a differentiating between language constructs and functions. You go back and forth between attached and detached parens. Reserve detached parens for the language constructs</p>\n\n<pre><code>for (/*...*/) { }\n\nwhile (/*...*/) { }\n</code></pre>\n\n<p>and attach the parens to your functions.</p>\n\n<pre><code>call(/*...*/) { }\n</code></pre>\n\n<hr>\n\n<pre><code> void push_back (int val);\n void pop_back ();\n void push_front (int val);\n void pop_front ();\n</code></pre>\n\n<p>Do not provide the tail operations as those will be surprising for users who may expect constant time operations. See the <a href=\"https://en.wikipedia.org/wiki/Principle_of_least_astonishment\" rel=\"nofollow noreferrer\">Principle of Least Astonishment</a>.</p>\n\n<hr>\n\n<pre><code> size_t get_size () const;\n</code></pre>\n\n<p>To avoid having to create a customization point to be able to use your container with non-member <code>std::size()</code>, you should name this member function <code>size()</code>.</p>\n\n<p>The C++ standard makes no guarantee that the unqualified <code>size_t</code> will exist. You should qualify your types (<code>std::size_t</code>) and include the library that defines it (<code>&lt;cstddef&gt;</code>). Do not rely on <code>&lt;iostream&gt;</code> to latently include it for you.</p>\n\n<p>If you are not going to provide splicing operations, consider caching the size. Splicing is a constant time operation. If you cache the size, you'll need to recalculate the size on every slice, resulting in a linear-time operation. This is why <code>std::forward_list</code> doesn't have a size member function.</p>\n\n<hr>\n\n<pre><code> void SinglyLinkedList::print_list () const { ... }\n</code></pre>\n\n<p><code>&lt;iostream&gt;</code> provides an unnecessary initialization cost due to the static constructors for those that simply want to store data and not print it to the console. Provide an alternative. Here are a few design patterns to consider:</p>\n\n<ul>\n<li>Iterator - Objects that traverse the container providing direct access to the values.</li>\n<li>Visitor - A function that takes another function (or lambda) and applies each value to that function.</li>\n<li>Adaptor - An IO object that inherits the container, providing functionality for those who want to opt-in at the costs above.</li>\n</ul>\n\n<hr>\n\n<pre><code>void SinglyLinkedList::push_back(int val) { ... }\n</code></pre>\n\n<p>This doesn't need to be <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>. If <code>tail</code> doesn't exist, then neither should <code>head</code>. If <code>tail</code> does exist, then you append your new node to the tail node.</p>\n\n<hr>\n\n<pre><code> // swap is O(1), find is O(n)\n // Should I be swapping nodes instead of values?\n std::shared_ptr&lt;ListNode&gt; val1Node = find (val1);\n std::shared_ptr&lt;ListNode&gt; val2Node = find (val2);\n\n if (!val1Node) {\n std::cout &lt;&lt; \"Value \" &lt;&lt; val1 &lt;&lt; \" is not in the list.\\n\";\n return;\n }\n if (!val2Node) {\n std::cout &lt;&lt; \"Value \" &lt;&lt; val2 &lt;&lt; \" is not in the list.\\n\";\n return;\n }\n\n int tempNodeVal = val1Node-&gt;value;\n val1Node-&gt;value = val2Node-&gt;value;\n val2Node-&gt;value = tempNodeVal;\n</code></pre>\n\n<p>When working with generic types where the size isn't known, it's going to better to swap the links. For this case, why swap? You already have the new values cached in temporaries from the arguments. Just assign them.</p>\n\n<pre><code> std::shared_ptr&lt;ListNode&gt; val1Node = find (val1);\n std::shared_ptr&lt;ListNode&gt; val2Node = find (val2);\n\n if (!val1Node || !val2Node) {\n // indicate that a swap didn't happen?\n return false;\n }\n\n val1Node-&gt;value = val2;\n val2Node-&gt;value = val1;\n return true;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T22:33:00.723", "Id": "403006", "Score": "0", "body": "Thank you so much for the review, I appreciate your input a lot! I have several question regarding thing I didn't understand: 1. I don't really understand your very first comment about <iostream>, could you explain it a bit more or point to a resource, where I can read about it? 2. \"However, the semantics of the implicitly generated functions are meant to be used with values, not ownership references/pointers.\" - this is very interesting and new for me, where can I read more? I don't think I encountered this when reading about destructors in a text book. Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-29T06:54:46.927", "Id": "403062", "Score": "1", "body": "1. It's just knowledge of how the streams are initialized. Read up on static object initialization. 2. See @quuxplusone's [talk](https://www.youtube.com/watch?v=IzQk6IM74JE)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T11:20:15.710", "Id": "208440", "ParentId": "208260", "Score": "4" } }, { "body": "<p>Other answers have most of this covered. But I'd like to add one observation:</p>\n\n<h1>Don't print error messages to <code>std::cout</code></h1>\n\n<p>The standard output stream is for program output. Use <code>std::cerr</code> for error messages; in many cases, the user may be sending standard output to a pipeline or a file, but leave standard error writing to their terminal. In any case, that's the one to watch for error messages.</p>\n\n<p>For a general-purpose utility class like this, you really should consider whether writing a message is the appropriate choice. I recommend you consider throwing exceptions for list underrun or use of other lists' iterators. The calling application can choose whether and how to handle the exception (as it must for <code>std::bad_alloc</code> already).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-29T21:16:44.473", "Id": "208719", "ParentId": "208260", "Score": "3" } } ]
{ "AcceptedAnswerId": "208274", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T04:51:26.387", "Id": "208260", "Score": "6", "Tags": [ "c++", "algorithm", "c++11", "linked-list", "reinventing-the-wheel" ], "Title": "Singly-linked list data structure implementation" }
208260
<p>While translating an old Basic game to C, I found myself needing a function to get one character from the keyboard. You can't do this with common standard C library functions like <code>getchar()</code> because the standard input stream is <a href="https://stackoverflow.com/a/36573506/2644192">line-buffered</a> (i.e. it will store whole line of input, including the terminating <code>\n</code>, in its internal buffer although <code>getchar()</code> only uses its first character. Subsequent calls to <code>getchar()</code> will consume buffer's remaining characters until exhausted and only then will it resume accepting user's new inputs). This causes problems because if you need inputting twice, the second time you will get some unexpected value instead of letting user entering second character.</p> <p>Now, I know the way around this is to use operating system calls such as <a href="https://fr.wikipedia.org/wiki/Ioctl" rel="nofollow noreferrer"><code>ioctl</code></a> and <a href="http://man7.org/linux/man-pages/man2/read.2.html" rel="nofollow noreferrer"><code>read</code></a> to set input to an unbuffered state and read a character (or better yet use a library like <a href="https://en.wikipedia.org/wiki/Curses_(programming_library)" rel="nofollow noreferrer"><code>Curses</code></a> which abstracts away all this in a cross-platform way.) but I started wondering if it was possible to do this entirely via the standard C library.</p> <p>My first attempt was to empty out the remaining characters in <code>stdin</code>'s buffer by adding a call to:</p> <pre><code>fflush(stdin); </code></pre> <p>...after calling <code>getchar()</code> but this didn't do anything.</p> <p>My next attempt was to try and take <code>stdin</code> out of line buffer mode like this:</p> <pre><code>setvbuf(stdin, NULL, _IONBF, 0); </code></pre> <p>I had high hopes this would work but actually it seems calling <code>setvbuf</code> on <code>stdin</code> is undefined behavior. It certainly does not work on Linux.</p> <p>So finally I came up with this function. It works but I have a nagging feeling it could be improved. What do you think?</p> <pre><code>int getkey(const char* prompt = "") { /* Print the prompt message if there is one */ if (strcmp(prompt, "") != 0) { puts(prompt); } /* Get a character and examine it. If it is a newline from a previous call to this function eat it otherwise put it back in the buffer. */ int c = getchar(); if (c != '\n') { ungetc(c, stdin); } /* This is the character we really want. */ c = getchar(); /* Drain the input buffer so any extra characters which were pressed are discarded except for newline which is needed to actually send the input to stdin. */ int next; while(!feof(stdin) &amp;&amp; next != '\n') { next = getchar(); } return c; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T08:42:43.533", "Id": "402238", "Score": "1", "body": "Are you sure it's valid C ?" } ]
[ { "body": "<p>Your <code>strcmp</code> can be replaced with:</p>\n\n<pre><code>if (*prompt) {\n</code></pre>\n\n<p>Your last loop has issues. You effectively have both a precondition (<code>feof</code>) and a postcondition (<code>next</code>). You can replace the lot with:</p>\n\n<pre><code>while (!feof(stdin))\n if (getchar() == '\\n')\n break;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T09:21:54.607", "Id": "402243", "Score": "1", "body": "I'm surprised you didn't mention the UB when `next` is used uninitialized..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T11:27:40.500", "Id": "402268", "Score": "0", "body": "Wait, next won't default initialize to 0? Or am I thinking of C++ again?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T15:39:58.060", "Id": "402296", "Score": "0", "body": "@TobySpeight I would have mentioned it, but I decided to omit the variable entirely instead" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T05:57:29.180", "Id": "402357", "Score": "0", "body": "@Jaldhar Why do you think `next` is initialized in C++?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T05:09:50.863", "Id": "208262", "ParentId": "208261", "Score": "2" } }, { "body": "<p>First, <em>I'm not sure</em>, but default parameter <a href=\"https://stackoverflow.com/questions/1472138/c-default-arguments\">isn't valid in C</a></p>\n\n<p>Otherwise, you lack includes:</p>\n\n<pre><code>#include &lt;stdio.h&gt; //puts, getchar, printf\n#include &lt;string.h&gt; //strcmp\n</code></pre>\n\n<p>You can get rig of <code>strcmp</code> call (and by extension, the <code>string.h</code> header):</p>\n\n<pre><code>if (prompt != NULL &amp;&amp; *prompt) {...}\n</code></pre>\n\n<p>Finally, your loop can be simplified, removing useless (and unsafe) variable:</p>\n\n<pre><code> while(!feof(stdin) &amp;&amp; getchar() != '\\n');\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T11:18:39.450", "Id": "402265", "Score": "0", "body": "Oops just noticed I've been compiling this program as C++ (which I normally use) not C. The intent was to write C though. Also: @reinderien made a similar observation about the strcmp but he did not do an explicit NULL check. Is that really necessary?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T11:25:31.320", "Id": "402267", "Score": "0", "body": "This is one function out of a larger program so I didn't bother showing the includes. Of course they are there in the actual codebase." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T11:36:10.430", "Id": "402270", "Score": "0", "body": "For your first message, to make a long explanation short, [read this](https://stackoverflow.com/questions/8321459/what-is-the-difference-between-str-null-and-str0-0-in-c). Otherwise, for the 2nd point, since you have to provide a full working code, you have to provides includes. Take care for the next :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T15:40:36.097", "Id": "402297", "Score": "0", "body": "@Jaldhar It's not a bad idea, for robustness." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T09:07:21.507", "Id": "208272", "ParentId": "208261", "Score": "1" } }, { "body": "<blockquote>\n <p>if it was possible to do this entirely via the standard C library.</p>\n</blockquote>\n\n<p>Yes, yet OP's code has issues.</p>\n\n<p><strong>Invalid C</strong></p>\n\n<p>Standard C does not have default function parameters. Even if it did, as in C++, the usage belongs in a .h file <em>declaration</em>, not the .c file <em>definition</em>.</p>\n\n<pre><code>// int getkey(const char* prompt = \"\") {\nint getkey(const char* prompt) {\n</code></pre>\n\n<p><strong>No need to involve <code>stdout</code> in a <code>stdin</code> function</strong></p>\n\n<p>Consider dropping the prompt code. If still desired, code as a higher level function. Also allow a prompt without an output <code>'\\n'</code> occurring. Be prepared for <code>stdout</code> as fully buffered or unbuffered.</p>\n\n<pre><code> int prompt_and_getkey(const char* prompt) {\n // Do not use puts() which appends a \\n, let caller decide.\n fputs(prompt, stdout);\n fflush(stdout); // Ensure output occurs before input.\n\n return getkey();\n }\n</code></pre>\n\n<p><strong>Bug</strong></p>\n\n<p>Below code uses <code>next</code> before it is assigned, thus <strong>undefined behavior</strong> (UB) and anything may happen. This also implies that OP does not have all warnings enabled with a good compiler as such trivial errors are automatically detected. Save time. Enable all warnings.</p>\n\n<pre><code>int next;\nwhile(!feof(stdin) &amp;&amp; next != '\\n') { // bad code\n</code></pre>\n\n<p><strong>Handle rare input error</strong></p>\n\n<p><code>feof(stdin)</code> is simply the wrong test as the below is an infinite loop on input error. The earlier answers are also infinite loops on input error.</p>\n\n<pre><code>// bad\nint next;\nwhile(!feof(stdin) &amp;&amp; next != '\\n') { \n next = getchar();\n}\n\n// Amended\nint next = ch;\nwhile(next != EOF &amp;&amp; next != '\\n') { \n next = getchar();\n}\n</code></pre>\n\n<p><strong>Questionable design</strong></p>\n\n<p>Code does not consider that the input may be simple <code>\"\\n\"</code>. Code <em>assumes</em> a first read <code>'\\n'</code> is due to a previous line. Instead it may simple be a line that only consists of <code>\"\\n\"</code></p>\n\n<p>To fix, code needs to re-architect the whole idea of leaving <code>'\\n'</code> in <code>stdin</code> for the <em>next</em> line to read. Better to have code finish consuming the line before calling code to get the next line.</p>\n\n<p><strong><code>fflush(stdin)</code> and <code>feof()</code></strong></p>\n\n<p>Calling these functions are often strong indications of questionably-designed code. I recommend to never use <code>fflush(stdin)</code> and then use <code>feof()</code> only once one is very clear on its need: to distinguish end-of-file from input error. Do not use <code>feof()</code> to determine if end-of-file occurred. Use <code>... == EOF</code> to determine if end-of-file or input error occurred.</p>\n\n<p><strong>Unclear comments</strong></p>\n\n<p>Example: \"Drain the input buffer so any extra characters which were pressed are discarded <strong>except</strong> for newline\". The <strong>except</strong> does not apply here as code also discards <code>'\\n'</code>.</p>\n\n<p><strong>Simplification</strong></p>\n\n<p>Code only needs to check the first character. Testing <code>*string_pointer</code> for an empty string test is idiomatic in C and is <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a>.</p>\n\n<pre><code>// WET\n// if (strcmp(prompt, \"\") != 0) {\n\n// DRY\nif (*prompt) {\n</code></pre>\n\n<p>Either source code may emit the same run-time code. As with such style issue, consult your group's coding guide.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T05:38:40.087", "Id": "208323", "ParentId": "208261", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T04:56:42.453", "Id": "208261", "Score": "1", "Tags": [ "c", "strings", "io" ], "Title": "Portably get one character from standard input using standard library only" }
208261
<p>I'm using PHP <a href="https://github.com/andreskrey/readability.php" rel="nofollow noreferrer">Readability</a> to extract contents from news to get title, description and body like so.</p> <pre><code>&lt;?php include "vendor/autoload.php"; use andreskrey\Readability\Readability; use andreskrey\Readability\Configuration; $readability = new Readability(new Configuration()); $client_config = [ 'timeout' =&gt; 10.0, 'cookie' =&gt; true, 'verify' =&gt; false, ]; $client = new \GuzzleHttp\Client($client_config); $response = $client-&gt;request('GET', "https://www.nytimes.com/2018/11/22/world/middleeast/saudi-arabia-nuclear.html")-&gt;getBody(); $html = $response-&gt;getContents(); try { $readability-&gt;parse($html); echo "&lt;h3&gt;" . $readability-&gt;getTitle() . "&lt;/h3&gt;&lt;p&gt;&lt;/p&gt;"; echo "&lt;strong&gt;" . $readability-&gt;getExcerpt() . "&lt;/strong&gt;&lt;p&gt;&lt;/p&gt;"; echo $readability-&gt;getContent() . "&lt;p&gt;&lt;/p&gt;"; } catch (ParseException $e) { echo sprintf('Error processing text: %s', $e-&gt;getMessage()); } </code></pre> <p>Everything work just fine, but I was wondering, does it has any other better "PHP Reader view" library out there? Or someone can point me a better way to study?</p> <p>Any idea?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T08:11:44.190", "Id": "208269", "Score": "1", "Tags": [ "php", "web-scraping" ], "Title": "Parse news content with PHP" }
208269
<p>I'm using the time for e.g. ping and timeout calculation as well as animations in a game. So my (big) codebase uses <code>std::chrono::steady_clock::now()</code> in many places. For testing I'd like to test those without having to resort to <code>sleep</code> and friends (timeout of >=5mins will be hard to test this way...)</p> <p>For this I created a custom <code>Clock</code> class that uses a singleton-like instance which can be changed to provide a custom clock. A default of <code>steady_clock</code> is used for production code. This <code>Clock</code> can be used as a drop-in replacement of <code>std::chrono::steady_clock</code> and can be mocked in test code. </p> <p>I'd like a review with suggestions how to improve this or if it has any flaws. Pointers to similar/better implementations are also welcome. I'm mostly concerned about the multiple indirections (and related performance penalties) this causes: Lookup of a "constructed" flag, the impl and the vtable (3 pointers) although I only have 1 function. See <a href="https://godbolt.org/z/Sid-Z8" rel="nofollow noreferrer">godbold</a></p> <pre><code>#include &lt;chrono&gt; #include &lt;memory&gt; struct BaseClock { using Clock = std::chrono::steady_clock; using time_point = Clock::time_point; virtual ~BaseClock() = default; virtual time_point now(){ return std::chrono::steady_clock::now(); } }; class Clock { static std::unique_ptr&lt;BaseClock&gt;&amp; inst(){ static std::unique_ptr&lt;BaseClock&gt; clock(new BaseClock); return clock; } public: using rep = BaseClock::Clock::rep; using duration = BaseClock::Clock::duration; using time_point = std::chrono::time_point&lt;Clock&gt;; static time_point now(){ return time_point(inst()-&gt;now().time_since_epoch()); } static void set(std::unique_ptr&lt;BaseClock&gt; clock){inst() = std::move(clock);} }; int main() { return Clock::now().time_since_epoch().count(); } </code></pre> <p>Example usage in test code:</p> <pre><code>struct MockClock: public BaseClock{ static time_point current; time_point now() override { return current; } }; void test_method(){ Clock::set(new MockClock); MockClock::current = MockClock::time_point(100); testClass.methodUsingClock(); MockClock::current += std::chrono::seconds(10); REQUIRE(testClass.checkTimeout()); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T10:06:37.077", "Id": "402250", "Score": "0", "body": "What's the point of `BaseClock` ?\n\nWhat's advantage against using directly `std::chrono` ? \n\nAvoid naked `new`, use `std::make_unique` instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T10:54:52.473", "Id": "402257", "Score": "2", "body": "@Calak: IIUC the point of `BaseClock` is to provide a baseline clock interface without direct dependencies. A user expecting a `const BaseClock&` or similiar can now write code independent of the underlying clock type. This allows for switching the underlying clock on a higher level without affecting the dependent code (kind of \"dependency injection for clocks\"). As a side effect, this allows for easier test setups (especially for weird corner cases). // I'm not a fan of the singleton in `Clock`, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T12:20:05.260", "Id": "402276", "Score": "1", "body": "@Calak In test code you need to mock the time, that's the whole purpose that I stated in the intro. Hence you need some injection point which the virtual `BaseClock::now()` provides while defaulting to `std::chrono`. I added a usage example to make this clearer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T12:22:17.090", "Id": "402277", "Score": "0", "body": "@hoffmale You are correct, although the code does not get `BaseClock&` but simply uses `Clock` as a drop-in replacement for `std::chrono::*clock` (I edited the question to highlight this) So yes this is exactly dependency injection but without passing it as (template or regular) parameters which would require massive changes to the codebase. As clocks are static classes a singleton is required, I don't see a way avoiding this." } ]
[ { "body": "<p>While I think the underlying idea is quite nice, the actual implementation and design has some issues.</p>\n<h1>Wrong Abstraction Level</h1>\n<p>Let's start with the less obvious one: How would you actually use <code>Clock</code> or <code>BaseClock</code> with <code>std::chrono::high_resolution_clock</code> or <code>std::chrono::system_clock</code>?</p>\n<p>The simplest approach would be something akin to this:</p>\n<pre><code>struct HighResClock : BaseClock {\n time_point now() override { return std::chrono::high_resolution_clock::now(); }\n};\n</code></pre>\n<p>It seems so clean, so simple, and so easy. Except that it doesn't compile! That's because <code>std::chrono::high_resolution_clock::time_point</code> is not the same as <code>BaseClock::time_point</code> (and cannot easily be converted, if at all possible).</p>\n<p>But: Do we actually need <code>time_point</code>s in the public interface?</p>\n<p>The only reason to expose <code>time_point</code> values is to extract time differences between them. But that only matters if arbitrary <code>time_point</code>s are to be compared.</p>\n<blockquote>\n<p>Technically, the <code>time_point</code> could be stored in some form. However, for many clocks, like <code>std::chrono::steady_clock</code> or <code>std::chrono::high_resolution_clock</code>, the epoch from when the clock are measuring their time offset can change between different executions of the same program (e.g. because the computer got rebooted).</p>\n<p>This makes storing <code>time_point</code>s, especially those not obtained from <code>std::chrono::system_clock</code>, rather useless. In that case, you'll likely need a calendar library (or similar) to get points of time in a storable format.</p>\n</blockquote>\n<p>But in most cases, a simple <code>Timer</code> abstraction can fulfill all clock needs (comparing some <code>time_point</code>s with some relation). A simple <code>Timer</code> interface could look like this:</p>\n<pre><code>struct timer {\n // choose an appropriate duration type\n using duration = std::chrono::duration&lt;double&gt;;\n\n virtual ~timer() = default;\n \n virtual void start() = 0;\n virtual duration stop() = 0;\n virtual duration tick() = 0; // to obtain multiple measurements from the same baseline\n};\n\nclass steady_timer : public timer {\n using clock = std::chrono::steady_clock;\n using time_point = clock::time_point;\n\n time_point start_time;\n bool running;\n\npublic:\n steady_timer() = default;\n\n void start() override\n {\n start_time = clock::now();\n running = true;\n }\n\n duration tick() override\n {\n return duration(clock::now() - start_time);\n }\n\n duration stop() override\n {\n auto elapsed = tick();\n running = false;\n return elapsed;\n }\n};\n</code></pre>\n<p>Now the only exposed part of the interface is the duration. And it is easily extensible to other time sources (e.g. Win32 <code>QueryPerformanceCounter</code>) or mockable.</p>\n<h1>Singleton</h1>\n<p>I really don't like the <code>Clock</code> singleton. Yes, it is easy to just ask a global clock. Yes, it is also easy to screw all code depending on this clock by changing the underlying instance.</p>\n<p>For example, a test setting <code>Clock</code> to a mock but not restoring the original clock breaks all other tests that assume the default clock implementation - making test failure dependent on test execution order.</p>\n<p>Instead, take a reference or pointer to a <code>timer</code> as parameter. This allows you to pass in a clock where needed, without changing (or corrupting) everyone elses <code>timer</code>.</p>\n<p>Rewriting your test case:</p>\n<pre><code>class mock_timer : public timer {\n std::vector&lt;duration&gt; measurements;\n int counter = 0;\n\npublic:\n mock_timer(std::initializer_list&lt;duration&gt; il) : measurements(il) {}\n\n void start() override {}\n\n duration tick() override\n {\n if(counter &lt; measurements.size()) return measurements[counter++];\n return measurements.back();\n }\n\n duration stop() override\n {\n return measurements.back(); // just example\n }\n};\n\nvoid test_method(){\n using namespace std::literals::chrono_literals;\n mock_timer my_timer{ 10s };\n\n testClass.methodUsingClock(my_timer);\n \n // or, more likely:\n testclass inst{my_timer};\n inst.methodUsingClock();\n\n REQUIRE(testClass.checkTimeout());\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T14:58:10.447", "Id": "402291", "Score": "0", "body": "I understand your arguments But I see problems with that: Time is something global, so it makes sense for it being a singleton/global. Passing it to every class would require huge refactoring and passing things down in aggregates etc. which shows another problem: Your timer class cannot be reused! So e.g. a class that needs 2 timers cannot reuse the timer as it would restart. BUT: What if I use my design but change `BaseClass::now` to return a duration? Then the underlying clock does not matter as long is it returns \"time since epoch\" and is not changed while a Clock::time_point is held." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T16:52:54.680", "Id": "402303", "Score": "1", "body": "@Flamefire: I'm not sure if I am getting your whole argument. I don't think time is something global. Instead, everything has its own perspective on time. For example, a game might be using one clock for rendering and a different clock for logic updates. Why? Because if gameplay is paused (e.g. when entering a menu), the graphics should still continue to be rendered because otherwise the screen would freeze. // RE \"time since epoch\": When is epoch? What if the epoch changes because the clock is changed? Having mutable global state is just waiting for accidents to happen." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T16:44:24.970", "Id": "402412", "Score": "0", "body": "Even your timer needs a clock. And all instances of that (at least in the same logical unit) need to use the same clock. Otherwise the relative time won't match (or at least it is not ensured) For your example: Yes if paused the *timer* needs to be paused too, but the *time* does not. So you need different timers, but I don't see the need for different clocks. // \"mutable global state\": I actually don't want nor need it to be mutable. It should be set once: Start of program or start of test. Then the epoch stays the same ->hence my \"is not changed\" restriction, but I'm unsure how to enforce it" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T13:19:07.217", "Id": "208283", "ParentId": "208273", "Score": "5" } }, { "body": "<p>The use of a singleton will limit your possibilities, as hoffmale's review points out. It completely prevents concurrent testing. However, you'll find that getting the Clock instance to the code that needs it can easily add lots of \"tramp data\" to intermediated method signatures. I try to limit that by passing a factory/registry interface that allows classes to access the system interactions they need - time, filesystem, network, etc. In the tests, populate a mock-factory with the necessary mock objects, and in production, pass a concrete-factory that gives out objects with real system access.</p>\n\n<p>One aspect that's missing is that this interface only gives access to <code>now()</code> - it doesn't handle the other clock-related actions that can cause slow tests. In particular, you'll want sleeps and network- or mutux-related timeouts to respect the mock clock's idea of time. To achieve that, you'll need to redirect those timeouts to mockable methods. That's a bigger job, but will give you a much more useful test regime.</p>\n\n<p>I think that when I made something like that (many years ago, and in a different language), I ended up with the <code>MockTime</code> storing an ordered list of future events; whenever control entered its code, it could advance the time to match the next event (which could be the end of a sleep, release of a mutex, or an interrupt from an external (mocked) thread, for example).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T13:25:52.207", "Id": "208527", "ParentId": "208273", "Score": "1" } }, { "body": "<p>If you care about performance, you can use templates to provide arguments at compile time.</p>\n<h3>Example</h3>\n<pre class=\"lang-cpp prettyprint-override\"><code>template &lt;typename Clock&gt;\nclass TestClass {\n Clock clock;\n\n public:\n void testMethod() {\n auto start = clock.currentTime();\n doStuff();\n auto end = clock.currentTime();\n }\n}\n</code></pre>\n<p>Now you can use any class which has <code>currentTime</code> method</p>\n<p><strong>Edit:</strong> The downside of this approach, is if you have a lot of template instantiations, it will cripple your compile times. Do not optimize prematurely. <strong>Profile First!!!</strong></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-10T13:14:34.920", "Id": "253305", "ParentId": "208273", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T09:50:33.067", "Id": "208273", "Score": "3", "Tags": [ "c++", "c++11", "mocks" ], "Title": "Mockable clock meeting std::chrono TrivialClock requirement and interface" }
208273
<p>This piece of code is aimed to cancel any ongoing search requests sent from the web application if next request is started, e.g. after user updates the search term. </p> <p>I tested it in the final application and everything looks fine. It has already been deployed to the remote environment in our organization.</p> <p>It appears to work fine, but are there any pitfalls in the code?</p> <pre><code>const ongoingRequests = []; const fetchData = (text, activePage, itemsPerPage) =&gt; async dispatch =&gt; { dispatch({ type: FETCH_ENTITIES }); const page = activePage - 1; let response; // cancel any ongoing search requests if (ongoingRequests.length &gt; 0) { ongoingRequests.map(x =&gt; x.cancel('next request started')); ongoingRequests.length = 0; } // start a new request response = await (async () =&gt; { const cts = axios.CancelToken.source(); ongoingRequests.push(cts); let path = text !== '' ? `/Search?PageNumber=${page}&amp;PageSize=${itemsPerPage}&amp;SearchTerm=${text}` : `?QueryLead=true&amp;PageNumber=${page}&amp;PageSize=${itemsPerPage}`; return axios .get(`${env_urls.api.entity}Entity${path}`, { cancelToken: cts.token, }) .then(response =&gt; { return response; }) .catch(error =&gt; { if ( typeof cts !== 'undefined' &amp;&amp; typeof cts.token !== 'undefined' &amp;&amp; typeof cts.token.reason !== 'undefined' &amp;&amp; cts.token.reason.message === 'next request started' ) { // request cancelled, everything ok } else { throw error; } }); })(); // response is undefined if the request has been cancelled if (typeof response !== 'undefined') { const data = response.data; dispatch({ type: FETCH_ENTITIES_SUCCESS, data }); } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T10:46:56.847", "Id": "402255", "Score": "1", "body": "\"Does it work as intended?\" : it's up to you to tell us :]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T10:49:28.403", "Id": "402256", "Score": "0", "body": "@Calak Everything is fine when I test it in the application but maybe there is an issue that I cannot see. Like some js construct that makes no sense ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T10:55:14.670", "Id": "402258", "Score": "0", "body": "\"Does it work as intended?\" Did you test it? One of the prerequisites of posting on Code Review is that the code has to work to the best of your knowledge. Does it? You say it works in the application. Is that the final application that needs it? A test application?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T10:58:14.350", "Id": "402259", "Score": "1", "body": "@Mast I have updated the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T17:44:17.017", "Id": "402312", "Score": "1", "body": "When I implement this type of search functionality I usually cancel the current request when the user presses a key (on the keypress, paste events) and start a timer for a fraction of a second. I only start the request when the timer expires. That way I don't start requests while the user is still typing. I've also rarely found it unnecessary to keep an array of requests. I just keep the currently executing one if any." } ]
[ { "body": "<p>You can rewritte this piece of code:</p>\n\n<pre><code>.catch(error =&gt; {\n if (\n cts !== 'undefined' &amp;&amp;\n cts.token !== 'undefined' &amp;&amp;\n cts.token.reason !== 'undefined' &amp;&amp;\n cts.token.reason.message === 'next request started'\n ) {\n } else {\n throw error;\n }\n}\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>.catch(error =&gt; {\n if (\n typeof cts === 'undefined' ||\n typeof cts.token === 'undefined' ||\n typeof cts.token.reason === 'undefined' ||\n cts.token.reason.message !== 'next request started'\n ) {\n throw error;\n }\n}\n</code></pre>\n\n<p>And you can go further into the simplification using <a href=\"https://stackoverflow.com/questions/2631001/test-for-existence-of-nested-javascript-object-key\">this trick</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T17:39:58.620", "Id": "402311", "Score": "1", "body": "imo, you shouldn't use `typeof` you should just write it as `if (cts === undefined) || ...`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T17:50:22.107", "Id": "402315", "Score": "0", "body": "@MarcRohloff yeah, copy/paste's mistake :p Thx" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T04:19:57.980", "Id": "485225", "Score": "0", "body": "This is the perfect example to use the new [optional chaining operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T10:58:51.660", "Id": "208276", "ParentId": "208275", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T10:41:29.693", "Id": "208275", "Score": "4", "Tags": [ "javascript", "beginner", "axios" ], "Title": "Cancelling ongoing http requests when next one is started - web app search feature" }
208275
<p><strong>Question</strong></p> <p>Recently I have tried to create a web scraping program to get data from google trends. It uses an RSS feed to do so. My question is as follows:</p> <p><em>How can I improve my code such that it is more concise, efficient, and pleasing to a programmers eye? I would like to emphasise that I'm most concerned about if I've misused any functions, methods, or syntax in my code and if it could be 'cleaner'</em></p> <p><strong>Context</strong></p> <ul> <li>I'm not experienced at all. I'm doing this to learn. </li> <li>Security isn't an issue since the program is running locally. </li> </ul> <p><strong>The code</strong></p> <pre><code>"""Uses webscraping to retrieve html information from Google Trends for parsing""" # Imports import time import ssl from requests import get from bs4 import BeautifulSoup # Url for request url = "https://trends.google.com/trends/trendingsearches/daily/rss?geo=US" # Used to create an unverified certificate. ssl._create_default_https_context = ssl._create_unverified_context class connection(object): def __init__(self, f): self.f = f def __call__(self): """Calculates the time taken to complete the request without any errors""" try: # Times the amount of time the function takes to complete global html start = time.time() html = get(url) self.f() end = time.time() time_taken = end - start result = print("the function {} took {} to connect".format(self.f.__name__, time_taken)) return result except: print("function {} failed to connect".format(self.f.__name__)) @connection def html_parser(): """Parses the html into storable text""" html_unparsed = html.text soup = BeautifulSoup(html_unparsed, "html.parser") titles_unformatted = soup.find_all("title") traffic_unformatted = soup.find_all("ht:approx_traffic") # Indexes through list to make data readable titles = [x.text for x in titles_unformatted] traffic = [] for x in traffic_unformatted: x = x.text x = x.replace("+","") x = x.replace(",", "") traffic.append(x) print(traffic, titles) html_parser() </code></pre> <p><strong>Output</strong></p> <pre><code>['100000', '2000000', '2000000', '1000000', '1000000', '1000000', '1000000', '500000', '500000', '500000', '200000', '200000', '200000', '200000', '200000', '200000', '200000', '200000', '200000', '200000'] ['Daily Search Trends', '23 and Me', 'NFL scores', 'Best Buy', 'Walmart Supercenter', 'NFL', 'Saints', 'GameStop', 'JCPenney', 'Lion King 2019', 'Starbucks', 'Dollar General', 'Amazon Black Friday', 'Mike Posner', 'NFL games On Thanksgiving', 'McDonalds', 'Bath And Body Works Black Friday', 'Old Navy Black Friday 2018', 'Kroger', 'NFL standings', 'Safeway'] the function html_parser took 1.0186748504638672 to connect </code></pre> <p><strong>Concerns</strong></p> <ul> <li>Makes programmers cringe. </li> </ul> <p>As someone relatively new to python and programming in general my worst fear is that this code gives someone else a headache or a laugh to look at. At the end of the day I just want to improve, so to reiterate: how can I make this code look better? Have I misused any functions? </p>
[]
[ { "body": "<p>The idea behind your script is pretty cool and there's a couple ways to polish it up! While it certainly wouldn't cause a headache, I think that creating an entire class just to measure how long the request is going to take to complete is a little overkill.</p>\n\n<p>Within the class itself, let's look at 2 things which aren't the best practice.</p>\n\n<ul>\n<li>Use of a global variable</li>\n<li>Use of the <code>try/except</code> block</li>\n</ul>\n\n<h3>Global variables</h3>\n\n<p>There's a <a href=\"https://stackoverflow.com/questions/19158339/why-are-global-variables-evil\">brilliant StackOverflow question</a> with really good answers as to why using global variables should be discouraged. While in the scope of your script it is not harmful, imagine you had many functions and methods in your script. Using the global variable could decrease readability and potentially alter the behaviour of your code. Mind you, global variables aren't the same as global constants (also discussed in the StackOverflow question).</p>\n\n<h3>Exception handling</h3>\n\n<p>Using a bare <code>except</code> statement will handle <strong>all</strong> exceptions, even the ones you might not anticipate. Catch errors explicitly, otherwise you might cause unexpected behaviour in your code, should it become more complex. In this scope, your bare <code>except</code> statement should become more like this:</p>\n\n<pre><code>try:\n ...\nexcept requests.exceptions.ConnectionError:\n print(\"failed to connect\")\n</code></pre>\n\n<p>This way, you are handling the case where your request actually fails and you let other errors happen in their intended way. Otherwise, a different exception could have been raised and you won't know what caused it.</p>\n\n<p>Additionally, on this class:</p>\n\n<ul>\n<li>Following naming conventions, class names should use CapWords.</li>\n<li>In Python 3+, classes no longer need to be inherited from <code>object</code>.</li>\n</ul>\n\n<p>Instead of the class, you could just define a simple function which retrieves the XML document from the RSS feed, declare your timing functionality within it and returns the XML document. Seeing as the URL query takes in what's seemingly an ISO 3166-2 country code as one of the parameters, you could pass the country code into this function and have the ability to fetch search trends for so many different countries! Please note that in the following snippet I am using <code>f-strings</code> which were introduced since Python 3.6.</p>\n\n<pre><code>def fetch_xml(country_code):\n url = f\"https://trendse.google.com/trends/trendingsearches/daily/rss?geo={country_code}\"\n start = time.time()\n response = requests.get(url)\n response_time = time.time() - start\n print(f\"The request took {response_time}s to complete.\")\n return response.content`\n</code></pre>\n\n<h2>Parser</h2>\n\n<p>Looking at the docstring of your parser, one might argue it's a little misleading. You're mentioning \"storable text\" while you're only printing your output! To come closer to the intention of the docstring, it would be better to return the parsed data and decide what to do with it later. I think in this case, a dictionary would a very fitting data structure. Dictionaries store key-value pairs, so lets use the trend title as the key and the traffic approximation as the value.</p>\n\n<p>Using <a href=\"https://docs.python.org/3/library/re.html#re.sub\" rel=\"nofollow noreferrer\"><code>re.sub()</code></a> will allow you to remove different characters from a string in a single line, rather than replacing each character separately! This piece of code here:</p>\n\n<pre><code>for x in traffic_unformatted: \n x = x.text \n x = x.replace(\"+\",\"\")\n x = x.replace(\",\", \"\")\n</code></pre>\n\n<p>Can now become:</p>\n\n<pre><code> for x in traffic_unformatted:\n x = re.sub(\"[+,]\", \"\", x.text)\n</code></pre>\n\n<p>Zip the two lists of titles and traffic approximations together and iterate over them to create the dictionary. I am going to use a dictionary comprehension in the final script, however it works identically to the following.</p>\n\n<pre><code>titles = soup.find_all(\"title\")\napproximate_traffic = soup.find_all(\"ht:approx_traffic\")\ntrends = {}\nfor title, traffic in zip(titles[1:], approximate_traffic):\n trends[title.text] = re.sub(\"[+,]\", \"\", traffic.text)\nreturn trends\n</code></pre>\n\n<p>Please pay attention to the <code>titles</code> function having its first element sliced off - this is because BeautifulSoup picked up the title of the entire XML document together with titles of the trends.</p>\n\n<p>Finally, I am using an <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\"</code></a> guard to separate functions from the block of code where I am calling the functions from.</p>\n\n<p>Entire script:</p>\n\n<pre><code>import time\nimport re\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef fetch_xml(country_code):\n url = f\"https://trends.google.com/trends/trendingsearches/daily/rss?geo={country_code}\"\n start = time.time()\n response = requests.get(url)\n response_time = time.time() - start\n print(f\"The request took {response_time}s to complete.\")\n return response.content\n\ndef trends_retriever(country_code):\n \"\"\"Parses the Google Trends RSS feed using BeautifulSoup.\n\n Returns:\n dict: Trend title for key, trend approximate traffic for value.\n \"\"\"\n xml_document = fetch_xml(country_code)\n soup = BeautifulSoup(xml_document, \"lxml\")\n titles = soup.find_all(\"title\")\n approximate_traffic = soup.find_all(\"ht:approx_traffic\")\n return {title.text: re.sub(\"[+,]\", \"\", traffic.text)\n for title, traffic in zip(titles[1:], approximate_traffic)}\n\n\nif __name__ == '__main__':\n trends = trends_retriever(\"US\")\n print(trends)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>The request took 0.2512788772583008s to complete.\n{'Tiger vs Phil': '2000000', 'McKenzie Milton': '200000', 'Costco Black Friday': '200000', 'Nebraska Football': '200000', 'Patagonia': '100000', 'Michael Kors': '100000', 'Jcrew': '100000', 'finish line': '100000', 'WVU football': '100000', 'Texas football': '100000', 'Shoe Carnival': '100000', 'J Crew': '100000', 'Llbean': '100000', 'Cards Against Humanity': '100000', 'Bleacher Report': '100000', 'Steph Curry': '50000', 'Apple Cup': '50000', 'Bob McNair': '50000', 'Virginia Tech football': '50000', 'Glossier': '50000'}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T01:50:25.707", "Id": "208316", "ParentId": "208277", "Score": "3" } } ]
{ "AcceptedAnswerId": "208316", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T11:11:01.290", "Id": "208277", "Score": "5", "Tags": [ "python", "object-oriented", "python-3.x", "web-scraping" ], "Title": "Web scraping google trends in python" }
208277
<p>I have two issues/questions with figuring out a proper way to write this code for a player leveling system.</p> <p>My First question/issue is that when this code is run it works as intended with a slight problem. <code>public void levelUp()</code> is being used to, "set", the level if you will (I am sure this is a sloppy way of doing this but we will get to that in the next question) while <code>levelUpXp()</code> is being used as the only way I currently know how to store the elements of <code>int[] requiredXP</code> to let the game know when the player has reached X amount of xp to level him up to X level. <code>ding()</code> is simply a notification for the player to be aware that they have increased in level.</p> <p>As stated before this all works the way I am wanting it to work however upon implementing <code>ding()</code> after a countless amount of time trying to write multiple if statements to do what ding is doing now, I have run into an issue where <code>curXP</code> is NOT equal to either <code>reqXP</code> or <code>requiredXP[]</code> due to the amount of XP the player is gaining not always being an exact number within <code>requiredXP[]</code>. While I already assumed this would happen, it is now resulting in either a level up notification not being sent because <code>curXP == requiredXP[x]</code> is not always the case if the amount of xp needed to level is 17 but after killing an enemy the player goes from 15xp to 18xp or <code>curXP &lt;= requiredXP[x]</code> causing the level up notification to be constantly sent until that player reaches their next level in which the notification is still sent however with a new level attached.</p> <p>Second question will be below code.</p> <p>Here is my player class and methods:</p> <pre><code>public class Player extends Creature { int health = 100; int maxHealth = 100; int attackDamage = 25; int numHealthPotions = 3; int healthPotHeal = 30; int curXP = 0; int level = 0; int reqXP = 0; int[] currentLevel = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int[] requiredXP = { 0, 6, 17, 36, 65, 105, 158, 224, 305, 402 }; public void levelUp() { if (curXP == requiredXP[0]) { level = currentLevel[0]; } else if (curXP == requiredXP[1]) { level = currentLevel[1]; } else if (curXP == requiredXP[2]) { level = currentLevel[2]; } else if (curXP == requiredXP[3]) { level = currentLevel[3]; } else if (curXP == requiredXP[4]) { level = currentLevel[4]; } else if (curXP == requiredXP[5]) { level = currentLevel[5]; } else if (curXP == requiredXP[6]) { level = currentLevel[6]; } else if (curXP == requiredXP[7]) { level = currentLevel[7]; } else if (curXP == requiredXP[8]) { level = currentLevel[8]; } else if (curXP == requiredXP[9]) { level = currentLevel[9]; } } public void levelUpXp() { if (level == currentLevel[0]) { reqXP = requiredXP[0]; } else if (level == currentLevel[1]) { reqXP = requiredXP[1]; } else if (level == currentLevel[2]) { reqXP = requiredXP[2]; }else if (level == currentLevel[3]) { reqXP = requiredXP[3]; } else if (level == currentLevel[4]) { reqXP = requiredXP[4]; }else if (level == currentLevel[5]) { reqXP = requiredXP[5]; } else if (level == currentLevel[6]) { reqXP = requiredXP[6]; }else if (level == currentLevel[7]) { reqXP = requiredXP[7]; } else if (level == currentLevel[8]) { reqXP = requiredXP[8]; }else if(level == currentLevel[9]) { reqXP = requiredXP[9]; } } public void ding() { if(level == 2 &amp;&amp; curXP == requiredXP[1]) { System.out.println(" #############################"); System.out.println(" # You have reached level " + level + "! # "); System.out.println(" #############################"); } else if(level == 3 &amp;&amp; curXP == requiredXP[2]) { System.out.println(" #############################"); System.out.println(" # You have reached level " + level + "! # "); System.out.println(" #############################"); } else if(level == 4 &amp;&amp; curXP == requiredXP[3]) { System.out.println(" #############################"); System.out.println(" # You have reached level " + level + "! # "); System.out.println(" #############################"); } else if(level == 5 &amp;&amp; curXP == requiredXP[4]) { System.out.println(" #############################"); System.out.println(" # You have reached level " + level + "! # "); System.out.println(" #############################"); } else if(level == 6 &amp;&amp; curXP == requiredXP[5]) { System.out.println(" #############################"); System.out.println(" # You have reached level " + level + "! # "); System.out.println(" #############################"); } else if(level == 7 &amp;&amp; curXP == requiredXP[6]) { System.out.println(" #############################"); System.out.println(" # You have reached level " + level + "! # "); System.out.println(" #############################"); } else if(level == 8 &amp;&amp; curXP == requiredXP[7]) { System.out.println(" #############################"); System.out.println(" # You have reached level " + level + "! # "); System.out.println(" #############################"); } else if(level == 9 &amp;&amp; curXP == requiredXP[8]) { System.out.println(" #############################"); System.out.println(" # You have reached level " + level + "! # "); System.out.println(" #############################"); } else if(level == 10 &amp;&amp; curXP == requiredXP[9]) { System.out.println(" #############################"); System.out.println(" # You have reached level " + level + "! # "); System.out.println(" #############################"); } } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public void Level() { int maxLevel = 200; int maxLevelXP = 1000000; for (int currentLevel = 1; currentLevel &lt; maxLevel; currentLevel += 1) { float x = currentLevel / (float) maxLevel; double y = Math.pow(x, 2.61); int requiredXP = (int) (y * maxLevelXP); System.out.println("Level " + currentLevel + " XP: " + requiredXP); } } </code></pre> <p>Here is game class where ding and other previously mentioned Methods are used:</p> <pre><code>GAME: while (running) { p.levelUp(); p.levelUpXp(); System.out.println("-----------------------------------------------"); String enemy = e.enemies[rand.nextInt(e.enemies.length)]; int enemyHealth = e.enemyHealth; int preLevel = 1; int curLevel = preLevel + 1; System.out.println("\t# " + enemy + " has appeared! #\n"); while (enemyHealth &gt; 0) { System.out.println( "\t" + userName + "\n\t HP: " + p.health + " Level: " + p.level + " Exp: " + p.curXP + "\n\t" + "\n\t" + enemy + "\n\t HP: " + enemyHealth); System.out.println("\n\t What would you like to do?"); System.out.println("\t 1. Attack"); System.out.println("\t 2. Drink health potion"); System.out.println("\t 3. Run!"); String input = in.nextLine(); if (input.equals("1")) { int damageDealt = rand.nextInt(p.attackDamage); int damageTaken = rand.nextInt(e.maxEnemyAD); enemyHealth -= damageDealt; p.health -= damageTaken; if (damageDealt &gt; 0) { System.out.println("\t&gt; You strike the " + enemy + " for " + damageDealt + " damage!"); } else if (damageDealt &lt; 1) { System.out.println("\t&gt; You attempt to hit the " + enemy + " but miss!"); } if (damageTaken &gt; 0) { System.out.println("\t&gt; The " + enemy + " retaliates! You take " + damageTaken + " damage!"); } else if (damageTaken &lt; 1) { System.out.println("\t&gt; The " + enemy + " retaliates but misses!"); } if (p.health &lt; 1) { System.out.println( "\t ##################" + "\n\t # You Have Died! #" + "\n\t ##################"); break; } } else if (input.equals("2")) { if (p.numHealthPotions &gt; 0 &amp;&amp; p.health != p.maxHealth) { p.health += p.healthPotHeal; p.numHealthPotions--; if (p.health &gt; p.maxHealth) { p.health = p.maxHealth; } System.out.println("\t&gt; You drink the Health Potion!" + "\n\t&gt; You now have " + p.health + " Health!" + "\n\t&gt; You now have " + p.numHealthPotions + " Health Potion(s) left!"); } else if (p.health == p.maxHealth) { System.out.println("\t&gt; Your health is already full!"); } else if (p.numHealthPotions &lt; 1) { System.out.println("\t You have no Health Potions left!"); } } else if (input.equals("3")) { System.out.println("\t&gt; You run away from the " + enemy + "!"); continue GAME; } else { System.out.println("\t Invalid Command!"); } } if (p.health &lt; 1) { System.out.println("You fought bravely but in the end, you're just another corpse..."); break; } System.out.println("-----------------------------------------------"); if (enemyHealth &lt; 1) { p.curXP += 3; p.levelUp(); p.levelUpXp(); } System.out.println(" # The " + enemy + " was defeated! # "); System.out.println(" # You have " + p.health + " HP left! # "); System.out.println(" # You have gained " + e.xpGive + " xp! # "); p.ding(); if (rand.nextInt(100) &lt; e.dropChance) { p.numHealthPotions++; System.out.println(" # The " + enemy + " droppped a Health Potion! # "); System.out.println(" # You now have " + p.numHealthPotions + " Health Potion(s)! # "); } System.out.println("-----------------------------------------------"); System.out.println("\tWhat would you like to do?"); System.out.println("\t1. Press on!"); System.out.println("\t2. Get me out of here!"); String input = in.nextLine(); while (!input.equals("1") &amp;&amp; !input.equals("2")) { System.out.println("\tInvalid Command!"); input = in.nextLine(); } if (input.equals("1")) { System.out.println("\t&gt; You march on, deeper into the Dungeon!"); } else if (input.equals("2")) { System.out.println( "\tYou exit the dungeon. Battered and bruised as you may be, you live to fight another day!"); break; } } } </code></pre> <p>Now my second and last question is with my Player class and more specifically the way my <code>levelUp()</code>, <code>levelUpXp()</code> and <code>ding()</code> Methods are written. There has to be a better way right? I have read Javadocs, watched tutorials, read physical books and I have even done courses on sites like Codecademy and just can't seem to wrap my head around this.</p> <p>My initial goal was to have the Array automatically switch from <code>currentLevel[0]</code>(Level 1) to <code>currentLevel[1]</code>(Level 2) once the amount of <code>reqXP</code> of <code>requiredXP[1]</code> was met. I know a <code>.next()</code> exists for ArrayLists similar to <code>rand.nextInt()</code> but I don't know if that is exclusive to ArrayLists or if they can be used with Arrays as well. The current code you see now is a result of this lack of knowledge so any help or advice is much appreciated.</p> <p>I am still new to programming and this is also only my second post in 2 years.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T11:23:18.120", "Id": "402266", "Score": "3", "body": "It may be worth adding the definition of `Creature` if that will enable reviewers to compile and run the code ourselves. Don't worry about including \"too much\" code - that's unlikely to be a problem here (we're very different to [so] in that respect!)." } ]
[ { "body": "<p>This could be shortened by looping through <code>requiredXP[]</code> until you reach a value that <code>curXP</code> is equal to or using a <a href=\"https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html\" rel=\"nofollow noreferrer\">switch</a> statement. The same could be done in <code>levelUpXp()</code>.<br>\nYou are right that using and <code>ArrayList&lt;Integer&gt;</code> could simplify things as well. Possibly look into a list or queue data type.<br>\nYou could also call <code>ding()</code> from inside <code>levelUp()</code> or <code>levelUpXp()</code> instead of the while loop or set a flag variable (eg. <code>newLevel</code>) that it tests for to skip the test conditions inside.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T15:17:40.917", "Id": "402292", "Score": "1", "body": "Other than that, nice job on the code!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T08:58:26.503", "Id": "402368", "Score": "0", "body": "Something like... \n`for(curXP = 0; curXP < requiredXP[].length; curXP++) {\n level++;\n}`\n\nWould there need to be a nested if statement? I'm lost on what else to write within the for loop.\n\nI understand what you are saying even if the above is wrong, I am just struggling on figuring out how to exactly write the for loop because as stated before this was the original plan to begin with. Thanks again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T16:30:55.657", "Id": "402481", "Score": "0", "body": "Try looping through the array using the enhanced `for(element:collection)` syntax, as seen [here](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T16:33:46.940", "Id": "402482", "Score": "0", "body": "Or the incremental way could be useful because you need the index:" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T15:16:56.493", "Id": "208289", "ParentId": "208278", "Score": "2" } }, { "body": "<p>Welcome on Code Review.</p>\n\n<p>Your game's loop is way too long. You have to separate your code into functions that constitute logical units. </p>\n\n<p>E.g., taking and dealing of damages have to be moved into two separate function <code>dealDamage</code> and <code>takeDamage</code>. The whole loop of the battle into a function <code>doBattle</code>. Spawn of enemy have to be wrap into a <code>spawnEnemy</code>, inside which you place a call to <code>doBattle</code>. Etc.</p>\n\n<p>I'm afraid to tell you that all your logic seem to be weird.</p>\n\n<p>Instead of increasing the <code>level</code> and <code>Xp</code> in a clumsy way, just remove <code>ding</code>, <code>levelUp</code> and <code>levelUpXp</code>, replace:</p>\n\n<pre><code>p.curXP += 3;\np.levelUp();\np.levelUpXp();\n</code></pre>\n\n<p>by</p>\n\n<pre><code>p.addXp(3);\n</code></pre>\n\n<p>and add this function :</p>\n\n<pre><code>public void addXp(int reward) {\n curXP += reward;\n while (level &lt; requiredXP.length &amp;&amp; requiredXP[level] &lt; curXP) {\n ++level;\n System.out.println(\" #############################\");\n System.out.println(\" # You have reached level \" + level + \"! # \");\n System.out.println(\" #############################\");\n }\n}\n</code></pre>\n\n<p>By doing that, you can get rig or <code>reqXP</code> and <code>currentLevel</code> too.</p>\n\n<p>Your max level become the size of <code>requiredXP</code> (which you could rename <code>experienceGap</code>). </p>\n\n<p>You can populate this array using the logic from <code>Level()</code> (adding the values to the array instead of printing them)</p>\n\n<p>If you have some trouble to understand how game mechanics works, dive into the <a href=\"https://gamedev.stackexchange.com/\">GameDev</a> site.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T17:49:00.127", "Id": "208299", "ParentId": "208278", "Score": "3" } }, { "body": "<p>I'm not sure if it is ideal to keep the logic on how much XP is needed for a level up inside the player class itself. Usually these are properties kept outside and feed into the logic. While there are certain designs that consider the player to be a <a href=\"https://refactoring.guru/smells/data-class\" rel=\"nofollow noreferrer\">data class</a> with some external manager performing modifications like the levleUp and other routines on the player object, this somehow violates OOP principles where state should be encapsulated in the class and method invocations used to alter the state internally.</p>\n\n<p>By that, the first thing which comes to my mind on analyzing your code is, that you are actually performing a mapping between XP and the level. Your current solution creates such a mapping per player. If you have a system with hundreds of players this mapping would probably create a lot of duplicate data unless you want a per-player solution, which also would not work with the current approach. This therefore is a strong candidate for refactoring. </p>\n\n<p>You might use an implementation of <code>Map</code> that you can leverage to see how many XP are required for a player to gain a level-up. As mention before, ideally you sepcify such a mapping outside of the code and then only read in the configuration on application start. This allows you to tweak your application later on without having to recompile the whole code. As the levels are furthermore progressing you only need to store the XP required per level.</p>\n\n<p>You could i.e. have an <code>xpPerLevel.txt</code> file with the following content:</p>\n\n<pre><code>6\n17\n36\n...\n</code></pre>\n\n<p>which you could read in with a method like below:</p>\n\n<pre><code>public Map&lt;Integer, Integer&gt; loadXpPerLevel() {\n Map&lt;Integer, Integer&gt; xpPerLevel = new LinkedHashMap&lt;&gt;();\n int level = 1;\n try (Stream&lt;String&gt; lines = Files.lines(Paths.get(\"xpPerLevel.txt\"))) {\n lines.forEach(line -&gt; xpPerLevel.put(level++, Integer.valueOf(line));\n }\n return xpPerLevel;\n}\n</code></pre>\n\n<p>Ideally this code sits outside of the <code>Player</code> class and only the <code>xpPerLevel</code> map is injected to the player through its constructor. This allows certain different XP-level settings for different kinds of players, i.e. premium players get a different map injected than normal players. Via a <a href=\"https://dzone.com/articles/design-patterns-strategy\" rel=\"nofollow noreferrer\">strategy pattern</a> this can be customized quite easily.</p>\n\n<p>Next in your <code>levelUp</code> method you perform a check for the <code>currentXP</code> against the <code>requiredXP</code>. In order for a level up to kick in the player has tho have exactly the same amount of XP as required. If s/he has more though, no level up would occur. With the changes proposed from above the <code>levelUp()</code> method can be refactored as follows, which was renamed to <code>checkCurrentXP</code> to give it a bit more clarity:</p>\n\n<pre><code>private void checkCurrentXP() {\n Integer xpRequired = null;\n do {\n xpRequired = xpPerLevel.get(curLevel);\n if (null != xpRequired) {\n if (curXP &gt;= xpRequired) {\n performLevelUp();\n }\n }\n } while (xpRequired == null || curXP &lt; xpRequired);\n}\n</code></pre>\n\n<p>This method simply retrieves the XP required for a level up based on the user's current level and checks whether the user already acquired more XP than needed for a level up and in that case invokes the <code>performLevelUp()</code> method, which is just a renamed version of <code>ding()</code>. As the level up is XP driven it may occur that a user acquired more XP than actually needed for a single level up in which cace the proposed soultion automatically would perform a second, third, ... level up as well.</p>\n\n<p>Note that I started the <code>xpPerLevel.txt</code> by the XP requirements needed to reach level 2 as the current logic would initially bump a player to level 2 automatically as 0 XP are required to reach that level. On applying these changes you basically only need to store the <code>xpPerLevel</code> map, the current level of the user as well as the gained XP on the user.</p>\n\n<p>As before with the <code>xpPerLevel</code> map, <code>ding()</code> or <code>performLevelUp()</code>, as I renamed it to, are also good candidates for a strategy pattern that allows you to define different level up behaviors for different players which can be changed during runtime i.e. to see during test time which level-up logic is more suitable if multiple candidates may exist (i.e. one strategy might reset the XP of a user after a level up was performed while an other just builds up on the old amount. Yet another strategy might refill the player's HP back to maximum and so forth). The method itself has also a lot of duplicate code, which you don't really need as you don't do anything differently from level to leve. It is therefore a strong candidate for refactoring as well:</p>\n\n<pre><code>private void performLevelUp() {\n System.out.println(\" #############################\");\n System.out.println(\" # You have reached level \" + (++curLevel) + \"! # \");\n System.out.println(\" #############################\");\n}\n</code></pre>\n\n<p>As the level of a player is dependent on the XP earned I'd remove the <code>setLevel(int level)</code> method completly. Instead I'd provide a method that allows a player to gain XP:</p>\n\n<pre><code>public void awardXP(int xpAmount) {\n curXP += xpAmount;\n checkCurrentXP();\n}\n</code></pre>\n\n<p>Right after you awarded the player with a number of XP it will automatically check the whether it lead to a level up or not and thus update the user's level accordingly.</p>\n\n<p>As hopefully can be seen, certain state, such as the player's <code>level</code> and <code>curXP</code>, is encapsulated in the player's object and through invoking methods on that player's object that state gets manipulated. This is in essence what object-oriented programming should be.</p>\n\n<p>Whithin your game loop you only need to award the player a certain amount of XP which will trigger internal state changes automatically. So there is no need to invoke <code>p.levelUp()</code> and <code>p.levelUpXp()</code> within your game loop.</p>\n\n<p>As your main-loop is basically a typical console application reading in some user input and performing some task on the input applying a <a href=\"https://dzone.com/articles/design-patterns-command\" rel=\"nofollow noreferrer\">command pattern</a> here does make the code a bit more readable. You basically refactor out your if/if-else segments into own little classes that are only focusing on that particular task. Your loop is basically responsible for too many things, which violates a bit the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a> which is further a part of <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID</a>.</p>\n\n<p>Basically what you can do to improve your code here is, i.e. introduce a new <code>EventLoop</code> class where you can register a couple of commands with it. The commands are just implementations of either an interface or abstract base class. The <code>EventLoop</code> class will store the commands within a map for a certain input command. Upon user-input the input will be parsed and the respective command invoked, if available. In Java this may look something like this:</p>\n\n<pre><code>public class EventLoop {\n\n private final Map&lt;String, ConsoleCommand&gt; registeredCommands;\n\n EventLoop() {\n reisteredCommands = new ConcurrentSkipListMap&lt;&gt;();\n }\n\n public void registerCommand(String command, ConsoleCommand action) {\n if (action == null) {\n throws new IllegalArgumentException(\"No defined action for command \" + command);\n }\n registeredCommands.put(command, action);\n }\n\n public vod unregisterCommand(String command) {\n registeredCommands.remove(command);\n }\n\n public void update(GameState state) {\n Scanner scanner = new Scanner(System.in);\n\n while(GameState.FINISHED != state.currentState()) {\n printHelp(state);\n\n String input = scanner.nextLine();\n // String input = validate(input);\n ConsoleCommand action = registeredCommands.get(input);\n if (null != action) {\n action.perform(state);\n } else {\n System.err.println(\"\\t Invalid Command!\");\n }\n }\n scanner.close();\n }\n\n private void printHelp(GameState state) {\n System.out.println(\n getPlayerInfo(state.getPlayer()) \n + \"\\n\\t\\n\\t\" \n + getEnemyInfo(state.getEnemy()));\n System.out.println(\"\\n\\t What would you like to do?\");\n for(String cmd : registeredCommands.keySet()) {\n ConsoleCommand action = registeredCommands.get(cmd);\n System.out.println(\"\\t \" + cmd + \". \" + action.printHelp());\n } \n }\n\n private String getPlayerInfo(Player player) {\n return \"\\t\" + player.getName() + \"\\n\\t HP: \" player.getHealth() + \" Level: \" + player.getCurrentLevel() + \" Exp: \" + player.getCurrentXP();\n }\n\n private String getEnemyInfo(Creature enemy) {\n return \"\\t\" + enemy.getName() + \"\\n\\t HP: \" +enemy.getHealth() + \" Level: \" + enemy.getCurrentLevel();\n }\n}\n</code></pre>\n\n<p>A <code>ConsoleCommand</code> defines now the concrete action to perform once invoked. As can be seen from the <code>EventLoop</code> two methods are at least necessary:</p>\n\n<pre><code>public interface ConsoleCommand {\n void perform(GameState state);\n String printHelp();\n}\n</code></pre>\n\n<p>If you later on decide that you want to pass certain properties to a command, you should change the interface to an abstract class and implement a method like <code>parseCommand(String input)</code> in it so that inheriting classes automatically have access to the already parsed values.</p>\n\n<p>A concrete implementation of the <code>AttackCommand</code> may now look like this</p>\n\n<pre><code>public class AttackCommand implements ConsoleCommand {\n\n private Random rand = new SecureRandom();\n\n @Override\n public String printHelp() {\n return \"Attack\"\n }\n\n @Override\n public void perform(GameState state) {\n\n Player player = state.getPlayer();\n Creature enemy = state.getEnemy();\n int damageDealt = rand.nextInt(player.getAttackDamage());\n int damageTaken = rand.nextInt(enemy.getAttackDamage());\n\n player.takeDamage(damageTaken);\n enemy.takeDamage(damageDealt);\n\n if (damageDealt &gt; 0) {\n System.out.println(\"\\t&gt; You strike the \" \n + enemy.getName() + \" for \" + damageDealt + \" damage!\");\n } else if (damageDealt &lt; 1) {\n System.out.println(\"\\t&gt; You attempt to hit the \" \n + enemy.getName() + \" but miss!\");\n }\n if (damageTaken &gt; 0) {\n System.out.println(\"\\t&gt; The \" + enemy.getName() \n + \" retaliates! You take \" + damageTaken + \" damage!\");\n } else if (damageTaken &lt; 1) {\n System.out.println(\"\\t&gt; The \" + enemy.getName() \n + \" retaliates but misses!\");\n }\n\n if (player.getHealth() &lt; 1) {\n System.out.println(\"\\t ##################\" \n + \"\\n\\t # You Have Died! #\" \n + \"\\n\\t ##################\");\n state.updateGameState(GameState.FINISHED);\n }\n\n if (enemy.getHealth() &lt; 1) {\n System.out.println(\"\\t Enemy \" + enemy.getName() \n + \" was crushed by your mighty strikes. You have been awarded with \"\n + enemy.getAmountOfXPWorthForKilling() + \" XP\";\n player.awardXP(enemy.getAmountOfXPWorthForKilling());\n }\n }\n}\n</code></pre>\n\n<p>I hope that by the presented examples it does make sense to you, that by separating the actual actions into commands the general code becomes less cluttered and therefore easily readable and understandable. You further can test an action more easily as well.</p>\n\n<p>As you might have noticed that I also changed a couple of things throughout this example. I like to have names of methods that actually do the same things on the object to be the same. So <code>player.takeDamage(int)</code> does basically the same as <code>enemy.takeDamage(int)</code>. Refactoring this behavior to a parent class would make sense here as everything has to die once it has no HP left. The difference here is though that if a player dies the game is over compared to when a creature dies the player is awarded with XP.</p>\n\n<p>Further, it is IMO a good design to refactor the overall GameState out of the actual main-loop so that it can get passed around more easily. This allows the action commands to update the game state if needed without having to perform a callback into the main-loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T08:51:37.490", "Id": "402367", "Score": "0", "body": "Thank you for not only the response but the detail within it. This answered most of my questions and concerns as well as sparked new ideas in my head and taught me a few things I didn't think of before. I do have one final follow up question though, for clarification, would `GameState` be its own class effectively becoming the `run()` method and `boolean running = true;` variable I currently have being called within the main method?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T14:42:18.520", "Id": "402403", "Score": "1", "body": "Usually games are build on top of a game engine. This game engine is a framework that provides common task done by almost every game like rendering to some output device, playing audio files, listen for inputs and pass it on to the game logic itself, physics, AI, networking, .... The more you separate each concern into its own classes the more your code will be reusable for other projects. Something like `GameEngine` sounds like a propper place for it IMO." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T14:46:20.407", "Id": "402404", "Score": "1", "body": "Note further that you could implement [`GameState` as a state machine](https://www.mirkosertic.de/blog/2013/04/implementing-state-machines-with-java-enums/) which allows you to initially render a welcome screen initially where you can select to play a new game or load a previous one, i.e. in an `INITIAL` state, and after selecting an option proceed to the new state and so forth." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T19:59:21.803", "Id": "208305", "ParentId": "208278", "Score": "4" } } ]
{ "AcceptedAnswerId": "208305", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T11:14:44.217", "Id": "208278", "Score": "8", "Tags": [ "java", "beginner", "role-playing-game" ], "Title": "Simple text-based RPG leveling system" }
208278
<p>I want to implement following trigger function in Python:</p> <p>Input:</p> <ul> <li>time vector t [n dimensional numpy vector]</li> <li>data vector y [n dimensional numpy vector] (values correspond to t vector)</li> <li>threshold tr [float]</li> <li>Threshold type vector tr_type [m dimensional list of int values]</li> </ul> <p>Output:</p> <ul> <li>Threshold time vector tr_time [m dimensional list of float values]</li> </ul> <p>Function:</p> <p>I would like to return tr_time which consists of the exact (preffered also interpolated which is not yet in code below) time values at which y is crossing tr (crossing means going from less then to greater then or the other way around). The different values in tr_time correspond to the tr_type vector: the elements of tr_type indicate the number of the crossing and if this is an upgoing or a downgoing crossing. For example 1 means first time y goes from less then tr to greater than tr, -3 means the third time y goes from greater then tr to less then tr (third time means along the time vector t)</p> <p>For the moment I have next code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def trigger(t, y, tr, tr_type): triggermarker = np.diff(1 * (y &gt; tr)) positiveindices = [i for i, x in enumerate(triggermarker) if x == 1] negativeindices = [i for i, x in enumerate(triggermarker) if x == -1] triggertime = [] for i in tr_type: if i &gt;= 0: triggertime.append(t[positiveindices[i - 1]]) elif i &lt; 0: triggertime.append(t[negativeindices[i - 1]]) return triggertime t = np.linspace(0, 20, 1000) y = np.sin(t) tr = 0.5 tr_type = [1, 2, -2] print(trigger(t, y, tr, tr_type)) plt.plot(t, y) plt.grid() </code></pre> <p>Now I'm pretty new to Python so I was wondering if there is a more Pythonic and more efficient way to implement this. For example whitout for loops or without the need to write seperate code for upgoing or downgoing crossings.</p> <p>thanks!</p>
[]
[ { "body": "<p>If <code>y</code> will always be a sine wave, then you're going about this the wrong way. Rather than calculating <code>trigger_marker</code> based on whether <code>y</code> exceeds <code>tr</code>, you should be calling <code>asin(tr)</code> to see where in the cycle the trigger will be crossed. You would then avoid the need for most of your lists and loops.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T20:33:38.660", "Id": "208310", "ParentId": "208279", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T11:38:18.390", "Id": "208279", "Score": "2", "Tags": [ "python", "numpy", "matplotlib" ], "Title": "Implementation of a threshold detection function in Python" }
208279
<p>I have an asp.net web application and I want to export to a PDF tables in a particular way.</p> <p>Tables will have data of type Test. tests have a type(by type i mean an int to tell them apart) and for every type i'm creating a TestTable and for every Test a column in each TestTable , there are 9 types. That's why there are 9 TestTables but in tests there might be for example only two different types.</p> <p>Is there a better way to do this without creating two arrays that their might be useless</p> <pre><code>public IEnumerable&lt;TestTable&gt; TestHistoryItems(GetTestExportRequest request) { IEnumerable&lt;Test&gt; tests = repository.FindBy(t =&gt; t.Visit.pid == request.PetId &amp;&amp; t.Visit.dateofvisit &gt;= request.Start &amp;&amp; t.Visit.dateofvisit &lt;= request.End).OrderByDescending(t =&gt; t.stamp); TestTable[] testTables = new TestTable[9] // all the TestTables are 9 but it might need less depending on tests { //every TestTable needs tests, of type IEnumerable&lt;Test&gt;. new TestTable(), new TestTable(), new TestTable(), new TestTable(), new TestTable(), new TestTable(), new TestTable(), new TestTable(), new TestTable() }; List&lt;Test&gt;[] testTypes = new List&lt;Test&gt;[9] { new List&lt;Test&gt;(), new List&lt;Test&gt;(), new List&lt;Test&gt;(), new List&lt;Test&gt;(), new List&lt;Test&gt;(), new List&lt;Test&gt;(), new List&lt;Test&gt;(), new List&lt;Test&gt;(), new List&lt;Test&gt;() }; foreach (Test test in tests) { switch (test.type) { case 3: GetTable(test, ref testTables[0], 3); testTypes[0].Add(test); break; case 4: GetTable(test, ref testTables[1], 4); testTypes[1].Add(test); break; case 5: GetTable(test, ref testTables[2], 5); testTypes[2].Add(test); break; case 6: GetTable(test, ref testTables[3], 6); testTypes[3].Add(test); break; case 7: GetTable(test, ref testTables[4], 7); testTypes[4].Add(test); break; case 8: GetTable(test, ref testTables[5], 8); testTypes[5].Add(test); break; case 9: GetTable(test, ref testTables[6], 9); testTypes[6].Add(test); break; case 10: GetTable(test, ref testTables[7], 10); testTypes[7].Add(test); break; case 16: GetTable(test, ref testTables[8], 16); testTypes[8].Add(test); break; } } int i = 0; foreach (TestTable test in testTables) { testTables[i].Tests = testTypes[i]; //add tests in testTables i++; } return testTables; } public void GetTable(Test test, ref TestTable table, int index) { if (table.Type != index) { table.TestName = test.TestTypeName; //One Time for every TestTable table.Type = index; //One Time for every TestTable table.Rows = test.TestDatas.Count(); //One Time for every TestTable; Rows of the table } table.Columns++; // columns are the number of tests in every TestTable } </code></pre> <p>Here is the Class TestTable.</p> <pre><code>public class TestTable { public string TestName { get; set; } public int Type { get; set; } public IEnumerable&lt;Test&gt; Tests { get; set; } public int Rows { get; set; } public int Columns { get; set; } } </code></pre> <p>The program works as expected but I think this is wrong. Can't think of a better way to do this, I'm new to coding.</p> <p>How can I make this code better?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T12:39:09.970", "Id": "402279", "Score": "2", "body": "Welcome on Code Review. The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see How do I ask a good question? for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T12:46:15.023", "Id": "402281", "Score": "1", "body": "[How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T13:06:46.083", "Id": "402282", "Score": "0", "body": "Is this better?" } ]
[ { "body": "<p>Some quick remarks:</p>\n\n<ul>\n<li><p><code>pid</code>, <code>dateofvisit</code>, <code>stamp</code>, <code>type</code> are all properties and thus should follow Microsoft's <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines\" rel=\"nofollow noreferrer\">naming guidelines</a>. Moreover \"pid\" is fairly meaningless, why not call this \"PetId\" as well?</p></li>\n<li><p><code>testTypes</code> does not convey its actual contents.</p></li>\n<li><p>Using an <code>int</code> to indicate a type is meaningless. I don't know what a test of type \"1\" is, or a \"2\". You should translate this into an <code>enum</code> with meaningful values.</p></li>\n<li><p>WRT <code>// columns are the number of tests in every TestTable</code>: why do you need this? Can't you just count the entries in the property <code>Tests</code>?</p></li>\n<li><p>Why is <code>GetTable(Test test, ref TestTable table, int index)</code> a <code>public</code> method? I doubt this is re-used elsewhere. Please apply the correct access modifier to a method, class, property, field etc.</p></li>\n</ul>\n\n<hr>\n\n<p>I find your logic hard to understand. I've tried to rewrite it, based on what I think is happening, and this is what I came up with:</p>\n\n<pre><code> public IEnumerable&lt;TestTable&gt; TestHistoryItems()\n {\n IEnumerable&lt;Test&gt; tests = // get data\n\n var testTables = new List&lt;TestTable&gt;();\n\n foreach (var testType in new int[] { 3, 4, 5, 6, 7, 8, 9, 10, 16 })\n {\n var relevantTests = tests.Where(x =&gt; x.Type == testType).ToList();\n\n if (!relevantTests.Any())\n {\n continue;\n }\n\n testTables.Add(GetTestTable(relevantTests));\n }\n\n return testTables;\n }\n\n private TestTable GetTestTable(IReadOnlyCollection&lt;Test&gt; tests)\n {\n var sampleTest = tests.First();\n return new TestTable\n {\n TestName = sampleTest.TestTypeName,\n Type = sampleTest.Type,\n Rows = sampleTest.TestDatas.Count,\n Tests = tests\n };\n }\n</code></pre>\n\n<p>You could even reduce the first method even more:</p>\n\n<pre><code> public IEnumerable&lt;TestTable&gt; TestHistoryItems()\n {\n IEnumerable&lt;Test&gt; tests = // get data\n\n return new[] { 3, 4, 5, 6, 7, 8, 9, 10, 16 }\n .Select(testType =&gt; tests.Where(x =&gt; x.Type == testType).ToList())\n .Where(relevantTests =&gt; relevantTests.Any())\n .Select(GetTestTable)\n .ToList();\n }\n</code></pre>\n\n<p>To me, this looks a lot clearer: I see there's a list of test types you filter on, and based on that you make a <code>List</code> of <code>TestTable</code>s for each type that has actual tests.</p>\n\n<p>Again: I'm not 100% sure this is what you're doing, and that's because of the convoluted way your code works. And that is a major problem: good code can almost be \"read\" as a story. When I need to spend time trying to figure out that <code>index</code> is actually a test type that you've re-purposed, etc., that's a waste of time and energy.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T08:21:53.850", "Id": "402548", "Score": "0", "body": "Thank you it was really helpful and a lot better!!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T14:18:00.403", "Id": "208285", "ParentId": "208281", "Score": "3" } }, { "body": "<p>A few observations, in addition to what BCdotWEB already pointed out:</p>\n\n<ul>\n<li>There's a fair bit of repetition in that switch statement. You're using a type ID to look up a specific <code>TestTable</code> instance, so using a <code>Dictionary</code> instead of a <code>List</code> would be more appropriate here.</li>\n<li>Using multiple collections, where objects are related to each other by index, is fairly brittle. Storing them together is safer. Changing <code>TestTable.Tests</code> to a <code>List&lt;Test&gt;</code> would help, but that may not be desirable because it allows outside modifications.</li>\n<li>All <code>TestTable</code> properties have public setters. That's often a bad idea, as it allows any code to modify them, which can put a <code>TestTable</code> instance in an invalid state. Use a constructor to ensure that an instance is created in a valid state (any required data should be passed in via arguments), and don't make properties writable if they don't need to be.</li>\n<li><code>TestTable</code> is a reference type, and <code>TestTable</code> does not reassign <code>table</code>, so there's no need to pass it by <code>ref</code>.</li>\n<li>There's a lot of 'magic numbers' in the code - numbers whose meaning is unclear. Also note that hard-coded type IDs means you'll have to modify your code whenever a new type ID needs to be added. That's not ideal.</li>\n</ul>\n\n<hr>\n\n<p>All this makes the code fairly difficult to understand, but it looks like you're simply grouping tests by their type ID, where a <code>TestTable</code> represents a collection of related tests.</p>\n\n<p>If that's the case, then your code can be simplified to the following:</p>\n\n<pre><code>var testTables = new Dictionary&lt;int, TestTable&gt;();\nforeach (var test in tests)\n{\n if (!testTables.TryGetValue(test.type, out var testTable))\n {\n // This test is the first of its kind, so create a table for it:\n testTable = new TestTable {\n TestName = test.TestTypeName,\n Type = test.type,\n Rows = test.TestDatas.Count()\n };\n testTables[test.type] = testTable;\n }\n\n // Add the test to the table (this relies on Tests being a List):\n testTable.Tests.Add(test);\n testTable.Columns += 1;\n}\nreturn testTables.Values.ToArray();\n</code></pre>\n\n<p>Or, if you're familiar with Linq:</p>\n\n<pre><code>return tests\n .GroupBy(test =&gt; test.type)\n .Select(testsGroup =&gt;\n {\n // Pick the first test from the group to determine the name and row count:\n var test = testsGroup.First();\n\n // NOTE: I'd recommend using a proper constructor here instead:\n return new TestTable {\n TestName = test.TestTypeName,\n Type = test.type,\n Rows = test.TestDatas.Count(),\n Columns = testsGroup.Count(),\n Tests = testsGroup.ToList(), // Tests does not need to be a List here\n };\n })\n .ToArray();\n</code></pre>\n\n<p>'<code>GroupBy</code>' is actually an accurate description of what you're doing here - something that was not very clear in the original code.</p>\n\n<p>Note that these alternatives do not necessarily return results in the same order. If that's important to you then just add an <code>OrderBy(table =&gt; table.Type)</code> call before the final <code>ToArray()</code> call. Also note that the result only contains <code>TestTable</code> instances for those groups that actually contain any tests. Then again, without tests you can't determine the name of a group, so I'd consider that an improvement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T11:57:46.643", "Id": "402559", "Score": "0", "body": "In the second example you're grouping for all types that exist. What if there are certain types that i want to group for example{ 3, 4, 5, 6, 7, 8, 9, 10, 16 }. How can I do that with linq? and thank your for your answer it is really helpful" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T13:15:34.220", "Id": "402564", "Score": "0", "body": "@Theo: what exactly do you mean? Do you want to ignore tests if their type doesn't match any of those values? Or do you want the result to contain a `TestTable` for each of those type values, even if there are no tests with that type?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T13:58:58.033", "Id": "402577", "Score": "0", "body": "yes, i want to ignore tests if their type doesn't match. and not create a TestTable of that type. I currently have types from 1 to 16.is it something like: `Where(x => x.Type == new int[] { 3, 4, 5, 6, 7, 8, 9, 10, 16 })`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T14:08:53.973", "Id": "402581", "Score": "0", "body": "You would put a `Where` call before the `GroupBy` call, yes, to filter out unwanted tests. Keep in mind that that predicate will be invoked for every test, so that array will be created again and again - it's better to create it once beforehand." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T15:35:21.400", "Id": "208290", "ParentId": "208281", "Score": "2" } } ]
{ "AcceptedAnswerId": "208285", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T12:07:24.640", "Id": "208281", "Score": "1", "Tags": [ "c#", "beginner", "linq-to-sql" ], "Title": "Exporting test results to PDF tables" }
208281
<p>I use a single dockerfile to build and run the following images:</p> <p><strong>Production application image:</strong></p> <pre><code>docker build -t myapplication.program -f src/MyApplication.Program/dockerfile --target runner --build-arg version=1.0.19031.1 . docker run --rm -it -e ASPNETCORE_ENVIRONMENT=local -p 5050:5050 myapplication.program:latest </code></pre> <p><strong>Unit test and code coverage image:</strong></p> <pre><code>docker build -t myapplication.tests -f src/MyApplication.Program/dockerfile --target tester . docker run --rm -it -v $PWD/codecoveragereports:/app/test/MyApplication.UnitTests/codecoveragereports myapplication.tests:latest </code></pre> <p><strong>Dockerfile:</strong></p> <pre><code># Define the base image with .NET Core SDK to enable restoring, building &amp; publishing the code. FROM microsoft/dotnet:2.1-sdk AS builder # Set working directory in the container to /app. All further actions to affect this directory. WORKDIR /app # Copy csproj files from the source (period indicating the root solution directory) to our image (period indicating working directory). COPY ./src/MyApplication.Program/MyApplication.Program.csproj ./src/MyApplication.Program/MyApplication.Program.csproj COPY ./src/MyApplication.Interfaces/MyApplication.Interfaces.csproj ./src/MyApplication.Interfaces/MyApplication.Interfaces.csproj COPY ./src/MyApplication.SignalR/MyApplication.SignalR.csproj ./src/MyApplication.SignalR/MyApplication.SignalR.csproj COPY ./src/MyApplication.Protocol/MyApplication.Protocol.csproj ./src/MyApplication.Protocol/MyApplication.Protocol.csproj COPY ./src/MyApplication.Domain/MyApplication.Domain.csproj ./src/MyApplication.Domain/MyApplication.Domain.csproj COPY ./src/MyApplication.Infrastructure/MyApplication.Infrastructure.csproj ./src/MyApplication.Infrastructure/MyApplication.Infrastructure.csproj COPY ./src/MyApplication.Services/MyApplication.Services.csproj ./src/MyApplication.Services/MyApplication.Services.csproj COPY ./src/MyApplication.Actors/MyApplication.Actors.csproj ./src/MyApplication.Actors/MyApplication.Actors.csproj # Copy nuget.config to root working directory - dotnet restore will use this. COPY nuget.config ./ # Set working directory to starting project folder. WORKDIR ./src/MyApplication.Program/ # Run dotnet package restore on all projects. RUN dotnet restore # Reset working directory back to /app WORKDIR /app # Copy all source code to image. COPY ./src ./src # Set working directory to starting project folder. WORKDIR ./src/MyApplication.Program/ # Build the main project RUN dotnet build MyApplication.Program.csproj -c Release FROM builder as tester # Set working directory in the container to /app. All further actions to affect this directory. WORKDIR /app # Copy csproj files from the source (period indicating the root solution directory) to our image (period indicating working directory). COPY ./test/MyApplication.UnitTests/MyApplication.UnitTests.csproj ./test/MyApplication.UnitTests/MyApplication.UnitTests.csproj # Set working directory to starting project folder. WORKDIR ./test/MyApplication.UnitTests/ # Run dotnet package restore on all projects. RUN dotnet restore # Reset working directory back to /app WORKDIR /app # Copy all source code to image. COPY ./test ./test # Set working directory to starting project folder. WORKDIR ./test/MyApplication.UnitTests/ # Build the main project RUN dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura # Entry point command to generate the reports ENTRYPOINT ["dotnet", "reportgenerator", "-reports:coverage.cobertura.xml", "-targetdir:codecoveragereports", "-reportTypes:htmlInline"] FROM builder as publisher # Reset working directory back to /app WORKDIR /app # Set working directory to starting project folder. WORKDIR ./src/MyApplication.Program/ # Expect an argument for the artefact version number. ARG version # Dotnet publish project. RUN dotnet publish MyApplication.Program.csproj -c Release -o publish /p:Version=$version # Define the base image with just the (lightweight) .NET Core runtime to host and run MyApplication. FROM microsoft/dotnet:2.1-aspnetcore-runtime AS runner # Set working directory in the container to /app. All further actions to affect this directory. WORKDIR /app # Copy published output from the builder image. COPY --from=publisher /app/src/MyApplication.Program/publish/ . # Listen on this port at runtime. EXPOSE 5050 # Set application entry point ENTRYPOINT ["dotnet", "MyApplication.Program.dll"] </code></pre> <p>Please code review my dockerfile. </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T14:28:40.717", "Id": "208286", "Score": "2", "Tags": [ "dockerfile", "docker" ], "Title": "Dockerfile to generate a unit test image AND a production image" }
208286
<p>One of my biggest complaints about .NET is that there's no way to guarantee a string match a certain type in the type-system.</p> <blockquote> <h3>Note</h3> <p>This started as more of a proof-of-concept than a real usable system, but I'm curious about feasibility in real-world work now, because it does seem moderately usable.</p> </blockquote> <p>That is, say I want an alpha-numeric string, or I want it to be no longer than a certain length, I have no guarantee that the string passed to a function will meet those requirements. I have to run my validation <em>each and every time</em> I call a function that needs that validity.</p> <p>This problem is a tough problem to correct, especially as <code>string</code> is <code>sealed</code>. Because we cannot inherit from a <code>string</code>, we have to build our own implementation.</p> <p>As a result, I built a simple implementation that seems to work properly, but I'm curious on any intricacies I might have missed.</p> <p>I tried to make sensible decisions for the case when certain things are null, but I'm curious on any other suggestions anyone might have for other situations that have been missed.</p> <p>It starts with the <code>ValidatedString</code> abstract class:</p> <pre><code>[JsonConverter(typeof(ValidatedStringJsonNetConverter))] public abstract class ValidatedString : IComparable, IEnumerable, IEnumerable&lt;char&gt;, IComparable&lt;string&gt;, IComparable&lt;ValidatedString&gt;, IEquatable&lt;string&gt;, IEquatable&lt;ValidatedString&gt;, IXmlSerializable { protected abstract string ErrorRequirement { get; } protected Exception Exception =&gt; new ArgumentException($&quot;The value must {ErrorRequirement}&quot;); public string String { get; private set; } public int Length =&gt; String.Length; public char this[int index] =&gt; String[index]; protected ValidatedString() { } public ValidatedString(string str) { String = Validate(str); } private string Validate(string str) =&gt; IsValid(str) ? str : throw Exception; protected abstract bool IsValid(string str); public static implicit operator string(ValidatedString str) =&gt; str?.String; public override bool Equals(object obj) =&gt; (String == null &amp;&amp; obj == null) || (String?.Equals(obj) ?? false); public override int GetHashCode() =&gt; String?.GetHashCode() ?? 0; public override string ToString() =&gt; String?.ToString(); int IComparable.CompareTo(object obj) =&gt; (String == null &amp;&amp; obj == null) ? 0 : ((IComparable)String)?.CompareTo(obj) ?? 0; IEnumerator IEnumerable.GetEnumerator() =&gt; ((IEnumerable)String)?.GetEnumerator(); public IEnumerator&lt;char&gt; GetEnumerator() =&gt; ((IEnumerable&lt;char&gt;)String?.ToCharArray()).GetEnumerator(); public int CompareTo(string other) =&gt; (String == null &amp;&amp; other == null) ? 0 : String?.CompareTo(other) ?? other.CompareTo(String); public int CompareTo(ValidatedString other) =&gt; (String == null &amp;&amp; other.String == null) ? 0 : String?.CompareTo(other.String) ?? other.String.CompareTo(String); public bool Equals(string other) =&gt; (String == null &amp;&amp; other == null) || (String?.Equals(other) ?? false); public bool Equals(ValidatedString other) =&gt; (String == null &amp;&amp; other.String == null) || (String?.Equals(other.String) ?? false); public static bool operator ==(ValidatedString a, ValidatedString b) =&gt; a.String == b.String; public static bool operator !=(ValidatedString a, ValidatedString b) =&gt; a.String != b.String; public static int Compare(ValidatedString strA, ValidatedString strB) =&gt; string.Compare(strA.String, strB.String); [SecuritySafeCritical] public static int Compare(ValidatedString strA, ValidatedString strB, StringComparison comparisonType) =&gt; string.Compare(strA.String, strB.String, comparisonType); public static int Compare(ValidatedString strA, int indexA, ValidatedString strB, int indexB, int length) =&gt; string.Compare(strA.String, indexA, strB.String, indexB, length); [SecuritySafeCritical] public static int Compare(ValidatedString strA, int indexA, ValidatedString strB, int indexB, int length, StringComparison comparisonType) =&gt; string.Compare(strA.String, indexA, strB.String, indexB, length, comparisonType); public static int CompareOrdinal(ValidatedString strA, ValidatedString strB) =&gt; string.CompareOrdinal(strA.String, strB.String); [SecuritySafeCritical] public static int CompareOrdinal(ValidatedString strA, int indexA, ValidatedString strB, int indexB, int length) =&gt; string.CompareOrdinal(strA.String, indexA, strB.String, indexB, length); public static bool Equals(ValidatedString a, ValidatedString b) =&gt; string.Equals(a.String, b.String); [SecuritySafeCritical] public static bool Equals(ValidatedString a, ValidatedString b, StringComparison comparisonType) =&gt; string.Equals(a.String, b.String, comparisonType); XmlSchema IXmlSerializable.GetSchema() =&gt; null; void IXmlSerializable.ReadXml(XmlReader reader) { var isEmpty = reader.IsEmptyElement; reader.Read(); if (isEmpty) return; String = Validate(reader.Value); } void IXmlSerializable.WriteXml(XmlWriter writer) { writer.WriteValue(String); } } </code></pre> <p>Here, we do a lot of the major work required. This is the foundation of our string validation: we build the infrastructure for it to make sure we work consistently.</p> <p>From there, it's just a matter of building an implementation. I built a second major abstract class: <code>RegexString</code>, which can be supplied with a regular expression to perform the validation:</p> <pre><code>public abstract class RegexString : ValidatedString { protected abstract string RegexValidation { get; } protected abstract bool AllowNull { get; } protected override string ErrorRequirement =&gt; $&quot;match the Regular Expression: {RegexValidation}&quot;; private Regex _regex; protected RegexString() { } public RegexString(string str) : base(str) { } protected override bool IsValid(string str) { if (_regex == null) { _regex = new Regex(RegexValidation); }; if (str == null) { return AllowNull; } return _regex.IsMatch(str); } } </code></pre> <p>That said, no one <em>has</em> to use the <code>RegexString</code>: it's trivial to build other implementations, like a <code>NonEmptyString</code>:</p> <pre><code>public class NonEmptyString : ValidatedString { protected override string ErrorRequirement =&gt; &quot;not be null, empty, or whitespace&quot;; protected NonEmptyString() { } public NonEmptyString(string str) : base(str) { } protected override bool IsValid(string str) =&gt; !string.IsNullOrWhiteSpace(str); public static explicit operator NonEmptyString(string str) =&gt; new NonEmptyString(str); } </code></pre> <p>Now obviously there's a point to all of this, and I'm getting to that now.</p> <p>In my situations, I often want to guarantee that certain strings, like a <code>username</code> or <code>email</code>, are of a certain format. Previously, to do that, I would need to add many guard-clauses at the beginning of my function to validate them all. Now, instead, I just change their type:</p> <pre><code>public class StringEmail : RegexString { protected override string ErrorRequirement =&gt; &quot;be a valid email of the format &lt;example&gt;@&lt;example&gt;.&lt;com&gt;&quot;; protected override string RegexValidation =&gt; @&quot;^.+@.+\..+$&quot;; protected override bool AllowNull =&gt; false; protected StringEmail() { } public StringEmail(string str) : base(str) { } public static explicit operator StringEmail(string str) =&gt; new StringEmail(str); } </code></pre> <p>Then I require that string type in the class:</p> <pre><code>public class Test { public StringEmail Email { get; set; } } </code></pre> <p>This allows me to guarantee that the string is validated before it is given to me. Because there are no conversions, one cannot skip the validation process. Even serialization to/from XML/JSON revalidates the string. (This is why we implement <code>IXmlSerializable</code>, and why we have a <code>ValidatedStringJsonNetConverter</code> below.)</p> <pre><code>public class ValidatedStringJsonNetConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) =&gt; writer.WriteValue((value as ValidatedString).String); public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) =&gt; Activator.CreateInstance(objectType, reader.Value); public override bool CanConvert(Type objectType) { #if NETSTANDARD_1_0 try { return Activator.CreateInstance(objectType) is ValidatedString; } catch { // If we can't make an instance it's definitely not our type return false; } #else return objectType.IsSubclassOf(typeof(ValidatedString)) || objectType == typeof(ValidatedString); #endif } } </code></pre> <p>A few other basic implementations:</p> <pre><code>public class StringAlpha : RegexString { protected override string RegexValidation =&gt; &quot;^[a-zA-Z]*$&quot;; protected override string ErrorRequirement =&gt; &quot;contain only alphabetical (a-z) characters&quot;; protected override bool AllowNull =&gt; true; protected StringAlpha() { } public StringAlpha(string str) : base(str) { } public static explicit operator StringAlpha(string str) =&gt; new StringAlpha(str); } public class StringAlphaNum : RegexString { protected override string RegexValidation =&gt; &quot;^[a-zA-Z0-9]*$&quot;; protected override string ErrorRequirement =&gt; &quot;contain only alphabetical (a-z) or numeric (0-9) characters&quot;; protected override bool AllowNull =&gt; true; protected StringAlphaNum() { } public StringAlphaNum(string str) : base(str) { } public static explicit operator StringAlphaNum(string str) =&gt; new StringAlphaNum(str); } public class StringHex : RegexString { protected override string RegexValidation =&gt; &quot;^[0-9a-fA-F]*$&quot;; protected override string ErrorRequirement =&gt; &quot;be a hexadecimal number&quot;; protected override bool AllowNull =&gt; true; protected StringHex() { } public StringHex(string str) : base(str) { } public static explicit operator StringHex(string str) =&gt; new StringHex(str); } public class StringHexPrefix : RegexString { protected override string RegexValidation =&gt; &quot;^(0x|&amp;H)?[0-9a-fA-F]*$&quot;; protected override string ErrorRequirement =&gt; &quot;be a hexadecimal number (optional 0x or &amp;H prefix)&quot;; protected override bool AllowNull =&gt; true; protected StringHexPrefix() { } public StringHexPrefix(string str) : base(str) { } public static explicit operator StringHexPrefix(string str) =&gt; new StringHexPrefix(str); } public class StringNum : RegexString { protected override string RegexValidation =&gt; &quot;^[0-9]*$&quot;; protected override string ErrorRequirement =&gt; &quot;contain only numeric (0-9) characters&quot;; protected override bool AllowNull =&gt; true; protected StringNum() { } public StringNum(string str) : base(str) { } public static explicit operator StringNum(string str) =&gt; new StringNum(str); } </code></pre> <p>And finally, some of the remaining base classes one could build from:</p> <pre><code>public abstract class String_N : RegexString { protected abstract int MaxLength { get; } protected override string RegexValidation =&gt; $&quot;^.{{0,{MaxLength}}}$&quot;; protected override string ErrorRequirement =&gt; $&quot;be no more than {MaxLength} characters&quot;; protected override bool AllowNull =&gt; true; protected String_N() { } public String_N(string str) : base(str) { } } public abstract class StringN_ : RegexString { protected abstract int MinLength { get; } protected override string RegexValidation =&gt; $&quot;^.{{{MinLength},}}$&quot;; protected override string ErrorRequirement =&gt; $&quot;be no less than {MinLength} characters&quot;; protected override bool AllowNull =&gt; true; protected StringN_() { } public StringN_(string str) : base(str) { } } public abstract class StringNN : RegexString { protected abstract int MinLength { get; } protected abstract int MaxLength { get; } protected override string RegexValidation =&gt; $&quot;^.{{{MinLength},{MaxLength}}}$&quot;; protected override string ErrorRequirement =&gt; $&quot;be between {MinLength} and {MaxLength} characters&quot;; protected override bool AllowNull =&gt; true; protected StringNN() { } public StringNN(string str) : base(str) { } } public abstract class StringWhitelist : RegexString { private const string _special = @&quot;[\^$.|?*+()&quot;; protected abstract char[] Whitelist { get; } protected override string RegexValidation =&gt; $&quot;^[{CreateWhitelist(Whitelist)}]*$&quot;; protected override string ErrorRequirement =&gt; $&quot;contain only the whitelisted characters: {CreateWhitelist(Whitelist)}&quot;; protected override bool AllowNull =&gt; true; protected StringWhitelist() { } public StringWhitelist(string str) : base(str) { } public static string CreateWhitelist(char[] whitelist) { var result = new StringBuilder(whitelist.Length); foreach (var c in whitelist) { if (_special.IndexOf(c) &gt;= 0) { result.Append($@&quot;\{c}&quot;); } else { result.Append(c); } } return result.ToString(); } } public abstract class StringWhitelist_N : StringWhitelist { protected abstract int MaxLength { get; } protected override string RegexValidation =&gt; $&quot;^[{CreateWhitelist(Whitelist)}]{{0,{MaxLength}}}$&quot;; protected override string ErrorRequirement =&gt; $&quot;be no more than {MaxLength} characters and {base.ErrorRequirement}&quot;; protected StringWhitelist_N() { } public StringWhitelist_N(string str) : base(str) { } } public abstract class StringWhitelistN_ : StringWhitelist { protected abstract int MinLength { get; } protected override string RegexValidation =&gt; $&quot;^[{CreateWhitelist(Whitelist)}]{{{MinLength},}}$&quot;; protected override string ErrorRequirement =&gt; $&quot;be no less than {MinLength} characters and {base.ErrorRequirement}&quot;; protected StringWhitelistN_() { } public StringWhitelistN_(string str) : base(str) { } } public abstract class StringWhitelistNN : StringWhitelist { protected abstract int MinLength { get; } protected abstract int MaxLength { get; } protected override string RegexValidation =&gt; $&quot;^[{StringWhitelist.CreateWhitelist(Whitelist)}]{{{MinLength},{MaxLength}}}$&quot;; protected override string ErrorRequirement =&gt; $&quot;be between {MinLength} and {MaxLength} characters and {base.ErrorRequirement}&quot;; protected StringWhitelistNN() { } public StringWhitelistNN(string str) : base(str) { } } </code></pre> <p>Another note: when using <code>Newtonsoft.Json.JsonConvert</code> or <code>System.Xml.Serialization.XmlSerializer</code>, this serializes directly to/from the raw node, this doesn't serialize the class, but strictly the string:</p> <blockquote> <pre><code>var xmlSer = new XmlSerializer(test.GetType()); byte[] buffer; using (var ms = new System.IO.MemoryStream()) { xmlSer.Serialize(ms, test); buffer = ms.GetBuffer(); } Console.WriteLine(new UTF8Encoding(false).GetString(buffer)); using (var ms = new System.IO.MemoryStream(buffer)) { var result = (Test)xmlSer.Deserialize(ms); Console.WriteLine(result.Email); } var jsonResult = JsonConvert.SerializeObject(test); Console.WriteLine(jsonResult); Console.WriteLine(JsonConvert.DeserializeObject&lt;Test&gt;(jsonResult).Email); </code></pre> </blockquote> <p>Result:</p> <blockquote> <pre><code>&lt;?xml version=&quot;1.0&quot;?&gt; &lt;Test xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot;&gt; &lt;Email&gt;ebrown@example.com&lt;/Email&gt; &lt;/Test&gt; ebrown@example.com {&quot;Email&quot;:&quot;ebrown@example.com&quot;} ebrown@example.com </code></pre> </blockquote> <p>Any commentary is welcome, but especially any commentary with regard to whether this might be safe or not to use.</p> <p>And finally, if you want to see it on GitHub: <a href="https://github.com/EBrown8534/Evbpc.Strings" rel="noreferrer">EBrown8534/Evbpc.Strings</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T16:22:27.247", "Id": "402299", "Score": "0", "body": "I like it but... there is one super important feature missing that when forgotten it makes all this effort in vain and makes most string comparisons fail... I mean **trim** - I don't know how many times something appeared to be broken only becuase some value had a leading/trailing whitespace ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T16:26:22.187", "Id": "402300", "Score": "2", "body": "@t3chb0t I actually specifically decided _not_ to implement `trim` because that can affect the validation. Instead, you would want to `whatever.String.Trim()` or what-have-you, because it's possible that people would validate against whitespace, and I don't want to negatively impact that idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T16:30:14.893", "Id": "402301", "Score": "2", "body": "ok, so it's by design - that's an explanation too even though I've never ever seen a case where a not trimmed string was desired. It was always a _bug_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T16:31:32.717", "Id": "402302", "Score": "1", "body": "@t3chb0t Yeah, I could see it being an _intentional_ case, at which point I would have made the unilateral decision to say \"you can't do that\", I'd rather have the bug where whitespace is left as-is, than omit a potential feature. (As weird as that might sound, given the nature of what we're talking about.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T17:57:22.830", "Id": "402318", "Score": "0", "body": "fine, I think one could simply derive another class from it and make it both ignore-case and trimmed..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T17:59:02.217", "Id": "402319", "Score": "0", "body": "@t3chb0t Absolutely, this is more a framework for a general use-case. :)" } ]
[ { "body": "<h2>Review</h2>\n\n<p>I find this is a very nice idea that I have <em>borrow</em> from you and while doing this I'd change a couple things to make it more mature and even more flexible.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>: IComparable, IEnumerable, IEnumerable&lt;char&gt;, IComparable&lt;string&gt;, IComparable&lt;ValidatedString&gt;, IEquatable&lt;string&gt;, IEquatable&lt;ValidatedString&gt;, IXmlSerializable\n</code></pre>\n</blockquote>\n\n<p>The base class implements a lot of interfaces which is great because it can be used in many scenarios. There are however some more of them that currently cannot be implemented. By that I mean ones that require the usage of the <code>IEqualityComparer&lt;T&gt;</code> or <code>IComparer&lt;T&gt;</code>. This means I would extract the implementations from this class and put them in two corresponding and separate comparers. Then I would reuse them with the base class to imlement the class' interfaces.</p>\n\n<hr>\n\n<p>I would also unify the naming convention to <code>SomethingString</code>. Currently it's a battle between <em>prefix</em> vs <em>suffix</em> style. I don't know whether the <code>NN</code> style is a convention but I've never seen it before so I'd probably rename it to the full name.</p>\n\n<hr>\n\n<p>The <code>StringAlphaNum</code> type should something like <code>AlphanumericAsciiString</code> becuase it won't work correctly with other cultures. For them using <code>char.IsLetter</code> and <code>char.IsDigit</code> could be more appropriate.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public static implicit operator string(ValidatedString str) =&gt; str?.String;\n</code></pre>\n</blockquote>\n\n<p>This might be a source of weird bugs so I would definitely make it <code>explicit</code> because otherwise it's very easy to loose the validation when it invisibly gets converted into a <code>string</code>. To me it's like converting <code>double</code> to <code>int</code>. The <code>ValidatedString</code> is stripped off of its additional functionality so it should be an intentional act. Not something that happens <em>somewhere</em> automatically.</p>\n\n<hr>\n\n<h2>Alternative design</h2>\n\n<p>I'd like to suggest a different approach that makes it possible to combine powers of various validations. The following code is ony a model and a rough proof-of-concept so please don't be too harsh with it.</p>\n\n<p>In this design there is only <em>one</em> base class with different generic <em>overloads</em>. I think we actually don't need more then two or three of them. I created only to for this example.</p>\n\n<p>The <code>T</code> of each class is a simple interface that should be implemented by validations:</p>\n\n<pre><code>public interface IStringValidation\n{\n bool IsValid(string value);\n}\n</code></pre>\n\n<p>They can be used to pass them as arguments for method parameters:</p>\n\n<pre><code>void Main()\n{\n //Do1(string.Empty); // boom! = NotNullOrWhitespaceException\n Do1(\"abc\");\n //Do2(\"abc\"); // boom! = MinLength10Exception\n Do2(\"1234567890\");\n\n //Do3(\"1234567890X\"); // boom! = HexException\n Do3(\"1234567890\");\n}\n\npublic static void Do1(SafeString&lt;NotNullOrWhitespace&gt; value)\n{\n\n}\n\npublic static void Do2(SafeString&lt;NotNullOrWhitespace, MinLength10&gt; value)\n{\n\n}\n\npublic static void Do3(SafeString&lt;NotNullOrWhitespace, MinLength10, Hex&gt; value)\n{\n\n}\n</code></pre>\n\n<p>And here's the actual very general and basic implementation of the first class:</p>\n\n<pre><code>public class SafeString&lt;T&gt;\n where T : IStringValidation, new()\n{\n private readonly string _value;\n\n protected readonly IEnumerable&lt;IStringValidation&gt; _validations;\n\n private SafeString(string value)\n {\n _validations = new IStringValidation[] { new T() };\n _value = Validate(value);\n }\n\n protected SafeString(string value, params IStringValidation[] validations)\n {\n _validations = new IStringValidation[] { new T() }.Concat(validations);\n _value = Validate(value);\n }\n\n protected string Validate(string value)\n {\n return\n _validations.FirstOrDefault(v =&gt; !v.IsValid(value)) is var failed &amp;&amp; failed is null\n ? value\n : throw DynamicException.Create(failed.GetType().Name, \"Ooops!\");\n }\n\n public static implicit operator SafeString&lt;T&gt;(string value) =&gt; new SafeString&lt;T&gt;(value);\n}\n</code></pre>\n\n<p>and two more of these that extend it with further <code>T</code>s and reuse the previous one:</p>\n\n<pre><code>public class SafeString&lt;T1, T2&gt; : SafeString&lt;T1&gt;\n where T1 : IStringValidation, new()\n where T2 : IStringValidation, new()\n{\n private SafeString(string value) : base(value, new T2()) { }\n\n protected SafeString(string value, IStringValidation validation) : base(value, new T2(), validation) { }\n\n public static implicit operator SafeString&lt;T1, T2&gt;(string value) =&gt; new SafeString&lt;T1, T2&gt;(value);\n}\n\npublic class SafeString&lt;T1, T2, T3&gt; : SafeString&lt;T1, T2&gt;\n where T1 : IStringValidation, new()\n where T2 : IStringValidation, new()\n where T3 : IStringValidation, new()\n{\n private SafeString(string value) : base(value, new T3()) { }\n\n public static implicit operator SafeString&lt;T1, T2, T3&gt;(string value) =&gt; new SafeString&lt;T1, T2, T3&gt;(value);\n}\n</code></pre>\n\n<p>I've created three example implementations that look like this:</p>\n\n<pre><code>public class NotNullOrWhitespace : IStringValidation\n{\n public bool IsValid(string value) =&gt; !string.IsNullOrWhiteSpace(value);\n}\n\npublic abstract class MinLengthValidation : IStringValidation\n{\n private readonly int _minLength;\n\n protected MinLengthValidation(int minLength)\n {\n _minLength = minLength;\n }\n\n public bool IsValid(string value) =&gt; value.Length &gt;= _minLength;\n}\n\npublic class MinLength10 : MinLengthValidation\n{\n public MinLength10() : base(10) { }\n}\n\npublic abstract class RegexValidation : IStringValidation\n{\n protected abstract string Pattern { get; }\n\n private readonly Lazy&lt;Regex&gt; _regex;\n\n protected RegexValidation()\n {\n _regex = Lazy.Create(() =&gt; new Regex(Pattern));\n }\n\n public bool IsValid(string value) =&gt; _regex.Value.IsMatch(value);\n}\n\npublic class Hex : RegexValidation\n{\n protected override string Pattern =&gt; \"^[0-9a-fA-F]*$\";\n}\n</code></pre>\n\n<p>I find it's more flexible this way and the user can better see which validations are going to be made like here:</p>\n\n<blockquote>\n<pre><code>SafeString&lt;NotNullOrWhitespace, MinLength10, Hex&gt;\n</code></pre>\n</blockquote>\n\n<p>The string will be validated from left to right - in the same order as the generic parameters.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T20:13:55.070", "Id": "402342", "Score": "0", "body": "Not sure what you're getting at with the last point, can you expand on that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T20:49:37.553", "Id": "402345", "Score": "0", "body": "@202_accepted me either ;-] I removed this point and added an alternative design instead. Sorry for the confusion. I'm not sure what I was thinking about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T20:50:53.317", "Id": "402346", "Score": "0", "body": "@HenrikHansen what do you think about my alternative design? ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T06:47:36.413", "Id": "402363", "Score": "0", "body": "@t3chb0t: That's just nice - flexible for both subclassing and generic use. Is there a reason why the `_value` field isn't made public through a property: `public string Value => _value;`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T08:05:25.273", "Id": "402365", "Score": "1", "body": "@HenrikHansen nope, there is no particular reason for that. It's just a quick'n'dirty example for what is possible. There is a great deal of other features missing too that have to be implemented before it's production ready. I just wanted to to show a different point of view. It's intentionally not complete." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T11:47:39.487", "Id": "402393", "Score": "2", "body": "Regarding implicit conversion to `string`: any `ValidatedString` is a valid `string` value, just like how any `int` value is a valid `double` value. I'd say that makes it similar to converting an `int` to a `double`, not the other way around." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T03:03:35.933", "Id": "402525", "Score": "0", "body": "@PieterWitvoet That's exactly my thought -- I see this as a down-type of string, so the \"upward\" conversion should be transparent. If `String` weren't `sealed` I would have inherited it and done away with the operator." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-07T14:46:51.083", "Id": "404344", "Score": "0", "body": "@t3chb0t Decided to use the opposite naming convention, but still standardize them all: `String<whatever>`, because I want them to be grouped together in intellisense and such." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T18:19:01.897", "Id": "208301", "ParentId": "208291", "Score": "11" } }, { "body": "<p>I would call the actual String property <code>Value</code> instead of <code>String</code>, it will improve readability.</p>\n\n<hr>\n\n<p>Maybe you want to mark it as <code>serializable</code>?</p>\n\n<hr>\n\n<p>The String property should be immutable: <code>public string Value { get; }</code></p>\n\n<hr>\n\n<blockquote>\n<pre><code>public IEnumerator&lt;char&gt; GetEnumerator() =&gt; ((IEnumerable&lt;char&gt;)String?.ToCharArray()).GetEnumerator(); // HH: Why ?.ToCharArray()\n</code></pre>\n</blockquote>\n\n<p>Why do you call <code>ToCharArray()</code>?</p>\n\n<p>Why not just:</p>\n\n<pre><code>public IEnumerator&lt;char&gt; GetEnumerator() =&gt; String?.GetEnumerator(); \n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>protected override string ErrorRequirement =&gt; \"contain only alphabetical (a-z) characters\";\n</code></pre>\n</blockquote>\n\n<p>I'm not a fan of this <code>ErrorRequirement</code>. It is IMO only useful when debugging, and it's hard (read: impossible) to localize. A specialized <code>Exception</code> would be better (ex: <code>InvalidEmailFormatException</code>)</p>\n\n<hr>\n\n<p>Here I'm just thinking loud:</p>\n\n<p>Maybe I would not make the <code>base class</code> <code>abstract</code> and inject a validator interface and/or delegate into the constructor in a way like this:</p>\n\n<pre><code> public interface IStringValidator\n {\n string Validate(string value);\n }\n\n public class ValidatedString\n : IEnumerable&lt;char&gt; /* etc. */\n {\n public ValidatedString(string value, IStringValidator validator)\n {\n Value = validator.Validate(value);\n }\n\n public ValidatedString(string value, Func&lt;string, string&gt; validator)\n {\n Value = validator(value);\n }\n\n public string Value { get; }\n public int Length =&gt; Value.Length;\n public char this[int index] =&gt; Value[index];\n\n public IEnumerator&lt;char&gt; GetEnumerator()\n {\n return Value?.GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n }\n</code></pre>\n\n<p>Notice that here it's the responsibility of the derived class to react on invalidity in the validator. It makes it possible for the derived class to make the string value valid before sending it back to base class or throw an exception (dedicated).</p>\n\n<p>In the above, you're still free to derive from it, but also use it more freely in more rare places where a specialized subclass is overkill. </p>\n\n<p>The danger with all these sub classes is that over time you forget about them and invent them once and again.</p>\n\n<hr>\n\n<p>Example of subclass:</p>\n\n<pre><code> public class EmailValidator : IStringValidator\n {\n public string Validate(string value)\n {\n\n if (!Regex.IsMatch(value, @\"^.+@.+\\..+$\"))\n throw new ArgumentException(\"invalid email format\");\n\n return value;\n }\n }\n\n\n public class EmailString : ValidatedString\n {\n public EmailString(string value) : base(value, new EmailValidator())\n {\n\n }\n\n public static implicit operator EmailString(string email)\n {\n return new EmailString(email);\n }\n }\n\n\n SendEmail(\"email@example.com\");\n\n void SendEmail(EmailString email)\n {\n Console.WriteLine(email);\n }\n</code></pre>\n\n<hr>\n\n<p>Just another idea:</p>\n\n<p>You could easily make a generic super class to <code>ValidatedString</code>:</p>\n\n<pre><code> public abstract class ValidatedValue&lt;TValue&gt;\n {\n public ValidatedValue()\n {\n\n }\n\n public ValidatedValue(TValue value)\n {\n\n }\n\n protected abstract string ErrorRequirement { get; }\n protected Exception Exception =&gt; new ArgumentException($\"The value must {ErrorRequirement}\");\n\n private TValue Validate(TValue value) =&gt; IsValid(value) ? value : throw Exception;\n\n protected abstract bool IsValid(TValue value);\n\n public TValue Value { get; }\n }\n</code></pre>\n\n<p>And let <code>ValidatedString</code> inherit from that.</p>\n\n<p>That would make it possible to create validated objects from every possible type like <code>DateTime</code>:</p>\n\n<pre><code> public class HistoryTime : ValidatedValue&lt;DateTime&gt;\n {\n public HistoryTime(DateTime value) : base(value)\n {\n\n }\n\n protected override string ErrorRequirement =&gt; \"be in the past\";\n\n protected override bool IsValid(DateTime value)\n {\n return value &lt; DateTime.Now;\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T18:27:38.867", "Id": "402325", "Score": "1", "body": "I actually wanted to mark it `Serializable`, but I'm struggling to do that with .NET Standard 1.3. Looks like that's something Microsoft wants to move away from." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T18:36:12.373", "Id": "402327", "Score": "0", "body": "@202_accepted: It could well be." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T19:10:33.887", "Id": "402330", "Score": "0", "body": "Making the base class non-abstract and letting it accept an interface would make it impossible to use it for implicit casting into this type when using as a parameter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T19:17:39.100", "Id": "402332", "Score": "0", "body": "@t3chb0t: I don't see your point. Implicit conversion to string works for method parameters, but that's maybe not, what you mean?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T19:20:42.843", "Id": "402333", "Score": "1", "body": "I mean turning a `string` into a `ValidatedString` won't work, e.g: `void SendEmail(EmailString email)` and called like that `x.SendEmail(\"abc@example.com\")` - you would not be able to implicitly cast the string so that it's automatically validated. This is where I see the main use case for it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T19:35:54.400", "Id": "402336", "Score": "0", "body": "@t3chb0t: No, of course, but that applies to OP base class as well. What you suggest requires an `implict string operator` on `StringEmail` as my update shows." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T20:08:03.557", "Id": "402341", "Score": "0", "body": "@HenrikHansen Just as a note: `String` (which I'm changing to `Value` in the GitHub -- I like that idea) cannot be immutable in my version because XML Serialization cannot use the constructor (the `IXmlSerializable.ReadXml`), so I _have_ to have it `private`ly mutable. Otherwise, the plan was to make it an auto-implemented read-only property." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T20:44:07.637", "Id": "402344", "Score": "0", "body": "@202_accepted: You can change the `Value` property to `public readonly string Value` and then set it in `ReadXml()` as: `this.GetType().GetField(\"String\").SetValue(this, Validate(reader.Value));`, but that maybe gives some unexpected behavior elsewhere..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-07T14:35:24.003", "Id": "404341", "Score": "0", "body": "@HenrikHansen Been thinking about that last comment for some time, I don't think I want to use reflection there, as I think that will have some performance costs and I'm trying to keep things as simple as possible. :/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-07T17:41:27.673", "Id": "404368", "Score": "0", "body": "@202_accepted: I can easily follow you, I always try to avoid reflection, and in fact nearly never use it." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T18:26:24.123", "Id": "208303", "ParentId": "208291", "Score": "10" } } ]
{ "AcceptedAnswerId": "208301", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T16:12:26.620", "Id": "208291", "Score": "18", "Tags": [ "c#", "strings", ".net", "validation", "type-safety" ], "Title": "Enforcing string validity with the C# type system" }
208291
<p>A ring buffer or circular buffer is a fixed sized queue that advances head and tail pointers in a modulo manner rather than moving the data. Ring buffers are often used in embedded computer design.</p> <p>This implementation of a c++14 compatible Ring Buffer that was inspired by a <a href="https://accu.org/index.php/journals/389" rel="noreferrer">Pete Goodliffe's ACCU article</a> and the <a href="https://www.cs.northwestern.edu/~riesbeck/programming/c++/stl-iterator-define.html" rel="noreferrer">Chris Riesbeck web page</a>.</p> <p>As a hobbyist programmer, I started this project so I could learn some more about using templates. I intentionally avoided allocators since I don’t fully understand them (yet). I also did not attempt “emplace_back” for the same reason, but would love to learn about this. I used default copy/move constructors. Any suggestions or feedback that I can get about style, design and completeness of class will be appreciated. I believe that the iterator is basically STL compatible, but I would enjoy feedback on this aspect of the project as well.</p> <pre><code>#pragma once #include &lt;iostream&gt; #include &lt;exception&gt; #include &lt;cassert&gt; #include &lt;vector&gt; #include &lt;initializer_list&gt; template &lt;class T&gt; class ring { using value_type = T; using reference = T &amp; ; using const_reference = const T &amp;; using size_type = size_t; using circularBuffer = std::vector&lt;value_type&gt;; circularBuffer m_array; size_type m_head; size_type m_tail; size_type m_contents_size; const size_type m_array_size; public: ring(size_type size = 8) : m_array(size), m_array_size(size), m_head(1), m_tail(0), m_contents_size(0) { assert(m_array_size &gt; 1 &amp;&amp; "size must be greater than 1"); } ring(std::initializer_list&lt;T&gt; l) :m_array(l), m_array_size(l.size()), m_head(0), m_tail(l.size() - 1), m_contents_size(l.size()) { assert(m_array_size &gt; 1 &amp;&amp; "size must be greater than 1"); } template &lt;bool isconst&gt; struct my_iterator; reference front() { return m_array[m_head]; } reference top() { return front(); } reference back() { return m_array[m_tail]; } const_reference front() const { return m_array[m_head]; } const_reference back() const { return m_array[m_tail]; } void clear(); void push_back(const value_type &amp;item); void push(const value_type &amp;item) { push_back(item); } void pop_front() { increment_head(); } void pop() { pop_front(); } size_type size() const { return m_contents_size; } size_type capacity() const { return m_array_size; } bool empty() const; bool full() const; size_type max_size() const { return size_type(-1) / sizeof(value_type); } reference operator[](size_type index); const_reference operator[](size_type index) const; reference at(size_type index); const_reference at(size_type index) const; using iterator = my_iterator&lt;false&gt;; using const_iterator = my_iterator&lt;true&gt;; iterator begin(); const_iterator begin() const; const_iterator cbegin() const; iterator rbegin(); const_iterator rbegin() const; iterator end(); const_iterator end() const; const_iterator cend() const; iterator rend(); const_iterator rend() const; private: void increment_tail(); void increment_head(); template &lt;bool isconst = false&gt; struct my_iterator { using iterator_category = std::random_access_iterator_tag; using difference_type = long long; using reference = typename std::conditional_t&lt; isconst, T const &amp;, T &amp; &gt;; using pointer = typename std::conditional_t&lt; isconst, T const *, T * &gt;; using vec_pointer = typename std::conditional_t&lt;isconst, std::vector&lt;T&gt; const *, std::vector&lt;T&gt; *&gt;; private: vec_pointer ptrToBuffer; size_type offset; size_type index; bool reverse; bool comparable(const my_iterator &amp; other) { return (reverse == other.reverse); } public: my_iterator() : ptrToBuffer(nullptr), offset(0), index(0), reverse(false) {} // my_iterator(const ring&lt;T&gt;::my_iterator&lt;false&gt;&amp; i) : ptrToBuffer(i.ptrToBuffer), offset(i.offset), index(i.index), reverse(i.reverse) {} reference operator*() { if (reverse) return (*ptrToBuffer)[(ptrToBuffer-&gt;size() + offset - index) % (ptrToBuffer-&gt;size())]; return (*ptrToBuffer)[(offset+index)%(ptrToBuffer-&gt;size())]; } reference operator[](size_type index) { my_iterator iter = *this; iter.index += index; return *iter; } pointer operator-&gt;() { return &amp;(operator *()); } my_iterator&amp; operator++ () { ++index; return *this; }; my_iterator operator ++(int) { my_iterator iter = *this; ++index; return iter; } my_iterator&amp; operator --() { --index; return *this; } my_iterator operator --(int) { my_iterator iter = *this; --index; return iter; } friend my_iterator operator+(my_iterator lhs, int rhs) { lhs.index += rhs; return lhs; } friend my_iterator operator+(int lhs, my_iterator rhs) { rhs.index += lhs; return rhs; } my_iterator&amp; operator+=(int n) { index += n; return *this; } friend my_iterator operator-(my_iterator lhs, int rhs) { lhs.index -= rhs; return lhs; } friend difference_type operator-(const my_iterator&amp; lhs, const my_iterator&amp; rhs) { lhs.index -= rhs; return lhs.index - rhs.index; } my_iterator&amp; operator-=(int n) { index -= n; return *this; } bool operator==(const my_iterator &amp;other) { if (comparable(other)) return (index + offset == other.index + other.offset); return false; } bool operator!=(const my_iterator &amp;other) { if (comparable(other)) return !this-&gt;operator==(other); return true; } bool operator&lt;(const my_iterator &amp;other) { if(comparable(other)) return (index + offset &lt; other.index + other.offset); return false; } bool operator&lt;=(const my_iterator &amp;other) { if(comparable(other)) return (index + offset &lt;= other.index + other.offset); return false; } bool operator &gt;(const my_iterator &amp;other) { if (comparable(other)) return !this-&gt;operator&lt;=(other); return false; } bool operator&gt;=(const my_iterator &amp;other) { if (comparable(other)) return !this-&gt;operator&lt;(other); return false; } friend class ring&lt;T&gt;; }; }; template&lt;class T&gt; void ring&lt;T&gt;::push_back(const value_type &amp; item) { increment_tail(); if (m_contents_size &gt; m_array_size) increment_head(); // &gt; full, == comma m_array[m_tail] = item; } template&lt;class T&gt; void ring&lt;T&gt;::clear() { m_head = 1; m_tail = m_contents_size = 0; } template&lt;class T&gt; bool ring&lt;T&gt;::empty() const { if (m_contents_size == 0) return true; return false; } template&lt;class T&gt; inline bool ring&lt;T&gt;::full() const { if (m_contents_size == m_array_size) return true; return false; } template&lt;class T&gt; typename ring&lt;T&gt;::const_reference ring&lt;T&gt;::operator[](size_type index) const { index += m_head; index %= m_array_size; return m_array[index]; } template&lt;class T&gt; typename ring&lt;T&gt;::reference ring&lt;T&gt;::operator[](size_type index) { const ring&lt;T&gt;&amp; constMe = *this; return const_cast&lt;reference&gt;(constMe.operator[](index)); // return const_cast&lt;reference&gt;(static_cast&lt;const ring&lt;T&gt;&amp;&gt;(*this)[index]); } //*/ template&lt;class T&gt; typename ring&lt;T&gt;::reference ring&lt;T&gt;::at(size_type index) { if (index &lt; m_contents_size) return this-&gt;operator[](index); throw std::out_of_range("index too large"); } template&lt;class T&gt; typename ring&lt;T&gt;::const_reference ring&lt;T&gt;::at(size_type index) const { if (index &lt; m_contents_size) return this-&gt;operator[](index); throw std::out_of_range("index too large"); } template&lt;class T&gt; typename ring&lt;T&gt;::iterator ring&lt;T&gt;::begin() { iterator iter; iter.ptrToBuffer = &amp;m_array; iter.offset = m_head; iter.index = 0; iter.reverse = false; return iter; } template&lt;class T&gt; typename ring&lt;T&gt;::const_iterator ring&lt;T&gt;::begin() const { const_iterator iter; iter.ptrToBuffer = &amp;m_array; iter.offset = m_head; iter.index = 0; iter.reverse = false; return iter; } template&lt;class T&gt; typename ring&lt;T&gt;::const_iterator ring&lt;T&gt;::cbegin() const { const_iterator iter; iter.ptrToBuffer = &amp;m_array; iter.offset = m_head; iter.index = 0; iter.reverse = false; return iter; } template&lt;class T&gt; typename ring&lt;T&gt;::iterator ring&lt;T&gt;::rbegin() { iterator iter; iter.ptrToBuffer = &amp;m_array; iter.offset = m_tail; iter.index = 0; iter.reverse = true; return iter; } template&lt;class T&gt; typename ring&lt;T&gt;::const_iterator ring&lt;T&gt;::rbegin() const { const_iterator iter; iter.ptrToBuffer = &amp;m_array; iter.offset = m_tail; iter.index = 0; iter.reverse = true; return iter; } template&lt;class T&gt; typename ring&lt;T&gt;::iterator ring&lt;T&gt;::end() { iterator iter; iter.ptrToBuffer = &amp;m_array; iter.offset = m_head; iter.index = m_contents_size; iter.reverse = false; return iter; } template&lt;class T&gt; typename ring&lt;T&gt;::const_iterator ring&lt;T&gt;::end() const { const_iterator iter; iter.ptrToBuffer = &amp;m_array; iter.offset = m_head; iter.index = m_contents_size; iter.reverse = false; return iter; } template&lt;class T&gt; typename ring&lt;T&gt;::const_iterator ring&lt;T&gt;::cend() const { const_iterator iter; iter.ptrToBuffer = &amp;m_array; iter.offset = m_head; iter.index = m_contents_size; iter.reverse = false; return iter; } template&lt;class T&gt; typename ring&lt;T&gt;::iterator ring&lt;T&gt;::rend() { iterator iter; iter.ptrToBuffer = &amp;m_array; iter.offset = m_tail; iter.index = m_contents_size; iter.reverse = true; return iter; } template&lt;class T&gt; typename ring&lt;T&gt;::const_iterator ring&lt;T&gt;::rend() const { const_iterator iter; iter.ptrToBuffer = &amp;m_array; iter.offset = m_tail; iter.index = m_contents_size; iter.reverse = true; return iter; } template&lt;class T&gt; void ring&lt;T&gt;::increment_tail() { ++m_tail; ++m_contents_size; if (m_tail == m_array_size) m_tail = 0; } template&lt;class T&gt; void ring&lt;T&gt;::increment_head() { if (m_contents_size == 0) return; ++m_head; --m_contents_size; if (m_head == m_array_size) m_head = 0; } </code></pre> <p>Here is the code that I used to test stuff out.</p> <pre><code>int main() { ring&lt;int&gt; mybuf(10); for (size_t i = 0; i &lt; 20; ++i) { mybuf.push(i); for (auto i = mybuf.begin(); i != mybuf.end(); ++i) cout &lt;&lt; *i &lt;&lt; ": "; if (mybuf.full()) cout &lt;&lt; "full"; cout &lt;&lt; '\n'; } cout &lt;&lt; "Buffer Size: " &lt;&lt; mybuf.size() &lt;&lt; '\n'; for (size_t i = 0; i &lt; mybuf.size() + 1; ++i) { try { cout &lt;&lt; mybuf.at(i) &lt;&lt; ": "; } catch (std::exception e) { cout &lt;&lt; e.what() &lt;&lt; '\n'; continue; } } cout &lt;&lt; '\n'; auto start = mybuf.begin(); start += 1; cout &lt;&lt; "start++: " &lt;&lt; *start &lt;&lt; '\n'; ring&lt;int&gt;::const_iterator cstart(start); cout &lt;&lt; "cstart(start)++: " &lt;&lt; *(++cstart) &lt;&lt; '\n'; cout &lt;&lt; "--start: " &lt;&lt; *(--start) &lt;&lt; '\n'; if (start == mybuf.begin()) cout &lt;&lt; "Start is mybuf.begin\n"; else cout &lt;&lt; "Lost!\n"; cout &lt;&lt; "Push!\n"; mybuf.push(100); if (start == mybuf.begin()) cout &lt;&lt; "In the begining :-)\n"; else cout &lt;&lt; "Start is no longer mybuf.begin\n"; start = mybuf.begin(); cout &lt;&lt; "after push, start: " &lt;&lt; *start &lt;&lt; '\n'; cout &lt;&lt; "forwards: "; for (auto i = mybuf.begin(); i &lt; mybuf.end(); i+=2) cout &lt;&lt; *i &lt;&lt; ": "; cout &lt;&lt; '\n'; cout &lt;&lt; "backwards: "; for (auto i = mybuf.rbegin(); i &lt; mybuf.rend(); i+=2) cout &lt;&lt; *i &lt;&lt; ": "; cout &lt;&lt; '\n'; cout &lt;&lt; "mybuf[0]: "&lt;&lt;mybuf[0] &lt;&lt; " " &lt;&lt; "\nPush!\n\n"; mybuf.push(20); for (size_t i = 0; i &lt; mybuf.size(); ++i) cout &lt;&lt; mybuf[i] &lt;&lt; ": "; cout &lt;&lt; '\n'; cout &lt;&lt; "pop: " &lt;&lt; mybuf.top() &lt;&lt; '\n'; mybuf.pop(); cout &lt;&lt; "new front: " &lt;&lt; mybuf[0] &lt;&lt; " new size: "; cout &lt;&lt; mybuf.size() &lt;&lt; '\n'; cstart = mybuf.end(); cout &lt;&lt; "last: " &lt;&lt; *(--cstart) &lt;&lt; '\n'; for (auto i = mybuf.begin(); i != mybuf.end(); ++i) cout &lt;&lt; *i &lt;&lt; ": "; cout &lt;&lt; '\n'; cout &lt;&lt; "pop again: " &lt;&lt; mybuf.front() &lt;&lt; '\n'; mybuf.pop(); cstart = mybuf.rbegin(); cout &lt;&lt; "last: " &lt;&lt; *cstart &lt;&lt; '\n'; for (auto i = mybuf.begin(); i != mybuf.end(); ++i) cout &lt;&lt; *i &lt;&lt; ": "; cout &lt;&lt; "\n\nclone: "; ring&lt;int&gt; cbuf(mybuf); for (auto i = std::find(mybuf.begin(),mybuf.end(),100); i != cbuf.end(); ++i) cout &lt;&lt; *i &lt;&lt; ": "; auto iter = cbuf.cbegin(); cout &lt;&lt; "\nbegin[3] = " &lt;&lt; iter[3]; cout &lt;&lt; '\n' &lt;&lt; '\n'; cout &lt;&lt; "Hello World!\n"; } </code></pre> <p>And this is the output from that test.</p> <pre><code>0: 0: 1: 0: 1: 2: 0: 1: 2: 3: 0: 1: 2: 3: 4: 0: 1: 2: 3: 4: 5: 0: 1: 2: 3: 4: 5: 6: 0: 1: 2: 3: 4: 5: 6: 7: 0: 1: 2: 3: 4: 5: 6: 7: 8: 0: 1: 2: 3: 4: 5: 6: 7: 8: 9: full 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: full 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: full 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: full 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: full 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: full 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: full 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: full 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: full 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: full 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: full Buffer Size: 10 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: index too large start++: 11 cstart(start)++: 12 --start: 10 Start is mybuf.begin Push! Start is no longer mybuf.begin after push, start: 11 forwards: 11: 13: 15: 17: 19: backwards: 100: 18: 16: 14: 12: mybuf[0]: 11 Push! 12: 13: 14: 15: 16: 17: 18: 19: 100: 20: pop: 12 new front: 13 new size: 9 last: 20 13: 14: 15: 16: 17: 18: 19: 100: 20: pop again: 13 last: 20 14: 15: 16: 17: 18: 19: 100: 20: clone: 100: 20: begin[3] = 17 Hello World! </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T21:41:23.873", "Id": "402431", "Score": "0", "body": "I modified my review, adding *some* more things, in fact there's a lot of fix to apply :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-09T22:51:30.940", "Id": "488278", "Score": "0", "body": "class `ring` is not movable, because it has `const` member." } ]
[ { "body": "<h2>Coding idiomatically</h2>\n\n<ul>\n<li><strong>Remember that <a href=\"https://en.wikipedia.org/wiki/Pragma_once\" rel=\"nofollow noreferrer\"><code>#pragma once</code></a> isn't standard (unlike <a href=\"https://en.wikipedia.org/wiki/Include_guard\" rel=\"nofollow noreferrer\">include guards</a>).</strong>\n\n<ul>\n<li>If you only intend your class works on major compilers, you can use <code>#pragma once</code> (but care about <a href=\"//stackoverflow.com/a/26908048/2644192\">defects</a> and <a href=\"//stackoverflow.com/a/34884735/2644192\">drawbacks</a>)</li>\n<li>If you wish your class works on all compilers, <a href=\"https://stackoverflow.com/a/1144110/2644192\">use both <code>#pragma once</code> and the include guards</a>.</li>\n<li>If you want your class to be 100% compatible with standards, use only include guards.</li>\n<li>For completeness, I have to mention <a href=\"//stackoverflow.com/questions/2233401/\">redundant include guards</a> too, which you could combine (or not) with <code>#pragma once</code>.</li>\n</ul></li>\n<li><strong>Don't misspell <code>size_t</code></strong>\n\n<ul>\n<li>You should use the full qualified <code>std::size_t</code> instead of just <code>size_t</code>, because <a href=\"https://stackoverflow.com/questions/5813700/difference-between-size-t-and-stdsize-t\">it's the standard way to go</a>.</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<h2>Coding with style</h2>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/308581/how-should-i-order-the-members-of-a-c-class/308592\"><strong>Try to put <code>public</code> members first</strong></a> <strong>(primarily a matter of personal preference)</strong>\n\n<ul>\n<li>That makes your interface more explicit.</li>\n<li>When users read your header file, they directly know what your class does.</li>\n<li>That's what is adopted in a lot of coding standards (<a href=\"https://google.github.io/styleguide/cppguide.html#Declaration_Order\" rel=\"nofollow noreferrer\">google</a>, <a href=\"https://gcc.gnu.org/wiki/CppConventions#C.2B-.2B-_Coding_Conventions\" rel=\"nofollow noreferrer\">gcc</a>, ...)</li>\n</ul></li>\n<li><strong>Be consistent</strong>\n\n<ul>\n<li>In your methods' order (e.g. you shuffled <code>front</code>/<code>back</code> overloads )</li>\n<li>In your spacing (e.g. look at your <code>operator</code>s' definitions)</li>\n<li>In your members initialization alignment (It's really odd how you place the first member init on the same line that constructors signature, and other at the line, aligned with asserts)</li>\n<li>In your naming (Why are all types \"<code>snake_case</code>\" but <code>circularBuffer</code> is \"<code>camelCased</code>\"?)</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<h2>Design choices</h2>\n\n<ul>\n<li><p><strong>Type aliases</strong></p>\n\n<p>Why are the member type aliases (<code>value_type</code>, <code>reference</code>, ...) made private?</p></li>\n<li><p><strong>Naming</strong></p>\n\n<p>Use explicit name (<code>ring_iterator</code> instead of <code>my_iterator</code>, <code>container_type</code> instead of <code>circularBuffer</code>). Avoid useless function aliases (<code>pop_front()</code>, <code>push_back()</code>, <code>top()</code>).</p></li>\n<li><p><strong>Reconsider methods</strong></p>\n\n<p>Are <code>increment_head()</code>, <code>increment_tail()</code> or <code>full()</code> are really useful?</p></li>\n<li><p><strong>Consider computing <code>size</code> at compile time</strong></p>\n\n<p>If you don't need to allow <code>size</code> to be computed at runtime, consider making it <code>constexpr</code> or template parameter. It will allow some optimizations.</p></li>\n<li><p><strong>Maybe an oversight</strong></p>\n\n<p>Where are <code>crbegin</code>/<code>crend</code> ? Did you forget them? And what about <code>swap</code> or a <code>max_size</code> method?</p></li>\n<li><p><strong>Underlying container type</strong></p>\n\n<p>Did you considered using a <a href=\"https://en.cppreference.com/w/cpp/container/deque\" rel=\"nofollow noreferrer\">std::deque</a> as inner data type?</p></li>\n</ul>\n\n<hr>\n\n<h2>Checking again</h2>\n\n<hr>\n\n<h3>A second look</h3>\n\n<ul>\n<li>You really have a lot of formatting problems (too much or missing space, disgraceful indentation/alignment, ...). I think you have to consider adding a formatter in your tooling. <a href=\"//stackoverflow.com/questions/841075\">There's ton of options</a>. You can also complete your toolbox using some \"<a href=\"https://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis#C,_C++\" rel=\"nofollow noreferrer\">static code analysis</a>\" application and trying to compile on multiple compilers with a selected set of flags to get useful warnings.</li>\n<li>Consider <a href=\"https://foonathan.net/blog/2017/10/11/explicit-assignment.html\" rel=\"nofollow noreferrer\">adding the keyword <code>explicit</code> for constructors callable with one argument</a>.</li>\n<li>You don't have to <code>#include</code> <code>&lt;iostream&gt;</code> nor <code>&lt;exception&gt;</code> in your ring's header, as you use nothing from them in your class.</li>\n<li>You don't include <code>&lt;iostream&gt;</code>, <code>&lt;algorithm&gt;</code> and <code>&lt;exception&gt;</code> headers in the example file.</li>\n<li>Don't <em>implicitly</em> use <code>using namespace std</code> (using it is a mistake, but using it without writing it is even worse).</li>\n<li>Care about readability, even for example code.</li>\n<li><p>You have a <em>ninja</em> semicolon after the definition of <code>my_iterator::operator++()</code></p>\n\n<pre><code>my_iterator&amp; operator++ ()\n{\n ++index;\n return *this;\n}; // &lt;------ Here's the ninja!\n</code></pre></li>\n</ul>\n\n<hr>\n\n<h3>Help the compiler to help you</h3>\n\n<ul>\n<li><strong>Problem</strong>: <code>error: field 'm_array_size' will be initialized after field 'm_head' [-Werror,-Wreorder]</code></li>\n<li><strong>Solution</strong>: Initialize members in order of their declaration</li>\n</ul>\n\n<hr>\n\n<p>Once the <code>&lt;iostream&gt;</code> header removed :</p>\n\n<ul>\n<li><strong>Problem</strong>: <code>error: 'out_of_range' is not a member of 'std'</code></li>\n<li><strong>Solution</strong>: Simply <code>#include &lt;stdexcept&gt;</code> in your <code>ring</code>'s header</li>\n</ul>\n\n<p>Note that removing the <code>&lt;exception&gt;</code> header have no positive/negative effect on that, so keep it removed since you don't use it in your <code>ring</code> class.</p>\n\n<hr>\n\n<ul>\n<li><strong>Problem</strong>: <code>error: implicitly-declared 'constexpr ring&lt;int&gt;::my_iterator&lt;false&gt;&amp; ring&lt;int&gt;::my_iterator&lt;false&gt;::operator=(const ring&lt;int&gt;::my_iterator&lt;false&gt;&amp;)' is deprecated [-Werror=deprecated-copy]</code></li>\n<li><strong>Solution</strong>: Simply define explicitly a copy assignment operator</li>\n</ul>\n\n<hr>\n\n<ul>\n<li><strong>Problem</strong>: A lot of verbose errors coming from the <code>std::find</code> call in the example.</li>\n<li><strong>Solution</strong>: Referring to <a href=\"https://en.cppreference.com/w/cpp/iterator/iterator_traits\" rel=\"nofollow noreferrer\">the documentation</a> and <a href=\"//stackoverflow.com/questions/8054273/\">this post</a> your <code>my_iterator</code> class have to provide a <code>value_type</code>member. <code>using value_type = typename std::conditional_t&lt;isconst,T ,const T&gt;;</code> should do the trick (or simply <code>T</code>).</li>\n</ul>\n\n<hr>\n\n<ul>\n<li><strong>Problem</strong>: Another verbose error starting with <code>error: no match for 'operator-=' (operand types are 'const size_type' {aka 'const long unsigned int'} and 'const ring&lt;int&gt;::my_iterator&lt;true&gt;')</code></li>\n<li><strong>Solution</strong>: I think this is a copy/paste mistake. Here, the use of a subtraction assignment is pointless. just remove <code>lhs.index -= rhs;</code>.</li>\n</ul>\n\n<hr>\n\n<ul>\n<li><strong>Problem</strong>: msvc complains about \"assignment operator\" and \"move assignment operator\" implicitly defined as deleted for <code>ring&lt;int&gt;</code>. (C4626 &amp; C5027) (note: these warning are caused by the const-ness of <code>m_array_size</code>.)</li>\n<li><strong>Solution</strong>: Consider implementing them.</li>\n</ul>\n\n<hr>\n\n<ul>\n<li><strong>Problem</strong>: In <code>ring::my_iterator::operator[]</code> your parameter <code>index</code> hides the member variable <code>index</code>.</li>\n<li><strong>Solution</strong>: For a global solution, use a decoration (e.g. post-fix with underscore) for your member variables. Otherwise, care about naming; here change the name of the parameter. </li>\n</ul>\n\n<hr>\n\n<p>In your example:</p>\n\n<ul>\n<li><strong>Problem</strong>: <code>catching polymorphic type 'class std::exception' by value [-Werror=catch-value=]</code></li>\n<li><strong>Solution</strong>: Catch exceptions using <code>const &amp;</code> instead.</li>\n</ul>\n\n<hr>\n\n<ul>\n<li><strong>Problem</strong>: You pass <code>10</code> (which is an int) as <code>size_t</code> (an unsigned integer type, e.g. <code>uint32_t</code> or <code>uint64_t</code>) to the constructor of <code>ring</code>.</li>\n<li><strong>Problem</strong>: You use <code>push</code> 20 times <code>i</code> which is <code>size_t</code> into <code>ring&lt;int&gt;</code>.</li>\n<li><strong>Solution</strong>: Use the right type at the right place, even in examples.</li>\n</ul>\n\n<hr>\n\n<ul>\n<li><strong>Problem</strong>: You redeclare <code>i</code> in the nested \"for-loop\", already declared in the top-level one.</li>\n<li><strong>Solution</strong>: Care about naming, even in examples. Here, the outside one can be named <code>value</code>: it's more explicit, and bonus, you might have noticed the typing problem.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T17:07:20.407", "Id": "402483", "Score": "0", "body": "I have thought about using **std::deque** and decided that **std::vector**’s contiguous memory guarantee and that three is no need for insertion in this class made that option less attractive. I am curious as to how you generated all of those compiler errors, I don’t see them, and thus I didn’t know to fix them (I use VS17). \nBased on your review, I have substantially revised my code. What is the community standard for showing my new _review inspired_ code? I would be very much interested in seeing if this c++ barbarian has understood all of your suggestions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T17:22:21.423", "Id": "402484", "Score": "0", "body": "\" What is the community standard for showing my new review inspired code?\" Dunno, maybe post a new question, or a new reply to this question. Or wait response from a moderator ;) For warning, I compiled on Clang/GCC with `-Wpedantic -Werror -Wwrite-strings -Wno-parentheses -Warray-bounds -Weffc++ -Wstrict-aliasing` and `/W4` on msvc. Used CppCheck too." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T00:11:32.003", "Id": "208314", "ParentId": "208293", "Score": "12" } }, { "body": "<p>The implementation of <code>full()</code> should just be <code>return m_contents_size == m_array_size;</code>.</p>\n\n<p>Similarly, make the implementation of <code>empty()</code> be <code>return m_contents_size == 0;</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T20:46:19.437", "Id": "208349", "ParentId": "208293", "Score": "1" } } ]
{ "AcceptedAnswerId": "208314", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T16:58:29.943", "Id": "208293", "Score": "13", "Tags": [ "c++", "reinventing-the-wheel", "c++14", "collections", "circular-list" ], "Title": "Ring Buffer Implementation in C++14" }
208293
<p>I am trying to guess the paswords from the etc/shadow file(it has 43 user/passwords). And I have been given some hits about the passwords:</p> <ul> <li>Length is between 4 and 8 characters</li> <li>There can be only 2 numbers and only at the end</li> <li>Capital letters only in the beginning</li> </ul> <p>So I started just with a small group composed by 4 character with 2 digits in it. But it takes so much time to process:</p> <pre><code>import crypt import string import itertools import datetime dir = "shadow3" file = open(dir, 'r').readlines() #Read all the 43 hashes username = [] hashed = [] c = 0 cc = 0 for x in file: #Split the hash and the username usr, hshd, wtf, iss, this, thing, here, doing, example = x.split(':') username.append(usr) hashed.append(hshd) #GRUPO1 4 caracteres 2 numeros letters = string.ascii_lowercase digits = string.digits grupo1=[] group1=itertools.product(letters,repeat=2) group1b=itertools.product(digits,repeat=2) for x in itertools.product(group1,group1b): #Join the possible iterations string=''.join([''.join(k) for k in x]) grupo1.append(string) print(len(grupo1)) for y in grupo1:#Get the one of the iterations and try it prueba=y for x in hashed: #Verify if that iteration is the password to any of the 43 users rehashed = crypt.crypt(prueba, x) if rehashed == x: #Password is found print('La contraseña del usuario ' + username[c] + ' es ' + prueba) cc = 1 c = c + 1 if cc == 0: #after all iterations password is not found print('Lo sentimos "' + prueba + '" no es la contraseña de ningun usuario') </code></pre> <p>How can I improve the efficiency of this? I have a GTX 1070 if it helps for any kind of GPU processing.(I have no idea of this)</p> <p>Just this small part of 4 characters is taking me for hours, it has still not finished.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T17:39:26.200", "Id": "402310", "Score": "0", "body": "cant you hash prueba without the need of user hashes? Don´t understand the need of rehashed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T17:46:26.540", "Id": "402314", "Score": "0", "body": "As long as I know, to verify if the password is correct I have to crypt the password with the hash, then if the hash generated in that is equal to the initial hash then it is correct. But I'm really new into this, maybe if you could put me an example of what you mean" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T18:02:49.737", "Id": "402320", "Score": "0", "body": "8 characters are already 26^6 * 10^2 possibilities, will take too long" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T06:36:31.360", "Id": "402362", "Score": "1", "body": "@juvian “_can’t you hash prueba without the need of the user hashes”? No. If I set my password as “S3cr3t”, the system adds a two character random salt, say “xy” before the hashing, and stores the hash with the salt prefix “xy”, such as “xy7A2cyZTu”. If another user also uses the password “S3cr3t”, but “3w” was used as the salt, their password might be hashed as “3wHj85dFh” ... completely different despite being the same password. Hashing the trial password with the stored hash is just passing the correct salt (first 2 characters) to use when hashing the trial password." } ]
[ { "body": "<p>Starting with the code in <a href=\"https://codereview.stackexchange.com/questions/208313/checking-hash-and-passwords-with-a-wordlist-more-efficient\">my answer to your related question</a>, we can factor out the source of the words being guessed and encapsulate it all in functions:</p>\n\n<pre><code>def get_users_to_crack(file_name):\n users = {}\n with open(file_name) as file:\n for line in file:\n username, hashed_password, *_ = line.split(':')\n users[username] = hashed_password\n return users\n\ndef crack(users, words):\n cracked_users = {}\n for password in words:\n if not users:\n print(\"Cracked all passwords\")\n return cracked_users, {}\n for username, hashed_password in users.items():\n if crypt.crypt(password, hashed_password) == hashed_password:\n print(f'La contraseña del usuario {username} es {password}')\n cracked_users[username] = password\n del users[username]\n return cracked_users, users\n</code></pre>\n\n<p>Now we just need a supplier of words. This can be either from a file, similar to your other question:</p>\n\n<pre><code>def dictionary_attack(file_name):\n with open(file_name) as file:\n for line in file:\n word = line.rstrip('\\n').capitalize()\n if 4 &lt;= len(word) &lt;= 8:\n yield word\n</code></pre>\n\n<p>Or you build it yourself, according to the scheme you supplied here:</p>\n\n<pre><code>from string import ascii_lowercase as a_z, ascii_uppercase as A_Z, digits\nfrom itertools import product\n\ndef get_chars(length):\n \"\"\"Produces the allowed chars according to the scheme given\n [a-zA-Z][a-z]*(0-5)[a-z0-9]*2\"\"\"\n assert length &gt; 2\n return [a_z + A_Z] + [a_z] * (length - 3) + [a_z + digits] * 2\n\ndef brute_force(min_length, max_length, get_chars):\n for length in range(min_length, max_length + 1):\n for word in product(*get_chars(length)):\n yield \"\".join(word)\n</code></pre>\n\n<p>You can then combine them into one nice tool:</p>\n\n<pre><code>if __name__ == \"__main__\":\n users = get_users_to_crack(\"shadow3\")\n n = len(users)\n\n users_cracked_1, users = crack(users, dictionary_attack('out68.lst'))\n print(f\"Cracked {len(users_cracked_1)} out of {n} users passwords using a dictionary attack\")\n\n users_cracked_2, users = crack(users, brute_force(4, 8, get_chars))\n print(f\"Cracked {len(users_cracked_2)} out of {n} users passwords using brute force\")\n\n if users:\n print(f\"{len(users)} users passwords not cracked\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T17:04:09.623", "Id": "208388", "ParentId": "208295", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T17:27:55.620", "Id": "208295", "Score": "0", "Tags": [ "python", "performance", "hashcode" ], "Title": "Make password/hash verification algorithm more efficient" }
208295
<p>I am creating an estimation tool, where users can input part numbers and quantities, and the tool will output the lowest cost for that part number based on searches through multiple databases. </p> <p>I accomplish this by loading data into multiple sheets and then evaluate all possibilities on one sheet.</p> <p>I believe my code is struggling, because I have multiple instances of this loop below which I'm hoping someone can help me improve. The code below runs 3 separate times, for 3 different sheets. There can be up-to 1000 part numbers run at a time. Once the tool has been run, to start over I delete all the sheets, so each sheet is created every time the macro runs. </p> <pre><code>'Add Content to Summary 'MPN and Qty add to Summary page Sheet22.Visible = True Sheet1.Select Range("A2").Select Sheet22.Select Range("A2").Select For i = 1 To 3 Sheet1.Select If Len(ActiveCell.Value) &gt; 0 Then xmpn = ActiveCell.Value xqty = ActiveCell.Offset(0, 1).Value Sheet22.Select ActiveCell.Value = xmpn ActiveCell.Offset(0, 1).Value = xqty ActiveCell.Offset(1, 0).Select Sheet1.Select ActiveCell.Offset(1, 0).Select Else i = 10 End If i = i - 1 Next </code></pre> <p>If there are 1000 part number entries, this code can take about 45 seconds to run, and causes excel to show not responding. Any help or suggestions to improve would be greatly appreciated. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T19:40:56.060", "Id": "402340", "Score": "0", "body": "You should probably search directly in the database." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T07:49:49.310", "Id": "402364", "Score": "1", "body": "It would be best to work with the data in memory. But if you do write it to the worksheet this video will help immensely: [Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset)](https://www.youtube.com//watch?v=c8reU-H1PKQ&index=5&list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5). You should also watch: [Excel VBA Introduction Part 25 - Arrays](https://www.youtube.com//watch?v=h9FTX7TgkpM&index=28&list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T14:52:51.473", "Id": "402584", "Score": "0", "body": "@krishKM - Yes I am searching directly in 6 different databases, however 1 of them is through an excel add in which connects via an excel formula. and the other 2 instances of this loop are for the summary page and the evaluation page." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T14:53:36.697", "Id": "402585", "Score": "0", "body": "@TinMan - I will check out those videos, thanks for the suggestion!" } ]
[ { "body": "<p>Based on the array video provided by TinMan, I now declared the data as an array, and then populate each tab referencing the array. The code is now instantaneous for 1000s records. </p>\n\n<p>Thanks TinMan!!</p>\n\n<pre><code>'Set MpnQty array\n\nDim MpnQty() As Variant\nDim Dimension1 As Long, Dimension2 As Long\n\nSheet1.Activate\n\nDimension1 = Range(\"A2\", Range(\"A2\").End(xlDown)).Cells.Count - 1\nDimension2 = 1\n\nReDim MpnQty(0 To Dimension1, 0 To Dimension2)\n\nFor Dimension1 = LBound(MpnQty, 1) To UBound(MpnQty, 1)\n For Dimension2 = LBound(MpnQty, 2) To UBound(MpnQty, 2)\n MpnQty(Dimension1, Dimension2) = Range(\"A2\").Offset(Dimension1, Dimension2).Value\n Next Dimension2\nNext Dimension1\n\n'Add MPN and Qty to Summary page\n\nSheet22.Visible = True\nSheet22.Activate\n\nFor Dimension1 = LBound(MpnQty, 1) To UBound(MpnQty, 1)\n For Dimension2 = LBound(MpnQty, 2) To UBound(MpnQty, 2)\n Range(\"A2\").Offset(Dimension1, Dimension2).Value = MpnQty(Dimension1, Dimension2)\n Next Dimension2\nNext Dimension \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T19:24:47.830", "Id": "208468", "ParentId": "208300", "Score": "1" } }, { "body": "<p>Your answer is a big step up from your original code but we can do better.</p>\n\n<p><code>Dimension2 = 1</code> does no do anything. <code>Dimension2</code> is being initiated in the <code>For</code> loop.</p>\n\n<h2>Selecting and Activating Objects</h2>\n\n<p>It is rarely necessary to Select or Activate an Object. You should to fully qualify your Objects rather than it is to rely on the default active objects. Fully qualifying references will make your code more robust and easier to debug. </p>\n\n<blockquote>\n<pre><code>Sheet22.Visible = True\nSheet22.Activate\n</code></pre>\n</blockquote>\n\n<p>Above you are temporarily making Sheet22 visible and active when all you need to do is qualify the range.</p>\n\n<blockquote>\n<pre><code>For Dimension1 = LBound(MpnQty, 1) To UBound(MpnQty, 1)\n For Dimension2 = LBound(MpnQty, 2) To UBound(MpnQty, 2)\n Sheet22.Range(\"A2\").Offset(Dimension1, Dimension2).Value = MpnQty(Dimension1, Dimension2)\n Next Dimension2\nNext Dimension\n</code></pre>\n</blockquote>\n\n<p>Consider using a temp variable to shorten the worksheet reference.</p>\n\n<blockquote>\n<pre><code>Dim ws1 as Worksheet\nSet ws = Sheet1\nDimension1 = ws1.Range(\"A2\", ws1.Range(\"A2\").End(xlDown)).Count - 1\n</code></pre>\n</blockquote>\n\n<p>I prefer to use <code>With Blocks</code></p>\n\n<blockquote>\n<pre><code>With Sheet1 \n Dimension1 = .Range(\"A2\", .Range(\"A2\").End(xlDown)).Count - 1\nEnd With\n</code></pre>\n</blockquote>\n\n<p>Note: I omitted <code>Cells</code> because it is the default property of <code>Range</code>.</p>\n\n<h2>Ranges and Arrays</h2>\n\n<p><code>Range(\"A2\").Value</code> returns a single scalar value because it contains only one cell. <code>Range(\"A2:B2\").Value</code> is a multiple cell range which returns an array of values that can be directly assigned to a variant variable or another range.</p>\n\n<p>There are several nuances to resizing ranges, assigning ranges values to variants and assigning arrays to ranges. So practice!! </p>\n\n<h2>Refactored Code</h2>\n\n<p>Here is how I would write it:</p>\n\n<pre><code>Dim Data() As Variant\n\nWith Sheet1\n Data = .Range(\"A2:B2\", .Range(\"A2\").End(xlDown)).Value\nEnd With\n\nWith Sheet22\n Data = .Range(\"A2:B2\").Resize(UBound(Data), UBound(Data, 2)).Value = Data\nEnd With\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T17:01:26.347", "Id": "402936", "Score": "0", "body": "Thank you TinMan, very helpful suggestions here. I have removed the temporary visible and activate from the code and now qualify the range as you suggested above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T17:12:39.337", "Id": "402938", "Score": "0", "body": "I am using the Dimension 2 in the code to select A2:B2. I'm not sure your refactored code addresses this. \n\nCan you also clarify - for the refactored code in the with blocks for sheet 22 should not include 'Data =' at the start, but only at the end?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T17:26:37.817", "Id": "402943", "Score": "0", "body": "@AaronBates I did miss that. I updates my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T17:51:21.650", "Id": "402953", "Score": "0", "body": "I am now using your refactored code, it is lightening fast and makes the code easily readable :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T02:12:13.953", "Id": "208495", "ParentId": "208300", "Score": "0" } } ]
{ "AcceptedAnswerId": "208495", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T17:53:49.487", "Id": "208300", "Score": "0", "Tags": [ "performance", "vba", "excel" ], "Title": "Searching multiple Excel sheets for the cheapest item" }
208300
<p>I've an application that uses <code>gorm</code> and <code>go-swagger</code> for a simple API.</p> <p>One of the route's handlers bloated to 66 lines, being quite straightforward by performing the basic sanity-checks:</p> <pre class="lang-go prettyprint-override"><code>// CreateJWToken will create a JWToken based on credentials func (u *Users) CreateJWToken(params users.CreateJWTokenParams) middleware.Responder { if params.Body == nil || params.Body.Email == nil || params.Body.Password == nil { message := "Email or password invalid" return users.NewCreateJWTokenUnauthorized().WithPayload(&amp;models.Error{Message: &amp;message}) } var user types.User err := u.DB.First(&amp;user, "email = ?", params.Body.Email).Error if err != nil { message := "Failed to create the token" return users.NewCreateJWTokenDefault(500).WithPayload(&amp;models.Error{Message: &amp;message}) } if user.ID == 0 { message := "User not found" return users.NewCreateJWTokenUnauthorized().WithPayload(&amp;models.Error{Message: &amp;message}) } if !u.checkPasswordHash(*params.Body.Password, *user.Password) { message := "Unauthorized" return users.NewCreateJWTokenUnauthorized().WithPayload(&amp;models.Error{Message: &amp;message}) } // Generate JWToken token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "user_id": user.ID, "nbf": time.Date(2018, 11, 21, 12, 0, 0, 0, time.UTC).Unix(), }) // Decode the HMAC secret hmacSecret, err := hex.DecodeString(u.Config.JWTHmacSecret) if err != nil { message := "Failed to decode HMAC secret" log.Fatal(message, err.Error()) return users.NewCreateJWTokenDefault(500).WithPayload(&amp;models.Error{Message: &amp;message}) } // Sign and get the complete encoded token as a string using the secret tokenString, err := token.SignedString(hmacSecret) if err != nil { message := "Failed to sign the token" return users.NewCreateJWTokenUnauthorized().WithPayload(&amp;models.Error{Message: &amp;message}) } // Store the JWToken in the database var dbToken types.JWToken dbToken.User = user // Hash the token, we don't want to store it in plain text hash := utils.HashFromString(&amp;tokenString) dbToken.Token = &amp;hash // Save to the database err = u.DB.Create(&amp;dbToken).Error if err != nil { message := "Failed to create the token" return users.NewCreateJWTokenDefault(500).WithPayload(&amp;models.Error{Message: &amp;message}) } // Build the response payload := models.JWToken{ Token: &amp;tokenString, } return users.NewCreateJWTokenCreated().WithPayload(&amp;payload) } </code></pre> <p>Most of the code are the sanity-checks and there doesn't seem to be much to refactor into generalized functions.</p> <p>Is this length fine? How could this be structured this better?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T18:22:48.717", "Id": "208302", "Score": "1", "Tags": [ "go", "crud" ], "Title": "Handling CRUD methods with gorm and go-swagger" }
208302
<p>My goal is to apply a function <code>func1</code> to each row of the matrix <code>input</code> and then return a new one resulting from the transformation.</p> <p>The code works but when the data frame contains more than 1 million rows, it become extremely slow. How can I optimize my code? I start learning programming and I am not familiar with strategies to speed up R code.</p> <p>The functions performs 2 main steps:</p> <ol> <li>Find the locations of all neighboring cells that are located in the extent <code>PR</code> from a focal cell, extract <code>raster</code>'s values at these locations and calculate probability matrix</li> <li>Find the maximum value in the matrix and the new cell corresponding with the maximum value.</li> </ol> <p>Here's the data frame and raster:</p> <pre><code>library(dplyr) library(raster) library(psych) set.seed(1234) n = 10000 input &lt;- as.matrix(data.frame(c1 = sample(1:10, n, replace = T), c2 = sample(1:10, n, replace = T), c3 = sample(1:10, n, replace = T), c4 = sample(1:10, n, replace = T))) r &lt;- raster(extent(0, 10, 0, 10), res = 1) values(r) &lt;- sample(1:1000, size = 10*10, replace = T) ## plot(r) </code></pre> <p>Here's my code to apply the function to each row in the matrix:</p> <pre><code>system.time( test &lt;- input %&gt;% split(1:nrow(input)) %&gt;% map(~ func1(.x, 2, 2, "test_1")) %&gt;% do.call("rbind", .)) </code></pre> <p>Here's the function:</p> <pre><code>func1 &lt;- function(dataC, PR, DB, MT){ ## Retrieve the coordinates x and y of the current cell c1 &lt;- dataC[[1]] c2 &lt;- dataC[[2]] ## Retrieve the coordinates x and y of the previous cell c3 &lt;- dataC[[3]] c4 &lt;- dataC[[4]] ## Initialize the coordinates x and y of the new cell newc1 &lt;- -999 newc2 &lt;- -999 if(MT=="test_1"){ ## Extract the raster values with coordinates in matC matC &lt;- expand.grid(x = c((c1 - PR) : (c1 - 1)), y = c((c2 - PR) : (c2 - 1))) ## cells at upper-left corner V1 &lt;- mean(raster::extract(r, cbind(matC[,1], matC[,2])), na.rm = T) * sqrt(2) * DB ## Extract the raster values with coordinates in matC matC &lt;- expand.grid(x = c((c1 - PR) : (c1 - 1)), y = c((c2 - 1) : (c2 + 1))) ## cells at upper-middle corner V2 &lt;- mean(raster::extract(r, cbind(matC[,1], matC[,2])), na.rm = T) * DB ## Extract the raster values with coordinates in matC matC &lt;- expand.grid(x = c((c1 - PR) : (c1 - 1)), y = c((c2 + 1) : (c2 + PR))) ## cells at upper-right corner V3 &lt;- mean(raster::extract(r, cbind(matC[,1], matC[,2])), na.rm = T) * sqrt(2) * DB ## Extract the raster values with coordinates in matC matC &lt;- expand.grid(x = c((c1 - 1) : (c1 + 1)), y = c((c2 - PR) : (c2 - 1))) ## cells at left corner V4 &lt;- mean(raster::extract(r, cbind(matC[,1], matC[,2])), na.rm = T) * DB V5 &lt;- 0 ## cell at middle corner ## Extract the raster values with coordinates in matC matC &lt;- expand.grid(x = c((c1 - 1) : (c1 + 1)), y = c((c2 + 1) : (c2 + PR))) ## cells at right corner V6 &lt;- mean(raster::extract(r, cbind(matC[,1], matC[,2])), na.rm = T) * DB ## Extract the raster values with coordinates in matC matC &lt;- expand.grid(x = c((c1 + 1) : (c1 + PR)), y = c((c2 - PR) : (c2 - 1))) ## cells at bottom-left corner V7 &lt;- mean(raster::extract(r, cbind(matC[,1], matC[,2])), na.rm = T) * sqrt(2) * DB ## Extract the raster values with coordinates in matC matC &lt;- expand.grid(x = c((c1 + 1) : (c1 + PR)), y = c((c2 - 1) : (c2 + 1))) ## cells at bottom-middle corner V8 &lt;- mean(raster::extract(r, cbind(matC[,1], matC[,2])), na.rm = T) * DB ## Extract the raster values with coordinates in matC matC &lt;- expand.grid(x = c((c1 + 1) : (c1 + PR)), y = c((c2 + 1) : (c2 + PR))) ## cells at bottom-right corner V9 &lt;- mean(raster::extract(r, cbind(matC[,1], matC[,2])), na.rm = T) * sqrt(2) * DB } else if(MT=="test_2"){ ## Extract the raster values with coordinates in matC matC &lt;- expand.grid(x = c((c1 - PR) : (c1 - 1)), y = c((c2 - PR) : (c2 - 1))) ## cells at upper-left corner V1 &lt;- harmonic.mean(raster::extract(r, cbind(matC[,1], matC[,2])), na.rm = T) * sqrt(2) * DB ## Extract the raster values with coordinates in matC matC &lt;- expand.grid(x = c((c1 - PR) : (c1 - 1)), y = c((c2 - 1) : (c2 + 1))) ## cells at upper-middle corner V2 &lt;- harmonic.mean(raster::extract(r, cbind(matC[,1], matC[,2])), na.rm = T) * DB ## Extract the raster values with coordinates in matC matC &lt;- expand.grid(x = c((c1 - PR) : (c1 - 1)), y = c((c2 + 1) : (c2 + PR))) ## cells at upper-right corner V3 &lt;- harmonic.mean(raster::extract(r, cbind(matC[,1], matC[,2])), na.rm = T) * sqrt(2) * DB ## Extract the raster values with coordinates in matC matC &lt;- expand.grid(x = c((c1 - 1) : (c1 + 1)), y = c((c2 - PR) : (c2 - 1))) ## cells at left corner V4 &lt;- harmonic.mean(raster::extract(r, cbind(matC[,1], matC[,2])), na.rm = T) * DB V5 &lt;- 0 ## cells at middle corner ## Extract the raster values with coordinates in matC matC &lt;- expand.grid(x = c((c1 - 1) : (c1 + 1)), y = c((c2 + 1) : (c2 + PR))) ## cells at right corner V6 &lt;- harmonic.mean(raster::extract(r, cbind(matC[,1], matC[,2])), na.rm = T) * DB ## Extract the raster values with coordinates in matC matC &lt;- expand.grid(x = c((c1 + 1) : (c1 + PR)), y = c((c2 - PR) : (c2 - 1))) ## cells at bottom-left corner V7 &lt;- harmonic.mean(raster::extract(r, cbind(matC[,1], matC[,2])), na.rm = T) * sqrt(2) * DB ## Extract the raster values with coordinates in matC matC &lt;- expand.grid(x = c((c1 + 1) : (c1 + PR)), y = c((c2 - 1) : (c2 + 1))) ## cells at bottom-middle corner V8 &lt;- harmonic.mean(raster::extract(r, cbind(matC[,1], matC[,2])), na.rm = T) * DB ## Extract the raster values with coordinates in matC matC &lt;- expand.grid(x = c((c1 + 1) : (c1 + PR)), y = c((c2 + 1) : (c2 + PR))) ## cells at bottom-right corner V9 &lt;- harmonic.mean(raster::extract(r, cbind(matC[,1], matC[,2])), na.rm = T) * sqrt(2) * DB } ## Build the matrix of cell selection tot &lt;- sum(c(1/V1, 1/V2, 1/V3, 1/V4, 1/V6, 1/V7, 1/V8, 1/V9), na.rm = TRUE) mat_V &lt;- matrix(data = c((1/V1)/tot, (1/V2)/tot, (1/V3)/tot, (1/V4)/tot, V5, (1/V6)/tot, (1/V7)/tot, (1/V8)/tot, (1/V9)/tot), nrow = 3, ncol = 3, byrow = TRUE) while((newc1 == -999 &amp;&amp; newc2 == -999) || (c3 == newc1 &amp;&amp; c4 == newc2)){ ## Test if the new cell is the previous cell if(c3 == newc1 &amp;&amp; c4 == newc2){ mat_V[choiceC[1], choiceC[2]] &lt;- NaN ## print(mat_V) } ## Find the maximum value in the matrix choiceC &lt;- which(mat_V == max(mat_V, na.rm = TRUE), arr.ind = TRUE) ## print(choiceC) ## If there are several maximum values if(nrow(choiceC) &gt; 1){ choiceC &lt;- choiceC[sample(1:nrow(choiceC), 1), ] } ## Find the new cell relative to the current cell if(choiceC[1]==1 &amp; choiceC[2]==1){ ## cell at the upper-left corner newC &lt;- matrix(c(x = c1 - 1, y = c2 - 1), ncol = 2) } else if(choiceC[1]==1 &amp; choiceC[2]==2){ ## cell at the upper-middle corner newC &lt;- matrix(c(x = c1 - 1, y = c2), ncol = 2) } else if(choiceC[1]==1 &amp; choiceC[2]==3){ ## cell at the upper-right corner newC &lt;- matrix(c(x = c1 - 1, y = c2 + 1), ncol = 2) } else if(choiceC[1]==2 &amp; choiceC[2]==1){ ## cell at the left corner newC &lt;- matrix(c(x = c1, y = c2 - 1), ncol = 2) } else if(choiceC[1]==2 &amp; choiceC[2]==3){ ## cell at the right corner newC &lt;- matrix(c(x = c1, y = c2 + 1), ncol = 2) } else if(choiceC[1]==3 &amp; choiceC[2]==1){ ## cell at the bottom-left corner newC &lt;- matrix(c(x = c1 + 1, y = c2 - 1), ncol = 2) } else if(choiceC[1]==3 &amp; choiceC[2]==2){ ## cell at the bottom-middle corner newC &lt;- matrix(c(x = c1 + 1, y = c2), ncol = 2) } else if(choiceC[1]==3 &amp; choiceC[2]==3){ ## cell at the bottom-right corner newC &lt;- matrix(c(x = c1 + 1, y = c2 + 1), ncol = 2) } newc1 &lt;- newC[[1]] newc2 &lt;- newC[[2]] } return(newC) } </code></pre> <p>Here's the elapsed time when n = 10000. Ideally, I would like to reduce the time required at &lt; 1 min. </p> <pre><code>user system elapsed 108.96 0.01 109.81 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T12:28:08.250", "Id": "402561", "Score": "0", "body": "do the `r` need to be `raster`? can no t we use simple matrix?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T15:18:33.320", "Id": "402587", "Score": "0", "body": "Yes, `r` can be a matrix." } ]
[ { "body": "<p>Did dome upgrades, but only for <code>'test_1'</code> case, you can update <code>'test2'</code> case similarly.\nFor me this function run in 13.54 sek vs 26.16 sek for your original code.</p>\n\n<pre><code>func1 &lt;- function(dataC, PR, DB, MT){\n\n ## Retrieve the coordinates x and y of the current cell\n c1 &lt;- dataC[[1]]\n c2 &lt;- dataC[[2]]\n\n ## Retrieve the coordinates x and y of the previous cell\n c3 &lt;- dataC[[3]]\n c4 &lt;- dataC[[4]]\n\n ## Initialize the coordinates x and y of the new cell\n newc1 &lt;- -999\n newc2 &lt;- -999\n\n a1 &lt;- c((c1 - PR), (c1 - 1))\n a2 &lt;- c((c2 - PR), (c2 - 1))\n a3 &lt;- c((c2 - 1), (c2 + 1))\n a4 &lt;- c((c2 + 1), (c2 + PR))\n a5 &lt;- c((c1 - 1), (c1 + 1))\n a6 &lt;- c((c1 + 1), (c1 + PR))\n\n\n xx &lt;- c(a1, a2, a3, a4, a5, a6)\n xx &lt;- seq(min(xx), max(xx))\n gg &lt;- expand.grid(xx, xx, KEEP.OUT.ATTRS = F)\n gg &lt;- as.matrix(gg)\n gg1 &lt;- gg[, 1]\n gg2 &lt;- gg[, 2]\n\n ff2 &lt;- function(matC) {\n y1 &lt;- raster::extract(r, matC)\n mean(y1, na.rm = T)\n }\n\n cgrid &lt;- function(x, y) {\n gg[gg1 &gt;= x[1] &amp; gg1 &lt;= x[2] &amp; gg2 &gt;= y[1] &amp; gg2 &lt;= y[2], ]\n }\n\n if (MT == \"test_1\") {\n ## cells at upper-left corner\n V1 &lt;- ff2(cgrid(x = a1, y = a2)) * sqrt(2) * DB\n ## cells at upper-middle corner\n V2 &lt;- ff2(cgrid(x = a1, y = a3)) * DB\n ## cells at upper-right corner\n V3 &lt;- ff2(cgrid(x = a1, y = a4)) * sqrt(2) * DB\n ## cells at left corner\n V4 &lt;- ff2(cgrid(x = a5, y = a2)) * DB\n V5 &lt;- 0 ## cell at middle corner\n ## cells at right corner\n V6 &lt;- ff2(cgrid(x = a5, y = a4)) * DB\n ## cells at bottom-left corner\n V7 &lt;- ff2(cgrid(x = a6, y = a2)) * sqrt(2) * DB \n ## cells at bottom-middle corner\n V8 &lt;- ff2(cgrid(x = a6, y = a3)) * DB\n ## cells at bottom-right corner\n V9 &lt;- ff2(cgrid(x = a6, y = a4) ) * sqrt(2) * DB\n }\n\n ## Build the matrix of cell selection\n V &lt;- c(V1, V2, V3, V4, V5, V6, V7, V8, V9)\n tot &lt;- sum(1/V[-5], na.rm = TRUE)\n mat_V &lt;- matrix((1/V)/tot, nrow = 3, ncol = 3, byrow = TRUE)\n mat_V[5] &lt;- V5\n\n while ((newc1 == -999 &amp;&amp; newc2 == -999) || (c3 == newc1 &amp;&amp; c4 == newc2)) {\n\n ## Test if the new cell is the previous cell\n if (c3 == newc1 &amp;&amp; c4 == newc2) {\n mat_V[choiceC[1], choiceC[2]] &lt;- NaN\n ## print(mat_V)\n }\n\n ## Find the maximum value in the matrix\n choiceC &lt;- which(mat_V == max(mat_V, na.rm = TRUE), arr.ind = TRUE)\n\n ## If there are several maximum values\n if (nrow(choiceC) &gt; 1) choiceC &lt;- choiceC[sample.int(nrow(choiceC), 1L), ]\n\n ## Find the new cell relative to the current cell \n newC &lt;- c(x = c1 + (choiceC[1] - 2), y = c2 + (choiceC[2] - 2))\n newC &lt;- matrix(newC, ncol = 2)\n\n newc1 &lt;- newC[[1]]\n newc2 &lt;- newC[[2]]\n\n }\n return(newC)\n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T15:22:32.117", "Id": "402588", "Score": "0", "body": "Thank you very much ! The function runs for 99.16 s vs 110 s from my code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T10:34:55.513", "Id": "208438", "ParentId": "208307", "Score": "2" } } ]
{ "AcceptedAnswerId": "208438", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T20:25:10.387", "Id": "208307", "Score": "3", "Tags": [ "performance", "matrix", "r" ], "Title": "Applying a function to each row of a matrix" }
208307
<p>I had a lot of fun writing these. I haven't seen a version minimizing turns, so that was a neat challenge. Any suggestions are very welcome. </p> <p>Is there anything to gain by making more method variables like those in the <code>search()</code> method; <code>visited</code> or <code>open_pos</code> into instance variables?</p> <p>I would like to have something returned when instantiating an object</p> <pre><code>ham = MinTurns(start, end, grid) </code></pre> <p>instead of</p> <pre><code>eggs = MinTurns(start, end, grid) ham = eggs.search() </code></pre> <p>Is there a way to do this? Using <code>super</code> maybe? I have messed around but haven't come up with anything better. Am I being ridiculous?</p> <p>Is the level of commenting appropriate?</p> <p>Can I gain any efficiency?</p> <pre><code>from heapq import heappop, heappush class AStar(object): def __init__(self, start_pos: tuple, end_pos: tuple, grid: list): """Instantiate AStar object. start_pos and end_pos are tuples of coordinates. (0, 2), (0, 4) grid is a list of length n of strings of length n where 'x' indicates a barrier. i.e. ['...x...', '.xxxx..', '.x.....', '.x.xxx.', '.x...x.', '..xx.x.', '.......'] :param start_pos: Coordinates of start position. :param end_pos: Coordinates of end position. :param grid: List containing square grid of strings with 'x' denoting barriers. """ self.start_pos = start_pos self.end_pos = end_pos self.grid = grid class MinTurns(AStar): """A star algorithm for navigating a map in the fewest turns. Given start and end points for a grid style maze, outputs a tuple containing; a list of coordinates, number of turns, and length of route from start to end for the route with the fewest turns. """ def find_neighbors(self, curr_pos: tuple, prev_pos: tuple) -&gt; list: """Finds neighbors of curr_pos. Adds coordinates of neighbors to list along with boolean(is_turn) representing whether a turn occurs to reach the neighbor given path from prev_pos to curr_pos. :param curr_pos: curr_pos of self.search(). :param prev_pos: position prior to curr_pos. :return: list of tuples [((pos of neighbor), is_turn)]. """ limit = len(self.grid) - 1 neighbors = [] # Check each position adjacent to curr_pos. for y, x in zip([0, -1, 0, 1], [1, 0, -1, 0]): # If adjacent position is outside of grid, skip it. if (curr_pos[0] + y) &gt; limit or (curr_pos[0] + y) &lt; 0 or (curr_pos[1] + x) &gt; limit or (curr_pos[1] + x) &lt; 0: continue # If adjacent position is a barrier, skip it. if self.grid[curr_pos[0] + y][curr_pos[1] + x] == 'x': continue else: # Ensure we do not count a first step as a turn. if curr_pos == self.start_pos: is_turn = False else: # Determine direction from prev_pos to curr_pos. if curr_pos != prev_pos[1] and curr_pos[0] == prev_pos[1][0]: direction = 'horizontal' else: direction = 'vertical' # Determine movement from curr_pos to new position. if y != 0: movement = 'vertical' else: movement = 'horizontal' # If we're not still moving in the same direction, we have turned. is_turn = not (movement == direction) neighbors.append(((curr_pos[0] + y, curr_pos[1] + x), is_turn)) return neighbors def make_path(self, curr_pos: tuple, route: dict) -&gt; tuple: """Creates list of coordinates representing turns in path. :param curr_pos: end point of path. :param route: dict of coordinates leading to curr_pos :return: tuple containing list of coordinates of turns, len(list of coordinates) """ turn_coords = [] x, path_length = 0, 1 prev_pos = curr_pos if route.get(self.end_pos) is None: return 'No path found.', [] while route[curr_pos] is not None: curr_pos = route[curr_pos][1] if curr_pos[x] != prev_pos[x]: if x == 0: x = 1 else: x = 0 if prev_pos is not self.end_pos: turn_coords.append(prev_pos) prev_pos = curr_pos path_length += 1 turn_coords.reverse() return len(turn_coords), path_length def search(self): """Finds path through self.grid in fewest number of turns. Uses a priority queue to sort nodes by least number of turns required to reach it. Continually updates number of turns needed to reach any given position if a better path is found. :return: self.make_path(). """ # Keep track of where we've been. visited = set() # We'll keep track of the route and the number of turns to reach the curr_pos with a dict. # {(position): (turns_count, (previous-position))} route = {self.start_pos: None} # turn_count is used to promote routes with fewer turns. turn_count = {self.start_pos: 0} open_pos = [] heappush(open_pos, (0, self.start_pos)) while open_pos: # Routes with fewest turns_so_far are up first in the priority queue. turns_so_far, curr_pos = heappop(open_pos) if curr_pos in visited: continue prev = route[curr_pos] # Always remember where you came from so we know if we've turned. visited.add(curr_pos) # But keep moving forward. Never go back! neighbors_list = self.find_neighbors(curr_pos, prev) for pos, did_turn in neighbors_list: if pos in visited: continue if turn_count.get(pos): # Have we been here before? # If so, lets update our turn_count with the route containing the fewest turns. turn_count[pos] = min(turn_count[pos], turns_so_far + int(did_turn)) else: turn_count[pos] = turns_so_far + int(did_turn) # In any case add this place to the list of places to explore. heappush(open_pos, (turn_count[pos], pos)) old_route = route.get(pos) # Do we know of another way to get here? # If so, does the old_route take more turns than the current route to get to pos? if old_route and turn_count[pos] &lt; old_route[0]: # If pos can be reached in fewer turns by the current route, we overwrite the old route. route[pos] = (turn_count[pos], curr_pos) if not old_route: route[pos] = (turn_count[pos], curr_pos) # Wait until open_pos is exhausted to ensure a shorter path doesn't end our search prematurely. return self.make_path(self.end_pos, route) class ShortestRoute(AStar): """Algorithm to find shortest path between coordinates in a grid style maze """ def find_neighbors(self, curr_pos: tuple) -&gt; list: """Finds neighbors of curr_pos. Adds coordinates of neighbors to list. :param curr_pos: curr_pos of self.search(). :return: list of tuples [((pos of neighbor), is_turn)]. """ limit = len(self.grid) - 1 neighbors = [] # Check each position adjacent to curr_pos for y, x in zip([0, -1, 0, 1], [1, 0, -1, 0]): # If adjacent position is outside of grid, skip it. if (curr_pos[0] + y) &gt; limit or (curr_pos[0] + y) &lt; 0 or (curr_pos[1] + x) &gt; limit or (curr_pos[1] + x) &lt; 0: continue # If adjacent position is a barrier, skip it. if self.grid[curr_pos[0] + y][curr_pos[1] + x] == 'x': continue neighbors.append((curr_pos[0] + y, curr_pos[1] + x)) return neighbors def make_path(self, route: dict): """Creates list of coordinates in path. :param route: dict of coordinates leading to curr_pos. :return: tuple containing list of coordinates. """ path = [] curr_pos = self.end_pos while curr_pos is not None: path.append(curr_pos) curr_pos = route[curr_pos][1] path.reverse() return len(path) def search(self): """Finds shortest path through self.grid. Uses a deque to hold coordinates of positions to explore. Continually updates length to reach any given position if a shorter path to that position is found. :return: self.make_path(). """ visited = set() route = {self.start_pos: (1, None)} open_pos = [] heappush(open_pos, (1, self.start_pos)) while open_pos: length, curr_pos = heappop(open_pos) if curr_pos == self.end_pos: return self.make_path(route) if curr_pos in visited: continue visited.add(curr_pos) neighbors = self.find_neighbors(curr_pos) for neighbor in neighbors: if neighbor in visited: continue # if neighbor not in open_pos: length += 1 # neighbor is one step farther than curr_pos. heappush(open_pos, (length, neighbor)) old_route = route.get(neighbor) # Do we know of another way to get here? # If so, is it shorter than the current route to get to neighbor? if old_route and length &lt; old_route[0]: # If neighbor can be reached faster by the current route, we overwrite the old route. route[neighbor] = (length, curr_pos) if not old_route: route[neighbor] = (length, curr_pos) return 'No path found.', [] </code></pre> <p>Import and run:</p> <pre><code>from random import randint from a_star import AStar, MinTurns, ShortestRoute def make_maze_line(size): items = ['.', '.', '.', 'x'] maze_line = [items[randint(0, 3)] for _ in range(size)] return ''.join(maze_line) def make_maze(size): return [make_maze_line(size) for _ in range(size)] maze = ['...x.....', '.x.xx..x.', '.x...x.x.', '.xxx.x.x.', '...x...x.', '.x.x.x.x.', '.x.....x.', '..xxxxx..', '.........'] maze = make_maze(60) for line in maze: print(line) start, stop = (3, 2), (42, 54) def main(): route_1 = MinTurns(start, stop, maze).search() route_2 = ShortestRoute(start, stop, maze).search() print(route_1) print(route_2) if __name__ == "__main__": main() </code></pre>
[]
[ { "body": "<p>One test is to see if a backward run produces the same number of turns. This test fails given inputs like:</p>\n\n<p><code>start, end = (1, 0), (1, 4)\n grid = ['.....', \n '...x.', \n 'xxxxx',\n ...]</code></p>\n\n<p><code>MinTurns(start, end, grid).search()</code> results in output <code>([(1, 2), (0, 2), (0, 4)], 3, 8)</code></p>\n\n<p><code>MinTurns(end, start, grid).search()</code> results in output <code>([(0, 4), (0, 0)]), 2, 8)</code></p>\n\n<p>I'm finding that, since a turn is assigned and carried through the path along the top row starting with <code>(1, 1)</code>, the bottom row will be called first out of <code>open_pos</code> causing <code>(0, 2)</code> to become a child of <code>(1, 2)</code> instead of a child of <code>(0, 1)</code>. By the time we realize an extra turn will result from this path <code>(0, 2)</code> is in the visited set and won't be rewritten.</p>\n\n<p>I can't see a way to correct this without adding a lot of complexity to the algorithm, and because of the heuristic nature of the algorithm, I don't see a one off in rare circumstances as all that bad.</p>\n\n<p>Given all the above we can gain quite a bit of efficiency by returning the path when <code>end</code> is first encountered rather than waiting for all <code>open_pos</code> to be exhausted. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T00:31:32.230", "Id": "208491", "ParentId": "208311", "Score": "1" } } ]
{ "AcceptedAnswerId": "208491", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T20:55:17.610", "Id": "208311", "Score": "3", "Tags": [ "python", "object-oriented", "python-3.x", "pathfinding", "a-star" ], "Title": "Python A Star with fewest turns and shortest path variations" }
208311
<p>I wrote the following code to use Entity Framework 6 and Managed Oracle Providers to call an Oracle stored procedure that returns multiple cursors. </p> <p>Would like some input about the code I used to open and close the database connection. Please note that the open and close code is a workaround for a possible bug in the Oracle library that occurs every time <code>using</code> is used. Doing that <em>instead</em> of the workaround would throw the following exception:</p> <pre><code> System.ObjectDisposedException: 'Cannot access a disposed object.Object name: 'OracleConnection'.' </code></pre> <p>Would also like some input on the way I am getting the multiple cursors and whether or not there might be a better way.</p> <p><strong>Working Code:</strong></p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Data; using Oracle.ManagedDataAccess.Client; using System.Data.Entity.Infrastructure; namespace MyCompany { public class MyClass { private MyDbContext dbContext = new MyDbContext(); public MyItems GetMyItems(string id) { var sqlQuery = ""; var oracleParameters = new List&lt;OracleParameter&gt;(); var oneEntityList = new List&lt;OneEntity&gt;(); var twoEntityList = new List&lt;TwoEntity&gt;(); var threeEntityList = new List&lt;ThreeEntity&gt;(); sqlQuery = @" BEGIN MY_PACKAGE.GetMyItems(:id, :p_cursor1, :p_cursor2, :p_cursor3); END; "; oracleParameters = new List&lt;OracleParameter&gt; { new OracleParameter("p_id", id), new OracleParameter("p_cursor1", OracleDbType.RefCursor, ParameterDirection.Output), new OracleParameter("p_cursor2", OracleDbType.RefCursor, ParameterDirection.Output), new OracleParameter("p_cursor3", OracleDbType.RefCursor, ParameterDirection.Output) }; var connection = dbContext.Database.Connection; connection.Open(); var command = connection.CreateCommand(); command.CommandText = sqlQuery; command.Parameters.AddRange(oracleParameters.ToArray()); using (var reader = command.ExecuteReader()) { oneEntityList = ((IObjectContextAdapter)dbContext).ObjectContext .Translate&lt;OneEntity&gt;(reader) .ToList(); reader.NextResult(); twoEntityList = ((IObjectContextAdapter)dbContext).ObjectContext .Translate&lt;TwoEntity&gt;(reader) .ToList(); reader.NextResult(); threeEntityList = ((IObjectContextAdapter)dbContext).ObjectContext .Translate&lt;ThreeEntity&gt;(reader) .ToList(); } connection.Close(); return new MyItems { OneEntity = oneEntityList, TwoEntity = twoEntityList, ThreeEntity = threeEntityList }; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T15:07:32.607", "Id": "402405", "Score": "0", "body": "In my experience EF and Oracle don't like each other. EF is great only for the sql server. With oracle it's easier to use Dapper and raw queries." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T19:12:56.017", "Id": "402417", "Score": "1", "body": "It appears that [you removed the error](https://codereview.stackexchange.com/revisions/208312/3) “`System.ObjectDisposedException: 'Cannot access a disposed object.Object name: 'OracleConnection'.'`” from the description, yet didn’t change the code. Does the error still occur?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T20:30:28.887", "Id": "402423", "Score": "1", "body": "No, the error does not occur. There never was an error on the code I posted. I was mentioning that if I used a using statement an error occurred. This code review post is legit and should not be on hold." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T07:57:49.603", "Id": "402445", "Score": "0", "body": "_This code review post is legit_ - I think it could be if you reframed it because 1000% the first suggestion will be to use the `using` statement to which you will replay that it doesn't work because an exception is thrown... this is a vicious circle. You've removed a very important fact from your question. Please clarify that this is a **workaround** for the apparent bug in the Oracle library that occurs everytime `using` is used and it throws the exception you've named in the first version." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T13:38:12.897", "Id": "402464", "Score": "1", "body": "@t3chb0t Updated post. I did not realize the exception was a bug with Oracle." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T07:12:57.577", "Id": "402684", "Score": "0", "body": "I think the dispose problem relates to the fact, that you've tried to dispose a Connection owned by dbContext which is an instance member of `MyClass`. You should make your `MyClass` implement `IDisposable` and then dispose the dbContext in `MyClass.Dispose()` instead. That will dispose the connection properly when `dbContext` is disposed." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T21:02:09.403", "Id": "208312", "Score": "2", "Tags": [ "c#", "entity-framework", "oracle" ], "Title": "Using Entity Framework to Call an Oracle Stored Procedure with Multiple Cursors" }
208312
<p>I have done a small code in which with a wordlist (out68.lst) I get the passwords from the hashes in the file 'shadow3'.</p> <pre><code>import crypt import string import itertools import datetime dir = "shadow3" #File that contains hashes and users file = open(dir, 'r').readlines() username = [] hashed = [] k=0 for x in file: usr, hshd, wtf, iss, this, thing, here, doing, example = x.split(':') username.append(usr) hashed.append(hshd) #Loop in order to split the data in the file and store it in username and hashed grupo1=open('out68.lst','r').readlines() long=len(grupo1) print(long) for y in grupo1: #Loop in order to go through all the possible words available c = 0 y=y.rstrip('\n') y=y.capitalize() k = k+1 if k==(long//100): print('1%') if k==(long//10): print('10%') if k==(long//5): print('20%') if k==(3*long//10): print('30%') if k==(4*long//10): #Just to check the progress print('40%') if k==(5*long//10): print('50%') if k==(6*long//10): print('60%') if k==(7*long//10): print('70%') if k==(8*long//10): print('80%') if k==(9*long//10): print('90%') for x in hashed: rehashed = crypt.crypt(y, x) #Hash verification f(passwor+hash)=hash? if rehashed == x: print('La contraseña del usuario ' + username[c] + ' es ' + y) c = c + 1 </code></pre> <p>It does work but depending on the size of the files, it can last now from 30 minutes to 6 hours. So I am asking if there is any way to improve the performance, by paralelization, or GPU processing (but I have no idea about this).</p>
[]
[ { "body": "<p>Some suggestions:</p>\n\n<ul>\n<li>Run the code through at least one linter such as flake8 or pycodestyle to produce more idiomatic code.</li>\n<li>Don't read all the lines into a variable before starting processing - this will slow things down and use much more memory than necessary for large files. Instead you can use <a href=\"https://stackoverflow.com/q/1478697/96588\"><code>for line in file.readlines()</code></a>.</li>\n<li>You are doing ten calculations in order to run a single print statement. Either get rid of them or do something simpler like <code>print(\"{}/{} complete\".format(k, long))</code>.</li>\n<li>If you <em>know</em> <code>y</code> has exactly one newline at the end you can do <code>y[:-1]</code> instead of <code>y.rstrip('\\n')</code>.</li>\n<li>Capitalizing each word is expensive. Avoid it if at all possible.</li>\n<li>If you don't need a bunch of the fields in an input file add a limit to your <code>split()</code> and mark the last stuff as discarded by using the <code>_</code> variable. For example: <code>usr, hshd, _ = x.split(':', 3)</code></li>\n<li>Rather than keeping track of <code>k</code> manually you can just do <code>for k, y in enumerate(grupo1)</code>.</li>\n<li>Rather than having a list of usernames and a list of their hashed passwords, a <code>Dict[str, str]</code> of username to hash should be easier to keep track of.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T04:04:56.753", "Id": "208322", "ParentId": "208313", "Score": "3" } }, { "body": "<p>You should make sure you close files you open. This can be easily achieved using the <a href=\"http://effbot.org/zone/python-with-statement.htm\" rel=\"nofollow noreferrer\"><code>with</code></a> keyword:</p>\n\n<pre><code>file_name = \"shadow3\"\nwith open(file_name) as file:\n usernames, hashed_passwords = [], []\n for line in file:\n username, hashed_password, *_ = line.split(':')\n usernames.append(username)\n hashed_passwords.append(hashed_password)\n</code></pre>\n\n<p>Calling a file <code>dir</code> is just setting yourself up for trouble later. I also used the <a href=\"https://www.python.org/dev/peps/pep-3132/\" rel=\"nofollow noreferrer\">advanced tuple assignment</a> by using <code>*</code> to assign the rest of the line to the unused variable <code>_</code> (a customary name for unused variables).</p>\n\n<p>Note that <code>open</code> opens a file in read-only mode by default, so <code>'r'</code> is implicitly used.</p>\n\n<hr>\n\n<p>Whenever you want to iterate over an iterable but also need a counter, use <a href=\"https://docs.python.org/3.7/library/functions.html#enumerate\" rel=\"nofollow noreferrer\"><code>enumerate</code></a> and whenever you want to iterate over two iterables in tandem, use <a href=\"https://docs.python.org/3.7/library/functions.html#zip\" rel=\"nofollow noreferrer\"><code>zip</code></a>:</p>\n\n<pre><code>with open('out68.lst') as group:\n length = len(group)\n for k, password in enumerate(group):\n password = password.rstrip('\\n').capitalize()\n\n if k == length // 100 or k % (length // 10) == 0:\n print(f\"{k / length:.%}\")\n for username, hashed_password in zip(usernames, hashed_passwords):\n if crypt.crypt(password, hashed_password) == hashed_password:\n print(f'La contraseña del usuario {username} es {password}')\n</code></pre>\n\n<p>Here I also used modular arithmetic to cut down your special cases for ten percent increments, used the new <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\"><code>f-string</code></a> formatting.</p>\n\n<hr>\n\n<p>You might want to add some functionality where you save username password pairs if you have found some and remove them from the <code>usernames</code> and <code>hashed_passwords</code> lists so you don't keep on checking them once you found the password. To do this efficiently it might be necessary to change your data format to <code>{username: hashed_password}</code> and <code>{username: password}</code> for the yet to find and already found usernames.</p>\n\n<pre><code>file_name = \"shadow3\"\nusers = {}\nwith open(file_name) as file:\n for line in file:\n username, hashed_password, *_ = line.split(':')\n users[username] = hashed_password\n\ncracked_users = {}\nwith open('out68.lst') as group:\n length = len(group)\n for k, password in enumerate(group):\n password = password.rstrip('\\n').capitalize()\n if k == length // 100 or k % (length // 10) == 0:\n print(f\"{k / length:.%}\")\n if not users:\n print(\"Cracked all passwords\")\n break\n for username, hashed_password in users.items():\n if crypt.crypt(password, hashed_password) == hashed_password:\n print(f'La contraseña del usuario {username} es {password}')\n cracked_users[username] = password\n del users[username]\n</code></pre>\n\n<hr>\n\n<p>In general, don't be afraid of giving your variables clear names. If it is a username, call it <code>username</code>, not <code>usr</code>. If it is a hashed password, call it <code>hashed_password</code>, not <code>hshd</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T17:54:16.047", "Id": "402414", "Score": "0", "body": "Thank you for helping, I had problems changing the format because of the input file I think so I made this ` for x in hashed:\n rehashed = crypt.crypt(y, x)\n if rehashed == x:\n print('La contraseña del usuario ' + username[c] + ' es ' + y)\n del hashed[c]\n del username[c]\n c = c + 1` that this should work, right?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T09:59:01.837", "Id": "208329", "ParentId": "208313", "Score": "3" } } ]
{ "AcceptedAnswerId": "208322", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T00:11:07.920", "Id": "208313", "Score": "2", "Tags": [ "python", "performance", "cryptography", "hashcode" ], "Title": "Checking hash and passwords with a wordlist, more efficient" }
208313
<p>Specifically, how can I improve the time complexity of my algorithm (currently it is <code>O(listLength * numberOfLists)</code>)? It only beats 5% of accepted LeetCode solutions, which surprised me.</p> <pre><code>/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { private void advance(final ListNode[] listNodes, final int index) { listNodes[index] = listNodes[index].next; } public ListNode mergeKLists(final ListNode[] listNodes) { ListNode sortedListHead = null; ListNode sortedListNode = null; int associatedIndex; do { int minValue = Integer.MAX_VALUE; associatedIndex = -1; for (int listIndex = 0; listIndex &lt; listNodes.length; listIndex++) { final ListNode listNode = listNodes[listIndex]; if (listNode != null &amp;&amp; listNode.val &lt; minValue) { minValue = listNode.val; associatedIndex = listIndex; } } // An associated index of -1 indicates no more values left in any of the given lists if (associatedIndex != -1) { if (sortedListNode == null) { sortedListNode = new ListNode(minValue); sortedListHead = sortedListNode; } else { sortedListNode.next = new ListNode(minValue); sortedListNode = sortedListNode.next; } advance(listNodes, associatedIndex); } } while (associatedIndex != -1); return sortedListHead; } } </code></pre> <p>Note that the <code>Solution</code> class in addition to <code>ListNode</code> is already provided, the only code that I wrote was inside <code>mergeKLists</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T06:15:59.877", "Id": "402359", "Score": "0", "body": "You correctly determined the complexity of your approach. No surprise that it fares low. Strive for `O(listLength * log(numberOfLists))`." } ]
[ { "body": "<p>The time complexity is <span class=\"math-container\">\\$O(\\text{listLength} * \\text{numberOfLists}^2)\\$</span> because the check of <em>which node is the smallest?</em> is looking at one element of each list every iteration (so each iteration's complexity is <span class=\"math-container\">\\$O(\\text{numberOfLists})\\$</span>, and there are <span class=\"math-container\">\\$\\text{listLength} * \\text{numberOfLists}\\$</span> iterations.</p>\n\n<p>You can get to <span class=\"math-container\">\\$O(\\text{listLength} * \\text{numberOfLists} * \\log(\\text{numberOfLists}))\\$</span> by using a sorted list of the ListNode elements that you are checking in each iteration, instead of the unsorted array <code>listNodes</code>. Let's call this list <code>sortedNodes</code>. You can avoid checking each element of <code>sortedNodes</code> every iteration because you know the first one is the smallest, and once you take this first value into the merged list and advance the node - do a binary search to decide where to move the first element after its value has changed. (Or remove it if it got to a <code>null</code>.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T08:37:50.913", "Id": "208366", "ParentId": "208315", "Score": "1" } }, { "body": "<p>A <a href=\"https://codereview.stackexchange.com/questions/208315/merging-k-sorted-linked-lists#comment402359_208315\">comment</a> suggests that you can get <span class=\"math-container\">\\$\\mathcal{O}(n\\log{m})\\$</span>, where <span class=\"math-container\">\\$n\\$</span> is the total number of elements in all lists and <span class=\"math-container\">\\$m\\$</span> is the number of lists. How would you get <span class=\"math-container\">\\$\\mathcal{O}(n\\log{m})\\$</span>? The answer is to maintain a container of sorted lists. Two possible containers are a <code>SortedSet</code> (e.g. <code>TreeSet</code>) or a <code>PriorityQueue</code> (implemented with a heap). Both have <span class=\"math-container\">\\$\\mathcal{O}(\\log{m})\\$</span> insertions and removals. You would perform <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> insertions and removals (i.e. one for each element of the lists). <span class=\"math-container\">\\$\\mathcal{O}(n\\log{m})\\$</span> overall. </p>\n\n<p>Your current code is <span class=\"math-container\">\\$\\mathcal{O}(n\\cdot m)\\$</span>, so <span class=\"math-container\">\\$\\mathcal{O}(n\\log{m})\\$</span> would be an improvement asymptotically. </p>\n\n<p>Consider </p>\n\n<pre><code> public ListNode mergeKLists(final ListNode[] listNodes) {\n PriorityQueue&lt;ListNode&gt; lists = new PriorityQueue&lt;&gt;(Arrays.asList(listNodes));\n\n // create a dummy head so as to have the same logic for the first node as the others\n ListNode head = new ListNode(0);\n ListNode current = head;\n for (ListNode node = lists.poll(); node != null; node = lists.poll()) {\n current.next = new ListNode(node.val);\n current = current.next;\n\n if (node.next != null) {\n lists.add(node.next);\n }\n }\n\n return head.next;\n }\n</code></pre>\n\n<p>The <code>for</code> loop will run <span class=\"math-container\">\\$n\\$</span> times (once for each element in the lists). The <code>poll</code> and <code>add</code> operations will each take <span class=\"math-container\">\\$\\mathcal{O}(\\log{m})\\$</span> time. So <span class=\"math-container\">\\$\\mathcal{O}(n\\log{m})\\$</span> overall. The creation of the <code>PriorityQueue</code> will take <span class=\"math-container\">\\$\\mathcal{O}(m\\log{m})\\$</span>, so that's <span class=\"math-container\">\\$\\mathcal{O}((n + m)\\log{m})\\$</span>. If we assume that none of the lists are empty, then <span class=\"math-container\">\\$m &lt;= n\\$</span>, so <span class=\"math-container\">\\$\\mathcal{O}(n\\log{m})\\$</span>. </p>\n\n<p>We <code>return head.next</code> to avoid the problem of checking on each iteration if we are inserting the first element of the list. The <code>head</code> itself is not part of the list that we are creating, just a placeholder. Another alternative would be to create the first element outside the list. </p>\n\n<p>This code assumes that none of the entries in <code>listNodes</code> are null. If they can be, you'd need additional checking for that case. It also assumes that <code>ListNode</code> is comparable by <code>val</code>. If not, you'd have to pass a <code>Comparator</code> to the <code>PriorityQueue</code> constructor to implement that behavior. The <code>SortedSet</code> version is similar, with the same limitations. </p>\n\n<p>With a <code>Comparator</code> and capacity set, null checking, without a dummy head, and with <code>current</code> declared as part of the loop declaration (for better scoping, as <code>current</code> is not used outside the loop): </p>\n\n<pre><code> public ListNode mergeKLists(final ListNode[] listNodes) {\n PriorityQueue&lt;ListNode&gt; lists = new PriorityQueue&lt;&gt;(listNodes.length,\n new Comparator&lt;ListNode&gt;() {\n\n int compare(ListNode a, ListNode b) {\n return Integer.compare(a.val, b.val);\n }\n\n });\n\n for (ListNode node : listNodes) {\n if (node != null) {\n lists.add(node);\n }\n }\n\n if (lists.isEmpty()) {\n return null;\n }\n\n ListNode head = new ListNode(lists.poll().val);\n for (ListNode node = lists.poll(), current = head; node != null; node = lists.poll()) {\n current.next = new ListNode(node.val);\n current = current.next;\n\n if (node.next != null) {\n lists.add(node.next);\n }\n } \n\n return head;\n }\n</code></pre>\n\n<p>I think that the dummy head is actually easier, but you may find this form more readable. </p>\n\n<p>I haven't tested this, so beware of syntax errors, etc. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-25T17:58:00.523", "Id": "210319", "ParentId": "208315", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T00:12:34.790", "Id": "208315", "Score": "1", "Tags": [ "java", "algorithm", "linked-list" ], "Title": "Merging K Sorted Linked Lists" }
208315
<p>I'm trying to follow the <a href="https://drive.google.com/open?id=1_MZBMUSO25pg1gyeHa_D8WXu7r37CvC6" rel="noreferrer">Raytracing in One Weekend</a> book, and I found that he uses the same <code>Vec3</code> class for everything - colors, coordinates, direction, and more:</p> <pre><code>struct Vec3 { float x, y, z }; </code></pre> <p>He also overloads every possible operator of the <code>Vec3</code> class to make it convenient to use, and adds plenty of member functions (<code>length</code>, <code>distance_to</code>, etc). While this definitely reduces the amount of code one has to write, it isn't terribly safe, and allows for things doesn't make sense (why would you want a <code>distance_to</code> between two <code>Color</code>s?). I was trying to fix that.</p> <p>I defined a base Vector type:</p> <pre><code>struct Vector { Vector(float, float, float); float x; float y; float z; float length() const; }; </code></pre> <p>According to the <a href="https://en.wikipedia.org/wiki/Euclidean_vector#Overview" rel="noreferrer">Wikipedia</a> page, there can be 2 types of vectors - bound vectors (goes from point A to point B) and free vectors (the particular point is of no significance, only the magnitude and direction are). I defined these types too, but with very limited operators.</p> <p>Notice how you can add a <code>FreeVector</code> to a <code>BoundVector</code> to give a <code>BoundVector</code>, but you cannot add 2 <code>BoundVectors</code>:</p> <pre><code>struct BoundVector : public Vector { BoundVector(float, float, float); BoundVector&amp; operator+=(const FreeVector&amp;); BoundVector&amp; operator-=(const FreeVector&amp;); FreeVector operator-(const BoundVector&amp;) const; }; struct FreeVector : public Vector { FreeVector(float, float, float); explicit FreeVector(const UnitVector&amp;); FreeVector&amp; operator+=(const FreeVector&amp;); FreeVector&amp; operator-=(const FreeVector&amp;); FreeVector&amp; operator*=(float); FreeVector&amp; operator/=(float); UnitVector unit() const; float dot(const FreeVector&amp;) const; }; BoundVector operator+(BoundVector, const FreeVector&amp;); BoundVector operator-(BoundVector, const FreeVector&amp;); FreeVector operator+(FreeVector, const FreeVector&amp;); FreeVector operator-(FreeVector, const FreeVector&amp;); FreeVector operator*(FreeVector, float); FreeVector operator/(FreeVector, float); </code></pre> <p>I would have liked the <code>UnitVector</code> class to extend the <code>FreeVector</code> (or even the <code>Vector</code>) class, but I can't, since the implementation is completely different. For starters, to ensure that it is guaranteed to be a unit vector (<code>x*x + y*y + z*z == 1</code>) I have to make all members <code>const</code>:</p> <pre><code>struct UnitVector { UnitVector(float, float, float); explicit UnitVector(const FreeVector&amp;); const float x; const float y; const float z; FreeVector operator*(float) const; FreeVector operator/(float) const; private: UnitVector(float, float, float, float); }; UnitVector::UnitVector(const float x, const float y, const float z) : UnitVector(x, y, z, std::sqrt(x * x + y * y + z * z)) {} UnitVector::UnitVector(const FreeVector&amp; v) : UnitVector(v.x, v.y, v.z) {} FreeVector UnitVector::operator*(const float k) const { return FreeVector(x * k, y * k, z * k); } FreeVector UnitVector::operator/(const float k) const { return FreeVector(x / k, y / k, z / k); } UnitVector::UnitVector(const float x, const float y, const float z, const float r) : x{x / r}, y{y / r}, z{z / r} {} </code></pre> <p><code>UnitVectors</code> allow you to define directions in a much better manner:</p> <pre><code>struct Ray { BoundVector source; UnitVector direction; BoundVector parametric_eq(float) const; }; BoundVector Ray::parametric_eq(const float t) const { return source + direction * t; } </code></pre> <p>However, this is not all sunshine and roses, as it sometimes results in very ugly-looking <code>static_cast</code>s:</p> <pre><code>struct Lambertian : public Material { FreeVector albedo; std::optional&lt;Scatter&gt; scatter(const Ray&amp;, const Strike&amp;) const override; }; FreeVector random_in_unit_sphere() { std::random_device r; std::default_random_engine gen(r()); std::uniform_real_distribution&lt;float&gt; distribution(0, 1); while (true) { const FreeVector v(distribution(gen), distribution(gen), distribution(gen)); if (v.length() &lt; 1) return v; } } std::optional&lt;Scatter&gt; Lambertian::scatter(const Ray&amp; ray, const Strike&amp; strike) const { return Scatter{.attenuation = albedo, .scattered = Ray{.source = strike.point, .direction = static_cast&lt;UnitVector&gt;( static_cast&lt;FreeVector&gt;(strike.normal) + random_in_unit_sphere())}}; } </code></pre> <p>Note that the <code>std::optional</code> is added here because the material may choose to absorb the <code>Ray</code> completely with some probability, and hence not scatter it at all.</p> <p>Is there a way to reduce the number of <code>static_cast</code>s in the last example (or at least the overhead due to them)?</p> <p>Any other feedback, comments and nitpickings are also welcomed.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T01:57:21.457", "Id": "402350", "Score": "0", "body": "designated initializers are a very nice feature of C++20... but we're in 2018! I'm not even sure which compilers do support it already" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T02:02:45.417", "Id": "402351", "Score": "0", "body": "Strangely, CMake didn't support it so I couldn't use `set(CMAKE_CXX_STANDARD 2a)`, but GCC stopped complaining once I added `set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++2a)` to the CMakeLists.txt file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T06:25:31.290", "Id": "402361", "Score": "1", "body": "From a purely mathematical point of view, a bounded vector is in fact a pair of two free vectors. Try to model your classes with that in mind. A mathematical point of view could be very helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T11:53:56.360", "Id": "402395", "Score": "0", "body": "I did explore that option too, but I eventually settled for this (all bound vectors relative to the origin) because the bounded vectors were more space efficient (and even a little boost in efficiency really matters when you're doing raytracing). Although, in most cases, they are bound to the origin, in some cases in the book itself you come across a situation where the 2 free vector representation would have been helpful (such as the Camera class). In such cases, I used one bound vector position and a free vector to denote the direction taken from there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T17:21:53.837", "Id": "402941", "Score": "0", "body": "Is it intentional that we're missing the definitions of the the free functions declared immediately after `FreeVector`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T21:22:42.360", "Id": "403004", "Score": "0", "body": "@TobySpeight yep, since the implementation is rather obvious, and including it would lengthen the answer considerably. Instead, I put in the function prototypes to convey what _operations_ are possible. If need be, I can include that too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-29T08:55:30.647", "Id": "403069", "Score": "1", "body": "That's fine - I didn't want to answer if you needed to edit the question. BTW, there are subtleties to even such simple functions - I've seen implementations that do more copying than is necessary, for example." } ]
[ { "body": "<h1>Consider a typedef instead of hardcoding <code>float</code> everywhere</h1>\n\n<p>Whilst the current use-case requires <code>float</code>, we might want to convert to a template in future, so that we could use with <code>double</code> or <code>long double</code>. We can ease that by defining a type alias, so there's less work to change when we do so:</p>\n\n<pre><code>using value_type = float;\n</code></pre>\n\n<h1>Consider implementing unary minus</h1>\n\n<p>If we implement unary <code>operator-()</code> for <code>FreeVector</code>, we can use that to implement subtraction in terms of addition (without loss of efficiency).</p>\n\n<h1>Use standard Euclidean-length function</h1>\n\n<p>Instead of writing <code>std::sqrt(x * x + y * y + z * z)</code>, we could use <code>std::hypot()</code> instead for an algorithm that remains stable for very large and very small values. Since C++17, there's an overload that takes all three inputs:</p>\n\n<pre><code>float Vector::length() const {\n return std::hypot(x, y, z);\n}\n</code></pre>\n\n<h1>Could <code>UnitVector</code> be implemented using <code>FreeVector</code>?</h1>\n\n<p>Instead of having constant members (which of course inhibits assignment operators), perhaps it's worthwhile having a private <code>FreeVector</code> member in a <code>UnitVector</code>, and forwarding access? Something like this:</p>\n\n<pre><code>struct UnitVector\n{\n UnitVector(float x, float y, float z);\n explicit UnitVector(const FreeVector&amp; other);\n\n operator const FreeVector&amp;() const { return v; }\n\nprivate:\n FreeVector v;\n};\n\nUnitVector::UnitVector(const float x, const float y, const float z)\n : UnitVector{FreeVector{x, y, z}}\n{}\n\nUnitVector::UnitVector(const FreeVector&amp; v)\n : v{v / v.length()}\n{}\n</code></pre>\n\n<p>Note that I've provided a non-explicit conversion to <code>FreeVector</code>, as a replacement for the <code>FreeVector(UnitVector)</code> constructor. This means that we no longer need to implement arithmetic operators for <code>UnitVector</code>, as they will simply promote to <code>FreeVector</code> in such contexts.</p>\n\n<h1>Document the behaviour of indefinite unit vectors</h1>\n\n<p>What happens when we try to create a unit vector when its length is zero? I think we end up with all NaNs - we should make it clearer to users what they should expect (without them having to read the implementation). We might even need an <code>operator bool()</code> that tests whether any element of the vector is NaN.</p>\n\n<h1>Style - give names to formal parameters</h1>\n\n<p>It's subjective, but I think it makes an interface easier to read if the formal parameters have names, particularly when there are multiple arguments of the same type.</p>\n\n<h1>Kudos</h1>\n\n<p>I often forget to give this, so: well done on good use of <code>const</code> and <code>explicit</code>; I was pleased to see that the binary operations take one argument by copy and one by const-ref, so the copy can be modified and returned.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-01T04:43:23.933", "Id": "403385", "Score": "0", "body": "While I had considered the type alias, I wasn't sure whether to add `float` or `value_type` to parameters and return types. In case of a change, won't there be external functions that rely on having to work with a `float` that are suddenly forced to use whatever the new `value_type` is aliased to? Also, is `value_type` a standard naming practice, and should I be namespacing it to `geometry::value_type`? If yes, should I namespace everything else too?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-01T04:45:19.763", "Id": "403386", "Score": "0", "body": "You're right - the `UnitVector` divison by zero does give `NaN`. How would you suggest handling this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-03T09:19:38.630", "Id": "403602", "Score": "1", "body": "My suggestion is to provide the means to test whether the `UnitVector` is valid, and then leave it up to the user to check. But you could choose to throw an exception instead. You'll have to choose which best suits your users. As for `value_type`, as long as that's an alias of `float`, no change required by users - even when `Vector` becomes a template (provided the type defaults to `float`)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-29T11:05:19.777", "Id": "208681", "ParentId": "208317", "Score": "3" } } ]
{ "AcceptedAnswerId": "208681", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T01:52:42.700", "Id": "208317", "Score": "6", "Tags": [ "c++", "coordinate-system", "raytracing" ], "Title": "Type-safe Euclidean vectors in C++" }
208317
<p>I really like to use PDO because it's simple and easy to make a safe query, i prepared all queries and used placeholders, i think it's safe but i'm not sure at all, and I'm thinking if i used <code>trim()</code> the right way. What you guys think? Any doubt please ask me on the comments section.</p> <p>login.php</p> <pre><code>&lt;?php if($_SERVER['REQUEST_METHOD'] == 'POST'){ $email = trim($_POST['email']); try{ $Query = "SELECT * FROM users WHERE email = :email"; $statement = $conn-&gt;prepare($Query); $statement-&gt;bindValue(':email', $email); $statement-&gt;execute(); $user = $statement-&gt;fetch(PDO::FETCH_ASSOC); $RowCount = $statement-&gt;rowCount(); } catch (PDOerrorInfo $e){} if( $RowCount == 0 ){ // User doesn't exist $_SESSION['message'] = "Não existe um usuário com este e-mail."; header("location: error.php"); } else{ // User exists if( password_verify($_POST['password'], $user['password'])){ $_SESSION['email'] = $user['email']; $_SESSION['first_name'] = $user['first_name']; $_SESSION['last_name'] = $user['last_name']; $_SESSION['username'] = $user['username']; $_SESSION['img'] = $user['img']; $_SESSION['active'] = $user['active']; $_SESSION['logged_in'] = true; header("location: ../index.php"); } else { $_SESSION['message'] = "Senha incorreta, tente novamente!"; header("location: error.php"); } } } </code></pre> <p>register.php</p> <pre><code>&lt;?php $img = rand(0,30); $first_name = trim($_POST['first_name']); $last_name = trim($_POST['last_name']); $username = trim($_POST['username']); $email = trim($_POST['email']); $password = password_hash($_POST['password'], PASSWORD_BCRYPT); $hash = md5( rand(0,1000) ); // Check if user with that email already exists $result = $conn-&gt;prepare("SELECT * FROM users WHERE email = :email"); $result-&gt;bindParam(':email', $email); $result-&gt;execute(); $RowCount = $result-&gt;rowCount(); if ( $RowCount &gt; 0 ) { $_SESSION['message'] = 'Já existe um usuário com este e-mail!'; header("location: error.php"); } else { $sql = "INSERT INTO users (first_name, last_name, username, img, email, password, hash) VALUES (:first_name, :last_name, :username, :img, :email, :password, :hash)"; $sql = $conn-&gt;prepare($sql); $sql-&gt;bindParam(':first_name', $first_name); $sql-&gt;bindParam(':last_name', $last_name); $sql-&gt;bindParam(':username', $username); $sql-&gt;bindParam(':img', $img); $sql-&gt;bindParam(':email', $email); $sql-&gt;bindParam(':password', $password); $sql-&gt;bindParam(':hash', $hash); $sql-&gt;execute(); } </code></pre> <p>forgot.php</p> <pre><code>&lt;?php require 'db.php'; session_start(); if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) { $email = trim($_POST['email']); $result = $conn-&gt;prepare("SELECT * FROM users WHERE email = :email"); $result-&gt;bindValue(':email', $email); $result-&gt;execute(); $RowCount = $result-&gt;rowCount(); if ( $RowCount == 0 ) { $_SESSION['message'] = "Não existe um usuário com este e-mail."; header("location: error.php"); } else { $user = $result-&gt;fetch(PDO::FETCH_ASSOC); $email = $user['email']; $hash = $user['hash']; $first_name = $user['first_name']; $_SESSION['message'] = "&lt;p&gt;Link de confirmação enviado para &lt;span&gt;$email&lt;/span&gt;" . " clique no link para resetar a sua senha!&lt;/p&gt;"; $to = $email; $subject = 'Resetar senha - AnimeFire'; $message_body = ' Olá '.$first_name.' :), Você solicitou o resete de sua senha. Clique no link para resetar: https://localhost/login-system/reset.php?email='.$email.'&amp;hash='.$hash; mail($to, $subject, $message_body); header("location: success.php"); } } ?&gt; </code></pre> <p>reset.php</p> <pre><code>&lt;?php require 'db.php'; session_start(); if( isset($_GET['email']) &amp;&amp; !empty($_GET['email']) AND isset($_GET['hash']) &amp;&amp; !empty($_GET['hash']) ) { $email = trim($_GET['email']); $hash = trim($_GET['hash']); $result = $conn-&gt;prepared("SELECT * FROM users WHERE email = :email AND hash = :hash"); $result-&gt;bindValue(':email', $email); $result-&gt;bindValue(':hash', $hash); $result-&gt;execute(); $RowCount = $result-&gt;rowCount(); if ( $RowCount == 0 ) { $_SESSION['message'] = "A conta já foi verificada ou o URL é inválido!"; header("location: error.php"); } }else { $_SESSION['message'] = "A verificação falhou :/ tente novamente!"; header("location: error.php"); } ?&gt; </code></pre> <p>reset_password.php</p> <pre><code>&lt;?php require 'db.php'; session_start(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { if ( $_POST['newpassword'] == $_POST['confirmpassword'] ) { $new_password = password_hash($_POST['newpassword'], PASSWORD_BCRYPT); $email = trim($_GET['email']); $hash = trim($_GET['hash']); $sql = $conn-&gt;prepare("UPDATE users SET password = :new_password, hash = :hash WHERE email = :email"); $sql-&gt;bindValue(':new_password', $new_password); $sql-&gt;bindValue(':hash', $hash); $sql-&gt;bindValue(':email', $email); $sql-&gt;execute(); if ( $conn-&gt;prepare($sql) ) { $_SESSION['message'] = "Sua senha foi resetada com sucesso ^^"; header("location: success.php"); } } else { $_SESSION['message'] = "As senhas não estão iguais, tente novamente!"; header("location: error.php"); } } ?&gt; </code></pre> <p>profile.php</p> <pre><code>&lt;?php if (empty($_SESSION['email'])) { $_SESSION['message'] = "Você precisa estar logado para vizualizar esta página!"; header("location: error.php"); } else { $first_name = $_SESSION['first_name']; $last_name = $_SESSION['last_name']; $email = $_SESSION['email']; $username = $_SESSION['username']; $img = $_SESSION['img']; } ?&gt; &lt;img src="img/avatar/&lt;?= $img ?&gt;.jpg"&gt; &lt;h3 &gt;&lt;?= $username ?&gt;&lt;/h3&gt; &lt;h6 &gt;Nome: &lt;?= $first_name.' '.$last_name ?&gt;&lt;/h6&gt; &lt;h6 &gt;Email: &lt;?= $email ?&gt;&lt;/h6&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T12:33:08.140", "Id": "402398", "Score": "0", "body": "I don't see anything you need to change. You might want to consider passing your variables directly into the execute instead of binding them separately. For example use this when retrieving email: `$statement->execute([':email', $email]);`" } ]
[ { "body": "<p>The trim() function usage is OK.</p>\n\n<p>The biggest problem here is a hash security. A permanent <code>md5( rand(0,1000) );</code> hash is anything but security. It's so easily guessable that you can count it doesn't exist at all.</p>\n\n<p>Password reminder hashes are generated per request, each time anew. And it should be something less predictable, <a href=\"http://php.net/manual/en/function.random-bytes.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.random-bytes.php</a> for example.</p>\n\n<p>Other issues are so common that they made into my list of Top 10 PHP delusions:</p>\n\n<ul>\n<li><a href=\"https://phpdelusions.net/top#zero_error_reporting\" rel=\"nofollow noreferrer\">Empty try..catch is a big no-no</a>. Whatever your goal is, there are proper ways to achieve it.</li>\n<li><a href=\"https://phpdelusions.net/top#empty\" rel=\"nofollow noreferrer\">If (isset($var) &amp;&amp; !empty($var))</a> is essentially a tautology. You can and should use only empty() in this case.</li>\n<li><a href=\"https://phpdelusions.net/top#num_rows\" rel=\"nofollow noreferrer\">You don't really need to call rowCount()</a>. It does no harm if you do, but there is no reason. Better fetch the selected data, it can serve you as good as the number of rows.\n\n<ul>\n<li>besides, it makes the code in login.php a little bit more complicated that it could be. See my canonical example, <a href=\"https://phpdelusions.net/pdo_examples/password_hash\" rel=\"nofollow noreferrer\">Authenticating a user using PDO and password_verify()</a></li>\n</ul></li>\n</ul>\n\n<p>There is also a strange code snippet in reset_password.php, checking the result of prepare to test the success of the previous query makes no sense. Besides, given your error reporting is right, there is no need to check for the success at all, just do your redirect right away:</p>\n\n<pre><code> $sql-&gt;bindValue(':email', $email);\n $sql-&gt;execute();\n $_SESSION['message'] = \"Sua senha foi resetada com sucesso ^^\";\n header(\"location: success.php\"); \n exit;\n</code></pre>\n\n<p>it is also a very good habit to always add <code>exit</code> after every Location header call in your code, as a header itself doesn't mean thet the code execution has been stopped.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T13:21:04.827", "Id": "208335", "ParentId": "208319", "Score": "2" } } ]
{ "AcceptedAnswerId": "208335", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T02:53:27.450", "Id": "208319", "Score": "2", "Tags": [ "php", "security", "pdo", "session", "type-safety" ], "Title": "Login system with password reset sent to e-mail using PHP and PDO" }
208319
<p>Acquiring a form’s data for asynchronous POST requests has been a long-standing problem. There is the <a href="https://developer.mozilla.org/en-US/docs/Web/API/FormData" rel="nofollow noreferrer">FormData</a> API, but there are still some obstacles when the form’s data is encoded as <code>x-www-form-urlencoded</code> (the default).</p> <p>My current use case deals with arbitrary forms which might encode data either way; hence, I tried to generalize the way I construct the request’s body. Note that it’s intentional the form is submitted as an asynchronous request as the response is going to be rendered inside the current document.</p> <p>Can this generalization be simplified further?</p> <pre><code>document.querySelector('form').addEventListener('submit', performPostRequest); /** * Handles submit events that are about to perform a POST request. * * @param {Event} event */ function performPostRequest(event) { // Prevent the default action of sending a regular POST request. event.preventDefault(); const form = event.target; fetch(form.action, { method: 'post', headers: { 'Content-Type': `${form.enctype}; charset=UTF-8` }, body: constructRequestBody(form) }) .then(console.log) .catch(console.error); } /** * Encodes a form’s data for a POST request’s body. * * Supported encoding types: * * - `application/x-www-form-urlencoded` * - `multipart/form-data` * * @param {HTMLFormElement} form * @returns {FormData|URLSearchParams} */ function constructRequestBody(form) { const formData = new FormData(form); if (form.enctype === 'multipart/form-data') { return formData; } const requestBody = new URLSearchParams(); for (const [name, value] of formData) { requestBody.append(name, value); } return requestBody; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T09:29:52.433", "Id": "402374", "Score": "0", "body": "(Repost, link fixed) \n\"there are still some obstacles when the form’s data is encoded as x-www-form-urlencoded\" can you explain? Does [this](https://stackoverflow.com/a/38931547/2644192) resolve potential problems?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T09:33:58.640", "Id": "402376", "Score": "0", "body": "@Calak I’m referring to the problem I’m solving in the `constructRequestBody` function: Using a `FormData` object for a POST request with `x-www-form-urlencoded` data. The answer in the link you provided solves the problem, but it is more verbose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T09:38:37.520", "Id": "402379", "Score": "0", "body": "Does the *relative* verbosity is a real problem if your ending code is more robust and flexible?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T09:40:03.197", "Id": "402380", "Score": "0", "body": "@Calak The solution you linked to is not more robust or flexible than mine." } ]
[ { "body": "<blockquote>\n <p>Can this generalization be simplified further?</p>\n</blockquote>\n\n<pre><code>return new URLSearchParams(formData)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T08:07:06.210", "Id": "402546", "Score": "1", "body": "Oh, great! Since `formData[Symbol.iterator]` returns `formData.entries()`, it can be omitted from that call, too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T08:12:49.387", "Id": "402547", "Score": "0", "body": "Do you know whether this is implemented in most browsers? I tried Firefox and Chrome and it does work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T08:21:58.710", "Id": "402549", "Score": "0", "body": "@kleinfreund Have not tried Safari or Edge" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T15:19:50.113", "Id": "402915", "Score": "0", "body": "As of writing this comment only IE11 (and below) and some other browsers do not support URLSearchParams. Check here: https://caniuse.com/#feat=urlsearchparams" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T06:14:05.770", "Id": "208429", "ParentId": "208327", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T08:39:37.190", "Id": "208327", "Score": "0", "Tags": [ "javascript", "form", "ajax" ], "Title": "Preparing form data for a POST request with fetch" }
208327
<p>I need to evaluate some data. The rules how it should be done are changing frequently (it's an evolving model) so I don't want to rewrite my application each time such a change comes. I'd rather do it quickly via a config file.</p> <p>In order to make this possible I've designed a system of components that are very similar to <code>C#</code>'s expression trees and LINQ extensions. They can be put together to be used as decision trees or to calculate other results. It provides a couple of standard operations and needs to be extended by buisiness specific components.</p> <hr /> <h3>Core</h3> <p>The <code>Expression</code> type is the core. All other components are built from here. It's an interface and a class that provides the basic functionality.</p> <pre><code>public interface ISwitchable { [DefaultValue(true)] bool Enabled { get; } } [UsedImplicitly] public interface IExpression : ISwitchable { [NotNull] string Name { get; } [NotNull] IExpression Invoke([NotNull] IExpressionContext context); } public abstract class Expression : IExpression { protected Expression(string name) =&gt; Name = name; public virtual string Name { get; } public bool Enabled { get; set; } = true; public abstract IExpression Invoke(IExpressionContext context); } </code></pre> <p>The next level is represented by types that help me to implement standard logical operations or calculations:</p> <pre><code>public abstract class PredicateExpression : Expression { protected PredicateExpression(string name) : base(name) { } public override IExpression Invoke(IExpressionContext context) { using (context.Scope(this)) { return Constant.Create(Name, Calculate(context)); } } protected abstract bool Calculate(IExpressionContext context); } public abstract class AggregateExpression : Expression { private readonly Func&lt;IEnumerable&lt;double&gt;, double&gt; _aggregate; protected AggregateExpression(string name, [NotNull] Func&lt;IEnumerable&lt;double&gt;, double&gt; aggregate) : base(name) =&gt; _aggregate = aggregate; [JsonRequired] public IEnumerable&lt;IExpression&gt; Expressions { get; set; } public override IExpression Invoke(IExpressionContext context) =&gt; Constant.Create(Name, _aggregate(Expressions.InvokeWithValidation(context).Values&lt;double&gt;().ToList())); } public abstract class ComparerExpression : Expression { private readonly Func&lt;int, bool&gt; _predicate; protected ComparerExpression(string name, [NotNull] Func&lt;int, bool&gt; predicate) : base(name) =&gt; _predicate = predicate; [JsonRequired] public IExpression Left { get; set; } [JsonRequired] public IExpression Right { get; set; } public override IExpression Invoke(IExpressionContext context) { var result1 = Left.InvokeWithValidation(context); var result2 = Right.InvokeWithValidation(context); // optimizations if (result1 is Constant&lt;double&gt; d1 &amp;&amp; result2 is Constant&lt;double&gt; d2) return Constant.Create(Name, _predicate(d1.Value.CompareTo(d2.Value))); if (result1 is Constant&lt;int&gt; i1 &amp;&amp; result2 is Constant&lt;int&gt; i2) return Constant.Create(Name, _predicate(i1.Value.CompareTo(i2.Value))); // fallback to weak comparer var x = (result1 as IConstant)?.Value as IComparable ?? throw new InvalidOperationException($&quot;{nameof(Left)} must return an {nameof(IConstant)} expression with an {nameof(IComparable)} value.&quot;); var y = (result2 as IConstant)?.Value as IComparable ?? throw new InvalidOperationException($&quot;{nameof(Right)} must return an {nameof(IConstant)} expression with an {nameof(IComparable)} value.&quot;); ; return Constant.Create(Name, _predicate(x.CompareTo(y))); } } </code></pre> <hr /> <h3>Expressions</h3> <p>I use the above base classes to create the actual components with very few lines of code. They mostly use LINQ internally.</p> <pre><code>public class All : PredicateExpression { public All() : base(nameof(All)) { } [JsonRequired] public IEnumerable&lt;IExpression&gt; Expressions { get; set; } protected override bool Calculate(IExpressionContext context) { return Expressions .Enabled() .InvokeWithValidation(context) .Values&lt;bool&gt;() .All(x =&gt; x); } } public class Any : PredicateExpression { public Any() : base(nameof(Any)) { } [JsonRequired] public IEnumerable&lt;IExpression&gt; Expressions { get; set; } protected override bool Calculate(IExpressionContext context) { return Expressions .Enabled() .InvokeWithValidation(context) .Values&lt;bool&gt;() .Any(x =&gt; x); } } public class IIf : Expression { public IIf() : base(nameof(IIf)) { } [JsonRequired] public IExpression Predicate { get; set; } public IExpression True { get; set; } public IExpression False { get; set; } public override IExpression Invoke(IExpressionContext context) { using (context.Scope(this)) { var expression = (Predicate.InvokeWithValidation(context).Value&lt;bool&gt;() ? True : False) ?? throw new InvalidOperationException($&quot;{nameof(True)} or {nameof(False)} expression is not defined.&quot;); ; return expression.InvokeWithValidation(context); } } } public class Min : AggregateExpression { public Min() : base(nameof(Min), Enumerable.Min) { } } public class Max : AggregateExpression { public Max() : base(nameof(Max), Enumerable.Max) { } } public class Sum : AggregateExpression { public Sum() : base(nameof(Sum), Enumerable.Sum) { } } public class Equals : PredicateExpression { public Equals() : base(nameof(Equals)) { } [DefaultValue(true)] public bool IgnoreCase { get; set; } = true; public IExpression Left { get; set; } public IExpression Right { get; set; } protected override bool Calculate(IExpressionContext context) { var x = Left.InvokeWithValidation(context).ValueOrDefault(); var y = Right.InvokeWithValidation(context).ValueOrDefault(); if (x is string str1 &amp;&amp; y is string str2 &amp;&amp; IgnoreCase) { return StringComparer.OrdinalIgnoreCase.Equals(str1, str2); } return x.Equals(y); } } public class Matches : PredicateExpression { protected Matches() : base(nameof(Matches)) { } [DefaultValue(true)] public bool IgnoreCase { get; set; } = true; public IExpression Expression { get; set; } public string Pattern { get; set; } protected override bool Calculate(IExpressionContext context) { var x = Expression.InvokeWithValidation(context).Value&lt;string&gt;(); return !(x is null) &amp;&amp; Regex.IsMatch(x, Pattern, IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None); } } public class GreaterThan : ComparerExpression { public GreaterThan() : base(nameof(GreaterThan), x =&gt; x &gt; 0) { } } public class GreaterThanOrEqual : ComparerExpression { public GreaterThanOrEqual() : base(nameof(GreaterThanOrEqual), x =&gt; x &gt;= 0) { } } public class LessThan : ComparerExpression { public LessThan() : base(nameof(LessThan), x =&gt; x &lt; 0) { } } public class LessThanOrEqual : ComparerExpression { public LessThanOrEqual() : base(nameof(LessThanOrEqual), x =&gt; x &lt;= 0) { } } public class Not : PredicateExpression { public Not() : base(nameof(Not)) { } public IExpression Expression { get; set; } protected override bool Calculate(IExpressionContext context) =&gt; !Expression.InvokeWithValidation(context).Value&lt;bool&gt;(); } </code></pre> <hr /> <h3>Constant expression</h3> <p>There is also one very special expression which is the <code>Constant&lt;T&gt;</code>. No expression is allowed to return a <code>null</code> so they all must return either another expression or a <code>Constant&lt;T&gt;</code> expression. A constant is a type that can have a name and must have a <code>Value</code>. It also provides a bunch of helper factory methods to reduce the ammount of typing necessary to create them.</p> <pre><code>public interface IConstant { string Name { get; } object Value { get; } } public class Constant&lt;TValue&gt; : Expression, IEquatable&lt;Constant&lt;TValue&gt;&gt;, IConstant { public Constant(string name) : base(name) { } [JsonConstructor] public Constant(string name, TValue value) : this(name) =&gt; Value = value; [AutoEqualityProperty] [CanBeNull] public TValue Value { get; } [CanBeNull] object IConstant.Value =&gt; Value; public override IExpression Invoke(IExpressionContext context) { using (context.Scope(this)) { return this; } } public override string ToString() =&gt; $&quot;\&quot;{Name}\&quot; = \&quot;{Value}\&quot;&quot;; public static implicit operator Constant&lt;TValue&gt;((string name, TValue value) t) =&gt; new Constant&lt;TValue&gt;(t.name, t.value); public static implicit operator TValue(Constant&lt;TValue&gt; constant) =&gt; constant.Value; #region IEquatable public override int GetHashCode() =&gt; AutoEquality&lt;Constant&lt;TValue&gt;&gt;.Comparer.GetHashCode(this); public override bool Equals(object obj) =&gt; obj is Constant&lt;TValue&gt; constant &amp;&amp; Equals(constant); public bool Equals(Constant&lt;TValue&gt; other) =&gt; AutoEquality&lt;Constant&lt;TValue&gt;&gt;.Comparer.Equals(this, other); #endregion } public class One : Constant&lt;double&gt; { public One(string name) : base(name, 1.0) { } } public class Zero : Constant&lt;double&gt; { public Zero(string name) : base(name, 0.0) { } } public class True : Constant&lt;bool&gt; { public True(string name) : base(name, true) { } } public class False : Constant&lt;bool&gt; { public False(string name) : base(name, false) { } } public class String : Constant&lt;string&gt; { [JsonConstructor] public String(string name, string value) : base(name, value) { } } /// &lt;summary&gt; /// This class provides factory methods. /// &lt;/summary&gt; public class Constant { private static volatile int _counter; public static Constant&lt;TValue&gt; Create&lt;TValue&gt;(string name, TValue value) =&gt; new Constant&lt;TValue&gt;(name, value); public static Constant&lt;TValue&gt; Create&lt;TValue&gt;(TValue value) =&gt; new Constant&lt;TValue&gt;($&quot;{typeof(Constant&lt;TValue&gt;).ToPrettyString()}{_counter++}&quot;, value); public static IList&lt;Constant&lt;TValue&gt;&gt; CreateMany&lt;TValue&gt;(string name, params TValue[] values) =&gt; values.Select(value =&gt; Create(name, value)).ToList(); public static IList&lt;Constant&lt;TValue&gt;&gt; CreateMany&lt;TValue&gt;(params TValue[] values) =&gt; values.Select(Create).ToList(); } </code></pre> <hr /> <h3>Unit-testing</h3> <p>The <code>Constant</code> expression is also a great help for testing. Here are a couple of exmpales (the actual list is much longer):</p> <pre><code> [TestMethod] public void All_ReturnsTrueWhenAllTrue() =&gt; Assert.That.ExpressionsEqual(true, new All { Expressions = Constant.CreateMany(true, true, true) }); [TestMethod] public void All_ReturnsFalseWhenSomeFalse() =&gt; Assert.That.ExpressionsEqual(false, new All { Expressions = Constant.CreateMany(true, false, true) }); [TestMethod] public void All_ReturnsFalseWhenAllFalse() =&gt; Assert.That.ExpressionsEqual(false, new All { Expressions = Constant.CreateMany(false, false, false) }); [TestMethod] public void Any_ReturnsTrueWhenSomeTrue() =&gt; Assert.That.ExpressionsEqual(true, new Any { Expressions = Constant.CreateMany(false, false, true) }); [TestMethod] public void Any_ReturnsFalseWhenAllFalse() =&gt; Assert.That.ExpressionsEqual(false, new Any { Expressions = Constant.CreateMany(false, false, false) }); </code></pre> <p>They use my helper extension to reduce code repetition:</p> <pre><code>internal static class Helpers { public static void ExpressionsEqual&lt;TValue, TExpression&gt;(this Assert _, TValue expectedValue, TExpression expression, IExpressionContext context = null) where TExpression : IExpression { context = context ?? new ExpressionContext(); var expected = Constant.Create(expression.Name, expectedValue); var actual = expression.Invoke(context); if (!expected.Equals(actual)) { throw new AssertFailedException(CreateAssertFailedMessage(expected, actual)); } } private static string CreateAssertFailedMessage(object expected, object actual) { return $&quot;{Environment.NewLine}&quot; + $&quot;» Expected:{Environment.NewLine}{expected}{Environment.NewLine}&quot; + $&quot;» Actual:{Environment.NewLine}{actual}&quot; + $&quot;{Environment.NewLine}&quot;; } } </code></pre> <hr /> <h3>Invoking expressions</h3> <p>To <em>run</em> an expression you <code>Invoke</code> it by passing the <code>IExpressionContext</code></p> <pre><code>public interface IExpressionContext { [NotNull] IDictionary&lt;object, object&gt; Items { get; } [NotNull] ExpressionMetadata Metadata { get; } } public class ExpressionContext : IExpressionContext { public IDictionary&lt;object, object&gt; Items { get; } = new Dictionary&lt;object, object&gt;(); public ExpressionMetadata Metadata { get; } = new ExpressionMetadata(); } public class ExpressionMetadata { public string DebugView =&gt; ExpressionContextScope.Current.ToDebugView(); } </code></pre> <p>I usually use this context as a base class for a business context adding other properties to it (e.g. <code>CarName</code>)</p> <p>I borrowed also the idea of <code>Items</code> from <code>ASP.NET Core</code>'s <code>HttpContext.Items</code> and the <code>Metadata</code> from <code>EF Core</code>. I use the metadata to create a <code>DebugView</code> and to see where I am while testing the tree:</p> <hr /> <h3>Debug helpers</h3> <p>The <code>ExpressionContextScope</code> is inspired by the logger scope used in <code>ASP.NET Core</code>. Here it maintains the scope of expressions and the extension is used to build a string showing the position in the tree. (This is going to be more complex later and will render more information in to <code>DebugView</code>.)</p> <pre><code>[DebuggerDisplay(&quot;{&quot; + nameof(DebuggerDisplay) + &quot;,nq}&quot;)] public class ExpressionContextScope : IDisposable { // ReSharper disable once InconsistentNaming - This cannot be renamed because it'd confilict with the property that has the same name. private static readonly AsyncLocal&lt;ExpressionContextScope&gt; _current = new AsyncLocal&lt;ExpressionContextScope&gt;(); private ExpressionContextScope(IExpression expression, IExpressionContext context, int depth) { Expression = expression; Context = context; Depth = depth; } private string DebuggerDisplay =&gt; this.ToDebuggerDisplayString(builder =&gt; { builder.Property(x =&gt; x.Depth); }); public ExpressionContextScope Parent { get; private set; } public static ExpressionContextScope Current { get =&gt; _current.Value; private set =&gt; _current.Value = value; } public IExpression Expression { get; } public IExpressionContext Context { get; } public int Depth { get; } public static ExpressionContextScope Push(IExpression expression, IExpressionContext context) { var scope = Current = new ExpressionContextScope(expression, context, Current?.Depth + 1 ?? 0) { Parent = Current }; return scope; } public void Dispose() =&gt; Current = Current.Parent; } public static class ExpressionContextScopeExtensions { private const int IndentWidth = 4; public static string ToDebugView(this ExpressionContextScope scope) { var scopes = new Stack&lt;ExpressionContextScope&gt;(scope.Flatten()); var debugView = new StringBuilder(); foreach (var inner in scopes) { debugView .Append(IndentString(inner.Depth)) .Append(inner.Expression.Name) .Append(inner.Expression is IConstant constant ? $&quot;: {constant.Value}&quot; : default) .AppendLine(); } return debugView.ToString(); } private static string IndentString(int depth) =&gt; new string(' ', IndentWidth * depth); public static IEnumerable&lt;ExpressionContextScope&gt; Flatten(this ExpressionContextScope scope) { var current = scope; while (current != null) { yield return current; current = current.Parent; } } } </code></pre> <hr /> <h3>Using data from other expressions</h3> <p>There also a couple of cases where expressions like <code>TryGetCarColor</code> are not only used to determine whether a property exists but also should return a value that is used by other expression later.</p> <p>To make the framework more robust I decorate such expressions with <code>In</code> and/or <code>Out</code> attibutes that specify which values they expect or return. The in/out data is stored inside <code>Items</code>.</p> <pre><code>[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class InAttribute : Attribute, IParameterAttribute { public InAttribute(string name) =&gt; Name = name; public string Name { get; } public bool Required { get; set; } = true; } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class OutAttribute : Attribute, IParameterAttribute { public OutAttribute(string name) =&gt; Name = name; public string Name { get; } public bool Required { get; set; } = true; } </code></pre> <p>The framework validates their existence via</p> <blockquote> <pre><code>.InvokeWithValidation(context) </code></pre> </blockquote> <p>that checks whether all required in/out items exist:</p> <pre><code> public static IEnumerable&lt;IExpression&gt; InvokeWithValidation(this IEnumerable&lt;IExpression&gt; expressions, IExpressionContext context) { return from expression in expressions select expression .ValidateInItems(context) .Invoke(context) .ValidateOutItems(context); } </code></pre> <p>This way (if everything is properly decorated) I can be sure that each expression will receive it's data and doesn't need any additional checks.</p> <hr /> <h3>Example</h3> <p>Here's an example of a real-world epxpression tree. (I've anonymized it by only changing the name of the business specific expressions like <code>HasColor</code> etc. the tree by itself is the same.)</p> <p>As you can see I use it to evaluate a couple of conditions and then based on them perfom a calculation. Business specific expressions such as <code>HasColor</code> or <code>SeatCount</code> are also derived from <code>Expression</code> but they evaluate the business data.</p> <pre class="lang-js prettyprint-override"><code>{ &quot;$t:&quot;: &quot;IIf&quot;, &quot;Predicate&quot;: { &quot;$t&quot;: &quot;Not&quot;, &quot;Expression&quot;: { &quot;$t&quot;: &quot;Any&quot;, &quot;Expressions&quot;: [ { &quot;$t&quot;: &quot;All&quot;, &quot;Expressions&quot;: [ { &quot;$t&quot;: &quot;HasColor&quot;, &quot;Values&quot;: [ &quot;Red&quot;, &quot;Blue&quot; ] }, { &quot;$t&quot;: &quot;HasFeature&quot;, &quot;Values&quot;: [ &quot;PowerSteering&quot; ] } ] }, { &quot;$t&quot;: &quot;IIf&quot;, &quot;Predicate&quot;: { &quot;$t&quot;: &quot;HasColor&quot;, &quot;Values&quot;: [ &quot;Red&quot; ] }, &quot;True&quot;: { &quot;$t&quot;: &quot;Not&quot;, &quot;Expression&quot;: { &quot;$t&quot;: &quot;HasFeature&quot;, &quot;Values&quot;: [ &quot;PowerBrake&quot; ] } }, &quot;False&quot;: { &quot;$t&quot;: &quot;Constant&lt;double&gt;&quot;, &quot;Value&quot;: 1 } } ] } }, &quot;True&quot;: { &quot;$t&quot;: &quot;Sum&quot;, &quot;Expressions&quot;: [ { &quot;$t&quot;: &quot;Color&quot; }, { &quot;$t&quot;: &quot;SeatCount&quot; }, { &quot;$t&quot;: &quot;IIf&quot;, &quot;Predicate&quot;:{ &quot;$t&quot;: &quot;HasFeature&quot;, &quot;Values&quot;: [ &quot;PowerBrake&quot; ] }, &quot;True&quot;: { &quot;$t&quot;: &quot;Constant&lt;double&gt;&quot;, &quot;Value&quot;: 3, }, &quot;False&quot;: null } ] }, &quot;False&quot;: null } </code></pre> <p>This means that in code you'd have:</p> <pre><code>var result = carValueExpression.Invoke(new CarStockExpressionContext { // ... general car data // other data can be pulled from a db by any business expression }).Value&lt;double&gt;(); </code></pre> <hr /> <p>I find this is very easy to test and to extend because everything can be covered by unit-tests. Knowing that all components work as expected, it's a piece of cake to put them together so that they can do much bigger things.</p> <hr /> <p>In case you are wondering what those <code>$t</code> are and why the types are not named by their full names, I'm using here my json.net <a href="https://codereview.stackexchange.com/questions/205940/making-typenamehandling-in-json-net-more-convenient">helper</a> for more friendly type handling.</p> <hr /> <p>What do you think about this framework? Did I forget to implement anything important or could I have done it better?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T15:16:45.570", "Id": "402470", "Score": "1", "body": "It looks like you've written a tiny scripting language with a JSON-based syntax. The example looks rather verbose - in C# that would only take a handful of lines. Are you sure this will make it easier to adjust and maintain your program?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T15:34:58.900", "Id": "402474", "Score": "0", "body": "@PieterWitvoet oh yeah, I'm pretty sure and it's already paying off ;-) being able to introduce changes that do not require the entire development and deployment process is a great time saver. This should be seen as a slightly more complex configuration rather than a scripting language." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T09:15:56.453", "Id": "402553", "Score": "0", "body": "I'm trying to get this to work, but it's missing several definitions that cannot easily be stubbed: `Scope(this IExpression)`, `InvokeWithValidation(this IExpression)`, `Values<T>(this IEnumerable<IExpression>)`, `ValidateInItems(this IExpression, IExpressionContext)` and `ValidateOutItems(this IExpression, IExpressionContext)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T09:18:33.777", "Id": "402555", "Score": "1", "body": "@PieterWitvoet oh, sorry... posting everything would probably be too much but you can find the complete code [here](https://github.com/he-dev/Reusable/tree/dev) in my repository and exactly in [this](https://github.com/he-dev/Reusable/tree/dev/Reusable.Flexo) project and [this](https://github.com/he-dev/Reusable/tree/dev/Reusable.Tests/src/Flexo) are my tests that I have so far in the open-source part." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T10:30:02.637", "Id": "402556", "Score": "0", "body": "Thanks. So the `Color`, `SeatCount`, `HasColor` and `HasFeature` expressions in the example would be business-specific extensions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T10:32:56.217", "Id": "402557", "Score": "0", "body": "@PieterWitvoet exactly. This is just the general framework. The business case needs to implement its own special expressions that actually do something useful with its own business objects etc. [this](https://github.com/he-dev/Reusable/blob/dev/Reusable.Tests/res/OmniLog/OmniLog.json) is an experiment where I was designing a log-filter utilizing it (its API however is not longer up-to-date)." } ]
[ { "body": "<p>I think there's a lot of room for improvement here. The 'syntax' could be made less verbose and extending the system could be made easier with a better selection of core expressions, among other things.</p>\n\n<h1>Syntax</h1>\n\n<p>Using JSON as a serialization format saves a lot of work, but the resulting syntax is, in my opinion, quite terrible. 60+ lines of JSON, littered with repetitive <code>$t</code>'s and property names, for just a couple of lines of code. That makes these scripts difficult to write and read, increasing the likelyhood of bugs and the cost of fixing them. For example, let's translate that example to C#:</p>\n\n<pre><code>if (!(HasColor(\"Red\", \"Blue\") &amp;&amp; HasFeature(\"PowerSteering\")) ||\n HasColor(\"Red\") ? !HasFeature(\"PowerBrake\") : 1.0)\n{\n if (Color + SeatCount + HasFeature(\"PowerBrake\"))\n {\n return 3.0;\n }\n}\n</code></pre>\n\n<p>It's now much more obvious that the code is broken: it's adding a color, a number and a boolean together and treating it as a boolean. It's also missing else branches so it's not always returning a result, and there's an if-statement that returns either a boolean or a number, depending on its condition. The logic itself is also somewhat complicated - a few descriptively named local variables would be helpful.</p>\n\n<p><strong>Alternatives</strong></p>\n\n<p>I'd suggest taking some inspiration from Lisp, in this case the s-expression format it uses:</p>\n\n<pre><code>(if (not (any (all (HasColor \"Red\" \"Blue\")\n (HasFeature \"PowerSteering\"))\n (if (HasColor \"Red\")\n (not (HasFeature \"PowerBrake\"))\n 1.0)))\n (sum Color\n SeatCount\n (if (HasFeature \"PowerBrake\")\n 3.0)))\n</code></pre>\n\n<p>Quite readable if you ask me, and fairly easy to parse as well. Parenthesis denote lists, and the first item in a list is either a function or a special form (a keyword), with the rest of the items being arguments (or keyword-specific parts). You could do something similar with JSON arrays. It'll be less terse, and you may have to get creative to distinguish between identifiers and strings (I've prefixed identifiers with a <code>'</code> below), but it could be a reasonable trade-off between development time and usability:</p>\n\n<pre><code>[\"'if\", [\"'not\", [\"'any\", [\"'all\", [\"'HasColor\", \"Red\", \"Blue\"],\n [\"'HasFeature\", \"PowerSteering\"]],\n [\"'if\", [\"'HasColor\", \"Red\"],\n [\"'not\", [\"'HasFeature\", \"PowerBrake\"]],\n 1.0]]],\n [\"'sum\", \"'Color\",\n \"'SeatCount\",\n [\"'if\", [\"'HasFeature\", \"PowerBrake\"],\n 3.0]]]\n</code></pre>\n\n<hr>\n\n<h1>Expressions</h1>\n\n<p>If you look at the types in <code>System.Linq.Expressions</code>, you'll notice that all of them represent a <em>language construct</em>. Most of your expression types however represent standard library <em>functions</em>. This means that in C#, you only need to extend the language if you want to introduce a new syntactical construct. But in your language, every function and variable you wish to expose requires an extension.</p>\n\n<p>I would replace all of <code>Min</code>, <code>Max</code>, <code>Sum</code>, <code>Equals</code>, <code>Matches</code>, <code>GreaterThan</code>, <code>GreaterThanOrEqual</code>, <code>LessThan</code>, <code>LessThanOrEqual</code>, <code>Not</code> and other application-specific expression classes with just two expression types: <code>FunctionCall</code> and <code>Identifier</code>. That enables a more data-driven extension approach:</p>\n\n<pre><code>// Initialize the context with bindings to standard library functions:\ncontext.Items[\"Min\"] = StandardFunctions.Min;\n\n// Which can then be referenced via identifiers:\nnew FunctionCall(\n function: new Identifier(\"Min\"),\n arguments: new IExpression[] {\n new Constant&lt;double&gt;(4.0),\n new Identifier(\"height\")\n });\n</code></pre>\n\n<p>Other useful expression types would be <code>MemberAccess</code> and <code>Index</code>, and perhaps a <code>Scope</code> expression that allows you to introduce local variables:</p>\n\n<pre><code>// [scope, [[local-identifier, value-expression], ...], body-expression]:\n// [member, object-expression, member-identifier]:\n// [index, indexable-expression, index-expression]:\n[\"'scope\", [[\"'minHeight\", 12.5],\n [\"'maxHeight\", 37.5],\n [\"'firstCarHeight\", [\"'member\", [\"'index\", \"'cars\", 0], \"'height\"]]],\n [\"'all\", [\"'&gt;=\", \"'firstCarHeight\", \"'minHeight\"],\n [\"'&lt;=\", \"'firstCarHeight\", \"'maxHeight\"]]]\n</code></pre>\n\n<hr>\n\n<h1>Usability</h1>\n\n<p>Other (mostly usability) issues:</p>\n\n<ul>\n<li>A lack of documentation. There are almost no comments in the code, and there's no high-level explanation of how the system is meant to be used. How does each expression work? Are all their parts required or are some optional? What types does each expression expect and return? How should the system be extended? How are those <code>In</code>/<code>Out</code> attributes supposed to work?</li>\n<li>A confusing 'entry-point': <code>ExpressionSerializer.Deserialize</code> takes a generic parameter, but the most obvious choice, <code>IExpression</code>, failed (due to a typo in your example, I later found out). I would've expected a more simple signature like <code>IExpression Parse(...)</code> instead.</li>\n<li>Error reporting could be better. A few examples:\n\n<ul>\n<li>A <code>\"$t:\"</code> typo in your example resulted in a serialization exception that did point out the location, but the rest of the message wasn't very helpful (<code>Type is an interface or abstract class and cannot be instantiated.</code>).</li>\n<li>Trying to sum two incompatible types gives an invalid-expression exception that says <code>Invalid expression type. Expected: Constant`1; Actual: Constant`1.</code>. That doesn't show the actual types or the location of the problem.</li>\n<li>Evaluating an empty <code>IIf</code> expression resulted in a null-reference exception. I would've expected a parsing failure instead.</li>\n</ul></li>\n<li>What's with the typo in <code>IIf</code>?</li>\n<li><code>ISwitchable</code>'s <code>Enabled</code> only affects child expressions within <code>Any</code> and <code>All</code> expressions, yet every expression is switchable regarless of their parent. How exactly are expressions disabled in practice, and shouldn't this be taken care of by <code>Any</code> and <code>All</code> instead?</li>\n<li>Why does <code>ExpressionContextScope</code> have a <em>static</em> <code>Current</code> property? That seems brittle.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-04T16:36:17.417", "Id": "403783", "Score": "0", "body": "Oh boy, I'm sorry, I somehow missed the notification that you've posted an answer. I'm reading it now ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-04T16:54:25.433", "Id": "403789", "Score": "0", "body": "These are a lot of cool ideas so I'll see how I can use them. I think I'm not ready to create an entire new parser and logic yet but I see your point and I'll consider it with the next version... usually it's not that far in future until you hit the limits of something ;-) I have also a couple of answers to your questions and maybe explanations too. You're right, I picked JSON because I'm lazy and it's easy to use. [...]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-04T16:57:09.030", "Id": "403790", "Score": "0", "body": "[...] I chose to use the type `$t` for each expression because my production expressions need to be able to get their dependencies from `Autofac` and I didn't want to resolve them by myself. json.net is doing a good job here. You're right about the super unhelpful type names like `Constant`1`, I have my extension for it that I call [`ToPrettyString`](https://github.com/he-dev/Reusable/blob/dev/Reusable.Core/src/PrettyString.cs) that is supposed to produce nicer names. Making excepiton handling helpufl is as difficult as creating the actual library so I'll better create some test for it. [...]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-04T17:04:49.047", "Id": "403793", "Score": "0", "body": "[...] _What's with the typo in `IIf`_ - this is by convention see [IIf](https://en.wikipedia.org/wiki/IIf) so I kept this ;-) Expressions are `ISwitchable` because it's often easer to simply disable something and experiment without it for a moment than remove this part; You're right this affects expressions only if they are used in collection expression like `All/Any/Sum` etc - I see I need to give it another thought. `Current` must be _`async-static`_ because this way I can open a new scope anywhere and don't need the object that holds it. I can also use it in an `async` context. [...]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-04T17:05:36.640", "Id": "403794", "Score": "0", "body": "[...] The scope is adapted from the `LoggerScope` used by `ASP.NET Core` and also my custom logger. It's a very useful _pattern_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-05T08:26:55.427", "Id": "403901", "Score": "0", "body": "I was beginning to wonder about the lack of reaction, heh. ;) I didn't know about `IIf`, but apparently it's a function that evaluates all of its arguments, while your expression only evaluates one of the branches, like `if` does. 'Scope' in this context typically refers to the visibility and lifetime of variables, but here it's used to build an indented log for debugging purposes, so I think the name is a little confusing. As for static, can't you move those 'log-scopes' into `IExpressionContext`? If you evaluate two scripts in parallel then each should have its own log." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-05T08:34:32.883", "Id": "403903", "Score": "0", "body": "It's not necessary to move the socpe to the context. The trick is that there can be only a single scope per thread or per anyc-context anyway, that's why it's using `AsyncLocal<T>`. This is separating the instances and keeping them alive along the path. Yeah, the `IIf` evaluating all expression is a dangerous thing that I'd rather not do. It would be equally bad as the all conditions evaluating `if` in `VBA` - a real pain :-]" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-29T21:03:31.740", "Id": "208716", "ParentId": "208332", "Score": "3" } } ]
{ "AcceptedAnswerId": "208716", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T11:37:34.390", "Id": "208332", "Score": "5", "Tags": [ "c#", "framework", "expression-trees", "json.net" ], "Title": "Adjusting business logic conveniently through JSON and expression trees" }
208332
<p>I have implemented <a href="https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm" rel="nofollow noreferrer">Pollard's Rho algorithm</a> in <code>Java</code>. Due to the nature of it there is a <em>small chance</em> for it to fail (have not seen it happening yet).</p> <p>Since I do not want to see my unit tests failing due to this <em>"too often"</em>, I set a retry, with which I am not totally satisfied, as you can see here:</p> <pre><code>@Test void primeFactorsCalculatedWithPollardsRhoAreCorrect() { Operations op = new Operations(); int remainingAttempts = 5; while (true) { try { assertEquals(5, op.primeFactorsPollardRho(13195)); break; } catch (UnsupportedOperationException e) { remainingAttempts -= 1; if (remainingAttempts == 0) { throw e; } } } } </code></pre> <p>I am using <code>jUnit</code>.</p> <p>Is there a better, more pleasing to the eye, way of doing this?</p>
[]
[ { "body": "<p>Your test is missing the central point of unit testing which is to prove the code under test works in the specific circumstances in question, these should be deterministic. So for each parameter you can know in advance what the result <strong>should be</strong>. Create multiple unit tests for the known factors that should work and a number for the parameters expected to fail.</p>\n\n<p>Secondly, I suggest you create your own Checked Exception for the failing circumstance rather than reusing the runtime <code>UnsupportedOperationException</code>, this will ensure a client using your function/library is forced to handled the exception. When the error can be handled use a checked exception, only use the unchecked runtime exceptions when the error cannot be handled by the code. If the program can, it should still fail gracefully with either. I can see that is what you are trying to achieve for your live code but visibility of the issue is more important in unit tests.</p>\n\n<p>The client code handling exception could skip the value and proceed to the next value. Simply retrying with the same value should produce the same result, so the retry with the same value is actually pointless.</p>\n\n<p>You can verify that the test produces the result you expect by catching the expected failure with the expected Exception clause of the <code>@Test</code> annotation.</p>\n\n<pre><code>@Test(expected = BirthdayParadoxException.class) \npublic void testBirthdayParadox() {\n op.primeFactorsPollardRho(BIRTHDAY_PARADOX_VALUE); \n}\n\n@Test \npublic void testPassingValue() {\n assertEquals(EXPECTED_RESULT, op.primeFactorsPollardRho(FACTORABLE_VALUE); \n}\n</code></pre>\n\n<p>Create multiple tests for each specific situation you can predict and verify the expected behaviour, catching failures should be considered expected behaviour for unit testing purposes. </p>\n\n<p>Also see : <a href=\"https://github.com/junit-team/junit4/wiki/Exception-testing\" rel=\"nofollow noreferrer\">https://github.com/junit-team/junit4/wiki/Exception-testing</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T01:36:48.287", "Id": "402437", "Score": "0", "body": "It might be worth adding a sentence on the value of fuzzing. While unit tests should be deterministic, having non-deterministic tests can be very useful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T08:51:58.237", "Id": "402552", "Score": "0", "body": "I could then pass `g(x)` in Pollard's Rho as a `lambda` to the method, to guarantee a deterministic output for the unit tests." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T19:31:51.157", "Id": "208344", "ParentId": "208341", "Score": "2" } } ]
{ "AcceptedAnswerId": "208344", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T17:55:34.380", "Id": "208341", "Score": "2", "Tags": [ "java", "unit-testing", "primes", "error-handling", "junit" ], "Title": "Testing a probabilistic prime-testing algorithm that may fail" }
208341
<p>This is a game for two users who roll 2 dice 5 times. If the total of dice is even the player gains 10 points if it is odd, they lose 5.</p> <p>If there it is a draw after five rounds then the both users will have to roll one die to determine the winner.</p> <pre><code>from random import randint from time import sleep import time import sys import random import operator total_score2 = 0 total_score1 = 0 rounds = 0 playerOnePoints = 0 playerTwoPoints = 0 print("*****************Welcome To The DICE Game*******************") print("Please enter 'n' if you are a new user and 'e' if you are a exsiting user and enter 's' to display scores") ens=input("") while ens != ("e") and ens != ("n") and ens != ("s"): # if anything else but these characters are entered it will loop until it is correct print("Please enter 'n' if you are a new user and 'e' if you are a exsiting user and enter 's' to display scores") ens = input() if ens == "s": s = open("scores.txt","r") file_content = s.read().splitlines() users_points = {i.split()[0]: int(i.split()[2]) for i in file_content} best_player = max(users_points.items(), key=operator.itemgetter(1))[0] print("LeaderBoard: ") print("\n") print('player with maximum points is {}, this player has {} points'.format(best_player, users_points[best_player])) best_players = sorted(users_points, key=users_points.get, reverse=True) for bp in best_players: print('{} has {} points'.format(bp, users_points[bp])) # This prints all players scores if ens == "n": username=input("Please enter appropiate username: ") password1=input("Please enter password: ") password2=input("Please re-enter password: ") if password1 == password2: # checking if both passwords entered are the same print("your account has been successfully been made Thankyou") file = open("accountfile.txt","a") file.write("username: ") file.write(username) file.write(" ") file.write("password: ") file.write(password2) file.write("\n") file.close() print("Please enter 'n' if you are a new user and 'e' if you are a exsiting user") ens=input(" ") if password1 != password2: # if passwords entered are not the same will loop until they are correctly entered correctPassword=(password1) while True: password=input('Enter password again ') if password == correctPassword: print('Correct password has been entered') f = open ("accountfile.txt","a+") f.write("username: ") f.write(username) f.write(" ") f.write("password: ") f.write(correctPassword) f.write("\n") f.close() print("Please enter 'n' if you are a new user and 'e' if you are a exsiting user") en=input(" ") print('Incorrect password ') if ens == "e": counter = 0 check_failed = True while check_failed: print("Could player 1 enter their username and password") username1=input("Please enter your username ") password=input("Please enter your password ") with open("accountfile.txt","r") as username_finder: for line in username_finder: if ("username: " + username1 + " password: " + password) == line.strip(): print("you are logged in") check_failed = False counter = 0 check_failed = True while check_failed: print("Could player 2 enter their username and password") username2=input("Please enter your username ") password=input("Please enter your password ") with open("accountfile.txt","r") as username_finder: for line in username_finder: if ("username: " + username2 + " password: " + password) == line.strip(): print("you are logged in") check_failed = False time.sleep(1) print("Welcome to the dice game") time.sleep(1) while rounds &lt; 5: total_score2 = total_score2 + playerTwoPoints total_score1 = total_score1 + playerOnePoints rounds = rounds + 1 number = random.randint(1,6) number2 = random.randint(1,6) playerOnePoints = number + number2 print("Round",rounds) print("-------------------------------------------") print("Player 1's turn Type 'roll' to roll the dice") userOneInput = input("&gt;&gt;&gt; ") if userOneInput == "roll": time.sleep(1) print("Player 1's first roll is", number) print("Player 1's second roll Type 'roll' to roll the dice") userOneInput = input("&gt;&gt;&gt; ") if userOneInput == "roll": time.sleep(1) print("player 1's second roll is", number2) if playerOnePoints &lt;= 0: playerOnePoints = 0 if playerOnePoints % 2 == 0: playerOnePoints = playerOnePoints + 10 print("Player 1's total is even so + 10 points") print("-------------------------------------------") print("Player 1 has",playerOnePoints, "points") else: playerOnePoints = playerOnePoints - 5 print("player 1's total is odd so -5 points") print("-------------------------------------------") print("Player 1 has",playerOnePoints, "points") if playerOnePoints &lt;= 0: playerOnePoints = 0 number = random.randint(1,6) number2 = random.randint(1,6) playerTwoPoints = number + number2 print("-------------------------------------------") print("Player 2's turn Type 'roll' to roll the dice") userTwoInput = input("&gt;&gt;&gt; ") if userTwoInput == "roll": time.sleep(1) print("Player 2's first roll is", number) print("Player 2's second roll Type 'roll' to roll the dice") userTwoInput = input("&gt;&gt;&gt; ") if userTwoInput == "roll": time.sleep(1) print("player 2's second roll is", number2) if playerTwoPoints &lt;= 0: playerTwoPoints = 0 if playerTwoPoints % 2 == 0: playerTwoPoints = playerTwoPoints + 10 print("Player 2's total is even so + 10 points") print("-------------------------------------------") print("Player 2 has",playerTwoPoints, "points") else: playerTwoPoints = playerTwoPoints - 5 print("player 2's total is odd so -5 points") print("-------------------------------------------") print("Player 2 has",playerTwoPoints, "points") print("-------------------------------------------") print("Total score for player 1 is", total_score1) print("-------------------------------------------") print("Total score for player 2 is", total_score2) print("-------------------------------------------") if total_score1 &gt; total_score2: print("Player 1 Wins!") file = open("scores.txt","a") file.write(username1) file.write(" has ") file.write(str(total_score1)) file.write(" points") file.write("\n") file.close() sys.exit() if total_score2 &gt; total_score1: print("Player 2 Wins!") file = open("scores.txt","a") file.write(username2) file.write(" has ") file.write(str(total_score2)) file.write(" points") file.write("\n") file.close() sys.exit() if total_score1 == total_score2: print("Its a draw!") print("So both players will have to roll one more dice") time.sleep(2) print("-------------------------------------------") print("Player 1's turn Type 'roll' to roll the dice") userOneInput = input("&gt;&gt;&gt; ") if userOneInput == "roll": time.sleep(1) print("Player 1's first roll is", number) print("Player 1's second roll Type 'roll' to roll the dice") userOneInput = input("&gt;&gt;&gt; ") if userOneInput == "roll": time.sleep(1) print("player 1's second roll is", number2) if playerOnePoints % 2 == 0: playerOnePoints = playerOnePoints + 10 print("Player 1's total is even so + 10 points") print("-------------------------------------------") print("Player 1 has",playerOnePoints, "points") else: playerOnePoints = playerOnePoints - 5 print("player 1's total is odd so -5 points") print("-------------------------------------------") print("Player 1 has",playerOnePoints, "points") number = random.randint(1,6) number2 = random.randint(1,6) playerTwoPoints = number + number2 print("-------------------------------------------") print("Player 2's turn Type 'roll' to roll the dice") userTwoInput = input("&gt;&gt;&gt; ") if userTwoInput == "roll": time.sleep(1) print("Player 2's first roll is", number) print("Player 2's second roll Type 'roll' to roll the dice") userTwoInput = input("&gt;&gt;&gt; ") if userTwoInput == "roll": time.sleep(1) print("player 2's second roll is", number2) if playerTwoPoints % 2 == 0: playerTwoPoints = playerTwoPoints + 10 print("Player 2's total is even so + 10 points") print("-------------------------------------------") print("Player 2 has",playerTwoPoints, "points") else: playerTwoPoints = playerTwoPoints - 5 print("player 2's total is odd so -5 points") print("-------------------------------------------") print("Player 2 has",playerTwoPoints, "points") print("-------------------------------------------") if total_score1 &gt; total_score2: print("Player 1 Wins!") file = open("scores.txt","a") file.write(username1) file.write(" has ") file.write(str(total_score1)) file.write(" points") file.write("\n") file.close() if total_score2 &gt; total_score1: print("Player 2 Wins!") file = open("scores.txt","a") file.write(username2) file.write(" has ") file.write(str(total_score2)) file.write(" points") file.write("\n") file.close() sys.exit() else: print("Sorry, this username or password does not exist please try again") counter = counter + 1 if counter == 3: print("----------------------------------------------------") print("You have been locked out please restart to try again") sys.exit() else: print("Sorry, this username or password does not exist please try again") counter = counter + 1 if counter == 3: print("----------------------------------------------------") print("You have been locked out please restart to try again") sys.exit() </code></pre> <p>This was a project that i have been doing in computer science which I have now finished if anyone has any suggestions on how I could make it better they will appreciated alot so please suggest how I can improve it. Also It would be very helpful to me if you could rewrite the parts of my code that need improving or are wrong step by step so I can understand it better</p> <p>Thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-22T16:44:12.977", "Id": "406243", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Feel free to post a follow-up question linking back to this one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-23T10:44:47.920", "Id": "406294", "Score": "0", "body": "I didn't know that I shouldn't do that sorry" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-23T10:48:17.453", "Id": "406296", "Score": "0", "body": "@Mast so I should post my updated code on a new question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-23T12:00:30.927", "Id": "406300", "Score": "0", "body": "Yes. Make sure you add a piece of text about what it does, what is improved and a link to your original question (this one)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-23T15:35:50.593", "Id": "406329", "Score": "0", "body": "No problem. Feel free to ask if anything is unclear." } ]
[ { "body": "<ul>\n<li>The requirements for this game are unclear. Code is always produced to implement a set of well defined and understood requirements, even if you are defining these yourself.</li>\n<li>The code is monolithic, break it down into functions, this is <a href=\"https://en.wikipedia.org/wiki/Functional_decomposition\" rel=\"nofollow noreferrer\">functional decomposition</a> and one of the first skills a programmer needs to learn, regardless of language or programming paradigm.</li>\n<li>Use <code>unittests</code> to <a href=\"http://pythontesting.net/framework/unittest/unittest-introduction/\" rel=\"nofollow noreferrer\">automatically test</a> the functionality of those methods, learning to use <code>unittest</code> to engage in Test Driven development will increase your speed of learning at first and make you a far better developer in the long run.</li>\n<li>The code has a very linear flow, programs should provide flexible flows, break it down into three parts, the setup, the game and the results, wrap these with a menu, to setup, play, see score or exit. Once each part is complete return to the menu loop.</li>\n<li>What is the point of requiring usernames then referring to Players 1 &amp; 2.</li>\n<li>It include lots of pointless functionality such usernames and password from plain text files, capture the names, but do away with the password, security by obscurity offers no security at all.</li>\n<li>It fails if you enter S when first starting, if the file does not exist use <a href=\"https://docs.python.org/3.7/reference/compound_stmts.html#the-try-statement\" rel=\"nofollow noreferrer\">Exception Handing</a> to catch this failure, create the blank file and continue. Always attempt to recover from error conditions when possible, make this second nature.</li>\n<li><a href=\"https://www.101computing.net/number-only/\" rel=\"nofollow noreferrer\">Always validate user input before proceeding</a>.</li>\n<li>Learn to use the built in language features and libraries, this example plays a similar game with much better usage of Python's built in capabilities. <a href=\"https://codereview.stackexchange.com/questions/33811/how-to-make-this-random-number-game-better\">How to make this random number game better?</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T20:52:19.967", "Id": "208350", "ParentId": "208342", "Score": "6" } }, { "body": "<ul>\n<li>You need to run your UI text through a spell checker. Example - <code>exsiting</code></li>\n<li>Since each player has more than one attribute (<code>total_score</code>, <code>points</code>, <code>password</code>, etc.) each player should be represented by a class, or at least a <code>namedtuple</code>.</li>\n<li>You have a <code>print</code> followed by a blank <code>input(\"\")</code>. Don't do this; just put the content of the print into the prompt argument of the input call.</li>\n<li><code>while ens != (\"e\") and ens != (\"n\") and ens != (\"s\")</code> should be something like <code>while ens not in ('e', 'n', 's'):</code></li>\n<li>Rather than bare <code>open</code>/<code>close</code> calls, you should use a proper <code>with</code> statement.</li>\n<li>Rather than using a half a dozen <code>write</code> calls, consider just issuing one <code>write</code> call with a multi-line (triple-quoted) string.</li>\n<li>Something like <code>\"username: \" + username1 + \" password: \" + password</code> is better done with a <code>format</code> call.</li>\n</ul>\n\n<p>Other than that, you really need to strengthen your DRY (don't repeat yourself) skills. Writing a handful of functions for repeated code would be a good start.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T19:22:54.280", "Id": "402494", "Score": "0", "body": "Is it possible for you to re write my code so it isn't so long. it would be very helpful if you did it. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T20:17:17.910", "Id": "402500", "Score": "0", "body": "@colkat406 absolutely not. Then you wouldn't learn. Try it yourself and submit a new review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T17:00:59.793", "Id": "402769", "Score": "0", "body": "could you show me an example of a namedtuple" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T17:10:12.497", "Id": "402770", "Score": "0", "body": "could you also show me how to use a function for username and password becasue it is not working for me" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T17:46:53.643", "Id": "402774", "Score": "0", "body": "If it isn't working, that's a question for StackOverflow :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T04:47:21.233", "Id": "208362", "ParentId": "208342", "Score": "4" } } ]
{ "AcceptedAnswerId": "208362", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T18:19:08.317", "Id": "208342", "Score": "6", "Tags": [ "python", "python-3.x", "game", "homework", "dice" ], "Title": "2 player dice game, where even total gains points and odd total loses points NEA task computer science" }
208342
<p>I've written a code that I try to use divide and conquer approach to determine if the given array is sorted. I wonder whether I apply the approach accurately.</p> <pre><code>public static boolean isSorted(List&lt;Integer&gt; arr, int start, int end) { if (end - start == 1) // base case to compare two elements return arr.get(end) &gt; arr.get(start); int middle = (end + start) &gt;&gt;&gt; 1; // division by two boolean leftPart = isSorted(arr, start, middle); boolean rightPart = isSorted(arr, middle, end); return leftPart &amp;&amp; rightPart; } </code></pre> <p>To use call,</p> <pre><code>isSorted(list, 0, list.size() - 1) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T22:24:21.677", "Id": "402433", "Score": "3", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T06:43:40.050", "Id": "402441", "Score": "0", "body": "Test your code on `3, 4, 1, 2`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T18:02:05.660", "Id": "402487", "Score": "0", "body": "@vnp `isSorted(list, 0, 3)` will call `isSorted(arr, 1, 3)` which will call `isSorted(arr, 1, 2)` which will return `false`. That test case is fine." } ]
[ { "body": "<p>It looks like your are doing it mostly right. You have problems with length zero and length 1 arrays, but you should be able to fix those pretty quick. </p>\n\n<p>You may be doing more work than necessary. If an array is not sorted, you might find <code>leftPart</code> is <code>false</code>, but you unconditionally go on to determine the value of <code>rightPart</code> anyway, despite it not mattering. The simplest way to avoid that is to combine that recursive calls and the <code>&amp;&amp;</code> operation. Ie:</p>\n\n<pre><code>return isSorted(arr, start, middle) &amp;&amp; isSorted(arr, middle, end);\n</code></pre>\n\n<p>Lastly, if the array contains duplicates, can it still be considered sorted? You return <code>false</code> for <code>[1, 2, 2, 3]</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T20:09:25.340", "Id": "208345", "ParentId": "208343", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T19:24:12.820", "Id": "208343", "Score": "3", "Tags": [ "java", "algorithm", "array", "recursion", "divide-and-conquer" ], "Title": "Checking whether given array is sorted by divide-and-conquer" }
208343
<p>As a beginner I try to implement a vokable memory game. It is still missing some feature (Loading, Display), but I would like to hear how to improve what is already there.</p> <p>The user should identify matching pairs. Theses are then removed from the game. The game ends when there are not any pairs left.</p> <p>I think there has to be nicer way to write the code for <code>game'</code> in <code>mainLoop</code>.</p> <p>Any other suggestions to improve the code are also welcome.</p> <pre><code>module Main where import Data.Maybe (fromMaybe) import qualified Data.List.Safe as List import Data.List (foldl') type Vokabel = (String,String) data Tile = Tile { _front :: Bool , _vokabel :: Vokabel } deriving (Show) instance Eq Tile where (==) (Tile _ v1) (Tile _ v2) = v1 == v2 getText :: Tile -&gt; String getText (Tile b (s1,s2)) | b = s1 | not b = s2 newtype Game = Game { _tiles :: [Tile] } deriving Show displayGame :: Game -&gt; String displayGame g = let tile2Line s x = s ++ getText x ++ "\n" in foldl' tile2Line "" . _tiles $ g --(foldl' "" tile2Line) . _tiles $ g makeTile s = Tile True (s++"-Front",s++"-Back") makeVok s = (s++"-Front",s++"-Back") gameExampel :: Game gameExampel = generateGame . map makeVok $ ["Alpha","Beta","Gamma"] generateGame :: [Vokabel] -&gt; Game generateGame vs = Game (map (Tile True) vs ++ map (Tile False) vs) main :: IO () main = do putStrLn "Vokabel Memory" mainLoop gameExampel pure () chooseTile :: Game -&gt; Int -&gt; Maybe Tile chooseTile g x = _tiles g List.!! x mainLoop :: Game -&gt; IO () mainLoop game = do putStrLn . displayGame $ game putStrLn "choose Tile, or exit" input &lt;- getLine if input == "exit" then do putStrLn "exit now!" pure() else do let indexA = read input let choosenTileA = chooseTile game indexA putStrLn ("choosen: " ++ maybe "nothing" getText choosenTileA) indexB &lt;- read &lt;$&gt; getLine let choosenTileB = chooseTile game indexB putStrLn ("choosen: " ++ maybe "nothing" getText choosenTileB) let game' = fromMaybe game (do vokA &lt;- _vokabel &lt;$&gt; choosenTileA vokB &lt;- _vokabel &lt;$&gt; choosenTileB if vokA == vokB &amp;&amp; indexA /= indexB then Game &lt;$&gt; ((List.delete &lt;$&gt; choosenTileB) &lt;*&gt; ((List.delete &lt;$&gt; choosenTileA) &lt;*&gt; (pure . _tiles $ game))) else pure game ) if null . drop 1 . _tiles $ game' then return () else mainLoop game' </code></pre> <p>EDIT: Having thought about it: I would like to know how to use the state monade in this example.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T20:20:33.663", "Id": "208347", "Score": "3", "Tags": [ "beginner", "game", "haskell" ], "Title": "Vocabulary memory game in Haskell" }
208347
<p>This code gets the most frequent number and least duplicate number in an array. How can I optimize it and improve its performance?</p> <pre><code>public class X { public static String findMin(String[] numbers, int counter) { int count = 0; String elements = ""; for (String tempElement: numbers) { int tempCount = 0; for (int n = 0; n &lt; numbers.length; n++) { if (numbers[n].equals(tempElement)) { tempCount++; if (tempCount &gt; counter) { count = 0; break; } if (tempCount &gt; count) { elements = tempElement; // System.out.println(elements); count = tempCount; } } } if (count == counter) { return elements; } } if (count &lt; counter) { return ""; } return elements; } public static void main(String[] args) { String[] numbers = "756655874075297346".split(""); String elements = ""; int count = 0; for (String tempElement: numbers) { int tempCount = 0; for (int n = 0; n &lt; numbers.length; n++) { if (numbers[n].equals(tempElement)) { tempCount++; if (tempCount &gt; count) { elements = tempElement; // System.out.println(elements); count = tempCount; } } } } String x = ""; int c = 2; do { x = findMin(numbers, c++); } while (x == ""); System.out.println("Frequent number is: " + elements + " It appeared " + count + " times"); System.out.println("Min Frequent number is: " + x + " It appeared " + (c - 1) + " times"); } } </code></pre>
[]
[ { "body": "<ul>\n<li>First, you should care about indentation.</li>\n<li>Why slitting the <code>numbers</code> string while you can access individual char with <code>numbers.charAt(n)</code> ? It force you to work with <code>String</code> instead of <code>char</code>.</li>\n<li>You don't check for validity of the string. Here, it's hard coded, but if you have to get it from a unknown source, a good habit is to validate it before using.</li>\n<li>Also, you don't check if there's duplicates or not. If <code>numbers</code> is \"1234567890\" your program go for a infinite loop.</li>\n<li>You compute the \"Max\" count into the <code>main</code>, and the \"Min\" in a function; try to be consistent.</li>\n<li>For both computations, you make <span class=\"math-container\">\\$n*n\\$</span> iterations (where <span class=\"math-container\">\\$n\\$</span> is the <code>numbers</code> length) giving a complexity of <span class=\"math-container\">\\$ O(n^2)\\$</span> for both.</li>\n</ul>\n\n<p>Instead, try to construct a table of occurrences by traversing the table once. \nAfter, simply search in this table the min and max values in one traversal.</p>\n\n<p>There's a very naive implementation, but i think a lot simpler to understand than your, and surely more efficient.</p>\n\n<pre><code>public class X {\n public static void main(String[] args) {\n\n String data = \"756655874075297346\";\n int[] counts = new int[10];\n\n for (int i = 0; i &lt; data.length(); i++) {\n char n = data.charAt(i);\n if (n &gt;= '0' &amp;&amp; n &lt;= '9') {\n counts[n-'0']++; \n }\n }\n\n int min_index = 0;\n int max_index = 0;\n int min_count = Integer.MAX_VALUE;\n int max_count = 0;\n\n for (int i = 0; i &lt; 10; i++) {\n if (counts[i] &gt;= max_count) {\n max_index = i;\n max_count = counts[i];\n }\n if (counts[i] &gt; 1 &amp;&amp; counts[i] &lt; min_count) {\n min_index = i;\n min_count = counts[i];\n } \n }\n System.out.println(\"Frequent number is: \" + (char)(max_index + '0') + \" It appeared \" + max_count + \" times\");\n if (min_count &lt; Integer.MAX_VALUE) {\n System.out.println(\"Min Frequent number is: \" + (char)(min_index + '0') + \" It appeared \" + min_count + \" times\");\n }\n else {\n System.out.println(\"There's no duplicates!\");\n }\n }\n}\n</code></pre>\n\n<p>Here, the function print the higher number with the higher number of occurrences (in case of multiples char with maximal occurrence count). If instead you want to get the lower, change <code>if (counts[i] &gt;= max_count)</code> for <code>if (counts[i] &gt; max_count)</code>.</p>\n\n<p>Conversely, it print the lower duplicated number with the lower count, to get the higher duplicated with the lower count, change <code>counts[i] &lt; min_count</code> with <code>counts[i] &lt;= min_count</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T23:19:51.553", "Id": "208354", "ParentId": "208352", "Score": "1" } } ]
{ "AcceptedAnswerId": "208354", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T21:17:44.377", "Id": "208352", "Score": "1", "Tags": [ "java", "performance", "array", "statistics" ], "Title": "Get the most frequent number and least frequent duplicate in array" }
208352
<pre><code>import java.util.*; public class PrimeNumber { private static ArrayList&lt;Integer&gt; listOfPrime = new ArrayList&lt;Integer&gt;(); public static void main(String args[]) { Scanner userInput = new Scanner(System.in); System.out.print("Please enter a number to checked the list of prime number &gt; "); //Request user to input number. String input = userInput.nextLine(); int number = 0; boolean check = false; //Check if integer entered is it integer while(check != true) { try { // if input can be parse into integer, shows that its number so can change check into true to exit the while loop number = Integer.parseInt(input); check = true; } catch(NumberFormatException e) { System.out.println("Please enter numbers only &gt; "); input = userInput.nextLine(); } } //Check if input enter is 0 or 1, as prime number cannot be those. if(number &lt; 2) { System.out.println("Prime number cannot be 0 or 1"); }else { checkPrime(number); } } //Check for all prime numbers within the number user input. private static void checkPrime(int input) { boolean primeValidation = true; //first for loop to check from small to biggest integer in the input for(int i = 1; i &lt;= input;i++) { if(i !=1) { //Second for loop to check from prime number in the small to big number. //If the number i is 2 or 3, the loop will exit and add into the list as the default is prime, and no option changes it to not prime number. for(int x = 2; x &lt; i ; x++) { if(i%x == 0) { //If the number is divisable by any number to 0, set it to not prime. primeValidation = false; } } } //if the input is either 0 or 1 set it to false and 0 and 1 is not prime else { primeValidation = false; } if(primeValidation == true) { listOfPrime.add(i); }else { primeValidation = true; } } System.out.println("The list of prime numbers of the number " + input + " are "+listOfPrime); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T22:34:27.027", "Id": "402434", "Score": "1", "body": "Welcome to Code Review. Please fix your indentation. The easiest way to post core is to paste it into the question editor, highlight it, and press Ctrl-K to mark it as a code block. Also tell us what the code accomplishes — see [ask]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T23:52:21.370", "Id": "402435", "Score": "1", "body": "Plus you have two \" ` \" character making your code unable to compile. Otherwise, a small advise: try to look on internet how to find prime numbers (in any language), you chose one of the worst methods and don't comment what's obvious, it make the reading harder (even with code cleaned ). Welcome on Code Review anyway :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T09:19:05.250", "Id": "402447", "Score": "0", "body": "There is only one even prime number: 2. All other prime numbers are odd. That means you can halve the amount of work you have to do by not bothering to look at even numbers > 2." } ]
[ { "body": "<p>The first thing I'd suggest is break out code segments into functions. This keeps your <code>Main</code> free of clutter and makes the flow easier to understand.</p>\n\n<p>You don't mention which IDE you're using. If it doesn't have the option for you to format your code according to acceptable guidelines, I would seriously consider changing programs. There are several well established IDE's freely available.</p>\n\n<p>Your, check for prime, algorithm, while naive, could do with some optimization. Check for 0,1, and 2 separately. If the number is bigger than 1 then add 2 to the list. The loop should start at 3 and step by 2. As was pointed out, all primes larger than 2 are odd.</p>\n\n<p>There are much better algorithms for getting a list of prime numbers, not the least of which is the <code>Sieve of Eratosthenes</code>. With this algorithm it is very easy to make a master list of primes then build the sublist that you want.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T21:25:05.020", "Id": "208406", "ParentId": "208353", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T22:30:19.710", "Id": "208353", "Score": "0", "Tags": [ "java", "primes" ], "Title": "Listing prime numbers up to the given number" }
208353
<p>I have successfully created a plot of a binomial glm using example data. <a href="https://sciences.ucf.edu/biology/d4lab/wp-content/uploads/sites/125/2018/11/parasites.txt" rel="nofollow noreferrer">https://sciences.ucf.edu/biology/d4lab/wp-content/uploads/sites/125/2018/11/parasites.txt</a></p> <p>The predictors of the model include 3 predictors (one categorical, 2 continuous)</p> <p>The code works fine but I have been wanting to try and incorporating more dplyr functions and pipes to streamline code. Ultimately, I want to make my block of code into a function that works with any model with the same type and number of predictors for a binomial glm. Are there better ways to carry out my code with more tidyverse/dplyr code?</p> <pre><code>#import parasites file df&lt;-parasites m1&lt;-glm(data=df, infected~age+weight+sex, family = "binomial") summary(m1) age_grid &lt;- round(seq(min(df$age), max(df$age), length.out = 15)) weight_grid &lt;- round(seq(min(df$weight), max(df$weight), length.out = 15)) newdat &lt;- expand.grid(weight =weight_grid, age = age_grid, sex = c("female", "male")) pred &lt;- predict.glm(m1, newdata = newdat, type="link", se=TRUE) ymin &lt;- m1$family$linkinv(pred$fit - 1.96 * pred$se.fit) ymax &lt;- m1$family$linkinv(pred$fit + 1.96 * pred$se.fit) fit &lt;- m1$family$linkinv(pred$fit) z &lt;- matrix(fit, length(age_grid)) ci.low &lt;- matrix(ymin, length(age_grid)) ci.up &lt;- matrix(ymax, length(age_grid)) x&lt;-data.frame(pred = fit, low = ymin, high = ymax, newdat) %&gt;% mutate(category=cut(age, breaks=c(0, 69, 138, 206), labels = c("0-69", "70-139", "139-206"))) x$age&lt;-as.factor(x$age) library(ggplot2) finalgraph&lt;-ggplot(data=x)+ geom_line(aes(x = weight, y = pred, color = age))+ geom_ribbon(aes(x = weight, ymin = low, ymax = high, fill = age), alpha = 0.1) + facet_grid(category~sex) +theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+ ylab(expression(bold(y = "Infection Probability"))) + xlab(expression(bold("Weight"))) + theme(legend.position = "right",strip.text.x = element_text(face = "bold", size=12), strip.text.y = element_text(size=10), axis.text.y = element_text(size=10, face = "bold"), axis.text.x = element_text(size=10), axis.title = element_text(size=12), legend.text=element_text(size=10), legend.title = element_text(size=12, face="bold"))+ labs(linetype="Age (months)", colour="Age (months)", fill = "Age (months)") finalgraph </code></pre> <p>Code notes: Essentially I made a model, created a bunch of values from my predictors (age_grid, v_grid) and made all possible combinations of these values along with the categorical variable of sex using expand.grid.</p> <p>Then I just used the predict.glm function to extract predicted values based off of expand.grid object. I also extracted std. errors and calculated confidence intervals (ci.up and ci. low). Then I used some dplyr functions to create a dataframe with all this information and also made a new column called category. Category breaks down one of my variables (age) into four distinct groups based of f of breaks I decided on and labelled as decided as well. Then I plotted all of this data using ggplot2. </p>
[]
[ { "body": "<p>Here is what I would do leaning fully into the <code>tidyverse</code> style to get a nice \"pipelined\" set of steps that are easy to wrap up into functions.</p>\n\n<p>Loading <code>tidyverse</code> just gets some extra tools from <code>purrr</code> here, but I find it much more productive for data manipulation in general, compared to just using <code>dplyr</code> alone. That said if you can only use <code>dplyr</code> you can replace the <code>purrr::map()</code> for <code>lapply()</code> and <code>purrr::keep()</code> for <code>Filter()</code>, but you lose a little pipe readability.</p>\n\n<p>First time posting on the sub-Exchange, so feedback is welcome. </p>\n\n<pre><code>df &lt;- read.csv(\"https://sciences.ucf.edu/biology/d4lab/wp-content/uploads/sites/125/2018/11/parasites.txt\", header = T)\n\nm1 &lt;- glm(data=df, infected ~ age + weight + sex, family = \"binomial\") # add spaces to variables separated by arithmetic operators\nlink_func &lt;- m1$family$linkinv # maybe this could become a generic function\n\nlibrary(tidyverse)\n\n# anonymous functions are quick and easy to type, my preference if only one input arg\nnewdat_func &lt;- . %&gt;% # meant to start with df\n select(weight, age) %&gt;% # keep only column of interest\n map(~ round(seq(min(.), max(.), length.out = 15))) %&gt;% # don't repeat yourself and call the same operation on both columns in one line\n c(list(sex = c(\"female\", \"male\"))) %&gt;% # prep a 3-element list for expand.grid to process\n expand.grid()\n\nnewdat2 &lt;- newdat_func(df)\n\n# fall back to traditional function format for multiple inputs\nx_func &lt;- function(model, newdata, link_func) {\n predict.glm(model, newdata = newdata, type=\"link\", se=TRUE) %&gt;% # obviously this only works on glm objects, you could add checks to be defensive\n keep(~ length(.) == nrow(newdata)) %&gt;% # drop the third element that is length 1\n bind_cols() %&gt;% # build data frame with a column from each list element\n mutate(low = fit - 1.96 * se.fit,\n high = fit + 1.96 * se.fit) %&gt;%\n mutate_all(funs(link_func)) %&gt;% # again don't repeat yourself\n bind_cols(newdata) %&gt;% # bolt back on simulated predictors\n mutate(category = cut(age,\n breaks = c(0, 69, 138, 206),\n labels = c(\"0-69\", \"70-139\", \"139-206\")),\n age = as.factor(age))\n}\n\nx2 &lt;- x_func(m1, newdat2, link_func)\n\nggplot(data = x2, aes(x = weight)) + # always use spaces around '+' and '=', do ggplot(data = data) +\n geom_line(aes(y = fit, color = age)) +\n geom_ribbon(aes(ymin = low, ymax = high, fill = age), alpha = 0.1) + # okay is all on one line (&lt;80 chars)\n facet_grid(category ~ sex) +\n labs(x = expression(bold(\"Weight\")), # if a function goes beyond 1 line, split its args one per row\n y = expression(bold(y = \"Infection Probability\")),\n linetype = \"Age (months)\",\n colour = \"Age (months)\",\n fill = \"Age (months)\") +\n theme(panel.grid.major = element_blank(), # split args again\n panel.grid.minor = element_blank(),\n legend.position = \"right\",\n strip.text.x = element_text(face = \"bold\", size=12),\n strip.text.y = element_text(size=10),\n axis.text.y = element_text(size=10, face = \"bold\"),\n axis.text.x = element_text(size=10),\n axis.title = element_text(size=12), \n legend.text = element_text(size=10),\n legend.title = element_text(size=12, face=\"bold\"))\n</code></pre>\n\n<p>Minor tidy-style adjustments everywhere are adding spaces around <code>~/=/+</code> signs and only one argument per line for multiy line calls like <code>theme()</code> and <code>labs()</code>. See more here <a href=\"https://style.tidyverse.org/\" rel=\"nofollow noreferrer\">https://style.tidyverse.org/</a></p>\n\n<p>Obviously I went the last inch and wrapped the processing steps into functions. But I developed the sequence as an open pipe chain, adding a step and printing the result to console as I progressed. The speed of that iterative/dev workflow is why I love leveraging pipes, but I think it also makes the code easier to read. Now instead of multiple intermediate variables and repeated patterns your have two code chunks/functions that handle the two distinct phases of this model plotting problem</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T16:16:46.473", "Id": "402479", "Score": "0", "body": "Hey, welcome to Code Review! Here we usually look for reviews of the OP's code and not just alternative implementations. While you did write some comments on what is different about your approach, it might help if you could add some more on why/how this is better (is it more readable, more modular or maintainable, faster, more memory efficient, just plain best practices or more modern?)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T23:16:15.833", "Id": "402665", "Score": "0", "body": "Thanks @Nate! the code worked very well. I do have a question though. For some of your function calls you use \".\" in the arguments section, e.g. length(.) or keep(~length(.) == nrow(newdat). What exactly does this do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T14:30:22.900", "Id": "402732", "Score": "0", "body": "Yea its from the `purrr` formula syntax, specified by the `~`. See the help/man page for `?map` for more, but the `.` is the reference to the element being passed into the function (each element in the list being mapped over). So the statement `~length(.)` is the same as `function(x) length(x)` its just shorthand. You can always pass the `function()...` syntax to `map(.f = )` and for more complicated functions the `~` shorthand may fail, but its faster for more simple cases." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T14:02:24.650", "Id": "208377", "ParentId": "208355", "Score": "2" } } ]
{ "AcceptedAnswerId": "208377", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T00:11:13.483", "Id": "208355", "Score": "1", "Tags": [ "r", "statistics", "data-visualization" ], "Title": "Using dplyr and pipes for logistic regression plotting" }
208355
<p>I have a program to calculate grades that uses pointers and I am trying to figure out if I did it right and if there are any problems with my implementation.</p> <p>I'm trying to get a more firm grasp on pointers in C++ and have been using them more frequently in my practice programs. I was looking at my grades and thought to myself, "what if I made a program that could calculate grades just like this." Essentially the features it has are: having a Class (not a C++ class, a school class), that has categories. Categories can be things like, "Tests," and, "Classwork," which can be weighted differently. Then you can add assignments into the categories and the grades will be calculated accordingly. You can also change the categories name and weight, as well as attributes of each individual grade. I haven't fully completed the program yet and I plan to redo this code so that it is a little bit less redundant and well, bad; but the features I have seem to work, and my main concern are the pointers and if I am using them correctly/have any problems with them.</p> <p>One other thing I should mention is that the reason I am using raw pointers is for learning, I know I could probably use something else like smart pointers, or unique pointers.</p> <p>Class.h:</p> <pre><code>#include &lt;map&gt; #include &lt;vector&gt; class Class{ private: struct grade; struct category; std::vector&lt;category*&gt; categories; public: void addGrade(const std::string&amp;, const std::string&amp;, float, float); void addCategory(const std::string&amp;, float); void deleteGradeAtIndex(const std::string&amp;, int); void deleteGradeByName(const std::string&amp;, const std::string&amp;); void deleteCategory(const std::string&amp;); void changeGradeAtIndex(const std::string&amp;, int, const std::string&amp;, float, float); void changeGradeByName(const std::string&amp;, const std::string&amp;, const std::string&amp;, float, float); void changeCategory(const std::string&amp;, const std::string&amp;, float); void printGrades(); }; </code></pre> <p>Class.cpp:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include "Class.h" struct Class::category{ float weight; float percentage; std::string name; std::vector&lt;grade*&gt; grades; }; struct Class::grade{ float ptsEarned; float ptsPossible; float percentage; std::string name; }; void Class::addCategory(const std::string&amp; name, float weight){ category* temp = new category; temp-&gt;weight = weight; temp-&gt;name = name; categories.push_back(temp); } void Class::addGrade(const std::string&amp; category, const std::string&amp; name, float pEarn, float pPoss){ for(uint32_t i = 0; i &lt; categories.size(); i++){ if(categories[i]-&gt;name.compare(category) == 0){ grade* temp = new grade; temp-&gt;name = name; temp-&gt;ptsEarned = pEarn; temp-&gt;ptsPossible = pPoss; temp-&gt;percentage = (pEarn/pPoss)*100; categories[i]-&gt;grades.push_back(temp); float pos = 0, ear = 0; for(uint32_t j = 0; j &lt; categories[i]-&gt;grades.size(); j++){ pos += categories[i]-&gt;grades[j]-&gt;ptsPossible; ear += categories[i]-&gt;grades[j]-&gt;ptsEarned; } categories[i]-&gt;percentage = (ear/pos)*100; return; } } std::cout &lt;&lt; "category not found" &lt;&lt; std::endl; } void Class::deleteGradeAtIndex(const std::string&amp; category, int index){ for(uint32_t i = 0; i &lt; categories.size(); i++){ if(categories[i]-&gt;name.compare(category) == 0){ delete categories[i]-&gt;grades[index]; categories[i]-&gt;grades[index] = nullptr; categories[i]-&gt;grades.erase(categories[i]-&gt;grades.begin() + index); return; } } } void Class::deleteGradeByName(const std::string&amp; category, const std::string&amp; gradeName){ for(uint32_t i = 0; i &lt; categories.size(); i++){ if(categories[i]-&gt;name.compare(category) == 0){ for(uint32_t j = 0; j &lt; categories[i]-&gt;grades.size(); j++){ if(categories[i]-&gt;grades[j]-&gt;name.compare(gradeName) == 0){ delete categories[i]-&gt;grades[j]; categories[i]-&gt;grades[j] = nullptr; categories[i]-&gt;grades.erase(categories[i]-&gt;grades.begin() + j); return; } } } } } void Class::deleteCategory(const std::string&amp; category){ for(uint32_t i = 0; i &lt; categories.size(); i++){ if(categories[i]-&gt;name.compare(category) == 0){ for(uint32_t j = 0; j &lt; categories[i]-&gt;grades.size(); j++){ delete categories[i]-&gt;grades[j]; categories[i]-&gt;grades[j] = nullptr; categories[i]-&gt;grades.erase(categories[i]-&gt;grades.begin() + j); } delete categories[i]; categories[i] = nullptr; categories.erase(categories.begin() + i); return; } } } void Class::changeCategory(const std::string&amp; category, const std::string&amp; newName, float newWeight){ for(uint32_t i = 0; i &lt; categories.size(); i++){ if(categories[i]-&gt;name.compare(category) == 0){ categories[i]-&gt;name = newName; categories[i]-&gt;weight = newWeight; return; } } } void Class::changeGradeAtIndex(const std::string&amp; category, int index, const std::string&amp; newName, float pEarn, float pPoss){ for(uint32_t i = 0; i &lt; categories.size(); i++){ if(categories[i]-&gt;name.compare(category) == 0){ categories[i]-&gt;grades[index]-&gt;name = newName; categories[i]-&gt;grades[index]-&gt;ptsEarned = pEarn; categories[i]-&gt;grades[index]-&gt;ptsPossible = pPoss; categories[i]-&gt;grades[index]-&gt;percentage = (pEarn/pPoss)*100; float pos = 0, ear = 0; for(uint32_t j = 0; j &lt; categories[i]-&gt;grades.size(); j++){ pos += categories[i]-&gt;grades[j]-&gt;ptsPossible; ear += categories[i]-&gt;grades[j]-&gt;ptsEarned; } categories[i]-&gt;percentage = (ear/pos)*100; return; } } } void Class::changeGradeByName(const std::string&amp; category, const std::string&amp; gradeName, const std::string&amp; newName, float pEarn, float pPoss){ for(uint32_t i = 0; i &lt; categories.size(); i++){ if(categories[i]-&gt;name.compare(category) == 0){ for(uint32_t j = 0; j &lt; categories[i]-&gt;grades.size(); j++){ if(categories[i]-&gt;grades[j]-&gt;name.compare(gradeName) == 0){ categories[i]-&gt;grades[j]-&gt;name = newName; categories[i]-&gt;grades[j]-&gt;ptsEarned = pEarn; categories[i]-&gt;grades[j]-&gt;ptsPossible = pPoss; categories[i]-&gt;grades[j]-&gt;percentage = (pEarn/pPoss)*100; float pos = 0, ear = 0; for(uint32_t j = 0; j &lt; categories[i]-&gt;grades.size(); j++){ pos += categories[i]-&gt;grades[j]-&gt;ptsPossible; ear += categories[i]-&gt;grades[j]-&gt;ptsEarned; } categories[i]-&gt;percentage = (ear/pos)*100; return; } } } } } void Class::printGrades(){ for(uint32_t i = 0; i &lt; categories.size(); i++){ std::cout &lt;&lt; "Category: " &lt;&lt; categories[i]-&gt;name &lt;&lt; " | weight: " &lt;&lt; categories[i]-&gt;weight &lt;&lt; " | " &lt;&lt; categories[i]-&gt;percentage &lt;&lt; "%\n"; for(uint32_t j = 0; j &lt; categories[i]-&gt;grades.size(); j++){ std::cout &lt;&lt; "\tassignment: " &lt;&lt; categories[i]-&gt;grades[j]-&gt;name &lt;&lt; " | points earned: " &lt;&lt; categories[i]-&gt;grades[j]-&gt;ptsEarned &lt;&lt; " | points possible: " &lt;&lt; categories[i]-&gt;grades[j]-&gt;ptsPossible &lt;&lt; " | " &lt;&lt; categories[i]-&gt;grades[j]-&gt;percentage &lt;&lt; "%" &lt;&lt; std::endl; } } } </code></pre> <p>main.cpp:</p> <pre><code>int main() { Class math; math.addCategory("tests", 70); math.addGrade("tests", "test1", 95, 100); math.addGrade("tests", "test2", 80, 100); math.addCategory("class work", 30); math.addGrade("class work", "assignment1", 100, 100); math.addGrade("class work", "assignment2", 100, 100); math.deleteGradeByName("class work", "assignment1"); math.changeGradeAtIndex("tests", 0, "test1c", 93, 100); math.changeGradeByName("tests", "test2", "test2c", 95, 100); math.printGrades(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T12:14:20.570", "Id": "402457", "Score": "0", "body": "*I know I could probably use something else like smart pointers, or unique pointers.* Or no pointers at all ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T14:14:09.240", "Id": "402466", "Score": "0", "body": "By the way, *Class* is a horrible name for a class. Could you think of something more descriptive? What is the class actually doing?" } ]
[ { "body": "<p>Welcome on Code Review!</p>\n\n<p>Congratulation, it's a pretty clean code, just some points:</p>\n\n<ul>\n<li>There's missing the <code>#include \"Class.h\"</code> in <code>main.cpp</code></li>\n<li>Although a C string literal can be implicitly converted to a <code>std::string</code>, if you don't <code>#include &lt;string&gt;</code> in <code>main.cpp</code> Clang with the <code>-pedantic</code> flag will complain.</li>\n<li>In <code>Class::changeGradeByName</code> you hide the previous declared <code>j</code> in your 3rd-nested for-loop.</li>\n<li>Since the header file is what the user (or you, later) will look at first to understand your interface, a good practice is to don't omit parameter name in prototypes. It make the interface more explicit:</li>\n</ul>\n\n<p>Compare:</p>\n\n<pre><code>void changeGradeByName(const std::string&amp;, const std::string&amp;, const std::string&amp;, float, float)\n</code></pre>\n\n<p>Versus:</p>\n\n<pre><code>void changeGradeByName(const std::string&amp; category, const std::string&amp; gradeName, const std::string&amp; newName, float pEarn, float pPoss);\n</code></pre>\n\n<ul>\n<li>Use meaningful names. In this latter, what mean <code>pPoss</code> or <code>pEarn</code> ?</li>\n<li>You should provide constructor/destructor for your structs, it will make the code easier.</li>\n</ul>\n\n<p>I surely miss something, but I hope others will come and review your code with a different perspective or another angle.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T02:00:31.573", "Id": "402438", "Score": "0", "body": "Thanks this was really helpful, and I've been trying to work on making my code cleaner. The J in the third for loop in Class::changeGradeByName was a mistake I didn't notice, thanks for pointing that out, i didn't even know something like that would compile. I added a constructor and a destructor to my structs which also shortened it a bit. #include \"Class.h\" in main.cpp is there, I just accidentally left that bit off when I copied main.cpp. Also i will take note to put parameter identifiers in my header too because it does get confusing when reading the header before reading the source." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T02:09:49.910", "Id": "402439", "Score": "0", "body": "And didn't forget to add `#include <string>` in `main.cpp` otherwise Clang will complain with the `-pedantic` flag. (Or 1// provide `const char*` overloads, or 2// use c++14 and string literal operator to defines your string, or 3// explicitly pass `std::string(\"tests\")` to your functions. But I think the include is the simplest. ;))" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T01:31:57.270", "Id": "208359", "ParentId": "208356", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T00:18:56.950", "Id": "208356", "Score": "5", "Tags": [ "c++", "pointers" ], "Title": "C++ grades calculator using pointers" }
208356
<p>This is rather toy example of immutable datatype in C++. I've tried to follow functional languages like Scheme, Racket - making list as a cons cell: list is list or is empty.</p> <pre><code>/* * Abstract class */ template &lt;class T&gt; class ImmutableList { public: ~ImmutableList() {std::cout &lt;&lt; "base class destructor";} virtual bool is_empty() = 0; virtual T head() = 0; virtual ImmutableList&lt;T&gt; * tail() = 0; virtual int length() = 0; }; /* * class non empty List */ template &lt;class T&gt; class List: public ImmutableList&lt;T&gt; { int size = 1; T first; ImmutableList&lt;T&gt; * rest; public: List(T _first, ImmutableList&lt;T&gt; * _tail){ first = _first; rest = _tail; size += _tail-&gt;length(); } ~List() {std::cout &lt;&lt; "List class destructor";} bool is_empty() { return false; } T head(){ return first; } ImmutableList&lt;T&gt;* tail(){ return rest; } int length() {return size;} }; /* * class empty list */ template &lt;class T&gt; class Nil: public ImmutableList&lt;T&gt; { public: ~Nil(); bool is_empty() {return true;} int length() {return 0;} T head() { throw std::logic_error("Head of empty list!"); } ImmutableList&lt;T&gt; * tail() { throw std::logic_error("Tail of empty list!"); } }; </code></pre> <p>There is more functions, like a <code>reverse</code>, there is also <code>cons</code> function - constructs a list.<br> Do this really need destructors? Will be better to use smart pointers?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T21:41:34.930", "Id": "402650", "Score": "1", "body": "If you have `reverse` and `cons` functions, you should the code for them in the question." } ]
[ { "body": "<h2>Overview</h2>\n<p>The trouble here is ownership. Who owns the <code>tail</code>?</p>\n<p>In C++ ownership is a very important topic and defines who is responsible for who should destroy an object. The problem with C like pointers is there are no explicit ownership semantics. So as part of the documentation you need to define who the owner (and people read documentation is the problem here) is otherwise things go wrong and the wrong person will delete the object or it will never get deleted.</p>\n<p>This is why in modern C++ it is very <strong>uncommon</strong> to see C-pointers. Because there is no ownership defined. You can use smart pointers to explicitly define the owner of a pointer or you can use references to show that you are retaining ownership.</p>\n<p>Note: Inside a class it's OK to use a pointer as you control everything inside a class. The problems happen when you leak a pointer through a public interface.</p>\n<p>You don't show how you expect your class to be used, but given the interface it is easy to use it with pointers and leak object all over the place. Given the current interface I would expect the following to be standard usage:</p>\n<pre><code> ImmutableList&lt;int&gt;* data = new List&lt;int&gt;(1, new List&lt;int&gt;(2, new List&lt;int&gt;(3, new Nil&lt;int&gt;())));\n\n // Do stuff.\n\n delete data;\n</code></pre>\n<p>This leads to all but the first element from being leaked (because the destructor does not delete the chain).</p>\n<p>Now you can't just add a delete into the destructor as you can retrieve the tail and place it another object.</p>\n<pre><code>ImmutableList&lt;int&gt;* data1 = new List&lt;int&gt;(1, new Nil&lt;int&gt;());\nImmutableList&lt;int&gt;* data2 = new List&lt;int&gt;(2, data1-&gt;tail());\n</code></pre>\n<p>In this situation simply deleting the tail is not going to work as both <code>data1</code> and <code>data1</code> share the same tail. So you need some form of shared ownership semantics. Now you can do this yourself but if you try and implement your own ownership semantics then you need to define the copy and move operators for your class.</p>\n<pre><code>// Copy Operators\nList&amp; List::List(List const&amp;);\nList&amp; List::operator=(List const&amp;);\n\n// Move Operators\nList&amp; List::List(List&amp;&amp;);\nList&amp; List::operator=(List&amp;&amp;);\n</code></pre>\n<p>This becomes exceedingly not trivial when you have shared objects. So really you need to use <code>std::shared_ptr</code>.</p>\n<h2>Code Review</h2>\n<p>If you have a base class with virtual methods then you your destructor should also be virtual:</p>\n<pre><code>template &lt;class T&gt;\nclass ImmutableList {\n public: \n // Destructor should be declared virtual\n ~ImmutableList() {std::cout &lt;&lt; &quot;base class destructor&quot;;}\n ...\n}\n</code></pre>\n<p>This is because you are likely to use <code>delete</code> on a base class pointer that points at a derived type. If the destructor is not virtual you call the wrong destructor.</p>\n<p>Your code is not <code>const</code> correct.</p>\n<pre><code>virtual bool is_empty() = 0;\nvirtual T head() = 0;\nvirtual ImmutableList&lt;T&gt; * tail() = 0; \n</code></pre>\n<p>All the above methods are const (as your class is <code>Immutable</code>). So you can change the object just query it.</p>\n<pre><code>virtual bool is_empty() const = 0;\nvirtual T head() const = 0;\nvirtual ImmutableList&lt;T&gt;* tail() const = 0; \nvirtual int length() const = 0;\n // ^^^^^\n</code></pre>\n<p>You return the head by value. This causes a copy of the object. Now for int and other simple types this is not a problem. But for complex types (like vector) a copy may be much more expensive.</p>\n<p>So normally you return by reference. Not because the class in <code>Immutable</code> you should return a const reference.</p>\n<pre><code>virtual const&amp; T head() const = 0;\n // ^^^^^^\n</code></pre>\n<p>Now you return a reference to the object (allowing it to be queried). If you actually want a copy you can assign it to a variable and it will be copied.</p>\n<pre><code>T val = data1-&gt;head();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T00:42:59.260", "Id": "208411", "ParentId": "208357", "Score": "1" } } ]
{ "AcceptedAnswerId": "208411", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T00:40:15.337", "Id": "208357", "Score": "0", "Tags": [ "c++", "functional-programming", "interface" ], "Title": "Functional List in C++" }
208357
<p>I am doing some simple projects in an attempt to get good at programming, this is my first GUI would love some feedback, and some guidelines.</p> <pre><code>from tkinter import * import random root = Tk() root.resizable(False, False) root.title('Coinflipper') topframe = Frame(root) topframe.pack() botframe = Frame(root) botframe.pack(side=BOTTOM) midframe = Frame(root) midframe.pack() choice = Label(topframe, text="Enter the number of flips: ") choice.grid(row=1) ent = Entry(topframe) ent.grid(row=1, column=2) clickit = Button(botframe, text="FLIP THE COIN!!!") clickit.pack() out = Text(midframe, width=15, height=1) out2 = Text(midframe, width=15, height=1) out.grid(row=1, column=1, columnspan=3) out2.grid(row=2, column=1, columnspan=3) def flipy(event): guess = ent.get() heads = [] tails = [] if guess == '' or guess == str(guess): out.delete(1.0, "end-1c") out.insert("end-1c", 'Invalid') for flips in range(int(guess)): out.delete(1.0, "end-1c") out2.delete(1.0, "end-1c") random_number = random.randint(1, 2) if random_number == 1: heads.append("Heads") elif random_number == 2: tails.append("Tails") out.insert("end-1c", len(tails)) out.insert("end-1c", " -TAILS") out2.insert("end-1c", len(heads)) out2.insert("end-1c", " -HEADS") clickit.bind("&lt;Button-1&gt;", flipy) root.mainloop() </code></pre>
[]
[ { "body": "<p>Skyn37, </p>\n\n<p>This a great first time GUI setup.\nOnly saw a few things I would change to make it easier on yourself.\nI don't see anything wrong with your Function.</p>\n\n<p>Things that need work:</p>\n\n<p>1.Line 9 to 14: These are unnecessary as you already started using grid. Yet this is good practice. Just not needed for this program.</p>\n\n<p>2.Also try to organize your code better. It helps yourself and also others to quickly identify what the code is doing. I made a few tweaks to your code. Organized it a bit, and made a few minor changes. Placed everything using Grid and Tidied up the GUI a bit.</p>\n\n<pre><code>\"\"\"Geometry and Title\"\"\"\nroot.title('Coinflipper')\nroot.geometry(\"300x100\")\nroot.resizable(False,False)\n\n\"\"\"Labels &amp; Text Box\"\"\"\nchoice = Label(text=\"How Many Flips: \")\nT = Label(text=\"Tails: \")\nH = Label(text=\"Heads: \")\nent = Entry(root)\nout = Text(width=15, height=1)\nout2 = Text(width=15, height=1)\n\n\"\"\"Grid Positions\"\"\"\nchoice.grid(row=0, column=0, sticky=E)\nT.grid(row=1,column=0,sticky=E)\nH.grid(row=2,column=0,sticky=E)\nent.grid(row=0, column=1, columnspan=3)\nout.grid(row=1, column=1, columnspan=3)\nout2.grid(row=2, column=1, columnspan=3)\n\n\"\"\"Button Text and Position\"\"\"\nclickit = Button(text=\"FLIP THE COIN!!!\")\nclickit.grid(row=3,column=1)\n</code></pre>\n\n<p>Overall great work!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T20:52:52.380", "Id": "208404", "ParentId": "208358", "Score": "0" } }, { "body": "<p>You are abusing the <code>heads</code> &amp; <code>tails</code> lists into making simple counters.</p>\n\n<pre><code>heads = []\ntails = []\n\nfor flips in range(int(guess)):\n random_number = random.randint(1, 2)\n if random_number == 1:\n heads.append(\"Heads\")\n elif random_number == 2:\n tails.append(\"Tails\")\n\nlen(tails)\nlen(heads)\n</code></pre>\n\n<p>This could be replaced with simply:</p>\n\n<pre><code>heads = 0\ntails = 0\n\nfor flips in range(int(guess)):\n random_number = random.randint(1, 2)\n if random_number == 1:\n heads += 1\n else:\n tails += 1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T21:21:51.127", "Id": "402648", "Score": "0", "body": "Thank you ! I tend to overcomplicate things for myself. Guess that will go away with practice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T01:39:53.590", "Id": "208418", "ParentId": "208358", "Score": "3" } } ]
{ "AcceptedAnswerId": "208418", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T00:43:55.363", "Id": "208358", "Score": "4", "Tags": [ "python", "python-3.x", "gui", "tkinter", "user-interface" ], "Title": "Python coin flipper with GUI" }
208358
<p>When I was studying <a href="https://en.wikibooks.org/wiki/Haskell/Monad_transformers" rel="nofollow noreferrer">Monad Transformer</a>, I decided to create <code>StateT s m a</code> from scratch with instances for <code>Functor</code>, <code>Applicative</code> and <code>Monad</code>. </p> <p>This is what I have:</p> <pre><code>newtype StateT s m a = StateT { runStateT :: (s -&gt; m (a, s)) } instance Functor m =&gt; Functor (StateT s m) where -- fmap :: (a -&gt; b) -&gt; StateT s m a -&gt; StateT s m b -- which is (a -&gt; b) -&gt; (s -&gt; m (a, s)) -&gt; (s -&gt; m (b, s)) f `fmap` (StateT x) = StateT $ \ s -&gt; fmap run (x s) where run (a, s) = (f a, s) instance Monad m =&gt; Applicative (StateT s m) where -- pure :: a -&gt; StateT s m a pure a = StateT $ \ s -&gt; pure (a, s) -- &lt;*&gt; :: f (a -&gt; b) -&gt; f a -&gt; f b -- which is StateT s m (a -&gt; b) -&gt; StateT s m a -&gt; State s m b k &lt;*&gt; x = StateT $ \ s -&gt; do (f, s1) &lt;- runStateT k s -- :: m ((a -&gt; b), s) (a, s2) &lt;- runStateT x s1 return (f a, s2) instance (Monad m) =&gt; Monad (StateT s m) where return a = StateT $ \ s -&gt; return (a, s) -- &gt;&gt;= :: StateT s m a -&gt; (a -&gt; StateT s m b) -&gt; StateT s m b (StateT x) &gt;&gt;= f = StateT $ \ s -&gt; do (v, s') &lt;- x s runStateT (f v) s' </code></pre> <p>My original intention is to implement <code>Functor (StateT s m)</code> with <code>Functor m</code> restriction, <code>Applicative (StateT s m)</code> with <code>Applicative m</code> restriction, and <code>Monad (StateT s m) with</code>Monad m) restriction. However I couldn't do the <code>Applicative</code> case and had to use <code>Monad m</code> restriction instead. Is there a way to do it with <code>Applicative m</code>?</p> <p>Thank you in advance. </p>
[]
[ { "body": "<p>Your implementation is correct. The additional comments are also welcome. I would write <code>&lt;*&gt;</code> without <code>runState</code>, but that's personal preference.</p>\n\n<p>Keep in mind that you've re-implementend <code>Control.Monad.Trans.State.Strict.StateT</code>. For the lazy variant <code>Control.Monad.Trans.State.Lazy.StateT</code>, you would have to use lazy pattern matches in several places, so I assume you wanted to implement the strict variant.</p>\n\n<p>To answer your question: no, we cannot implement <code>Applicative (StateT s m)</code> in terms of <code>Applicative m</code>. A <a href=\"https://stackoverflow.com/q/18673525/1139697\">Q&amp;A on StackOverflow</a> contains some hints, but let's reiterate them:</p>\n\n<p>Suppose you have two values <code>f</code>, <code>x</code> and want <code>y</code> with the following types:</p>\n\n<pre><code>f :: StateT m s (a -&gt; b)\nx :: StateT m s a\ny :: StateT m s b\n</code></pre>\n\n<p>We first remove the newtype:</p>\n\n<pre><code>f :: s -&gt; m (s, (a -&gt; b))\nx :: s -&gt; m (s, a)\ny :: s -&gt; m (s, b)\n</code></pre>\n\n<p>If our initial state is <code>p</code>, we have</p>\n\n<pre><code>f p :: m (s, (a -&gt; b))\nx :: s -&gt; m (s, a)\n</code></pre>\n\n<p>We want to use the <code>s</code> from <code>f p</code> in <code>x</code> to feed into <code>x</code> and the function to use the <code>a</code>. Now, let's suppose that <code>m</code> is an Applicative. This gives us only <code>pure</code>, <code>fmap</code> and <code>&lt;*&gt;</code> to work with. Let's try to write an expression that only uses those three functions<code>pure</code>, <code>fmap</code> and <code>&lt;*&gt;</code>:</p>\n\n<pre><code>z s = fmap (\\(s', f') -&gt; fmap (\\(s'', x') -&gt; (s'', f' x')) x s') (f s)\n</code></pre>\n\n<p>Let's check whether that implementation is sane. It's easier to deciper if we swap <code>fmap</code>'s arguments:</p>\n\n<pre><code>x ~~&gt; f = fmap f x\nz s = f s -- 1\n ~~&gt; (\\(s', f') -&gt; -- 2\n x s' -- 3\n ~~&gt; (\\(s'', x') -&gt; (s'', f' x') -- 4\n )\n</code></pre>\n\n<ol>\n<li>We run <code>f s</code> to get our new state and our function. </li>\n<li>Both are in <code>m</code>, so we use <code>fmap</code> to get in there.</li>\n<li>We run <code>x s'</code> to get our new state again and our value. </li>\n<li>Both are in <code>m</code>, so we use <code>fmap</code> yet again. However, we're using <code>fmap</code> <strong>inside</strong> <code>fmap</code>, which already tells us that we're not going to end up with a simple <code>m ...</code>.</li>\n</ol>\n\n<p>In (4), we end up with the correct new state <code>s''</code> and the correct value <code>f' x'</code>. However, our type is <code>s -&gt; m (m (s, b))</code>. Applicative does not provide any methods to reduce the number of <code>m</code>'s, so we're stuck. We need to use <code>join :: Monad m =&gt; m (m x) -&gt; m x</code>.</p>\n\n<p>If we go back, we see that the problem arises due to <code>x</code>'s type <code>s -&gt; m (s, a)</code>. If it was <code>m (s -&gt; (s, a))</code>, we could simply use <code>Applicative</code>. <a href=\"https://stackoverflow.com/a/18676062/1139697\">Petr provides a detailed answer on SO</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T11:30:23.300", "Id": "208370", "ParentId": "208363", "Score": "1" } } ]
{ "AcceptedAnswerId": "208370", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T05:25:04.717", "Id": "208363", "Score": "1", "Tags": [ "haskell", "monads" ], "Title": "Implement State Monad transformer in Haskell from scratch" }
208363
<p>I've been working on some code to pull questions from the realtime feed on stackexchange.com and query more information about them from the API. It works, but I'd love some feedback on how I could make better use of some of the monads and how I could make better use of Aeson. I'd also love general refactoring/code organization tips.</p> <p>I've split my code into 3 sections (imports, aeson/type stuff, main code) to make it easier for reviewers. To run the code, just remove the text between them. In addition to the text above and below each section, I also added comments where I'm unsure about stuff in the code.</p> <hr> <p>First, my imports. If there's any best-practices I should be aware of related to my use of language extensions or best-practices regarding how I import things, please let me know.</p> <pre><code>{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DuplicateRecordFields #-} -- Also, is this the right way to declare Main? I've seen it done in different ways in different places. module Main (main) where import Control.Concurrent (forkIO) import Control.Monad (forever, unless) import Control.Monad.Trans (liftIO) import Network.Socket (withSocketsDo) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Network.WebSockets as WS import qualified Data.ByteString.Lazy.Char8 (unpack) import Data.CaseInsensitive ( CI ) import Data.Aeson import GHC.Exts (fromString) import Data.Maybe (fromJust) import Data.List (intercalate) import Network.HTTP.Conduit import qualified Network.URI.Encode (encode) import Data.Either.Unwrap (fromRight) import Data.Aeson.Encode.Pretty </code></pre> <p>Next, my data types and aeson fromJSON instances. It seems like I've got a ton of repetition with <code>field &lt;- o .: "field"</code> and then using <code>field=field</code> in the record syntax. Is there a better way to do that? I'm trying to avoid doing it with positional arguments to make it more flexible, in case I want to change the order for some reason.</p> <p>Also, in my fromJSON declaration for QAThread, I create a Post instance which really could be created from the top level of the QAThread json. I feel like there must be a way to do that more efficiently.</p> <p>I'm also open to ideas for better code organization/style/indentation/formatting in this section.</p> <pre><code>data WSResponse = WSResponse {action :: String, innerJSON :: String} deriving(Show) instance FromJSON WSResponse where parseJSON = withObject "HashMap" $ \o -&gt; WSResponse &lt;$&gt; o .: "action" &lt;*&gt; o .: "data" data WSPost = WSPost { siteBaseHostAddress :: String, nativeId :: Int, titleEncodedFancy :: String, bodySummary :: String, tags :: [String], lastActivityDate :: Int, url :: String, ownerUrl :: String, ownerDisplayName :: String, apiSiteParameter :: String } deriving(Show) instance FromJSON WSPost where parseJSON = withObject "WSPost" $ \o -&gt; do siteBaseHostAddress &lt;- o .: "siteBaseHostAddress" nativeId &lt;- o .: "id" titleEncodedFancy &lt;- o .: "titleEncodedFancy" bodySummary &lt;- o .: "bodySummary" tags &lt;- o .: "tags" lastActivityDate &lt;- o .: "lastActivityDate" url &lt;- o .: "url" ownerUrl &lt;- o .: "ownerUrl" ownerDisplayName &lt;- o .: "ownerDisplayName" apiSiteParameter &lt;- o .: "apiSiteParameter" return WSPost { siteBaseHostAddress=siteBaseHostAddress, nativeId=nativeId, titleEncodedFancy=titleEncodedFancy, bodySummary=bodySummary, tags=tags, lastActivityDate=lastActivityDate, url=url, ownerUrl=ownerUrl, ownerDisplayName=ownerDisplayName, apiSiteParameter=apiSiteParameter } data APIResponse a = APIResponse { items :: [a], has_more :: Bool, quota :: APIQuota } deriving(Show) -- Only used in APIResponse, does not need its own fromJSON instance (although that might be prettier) data APIQuota = APIQuota { total :: Int, remaining :: Int} deriving(Show) instance FromJSON b =&gt; FromJSON (APIResponse b) where parseJSON = withObject "APIResponse" $ \o -&gt; do has_more &lt;- o .: "has_more" items &lt;- o .: "items" quota_max &lt;- o .: "quota_max" quota_remaining &lt;- o .: "quota_remaining" -- page, page_size, total, type return APIResponse { items=items, has_more=has_more, quota=APIQuota {total=quota_max, remaining=quota_remaining} } data User = User { display_name :: String, link :: String, user_type :: String, -- Could prolly be its own type reputation :: Int, se_id :: Int } deriving(Show) instance FromJSON User where parseJSON = withObject "User" $ \o -&gt; do display_name &lt;- o .: "display_name" link &lt;- o .: "link" user_type &lt;- o .: "user_type" reputation &lt;- o .: "reputation" se_id &lt;- o .: "user_id" return User { display_name=display_name, link=link, user_type=user_type, reputation=reputation, se_id=se_id } data Comment = Comment { score :: Int, link :: String, owner :: User, se_id :: Int, creation_date :: Int, edited :: Bool, body :: String, body_markdown :: String } deriving(Show) instance FromJSON Comment where parseJSON = withObject "Comment" $ \o -&gt; do score &lt;- o .: "score" link &lt;- o .: "link" owner &lt;- o .: "owner" se_id &lt;- o .: "comment_id" creation_date &lt;- o .: "creation_date" edited &lt;- o .: "edited" body &lt;- o .: "body" body_markdown &lt;- o .: "body_markdown" return Comment { score=score, link=link, owner=owner, se_id=se_id, creation_date=creation_date, edited=edited, body=body, body_markdown=body_markdown } data QAThread = QAThread { title :: String, tags :: [String], question :: Post, answers :: [Post] } deriving(Show) instance FromJSON QAThread where parseJSON = withObject "QAThread" $ \o -&gt; do tags &lt;- o .: "tags" title &lt;- o .: "title" answers &lt;- o .:? "answers" .!= [] -- Stuff q_se_id &lt;- o .: "question_id" q_up_vote_count &lt;- o .: "up_vote_count" q_down_vote_count &lt;- o .: "down_vote_count" q_owner &lt;- o .: "owner" q_last_edit_date &lt;- o .:? "last_edit_date" .!= 0 q_last_activity_date &lt;- o .:? "last_activity_date" .!= 0 q_creation_date &lt;- o .: "creation_date" q_comments &lt;- o .:? "comments" .!= [] q_body &lt;- o .: "body" q_body_markdown &lt;- o .: "body_markdown" let question = Post { se_id=q_se_id, up_vote_count=q_up_vote_count, down_vote_count=q_down_vote_count, owner=q_owner, last_edit_date=q_last_edit_date, last_activity_date=q_last_activity_date, creation_date=q_creation_date, comments=q_comments, body=q_body, body_markdown=q_body_markdown } return QAThread { title=title, tags=tags, question=question, answers=answers } data Post = Post { se_id :: Int, up_vote_count :: Int, down_vote_count :: Int, owner :: User, last_edit_date :: Int, last_activity_date :: Int, creation_date :: Int, comments :: [Comment], body :: String, body_markdown :: String } deriving(Show) instance FromJSON Post where parseJSON = withObject "Post" $ \o -&gt; do answer_id &lt;- o .: "answer_id" question_id &lt;- o .:? "question_id" .!= 0 let se_id = if question_id == 0 then answer_id else question_id up_vote_count &lt;- o .: "up_vote_count" down_vote_count &lt;- o .: "down_vote_count" owner &lt;- o .: "owner" last_edit_date &lt;- o .:? "last_edit_date" .!= 0 last_activity_date &lt;- o .:? "last_activity_date" .!= 0 creation_date &lt;- o .: "creation_date" comments &lt;- o .:? "comments" .!= [] body &lt;- o .: "body" body_markdown &lt;- o .: "body_markdown" return Post { se_id=se_id, up_vote_count=up_vote_count, down_vote_count=down_vote_count, owner=owner, last_edit_date=last_edit_date, last_activity_date=last_activity_date, creation_date=creation_date, comments=comments, body=body, body_markdown=body_markdown } </code></pre> <p>And finally, the actual code for everything. Here's where most of my messy code is, and where I foresee needing the most improvement. All of my thoughts will be inline:</p> <pre><code>-- I have no idea how to write a type signature for this -- Also, I really think that these Maybes should be propogated out to avoid errors. However, doing -- that requires a bit more monad knowledge than I have. parseWSJSON msg = fromJust (decode (fromString . innerJSON . fromJust $ (decode msg :: Maybe WSResponse)) :: Maybe WSPost) -- This function declaration doesn't really make sense to me. It looks like it takes no argument, but -- then it actually takes a connection? app :: WS.ClientApp () app conn = do putStrLn "Connected!" -- and how does this go to STDOUT if the monad here is a WS.ClientApp? WS.sendTextData conn ("155-questions-active" :: Text) -- Fork a thread that writes WS data to stdout _ &lt;- forkIO $ forever $ do msg &lt;- WS.receiveData conn -- and how does this work, aren't we in an IO monad now? let post = parseWSJSON msg -- See comment by parseWSJSON above apiPost &lt;- getAPIPost post -- I'd like to have a scanQaThread :: APIResponse QAThread -&gt; ??? that does various things using -- the data in the QAThread object. I have a feeling that I should do something monadic there to -- preserve the Either-ness, but I don't know how. Suggestions appreciated. let qa_thread = fromRight (eitherDecode apiPost :: Either String (APIResponse QAThread)) -- This is my take on pretty printing the json. I'm sure there's a better way, but it's not too important liftIO $ T.putStrLn . T.pack $ unlines . map (take 100) . lines . Data.ByteString.Lazy.Char8.unpack $ (encodePretty (fromJust (decode apiPost :: Maybe Object))) -- This is where we actually decode the json to a APIResponse QAThread liftIO $ T.putStrLn . T.pack $ show (eitherDecode apiPost :: Either String (APIResponse QAThread)) -- Read from stdin and write to WS let loop = do line &lt;- T.getLine if line == "exit" then WS.sendClose conn ("Bye!" :: Text) else loop loop -- GHCi reports the type signature as of simpleHttp as Control.Monad.IO.Class.MonadIO m =&gt; String -&gt; m Data.ByteString.Lazy.Internal.ByteString -- but if I actually type IO Data.ByteString.Lazy.Internal.ByteString, I get an error. -- getAPIPost :: WSPost -&gt; IO ??? getAPIPost WSPost {apiSiteParameter=site, nativeId=nativeId} = simpleHttp $ "https://api.stackexchange.com/questions/" ++ show nativeId ++ generateQueryString [("site", site), ("filter", "!)F8(_jKugA9t(M_HBgMTswzW5VgyIjFl-O-sNR)ZYeihN)0*(")] generateQueryString :: [(String, String)] -&gt; String generateQueryString = ("?"++) . intercalate "&amp;" . map (\(k,v) -&gt; Network.URI.Encode.encode k ++ "=" ++ Network.URI.Encode.encode v) main :: IO () main = withSocketsDo $ WS.runClient "qa.sockets.stackexchange.com" 80 "/" app </code></pre>
[]
[ { "body": "<p>As you've noticed yourself, your <code>FromJSON</code> instances suffer from duplication. You could use the <em>automatic</em> instance generation with <a href=\"https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#extension-DeriveGeneric\" rel=\"nofollow noreferrer\"><code>-XDeriveGeneric</code></a>, however, some of your fields would mismatch (namely <code>id</code>).</p>\n\n<p>We can still fix this if we use <a href=\"https://hackage.haskell.org/package/aeson-1.4.2.0/docs/Data-Aeson-Types.html#v:defaultOptions\" rel=\"nofollow noreferrer\">custom options</a>, which simply remove the <code>native</code>:</p>\n\n<pre><code>fixName :: String -&gt; String\nfixName xs \n | \"native\" `isPrefixOf` xs = let (a:as) = drop 6 xs in toLower a : as\n | otherwise = xs\n\ndata WSPost = WSPost {\n ... snip ...\n }\n deriving(Show, Generic)\n\ninstance FromJSON WSPost where\n parseJSON = genericParseJSON customOptions\n where customOptions = defaultOptions\n { fieldLabelModifier = fixNames\n }\n</code></pre>\n\n<p>However, this still falls short on complicated fields like <code>APIQuota</code>. Here, we still suffer from duplication as you've noticed:</p>\n\n<blockquote>\n <p>It seems like I've got a ton of repetition with <code>field &lt;- o .: \"field\"</code> and then using <code>field=field</code> in the record syntax. Is there a better way to do that? </p>\n</blockquote>\n\n<p>Enter <a href=\"https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#record-wildcards\" rel=\"nofollow noreferrer\"><code>-XRecordWildCards</code></a>. It does exactly what you want:</p>\n\n<pre><code>instance FromJSON b =&gt; FromJSON (APIResponse b) where\n parseJSON = withObject \"APIResponse\" $ \\o -&gt; do\n has_more &lt;- o .: \"has_more\"\n items &lt;- o .: \"items\"\n quota_max &lt;- o .: \"quota_max\"\n quota_remaining &lt;- o .: \"quota_remaining\"\n -- page, page_size, total, type\n\n let quota = APIQuota {total=quota_max, remaining=quota_remaining}\n\n return APIResponse { .. } -- no duplication here\n</code></pre>\n\n<p>Note that you can shuffle your elements in your types arbitrarily.</p>\n\n<hr>\n\n<p>Unfortunately, I don't have time for a further in-depth analysis, but these remarks should help you improve the code and make it more readable. That being said, if you find yourself often in a situation where you want to describe code and still make it compileable or runnable, have a look at <a href=\"https://wiki.haskell.org/Literate_programming\" rel=\"nofollow noreferrer\">Literate Haskell</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T12:07:42.490", "Id": "208372", "ParentId": "208364", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T06:07:54.863", "Id": "208364", "Score": "1", "Tags": [ "haskell", "functional-programming", "monads" ], "Title": "Stack Exchange API Reader" }
208364
<blockquote> <h1><a href="https://www.pbinfo.ro/?pagina=probleme&amp;id=2347" rel="nofollow noreferrer">Ants</a></h1> <h2>Requirement</h2> <p>Given a natural number <span class="math-container">\$n\$</span>, representing the number of days the study is made, and then a number <span class="math-container">\$x\$</span> of <span class="math-container">\$n\$</span> natural numbers, representing the number of working ant flies after food, where the <span class="math-container">\$x_i\$</span> number of working ants is the day <span class="math-container">\$i\$</span>. It is required to determine the number of maximum sequences, ordered strictly decreasing after the number of divisors, of minimum length <span class="math-container">\$2\$</span>.</p> <h2>Input data</h2> <p>The input file <em>furnici.in</em> contains two lines. On the first line is the natural number <span class="math-container">\$n\$</span>, with the meaning of the requirement and on the second line, the elements of the string <span class="math-container">\$x\$</span>, with the meaning in the requirement.</p> <h2>Output data</h2> <p>The output file <em>furnici.out</em> will contain a natural number representing the number of maximum sequences, of minimum length <span class="math-container">\$2\$</span>, ordered strictly downwards by the number of divisors.</p> <h2>Restrictions and clarifications</h2> <p>Time Limit - 0.5 seconds<br> Memory limit - 64 MB Total / 8 MB Stack<br> <span class="math-container">\$2 \leq n \leq 100000 \$</span><br> <span class="math-container">\$10 \leq x_i \leq 1.000.000.000\$</span></p> <h2>Example</h2> <h3><em>furnici.in</em></h3> <pre><code>10 719 169 4065 813 289 101 123 516 516 1017 </code></pre> <h3><em>furnici.out</em></h3> <pre><code>2 </code></pre> <h3>Explanation</h3> <p>Row number of divisions is <span class="math-container">\$2\ 3\ 8\ 4\ 3\ 2\ 4\ 12\ 12\ 6\$</span>. It is noted that there are two maximum sequences, of at least two, strictly decreasing, <span class="math-container">\$8\ 4\ 3\ 2\$</span> and <span class="math-container">\$12\ 6\$</span>.</p> </blockquote> <p>My program is given an array of numbers that it has to find the divisors for and then replace the number in the array with its corresponding number of divisors. In the new created array, it will have to find and count all the descending subsequences that occur.</p> <p>Here is my code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;cmath&gt; using namespace std; int n,i,v[100001],nr,j,s; int main() { ifstream in("furnici.in"); ofstream out("furnici.out"); in&gt;&gt;n; for(i=1; i&lt;=n; i++) { in&gt;&gt;v[i]; nr=2; for(j=2; j&lt;=sqrt(v[i]); j++) { if(v[i]%j==0) { nr++; if(j!=v[i]/j) nr++; } } v[i]=nr; if(v[i]&lt;v[i-1]) { j=i; while(v[j]&lt;v[j-1] &amp;&amp; j&lt;n) { j++; nr=2; in&gt;&gt;v[j]; for(int k=2; k&lt;=sqrt(v[j]); k++) { if(v[j]%k==0) { nr++; if(k!=v[j]/k) nr++; } } v[j]=nr; } s++; i=j; } } out&lt;&lt;s; return 0; } </code></pre> <p>furnici.in</p> <pre><code>10 719 169 4065 813 289 101 123 516 516 1017 </code></pre> <p>furnici.out</p> <pre><code>2 </code></pre> <p>Explained:</p> <ul> <li>10 represents how many numbers are going to be read from the file;</li> <li>number 719 has 2 divisors, so 719 gets replaced with 2;</li> <li>number 169 has 3 divisors, so 169 gets replaced with 3;</li> <li>number 4065 has 8 divisors, so 4065 gets replaced with 8;</li> <li>and so on, you kind of get the point. The resulting array will have descending sequences: 2 3 <strong><em>8 4 3 2</em></strong> 4 12 <strong><em>12 6</em></strong> and these need to be counted.</li> </ul> <p>The issue with it is that it exceeds the time limit in the last test given to it, but otherwise the answer is correct.</p>
[]
[ { "body": "<p>Some general remarks:</p>\n\n<ul>\n<li><p>Don't use <code>namespace std;</code>, see for example <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Why is “using namespace std;” considered bad practice?</a>.</p></li>\n<li><p>Define variables at the narrowest possible scope. In particular, avoid\nglobal variables.</p></li>\n<li><p>Use better variable names. It is unclear what each variable in</p>\n\n<pre><code>int n,i,v[100001],nr,j,s;\n</code></pre>\n\n<p>stands for.</p></li>\n<li><p><code>return 0;</code> at the end of the main program can be omitted.</p></li>\n<li><p>The range of integer types is implementation defined, the C++ standard only\nguarantees that a (signed) <code>int</code> can hold values from -32767 to 32767,\nwhich is too small for your numbers. Many compilers define <code>int</code> as a 32-bit\ninteger, but you can use <code>long</code> to be on the safe side, or use fixed-size\ntypes like <code>int32_t</code>.</p></li>\n</ul>\n\n<p>With respect to readability, I recommend to leave more (horizontal) space,\ne.g. around operators and parentheses.</p>\n\n<p>There are two places with identical code to count the divisors\nof a number. This should be done in a separate function.</p>\n\n<p>Your code uses a nested loop where the inner loop updates the index of the\nouter loop. That is difficult to understand and error-prone. And it is \nnot necessary: Instead of starting a nested loop when the start of a \ndecreasing subsequence is found, set a flag instead and continue with the \nmain loop.</p>\n\n<p>You store all numbers from the input file in an array, which is not necessary:\neach loop iteration only needs the previous number to decide if the subsequence\nis (still) decreasing. It suffices to store the previously processed number\nin a variable.</p>\n\n<p>Summarizing the suggestions so far, the code could look like this:</p>\n\n<pre><code>#include &lt;fstream&gt;\n#include &lt;cmath&gt;\n\nlong numberOfDivisors(long n) {\n long count = 0;\n for (long j = 2; j &lt;= sqrt(n); j++) {\n if (n % j == 0) {\n count++;\n if (j != n/j)\n count++;\n }\n }\n return count;\n}\n\nint main()\n{\n std::ifstream inFile(\"furnici.in\");\n std::ofstream outFile(\"furnici.out\");\n\n long decreasingSequences = 0;\n bool isDescending = false;\n long lastDivisorCount = 0;\n long numDays;\n inFile &gt;&gt; numDays;\n for (long i = 1; i &lt;= numDays; i++) {\n long numAnts;\n inFile &gt;&gt; numAnts;\n long divisorCount = numberOfDivisors(numAnts);\n if (divisorCount &gt;= lastDivisorCount) {\n // No longer decreasing.\n isDescending = false;\n } else if (!isDescending) {\n // A decreasing subsequence started right here.\n isDescending = true;\n decreasingSequences += 1;\n }\n lastDivisorCount = divisorCount;\n }\n outFile &lt;&lt; decreasingSequences;\n}\n</code></pre>\n\n<p>Now you can start to improve the performance, and the prime candidate is\nof course the <code>numberOfDivisors()</code> function. </p>\n\n<p>An efficient method (and I'm repeating arguments from <a href=\"https://codereview.stackexchange.com/questions/120642/getting-all-divisors-from-an-integer/120646#120646\">Getting all divisors from an integer</a> now) is to use the prime factorization: If\n<span class=\"math-container\">$$\n n = p_1^{e_1} \\, p_2^{e_2} \\cdots p_k^{e_k}\n$$</span>\nis the factorization of <span class=\"math-container\">\\$ n \\$</span> into prime numbers <span class=\"math-container\">\\$ p_i \\$</span>\nwith exponents <span class=\"math-container\">\\$ e_i \\$</span>, then \n<span class=\"math-container\">$$\n \\sigma_0(n) = (e_1+1)(e_2+1) \\cdots (e_k+1)\n$$</span>\nis the number of divisors of <span class=\"math-container\">\\$ n \\$</span>, see for example\n<a href=\"https://en.wikipedia.org/wiki/Divisor_function\" rel=\"nofollow noreferrer\">Wikipedia: Divisor function</a>. Example:\n<span class=\"math-container\">$$\n 720 = 2^4 \\cdot 3^2 \\cdot 5^1 \\Longrightarrow\n \\sigma_0(720) = (4+1)(2+1)(1+1) = 30 \\, .\n$$</span></p>\n\n<p>Here is a possible implementation in C:</p>\n\n<pre><code>long numberOfDivisors(long n){\n\n long numDivisors = 1;\n long factor = 2; // Candidate for prime factor of `n`\n\n // If `n` is not a prime number then it must have one factor\n // which is &lt;= `sqrt(n)`, so we try these first:\n while (factor * factor &lt;= n) {\n if (n % factor == 0) {\n // `factor` is a prime factor of `n`, determine the exponent:\n long exponent = 0;\n do {\n n /= factor;\n exponent++;\n } while (n % factor == 0);\n // `factor^exponent` is one term in the prime factorization of n,\n // this contributes as factor `exponent + 1`:\n numDivisors *= exponent + 1;\n }\n // Next possible prime factor:\n factor = factor == 2 ? 3 : factor + 2;\n }\n\n // Now `n` is either 1 or a prime number. In the latter case,\n // it contributes a factor 2:\n if (n &gt; 1) {\n numDivisors *= 2;\n }\n\n return numDivisors;\n}\n</code></pre>\n\n<p>As a further improvement you can pre-compute the prime numbers with a \nsieving method. Note that it sufficient to pre-compute the primes in the\nrange <span class=\"math-container\">\\$ 2 \\ldots \\sqrt{N} \\$</span> where <span class=\"math-container\">\\$ N = 10^9 \\$</span> is the upper bound for the given input. That should help to stay within the given memory\nlimit of 64 MB.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T20:09:35.330", "Id": "402497", "Score": "0", "body": "This does solve the time issue, but I have a question, as I haven't seen this before: what does this ***\"factor = factor == 2 ? 3 : factor + 2;\"*** line do? Most notably, the question mark." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T20:14:51.783", "Id": "402498", "Score": "1", "body": "@antoniu200: That is the “conditional operator” (some people call it “ternary operator”). `condition ? expr1 : expr2` evaluates to `expr1` if the condition is true, and to `expr2` otherwise. Here it is a shorthand for `if (factor == 2) { factor = 3 } else { factor = factor + 2 }`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T20:20:32.877", "Id": "402502", "Score": "0", "body": "Thank you very much! I also noticed you edited the SO completely. Thanks for that too, now I know exactly what to include from now on!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T20:22:58.430", "Id": "402503", "Score": "0", "body": "@antoniu200: It was Snowhawk who did the work on your question, not me :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T20:24:51.020", "Id": "402504", "Score": "0", "body": "Whoops! You're right." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T19:32:11.363", "Id": "208401", "ParentId": "208368", "Score": "4" } } ]
{ "AcceptedAnswerId": "208401", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T11:14:01.580", "Id": "208368", "Score": "4", "Tags": [ "c++", "array", "time-limit-exceeded" ], "Title": "Finding decreasing sequences in an array of numbers" }
208368
<p>I am trying to manage an "app list" in my app (I currently have "MS Office" app list, "Games" app list and "other" app list). </p> <p>lists table:</p> <pre><code>list_id | list_name ---------------------------- 1 | MS Office 2 | Games 3 | Other </code></pre> <p>app to list table: </p> <pre><code>app_id | list_id ---------------------------- 1 | 1 2 | 1 3 | 1 4 | 3 5 | 2 </code></pre> <p>I want to create an object for each list and to be able to fetch data from each list (Unless it's not recommended due to bad practice), practicing OOP. </p> <p>Lets say I summon the MS Office list - <code>$office_list = new List_ms_office();</code> and get an object that handles the ms office list. </p> <p>I am adding my working code, I was just wondering if it's written well, structured well, doesn't have any "bad practices", ect'. </p> <p>This is my Main List class:</p> <pre><code>&lt;?php namespace App\Models; use App\Core\Database; /** * * Static List Template: Class that controls all data to and from `list_%` * */ class StaticList { /*================================= = Variables = =================================*/ # Database instance private $db; # Result app list array protected $appList; # Developer must include the list name of the llist // abstract protected $listName; /*=============================== = Methods = ================================*/ /** * * Construct * Init DB connectiom * */ public function __construct($listName){ # Get database instance $this-&gt;db = Database::getInstance(); } /** * * Get List ID: Gets the list id by the list name (from 'lists' table) * @param $listName String List name * @throws Init Returns the ID of the list * */ private function get_list_id_by_name($listName) { $sql = "SELECT `list_id` FROM `lists` WHERE `list_name` LIKE :listName"; $list_result = $this-&gt;db-&gt;queryIn($sql, array("listName" =&gt; "%{$listName}%")); return $list_result[0]['list_id']; } /** * * Get list array by id * @param $list_id init Gets a list id (as set in the 'list_apps' table) * @throws Array Returns an array of apps (which is the list) * */ private function get_list_array_by_id($list_id) { $app_query = "SELECT `app_id` FROM `list_apps` WHERE `list_id` = :listID"; return $this-&gt;db-&gt;query($app_query, array('listID'=&gt;$list_id)); } /** * * Get List of Apps * @param $listName String Gets a list name * @throws Array Returns app list as an array * */ protected function get_list_apps($listName) { # Get the list ID by List Name $list_id = $this-&gt;get_list_id_by_name($listName); # Get list array by id $app_result = $this-&gt;get_list_array_by_id($list_id); # Get list organized and ready foreach ($app_result AS $key =&gt; $app_array) { $app_id_array[] = $app_array['app_id']; } # Genrerate object $App = new App(); $app_data = $App-&gt;get_multiple_apps_data($app_id_array); return $app_data; } } </code></pre> <p>And this is my list extension (in this specific case, it's an MS Office class - fetching the list): </p> <pre><code>&lt;?php namespace App\Models\Lists; use App\Core\Database; use App\Models\StaticList; /* * App List: MS Office */ Class List_ms_office extends StaticList { /*================================= = Variables = =================================*/ # Database instance private $db; # This list must have a name right? private $listName = 'MS Office'; /*=============================== = Methods = ================================*/ /** * * Construct * Init DB connectiom * */ public function __construct() { $this-&gt;db = Database::getInstance(); // $this-&gt;appList = $this-&gt;get_list_apps($this-&gt;listName); } /** * * Get List: Gets the list of this object * */ public function getList() { $this-&gt;appList = $this-&gt;get_list_apps($this-&gt;listName); return $this-&gt;appList; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T02:07:16.400", "Id": "408248", "Score": "1", "body": "You have a few questions asked at this site and it looks like the answers you have received have been helpful to you. This site goes both ways. If you receive help you should reward those who help you by accepting their answer. Read [How does accepting an answer work?](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) and start giving back to the community. You also get two reputation points for each accepted answer! :)" } ]
[ { "body": "<p>I think the biggest issue here is not properly working with abstractions.</p>\n\n<p>Before we can create a proper abstraction, we need a better name. When I first looked at the \"StaticList\" class, I assumed all members of this class were static, as in, not an instance member. They are all instance members, which makes the name of the class misleading. Calling this class \"ApplicationList\" would be more appropriate</p>\n\n<p>So, first things first, rename the StaticList class (I'll use ApplicationList from here on).</p>\n\n<h2>Abstraction #1: An ApplicationList has a name</h2>\n\n<p>You created a child class that is specific to a single list and hard coded the name of the list. Move this name up into the ApplicationList class and pass the name in when instantiating the list at runtime:</p>\n\n<pre><code>$list = new ApplicationList('MS Office');\n</code></pre>\n\n<h2>Abstraction #2: iterating over the list</h2>\n\n<p>Since you are modeling a list, and I'm sure at some point you'll want to iterate/loop over all the items in the list, you can have ApplicationList <a href=\"http://php.net/manual/en/language.oop5.iterations.php\" rel=\"nofollow noreferrer\">implement the Iterator interface in PHP</a>, so you can do things like:</p>\n\n<pre><code>foreach ($list as $index =&gt; $item) {\n // do something with $item\n}\n</code></pre>\n\n<h2>Separation of Concerns</h2>\n\n<p>You are also mixing data access code with an object more focused on business logic. Consider moving this logic into another class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-21T13:22:17.727", "Id": "210118", "ParentId": "208371", "Score": "1" } } ]
{ "AcceptedAnswerId": "210118", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T12:06:39.993", "Id": "208371", "Score": "2", "Tags": [ "php", "object-oriented" ], "Title": "PHP OOP: List management" }
208371
<p>I have a script that changes the display brightness using <code>xrandr</code>. It is my first bash script. I mainly had a lot of trouble with dealing with the floating point values. I think that is one of the main reasons the performance is bad.</p> <pre><code> 1 #!/bin/bash 2 # increase/decrease display brightness of xrandr of both displays 3 # use: 4 # $ ./change_brightness [up/down (0/1)] 5 6 export current_brightness=$(xrandr --verbose | awk '/Brightness/ { print $2; exit }') 7 8 export increase=$1 9 export new_brightness=$current_brightness 10 11 if [ "$increase" = "1" ]; then 12 if [ $current_brightness != "1.0" ]; then 13 new_brightness="$current_brightness + 0.2" 14 fi 15 elif [ "$increase" = "0" ]; then 16 if [ $current_brightness != "0.20" ]; then 17 new_brightness="$current_brightness - 0.2" 18 fi 19 fi 20 21 new_brightness=$(bc &lt;&lt;&lt; "$new_brightness") 22 23 xrandr --output eDP-1-1 --brightness $new_brightness 24 xrandr --output DP-0 --brightness $new_brightness </code></pre> <p>The performance isn't terrible, but any improvements would be highly appreciated. Also the improvements that have nothing to do with performance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T14:50:48.903", "Id": "402468", "Score": "6", "body": "Please don't put line numbers in code snippets. That makes it much harder for people like me to cut and paste your code" } ]
[ { "body": "<p>I'm confused about your goal for this question:</p>\n\n<ol>\n<li>performance is bad</li>\n<li>performance isn't terrible</li>\n<li>improvements would be appreciated</li>\n<li>improvements have nothing to do with performance.</li>\n</ol>\n\n<p>Nevertheless, code review notes:</p>\n\n<ul>\n<li>you don't have to <code>export</code> every variable, only the ones that are needed by processes you spawn from this script.</li>\n<li>validate inputs: why do anything if the input is neither \"0\" nor \"1\"?</li>\n</ul>\n\n<p>Here's my take:</p>\n\n<pre><code>#!/bin/bash \n# increase/decrease display brightness of xrandr of both displays \n# use: \n# $ ./change_brightness [up/down (0/1)] \n\ncurrent_brightness=$(xrandr --verbose | awk '/Brightness/ { print $2; exit }') \ncase $1 in\n 0) direction=-1;;\n 1) direction=1;;\n *) echo \"some error message\"; exit 1;;\nesac\n\nexport current_brightness direction\nnew_brightness=$( perl -E '\n use List::Util qw( min max );\n say max(0, min($ENV{current_brightness} + $ENV{direction} * 0.2, 1.0));\n')\n\nxrandr --output eDP-1-1 --brightness $new_brightness \nxrandr --output DP-0 --brightness $new_brightness \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T15:34:31.503", "Id": "208383", "ParentId": "208375", "Score": "1" } }, { "body": "<h3>Validate your inputs</h3>\n\n<p>As <a href=\"https://codereview.stackexchange.com/users/3219/glenn-jackman\">@glenn-jackman</a> pointed out, validate your inputs.\nIf the script argument should be either 0 or 1,\nthen enforce that rule, by checking the value,\nand exit with an error if it's some other value.\nIt's always good to fail early,\nfor example to avoid confusing crashes later due to an unexpected value,\nor to avoid doing unnecessary work.</p>\n\n<h3>Look for corner cases</h3>\n\n<p>The script increases or decreases brightness in increments of 0.2,\nunless the value is 1.0 or 0.2.\nThis is fragile.\nWhat if the current value is 0.9?\nThe script will not prevent going to 1.1, 1.3, ..., or 0.1, -0.1, ..., and so on.\nThis is a bug waiting to happen.</p>\n\n<p>To correctly enforce upper and lower limits,\nyou need an appropriate technique.\nAs you discovered, Bash cannot do floating point math.\nI would recommend Awk instead.\nIt's lightweight and universally available.</p>\n\n<h3>Always double-quote variables in program arguments</h3>\n\n<p>As a good rule of thumb,\nalways double-quote variables used in program arguments,\nfor example here:</p>\n\n<blockquote>\n<pre><code>if [ $current_brightness != \"1.0\" ]; then \n...\n\nxrandr --output eDP-1-1 --brightness $new_brightness\n</code></pre>\n</blockquote>\n\n<p>Write like this instead:</p>\n\n<pre><code>if [ \"$current_brightness\" != \"1.0\" ]; then \n...\n\nxrandr --output eDP-1-1 --brightness \"$new_brightness\"\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T22:49:03.610", "Id": "208407", "ParentId": "208375", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T13:23:15.803", "Id": "208375", "Score": "1", "Tags": [ "beginner", "bash", "floating-point" ], "Title": "Bad performance bash, changing display brightness" }
208375
<p>I made using SFML my first game project. It's a snake game, and I used 2 custom classes:</p> <ul> <li>snake</li> <li>fruit (snake grow by 1 when eat it)</li> </ul> <p>Here's main.cpp code:</p> <pre><code>#include &lt;SFML/Graphics.hpp&gt; #include "snake.h" #include "fruit.h" int main() { sf::RenderWindow app(sf::VideoMode(800, 600), "SFML window"); snake snake; fruit fruit; snake.fruitptr = &amp;fruit; snake.window = &amp;app; while (app.isOpen()) { // Process events sf::Event event; while (app.pollEvent(event)) { // Close window : exit if (event.type == sf::Event::Closed) app.close(); } snake.movement(); snake.checkCollisions(); app.clear(); app.draw(fruit); app.draw(snake); app.display(); } return EXIT_SUCCESS; } </code></pre> <p>Fruit and Snake header</p> <pre><code>#ifndef SNAKE_H #define SNAKE_H #include &lt;SFML/Graphics.hpp&gt; #include &lt;iostream&gt; #include "fruit.h" class snake : public sf::Drawable { public: snake(); virtual ~snake(); void movement(); void addElement(); void checkCollisions(); fruit* fruitptr; virtual void draw(sf::RenderTarget&amp; target, sf::RenderStates states) const; sf::RectangleShape oldPosition; sf::RenderWindow* window; private: float a, b; float x, y; int length; sf::Time time; sf::RectangleShape shape; sf::RectangleShape* snakeBody; sf::RectangleShape* snakeBodycopy; }; #endif // SNAKE_H </code></pre> <pre><code>#ifndef FRUIT_H #define FRUIT_H #include &lt;SFML/Graphics.hpp&gt; #include &lt;time.h&gt; class fruit : public sf::Drawable { public: fruit(); virtual ~fruit(); sf::RectangleShape shape; virtual void draw(sf::RenderTarget&amp; target, sf::RenderStates states) const; private: }; #endif // FRUIT_H </code></pre> <p>And finally the .cpp files:</p> <pre><code>#include "snake.h" snake::snake() { x = 20.f; y = 20.f; length = 0; time = sf::seconds(0.1f); shape.setFillColor(sf::Color::Red); shape.setSize( {20.f,20.f}); shape.setPosition( {20.f,20.f}); } snake::~snake() { //dtor } void snake::draw(sf::RenderTarget&amp; target, sf::RenderStates states) const { target.draw(this-&gt;shape, states); if(this-&gt;length == 1){ this-&gt;snakeBody[0].setPosition(this-&gt;oldPosition.getPosition()); target.draw(this-&gt;snakeBody[0] ,states); } else if(this-&gt;length&gt;1){ for(int i=this-&gt;length-1;i&gt;0;i--){ this-&gt;snakeBody[i].setPosition(this-&gt;snakeBody[i-1].getPosition()); this-&gt;snakeBody[i].setFillColor(sf::Color::Red); this-&gt;snakeBody[i].setSize({20.f ,20.f}); target.draw(this-&gt;snakeBody[i], states); } this-&gt;snakeBody[0].setFillColor(sf::Color::Red); this-&gt;snakeBody[0].setSize({20.f , 20.f}); this-&gt;snakeBody[0].setPosition(this-&gt;oldPosition.getPosition()); target.draw(this-&gt;snakeBody[0], states); } } void snake::movement() { this-&gt;oldPosition.setPosition(this-&gt;shape.getPosition()); if(sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { this-&gt;a=0; this-&gt;b=-20.f; } else if(sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { this-&gt;a=-20.f; this-&gt;b=0; } else if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { this-&gt;a=0; this-&gt;b=20.f; } else if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { this-&gt;a=20.f; this-&gt;b=0; } this-&gt;shape.move(a,b); sf::sleep(this-&gt;time); } void snake::checkCollisions() { for(int i=0; i&lt;this-&gt;length; i++) { if(this-&gt;shape.getGlobalBounds().intersects(this-&gt;snakeBody[i].getGlobalBounds())){ this-&gt;window-&gt;close(); std::cout&lt;&lt;"You Lose!"&lt;&lt;std::endl; } } if(this-&gt;shape.getGlobalBounds().intersects(this-&gt;fruitptr-&gt;shape.getGlobalBounds())) { this-&gt;fruitptr-&gt;shape.setPosition( (rand()%40)*20, (rand()%30)*20); this-&gt;addElement(); std::cout&lt;&lt;"+1"&lt;&lt;std::endl; } } void snake::addElement() { if(this-&gt;length == 0){ this-&gt;length++; snakeBody = new sf::RectangleShape [this-&gt;length]; snakeBody[0].setFillColor(sf::Color::Red); snakeBody[0].setSize({20.f, 20.f}); } else{ this-&gt;snakeBodycopy = new sf::RectangleShape [this-&gt;length]; for(int i=0;i&lt;this-&gt;length;i++){ this-&gt;snakeBodycopy[i].setPosition(this-&gt;snakeBody[i].getPosition()); } this-&gt;length++; delete [] snakeBody; this-&gt;snakeBody = new sf::RectangleShape [this-&gt;length]; for(int i=0;i&lt;this-&gt;length-1;i++){ this-&gt;snakeBody[i].setPosition(this-&gt;snakeBodycopy[i].getPosition()); } delete [] snakeBodycopy; } } </code></pre> <pre><code>#include "fruit.h" fruit::fruit() { shape.setFillColor(sf::Color::White); shape.setSize( {20.f,20.f}); shape.setPosition( (rand()%40)*20, (rand()%30)*20); } fruit::~fruit() { //dtor } void fruit::draw(sf::RenderTarget&amp; target, sf::RenderStates states) const{ target.draw(this-&gt;shape, states); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T21:31:18.487", "Id": "402510", "Score": "0", "body": "Some of your indentation is off. Is this a side-effect of posting on stackexchange or is this how it appears in your editor?" } ]
[ { "body": "<p>Here are a list of things that I notice here.</p>\n\n<h3>Indentation and Spacing</h3>\n\n<p>Throughout your code, your indentation and spacing is inconsistent. I would recommend picking a specific tab width and setting this either to 1 tab or the respective amount of spaces. In addition, placing spaces around all operators and before braces will create clarity.</p>\n\n<h3>Useless Destructor</h3>\n\n<pre><code>snake::~snake()\n{\n //dtor\n}\n</code></pre>\n\n<p>If you don't plan on using your destructor, then adding an implementation is unnecessary.</p>\n\n<h3>Usage of <code>this</code></h3>\n\n<p>Looking through your classes, I notice that you prefix everything with <code>this-&gt;</code>, even though this is unnecessary in C++. If you really need to separate local variables from members, then I would recommend a good naming convention (I use a trailing underscore).</p>\n\n<h3>Random Numbers</h3>\n\n<pre><code>shape.setPosition( (rand()%40)*20, (rand()%30)*20);\n</code></pre>\n\n<p>In C++, using the <a href=\"https://en.cppreference.com/w/cpp/header/random\" rel=\"nofollow noreferrer\"><code>&lt;random&gt;</code></a> header is recommended over plain old <code>rand()</code> (which you didn't seed with <code>srand()</code>, AFAICT so the fruit location will always be the same every run of the game).</p>\n\n<h3>Use of <code>std::endl</code></h3>\n\n<p>Unless your goal is to specifically flush the console, then you shouldn't be using <code>std::endl</code>. Prefer plain old <code>\\n</code> instead.</p>\n\n<h3>A Proper Fixed Timestep</h3>\n\n<pre><code>sf::sleep(this-&gt;time);\n</code></pre>\n\n<p>In most games, what you want to aim for is a proper <a href=\"https://gafferongames.com/post/fix_your_timestep/\" rel=\"nofollow noreferrer\">fixed timestep</a>, which helps create deterministic runs with use of delta times in between frames. Good beginner SFML tutorials/books usually cover this and it is a <em>must</em> for a good game loop.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T01:15:24.013", "Id": "208417", "ParentId": "208378", "Score": "1" } }, { "body": "<p>One thing that jumps off the page immediately is that you are dealing with raw pointer management (via new[] and delete[]). In 2018, it should be very rare that a casual programmer need to do this. There are a lot of good reasons not to.</p>\n\n<p>Some of the most compelling reasons involve moving/assigning/copying objects...and you're not doing that yet, since you just have one snake and one fruit. But even still, you have a memory leak, just because your <code>addElement()</code> routine does allocations of the <code>snakeBody</code> with <code>new []</code> that it never frees in the destructor.</p>\n\n<p><em>(Note: You'd do well to go ahead and start running something like Valgrind or Address Sanitizer, or Dr. Memory on Windows, so you get a report of memory leaks and errors. But you should have a lot fewer of them if you learn and follow modern practices.)</em></p>\n\n<h2>learn and use <a href=\"https://en.cppreference.com/w/cpp/container/vector\" rel=\"nofollow noreferrer\"><code>std::vector</code></a></h2>\n\n<p>Your entire addElement() routine is essentially trying to implement the std::vector container's <code>push_back()</code>. If you're trying to learn low-level memory management on purpose, I'd encourage you to do it by breaking off that task into writing a <code>my_vector</code> class.</p>\n\n<p>But if you're doing it because you don't know what a std::vector is, then I'd certainly urge you to look through a tutorial. Here's <a href=\"https://embeddedartistry.com/blog/2017/6/20/an-introduction-to-stdvector\" rel=\"nofollow noreferrer\">one</a> and <a href=\"https://medium.com/the-renaissance-developer/c-standard-template-library-stl-vector-a-pretty-simple-guide-d2b64184d50b\" rel=\"nofollow noreferrer\">another</a> I can find offhand on the present-day web.</p>\n\n<p>So <code>#include &lt;vector&gt;</code> in your project, and start by changing:</p>\n\n<pre><code>sf::RectangleShape* snakeBody;\nsf::RectangleShape* snakeBodycopy;\n</code></pre>\n\n<p>into:</p>\n\n<pre><code>std::vector&lt;sf::RectangleShape&gt; snakeBody;\n</code></pre>\n\n<p>Tutorials and reference guides should hopefully give you enough examples to adapt your program to that change and keep it working. If not, you can ask for help on StackOverflow. It may not seem easy at first, but it really is easier and less error prone than what you're attempting here.</p>\n\n<hr>\n\n<h2>start remembering the catchphrase: <a href=\"https://stackoverflow.com/questions/44997955/rule-of-zero-confusion\">\"Rule of Zero\"</a></h2>\n\n<p>You don't have to fully absorb what \"rule of zero\" means yet...but maybe read around on it and start getting the inkling that it's important. It applies to why you don't want raw pointers in your classes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T01:50:24.040", "Id": "208419", "ParentId": "208378", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T14:08:06.927", "Id": "208378", "Score": "6", "Tags": [ "c++", "snake-game", "sfml" ], "Title": "Snake game using SFML CPP" }
208378
<p>I am a newbie in a programming, and I just randomly chose <a href="https://scontent.fiev10-1.fna.fbcdn.net/v/t1.0-9/46518941_2219787068289887_5720743666285281280_n.jpg?_nc_cat=110&amp;_nc_ht=scontent.fiev10-1.fna&amp;oh=de67fd916226fe613a6f9eab7526fd54&amp;oe=5C79CD84" rel="nofollow noreferrer">a task for training from some group on Facebook</a>. The task is to calculate the cost of cement for a construction project. The input is the number of pounds of cement required (guaranteed not to be a multiple of 120). The store sells cement in 120-pound bags, each costing $45.</p> <p>Example input: <code>295.8</code><br> Output: <code>135</code></p> <hr> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define PRICE 45 #define CAPACITY 120 #define MAXDIGITS 5 int sum(int); int main(int argc, char *argv[]) { int val = 0; char inp[MAXDIGITS]; if ((argc &gt; 1) &amp;&amp; (argv[1] &gt; 0)) val = strtol(argv[1], NULL, 0); else { do { printf("Please input the value of cement: "); scanf("%s", inp); val = strtol(inp, NULL, 0); } while (!val); } if (val) printf("Money you need: %d\n", sum(val)); return 0; } int sum(int need) { int mon = PRICE; int n = CAPACITY; while (n &lt; need) { n += CAPACITY; mon += PRICE; } return mon; } </code></pre> <p>I'm interested in code style, rational memory usage, etc.</p>
[]
[ { "body": "<p>Welcome on Code Review</p>\n\n<h2>Review</h2>\n\n\n\n<pre><code>#define PRICE 45\n#define CAPACITY 120\n#define MAXDIGITS 5\n</code></pre>\n\n<ul>\n<li>You define <code>PRICE</code> and <code>CAPATITY</code> as integers, but a price can have cents, and a bag can maybe contains more than a plain amount in pounds, maybe some ounces more. So you should use decimals here.</li>\n</ul>\n\n\n\n<pre><code>if ((argc &gt; 1) &amp;&amp; (argv[1] &gt; 0))\n</code></pre>\n\n<ul>\n<li>Don't compare a <code>char*</code> to an <code>int</code>. This check doesn't insure that <code>argv[1]</code> is a valid number.</li>\n<li>If the parameter isn't what you want, you can either print the usage and quit, or silently continue and ask for input.</li>\n</ul>\n\n\n\n<pre><code>val = strtol(argv[1], NULL, 0);\n</code></pre>\n\n<ul>\n<li>You don't validate the program argument. <code>strtol</code> can silently fail and return \"0\". In this case, a good option would be to ask for a good input.</li>\n<li><p>You parse the string to an unsigned integer; but the asked task stand asking a decimal number (and show \"295.8\" in the example). You could use <code>strtod</code> or <code>atof</code> but since you are a conscientious programmer, you want to check for validity.</p>\n\n<p>So the combo <code>scanf</code>/<code>sscanf</code> (with <code>\"%f\"</code> or <code>\"%lf\"</code>)` are the solution. </p></li>\n</ul>\n\n<p></p>\n\n<pre><code>do \n{\n printf(\"Please input the value of cement: \");\n</code></pre>\n\n<ul>\n<li>Try to put a <code>\\n</code>before your request. It will make the output more clear. Otherwise, it will print on the same line as last output.</li>\n</ul>\n\n\n\n<pre><code>scanf(\"%s\", inp);\nval = strtol(inp, NULL, 0);\n</code></pre>\n\n<ul>\n<li>As above, use <code>scanf(\"%lf\", ...)</code> instead (shorter, and you can check for errors)</li>\n</ul>\n\n<p></p>\n\n<pre><code>int sum(int need)\n</code></pre>\n\n<p>Once what i said above is fixed (price and capacity as <code>double</code>) your function work fine. However, you can simplify it, by doing the computation in only one line (which can be simplified even more, with libmath).</p>\n\n<p>Here's my corrected version:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\n#define PRICE 45.\n#define CAPACITY 120.\n\nint sum(int);\n\nint main(int argc, char *argv[])\n{\n double need = 0.;\n\n if (argc &lt; 2 || sscanf(argv[1], \"%lf\", &amp;need) != 1) {\n while (printf(\"\\nPlease input the amount of cement you need (e.g. 295.8): \") &amp;&amp; scanf(\"%lf\", &amp;need) != 1) {\n for(int c = 0; c != '\\n' &amp;&amp; c != EOF; c = getchar());\n } \n }\n printf(\"For %.02lf pounds you need: $%.02lf!\\n\", need, PRICE * ((int)((int)(need / CAPACITY) * CAPACITY &lt; need) + (int)(need / CAPACITY)));\n\n // or with \"#include &lt;math.h&gt;\" and the compiler/linker flag \"-lm\"\n //printf(\"For %.02lf pounds you need: $%.02lf!\\n\", need, PRICE * ceil(need / CAPACITY));\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T23:02:16.020", "Id": "402514", "Score": "0", "body": "Agree with you. Only one small mark for your code. If it receive a characters instead of digits, it enters to infinite loop. I think there is no alternative to use additional variable to avoid that possibility." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T23:38:15.880", "Id": "402516", "Score": "1", "body": "@DmitryKhaletskiy fixed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T14:33:17.000", "Id": "402734", "Score": "3", "body": "Sorry, but this code is severely lacking and definitely not something that should be used in place of the OP's much more readable code. The calculations badly need to be split over several lines. Arbitrary checking the return value of printf is fishy. C programming isn't about writing as few LOC as possible, if that comes at the expensive of readability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T18:33:32.623", "Id": "402787", "Score": "0", "body": "`while (... scanf(\"%lf\", &need) != 1) {` is an infinite loop on end-of-file, input error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T18:36:23.033", "Id": "402789", "Score": "0", "body": "`(int)` unnecessarily limits a floating-pint function to the `int` range - promoting a weak programing paradigm. Robust code would use `rint()`, `round()`, `trunc()` etc. instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T18:39:11.150", "Id": "402792", "Score": "0", "body": "Code that follows the width of the presentation with of the site (about 92 here) is easier to read and review. Consider re-formatting. Should be easy with an auto formatter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T18:42:27.177", "Id": "402794", "Score": "0", "body": "Why is code checking the return value of `printf()` against 0? A negative value indicates error. If the value is to be ignored, consider `,` instead of `&&`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T19:00:32.053", "Id": "402796", "Score": "0", "body": "Concerning \"Try to put a \\nbefore your request.\", consider [Why use trailing newlines instead of leading with printf?](https://softwareengineering.stackexchange.com/q/381711/94903)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T01:43:15.963", "Id": "402837", "Score": "0", "body": "@chux about the casting, did you notice the commented lines? And here, casting do the job. I didn't say to don't using libmath, just that in this case we can go without. (and I showed how to do with `libmath` too just in case). Also, you have 600 characters to put your message, you don't need to post 5 times in a row." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T03:55:34.663", "Id": "402847", "Score": "0", "body": "I did not notice the commented out code. The comments were separate as they cover different subjects over time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T09:52:25.687", "Id": "402870", "Score": "0", "body": "I don't recommend using floating-point types for financial quantities - use a type where hundredths can be precisely represented instead. For most uses, a suitable type is fixed-precision representation, using integers to represent each 0.01 of the value." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T17:16:46.847", "Id": "208390", "ParentId": "208380", "Score": "-2" } }, { "body": "<h2>Buffer overflow</h2>\n<p>Consider what entering <code>&quot;295.8&quot;</code> does.</p>\n<pre><code>#define MAXDIGITS 5\nchar inp[MAXDIGITS];\nprintf(&quot;Please input the value of cement: &quot;);\nscanf(&quot;%s&quot;, inp);\n</code></pre>\n<p>Code used the dangerous <code>scanf(&quot;%s&quot;, inp);</code> with no width limits. <code>scanf(&quot;%s&quot;, inp);</code> being ignorant of the size of <code>inp[]</code>, stored the 5 read characters <strong>and</strong> the appended <em>null character</em>.</p>\n<p>This results in <em>undefined behavior</em> (UB). Code may work as expected today and fail in strange ways tomorrow.</p>\n<p>I recommend to only use <code>fgets()</code> for user input. After reading a <em>line</em> of user input, it is saved as a <em>string</em>. Then parse the string.</p>\n<p>No need for such a tight buffer size. Recommend twice the expected max width needed.</p>\n<pre><code>#define BUFFER_SIZE (2*MAXDIGITS + 1)\nchar buffer[BUFFER_SIZE];\n\nprintf(&quot;Please input the value of cement: &quot;);\nfflush(stdout); // Insure output is seen before reading\n\nfgets(buffer, sizeof buffer, stdin);\ndouble val = strtod(buffer, NULL);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T19:33:36.593", "Id": "208563", "ParentId": "208380", "Score": "2" } } ]
{ "AcceptedAnswerId": "208390", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T14:39:43.100", "Id": "208380", "Score": "6", "Tags": [ "beginner", "c", "calculator" ], "Title": "Calculate the cost of cement for a project" }
208380
<p>Have a look at this dataset. The"a" and "b" are used to make possible differentiate when the <em>same</em> variable was measured. In this case X1a and X1b access the same variable, but "a" was (suppose..) in the last year and "b" was this year. </p> <p><a href="https://i.stack.imgur.com/eVV6d.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eVV6d.png" alt="Original dataframe"></a><br> I just want to correlate "a" and "b" and plot it. Simple like that and I really imagine the following code can be improved. </p> <p>The final plot will be this one: <a href="https://i.stack.imgur.com/H9SqJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H9SqJ.png" alt="Correlation plot"></a> The data is fake, but it's virtually equal as the original dataset I'm working on.</p> <pre><code> all_items &lt;- data.frame("1a" = sample(1:5), "2a" = sample(1:5), "3a" = sample(1:5), "1b" = sample(1:5), "2b" = sample(1:5), "3b" = rep(sample(1:5),10)) #matrix with correlation all_correlation &lt;- cor(all_items, method = "spearman") %&gt;% as.data.frame() #filter all_correlation &lt;- all_correlation %&gt;% select(-c(ends_with("a"))) #columns #create a colum with the now name all_correlation &lt;- all_correlation %&gt;% mutate(item = row.names(.)) %&gt;% select(item, everything()) #supress some rows all_correlation &lt;- all_correlation %&gt;% filter(!grepl("b", item)) #filter(stringr::str_detect(row.names(.), "b")) #get only the diagonal all_correlation &lt;- data.frame(item=1:3,Result=diag(as.matrix(all_correlation[, -1]))) #P Value all_correlation_p_value &lt;- Hmisc::rcorr(as.matrix(all_items))$P %&gt;% as.data.frame() #filter all_correlation_p_value &lt;- all_correlation_p_value %&gt;% select(-c(ends_with("a"))) all_correlation_p_value &lt;- all_correlation_p_value %&gt;% mutate(item = row.names(.)) %&gt;% select(item, everything()) all_correlation_p_value &lt;- all_correlation_p_value %&gt;% filter(!grepl("b", item)) all_correlation_p_value &lt;- data.frame(item=1:3,P_Valor=diag(as.matrix(all_correlation_p_value[, -1]))) #General table with the correlation results all_correlation &lt;- right_join(all_correlation,all_correlation_p_value, by = "item") #Plot ggplot(all_correlation, aes(x=item, y=Result)) + geom_point(aes(color=Result)) + geom_line() + annotate("text", x = all_correlation$item, y=all_correlation$Result, label = paste("P-value =",round(all_correlation$P_Valor,3)), hjust = -0.1, colour = "red") + scale_x_continuous(breaks = seq(1,3,1)) </code></pre>
[]
[ { "body": "<p>Here are two possible rewrites. For the first one, notice how <code>Hmisc::rcorr</code> already computes correlations (<code>$r</code>) and p-values (<code>$P</code>) matrices so you can base all your work from it, provided you extract the rights rows (<code>a_vars</code>) and columns (<code>b_vars</code>) and only keep the diagonal values:</p>\n\n<pre><code>correlations &lt;- rcorr(as.matrix(all_items), type = \"spearman\")\na_vars &lt;- ends_with(\"a\", vars = names(all_items))\nb_vars &lt;- ends_with(\"b\", vars = names(all_items))\nall_correlation &lt;- data.frame(\n item = seq_along(a_vars),\n Result = diag(correlations$r[a_vars, b_vars]),\n P_Valor = diag(correlations$P[a_vars, b_vars])\n)\n</code></pre>\n\n<p>What I don't like too much about this approach is that it only uses 3 of the 36 correlations that were computed by <code>rcorr</code>. In this second approach, I start by splitting the data into two tables (one for <code>a</code> and one for <code>b</code>) so as to compute only 3 correlations via <code>Map</code>. I also switched from <code>rcorr</code> to the base <code>cor.test</code> which has (IMO) a more intuitive behavior: when given two vectors as input, it computes one correlation, not four.</p>\n\n<pre><code>a &lt;- all_items %&gt;% select(ends_with(\"a\"))\nb &lt;- all_items %&gt;% select(ends_with(\"b\"))\ncor_test &lt;- Map(cor.test, a, b)\nall_correlation &lt;- data.frame(\n item = seq_along(a),\n Result = sapply(cor_test, `[[`, \"estimate\"),\n P_Valor = sapply(cor_test, `[[`, \"p.value\")\n)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T18:12:13.573", "Id": "402488", "Score": "0", "body": "Wow!! Both are amazing solutions! Thanks much for replying my question. I will go with the first one because my knowledge of \"sapply\" still very incipient and (because of that) it is not easy to understand what sapply does. Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T17:34:10.973", "Id": "208394", "ParentId": "208382", "Score": "1" } } ]
{ "AcceptedAnswerId": "208394", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T14:52:31.807", "Id": "208382", "Score": "2", "Tags": [ "statistics", "r", "data-visualization" ], "Title": "dplyr -- tidyverse, pipes, correlation, same variable across time \"a\" \"b\"" }
208382
<p>I've been wanting to experiment with a bit of error handling and robustness to make my code more user friendly. I was inspired by <a href="https://ux.stackexchange.com/a/122059">this answer on UX</a> to try and add a progress bar to a button - but was unable to find any simple text based progress bars out there, so I decided to write my own in that style. It boils down to a single class (which references a helper method in an addin: <code>printf</code>):</p> <h3>Class: <code>AsciiProgressBar</code></h3> <pre><code>Option Explicit Private Type tProgressBar percentComplete As Double size As Long base As String bar As String character As String whitespace As String mask As String End Type Private Enum progressError percentOutOfBoundsError = vbObjectError + 513 'to get into custom error raising territory barSizeOutOfRangeError singleCharacterRequiredError baseIsNotAStringError maskMissingPositionalArgumentError End Enum Private Const DEFAULT_CHAR As String = "|" Private Const DEFAULT_SIZE As Long = 10 Private Const DEFAULT_BASE As String = vbNullString Private Const DEFAULT_WHITESPACE As String = " " Private Const DEFAULT_MASK As String = "{0}{1}{2}%" Private this As tProgressBar Public Function Update(ByVal fractionComplete As Double) As String 'check if valid input (0-100%) If fractionComplete &lt; 0# Or fractionComplete &gt; 1# Then raiseError percentOutOfBoundsError 'set number of characters in progress bar this.percentComplete = fractionComplete Dim numberOfChars As Long numberOfChars = Round(this.size * this.percentComplete, 0) this.bar = String(numberOfChars, this.character) &amp; String(this.size - numberOfChars, this.whitespace) Update = repr End Function Public Property Get repr() As String repr = printf(this.mask, this.base, this.bar, Round(this.percentComplete * 100, 0)) End Property Private Sub raiseError(ByVal errNum As progressError, ParamArray args() As Variant) Select Case errNum Case percentOutOfBoundsError Err.Description = "Percent must lie between 0.0 and 1.0" Case barSizeOutOfRangeError Err.Description = printf("Bar size must be at least {0} characters", args(0)) Case singleCharacterRequiredError Err.Description = printf("Only a single character should be used as {0}, not '{1}'", args(0), args(1)) Case baseIsNotAStringError Err.Description = printf("Base must be of type string or left blank, not '{0}'", TypeName(args(0))) Case maskMissingPositionalArgumentError Err.Description = printf("formatMask must contain all three positional tokens ({0,1,2}){0}'{1}' does not", _ vbCrLf, args(0)) Case Else 'some errNum we don't know what to do with On Error Resume Next 'fake raise to grab description text Err.Raise errNum Dim errDescription As String errDescription = Err.Description On Error GoTo 0 Debug.Print printf("Warning: Unexpected error '{0}' with description '{1}'", errNum, errDescription) End Select Err.Raise errNum End Sub Public Sub Init(Optional ByVal size As Long = 0, Optional ByVal base As Variant, _ Optional ByVal character As String = vbNullString, Optional ByVal whitespace As String = vbNullString, _ Optional ByVal formatMask As String = vbNullString) 'Method to set appearence and other properties of the progress bar 'check if inputs were missing - if so leave as they were 'Base can be any string so can't be checked in this way, needs special handling size = IIf(size = 0, this.size, size) character = IIf(character = vbNullString, this.character, character) whitespace = IIf(whitespace = vbNullString, this.whitespace, whitespace) formatMask = IIf(formatMask = vbNullString, this.mask, formatMask) 'check for valid inputs Const minBarSize As Long = 2 If size &lt; minBarSize Then raiseError barSizeOutOfRangeError, minBarSize ElseIf Len(character) &lt;&gt; 1 Then raiseError singleCharacterRequiredError, "'character'", character ElseIf Len(whitespace) &lt;&gt; 1 Then raiseError singleCharacterRequiredError, "'whitespace'", whitespace ElseIf MaskIsInvalid(formatMask) Then raiseError maskMissingPositionalArgumentError, formatMask ElseIf Not IsMissing(base) Then 'base is variant so requires type checking On Error Resume Next this.base = base 'may be type error if base can't be converted; e.g an object was passed Dim errNum As Long errNum = Err.Number On Error GoTo 0 If errNum &lt;&gt; 0 Then raiseError baseIsNotAStringError, base End If End If 'If we've got here then inputs are valid, so we can commit them this.size = size this.whitespace = whitespace this.character = character this.mask = formatMask End Sub Private Function MaskIsInvalid(ByVal mask As String) As Boolean 'check whether any of the positional tokens don't appear in the mask Const matchPattern As String = "{0} {1} {2}" Dim tokens() As String tokens = Split(matchPattern) MaskIsInvalid = False Dim token As Variant For Each token In tokens MaskIsInvalid = Not CBool(InStr(mask, token)) If MaskIsInvalid Then Exit Function Next End Function Private Sub Class_Initialize() ResetDefaults Update this.percentComplete End Sub Public Sub ResetDefaults() this.character = DEFAULT_CHAR this.base = DEFAULT_BASE this.whitespace = DEFAULT_WHITESPACE this.size = DEFAULT_SIZE this.mask = DEFAULT_MASK End Sub Public Function Create(Optional ByVal size As Long = 0, Optional ByVal base As Variant, _ Optional ByVal character As String = vbNullString, Optional ByVal whitespace As String = vbNullString, _ Optional ByVal formatMask As String = vbNullString) As AsciiProgressBar Dim result As New AsciiProgressBar result.Init size, base, character, whitespace, formatMask Set Create = result End Function </code></pre> <p>Which references my addin</p> <pre><code>Public Function printf(ByVal mask As String, ParamArray tokens()) As String 'Format string with by substituting into mask - stackoverflow.com/a/17233834/6609896 Dim i As Long For i = 0 To UBound(tokens) mask = Replace$(mask, "{" &amp; i &amp; "}", tokens(i)) Next printf = mask End Function </code></pre> <p>The class has a <code>Create</code> method as it is intended to be used in an addin (and pre-declared), i.e. the header looks like this:</p> <pre><code>VERSION 1.0 CLASS BEGIN MultiUse = -1 'True END Attribute VB_Name = "AsciiProgressBar" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = True </code></pre> <h3>Feedback</h3> <p>I'd particularly like feedback on:</p> <ul> <li>Robustness of code (to user input)</li> <li>Ease of use</li> <li>Error raising</li> <li>Use of Init vs individual get/letters</li> <li>Code writing and formatting style</li> <li>Everything else :)</li> </ul> <p>Rubberduck advises against overwriting variables passed <code>ByVal</code> - e.g in the <code>Init</code> method - why? Is it safe here?</p> <h2>Examples</h2> <p>The class can be used to supply content to userform text boxes, button captions, the <code>Application.StatusBar</code>, basically anywhere that displays strings; here are a couple of examples:</p> <h3>Using a worksheet button (ActiveX)</h3> <p>Best to use a monospaced font like <em>Consolas</em></p> <pre><code>Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private stillHeld As Boolean Private Sub CommandButton1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) 'start loading progress bar Const numberOfSteps As Long = 50 Dim progress As AsciiProgressBar Set progress = AsciiProgressBar.Create(size:=20, base:="Loading: ") stillHeld = True Dim i As Long For i = 1 To numberOfSteps CommandButton1.Caption = progress.Update(i / numberOfSteps) If Not stillHeld Then Exit For DoEvents Sleep 20 Next i If i &gt; numberOfSteps Then CommandButton1.Caption = "Held on long enough" DoEvents Sleep 1000 Else CommandButton1.Caption = "Let go too early" DoEvents Sleep 1000 End If CommandButton1.Caption = "Hold down" End Sub Private Sub CommandButton1_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) stillHeld = False End Sub </code></pre> <p><a href="https://i.stack.imgur.com/Z4SG3.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z4SG3.gif" alt="Command button"></a></p> <h3>Using <code>Application.StatusBar</code></h3> <pre><code>Option Explicit Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Public Sub StatusBarProgress() Const runningTime As Single = 5000 'in milliseconds Const numberOfSteps As Long = 100 With AsciiProgressBar.Create(base:="Loading: ", formatMask:="{0}{2}%{1}|") Dim i As Long For i = 1 To numberOfSteps .Update i / numberOfSteps Application.StatusBar = .repr 'Or equivalently: 'Application.StatusBar = .Update(i / numberOfSteps) Sleep runningTime / numberOfSteps DoEvents Next i End With Application.StatusBar = False End Sub </code></pre> <p><a href="https://i.stack.imgur.com/hQbPa.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hQbPa.gif" alt="StatusBar"></a></p> <p><em>NB actual operation is much smoother, the gif is just low quality</em></p>
[]
[ { "body": "<blockquote>\n <p>Rubberduck advises against overwriting variables passed ByVal - e.g in\n the Init method - why?</p>\n</blockquote>\n\n<p>It's</p>\n\n<ul>\n<li>a) coding style; keeping the original value in the parameter is supposed to be cleaner code because you can spot all the places where the <em>exact</em> passed in value is used and know where it is not used (but instead a modified/derived/sanitized version of it) and</li>\n<li>b) assigning to a by-value parameter may be an error because the programmer intended the value to be seen by the caller, mistakenly thinking it was a <code>ByRef</code>. Your code is \"safe\" in this respect because you clearly do not assume the parameter is <code>ByRef</code>.</li>\n</ul>\n\n<p>For best maintainability you should introduce new local variables for your input parameters' sanitized values, and make sure you only use those variables in the function and not accidentally use the original parameter at one place or another.</p>\n\n<p>For my taste, a few more comments would be helpful. Those which are there are ok, though very brief. A rule of thumb: If it's not really obvious, <em>why</em> something is done in a program, explain the <em>reason</em> in a comment. Good example of a comment: <code>'fake raise to grab description text</code> explains <em>why</em> we do a raise here.</p>\n\n<p>In <code>MaskIsInvalid</code>, you don't need to use a pattern and <code>Split</code> to create the array of tokens. Just use <code>tokens = Array(\"{0}\",\"{1}\",\"{2}\")</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-04T16:56:20.380", "Id": "209006", "ParentId": "208385", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T15:51:19.763", "Id": "208385", "Score": "10", "Tags": [ "beginner", "vba", "excel", "error-handling" ], "Title": "A simple ascii progress bar" }
208385
<p>In this question I present a method to solve the Traveling Salesman Problem and/or the Single Route Optimization problem.</p> <p>I am extracting 100 lat/long points from Google Maps and placing these into a text file. The program should be able to read in the text file, calculate the haversine distance between each point, and store in an adjacency matrix. The adjacency matrix will eventually be fed to a 2-opt algorithm.</p> <p><a href="https://codereview.stackexchange.com/questions/207461/extracting-an-adjaceny-matrix-containing-haversine-distance-from-points-on-map?noredirect=1&amp;lq=1">Extracting an adjaceny matrix containing haversine distance from points on map has already been dealt with.</a> This question tackles the 2-opt algorithm.</p> <p>The 2-opt function is called from main as follows. <code>route</code> is a randomly generated list of 100 numbers, which is the path the 2-opt should follow.</p> <pre><code>def main(): best = two_opt(connect_mat, route) #connectivity/adjacency matrix </code></pre> <p>And here is the <code>2-opt</code> function and a <code>cost</code> function that it utilizes. <strong>Can they be optimized</strong> in any way?</p> <pre><code>def cost(cost_mat, route): return cost_mat[np.roll(route, 1), route].sum() # shifts route array by 1 in order to look at pairs of cities def two_opt(cost_mat, route): best = route improved = True while improved: improved = False for i in range(1, len(route) - 2): for j in range(i + 1, len(route)): if j - i == 1: continue # changes nothing, skip then new_route = route[:] # Creates a copy of route new_route[i:j] = route[j - 1:i - 1:-1] # this is the 2-optSwap since j &gt;= i we use -1 if cost(cost_mat, new_route) &lt; cost(cost_mat, best): best = new_route improved = True route = best return best </code></pre> <p>Sample Input:</p> <pre><code>35.905333, 14.471970 35.896389, 14.477780 35.901281, 14.518173 35.860491, 14.572245 35.807607, 14.535320 35.832267, 14.455894 35.882414, 14.373217 35.983794, 14.336096 35.974463, 14.351006 35.930951, 14.401137 . . . </code></pre> <p>Sample Output</p> <p><a href="https://i.stack.imgur.com/dfiyx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dfiyx.png" alt="enter image description here"></a></p> <p>I would like to be able to <strong>scale up the points being read</strong> to 5000. With the code above it would be <em>painfully</em> slow.</p> <p>Timer Test:</p> <p>Starting a timer at the beginning of the function and ending before the return statement gives an average of 1.5s per 100 points. If simple proportion can be used to test algorithm scaling performance, then:</p> <ul> <li>100 points: 1.5s</li> <li>1000 points: 15s</li> <li>5000 points: 75s</li> </ul> <p>Please correct me if my above assumption is wrong.</p> <p>I was wondering whether it could be improved in any way. More information can be added if requested.</p> <hr> <p><strong>EDIT:</strong></p> <p>I noticed that I was using an extra variable <code>best</code>. This can be removed as such:</p> <pre><code>def two_opt(connect_mat, route): improved = True while improved: improved = False for i in range(1, len(route) - 2): for j in range(i + 1, len(route)): if j - i == 1: continue # changes nothing, skip then new_route = route[:] # Creates a copy of route new_route[i:j] = route[j - 1:i - 1:-1] # this is the 2-optSwap since j &gt;= i we use -1 if cost(connect_mat, new_route) &lt; cost(connect_mat, route): route = new_route # change current route to best improved = True return route </code></pre> <p>I doubt how much (if any) this increases efficiency, however it does sacrifice readability to some extent.</p>
[]
[ { "body": "<p>You repeatedly evaluate</p>\n\n<pre><code>cost(cost_mat, best)\n</code></pre>\n\n<p>There is an opportunity to <a href=\"https://docs.python.org/3/library/functools.html#functools.lru_cache\" rel=\"nofollow noreferrer\">memoize</a> this, or at least store it in a temp var.</p>\n\n<p>You should decide if you want \"optimal\" TSP, or \"good enough\" TSP\nthat is k-competitive with an optimal solution.</p>\n\n<p>You suggest you're taking 15ms per city.\nYou didn't post profile / timing data, but\nI have to believe that much of the time is taken up by <code>roll</code> + <code>sum</code>,\nrather than by, say, creating route copies.\nCould we pre-compute distances between points, and\nthen consider just next hops within some threshold distance?\nOr order by distance, and consider only a fixed number of next hops,\nadjusted upward each time a better route is found?</p>\n\n<p>Could the <code>cost()</code> function be broken into \"near\" and \"far\" components,\nwith the advantage that \"far\" would be substantially constant?\nUsually we do <em>not</em> find a better cost.\nIf we <em>do</em> find one, we could then fall back to \"carefully\"\ncomputing the detailed \"far\" cost.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-01T06:45:43.280", "Id": "216628", "ParentId": "208387", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T16:54:51.103", "Id": "208387", "Score": "5", "Tags": [ "python", "performance", "algorithm", "python-3.x", "traveling-salesman" ], "Title": "2-opt algorithm for the Traveling Salesman and/or SRO" }
208387
<p>This is similar to the game <a href="https://en.wikipedia.org/wiki/War_(card_game)" rel="noreferrer">War</a>, but with notable differences. For this program, it is the player versus the computer (so each with half of the deck). They draw the top card of their deck and compare. Whoever has the higher value card wins both cards and put both cards into the bottom of their decks (first the card the winner chose then the card the loser chose). Ranks <em>and</em> suits do matter when comparing. Order of rank and suits from highest to lowest:</p> <ul> <li>Ranks: King, Queen, Jack, 10, 9, 8, 7, 6, 5, 4, 3, 2, Ace</li> <li>Suits: Hearts, Diamonds, Clubs, Spades</li> </ul> <p>The winner of the entire match, (or Duel as I call it in the program), is whoever ends up with the entire deck in their possession. Since the games generally get to several hundred moves, the game is automated.</p> <pre><code>/* Card game in which the two players each have half of the deck. Taking the top card of their deck, they compare the cards, seeing who has the higher ranked card (compare rank then suit). Winner takes the two cards. To win the game, the player must have the entire deck in his possession. For this game, it will be the user versus the computer. Based on the children's game, War */ #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;ctype.h&gt; #include &lt;time.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #define FALSE 0 #define TRUE 1 // Define suits, ranks, and respective names enum Suit { Spades, Clubs, Diamonds, Hearts}; enum Rank { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King}; char * SuitNames[] = {"Spades", "Clubs", "Diamonds", "Hearts"}; char * RankNames[] = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}; // struct for a card typedef struct CardStructure { enum Suit suit; enum Rank rank; } Card; // Method prototyping void playMove(Card * playerHand[], Card * compHand[]); void dealCards(Card * playerHand[], Card * compHand[], Card * deck[]); int compareCards(Card * playerCard, Card * compCard); int checkWin(Card * playerHand[], Card * compHand[]); int main() { Card * playerHand[52]; Card * compHand[52]; Card * deck[52]; char playAgain; puts("Welcome to War! You literally duel the computer by comparing\n" // Basic greeting and introduction "your top card with the computer's top card. Whoever has the highest\n" "value card takes the two cards and puts them onto the bottom of their\n" "deck. The winner of the game is determined by whoever ends with the\n" "entire deck in their possession.\n" "From highest to lowest:\n" "\tRanks: A K Q J 10 9 8 7 6 5 4 3 2\n" "\tSuits: Hearts, Diamonds, Clubs, Spades\n" "The game will start shortly.\n"); sleep(25); // Give user time to read the greeting // Main game loop do { dealCards(playerHand, compHand, deck); // Give the player and computer half the deck int moves = 1; // Keeps track of number of moves while (1) { printf("Move: %d\n", moves); playMove(playerHand, compHand); // Player and computer draw their top card and compare, finish turn int result = checkWin(playerHand, compHand); if (result == 1) { puts("The player has won the duel!"); break; } else if (result == 2) { puts("The computer has won the duel!"); break; } moves++; } printf("\n\nWould you like to play again? Enter Y for yes, anything else for no: "); // Prompt to restart game scanf(" %c", &amp;playAgain); if (toupper(playAgain) != 'Y') { for (int index = 0; index &lt; 52; index++) { free(deck[index]); // Cards were malloced in dealCards(), time to free them } break; } } while (1); return 0; } void dealCards(Card * playerHand[], Card * compHand[], Card * deck[]) { int cardsCreated = 0; int turn = 0; // Keeps track of who is supposed to get the card, player = 0, computer = 1 Card card; // Card template srand(time(NULL)); // Randomize the seed while (cardsCreated &lt; 52) { int cardFound = FALSE; card.rank = rand() % 13; card.suit = rand() % 4; for (int index = 0; index &lt; cardsCreated; index++) { Card * deckCard = deck[index]; // Take a card from the deck... if (deckCard-&gt;rank == card.rank &amp;&amp; deckCard-&gt;suit == card.suit) // ...and compare it to the newly made card { cardFound = TRUE; // Card is a duplicate, exit loop and continue break; } } if (cardFound == FALSE) { if (turn == 0) { playerHand[cardsCreated/2] = ( Card *) malloc ( sizeof(Card)); // Malloc the card and give player the card playerHand[cardsCreated/2]-&gt;suit = card.suit; playerHand[cardsCreated/2]-&gt;rank = card.rank; deck[cardsCreated] = playerHand[cardsCreated/2]; // Add card to deck for comparison purposes } else if (turn == 1) { compHand[(cardsCreated-1)/2] = ( Card *) malloc ( sizeof(Card)); // Malloc the card and give computer the card compHand[(cardsCreated-1)/2]-&gt;suit = card.suit; compHand[(cardsCreated-1)/2]-&gt;rank = card.rank; deck[cardsCreated] = compHand[(cardsCreated-1)/2]; // Add card to deck for comparison purposes } turn = (turn == 0) ? 1 : 0; // Switch turn from 0 -&gt; 1 or 1 -&gt; 0 cardsCreated++; } } for (int index = 26; index &lt; 52; index++) // Set the non-existent cards to NULL { playerHand[index] = NULL; compHand[index] = NULL; } } void playMove(Card * playerHand[], Card * compHand[]) { Card * playerCard = playerHand[0]; // Get top cards and their information Card * compCard = compHand[0]; int pSuit = playerCard-&gt;suit; int pRank = playerCard-&gt;rank; int cSuit = compCard-&gt;suit; int cRank = compCard-&gt;rank; int result = compareCards(playerCard, compCard); // If player has the better card, returns 0, otherwise returns 1 if (!result) { printf("The player won this turn.\n" "\tPlayer's card: %s of %s\n" "\tComputer's card: %s of %s\n", RankNames[pRank], SuitNames[pSuit], RankNames[cRank], SuitNames[cSuit]); for (int index = 1; index &lt; 52; index++) { playerHand[index-1] = playerHand[index]; // Shifts every card forward (subtracts one from their index) compHand[index-1] = compHand[index]; } int length = 0; for (int index = 0; index &lt; 52; index++) // Calculate how many cards in the player's hand with the top card discarded { if (playerHand[index] != NULL) length++; } playerHand[length] = playerCard; // Place discarded top card to the bottom of the deck playerHand[length+1] = compCard; // Place the won card to the bottom of the deck } else { printf("The computer won this turn.\n" "\tPlayer's card: %s of %s\n" "\tComputer's card: %s of %s\n", RankNames[pRank], SuitNames[pSuit], RankNames[cRank], SuitNames[cSuit]); for (int index = 1; index &lt; 52; index++) { playerHand[index-1] = playerHand[index]; // Shifts every card forward (subtracts one from their index) compHand[index-1] = compHand[index]; } int length = 0; for (int index = 0; index &lt; 52; index++) // Calculate how many cards in the computer's hand with the top card discarded { if (compHand[index] != NULL) length++; } compHand[length] = compCard; // Place discarded top card to the bottom of the deck compHand[length+1] = playerCard; // Place the won card to the bottom of the deck } } int compareCards(Card * playerCard, Card * compCard) { if (playerCard-&gt;rank &gt; compCard-&gt;rank) // Compares ranks return 0; else if (playerCard-&gt;rank &lt; compCard-&gt;rank) return 1; else { if (playerCard-&gt;suit &gt; compCard-&gt;suit) // If ranks match, compare suits return 0; else return 1; } } int checkWin(Card * playerHand[], Card * compHand[]) { int playerLen = 0; int compLen = 0; for (int i = 0; i &lt; 52; i++) // Number of cards is determined by the number of non-NULL cards { if (playerHand[i] != NULL) playerLen++; if (compHand[i] != NULL) compLen++; } printf("Player deck size: %d\nComputer deck size: %d\n" "----------------------------------------------\n", playerLen, compLen); // Output current size of player's and computer's deck if (playerLen == 52) // Player has entire deck, player wins return 1; if (compLen == 52) // Computer has entire deck, computer wins return 2; return -1; // No one has entire deck, continue play } </code></pre> <p>My question is that what can I do to improve the program, specifically around the areas of code logic and style (like the C equivalent of Python's PEP8)?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T03:31:33.867", "Id": "402846", "Score": "2", "body": "Maybe I am misunderstanding this game, but to me it seems like whoever is dealt the King of Hearts will always win the game, because that card can never lose. In War, even if you are dealt all the Aces, you can still lose because you can lose any card during a tie." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T12:24:24.913", "Id": "402889", "Score": "0", "body": "A little too late to change the code now since it would be drastic, but I will see that I change the code to prevent that @JS1" } ]
[ { "body": "<p>There's no major issue. Beautiful code.\n- That's a matter of taste, but you could define <code>TRUE</code> and <code>FALSE</code> in their logical terms:</p>\n\n<pre><code>#define TRUE (1==1)\n#define FALSE (!TRUE)\n</code></pre>\n\n<ul>\n<li><code>moves</code> could be an <code>unsigned</code></li>\n</ul>\n\n<hr>\n\n<h3><code>dealCards</code></h3>\n\n<pre><code>int turn = 0;\n</code></pre>\n\n<ul>\n<li><code>turn</code> should be simply renamed <code>computerTurn</code> (see below why)</li>\n<li><p>and since you defined <code>TRUE</code>/<code>FALSE</code>, use it here : <code>int computerTurn = FALSE;</code>.</p></li>\n<li><p>also, <code>if (turn == 0)</code> can be explicitly changed to <code>if (!computerTurn)</code></p></li>\n<li>and <code>else if (turn == 1)</code> to <code>else if (computerTurn)</code> or even just <code>else</code>.</li>\n<li><code>turn = (turn == 0) ? 1 : 0;</code> can be rewritten with the logical unary not: <code>computerTurn = !computerTurn;</code>.</li>\n<li>Instead of writing two times almost the same code...</li>\n</ul>\n\n<p></p>\n\n<pre><code>playerHand[cardsCreated/2] = ( Card *) malloc ( sizeof(Card)); // Malloc the card a...\nplayerHand[cardsCreated/2]-&gt;suit = card.suit;\nplayerHand[cardsCreated/2]-&gt;rank = card.rank;\n</code></pre>\n\n<p></p>\n\n<p>       ...make cards allocation and creation outside of the condition (see my example below). </p>\n\n<ul>\n<li>Also, <a href=\"https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc\">you could omit to cast the result of malloc</a> and <a href=\"https://softwareengineering.stackexchange.com/questions/201104/sizeof-style-sizeoftype-or-sizeof-variable\">use the variable name into <code>sizeof</code></a> instead of using the type.</li>\n</ul>\n\n<hr>\n\n<p>Instead of your logic, you can try this:</p>\n\n<ul>\n<li>Make an array of 52 <code>int</code> :</li>\n</ul>\n\n\n\n<pre><code>int cards[52];\nfor (unsigned int i = 0; i &lt; 52; i++) {\n cards[i] = i;\n}\n</code></pre>\n\n<ul>\n<li>Then, <a href=\"https://stackoverflow.com/questions/6127503/shuffle-array-in-c\">shuffle it</a> (maybe with the <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow noreferrer\">Fisher–Yates shuffle</a>).</li>\n<li>Now you just have to alternatively deal card from this array to player and computer (and after, as you do, set non-existent cards from both hands, to null).</li>\n</ul>\n\n\n\n<pre><code>for (unsigned int i = 0; i &lt; 52; i++) {\n Card *current = malloc(sizeof(card));\n current-&gt;suit = cards[i] % sizeof(SuitNames)/sizeof(*SuitNames);\n current-&gt;rank = cards[i] % sizeof(RankNames)/sizeof(*RankNames);\n\n if (!computerTurn) playerHand[i/2] = current;\n else computerHand[i/2] = current;\n\n computerTurn = !computerTurn;\n}\n</code></pre>\n\n<p>I see some advantages of this method:</p>\n\n<ul>\n<li>You can get rid of the variable <code>deck</code></li>\n<li>The generation and dealing in constant in time, where with your method, if you are out of luck, filling both hands can take long time.</li>\n</ul>\n\n<hr>\n\n<h2><code>playMove</code></h2>\n\n<p>I didn't understand advantage of <code>pSuit</code>, <code>pRank</code>, <code>cSuit</code> and <code>cRank</code> against their arrowed counter-part.</p>\n\n<p><code>result</code> should be renamed <code>computerWin</code> it's more explicit.</p>\n\n<p>A lot of duplicated code can be moved out of the <code>if...else</code> (before or after), but above all, a major optimization could be to keep a track of how many cards each hand have (<code>playerCount</code> and <code>compCount</code>).</p>\n\n<ul>\n<li>You don't have anymore to shift left every card in both deck</li>\n<li>You don't have to compute how many card each hand have</li>\n<li>You also have easily access to the current card (<code>playerHand[playerCount-1]</code>)</li>\n</ul>\n\n<p>In fact, maybe you can wrap the \"hand\" and the \"count\" into a struct:</p>\n\n<pre><code>typedef struct HandStructure\n{\n Card *cards[52];\n size_t count;\n} Hand;\n</code></pre>\n\n<hr>\n\n<h2><code>compareCards</code></h2>\n\n<p>You can simplify branching a lot:</p>\n\n<pre><code>int compareCards(Card * playerCard, Card * compCard)\n{\n if (playerCard-&gt;rank &lt;= compCard-&gt;rank) \n return (playerCard-&gt;rank &lt; compCard-&gt;rank) || (playerCard-&gt;suit &lt; compCard-&gt;suit)\n else return 0;\n}\n</code></pre>\n\n<hr>\n\n<h2><code>checkWin</code></h2>\n\n<p>You should return <code>0</code> instead of <code>-1</code> if no one won, it allow <code>if(checkWin(...))</code> in the <code>main</code>.</p>\n\n<p>Dealing with the <code>Hand</code> structure which I talked about, this function became also shorter and simple:</p>\n\n<pre><code>int checkWin(Hand * player, Hand * computer)\n{\n assert(player-&gt;count + computer-&gt;count == 52);\n\n if (!computer-&gt;count) // Player has entire deck, player wins\n return 1;\n if (!player-&gt;count) // Computer has entire deck, computer wins\n return 2;\n return 0; // No one has entire deck, continue play\n}\n</code></pre>\n\n<hr>\n\n<p><strong>edit</strong>: Also, you should define both <code>char*</code> at the top as <code>const</code>.</p>\n\n<h1>End words</h1>\n\n<p>Also, as you can see, I introduced <a href=\"https://ptolemy.berkeley.edu/~johnr/tutorials/assertions.html\" rel=\"nofollow noreferrer\">assertion</a> in the last code, paradoxically to the length of this post, i found code pretty well writes. It's time, I think, to adopt stronger concepts and methods. Assertions are one of those things.</p>\n\n<p>I hope not being too straight or rude, English isn't my primary language, so I miss some nuancies.</p>\n\n<hr>\n\n<h1>10 days later...</h1>\n\n<p><em>I wrote this few days ago, but didn't take time to add it before. Hope it will help.</em></p>\n\n<h2>Cards</h2>\n\n<p>Actually in your code, you compare cards with ranks, and then if equals, with suits.</p>\n\n<p>So the lowest card is the <em>Ace of Spikes</em> and the greatest the <em>King of Hearts</em>. Also, the <em>Ace of Spikes</em> is lower than the <em>Ace of Clubs</em> which is lower than all others.</p>\n\n<p>So, what's cards values?</p>\n\n<ul>\n<li><p>1: Ace of Spikes</p></li>\n<li><p>2: Ace of Clubs</p></li>\n<li><p>3: Ace of Diamonds</p>\n\n<p>...</p></li>\n<li><p>51: King of Diamonds</p></li>\n<li><p>52: King of Hearts</p></li>\n</ul>\n\n<p>So, instead of dealing with suits and ranks, you can try to deal with values directly. The question is now: \"How retrieve suits and ranks from a card's value?\"</p>\n\n<p>Pretty simple!</p>\n\n<p>(with card values going from 0 to 51)</p>\n\n<pre><code>//ensure card value &lt; (number of suits * number of ranks), then:\nSuit = card value % number of suits\nRank = card value / number of ranks\n</code></pre>\n\n<h3>Working example</h3>\n\n<p>Let's test it (pseudo-code):</p>\n\n<pre><code>array suits[4] = {\"Spike\", \"Club\", \"Diamond\", \"Heart\"}\narray ranks[13] = {\"Ace\", \"Two\", ..., \"Queen\", \"King\"}\n\nlet ace_of_spikes = 0\nlet ace_of_diamonds = 2\nlet king_of_diamonds = 50\nlet king_of_hearts = 51\n\nprint suit[ace_of_spikes % sizeof suits] -&gt; \"Spike\"\nprint suit[ace_of_diamonds % sizeof suits] -&gt; \"Diamond\"\n</code></pre>\n\n<p>We simply divided memory usage by two, using only one integer instead of two per card.</p>\n\n<p>In this same way, you also make a lot of things in your code easier (build of deck(s), comparison of card to get winner, ...).</p>\n\n<p><em>About the modulus operator, even if it <a href=\"https://embeddedgurus.com/stack-overflow/2011/02/efficient-c-tip-13-use-the-modulus-operator-with-caution/\" rel=\"nofollow noreferrer\">can be slow</a> before trying to optimize it, you should ensure it's needed with benchmarks. (other related links: <a href=\"https://stackoverflow.com/questions/27977834/why-is-modulus-operator-slow\">[1]</a>, <a href=\"https://stackoverflow.com/questions/15596318/is-it-better-to-avoid-using-the-mod-operator-when-possible\">[2]</a>, <a href=\"https://stackoverflow.com/questions/11040646/faster-modulus-in-c-c\">[3]</a>).</em></p>\n\n<h2>Deck(s)</h2>\n\n<p>Just think two second about this game (in your program and in real life).</p>\n\n<p>Each player have card from the same deck, right? The deck is just split into halves to players.</p>\n\n<p>I got the intuition that we can work with this unique deck, and using two virtually splitted up views of it as players' sub-deck. After all, in real life, if you join the cards from both players, it's always the same deck.</p>\n\n<p>Let's try to set that idea into practice!</p>\n\n<ul>\n<li>Virtually splits our deck at the middle. Let's call this position \"separator\"</li>\n<li>Each player take cards from this separator until their sides.</li>\n<li>When a player won a card, it come in his side of the separator and so became a part of his sub-deck.</li>\n<li>When a player reach the last card of his part of the deck, he continues taking the card right before the separator, i.e. his new top sub-deck. In real life, before picking this card, his part of the deck is shuffled. Let's assume that we can do the same, that will add a bit randomization.</li>\n<li>Finally, when he don't have card from his side of separator, he have lost.</li>\n</ul>\n\n<h3>Visual example</h3>\n\n<p><strong>Legend</strong>:</p>\n\n<p><code>▲ : The current card of each player</code></p>\n\n<p><code>⋆ : The card that was just won</code> </p>\n\n<p><strong>Turn 1</strong>:</p>\n\n<pre><code>#1 : 1 7 2 3 8|4 5 9 6 0 : #2\n ▲ ▲ \n</code></pre>\n\n<p><em>#1</em> got a <kbd>8</kbd>, <em>#2</em> got a <kbd>4</kbd> ➔ <em>#1</em> won the <kbd>4</kbd></p>\n\n<p>We move pointers to the next cards, and the separator to the right to give one card from <em>#2</em> to <em>#1</em> and.</p>\n\n<p><em>Note: In fact, we swap the right-most card (the nearest of the separator) of his sub-deck with the card he have just won. Since here it's the same card, it's a no-op.</em></p>\n\n<pre><code>#1 : 1 7 2 3 8 4|5 9 6 0 : #2\n ▲ ⋆ ▲\n</code></pre>\n\n<p>Since <kbd>4</kbd> is already in the deck <em>#1</em>, we have noting to do.</p>\n\n<hr>\n\n<p><strong>Turn 2</strong>:</p>\n\n<pre><code>#1 : 1 7 2 3 8 4|5 9 6 0 : #2\n ▲ ▲\n</code></pre>\n\n<p><em>#1</em> got a <kbd>3</kbd>, <em>#2</em> got a <kbd>5</kbd> ➔ <em>#2</em> won the <kbd>3</kbd></p>\n\n<p>Let's move pointers to the next cards, and the separator to the left to give one card from #1 to #2 and.</p>\n\n<pre><code>#1 : 1 7 2 3 8|4 5 9 6 0 : #2\n ▲ ⋆ ▲\n</code></pre>\n\n<p>Here, <kbd>3</kbd> isn't is already in the deck <em>#2</em>, we have to swap it with the card nearest of the separator, on his side.</p>\n\n<p><em>Note: We could, instead, have operate a circular left shift of card <code>3 8 4</code> to get <code>8 4 3</code> and so, keep a consistent order, but since we'll shuffling cards of a player when he have no more not already played card (i.e when we'll have to move the pointer to the card before the separator), it's not necessary.</em></p>\n\n<pre><code>#1 : 1 7 2 4 8|3 5 9 6 0 : #2\n ▲ ⋆ ▲\n</code></pre>\n\n<hr>\n\n<p><strong>Turn 3</strong>:</p>\n\n<pre><code>#1 : 1 7 2 4 8|3 5 9 6 0 : #2\n ▲ ▲\n</code></pre>\n\n<p><em>#1</em> got a <kbd>2</kbd>, <em>#2</em> got a <kbd>9</kbd> ➔ <em>#2</em> won the <kbd>2</kbd></p>\n\n<p>We move pointers to the next cards, and the separator to the left to give one card from <em>#1</em> to <em>#2</em> and.</p>\n\n<pre><code>#1 : 1 7 2 4|8 3 5 9 6 0 : #2\n ▲ ⋆ ▲\n</code></pre>\n\n<p>Since, <kbd>2</kbd> isn't is in the deck <em>#2</em>, we swap it with the card at the right of the separator.</p>\n\n<pre><code>#1 : 1 7 8 4|2 3 5 9 6 0 : #2\n ▲ ⋆ ▲\n</code></pre>\n\n<hr>\n\n<p>Let's go faster with this logic, showing just results</p>\n\n<p><strong>Turn 4</strong> :</p>\n\n<pre><code>#1 : 1 7 8 4 2|3 5 9 6 0 : #2\n ▲ ▲\n</code></pre>\n\n<p></p>\n\n<pre><code>#1 : 1 7 8 4 2 3|5 9 6 0 : #2\n ▲ ⋆ ▲\n</code></pre>\n\n<p></p>\n\n<pre><code>#1 : 1 7 8 4 2 6|5 9 3 0 : #2\n ▲ ⋆ ▲\n</code></pre>\n\n<hr>\n\n<p><strong>Turn 5</strong>:</p>\n\n<pre><code>#1 : 1 7 8 4 2 6|5 9 3 0 : #2\n ▲ ▲\n</code></pre>\n\n<p>Let's start with same as usual</p>\n\n<pre><code>#1 : 1 7 8 4 2 6 5|9 3 0 : #2\n ▲ ⋆ ▲\n ? ?\n</code></pre>\n\n<p></p>\n\n<pre><code>#1 : 1 7 8 4 2 6 0|9 3 5 : #2\n ▲ ⋆ ▲\n ⤷ ⤶\n</code></pre>\n\n<p>But here, both players have no more card to draw, let's shuffle their part of the deck, and move pointers before the separator.</p>\n\n<pre><code>#1 : 4 2 0 6 1 7 8|3 5 9 : #2\n ▲ ▲ \n</code></pre>\n\n<p>And this, until a player doesn't have card anymore.</p>\n\n<hr>\n\n<h1>Final End words</h1>\n\n<p>As stated in comments, the player who have to top deck card is his sub-deck automatically win. So here, you also have two options:\n- Provide option to just print the winner, without computation of turns\n- Rethink some functions (<code>playMove</code> and <code>checkWin</code> in your case) to handle \"draws\" (same ranks).</p>\n\n<p>If you want, I can try to come back in few days with a example of implementation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T00:42:38.883", "Id": "402518", "Score": "0", "body": "A very interesting answer indeed, I'll be sure to take a lot closer look at what you said. About `pSuit`, `pRank` and the computer equivalent, I thought it'd be shorter and the line of code where they are used wouldn't be extremely long. But for the card creation logic, I assume you meant `...else compHand[(i-1)/2] = current;`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T00:45:51.830", "Id": "402519", "Score": "0", "body": "Also, I don't understand how I am not supposed to shift my deck left every time if the size of both hands are still limited to 52" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T00:55:09.827", "Id": "402520", "Score": "0", "body": "No, `compHand[i/2]`, with `-1` you are out of bounds. And you don't have to shift if you access the current card at `compHand[compCount-1]` instead of `compHand[0]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T01:03:37.587", "Id": "402521", "Score": "0", "body": "I added an edit: \"Also, you should define both char* at the top as const.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T01:07:12.320", "Id": "402522", "Score": "0", "body": "One last question, sure I can get the current card with `compCount-1` but wouldn't this slowly shift out of bounds as the winner retrieves the two cards? If you can, a code example would help me understand this a lot better" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T12:07:23.577", "Id": "402560", "Score": "2", "body": "One shouldn't define TRUE or FALSE at all, but use `stdbool.h` with `true` and `false`. Furthermore, the result of `1==1` is guaranteed to be `int` with value `1`, so it is cleaner to write `#define TRUE 1` if stuck with C90." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T05:50:30.173", "Id": "402850", "Score": "0", "body": "Review `return (playerCard->rank < compCard->rank) || (playerCard->suit < compCard->suit)` Do you want `... || (playerCard->suit <= compCard->suit)`? `<` --> `<=` to match OP's compare?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T06:56:01.507", "Id": "402851", "Score": "0", "body": "@chux Nice try but no. Because in a deck of cards, if ranks of two cards are equals, suits can't be equal. And where the OP deal about equality of suits!? But your feeling was good, there was a typo in my post, but not here. Please, continue to hunt my replies, it forces me to improve myself." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T21:15:18.990", "Id": "208405", "ParentId": "208389", "Score": "3" } }, { "body": "<blockquote>\n <p>My question is that what can I do to improve the program, specifically around the areas of code logic and style ... ?</p>\n</blockquote>\n\n<p><strong>Use <code>stdbool.h</code></strong></p>\n\n<p>Since C99 <a href=\"https://codereview.stackexchange.com/questions/208389/duel-type-card-game-in-c/208585#comment402560_208405\">@Lundin</a>, C has the <code>_Bool</code> type which has 2 values: 0 and 1. Use that rather than </p>\n\n<pre><code>// #define FALSE 0\n// #define TRUE 1\n// int cardFound = FALSE;\n// cardFound = TRUE; \n// if (cardFound == FALSE)\n</code></pre>\n\n<p>use</p>\n\n<pre><code>#include &lt;stdbool.h&gt;\nbool cardFound = false;\ncardFound = true; \nif (!cardFound)\n</code></pre>\n\n<p><strong>Flush output</strong></p>\n\n<p><code>stdout</code> is commonly line buffered, but may be unbuffered or fully buffered. To insure out is seen before requesting input, (especially when that output does not end in a <code>'\\n'</code>) us <code>fflush()</code>.</p>\n\n<pre><code> printf(\"\\n\\nWould you like to play again? Enter Y for yes, anything else for no: \");\n fflush(stdout);\n scanf(\" %c\", &amp;playAgain);\n</code></pre>\n\n<p><strong>Format to presentation width</strong></p>\n\n<p>Code should be auto-formated so re-formating to a different preferred max width should be easy. Reviewing code that rolls <em>far</em> off the right of the screen reduced code review efficiency. OP's width is 143+. Suggest something in the 75-100 range.</p>\n\n<pre><code>char * RankNames[] = {\"Ace\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\"};\n\nprintf(\"\\n\\nWould you like to play again? Enter Y for yes, anything else for no: \"); // Prompt to restart game\nscanf(\" %c\", &amp;playAgain);\n\n \"----------------------------------------------\\n\", playerLen, compLen); // Output current size of player's and computer's deck \n</code></pre>\n\n<p>vs.</p>\n\n<pre><code>char * RankNames[] = {\"Ace\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \n \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\"};\n\n// Prompt to restart game\nprintf(\"\\n\\n\" // \n \"Would you like to play again? Enter Y for yes, anything else for no: \");\nscanf(\" %c\", &amp;playAgain);\n\n // Output current size of player's and computer's deck\n \"----------------------------------------------\\n\", playerLen, compLen);\n</code></pre>\n\n<p><strong>Allocate to the object and drop cast</strong></p>\n\n<p>Consider the below. The first obliges a check: Was the correct type used? The 2nd does not need that check. The unnecessary cast is <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">WET</a>. The 2nd is DRY, easier to code right, review and maintain.</p>\n\n<pre><code>// playerHand[cardsCreated/2] = ( Card *) malloc ( sizeof(Card));\nplayerHand[cardsCreated/2] = malloc (sizeof *playerHand);\n</code></pre>\n\n<p>Robust code would also detect allocation failures.</p>\n\n<pre><code>if (playerHand[cardsCreated/2] == NULL) {\n // call out of memory handler\n}\n</code></pre>\n\n<p><strong>Reduce <code>rand()</code> calls</strong></p>\n\n<p>2 calls to <code>rand()</code> is twice the time when one would do.</p>\n\n<pre><code>// card.rank = rand() % 13;\n// card.suit = rand() % 4;\nint r = rand();\ncard.rank = (r/4) % 13;\ncard.suit = r%4;\n</code></pre>\n\n<p><strong>Remove <code>else</code></strong></p>\n\n<p>Minor style issue: <code>compareCards()</code> looks like it is missing a <code>return</code> at the function end. (it is not though)</p>\n\n<p>Alternate layout:</p>\n\n<pre><code>int compareCards(Card * playerCard, Card * compCard) {\n if (playerCard-&gt;rank &gt; compCard-&gt;rank) { // Compares ranks\n return 0;\n }\n if (playerCard-&gt;rank &lt; compCard-&gt;rank) {\n return 1;\n } \n if (playerCard-&gt;suit &gt; compCard-&gt;suit) { // As ranks match, compare suits\n return 0;\n }\n return 1;\n}\n</code></pre>\n\n<p>Other simplification possible.</p>\n\n<p><strong>Employ <code>const</code></strong></p>\n\n<p>When a function parameter points to unchanged data, make it <code>const</code>. This allows for wider code use, some optimizations and conveys better codes intent.</p>\n\n<pre><code>// int checkWin(Card * playerHand[], Card * compHand[]);\nint checkWin(const Card * playerHand[], const Card * compHand[]);\n</code></pre>\n\n<p><strong>Unused non-standard include</strong></p>\n\n<p>The only reason for the non-standard C <code>&lt;unistd.h&gt;</code> seems to be <code>sleep()</code>. Consider removal for greater portability.</p>\n\n<p><strong>Technical undefined behavior (UB)</strong></p>\n\n<p><code>toupper(ch)</code> is valid for <code>int</code> values in the <code>unsigned char</code>range and <code>EOF</code>. Else UB when <code>ch &lt; 0</code>.</p>\n\n<pre><code> scanf(\" %c\", &amp;playAgain);\n // if (toupper(playAgain) != 'Y')\n if (toupper((unsigned char) playAgain) != 'Y')\n</code></pre>\n\n<p><strong>Design - missing <code>dealCards()</code> companion</strong></p>\n\n<p>Rather than code in <code>main()</code> the free-ing <code>for (int index = 0; index &lt; 52; index++) free(deck[index]);</code>, Consider a companion function to <em>un-deal</em>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T05:28:52.107", "Id": "208585", "ParentId": "208389", "Score": "1" } }, { "body": "<p>You've already heard about efficient shuffling in <a href=\"https://codereview.stackexchange.com/a/208405/151754\">Calak's excellent answer</a>. I have just one thing to add to it: don't <code>malloc</code> each card independently. <code>Card</code> is two <code>enum</code>s. Even if each of these are represented as an <code>int</code>, then <code>Card</code> is an 8-byte data structure (though it is possible your compiler uses only one byte for each <code>enum</code> value):</p>\n\n<pre><code>typedef struct CardStructure\n{\n enum Suit suit;\n enum Rank rank;\n} Card;\n</code></pre>\n\n<p>A pointer to such a structure is also 8 bytes (assuming you're on a 64-bit OS). So, the array of 52 pointers to <code>Card</code> takes up just as much space as an array of 52 <code>Card</code> objects. Calling <code>malloc</code> is relatively expensive, you need an extra indirection (pointer dereference) for each card read, and you end up with data (potentially) all over the heap, which is bad for cache usage. So even if <code>Card</code> were larger (32 bytes, 64 bytes) it would be beneficial to store them directly inside an array, and copy them around. An additional advantage is that you don't need to remember to <code>free</code> the cards.</p>\n\n<p>I recommend <code>malloc</code> only for cases where you cannot store data on the stack: in a function that creates an object and returns it, or for a large array.</p>\n\n<hr>\n\n<p>Now, considering that there are only 52 unique cards, we know it should be possible to store one card in one byte. One approach could use a bit field like this:</p>\n\n<pre><code>typedef struct CardStructure {\n unsigned int suit : 2; // allows any integer in [0,3]\n unsigned int rank : 4; // allows any integer in [0,15]\n} Card;\n</code></pre>\n\n<p>It should be possible to still assign the <code>enum Suit</code> and <code>enum Rank</code> values to these bit fields. But I must say that this is an optimization that maybe goes a little too far, the original <code>Card</code> is easier and cleaner, and therefore the better choice.</p>\n\n<hr>\n\n<p>Oh, I just realized that you are not actually using the <code>enum</code> constants anywhere in your code. You are just using their numeric values. You are better off not defining those enums in that case, and just use a <code>char</code> to store each value.</p>\n\n<hr>\n\n<p>Bug: Your documentation says that the cards are ordered: \"A K Q J 10 9 8 7 6 5 4 3 2\", but your code logic says that A is the lowest card.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T07:52:35.930", "Id": "208590", "ParentId": "208389", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T17:04:13.227", "Id": "208389", "Score": "5", "Tags": [ "beginner", "c", "playing-cards" ], "Title": "Duel-type card game in C" }
208389
<p>This is an implementation of mine to an exercise found in the book <a href="http://www.informit.com/store/core-java-se-9-for-the-impatient-9780134694726" rel="nofollow noreferrer">Core Java SE 9 for the Impatient</a>. Goal is basically to print a monthly calendar by accepting month and year information from the user. </p> <p>Here is a sample run in my local:</p> <pre><code>java App 1984 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 </code></pre> <p>Here is my implementation, which I am happy to hear your criticisms on: </p> <pre><code>import java.time.LocalDate; import java.time.Month; import java.time.DayOfWeek; import java.lang.StringBuilder; import java.util.stream.IntStream; class App { public static final String SEPERATOR = "\t"; public static void main(String[] args) { // First day of the month that we will be printing - this is our reference date final LocalDate referenceDate = LocalDate.of(Integer.valueOf(args[0]), Integer.valueOf(args[1]), 1); // Temporary instance we will be using, initially set to our reference date // We will be assigning next dates to this reference LocalDate nextDate = referenceDate; // Temporary instance we will be using to print a row // Row will start with this value int weekStart = nextDate.getDayOfMonth(); // offset might be gt 0 for the first printed week (imagine 1st of a month is wednesday..) int offset = nextDate.getDayOfWeek().getValue() - 1; // We need to do this as long as the date we are processing is in the same month with our reference date while (nextDate.getMonth() == referenceDate.getMonth()) { // Print a week if we hit a SUNDAY or if the next date would be in a different month.. if (nextDate.getDayOfWeek() == DayOfWeek.SUNDAY || nextDate.plusDays(1).getMonth() != referenceDate.getMonth()) { printWeek(offset, weekStart, nextDate.getDayOfMonth()); offset = 0; // offset will always be zero after printing the first week in a month weekStart = nextDate.getDayOfMonth() + 1; } // keep incrementing nextDate = nextDate.plusDays(1); } } static void printWeek(int offset, int weekStart, int weekEnd) { StringBuilder sb = new StringBuilder(); IntStream.range(0, offset).forEach(i -&gt; sb.append(SEPERATOR)); IntStream.rangeClosed(weekStart, weekEnd).forEach(i -&gt; sb.append(i).append(SEPERATOR)); System.out.println(sb); } } </code></pre> <p>Here is another approach I have taken, the output is not exactly the same but can be made same very easily:</p> <pre><code>import java.time.DayOfWeek; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.List; class App { static final List&lt;int[]&gt; weeks = new ArrayList&lt;&gt;(); public static void main(String[] args) { final LocalDate firstDay = LocalDate.of(Integer.valueOf(args[0]), Integer.valueOf(args[1]), 1); int[] weekDays = new int[7]; LocalDate aDate = firstDay; while (aDate.getMonth() == firstDay.getMonth()) { weekDays[aDate.getDayOfWeek().getValue() - 1] = aDate.getDayOfMonth(); if (aDate.getDayOfWeek() == DayOfWeek.SUNDAY || aDate.plusDays(1).getMonth() != firstDay.getMonth()) { weeks.add(weekDays); weekDays = new int[7]; } aDate = aDate.plusDays(1); } weeks.forEach(week -&gt; System.out.println(Arrays.toString(week))); } } </code></pre> <p>where the output is:</p> <pre><code>[0, 0, 0, 0, 0, 0, 1] [2, 3, 4, 5, 6, 7, 8] [9, 10, 11, 12, 13, 14, 15] [16, 17, 18, 19, 20, 21, 22] [23, 24, 25, 26, 27, 28, 29] [30, 0, 0, 0, 0, 0, 0] </code></pre> <p>I came up with a 3rd option, leaving here just for future reference:</p> <pre><code>import java.time.LocalDate; import java.util.stream.IntStream; import java.lang.StringBuilder; class App { public static void main(String[] args) { LocalDate ld = LocalDate.of(Integer.valueOf(args[0]), Integer.valueOf(args[1]), 1); int offset = ld.getDayOfWeek().getValue() - 1; int monthLength = ld.lengthOfMonth(); StringBuilder sb = new StringBuilder(); IntStream.rangeClosed(-offset, monthLength).forEach(i -&gt; { if (i &gt; 0) sb.append(i); sb.append("\t"); if ((i + offset) % 7 == 0) sb.append("\n"); }); System.out.println(sb); } } </code></pre>
[]
[ { "body": "<p>First thing I'd like to say is get into the habit of putting your code into functions outside of Main. Use Main to run the functions. In this case, I would recommend passing in PrintStream and LocalDate objects.</p>\n\n<p>You seem to be doing a lot of work with the LocalDate fields. Basically all the printout is is a list of numbers in a tabular format. All you need is the weekday of the first day of the month to get the offset. Use a loop to get the numbers and when <code>(weekday - 1 + loop counter) % 7</code> equals 0 print a line break.</p>\n\n<p>Using <code>printf</code> to format the numbers with leading 0's, makes the print out much easier to read.</p>\n\n<p>Typically when printing out the month one would expect to see the name of the month and the year, as well as the days of the week. The days of the week can be pulled from the DayOfWeek enum.</p>\n\n<p>Here's one way the function could look like:</p>\n\n<pre><code>private static void printMonth(PrintStream out, LocalDate date){\n date = date.minusDays(date.getDayOfMonth()-1);\n var month = date.getMonth();\n int days = month.length(date.isLeapYear());\n int firstWeekDay = date.getDayOfWeek().getValue()-1;\n out.printf(\"%1$s, %2$d\\n\",month.toString(),date.getYear()); \n for(var weekday :DayOfWeek.values()){\n out.printf(\"%s\\t\",weekday.name().substring(0, 2));\n }\n out.println();\n for(int i = 0; i &lt; firstWeekDay;++i){\n out.print(\" \\t\");\n }\n for(int day = 1; day &lt;= days;++day){\n out.printf(\"%02d\\t\",day );\n if((day + firstWeekDay)% 7 ==0){\n out.println();\n }\n }\n out.println();\n}\n</code></pre>\n\n<p>The print out looks like this:</p>\n\n<pre><code>NOVEMBER, 2018\nMO TU WE TH FR SA SU \n 01 02 03 04 \n05 06 07 08 09 10 11 \n12 13 14 15 16 17 18 \n19 20 21 22 23 24 25 \n26 27 28 29 30\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T13:49:24.190", "Id": "402571", "Score": "0", "body": "I think your suggestion is pretty much same with my 3rd implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T13:53:17.767", "Id": "402572", "Score": "0", "body": "Except it doesn't store all the days, just prints them out, and includes more formatting" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T13:56:48.427", "Id": "402575", "Score": "0", "body": "Well yes but you are changing the requirements. No one asked for MO, TU etc and in which calendar did you see 01 instead of 1? And I do not store all days either. (Store where anyway?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T14:01:21.703", "Id": "402580", "Score": "0", "body": "I covered the extra information in my answer as an improvement. Adding the days to a StringBuilder is storing them." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T04:54:11.317", "Id": "208427", "ParentId": "208391", "Score": "3" } }, { "body": "<p>Here is a different possible approach:</p>\n\n<pre><code>import java.time.*;\n\nclass Cal {\n public static void main(String[] args) {\n final LocalDate firstDate = LocalDate.of(Integer.valueOf(args[1]), Integer.valueOf(args[0]), 1);\n\n int firstDayOffset = firstDate.getDayOfWeek().getValue() - 1;\n for (int i = 0; i &lt; firstDayOffset; i++) {\n System.out.print(\" \");\n }\n\n LocalDate aDate = firstDate.plusDays(0);\n while (aDate.getMonth() == firstDate.getMonth()) {\n System.out.printf(\"%2d \",aDate.getDayOfMonth());\n if ((aDate.getDayOfMonth() + firstDayOffset) % 7 == 0) {\n System.out.println(\"\\n\");\n } \n aDate = aDate.plusDays(1);\n }\n\n System.out.println(\"\\n\");\n }\n}\n</code></pre>\n\n<p>A sample run: <code>javac Cal.java; java Cal 12 2018;</code></p>\n\n<pre><code> 1 2 \n\n 3 4 5 6 7 8 9 \n\n10 11 12 13 14 15 16 \n\n17 18 19 20 21 22 23 \n\n24 25 26 27 28 29 30 \n\n31 \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-23T23:14:07.230", "Id": "210247", "ParentId": "208391", "Score": "-2" } }, { "body": "<p>I made yet another implementation, this one lets you define which weekday you want to consider as week start:</p>\n\n<pre><code>class Calendar {\n public List&lt;CalendarWeek&gt; getWeeks(YearMonth yearMonth, DayOfWeek weekStart) {\n ArrayList&lt;CalendarWeek&gt; calenderweeks = new ArrayList&lt;&gt;();\n\n int monthStart = LocalDate.of(yearMonth.getYear(), yearMonth.getMonth(), 1).getDayOfWeek().getValue();\n int calendarWeekStart = weekStart.getValue();\n\n int offset = monthStart - calendarWeekStart;\n if (offset &lt; 0) {\n offset = offset + 7;\n }\n\n int start = 1;\n int end = 8 - (start + offset);\n\n int monthLength = yearMonth.lengthOfMonth();\n do {\n calenderweeks.add(new CalendarWeek(offset, start, end));\n start = end + 1;\n end = monthLength &lt; start + 6 ? monthLength : start + 6;\n offset = 0;\n } while (start &lt; monthLength);\n\n return calenderweeks;\n }\n}\n\nclass CalendarWeek {\n int offset;\n int start;\n int end;\n\n public CalendarWeek(int offset, int start, int end) {\n this.offset = offset;\n this.start = start;\n this.end = end;\n }\n\n @Override\n public String toString() {\n StringBuilder stringBuilder = new StringBuilder();\n\n for (int i = 0; i &lt; offset; i++) {\n stringBuilder.append(\" \");\n }\n\n for (int i = start; i &lt; end + 1; i++) {\n stringBuilder.append(String.format(\" %2d\", i));\n }\n\n return stringBuilder.toString();\n }\n}\n</code></pre>\n\n<p>Sample run:</p>\n\n<pre><code>class App {\n public static void main(String[] args) {\n List&lt;CalendarWeek&gt; weeks;\n\n weeks = new Calendar().getWeeks(YearMonth.of(2019, 2), DayOfWeek.SATURDAY);\n weeks.forEach(System.out::println);\n\n System.out.println(\"\");\n\n weeks = new Calendar().getWeeks(YearMonth.of(2019, 2), DayOfWeek.SUNDAY);\n weeks.forEach(System.out::println);\n\n System.out.println(\"\");\n\n weeks = new Calendar().getWeeks(YearMonth.of(2019, 2), DayOfWeek.MONDAY);\n weeks.forEach(System.out::println);\n }\n}\n</code></pre>\n\n<p>Sample output</p>\n\n<pre><code> 1\n 2 3 4 5 6 7 8\n 9 10 11 12 13 14 15\n 16 17 18 19 20 21 22\n 23 24 25 26 27 28\n\n 1 2\n 3 4 5 6 7 8 9\n 10 11 12 13 14 15 16\n 17 18 19 20 21 22 23\n 24 25 26 27 28\n\n 1 2 3\n 4 5 6 7 8 9 10\n 11 12 13 14 15 16 17\n 18 19 20 21 22 23 24\n 25 26 27 28\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-16T01:12:07.947", "Id": "213552", "ParentId": "208391", "Score": "-1" } } ]
{ "AcceptedAnswerId": "210247", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T17:21:29.213", "Id": "208391", "Score": "2", "Tags": [ "java", "datetime", "formatting" ], "Title": "Printing a monthly calendar on console" }
208391
<p>My goal is to design an Auction that will take in data like this: </p> <pre><code>Bidder A - ( StartingBid , AutoIncrement , MaxBid) Bidder B - ( StartingBid , AutoIncrement , MaxBid) </code></pre> <p>This Auction will generate a winner based on the bidders entered. The Auction algorithm will automatically increment a bidder's starting bid given he has a relative losing position to other Bidders. However, the algorithm should never increment a user's bid automatically if the max bid would be surpassed!</p> <p>Here is my design. These are all the classes I created. Please let me know If there is a better object oriented design. </p> <pre><code> /** * Auction will have a list of bidders where order matters in tie disputes * * @author agoel * */ public class Auction { private boolean isLive = true; private List&lt;Bidder&gt; bidders; private String itemName; private Bidder winner; public Auction(List&lt;Bidder&gt; bidders, String itemName) { this.bidders = bidders; } public boolean isLive() { return isLive; } public void setLive(boolean isLive) { this.isLive = isLive; } public List&lt;Bidder&gt; getBidders() { return bidders; } public void setBidders(List&lt;Bidder&gt; bidders) { this.bidders = bidders; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public Bidder findWinner() { Collections.sort(bidders); Map.Entry&lt;Bidder, Double&gt; winningEntry = processBids(); Bidder winningBidder = null; winningBidder = winningEntry.getKey(); winningBidder.setCurrentAmount(winningEntry.getValue()); return winningBidder; } /** * Main Processing which increments bids based on if they have capacity and * if the currentAmount &lt; max bid If there is a current tie where both bids * are equal to the max then we break that by checking a list that gets * populated when a tie occurs * * A bid is marked as a loser if it no longer has capacity to increase its * bid and its less than the current max bid * * @param validBids * @param max * @return */ private Map.Entry&lt;Bidder, Double&gt; processBids() { HashMap&lt;Bidder, Double&gt; maxBids = new HashMap&lt;Bidder, Double&gt;(); for (Bidder participant : bidders) { double maxMinusInitial = participant.getMaxBid() - participant.getCurrentAmount(); if (maxMinusInitial % participant.getAutoIncrement() == 0) { maxBids.put(participant, participant.getMaxBid()); } else { maxBids.put(participant, participant.getMaxBid() - (maxMinusInitial % participant.getAutoIncrement())); } } // Create a list from elements of HashMap List&lt;Map.Entry&lt;Bidder, Double&gt;&gt; list = new LinkedList&lt;Map.Entry&lt;Bidder, Double&gt;&gt;(maxBids.entrySet()); // Sort the list Collections.sort(list, new Comparator&lt;Map.Entry&lt;Bidder, Double&gt;&gt;() { public int compare(Map.Entry&lt;Bidder, Double&gt; o1, Map.Entry&lt;Bidder, Double&gt; o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); Map.Entry&lt;Bidder, Double&gt; winningEntry = list.get(list.size() - 1); Bidder winningBidder = winningEntry.getKey(); Map.Entry&lt;Bidder, Double&gt; secondPlaceEntry = list.get(list.size() - 2); // Resolve Ties boolean ties = resolveTies(winningEntry, secondPlaceEntry); if (ties) { return determineByPositionInAuction(winningEntry, secondPlaceEntry); } double secondPlaceMaxBet = secondPlaceEntry.getValue(); double maxMinusInitial = secondPlaceMaxBet - winningEntry.getKey().getCurrentAmount(); if (maxMinusInitial % winningEntry.getKey().getAutoIncrement() == 0) { winningEntry.setValue(secondPlaceMaxBet + winningBidder.getAutoIncrement()); } else { double remainder = secondPlaceMaxBet % winningBidder.getAutoIncrement(); secondPlaceMaxBet = secondPlaceMaxBet + remainder; winningEntry.setValue(secondPlaceMaxBet); } return winningEntry; } private Map.Entry&lt;Bidder, Double&gt; determineByPositionInAuction(Entry&lt;Bidder, Double&gt; winningEntry, Entry&lt;Bidder, Double&gt; secondPlaceEntry) { // TODO Auto-generated method stub Bidder secondPlace = secondPlaceEntry.getKey(); Bidder firstPlace = winningEntry.getKey(); if (firstPlace.getPositionInAuction() &gt; secondPlace.getPositionInAuction()) { return secondPlaceEntry; } else { return winningEntry; } } private boolean resolveTies(Entry&lt;Bidder, Double&gt; winningEntry, Entry&lt;Bidder, Double&gt; secondPlaceEntry) { // TODO Auto-generated method st if (winningEntry.getValue().equals(secondPlaceEntry.getValue())) { return true; } return false; } public Bidder getWinner() { return winner; } public void setWinner(Bidder winner) { this.winner = winner; } } public final class AuctionResult { private Bidder winningBidder; public AuctionResult(Bidder winningBidder) { this.winningBidder = winningBidder; } /** * Display the Auction Result */ public void displayResults() { System.out.println("The auction c was won by " + winningBidder.getName() + " for the amount of $ " + winningBidder.getCurrentAmount()); } public double getWinningAmount() { return winningBidder.getCurrentAmount(); } } /** * A bidder will have a one to one association with a bid object. * * @author agoel * */ public class Bidder implements Comparable&lt;Bidder&gt; { private double maxBid; private boolean loser; private String name; private double autoIncrement; private double currentAmount; private int positionInAuction; public Bidder(double currentAmount, double maxBid, String name, double autoIncrement , int positionInAuction) { this.maxBid = maxBid; this.currentAmount = currentAmount; this.setAutoIncrement(autoIncrement); this.name = name; this.positionInAuction = positionInAuction; } public double getMaxBid() { return maxBid; } public void setMaxBid(double maxBid) { this.maxBid = maxBid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getAutoIncrement() { return autoIncrement; } public void setAutoIncrement(double autoIncrement) { this.autoIncrement = autoIncrement; } public int getPositionInAuction() { return positionInAuction; } public void setPositionInAuction(int positionInAuction) { this.positionInAuction = positionInAuction; } public double getCurrentAmount() { return currentAmount; } public void setCurrentAmount(double currentAmount) { this.currentAmount = currentAmount; } @Override public int compareTo(Bidder otherBid) { if (this.currentAmount &lt; otherBid.getCurrentAmount()) { return -1; } else if (this.currentAmount == otherBid.getCurrentAmount()) { return 0; } else { return 1; } } @Override public int hashCode() { return Double.valueOf(currentAmount).hashCode(); } @Override public boolean equals(Object otherBid) { if (otherBid == this) { return true; } if (!(otherBid instanceof Bidder)) { return false; } Bidder bid = (Bidder) otherBid; if (this.currentAmount == bid.getCurrentAmount()) { return true; } return false; } public boolean isLoser() { return loser; } public void setLoser(boolean loser) { this.loser = loser; } } import java.util.List; import com.goel.model.Auction; import com.goel.model.Bidder; public class AuctionBuilder { /** * Realistically an Auction should be built by pieces * @param bidders * @param itemName * @return */ public Auction buildAuction(List&lt;Bidder&gt; bidders, String itemName) { return new Auction(bidders, itemName); } } import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import com.goel.model.Auction; import com.goel.model.AuctionResult; import com.goel.model.Bidder; /** * This class will handle the heavylighting and be a facade to the backend. It * will operate on an Auction object * result in an immutable class on completion of the Auction * * @author agoel * */ public class AuctionProcessor { private Auction auction; public Auction getAuction() { return auction; } public void setAuction(Auction auction) { this.auction = auction; } public AuctionProcessor(Auction auction) { this.auction = auction; } public AuctionResult execute() { Bidder winningBidder = auction.findWinner(); return new AuctionResult(winningBidder); } } import java.util.ArrayList; import java.util.List; import com.goel.model.Auction; import com.goel.model.AuctionResult; import com.goel.model.Bidder; public class AuctionCoordinator { public static void main(String[] args) { AuctionBuilder auctionBuilder = new AuctionBuilder(); Bidder linda = new Bidder(170.0d, 240.0d, "Linda", 3.0d, 1); Bidder dave = new Bidder(160.0d, 243.0d, "Dave", 7.0d, 2); Bidder eric = new Bidder(190.0d, 240.0d, "Matt", 4.0d, 3); List&lt;Bidder&gt; bidders = new ArrayList&lt;Bidder&gt;(); bidders.add(linda); bidders.add(dave); bidders.add(eric); Auction auction = auctionBuilder.buildAuction(bidders, "Record Player"); AuctionProcessor processor = new AuctionProcessor(auction); AuctionResult result = processor.execute(); result.displayResults(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T22:41:36.333", "Id": "402512", "Score": "0", "body": "Is this just a design or does it actually do something? Did you test whether it works?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T22:45:05.200", "Id": "402513", "Score": "1", "body": "Yeah if you look at AuctionCoordinator class it builds an Auction and passes it to the AuctionProcessor which executes and returns an AuctionResult" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T19:26:22.783", "Id": "208400", "Score": "3", "Tags": [ "java", "object-oriented" ], "Title": "Object Oriented design for a live auction taking in bidders" }
208400
<p>I'm using bootstrap buttons, and in this case I have 5 different buttons with 5 different classes. When one of the buttons is clicked on, I want it to be the only one filled in, and the others to only be the outline. Here is how I currently do it:</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>$(".canvas_btn").on("click",function(){ for(var i = 0; i &lt; $(".canvas_btn").length; i++){ document.getElementById($(".canvas_btn")[i].id).className = document.getElementById($(".canvas_btn")[i].id).className.replace("btn-outline-","btn-"); document.getElementById($(".canvas_btn")[i].id).className = document.getElementById($(".canvas_btn")[i].id).className.replace("btn-","btn-outline-"); } document.getElementById(this.id).className = document.getElementById(this.id).className.replace("btn-outline","btn"); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;button class="btn btn-outline-info canvas_btn" align="left" id="new_text_btn"&gt;Text&lt;/button&gt; &lt;button class="btn btn-outline-secondary canvas_btn" align="left" id="new_audio_btn"&gt;Audio&lt;/button&gt; &lt;button class="btn btn-outline-success canvas_btn" align="left" id="new_image_btn"&gt;Image&lt;/button&gt; &lt;button class="btn btn-outline-danger canvas_btn" align="left" id="new_video_btn"&gt;Video&lt;/button&gt; &lt;button class="btn btn-outline-warning canvas_btn" align="left" id="new_input_btn"&gt;Input&lt;/button&gt;</code></pre> </div> </div> </p> <p>It feels a bit odd the way I've done it - is there a more elegant way to do it? A way to use jQuery to make it tidier would be great!</p> <p>I'm also not sure how I'm causing the error in the console - I think it's to do with the bootstrap script I call in, so don't know what I can do about that.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T23:20:07.093", "Id": "402515", "Score": "2", "body": "Bootstrap has [radio buttons](https://getbootstrap.com/docs/4.1/components/buttons/#checkbox-and-radio-buttons) that do what you're wanting." } ]
[ { "body": "<p>Here's how I refactored your code: </p>\n\n<pre><code>$(document).ready(function () {\n\n $(\".canvas_btn\").on(\"click\", function () {\n\n var idOfClickedElem = $(this).attr('id');\n $.each($('.canvas_btn'), function () {\n if (idOfClickedElem === $(this).attr('id')) {\n $(this).attr('class', getFilledClassName($(this).attr('class')))\n }\n else {\n $(this).attr('class', getOutlineClassName($(this).attr('class')))\n }\n });\n\n });\n\n function getOutlineClassName(currentClasses) {\n return currentClasses.replace(\"btn-outline-\", \"btn-\").replace(\"btn-\", \"btn-outline-\")\n }\n\n function getFilledClassName(currentClasses) {\n return currentClasses.replace(\"btn-outline\", \"btn\")\n }\n\n\n});\n</code></pre>\n\n<p>Instead of mixing jQuery and regular JavaScript selectors, I just used jQuery. I'm not a huge fan of the contents of <code>getOutlineClassName(currentClasses)</code> and <code>getFilledClassName(currentClasses)</code>, but it's certainly less code than the way I probably would have written it if I had done so from scratch -- which would be to make a <code>switch</code> on the element's id and return the correct classes as a string accordingly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T20:10:09.580", "Id": "208645", "ParentId": "208403", "Score": "3" } }, { "body": "<p>As was already mentioned, the code mixes a lot of jQuery methods with plain vanilla DOM access JS methods. If you are going to use jQuery then why not use other jQuery methods? I was initially thinking <a href=\"https://api.jquery.com/toggleClass\" rel=\"nofollow noreferrer\"><code>.toggleClass()</code></a> would work to simplify the logic on adding/removing class names, but because they are each somewhat unique that doesn't appear to work.</p>\n\n<p>It is wise to store DOM lookups in a variable and then reference the variable instead of repeatedly querying the DOM. For instance, <code>$('.canvas_btn')</code> can be stored once the DOM is ready (using <a href=\"https://api.jquery.com/jQuery/#jQuery3\" rel=\"nofollow noreferrer\"><code>$(function() {...}</code></a> (formerly <a href=\"https://api.jquery.com/ready\" rel=\"nofollow noreferrer\"><code>.ready()</code></a>):</p>\n\n<pre><code>$(function() { //DOM ready callback\n var canvasBtns = $('.canvas_btn');\n</code></pre>\n\n<p>Then use that variable instead of <code>$('.canvas_btn')</code>:</p>\n\n<pre><code>canvasBtns.click(function() { //click handler\n canvasBtns.each(function() { //iterate over canvas buttons\n</code></pre>\n\n<p>And as that last code snippet alludes to, use <a href=\"https://api.jquery.com/each\" rel=\"nofollow noreferrer\"><code>.each()</code></a> (similar to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/foreach\" rel=\"nofollow noreferrer\"><code>Array.prototype.forEach()</code></a> but for jQuery collections) to iterate over the buttons.</p>\n\n<p>As far as updating the class name for each button, what you really want to do is remove <code>-outline</code> if the id matches the button that was clicked, or add it if it doesn't already have that. So in the rewritten code below, the id of the button that was clicked is stored in a variable, and then that is passed to the <code>.each</code> handler, which uses a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind#Partially_applied_functions\" rel=\"nofollow noreferrer\">partially applied function</a> with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind#Partially_applied_functions\" rel=\"nofollow noreferrer\"><code>Function.bind()</code></a>.</p>\n\n<pre><code>canvasBtns.click(function() {\n var clickedId = $(this).attr('id');\n canvasBtns.each(toggleOutlineClass.bind(null, clickedId));\n});\n</code></pre>\n\n<p>Then that function <code>toggleOutlineClass</code> will accept first <code>clickedId</code>, followed by the other arguments passed by <a href=\"https://api.jquery.com/each\" rel=\"nofollow noreferrer\"><code>.each()</code></a>: </p>\n\n<blockquote>\n<pre><code>Integer index, Element element\n</code></pre>\n</blockquote>\n\n<p>Then that function can either remove the <code>-outline</code> string if it is the item clicked (based on whether <code>clickedId</code> matches <code>$(btn).attr('id')</code>) or add that string if the class name doesn't already have it.</p>\n\n<pre><code>function toggleOutlineClass(clickedId, index, btn) {\n var className = $(btn).attr('class');\n if (clickedId === $(btn).attr('id')) {\n $(btn).attr('class', className.replace('btn-outline-', 'btn-'));\n } else if (className.indexOf('btn-outline-') &lt; 0) {\n $(btn).attr('class', className.replace('btn-', 'btn-outline-'));\n }\n}\n</code></pre>\n\n<p>A lot of the tips above are based on information in <a href=\"https://ilikekillnerds.com/2015/02/stop-writing-slow-javascript/\" rel=\"nofollow noreferrer\">this article</a>. I suggest reading that for more tips.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(function() { //DOM ready callback\n var canvasBtns = $('.canvas_btn');\n canvasBtns.click(function() {\n var clickedId = $(this).attr('id');\n canvasBtns.each(toggleOutlineClass.bind(null, clickedId));\n });\n\n function toggleOutlineClass(clickedId, index, btn) {\n var className = $(btn).attr('class');\n if (clickedId === $(btn).attr('id')) {\n $(btn).attr('class', className.replace('btn-outline-', 'btn-'));\n } else if (className.indexOf('btn-outline-') &lt; 0) {\n $(btn).attr('class', className.replace('btn-', 'btn-outline-'));\n }\n }\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;link href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" rel=\"stylesheet\" /&gt;\n&lt;script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\"&gt;&lt;/script&gt;\n&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;button class=\"btn btn-outline-info canvas_btn\" align=\"left\" id=\"new_text_btn\"&gt;Text&lt;/button&gt;\n&lt;button class=\"btn btn-outline-secondary canvas_btn\" align=\"left\" id=\"new_audio_btn\"&gt;Audio&lt;/button&gt;\n&lt;button class=\"btn btn-outline-success canvas_btn\" align=\"left\" id=\"new_image_btn\"&gt;Image&lt;/button&gt;\n&lt;button class=\"btn btn-outline-danger canvas_btn\" align=\"left\" id=\"new_video_btn\"&gt;Video&lt;/button&gt;\n&lt;button class=\"btn btn-outline-warning canvas_btn\" align=\"left\" id=\"new_input_btn\"&gt;Input&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-29T17:22:19.913", "Id": "208705", "ParentId": "208403", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T20:49:42.517", "Id": "208403", "Score": "2", "Tags": [ "javascript", "jquery", "html", "dom", "twitter-bootstrap" ], "Title": "Replace string of class of button by class so that only one button is filled in using bootstrap buttons" }
208403
<p>As part of my journey in learning the Rust programming language, I decided to make a miniature cat clone (catty) in it. The following is my code, which depends on <a href="https://clap.rs/" rel="nofollow noreferrer">clap</a> for argument parsing (see below). It currently only supports concatenating 1 file with possibly numbered lines (<code>-n/--number</code>). I tried to be as close as possible to the actual <code>cat</code> program for this:</p> <pre><code>#[macro_use] extern crate clap; use std::{io, error, env, fs::read_to_string, path::PathBuf, process}; fn main() { process::exit( if let Err(err) = cli(env::args().collect::&lt;Vec&lt;_&gt;&gt;()) { // CLI parsing errors if let Some(clap_err) = err.downcast_ref::&lt;clap::Error&gt;() { eprint!("{}", clap_err); } else { eprintln!("{}", err); } 1 } else { 0 } ); } fn cli(cli_args: Vec&lt;String&gt;) -&gt; Result&lt;(), Box&lt;error::Error&gt;&gt; { let matches = clap::App::new("catty") .version(crate_version!()) .about("A minimal clone of the linux utility cat.") .arg(clap::Arg::with_name("FILE") .help("The file to concatenate to standard output") .required(true)) .arg(clap::Arg::with_name("number") .short("n") .long("number") .help("Numbers all output lines")) .get_matches_from_safe(cli_args)?; let file_contents = get_file_contents(matches.value_of("FILE").unwrap())?; let file_contents: Vec&lt;&amp;str&gt; = file_contents.split("\n").collect(); let number_lines = matches.is_present("number"); for (i, line) in file_contents.iter().enumerate() { let formatted_line = if number_lines { format!("{:&gt;6} {}", i + 1, line) } else { line.to_string() }; if i == file_contents.len() - 1 &amp;&amp; line.len() &gt; 0 { print!("{}", formatted_line); } else if !(i == file_contents.len() - 1 &amp;&amp; line.len() == 0) { println!("{}", formatted_line); } } Ok(()) } fn get_file_contents(passed_argument: &amp;str) -&gt; Result&lt;String, Box&lt;error::Error&gt;&gt; { let mut resolved_path = PathBuf::from(passed_argument); if !resolved_path.exists() || !resolved_path.is_file() { resolved_path = PathBuf::from(env::current_dir()?); resolved_path.push(passed_argument); if !resolved_path.exists() || !resolved_path.is_file() { return Err(io::Error::new(io::ErrorKind::NotFound, "The passed file is either not a file or does not exist!").into()); } } Ok(read_to_string(resolved_path)?) } </code></pre> <p>My <code>Cargo.toml</code> is as follows:</p> <pre><code>[package] name = "catty" version = "0.1.0" authors = ["My Name &lt;my@email.com&gt;"] [dependencies] [dependencies.clap] version = "2.32" default-features = false features = ["suggestions"] </code></pre> <p>Here is what I want to know from this code review:</p> <ol> <li>Is my code idiomatic rust (i.e good error handling, not overly verbose, etc)?</li> <li>Is my code performant or can it be improved in some way?</li> </ol>
[]
[ { "body": "<p>4: <code>use std::{env, error, fs::read_to_string, io, path::PathBuf, process};</code></p>\n\n<p>Just a personal taste, but I would do</p>\n\n<pre><code>use std::{env, error, io, process};\nuse std::fs::read_to_string;\nuse std::path::PathBuf;\n</code></pre>\n\n<p>Yes, nested includes are nice and easy, but hard to extend. It's up to you.</p>\n\n<hr>\n\n<p>35: <code>let file_contents: Vec&lt;&amp;str&gt; = file_contents.split('\\n').collect();</code></p>\n\n<p>I would suggest using <a href=\"https://doc.rust-lang.org/std/primitive.str.html#method.lines\" rel=\"nofollow noreferrer\"><code>lines</code></a> instead.</p>\n\n<p>Also, you can omit <code>&amp;str</code> or change the line completly.</p>\n\n<p>Either </p>\n\n<pre><code>let file_contents: Vec&lt;_&gt; = file_contents.lines().collect();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>let file_contents = file_contents.lines().collect::&lt;Vec&lt;_&gt;&gt;();\n</code></pre>\n\n<hr>\n\n<p>46/48: <code>line.len() &gt; 0</code> / <code>line.len() == 0</code></p>\n\n<p>Replace that by <code>!line.is_empty()</code> and <code>line.is_empty()</code>.</p>\n\n<hr>\n\n<p>60: <code>resolved_path = PathBuf::from(env::current_dir()?);</code></p>\n\n<p>Remove <code>PathBuf::from</code> completly, because <a href=\"https://doc.rust-lang.org/std/env/fn.current_dir.html\" rel=\"nofollow noreferrer\"><code>current_dir</code></a> is already a <code>PathBuf</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T20:31:20.537", "Id": "402633", "Score": "0", "body": "Also, is there an equivalent of `enumerate` for an iterator (so I can avoid collecting into a vector)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T07:03:44.273", "Id": "402683", "Score": "1", "body": "Yes, you can call `enumerate` on every iterator. The thing is, that you don't know the length of your iterator, which is the reason why I didn't mentioned it. If you are willing to use `println!` every iteration, you can simplify your code/loop a lot." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T17:00:40.993", "Id": "208458", "ParentId": "208408", "Score": "2" } } ]
{ "AcceptedAnswerId": "208458", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T23:19:33.773", "Id": "208408", "Score": "2", "Tags": [ "console", "rust" ], "Title": "Catty: A mini cat clone in Rust" }
208408
<p>I wanted to discuss Dijkstra's implementation that I generally find on Internet, and then compare it with my own implementation. </p> <p>On <a href="https://www.baeldung.com/java-dijkstra" rel="nofollow noreferrer">Baeldung</a> and on <a href="http://www.vogella.com/tutorials/JavaAlgorithmsDijkstra/article.html" rel="nofollow noreferrer">Vogella</a> (Thanks to both and many others, that I haven't referred here, for providing the program). What these programs basically do is first find the node with the minimal distance and then calculate the minimum distance! In this approach, we are looping more and also increasing unnecessary complexities...</p> <p>I have written my Dijkstra implementation, and basically that's a BFS with a little bit of modification to find the minimum distance! I have given my program below and the crux to find the minimum distance is <code>if (!distances.containsKey(thisCity)) {</code> and the else part of it along with <code>Map&lt;City, Integer&gt; distances = new HashMap&lt;&gt;();</code>. My program gives the expected output without any problem. To me it looks easier implementation and also easier to understand. </p> <p>I understand the same program can be written in thousand different ways but I just wanted to get it reviewed and wants opinion of fellow programmers... Thanks for your time and help</p> <pre><code>public int findMinDistance(City src, City dest) { Set&lt;City&gt; visited = new HashSet&lt;&gt;(); Queue&lt;City&gt; queue = new LinkedList&lt;&gt;(); Map&lt;City, Integer&gt; distances = new HashMap&lt;&gt;(); distances.put(src, Integer.valueOf(0)); visited.add(src); queue.add(src); City currentCity; while (queue.size() != 0) { currentCity = queue.poll(); Set&lt;City&gt; cities = currentCity.getCityDistancesMap().keySet(); for (City thisCity : cities) { int thisDistance = distances.get(currentCity).intValue() + currentCity.getCityDistance(thisCity); if (!distances.containsKey(thisCity)) { distances.put(thisCity, thisDistance); } else { int oldDistance = distances.get(thisCity).intValue(); if (oldDistance &gt; thisDistance) { distances.remove(thisCity); distances.put(thisCity, thisDistance); } } if (!visited.contains(thisCity)) { visited.add(thisCity); queue.add(thisCity); } } } return distances.get(dest); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T00:08:33.280", "Id": "402517", "Score": "0", "body": "I haven't fully verified, but I'm pretty sure that the code you present here does not return the correct result for the case where a shorter path has more hops than a longer path. Consider a graph where the start has a neighbor N with distance 1, and another neighbor K with distance 2. They both connect to another node, let's call it F (K does this via an additional hop), but the way through K is shorter overall... I think your code doesn't correctly update the distances of any nodes after F if you traverse F before it's distance is corrected downwards after traversing K." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T01:23:02.290", "Id": "402523", "Score": "1", "body": "Thanks for your feedback @Vogel612. I have tested the fact that you have mentioned, if the path has got more hops but shorter distance, and that does work perfectly fine with my program. Reason is that if condition, where it checks if the new distance is shorter then grab that. You can run the program and you will be able to verify the fact... Thanks for your time..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T02:53:57.173", "Id": "402524", "Score": "0", "body": "I had actually tested it for the graph mentioned in this link. https://www.baeldung.com/java-dijkstra In this graph, A to E is just 2 hops via C but the distance is 25. However A to E (same nodes) is 3 hops via B, D but the distance is 24. So my program will return 24. I understand if it was plain BFS, it would have returned the first case with 2 hops but I have considered distance values via if-else and with the help of the map" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T23:41:17.540", "Id": "208409", "Score": "1", "Tags": [ "java", "algorithm" ], "Title": "Dijkstra Implementation: Comparing my program with widely available Internet Java program" }
208409
<p>Beginner programmer here. What can I improve in my code? Are there things I'm doing wrong or are there easier ways of doing what I did?</p> <pre><code>def reduce(n): n = abs(n) ctr = 0 factors_list = [] for i in range(2,n+1): if ctr &gt;= 1: break if n % i == 0: factors_list.append(i) factors_list.append(int(n/i)) ctr += 1 return factors_list def isPrime(n): return 1 in reduce(n) def primeFactorization(n): if isPrime(n): return reduce(n) factors = reduce(n) primeFactors = [] while True: for e in factors: if isPrime(e): primeFactors.append(e) factors.remove(e) else: factors.extend(reduce(e)) factors.remove(e) if len(factors) == 0: break return sorted(primeFactors) </code></pre>
[]
[ { "body": "<p><strong>Documentation and tests</strong></p>\n\n<p>Before improving your code, is it important to write tests for it to make you you don't break anything.</p>\n\n<p>As you do it, you might want that you need to be a bit clearer about the behavior of your function. Let's see what your functions return with a simple piece of code:</p>\n\n<pre><code>def print_results():\n print(\"i, primeFactorization(i), reduce(i), isPrime(i)\")\n for i in range(15):\n print(i, primeFactorization(i), reduce(i), isPrime(i))\n</code></pre>\n\n<p>Most results seem ok but why do we sometimes have \"1\" in the return value for <code>primeFactorisation</code>. In theory, we should have only prime numbers in it.</p>\n\n<p>We could:</p>\n\n<ul>\n<li><p>write doc to specify what the functions does (return <strong>prime</strong> factorisation)</p></li>\n<li><p>write tests for the actual expected behavior</p></li>\n<li><p>fix the code</p></li>\n</ul>\n\n<p>Here are various snippets I've written to test the code. In a more serious project, you could use a testing framework.</p>\n\n<pre><code>def test_is_prime():\n primes = [2, 3, 5, 7, 11, 13]\n not_primes = [0, 1, 4, 6, 8, 9, 10, 12, 14, 15, 100, 100000]\n for p in primes:\n assert isPrime(p), p\n for np in not_primes:\n assert not isPrime(np), np\n\ndef test_prime_factorization():\n prime_factorisations = {\n 2: [2],\n 3: [3],\n 4: [2, 2],\n 5: [5],\n 6: [2, 3],\n 7: [7],\n 8: [2, 2, 2],\n 9: [3, 3],\n 10: [2, 5],\n 11: [11],\n 12: [2, 2, 3],\n 13: [13],\n 14: [2, 7],\n }\n for n, factors in prime_factorisations.items():\n ret = primeFactorization(n)\n assert ret == factors, str(n) + \": \" + str(ret) + \"!=\" + str(factors)\n\ndef test_prime_factorization_randomised():\n import random\n n = random.randint(2, 10000)\n ret = primeFactorization(n)\n m = 1\n assert sorted(ret) == ret, \"return is not sorted for n:\" + str(n)\n for p in ret:\n assert isPrime(p), \"factor \" + str(p) + \" is not prime for n:\" + str(n)\n m *= p\n assert m == n, \"product of factors does not lead to original value:\" + str(n) + \", \" + str(m)\n\nif __name__ == '__main__':\n print_results()\n test_is_prime()\n test_prime_factorization()\n for i in range(300):\n test_prime_factorization_randomised()\n</code></pre>\n\n<p>Now, it feels fuch safer to improve the code.</p>\n\n<p>Also, you could use this to perform benchmarks: compute the operations many times and/or on huge numbers to measure the time it takes.</p>\n\n<p><strong>Style</strong></p>\n\n<p>Python has a style guide called <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>. I highly recommend reading it (many times) and trying to apply it as much as possible.</p>\n\n<p>Among other things, the functions names should be in <code>snake_case</code>.</p>\n\n<p><strong>Algorithm</strong></p>\n\n<p>Splitting a problem into smaller problems and writing functions for these is usually a good idea.</p>\n\n<p>Unfortunately, I am not fully convinced that the reduce functions really helps you here.</p>\n\n<p>Let's see how things can be improved anyway.</p>\n\n<p><strong>Small simplifications/optimisations</strong></p>\n\n<p>We could use the <code>divmod</code> builtin to get both the quotient and the remainder of the division.</p>\n\n<p>The <code>ctr</code> variable seems useless. It is used to <code>break</code> after we've incremented it. We could just <code>break</code> directly.</p>\n\n<p>At this stage, we have:</p>\n\n<pre><code>def reduce(n):\n n = abs(n)\n factors_list = []\n for i in range(2,n+1):\n p, q = divmod(n, i)\n if q == 0:\n factors_list.append(i)\n factors_list.append(p)\n break\n return factors_list\n</code></pre>\n\n<p>Now it is clear that we either add <code>i</code> and <code>p</code> to the list only once or we add nothing as all. We could make this clearer:</p>\n\n<pre><code>def reduce(n):\n n = abs(n)\n for i in range(2,n+1):\n p, q = divmod(n, i)\n if q == 0:\n return [i, p]\n return []\n</code></pre>\n\n<p>Now, it is clear that the function:</p>\n\n<ul>\n<li>returns <code>[]</code> in the cases 0 and 1</li>\n<li>return <code>[n, 1]</code> when n is prime</li>\n<li>return <code>[d, n/d]</code> where d is the smallest (prime) divisisors otherwise.</li>\n</ul>\n\n<p>Also, <code>reduce</code> is called more than needed: everytime we do</p>\n\n<pre><code>if isPrime(n):\n ret = reduce(n)\n</code></pre>\n\n<p>on a prime number, we actually perform reduce twice which is very expensice, in particular for primes as we iterate up to n.</p>\n\n<p>Thus, we could get an optimisation boost by writing:</p>\n\n<pre><code>def primeFactorization(n):\n \"\"\"Return the prime factorisation of n in sorted order.\"\"\"\n factors = reduce(n)\n if 1 in factors:\n return [n]\n primeFactors = []\n while True:\n for e in factors:\n new_factors = reduce(e)\n if 1 in new_factors:\n primeFactors.append(e)\n factors.remove(e)\n else:\n factors.extend(new_factors)\n factors.remove(e)\n if len(factors) == 0:\n break\n ret = sorted(primeFactors)\n return ret\n</code></pre>\n\n<p>Another key hindsight is prime factorisation is that the smallest divisors of <code>n</code> is at most <code>sqrt(n)</code> which limits the range you have to look in.</p>\n\n<p>In your case, we could use this in reduce, change slightly how reduce behaves and write:</p>\n\n<pre><code>def reduce(n):\n \"\"\"Return [a, b] where a is the smallest divisor of n and n = a * b.\"\"\"\n n = abs(n)\n for i in range(2, int(math.sqrt(n)) + 1):\n p, q = divmod(n, i)\n if q == 0:\n return [i, p]\n return [n, 1]\n\n\ndef isPrime(n):\n \"\"\"Return True if n is a prime number, False otherwise.\"\"\"\n return n &gt; 1 and reduce(n) == [n, 1]\n\n\ndef primeFactorization(n):\n \"\"\"Return the prime factorisation of n in sorted order.\"\"\"\n factors = reduce(n)\n if factors == [n, 1]: # prime\n return [n] \n primeFactors = []\n while True:\n for e in factors:\n new_factors = reduce(e)\n if new_factors == [e, 1]: # prime\n primeFactors.append(e)\n else:\n factors.extend(new_factors)\n factors.remove(e)\n if len(factors) == 0:\n break\n ret = sorted(primeFactors)\n return ret\n</code></pre>\n\n<p>which is <strong>much</strong> faster.</p>\n\n<p>Then, you could get rid of:</p>\n\n<pre><code> if len(factors) == 0:\n break\n</code></pre>\n\n<p>by looping with <code>while factors</code>.</p>\n\n<p>Then using, <code>list.pop()</code>, you could get rid of <code>remove</code> (which takes a linear time):</p>\n\n<pre><code>def primeFactorization(n):\n \"\"\"Return the prime factorisation of n in sorted order.\"\"\"\n factors = reduce(n)\n if factors == [n, 1]: # prime\n return [n]\n primeFactors = []\n while factors:\n e = factors.pop()\n new_factors = reduce(e)\n if new_factors == [e, 1]: # prime\n primeFactors.append(e)\n else:\n factors.extend(new_factors)\n ret = sorted(primeFactors)\n return ret\n</code></pre>\n\n<p>Then it appears that the initial check is not really required as the logic is already performed inside the loop:</p>\n\n<pre><code>def primeFactorization(n):\n \"\"\"Return the prime factorisation of n in sorted order.\"\"\"\n primeFactors = []\n factors = [n]\n while factors:\n e = factors.pop()\n new_factors = reduce(e)\n if new_factors == [e, 1]: # prime\n primeFactors.append(e)\n else:\n factors.extend(new_factors)\n ret = sorted(primeFactors)\n return ret\n</code></pre>\n\n<p>We can actually get rid of the sorting by popping the first element of the list, thus generating the factors in order:</p>\n\n<pre><code>def primeFactorization(n):\n \"\"\"Return the prime factorisation of n in sorted order.\"\"\"\n primeFactors = []\n factors = [n]\n while factors:\n e = factors.pop(0)\n new_factors = reduce(e)\n if new_factors == [e, 1]: # prime\n primeFactors.append(e)\n else:\n factors.extend(new_factors)\n return primeFactors\n</code></pre>\n\n<p>Now, instead of a reduce function, we could write a somehow equivalent but easier to use <code>get_smallest_div</code> function. Taking this chance to rename all functions, the whole code becomes:</p>\n\n<pre><code>import math\n\ndef get_smallest_div(n):\n \"\"\"Return the smallest divisor of n.\"\"\"\n n = abs(n)\n for i in range(2, int(math.sqrt(n)) + 1):\n p, q = divmod(n, i)\n if q == 0:\n return i\n return n\n\n\ndef is_prime(n):\n \"\"\"Return True if n is a prime number, False otherwise.\"\"\"\n return n &gt; 1 and get_smallest_div(n) == n\n\ndef get_prime_factors(n):\n \"\"\"Return the prime factorisation of n in sorted order.\"\"\"\n prime_factors = []\n factors = [n]\n while factors:\n n = factors.pop(0)\n div = get_smallest_div(n)\n if div == n: # prime\n prime_factors.append(n)\n else:\n factors.extend([div, n//div])\n return prime_factors\n\ndef print_results():\n print(\"i, get_prime_factors(i), get_smallest_div(i), is_prime(i)\")\n for i in range(15):\n print(i, get_prime_factors(i), get_smallest_div(i), is_prime(i))\n\ndef test_is_prime():\n primes = [2, 3, 5, 7, 11, 13]\n not_primes = [0, 1, 4, 6, 8, 9, 10, 12, 14, 15, 100, 100000]\n for p in primes:\n assert is_prime(p), p\n for np in not_primes:\n assert not is_prime(np), np\n\ndef test_prime_factorization():\n prime_factorisations = {\n 2: [2],\n 3: [3],\n 4: [2, 2],\n 5: [5],\n 6: [2, 3],\n 7: [7],\n 8: [2, 2, 2],\n 9: [3, 3],\n 10: [2, 5],\n 11: [11],\n 12: [2, 2, 3],\n 13: [13],\n 14: [2, 7],\n }\n for n, factors in prime_factorisations.items():\n ret = get_prime_factors(n)\n assert ret == factors, str(n) + \": \" + str(ret) + \"!=\" + str(factors)\n\ndef test_prime_factorization_randomised():\n import random\n n = random.randint(2, 10000)\n ret = get_prime_factors(n)\n m = 1\n assert sorted(ret) == ret, \"return is not sorted for n:\" + str(n)\n for p in ret:\n assert is_prime(p), \"factor \" + str(p) + \" is not prime for n:\" + str(n)\n m *= p\n assert m == n, \"product of factors does not lead to original value:\" + str(n) + \", \" + str(m)\n\nif __name__ == '__main__':\n start = time.perf_counter()\n import time\n print_results()\n test_is_prime()\n test_prime_factorization()\n for i in range(300):\n test_prime_factorization_randomised()\n print(get_prime_factors(9000000))\n print(get_prime_factors(9000000 * 701 * 701))\n print(time.perf_counter() - start)\n</code></pre>\n\n<p><strong>My solution for this</strong></p>\n\n<p>If I was to write this from scratch, here is how I'd do it:</p>\n\n<pre><code>def is_prime(n):\n \"\"\"Return True if n is a prime number, False otherwise.\"\"\"\n if n &lt; 2:\n return False\n return all(n % i for i in range(2, int(math.sqrt(n)) + 1))\n\ndef get_prime_factors(n):\n \"\"\"Return the prime factorisation of n in sorted order.\"\"\"\n prime_factors = []\n d = 2\n while d * d &lt;= n:\n while n % d == 0:\n n //= d\n prime_factors.append(d)\n d += 1\n if n &gt; 1: # to avoid 1 as a factor\n assert d &lt;= n\n prime_factors.append(n)\n return prime_factors\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T15:47:52.583", "Id": "402591", "Score": "2", "body": "In one of the intermediate steps you do `for e in factors` and then later do `factors.remove(e)`. Removing elements from a list while iterating over it produces interesting results, you should probably iterate over a copy of the list." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T16:10:48.533", "Id": "402599", "Score": "1", "body": "@Graipher this is part of the original code but this is definitly worth mentionning. It is probably worth an answer on its own." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T10:13:41.210", "Id": "208435", "ParentId": "208410", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T00:23:21.750", "Id": "208410", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "primes" ], "Title": "Prime factorization in Python" }
208410
<p>I'm trying to implement logistic regression and I believe my batch gradient descent is correct or at least it works well enough to give me decent accuracy for the dataset I'm using. When I use stochastic gradient descent I'm getting really poor accuracy so I'm not sure if it's my learning rate, epochs or just my code is incorrect. Also I'm wondering how would I add regularization to both of these? Do I add a variable lambda and multiply it by the learning rate or is the more to it?</p> <p>BGD:</p> <pre><code>def batch_gradient(df, weights, bias, lr, epochs): X = df.values y = X[:,:1] X = X[:,1:] length = X.shape[0] for i in range(epochs): output = (sigmoid((np.dot(weights, X.T)+bias))) weights_tmp = (1/length) * (np.dot(X.T, (output - y.T).T)) bias_tmp = (1/length) * (np.sum(output - y.T)) weights -= (lr * (weights_tmp.T)) bias -= (lr * bias_tmp) return weights, bias </code></pre> <p>SGD:</p> <pre><code>def stochastic_gradient(df, weights, bias, lr, epochs): x_matrix = df.values for i in range(epochs): np.random.shuffle(x_matrix) x_instance = x_matrix[np.random.choice(x_matrix.shape[0], 1, replace=True)] y = x_instance[:,:1] output = sigmoid(np.dot(weights, x_instance[:,1:].T) + bias) weights_tmp = lr * np.dot(x_instance[:,1:].T, ((output - y))) weights = (weights - weights_tmp.T) bias -= lr * (output - y) return weights, bias </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T00:53:21.133", "Id": "208412", "Score": "1", "Tags": [ "python", "numpy", "pandas" ], "Title": "Batch gradient descent and stochastic gradient descent" }
208412
<p>I have been working on <a href="https://www.hackerrank.com/challenges/counter-game/problem" rel="nofollow noreferrer">this hackerrank problem</a>:</p> <blockquote> <p>Louise and Richard have developed a numbers game. They pick a number (1 ≤ <em>n</em> &lt; 2<sup>64</sup>) and check to see if it is a power of 2. If it is, they divide it by 2. If not, they reduce it by the next lower number which is a power of 2. Whoever reduces the number to 1 wins the game. Louise always starts.</p> <p>Given an initial value, determine who wins the game.</p> <p>As an example, let the initial value <em>n</em> = 132. It's Louise's turn so she first determines that 132 is not a power of 2. The next lower power of is 128, so she subtracts that from 132 and passes 4 to Richard. 4 is a power of 2, so Richard divides it by 2 and passes 2 to Louise. Likewise, 2 is a power so she divides it by 2 and reaches 1. She wins the game.</p> <p>If they initially set counter to 1, Richard wins. Louise cannot make a move so she loses.</p> </blockquote> <p>My question is, could somebody verify/help me with the current time complexity of this? And given this time complexity, what are some ways I could reduce it? </p> <p>I have tried to solve the time complexity, but it is quite confusing for me. What I have so far is: it takes O(log(N)) time to "reach" a given value N, since you are going up by factors of 2. Here I believe the worst case scenario is every number you land on is a power of two, since whenever you have a number that isn't a power of two, subtracting the highest power of two below it will reduce it by more than you would halving it. With that in mind, you have to "reach" a given value n log(M) times, where M is the first value for N.</p> <p>So we have Log(N) to reach a value N, and you have to do this log(M) times. The part that confuses me is that the value N halves each time. I don't know how to approach the rest of this. Any help with this would be greatly appreciated.</p> <p>What are some improvements to my code I could make?</p> <pre><code>static String counterGame(long n) { int turn = 0; long current = 2; long previous = 2; if (n == 1) return "Louise"; while (true) { if (current == n) { n /= 2; if (n == 1) { break; } else { turn ^= 1; current = 2; previous = 2; } } else if (current &lt; n) { previous = current; current *= 2; continue; } else { n = n - previous; if (n == 1) { break; } turn ^= 1; current = 2; previous = 2; } } return (turn == 1) ? "Richard" : "Louise"; } </code></pre>
[]
[ { "body": "<p>This can actually be solved with a super efficient 1 line of code, but the explanation is long :)<br>\n(and there are a few other things I should point out first)</p>\n\n<hr>\n\n<p>Your code will fail with any input bigger than <span class=\"math-container\">\\$2^{62}\\$</span> because you never overshoot this number by multiplying by 2 a power of 2 (in your code: <code>current</code>). This is because a signed <code>long</code> has only enough bits to represent powers of 2 up to <span class=\"math-container\">\\$2^{62}\\$</span> (you could have used it as an unsigned variable to have one extra bit, but it still wouldn't be enough to avoid this problem with the biggest numbers that the challenge says are expected input), multiplying it by 2 will cause the left most bit to become 1, which turns it into a big negative number, and multiplying it by 2 again will make it 0 which will then stay 0 no matter how much you multiply it, so your code will enter an infinite loop.</p>\n\n<hr>\n\n<p>Once you detect that a number is a power of 2 you shouldn't reset <code>previous</code> and <code>current</code> to 2 because a power of 2 divided by 2 is still a power of 2, so you know you can divide <code>current</code> by 2 together with <code>n</code>.</p>\n\n<hr>\n\n<p>A thing you could use to your advantage is the way powers of 2 look in binary code:</p>\n\n<pre><code>power | number | binary | even/odd power\n2^0 = 1 = 00001 | even\n2^1 = 2 = 00010 | odd\n2^2 = 4 = 00100 | even\n2^3 = 8 = 01000 | odd\n2^4 = 16 = 10000 | even\n</code></pre>\n\n<p>Notice how all bits are 0 except one, the position of this 1 bit tells you if you need an odd or even number of divisions (turns in the game) to reach 1.</p>\n\n<pre><code>long filter = 0b101010101010101010101010101010101010101010101010101010101010101L;\nboolean oddPower = (n &amp; filter) == 0;\n</code></pre>\n\n<p>As soon as you reach a power of 2, this check is enough to tell you who's gonna win. An odd number of turns left means that the player whose turn it is now will win, otherwise the other player will win.</p>\n\n<hr>\n\n<p>We can go further with looking at the bits and bypass the need to find the next lower power of 2 to divide <code>n</code> by it if <code>n</code> is not a power of 2. As you already know, any power of 2 is represented by a single 1 bit and lots of 0 bits. Now let's take a look at a few numbers represented in binary code:</p>\n\n<pre><code>3 = 0011\n4 = 0100\n5 = 0101\n6 = 0110\n7 = 0111\n8 = 1000\n</code></pre>\n\n<p>When the number isn't a power of 2, according to the game you need to remove the next lower power of 2. In binary it's gonna look like removing the left most bit (you can look at the numbers above to confirm this). Given our knowledge and solutions so far, we can rewrite the rules of the game to simple binary operations:</p>\n\n<pre><code>if ( number is a power of 2 ) then:\n use the check from the previous part of my answer to figure out the winner.\nelse:\n turn the most left 1 bit to 0.\n</code></pre>\n\n<p>This means the number of turns until we reach a power of 2 and find the answer depends on how many 1-bits are in the number, and knowing if this number is odd or even - combined with the answer to whether the power you reach is odd or even - is all you really need to know to predict the outcome of the game!</p>\n\n<p>Let's test this solution: here's what you see when you track the changes in a number as the game is played, in binary:</p>\n\n<pre><code>1000000110100\n0000000110100\n0000000010100\n0000000000100\n0000000000010\n0000000000001\n</code></pre>\n\n<p>There are 4 <code>1</code>s (even number) but you don't remove the last <code>1</code> bit so ignore it and say there are 3 <code>1</code>s to be removed (odd number) and the first power of 2 you reach is 4 (even) so overall there will be an odd number of turns taken in the whole game, which you can see is true.</p>\n\n<p>Here is the most optimized code I could possibly write to solve this:</p>\n\n<pre><code>static String counterGame(long n){\n boolean richardWins = true;\n\n while((n &amp; 1) == 0){\n richardWins = !richardWins;\n n &gt;&gt;&gt;= 1;\n }\n while(n != 1){\n if((n &amp; 1) == 1)\n richardWins = !richardWins;\n n &gt;&gt;&gt;= 1;\n }\n\n return richardWins ? \"Richard\" : \"Louise\";\n}\n</code></pre>\n\n<p>This code looks at each bit once, so the time complexity of this code is <code>O(log(N))</code> where <code>N</code> is the input number, and <code>log(N)</code> is the worst case scenario for the number of bits needed to represent the input number in binary.</p>\n\n<p>Judging by the fact that the exception to the rules (where Richard wins when Louise gets the 1 at the start of the game) emerges naturally with this solution if you don't add an if statement at the start to take care of it, I'd say this is what the author of this challenge expected to be the best possible answer.</p>\n\n<p><hr></p>\n\n<h2>Bonus</h2>\n\n<p>There are processor instructions for counting <code>1</code> bits and trailing zeros, so you could actually do the whole thing in one line instead of manually looping through the bits, and using these processor instructions is faster:</p>\n\n<pre><code>static String counterGame(long n){\n return ((Long.numberOfTrailingZeros(n) &amp; 1) == 1) ^ ((Long.bitCount(n) &amp; 1) == 1) ? \"Richard\" : \"Louise\";\n}\n</code></pre>\n\n<p><strong>EDIT:</strong> a shorter code suggested by @JS1:</p>\n\n<blockquote>\n <p>By subtracting one, it turns all the trailing zeroes into trailing ones, so that they can be counted by bitCount.</p>\n</blockquote>\n\n<pre><code>static String counterGame(long n){\n return ((Long.bitCount(n-1) &amp; 1) == 0) ? \"Richard\" : \"Louise\";\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T01:36:23.487", "Id": "402673", "Score": "0", "body": "Wow that's actually really cool. Bit manipulation messes with my head but having someone explain things like that always amazes me. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T06:55:05.713", "Id": "402682", "Score": "2", "body": "How about `((Long.bitCount(n-1) & 1) == 1)`? By subtracting one, it turns all the trailing zeroes into trailing ones, so that they can be counted by `bitCount`. Btw this is the condition for Louise to win." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T17:56:51.860", "Id": "208462", "ParentId": "208414", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T01:00:50.517", "Id": "208414", "Score": "3", "Tags": [ "java", "algorithm", "programming-challenge", "complexity" ], "Title": "\"Counter Game\" Powers of 2 Game" }
208414
<p>This is my attempt at the 4th problem on Project Euler:</p> <pre><code>#include "stdafx.h" #include &lt;string&gt; #include &lt;vector&gt; #include &lt;iostream&gt; using namespace std; int palindromeCheck(int pp) { int temp = pp; string palindrome = std::to_string(pp); auto it1 = palindrome.begin(); auto it2 = palindrome.end() - 1; while (it2 - it1 &gt;= 1) { if (*it1 == *it2) { ++it1; --it2; } else { return 0; } } return 1; } int main() { int highestPalindrome = 0; for (int x = 100; x &lt;= 999; x++) { for (int y = 100; y &lt;= 999; y++) { int newDigit = x * y; int paliCheck = palindromeCheck(newDigit); if (paliCheck == 1) { if (newDigit &gt; highestPalindrome) { highestPalindrome = newDigit; } } } } std::cout &lt;&lt; highestPalindrome; } </code></pre> <p>I'm trying to get better at both C++ and problem-solving so any help/tips are appreciated. </p>
[]
[ { "body": "<p><code>using namespace std;</code> is a bad practice. You should should spell out either what you are using, or spell out explicitly the <code>std::</code> when you are using something. You are doing the latter already with <code>std::to_string</code> and <code>std::cout</code>, just not with <code>string</code>.</p>\n\n<p>Your <code>palindromeCheck</code> function should return a <code>bool</code>, instead of an <code>int</code> with specific integers having certain meanings.</p>\n\n<p><code>temp</code> is not used.</p>\n\n<p>You are checking both <code>100 * 101</code> and <code>101 * 100</code>. Multiplication is commutative, so you can cut your work in half by adjusting your inner <code>y</code> loop to only use number from a range which hasn't been checked yet (from <code>x</code> to <code>999</code>, inclusive).</p>\n\n<p><code>newDigit</code> is an odd variable name for the product of <code>x * y</code>.</p>\n\n<p><code>palindromeCheck(newDigit)</code> is an expensive operation. <code>newDigit &gt; highestPalindrome</code> is a relatively cheap test. Consider reversing the order of these tests to avoid calling an expensive function when the result will never be used.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T03:03:08.600", "Id": "208423", "ParentId": "208422", "Score": "1" } }, { "body": "<h2>Performance improvement</h2>\n\n<p>AJNeufeld's answer is correct that you don't need to test both <code>100*101</code> and <code>101*100</code>, you're doing double work. The fix for that is small: don't evaluate any <code>y</code> that is smaller than <code>x</code> (or, in other words: start processing the inner loop when <code>y == x</code> and then increase the <code>y</code> value)</p>\n\n<pre><code>for (int x = 100; x &lt;= 999; x++) {\n for (int y = x; y &lt;= 999; y++) {\n</code></pre>\n\n<hr>\n\n<h2>Performance improvement 2</h2>\n\n<p>For every iteration you do, it makes no sense to start checking from the <em>lowest</em> value, since you're only interested in the <em>highest</em> value.</p>\n\n<p>Suppose you're in the inner loop, and for a given <code>x</code> value, you find a match for <code>y=105</code> and also a match for <code>y=305</code>. Since the value of <code>x</code> remains unchanged, you can conclusively state that <code>x*305</code> will always be bigger than <code>x*105</code> and thus <strong>your initial match is meaningless, you only want the biggest match</strong>.</p>\n\n<p>You can massively improve this by starting with the highest <code>y</code> and working your way down. For the sake of simplicity, I'm only changing the <code>y</code> iteration for now:</p>\n\n<pre><code>for (int x = 100; x &lt;= 999; x++) {\n for (int y = 999; y &gt;= x; y--) {\n</code></pre>\n\n<p>When you find your first matching <code>y</code> value (e.g. 305), then you know that you don't need to check any lower value for <code>y</code> anymore, as its product (with the same <code>x</code> value) will always be lower than the match you already found.</p>\n\n<p>You can apply the same logic to the <code>x</code> iteration: start from the highest.</p>\n\n<pre><code>for (int x = 999; x &gt;= 100; x--) {\n for (int y = 999; y &gt;= x; y--) {\n</code></pre>\n\n<hr>\n\n<h2>Performance improvement 3</h2>\n\n<p>Having this improved approach, there is a massive improvement we can make. First, let's look at which (x,y) values will be checked in the nested loops</p>\n\n<pre><code> X | Y \n===========\n 999 | 999\n |\n 998 | 999\n 998 | 998\n |\n 997 | 999\n 997 | 998\n 997 | 997\n |\n 996 | 999\n 996 | 998\n 996 | 997\n 996 | 996\n</code></pre>\n\n<p>You can see that the order of operations always tests <strong>the highest available (so far untested) pair of numbers</strong>. That means that when you find a palindrome, that you already know that you have <strong>the highest available product</strong> since bigger numbers always make for a bigger product, and thus you also know that you have <strong>the biggest (possible) palindrome</strong>.</p>\n\n<p>When that biggest possible palindrome is tested and turns out to actually be a palindrome, then you don't need to look for any other palindromes anymore as you know you've found the biggest possible one already.</p>\n\n<pre><code>for (int x = 999; x &gt;= 100; x--) \n{\n for (int y = 999; y &gt;= x; y--) \n {\n int product = x * y;\n if(palindromeCheck(product))\n {\n std::cout &lt;&lt; highestPalindrome; \n return;\n }\n }\n}\nstd::cout &lt;&lt; \"No palindrome found!?\"; \nreturn;\n</code></pre>\n\n<p><em>Note: I used a <code>return</code> here to show that you can exit both loop at this point and there's no need to iterate any further. How you exit these loops can be done in many ways, but I tend to stick to methods that return as its maximizes both readability and ease of implementation.</em></p>\n\n<hr>\n\n<h2>Smaller comments</h2>\n\n<pre><code>int palindromeCheck(int pp) {\n</code></pre>\n\n<p>Don't use unreadable parameter names. The amount of characters used in a parameter makes no different to the runtime of the application but it has a massive impact on readability. I assume <code>pp</code> stands for <code>possiblePalindrome</code>, so use the full name instead.</p>\n\n<pre><code>while (it2 - it1 &gt;= 1) {\n</code></pre>\n\n<p>I would suggest using <code>while (it1 &lt; it2)</code> as it's more readable (but exactly the same from a technical perspective)</p>\n\n<pre><code>int palindromeCheck(int pp) {\n // ...\n return 0;\n // ...\n return 1;\n}\n</code></pre>\n\n<p>Don't use integer values for what is clearly intended to be a boolean value. Booleans exist for a reason, use them. </p>\n\n<p>Methods should generally be phrased as imperative commands or questions. <code>checkPalindrome</code> would be better. But given this returns a boolean, <code>isPalindrome</code> would be even better.</p>\n\n<p>This makes using the method a lot simpler and more readable: <code>if(isPalindrome(12321))</code></p>\n\n<pre><code>int newDigit = x * y;\n</code></pre>\n\n<p><code>newDigit</code> is a meaningless name that doesn't tell me anything about the value stored inside of it. <code>product</code> is much clearer since this variable contains the product of <code>x</code> and <code>y</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T15:24:29.263", "Id": "402917", "Score": "0", "body": "You have an error in your logic: you are not always generating the highest available product. 995*999 is larger than 996*996, yet has not been considered. If both were palindromes, your code would return a **large** palindrome but not the **largest**. To **guarantee** you’ve found the largest palindrome, you would need to continue the outer loop until `x*999` is less than the palindrome you found. Each inner loop can be abandoned once `x*y` is less the discovered palindrome." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T15:33:26.640", "Id": "402919", "Score": "0", "body": "Also, `highestPalindrome` is either undeclared or zero in your `cout` statement. You’d need to either output `product` or assign `product` to `highestPalindrome`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-29T20:12:14.990", "Id": "403171", "Score": "0", "body": "`next(x*y for x in range(30, 0, -1) for y in range(30, x-1, -1) if x*y == int(str(x*y)[::-1]))` demonstrating the logic bug in \"**Performance improvement 3**\" for finding the largest palindrome for product of two integers between 1 & 30. It returns `676` for `26*26`. Unfortunately, `696` (which is `24*29`) is larger." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T10:23:54.777", "Id": "208437", "ParentId": "208422", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T02:47:05.577", "Id": "208422", "Score": "2", "Tags": [ "c++", "programming-challenge" ], "Title": "Project Euler #4 - Finding the largest palindrome that is the product of two three-digit numbers." }
208422
<p>I've just written my first C# class, so I'm looking for some feedback before I go and write more code. The goal of the code is to provide a Singleton-like class to deal with common operations on the set of prime numbers that I will need to complete projecteuler.net problems. </p> <p>I'm interested in feedback for all aspects of the implementation (short of the actual prime generation algorithms, the <code>6*i +/- 1</code> method was used solely for its simplicity). </p> <p>I'm also interested in feedback about how the interfaces are split up. I split these up into slices of functionality in an attempt to allow future implementation changes. I am planning to use DI (e.g. SimpleInjector) to bind the singleton instance to each of the interfaces, but I'm seriously starting to doubt this pattern.</p> <p>I'm less interested in feedback about the selections of methods, I just chose a relatively minimal subset of methods that I know that I will need at some point - more methods will probably be added as needed.</p> <h3>Interfaces</h3> <pre><code>public interface IPrimeGenerator { IEnumerable&lt;long&gt; PrimesUntilValue(long value); IEnumerable&lt;long&gt; PrimesUntilCount(int count); } public interface IPrimeChecker { bool IsPrime(long value); } public interface IPrimeFactorizer { IEnumerable&lt;long&gt; PrimeFactors(long value); IEnumerable&lt;long&gt; UniquePrimeFactors(long value); } </code></pre> <h3>Implementation</h3> <pre><code>public class PrimeEngine: IPrimeGenerator, IPrimeChecker, IPrimeFactorizer { private readonly ICollection&lt;long&gt; _primeCollection; private long _indexFactor; private long _maxChecked; public PrimeEngine() { _primeCollection = new Collection&lt;long&gt; {2, 3}; _indexFactor = 1; _maxChecked = 3; } private void CheckNextPossiblePrimeDoublet() { var low = 6 * _indexFactor - 1; var high = low + 2; if (IsPrime(low)) { _primeCollection.Add(low); } if (IsPrime(high)) { _primeCollection.Add(high); } _indexFactor += 1; _maxChecked = high; } private IEnumerable&lt;long&gt; GetPossibleSmallerPrimeFactors(long value) { FillPrimesUntilRoot(value); return PrimesUntilRoot(value); } public bool IsPrime(long value) { var primePool = GetPossibleSmallerPrimeFactors(value); return primePool.All(prime =&gt; value % prime != 0); } private void FillPrimesUntilValue(long value) { while (_maxChecked &lt; value) { CheckNextPossiblePrimeDoublet(); } } private void FillPrimesUntilCount(int count) { while (_primeCollection.Count &lt; count) { CheckNextPossiblePrimeDoublet(); } } private static long FloorOfRoot(long value) { return (long) Math.Floor(Math.Sqrt(value)); } private void FillPrimesUntilRoot(long value) { FillPrimesUntilValue(FloorOfRoot(value)); } public IEnumerable&lt;long&gt; PrimesUntilValue(long value) { FillPrimesUntilValue(value); return _primeCollection.TakeWhile(prime =&gt; prime &lt;= value); } public IEnumerable&lt;long&gt; PrimesUntilCount(int count) { FillPrimesUntilCount(count); return _primeCollection.Take(count); } public IEnumerable&lt;long&gt; PrimesUntilRoot(long value) { return PrimesUntilValue(FloorOfRoot(value)); } public IEnumerable&lt;long&gt; PrimeFactors(long value) { FillPrimesUntilRoot(value); foreach (var prime in PrimesUntilRoot(value)) { if (prime &gt; value) break; while (value % prime == 0) { yield return prime; value /= prime; } } if (value != 1) { yield return value; } } public IEnumerable&lt;long&gt; UniquePrimeFactors(long value) { return PrimeFactors(value).Distinct(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T07:14:54.343", "Id": "402544", "Score": "2", "body": "The two first interfaces are identical - a copy/paste mistake?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T15:01:27.040", "Id": "402909", "Score": "0", "body": "In many applications of prime numbers a `NextPrime(int value)` method, returning the next higher prime can be useful. Hint: after 2 and 3, all prime numbers are of the form 6n ± 1." } ]
[ { "body": "<p>This is excellent code for a beginner. It's neat, the methods are short, etc. However, there are a couple things I'm concerned with.</p>\n\n<p>1) Your engine has a lot of state. It looks like this is mostly related to the generation of the next prime sequences, and any found primes are cached, so it shouldn't be too bad. However, you have to test that calling <code>PrimesUntilValue</code> followed by <code>UniquePrimeFactors</code>, for example, doesn't generate \"duplicate\" values or skip any.</p>\n\n<p>2) Given that you are using an approximation for primes, your code is structured neatly. However, do note that actually generating the sequence might get a bit messier than this and don't expect to be able to swap it out neatly. Given that your class's state is <em>solely</em> used for generating the next prime and that all previously found values are cached, it shouldn't be an issue.</p>\n\n<p>3) This code could lead to massive memory use in an application. Since you are already caching the values and all, you should consider making it a <code>static</code> class and making the cached collection a thread-safe hashmap. Then you have one instance of the prime engine and can do things like <code>PrimeEngine.PrimesUntilRoot</code>, etc. The hashmap would prevent duplicate primes from being entered into the collection.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T15:44:47.547", "Id": "208455", "ParentId": "208424", "Score": "2" } }, { "body": "<p>I agree with @Hosch250 ... too much state in what really could be self-contained static methods. I am struggling to see why you would want any of the class-level variables.</p>\n\n<p>I personally do not like the interfaces, mainly because you can define it only to 1 integer type (long or Int64). Why not Int32, UInt32, or even UInt64? Granted Int32 gets a free ride with the Int64 version.</p>\n\n<p>For some functions, there is way too much bloat in terms of memory and time. If you want to check that a number is prime, why bother checking for its entire prime factors collection? Once you detect that a number is not prime, the IsPrime method should return immediately rather than clicking along to find out if there are other prime factors.</p>\n\n<p>On a positive note, the code is written neatly and is easy to understand.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T19:46:15.617", "Id": "402632", "Score": "0", "body": "How would I go about expanding the interfaces to accept variable types?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T13:30:06.883", "Id": "402901", "Score": "0", "body": "@JaredGoguen That's just it - you can't, which is why I don't like the interfaces for this solution. Consider something like Math.Max. All the integral types have that method but it can't be tied to an interface because the interface declares one specific output type for a method. To put it another way, if you want an Int32 method to return an Int32, and a similarly named UInt64 method to return an UInt64, they can't be declared by an interface." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-30T17:18:03.293", "Id": "403352", "Score": "0", "body": "Generics would work. `IPrimeGenerator<T>`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T16:06:51.853", "Id": "208457", "ParentId": "208424", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T03:16:39.790", "Id": "208424", "Score": "2", "Tags": [ "c#", "beginner", "primes" ], "Title": "Prime engine: generation, primality, factorization" }
208424
<p>I am currently attempting to implement Matrix Math for another project I am working on.</p> <p>However, I am not sure whether this implementation will work. Can someone please tell me if there are any errors with my implementation?</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;cassert&gt; using namespace std; typedef vector&lt;vector&lt;double&gt; &gt; Matrix; Matrix add(Matrix a, Matrix b) { assert(a.size() == b.size() &amp;&amp; a[0].size() == b[0].size()); int numRow = a.size(), numCol = a[0].size(); Matrix output(numRow, vector&lt;double&gt;(numCol)); for(int i = 0; i &lt; numRow; i++) { for(int j = 0; j &lt; numCol; j++) { output[i][j] = a[i][j] + b[i][j]; } } return output; } Matrix subtract(Matrix a, Matrix b) { assert(a.size() == b.size() &amp;&amp; a[0].size() == b[0].size()); int numRow = a.size(), numCol = a[0].size(); Matrix output(numRow, vector&lt;double&gt;(numCol)); for(int i = 0; i &lt; numRow; i++) { for(int j = 0; j &lt; numCol; j++) { output[i][j] = a[i][j] - b[i][j]; } } return output; } Matrix multiply(Matrix a, double b) { int numRow = a.size(), numCol = a[0].size(); Matrix output(numRow, vector&lt;double&gt;(numCol)); for(int i = 0; i &lt; numRow; i++) { for(int j = 0; j &lt; numCol; j++) { output[i][j] = a[i][j] * b; } } return output; } Matrix multiply(Matrix a, Matrix b) { assert(a.size() == b.size() &amp;&amp; a[0].size() == b[0].size()); int numRow = a.size(), numCol = a[0].size(); Matrix output(numRow, vector&lt;double&gt;(numCol)); for(int i = 0; i &lt; numRow; i++) { for(int j = 0; j &lt; numCol; j++) { output[i][j] = a[i][j] * b[i][j]; } } return output; } Matrix dotProduct(Matrix a, Matrix b) { assert(a[0].size() == b.size()); int numRow = a.size(), numCol = b[0].size(); Matrix output(numRow, vector&lt;double&gt;(numCol, 0)); for(int i = 0; i &lt; numRow; i++) { for(int j = 0; j &lt; numCol; j++) { for(unsigned int k = 0; k &lt; a[0].size(); k++) { output[i][j] += a[i][k] * b[k][j]; } } } return output; } Matrix transpose(Matrix a) { int numRow = a[0].size(), numCol = a.size(); Matrix output(numRow, vector&lt;double&gt;(numCol)); for(int i = 0; i &lt; numRow; i++) { for(int j = 0; j &lt; numCol; j++) { output[i][j] = a[j][i]; } } return output; } Matrix applyFunc(Matrix a, double (*f)(double)) { int numRow = a.size(), numCol = a[0].size(); Matrix output(numRow, vector&lt;double&gt;(numCol)); for(int i = 0; i &lt; numRow; i++) { for(int j = 0; j &lt; numCol; j++) { output[i][j] = (*f)(a[i][j]); } } return output; } int main() { } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T07:56:25.120", "Id": "402545", "Score": "1", "body": "I have rolled back your last edit. Please don't change or add to the code in your question after you have received answers. See [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) Thank you." } ]
[ { "body": "<h2>Overview</h2>\n<p>Sure this is one way to represent a <code>Matrix</code>.</p>\n<pre><code>typedef vector&lt;vector&lt;double&gt; &gt; Matrix;\n</code></pre>\n<p>The problem here is that there is no enforcement that these are rectangular. Your code makes the assumption they are rectangles and things will go very wrong if the assumption is wrong.</p>\n<p>You don't use encapsulation.</p>\n<pre><code>Matrix add(Matrix a, Matrix b)\nMatrix subtract(Matrix a, Matrix b)\nMatrix multiply(Matrix a, double b)\nMatrix multiply(Matrix a, Matrix b)\nMatrix dotProduct(Matrix a, Matrix b)\n</code></pre>\n<p>All these are standalone methods. Not an absolute no-no but using classes correctly you can enforce the rectangular size requirements (preferably at compile time) but you could do it at runtime. If you use these methods then these would normally be member functions.</p>\n<p>Also these functions are just wrong:</p>\n<pre><code>Matrix multiply(Matrix a, Matrix b)\nMatrix dotProduct(Matrix a, Matrix b)\n</code></pre>\n<p>Neither of these functions do what they advertise. You should check out wikipedia for the definitions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T06:29:08.863", "Id": "402536", "Score": "0", "body": "Am I wrong by saying multiply() is multiplying element to element and dotProduct() is multiplying row by column?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T06:30:35.797", "Id": "402537", "Score": "0", "body": "Instead should I change my code so that multiplyElements() is multiplying element to element and multiply() is multiplying row by column?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T06:30:39.900", "Id": "402538", "Score": "0", "body": "@kimchiboy03: Yes. Matrix multiplication is more complicated and involves multiplication and addition of elements. This will change the dimensions of the Matrix. A dot product generates a scalar value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T06:31:44.347", "Id": "402539", "Score": "2", "body": "https://en.wikipedia.org/wiki/Matrix_multiplication_algorithm" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T06:32:10.703", "Id": "402540", "Score": "2", "body": "https://mathinsight.org/dot_product_matrix_notation" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T06:33:12.363", "Id": "402541", "Score": "0", "body": "Please check my edited post. Are the definitions better now? Thank you for your help." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T06:23:38.037", "Id": "208430", "ParentId": "208428", "Score": "4" } } ]
{ "AcceptedAnswerId": "208430", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T05:22:51.043", "Id": "208428", "Score": "0", "Tags": [ "c++", "c++11", "matrix" ], "Title": "Matrix arithmetic operations" }
208428
<p><a href="https://i.stack.imgur.com/tjLsR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tjLsR.png" alt="This part of the application design deals with generating sql query strings dynamically"></a> <a href="https://i.stack.imgur.com/ymdkp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ymdkp.png" alt="This is the entire detailed architecture of the application"></a></p> <p><a href="https://tinyurl.com/minissms" rel="nofollow noreferrer">This is a link to my application that actually runs on the design specified in the image.</a></p> <p>The idea behind the image is that the <code>SubjectInfoViewer</code> behaves as the context in the strategy pattern, and the <code>ViewingQueryComponent</code> behaves as the strategy interface, as well as the component class in the decorator pattern, and its implementing classes except the Filter class are the different strategies. These strategies return an SQL string specific to their description, which can be decorated using the Filter class, which is the decorator, in the decorator pattern. The classes implementing the filter class just append the where clause of the SQL string produced by the strategies and push the parameters involved in the where clause in a parameter stack, so they can finally by used by a parameterized SQL statement involving the whole "stitched" SQL string. </p> <p>For some reason, this doesn't seem to be the right approach to tackle this particular usecase. Please suggest the best practices used in this situation.</p> <p>The reason this doesn't seem to be the right approach is that there are a lot of tables being joined in the base queries, just for the convenience of writing where clauses in the Filters. </p> <p>I really would like to reduce the accidental complexity of having to push the parameters used in where clauses into the <code>paramStack</code> for using them in a parameterized query and having to call all the filters only for some filters to do nothing but by pass the call to another filter without doing anything useful.</p> <p>By the way, the repeated code in the base queries can be easily abstracted.. Also, better decoupling can be ensured by isolating the <code>UserInterface</code> reference to the <code>SubjectInfoViewer</code> so that it passes the parameters it receives from the getters of the <code>UserInterace</code> to the Filters, instead of having the Filters get them from the <code>UserInterface</code>.</p> <p><strong>SubjectInfoViewer.java</strong></p> <pre><code>public class SubjectInfoViewer { private ViewingQueryComponent baseQuery; private ViewingQueryComponent vqc; private String viewingQuery; private Stack&lt;String&gt; viewParams=new Stack&lt;&gt;(); private UserInterface ui; public void changeBaseQuery(ViewingQueryComponent vqc){ baseQuery=vqc; } public void stitch(){ vqc=new COFilter(ui,viewParams, new USNFilter(ui,viewParams, new DifficultyFilter(ui,viewParams, new SectionFilter(ui,viewParams, new DateFilter(ui,viewParams, new ModuleFilter(ui,viewParams, new SubjectFilter(ui,viewParams, baseQuery))))))); viewingQuery=vqc.stitch()+" GROUP BY STATUS.Topic_Name,QUESTION_BANK.Question_Statement"; } public SubjectInfoViewer(UserInterface ui) { this.ui=ui; baseQuery=new DefaultViewingQuery(); } public DefaultTableModel getTableModel() { return new DBGateway().getSubjectDetails(viewingQuery,viewParams); } } </code></pre> <p><strong>ViewingQueryComponent.java</strong></p> <pre><code>public interface ViewingQueryComponent { String stitch();} </code></pre> <p><strong>DefaultViewingQuery.java</strong></p> <pre><code>public class DefaultViewingQuery implements ViewingQueryComponent { private String sql= "SELECT " + "TOPICS.Topic_Name AS \"Topic Name\", " + "TOPICS.Textbook_Name AS \"Textbook Name\", " + "TOPICS.Page_Number AS \"Page Number\", " + "MADE_FROM.Question_Statement AS \"Question Statement\", " + "QUESTION_BANK.Total_Marks AS \"Total Marks\", " + "ROUND((COUNT(DISTINCT STATUS.USN)/(SELECT SUM(STUDENT.USN) FROM STUDENT))*100,2) AS \"Total Students (%)\" " + "FROM " + "STATUS, " + "TEXTBOOK, " + "SUBJECT, " + "STUDENT, " + "DISTRIBUTE, " + "TOPICS LEFT JOIN (MADE_FROM,QUESTION_BANK) ON TOPICS.Topic_Name = MADE_FROM.Topic_Name AND QUESTION_BANK.Question_Statement=MADE_FROM.Question_Statement " + "WHERE " + "DISTRIBUTE.Topic_Name=TOPICS.Topic_Name and " + "TEXTBOOK.Textbook_Name=TOPICS.Textbook_Name and " + "STATUS.Topic_Name=TOPICS.Topic_Name and " + "STATUS.USN=STUDENT.USN "; @Override public String stitch() { return sql; }} </code></pre> <p><strong>SectionViewingQuery.java</strong></p> <pre><code>public class SectionViewingQuery implements ViewingQueryComponent{ private String sql; public SectionViewingQuery(UserInterface ui){ sql= "SELECT " + "TOPICS.Topic_Name AS \"Topic Name\", " + "TOPICS.Textbook_Name AS \"Textbook Name\", " + "TOPICS.Page_Number AS \"Page Number\", " + "MADE_FROM.Question_Statement AS \"Question Statement\", " + "QUESTION_BANK.Total_Marks AS \"Total Marks\", " + "(COUNT(DISTINCT STATUS.USN)/(SELECT SUM(STUDENT.USN) FROM STUDENT WHERE STUDENT.Section=\""+ui.getSection()+"\"))*100 AS \"Total Students (%)\" " + "FROM " + "STATUS, " + "TEXTBOOK, " + "SUBJECT, " + "STUDENT, " + "DISTRIBUTE, " + "TOPICS LEFT JOIN (MADE_FROM,QUESTION_BANK) ON TOPICS.Topic_Name = MADE_FROM.Topic_Name AND QUESTION_BANK.Question_Statement=MADE_FROM.Question_Statement " + "WHERE " + "DISTRIBUTE.Topic_Name=TOPICS.Topic_Name and " + "TEXTBOOK.Textbook_Name=TOPICS.Textbook_Name and " + "STATUS.Topic_Name=TOPICS.Topic_Name and " + "STATUS.USN=STUDENT.USN "; } @Override public String stitch() { return sql; }} </code></pre> <p><strong>Filter.java</strong></p> <pre><code>public abstract class Filter implements ViewingQueryComponent { private ViewingQueryComponent vqc; protected Stack&lt;String&gt; paramStack; protected String sql=""; abstract boolean setSql(); Filter(ViewingQueryComponent vqc,Stack&lt;String&gt; paramStack){ this.paramStack=paramStack; this.vqc=vqc; } @Override public String stitch(){ if(setSql()) return vqc.stitch()+" and "+sql; return vqc.stitch()+sql; }} </code></pre> <p><strong>SubjectFilter.java</strong></p> <pre><code>public class SubjectFilter extends Filter{ String subject; public SubjectFilter(UserInterface ui,Stack&lt;String&gt; paramStack,ViewingQueryComponent vqc) { super(vqc,paramStack); subject=ui.getSubject(); } @Override boolean setSql() { if(!CheckHelper.checkEmpty(subject)){ sql=" TEXTBOOK.Subject_Name=? "; paramStack.push(subject); return true; }return false; }} </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T08:37:35.900", "Id": "402551", "Score": "1", "body": "Hello @Muhammed. This is the kind of questions that you should ask on stackoverflow, not codereview (because there is not code to review). But you should explain why _\"this doesn't seem to be the right approach\"_" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T09:18:01.803", "Id": "402554", "Score": "0", "body": "Hi @gervais.b I have updated the question to reflect the suggestions made. Thank you. And regarding the explanation of why this doesn't seem to be the right approach, It is because of the awkwardness of pushing parameters used in the where clause into a stack to be later used in the parameterized sql query." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-03T10:24:00.110", "Id": "403606", "Score": "0", "body": "let me know if anyone needs more code to help them better review." } ]
[ { "body": "<ul>\n<li>You've followed the Java naming conventions, but several functions are named within the programming solution domain rather than the business problem domain. Stick to the problem domain when naming.</li>\n<li>Some bits of the code are difficult to follow, the <code>stitch()</code> method for example, with all the nested function calls to complete the parameters, you can achieve the same level of flexibility but with a large increase in clarity by using the <a href=\"https://en.wikipedia.org/wiki/Builder_pattern\" rel=\"nofollow noreferrer\">builder pattern</a>. Name the methods using the field names from the problem domain.</li>\n<li>Concatenating strings to construct SQL queries looks simple but it can quickly become unmanageable as you've discovered. It is also extremely dangerous for security being a risk of SQL injections attacks. <strong>Do not do it</strong>. Instead use <a href=\"https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html\" rel=\"nofollow noreferrer\"><code>PreparedStatements</code></a> which <a href=\"https://stackoverflow.com/questions/17380150/java-create-preparedstatement-with-no-sql-content\">works well with the Builder Pattern.</a></li>\n</ul>\n<p><a href=\"https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-08T01:15:03.190", "Id": "404421", "Score": "0", "body": "Regarding the first point, isn't it inevitable to have some functions or classes represent the solution instead of the problem domain ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-08T01:27:31.730", "Id": "404422", "Score": "0", "body": "As for the second point, thank you for the suggestion. I'll look into it seeking to find a builder solution that follows the open closed principle, like the current solution does. As for the third point, I have actually used `PreparedStatements` in the `DBGateway`. I'm sorry that I haven't made it obvious. but if you look closely at the last snippet's use of `?` you might get a clue. But again, i'll try to see how builder pattern fits here." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-07T20:11:47.443", "Id": "209235", "ParentId": "208432", "Score": "0" } }, { "body": "<p>I have made some names a bit more obvious with respect to their purpose.</p>\n\n<p>The inconvenience of using a parameter stack can be overcome, by creating a class <code>ViewingQuery</code> which encapsulates the sql query as well as its parameters.</p>\n\n<p>This could be instantiated as an immutable object, which gets transformed by the <code>ViewingQueryComponent</code>s' <code>composeViewingQuery()</code> method.</p>\n\n<p>The guard condition can be implemented within the <code>ViewingQuery</code> class.</p>\n\n<p>An object of the <code>ViewingQuery</code> class named <code>compositeViewingQuery</code> shall be composed in the <code>SubjectInfoViewer</code> class.</p>\n\n<p>The <code>composeViewingQuery()</code> in the <code>SubjectInfoViewer</code> shall transform the <code>ViewingQuery</code> and assign it to <code>compositeViewingQuery</code></p>\n\n<p>Although this approach provides nice abstraction and better adheres to the single responsibility principle, it has an accidental complexity built into it.</p>\n\n<p>The accidental complexity is that, <code>getViewTableModel()</code> is dependent on the state changed by <code>composeViewingQuery()</code>. Hence the sequence of invocation of these methods becomes important.</p>\n\n<p>One way to overcome this accidental complexity, is by making the <code>composeViewingQuery()</code> method in the <code>SubjectInfoViewer</code> private, and calling it from <code>getViewTableModel()</code> and removing the attribute <code>compositeViewingQuery</code> at the cost of violating single responsibility principle. This move would also make testing hard.</p>\n\n<p>Another way to overcome this accidental complexity, is by having the <code>composeViewingQuery()</code> method of <code>SubjectInfoViewer</code> return the compositeViewingQuery. Then remove the <code>getViewTableModel</code> method. This way, the client directly calls the <code>getSubjectDetails</code> method of DBGateway by passing the value returned from <code>composeViewingQuery</code>. This may be the best approach. </p>\n\n<p>Also, the current solution can be improved by passing an instance of <code>ViewingQuery</code> as a parameter for <code>composeViewingQuery()</code> in order to improve readability.</p>\n\n<p>The following is the refactored code:</p>\n\n<p><strong>ViewingQuery.java</strong></p>\n\n<pre><code>public class ViewingQuery {\n\nprivate final List&lt;String&gt; parameterList;\nprivate final String baseQuery;\nprivate final String queryFilters;\n\nViewingQuery(){\n parameterList=new ArrayList&lt;&gt;();\n baseQuery=\"\";\n queryFilters=\"\";\n}\nViewingQuery(List parameterList,String queryFilter,String baseQuery){\n this.parameterList=parameterList;\n this.baseQuery=baseQuery;\n this.queryFilters=queryFilter;\n}\n\npublic ViewingQuery withFilter(String queryFilter,String ... parameters){\n if(!CheckHelper.checkEmpty(parameters)){\n List&lt;String&gt; newParameterList=getNewParameterList(parameters);\n return new ViewingQuery(newParameterList,this.queryFilters+\" and \"+queryFilter,this.baseQuery);\n }\n return this;\n}\n\nprivate List&lt;String&gt; getNewParameterList(String[] parameters) {\n List&lt;String&gt; newParameterList=new ArrayList&lt;&gt;();\n newParameterList.addAll(this.parameterList);\n newParameterList.addAll(Arrays.asList(parameters));\n return newParameterList;\n}\npublic ViewingQuery withBaseQuery(String baseQuery,String ... parameters){\n List&lt;String&gt; newParameterList=getNewParameterList(parameters);\n return new ViewingQuery(newParameterList,this.queryFilters,baseQuery);\n} \npublic String getQuery(){\n if(CheckHelper.checkEmpty(baseQuery))\n return \"\";\n return baseQuery+queryFilters+\" GROUP BY STATUS.Topic_Name,QUESTION_BANK.Question_Statement\";\n}\npublic List&lt;String&gt; getParameterList(){\n return parameterList;\n}\n</code></pre>\n\n<p>}</p>\n\n<p><strong>SubjectInfoViewer.java</strong></p>\n\n<pre><code>public class SubjectInfoViewer {\nprivate ViewingQueryComponent baseQueryComponent;\nprivate final UserInterface ui;\n\npublic SubjectInfoViewer(UserInterface ui) {\n this.ui=ui;\n baseQueryComponent=new DefaultViewingQuery();\n} \n\npublic void changeBaseQueryComponent(ViewingQueryComponent baseQueryComponent){\n this.baseQueryComponent=baseQueryComponent;\n}\npublic ViewingQuery composeViewingQuery(){\n return new COFilter(ui.getCO(), \n new USNFilter(ui.getUSN(), \n new DifficultyFilter(ui.getDifficulty(), \n new SectionFilter(ui.getSection(), \n new DateFilter(ui.getInitialDate(),ui.getFinalDate(), \n new ModuleFilter(ui.getModule(), \n new SubjectFilter(ui.getSubject(), \n baseQueryComponent))))))).composeViewingQuery(); \n}\n</code></pre>\n\n<p>}</p>\n\n<p><strong>ViewingQueryComponent.java</strong></p>\n\n<pre><code>public interface ViewingQueryComponent {\n\nViewingQuery composeViewingQuery();\n</code></pre>\n\n<p>}</p>\n\n<p><strong>DefaultViewingQuery.java</strong></p>\n\n<pre><code>public class DefaultViewingQuery implements ViewingQueryComponent {\nprivate String sql= \n \"SELECT \"\n + \"TOPICS.Topic_Name AS \\\"Topic Name\\\", \"\n + \"TOPICS.Textbook_Name AS \\\"Textbook Name\\\", \"\n + \"TOPICS.Page_Number AS \\\"Page Number\\\", \"\n + \"MADE_FROM.Question_Statement AS \\\"Question Statement\\\", \"\n + \"QUESTION_BANK.Total_Marks AS \\\"Total Marks\\\", \"\n + \"ROUND((COUNT(DISTINCT STATUS.USN)/(SELECT SUM(STUDENT.USN) FROM STUDENT))*100,2) AS \\\"Total Students (%)\\\" \"\n + \"FROM \"\n + \"STATUS, \"\n + \"TEXTBOOK, \"\n + \"SUBJECT, \"\n + \"STUDENT, \"\n + \"DISTRIBUTE, \"\n + \"TOPICS LEFT JOIN (MADE_FROM,QUESTION_BANK) ON TOPICS.Topic_Name = MADE_FROM.Topic_Name AND QUESTION_BANK.Question_Statement=MADE_FROM.Question_Statement \"\n + \"WHERE \"\n + \"DISTRIBUTE.Topic_Name=TOPICS.Topic_Name and \"\n + \"TEXTBOOK.Textbook_Name=TOPICS.Textbook_Name and \"\n + \"STATUS.Topic_Name=TOPICS.Topic_Name and \"\n + \"STATUS.USN=STUDENT.USN \";\n\n@Override\npublic ViewingQuery composeViewingQuery() {\n return new ViewingQuery().withBaseQuery(sql);\n} \n</code></pre>\n\n<p>}</p>\n\n<p><strong>SectionViewingQuery.java</strong></p>\n\n<pre><code>public class SectionViewingQuery implements ViewingQueryComponent{\nprivate final String sql;\nprivate final String section;\npublic SectionViewingQuery(String section){\n this.section=section;\n sql= \"SELECT \"\n + \"TOPICS.Topic_Name AS \\\"Topic Name\\\", \"\n + \"TOPICS.Textbook_Name AS \\\"Textbook Name\\\", \"\n + \"TOPICS.Page_Number AS \\\"Page Number\\\", \"\n + \"MADE_FROM.Question_Statement AS \\\"Question Statement\\\", \"\n + \"QUESTION_BANK.Total_Marks AS \\\"Total Marks\\\", \"\n + \"(COUNT(DISTINCT STATUS.USN)/(SELECT SUM(STUDENT.USN) FROM STUDENT WHERE STUDENT.Section=?))*100 AS \\\"Total Students (%)\\\" \"\n + \"FROM \"\n + \"STATUS, \"\n + \"TEXTBOOK, \"\n + \"SUBJECT, \"\n + \"STUDENT, \"\n + \"DISTRIBUTE, \"\n + \"TOPICS LEFT JOIN (MADE_FROM,QUESTION_BANK) ON TOPICS.Topic_Name = MADE_FROM.Topic_Name AND QUESTION_BANK.Question_Statement=MADE_FROM.Question_Statement \"\n + \"WHERE \"\n + \"DISTRIBUTE.Topic_Name=TOPICS.Topic_Name and \"\n + \"TEXTBOOK.Textbook_Name=TOPICS.Textbook_Name and \"\n + \"STATUS.Topic_Name=TOPICS.Topic_Name and \"\n + \"STATUS.USN=STUDENT.USN \";\n}\n@Override\npublic ViewingQuery composeViewingQuery() {\n return new ViewingQuery().withBaseQuery(sql,section);\n} \n</code></pre>\n\n<p>}</p>\n\n<p><strong>Filter.java</strong></p>\n\n<pre><code>public abstract class Filter implements ViewingQueryComponent {\n\nprotected final ViewingQueryComponent vqc; \n\nFilter(ViewingQueryComponent vqc){ \n this.vqc=vqc;\n}\n</code></pre>\n\n<p>}</p>\n\n<p><strong>SubjectFilter.java</strong></p>\n\n<pre><code>public class SubjectFilter extends Filter{\n\nprivate final String subject;\nprivate final String sql;\n\npublic SubjectFilter(String subject,ViewingQueryComponent vqc) {\n super(vqc);\n sql=\"TEXTBOOK.Subject_Name=?\";\n this.subject=subject;\n}\n\n@Override\npublic ViewingQuery composeViewingQuery() {\n return vqc.composeViewingQuery().withFilter(sql, subject);\n}\n</code></pre>\n\n<p>}</p>\n\n<p>There's an inherent limitation in using the decorator pattern like this. The limitation is that you cannot selectively remove filters from existing filter chains dynamically, hopefully there might be an ideal solution that preserves the functional nature of the solution while over coming this limitation. </p>\n\n<p>Perhaps the intercepting filter design pattern is more appropriate here instead of the decorator design pattern. Make the <code>SubjectInfoViewer</code> the <code>FilterManager</code> and implement, for every <code>Filter</code> the <code>hashCode</code> and <code>equals</code> methods as shown <a href=\"https://stackoverflow.com/questions/38198019/whats-a-suitable-implementation-of-equals-for-a-class-with-no-fields\">here</a> as the state of the <code>Filter</code>s become irrelevant for every <code>composeViewingQuery</code> message passed from the <code>ui</code> so they can be easily removed in the <code>FilterChain</code>, if implemented as a <code>Set</code>.</p>\n\n<p>But this pattern although will provide more flexibility than the decorator, it will need to pass unneeded parameters into the constructors of the filters just to remove the filters from the <code>FilterChain</code>. And this solution will possibly be feasible at the expense of sacrificing the declarative nature of the decorator solution</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-10T05:35:11.973", "Id": "209343", "ParentId": "208432", "Score": "0" } } ]
{ "AcceptedAnswerId": "209343", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-26T06:39:14.273", "Id": "208432", "Score": "1", "Tags": [ "java", "sql", "design-patterns", "swing" ], "Title": "Using decorator and strategy pattern for dynamically generating SQL queries" }
208432